repo_name
stringlengths
7
71
file_path
stringlengths
5
118
context
list
import_statement
stringlengths
45
12.5k
token_num
int64
641
99.4k
cropped_code
stringlengths
44
17k
all_code
stringlengths
43
754k
next_line
stringlengths
2
330
gold_snippet_index
int64
0
68
created_at
stringlengths
25
25
level
stringclasses
9 values
JoaoPedro9674/django-ledger
django_ledger/io/io_mixin.py
[ { "identifier": "settings", "path": "django_ledger/settings.py", "snippet": " DJANGO_LEDGER_GRAPHQL_SUPPORT_ENABLED = True\n DJANGO_LEDGER_GRAPHQL_SUPPORT_ENABLED = False\n DJANGO_LEDGER_PDF_SUPPORT_ENABLED = True\n DJANGO_LEDGER_PDF_SUPPORT_ENABLED = False\nDJANGO_LEDGER_USE_CLOSING_ENTRIES = getattr(settings, 'DJANGO_LEDGER_USE_CLOSING_ENTRIES', False)\nDJANGO_LEDGER_DEFAULT_CLOSING_ENTRY_CACHE_TIMEOUT = getattr(settings,\n 'DJANGO_LEDGER_DEFAULT_CLOSING_ENTRY_CACHE_TIMEOUT', 3600)\nDJANGO_LEDGER_LOGIN_URL = getattr(settings, 'DJANGO_LEDGER_LOGIN_URL', settings.LOGIN_URL)\nDJANGO_LEDGER_BILL_NUMBER_LENGTH = getattr(settings, 'DJANGO_LEDGER_BILL_NUMBER_LENGTH', 10)\nDJANGO_LEDGER_INVOICE_NUMBER_LENGTH = getattr(settings, 'DJANGO_LEDGER_INVOICE_NUMBER_LENGTH', 10)\nDJANGO_LEDGER_FORM_INPUT_CLASSES = getattr(settings, 'DJANGO_LEDGER_FORM_INPUT_CLASSES', 'input')\nDJANGO_LEDGER_CURRENCY_SYMBOL = getattr(settings, 'DJANGO_LEDGER_CURRENCY_SYMBOL', '$')\nDJANGO_LEDGER_SPACED_CURRENCY_SYMBOL = getattr(settings, 'DJANGO_LEDGER_SPACED_CURRENCY_SYMBOL', False)\nDJANGO_LEDGER_SHOW_FEEDBACK_BUTTON = getattr(settings, 'DJANGO_LEDGER_SHOW_FEEDBACK_BUTTON', False)\nDJANGO_LEDGER_FEEDBACK_EMAIL_LIST = getattr(settings, 'DJANGO_LEDGER_FEEDBACK_EMAIL_LIST', [])\nDJANGO_LEDGER_FEEDBACK_FROM_EMAIL = getattr(settings, 'DJANGO_LEDGER_FEEDBACK_FROM_EMAIL', None)\nDJANGO_LEDGER_VALIDATE_SCHEMAS_AT_RUNTIME = getattr(settings, 'DJANGO_LEDGER_VALIDATE_SCHEMAS_AT_RUNTIME', False)\nDJANGO_LEDGER_TRANSACTION_MAX_TOLERANCE = getattr(settings, 'DJANGO_LEDGER_TRANSACTION_MAX_TOLERANCE', Decimal('0.02'))\nDJANGO_LEDGER_TRANSACTION_CORRECTION = getattr(settings, 'DJANGO_LEDGER_TRANSACTION_CORRECTION', Decimal('0.01'))\nDJANGO_LEDGER_ACCOUNT_CODE_GENERATE = getattr(settings, 'DJANGO_LEDGER_ACCOUNT_CODE_GENERATE', True)\nDJANGO_LEDGER_ACCOUNT_CODE_GENERATE_LENGTH = getattr(settings, 'DJANGO_LEDGER_ACCOUNT_CODE_GENERATE_LENGTH', 5)\nDJANGO_LEDGER_ACCOUNT_CODE_USE_PREFIX = getattr(settings, 'DJANGO_LEDGER_ACCOUNT_CODE_GENERATE_LENGTH', True)\nDJANGO_LEDGER_JE_NUMBER_PREFIX = getattr(settings, 'DJANGO_LEDGER_JE_NUMBER_PREFIX', 'JE')\nDJANGO_LEDGER_PO_NUMBER_PREFIX = getattr(settings, 'DJANGO_LEDGER_PO_NUMBER_PREFIX', 'PO')\nDJANGO_LEDGER_ESTIMATE_NUMBER_PREFIX = getattr(settings, 'DJANGO_LEDGER_ESTIMATE_NUMBER_PREFIX', 'E')\nDJANGO_LEDGER_INVOICE_NUMBER_PREFIX = getattr(settings, 'DJANGO_LEDGER_INVOICE_NUMBER_PREFIX', 'I')\nDJANGO_LEDGER_BILL_NUMBER_PREFIX = getattr(settings, 'DJANGO_LEDGER_BILL_NUMBER_PREFIX', 'B')\nDJANGO_LEDGER_VENDOR_NUMBER_PREFIX = getattr(settings, 'DJANGO_LEDGER_VENDOR_NUMBER_PREFIX', 'V')\nDJANGO_LEDGER_CUSTOMER_NUMBER_PREFIX = getattr(settings, 'DJANGO_LEDGER_CUSTOMER_NUMBER_PREFIX', 'C')\nDJANGO_LEDGER_EXPENSE_NUMBER_PREFIX = getattr(settings, 'DJANGO_LEDGER_EXPENSE_NUMBER_PREFIX', 'IEX')\nDJANGO_LEDGER_INVENTORY_NUMBER_PREFIX = getattr(settings, 'DJANGO_LEDGER_INVENTORY_NUMBER_PREFIX', 'INV')\nDJANGO_LEDGER_PRODUCT_NUMBER_PREFIX = getattr(settings, 'DJANGO_LEDGER_PRODUCT_NUMBER_PREFIX', 'IPR')\nDJANGO_LEDGER_DOCUMENT_NUMBER_PADDING = getattr(settings, 'DJANGO_LEDGER_DOCUMENT_NUMBER_PADDING', 10)\nDJANGO_LEDGER_JE_NUMBER_NO_UNIT_PREFIX = getattr(settings, 'DJANGO_LEDGER_JE_NUMBER_NO_UNIT_PREFIX', '000')\nDJANGO_LEDGER_BILL_MODEL_ABSTRACT_CLASS = getattr(settings,\n 'DJANGO_LEDGER_BILL_MODEL_ABSTRACT_CLASS',\n 'django_ledger.models.bill.BillModelAbstract')\nDJANGO_LEDGER_INVOICE_MODEL_ABSTRACT_CLASS = getattr(settings,\n 'DJANGO_LEDGER_INVOICE_MODEL_ABSTRACT_CLASS',\n 'django_ledger.models.invoice.InvoiceModelAbstract')\nDJANGO_LEDGER_DEFAULT_COA = getattr(settings, 'DJANGO_LEDGER_DEFAULT_COA', None)\nDJANGO_LEDGER_FINANCIAL_ANALYSIS = {\n 'ratios': {\n 'current_ratio': {\n 'good_incremental': True,\n 'ranges': {\n 'healthy': 2,\n 'watch': 1,\n 'warning': .5,\n 'critical': .25\n }\n },\n 'quick_ratio': {\n 'good_incremental': True,\n 'ranges': {\n 'healthy': 2,\n 'watch': 1,\n 'warning': .5,\n 'critical': .25\n }\n },\n 'debt_to_equity': {\n 'good_incremental': False,\n 'ranges': {\n 'healthy': 0,\n 'watch': .25,\n 'warning': .5,\n 'critical': 1\n }\n },\n 'return_on_equity': {\n 'good_incremental': True,\n 'ranges': {\n 'healthy': .10,\n 'watch': .07,\n 'warning': .04,\n 'critical': .02\n }\n },\n 'return_on_assets': {\n 'good_incremental': True,\n 'ranges': {\n 'healthy': .10,\n 'watch': .06,\n 'warning': .04,\n 'critical': .02\n }\n },\n 'net_profit_margin': {\n 'good_incremental': True,\n 'ranges': {\n 'healthy': .10,\n 'watch': .06,\n 'warning': .04,\n 'critical': .02\n }\n },\n 'gross_profit_margin': {\n 'good_incremental': True,\n 'ranges': {\n 'healthy': .10,\n 'watch': .06,\n 'warning': .04,\n 'critical': .02\n }\n },\n }\n}" }, { "identifier": "InvalidDateInputError", "path": "django_ledger/exceptions.py", "snippet": "class InvalidDateInputError(ValidationError):\n pass" }, { "identifier": "TransactionNotInBalanceError", "path": "django_ledger/exceptions.py", "snippet": "class TransactionNotInBalanceError(ValidationError):\n pass" }, { "identifier": "roles", "path": "django_ledger/io/roles.py", "snippet": "DEBIT = 'debit'\nCREDIT = 'credit'\nASSET_CA_CASH = 'asset_ca_cash'\nASSET_CA_MKT_SECURITIES = 'asset_ca_mkt_sec'\nASSET_CA_RECEIVABLES = 'asset_ca_recv'\nASSET_CA_INVENTORY = 'asset_ca_inv'\nASSET_CA_UNCOLLECTIBLES = 'asset_ca_uncoll'\nASSET_CA_PREPAID = 'asset_ca_prepaid'\nASSET_CA_OTHER = 'asset_ca_other'\nASSET_LTI_NOTES_RECEIVABLE = 'asset_lti_notes'\nASSET_LTI_LAND = 'asset_lti_land'\nASSET_LTI_SECURITIES = 'asset_lti_sec'\nASSET_PPE_BUILDINGS = 'asset_ppe_build'\nASSET_PPE_BUILDINGS_ACCUM_DEPRECIATION = 'asset_ppe_build_accum_depr'\nASSET_PPE_EQUIPMENT = 'asset_ppe_equip'\nASSET_PPE_EQUIPMENT_ACCUM_DEPRECIATION = 'asset_ppe_equip_accum_depr'\nASSET_PPE_PLANT = 'asset_ppe_plant'\nASSET_PPE_PLANT_ACCUM_DEPRECIATION = 'asset_ppe_plant_depr'\nASSET_INTANGIBLE_ASSETS = 'asset_ia'\nASSET_INTANGIBLE_ASSETS_ACCUM_AMORTIZATION = 'asset_ia_accum_amort'\nASSET_ADJUSTMENTS = 'asset_adjustment'\nLIABILITY_CL_ACC_PAYABLE = 'lia_cl_acc_payable'\nLIABILITY_CL_WAGES_PAYABLE = 'lia_cl_wages_payable'\nLIABILITY_CL_TAXES_PAYABLE = 'lia_cl_taxes_payable'\nLIABILITY_CL_INTEREST_PAYABLE = 'lia_cl_int_payable'\nLIABILITY_CL_ST_NOTES_PAYABLE = 'lia_cl_st_notes_payable'\nLIABILITY_CL_LTD_MATURITIES = 'lia_cl_ltd_mat'\nLIABILITY_CL_DEFERRED_REVENUE = 'lia_cl_def_rev'\nLIABILITY_CL_OTHER = 'lia_cl_other'\nLIABILITY_LTL_NOTES_PAYABLE = 'lia_ltl_notes'\nLIABILITY_LTL_BONDS_PAYABLE = 'lia_ltl_bonds'\nLIABILITY_LTL_MORTGAGE_PAYABLE = 'lia_ltl_mortgage'\nEQUITY_CAPITAL = 'eq_capital'\nEQUITY_ADJUSTMENT = 'eq_adjustment'\nEQUITY_COMMON_STOCK = 'eq_stock_common'\nEQUITY_PREFERRED_STOCK = 'eq_stock_preferred'\nEQUITY_DIVIDENDS = 'eq_dividends'\nINCOME_OPERATIONAL = 'in_operational'\nINCOME_PASSIVE = 'in_passive'\nINCOME_CAPITAL_GAIN_LOSS = 'in_gain_loss'\nINCOME_INTEREST = 'in_interest'\nINCOME_OTHER = 'in_other'\nCOGS = 'cogs_regular'\nEXPENSE_OPERATIONAL = 'ex_regular'\nEXPENSE_CAPITAL = 'ex_capital'\nEXPENSE_DEPRECIATION = 'ex_depreciation'\nEXPENSE_AMORTIZATION = 'ex_amortization'\nEXPENSE_TAXES = 'ex_taxes'\nEXPENSE_INTEREST_ST = 'ex_interest_st'\nEXPENSE_INTEREST_LT = 'ex_interest'\nEXPENSE_OTHER = 'ex_other'\nROOT_COA = 'root_coa'\nROOT_ASSETS = 'root_assets'\nROOT_LIABILITIES = 'root_liabilities'\nROOT_CAPITAL = 'root_capital'\nROOT_INCOME = 'root_income'\nROOT_COGS = 'root_cogs'\nROOT_EXPENSES = 'root_expenses'\nROOT_GROUP = [\n ROOT_COA,\n ROOT_ASSETS,\n ROOT_LIABILITIES,\n ROOT_CAPITAL,\n ROOT_INCOME,\n ROOT_COGS,\n ROOT_EXPENSES\n]\nROOT_GROUP_LEVEL_2 = [\n ROOT_ASSETS,\n ROOT_LIABILITIES,\n ROOT_CAPITAL,\n ROOT_INCOME,\n ROOT_COGS,\n ROOT_EXPENSES\n]\nROOT_GROUP_META = {\n ROOT_COA: {\n 'code': '00000',\n 'title': 'CoA Root Node',\n 'balance_type': DEBIT\n },\n ROOT_ASSETS: {\n 'code': '01000',\n 'title': 'Asset Accounts Root Node',\n 'balance_type': DEBIT\n },\n ROOT_LIABILITIES: {\n 'code': '02000',\n 'title': 'Liability Accounts Root Node',\n 'balance_type': CREDIT\n },\n ROOT_CAPITAL: {\n 'code': '03000',\n 'title': 'Capital Accounts Root Node',\n 'balance_type': CREDIT\n },\n ROOT_INCOME: {\n 'code': '04000',\n 'title': 'Income Accounts Root Node',\n 'balance_type': CREDIT\n },\n ROOT_COGS: {\n 'code': '05000',\n 'title': 'COGS Accounts Root Node',\n 'balance_type': DEBIT\n },\n ROOT_EXPENSES: {\n 'code': '06000',\n 'title': 'Expense Accounts Root Node',\n 'balance_type': DEBIT\n },\n}\nGROUP_QUICK_ASSETS = [\n ASSET_CA_CASH,\n ASSET_CA_MKT_SECURITIES\n]\nGROUP_CURRENT_ASSETS = [\n ASSET_CA_CASH,\n ASSET_CA_MKT_SECURITIES,\n ASSET_CA_INVENTORY,\n ASSET_CA_RECEIVABLES,\n ASSET_CA_PREPAID,\n ASSET_CA_UNCOLLECTIBLES,\n ASSET_CA_OTHER\n]\nGROUP_NON_CURRENT_ASSETS = [\n ASSET_LTI_NOTES_RECEIVABLE,\n ASSET_LTI_LAND,\n ASSET_LTI_SECURITIES,\n ASSET_PPE_BUILDINGS,\n ASSET_PPE_BUILDINGS_ACCUM_DEPRECIATION,\n ASSET_PPE_EQUIPMENT,\n ASSET_PPE_EQUIPMENT_ACCUM_DEPRECIATION,\n ASSET_PPE_PLANT,\n ASSET_PPE_PLANT_ACCUM_DEPRECIATION,\n ASSET_INTANGIBLE_ASSETS,\n ASSET_INTANGIBLE_ASSETS_ACCUM_AMORTIZATION,\n ASSET_ADJUSTMENTS\n]\nGROUP_ASSETS = GROUP_CURRENT_ASSETS + GROUP_NON_CURRENT_ASSETS\nGROUP_CURRENT_LIABILITIES = [\n LIABILITY_CL_ACC_PAYABLE,\n LIABILITY_CL_DEFERRED_REVENUE,\n LIABILITY_CL_INTEREST_PAYABLE,\n LIABILITY_CL_LTD_MATURITIES,\n LIABILITY_CL_OTHER,\n LIABILITY_CL_ST_NOTES_PAYABLE,\n LIABILITY_CL_WAGES_PAYABLE,\n LIABILITY_CL_TAXES_PAYABLE\n]\nGROUP_LT_LIABILITIES = [\n LIABILITY_LTL_NOTES_PAYABLE,\n LIABILITY_LTL_BONDS_PAYABLE,\n LIABILITY_LTL_MORTGAGE_PAYABLE,\n]\nGROUP_LIABILITIES = GROUP_CURRENT_LIABILITIES + GROUP_LT_LIABILITIES\nGROUP_CAPITAL = [\n EQUITY_CAPITAL,\n EQUITY_COMMON_STOCK,\n EQUITY_PREFERRED_STOCK,\n EQUITY_DIVIDENDS,\n EQUITY_ADJUSTMENT\n]\nGROUP_INCOME = [\n INCOME_OPERATIONAL,\n INCOME_PASSIVE,\n INCOME_INTEREST,\n INCOME_CAPITAL_GAIN_LOSS,\n INCOME_OTHER\n]\nGROUP_COGS = [\n COGS\n]\nGROUP_EXPENSES = [\n EXPENSE_OPERATIONAL,\n EXPENSE_INTEREST_ST,\n EXPENSE_INTEREST_LT,\n EXPENSE_TAXES,\n EXPENSE_CAPITAL,\n EXPENSE_DEPRECIATION,\n EXPENSE_AMORTIZATION,\n EXPENSE_OTHER\n]\nGROUP_NET_PROFIT = [\n INCOME_OPERATIONAL,\n INCOME_PASSIVE,\n INCOME_INTEREST,\n INCOME_CAPITAL_GAIN_LOSS,\n INCOME_OTHER,\n COGS\n]\nGROUP_GROSS_PROFIT = [\n INCOME_OPERATIONAL,\n COGS\n]\nGROUP_NET_SALES = [\n INCOME_OPERATIONAL,\n INCOME_PASSIVE\n]\nGROUP_PPE_ACCUM_DEPRECIATION = [\n ASSET_PPE_BUILDINGS_ACCUM_DEPRECIATION,\n ASSET_PPE_EQUIPMENT_ACCUM_DEPRECIATION,\n ASSET_PPE_PLANT_ACCUM_DEPRECIATION\n]\nGROUP_EXPENSE_DEP_AND_AMT = [\n EXPENSE_DEPRECIATION,\n EXPENSE_AMORTIZATION\n]\nGROUP_EARNINGS = GROUP_INCOME + GROUP_COGS + GROUP_EXPENSES\nGROUP_EQUITY = GROUP_CAPITAL + GROUP_EARNINGS\nGROUP_LIABILITIES_EQUITY = GROUP_LIABILITIES + GROUP_EQUITY\nGROUP_INVOICE = [ASSET_CA_CASH, ASSET_CA_RECEIVABLES, LIABILITY_CL_DEFERRED_REVENUE]\nGROUP_BILL = [ASSET_CA_CASH, ASSET_CA_PREPAID, LIABILITY_CL_ACC_PAYABLE]\nGROUP_IC_OPERATING_REVENUES = [INCOME_OPERATIONAL]\nGROUP_IC_OPERATING_COGS = [COGS]\nGROUP_IC_OPERATING_EXPENSES = [EXPENSE_OPERATIONAL]\nGROUP_IC_OTHER_REVENUES = [\n INCOME_PASSIVE,\n INCOME_INTEREST,\n INCOME_CAPITAL_GAIN_LOSS,\n INCOME_OTHER\n]\nGROUP_IC_OTHER_EXPENSES = [\n EXPENSE_INTEREST_ST,\n EXPENSE_INTEREST_LT,\n EXPENSE_TAXES,\n EXPENSE_CAPITAL,\n EXPENSE_DEPRECIATION,\n EXPENSE_AMORTIZATION,\n EXPENSE_OTHER\n]\nGROUP_CFS_NET_INCOME = GROUP_EARNINGS\nGROUP_CFS_OP_DEPRECIATION_AMORTIZATION = [\n EXPENSE_DEPRECIATION,\n EXPENSE_AMORTIZATION\n]\nGROUP_CFS_OP_INVESTMENT_GAINS = [\n INCOME_CAPITAL_GAIN_LOSS\n]\nGROUP_CFS_OP_ACCOUNTS_RECEIVABLE = [\n ASSET_CA_RECEIVABLES\n]\nGROUP_CFS_OP_INVENTORY = [\n ASSET_CA_INVENTORY\n]\nGROUP_CFS_OP_ACCOUNTS_PAYABLE = [\n LIABILITY_CL_ACC_PAYABLE\n]\nGROUP_CFS_OP_OTHER_CURRENT_ASSETS_ADJUSTMENT = [\n ASSET_CA_PREPAID,\n ASSET_CA_UNCOLLECTIBLES,\n ASSET_CA_OTHER\n]\nGROUP_CFS_OP_OTHER_CURRENT_LIABILITIES_ADJUSTMENT = [\n LIABILITY_CL_WAGES_PAYABLE,\n LIABILITY_CL_INTEREST_PAYABLE,\n LIABILITY_CL_TAXES_PAYABLE,\n LIABILITY_CL_LTD_MATURITIES,\n LIABILITY_CL_DEFERRED_REVENUE,\n LIABILITY_CL_OTHER,\n]\nGROUP_CFS_OPERATING = list(chain.from_iterable([\n GROUP_CFS_NET_INCOME,\n GROUP_CFS_OP_DEPRECIATION_AMORTIZATION,\n GROUP_CFS_OP_INVESTMENT_GAINS,\n GROUP_CFS_OP_ACCOUNTS_RECEIVABLE,\n GROUP_CFS_OP_INVENTORY,\n GROUP_CFS_OP_ACCOUNTS_PAYABLE,\n GROUP_CFS_OP_OTHER_CURRENT_ASSETS_ADJUSTMENT,\n GROUP_CFS_OP_OTHER_CURRENT_LIABILITIES_ADJUSTMENT\n]))\nGROUP_CFS_FIN_ISSUING_EQUITY = [EQUITY_CAPITAL, EQUITY_COMMON_STOCK, EQUITY_PREFERRED_STOCK]\nGROUP_CFS_FIN_DIVIDENDS = [EQUITY_DIVIDENDS]\nGROUP_CFS_FIN_ST_DEBT_PAYMENTS = [\n LIABILITY_CL_ST_NOTES_PAYABLE,\n LIABILITY_CL_ACC_PAYABLE,\n EXPENSE_INTEREST_ST\n]\nGROUP_CFS_FIN_LT_DEBT_PAYMENTS = [\n LIABILITY_LTL_NOTES_PAYABLE,\n LIABILITY_LTL_BONDS_PAYABLE,\n LIABILITY_LTL_MORTGAGE_PAYABLE,\n EXPENSE_INTEREST_LT\n]\nGROUP_CFS_FINANCING = GROUP_CFS_FIN_ISSUING_EQUITY + GROUP_CFS_FIN_DIVIDENDS\nGROUP_CFS_INV_PURCHASE_OR_SALE_OF_PPE = [\n ASSET_PPE_BUILDINGS,\n ASSET_PPE_PLANT,\n ASSET_PPE_EQUIPMENT,\n INCOME_CAPITAL_GAIN_LOSS\n]\nGROUP_CFS_INV_LTD_OF_PPE = [\n LIABILITY_LTL_NOTES_PAYABLE,\n LIABILITY_LTL_MORTGAGE_PAYABLE,\n LIABILITY_LTL_BONDS_PAYABLE,\n]\nGROUP_CFS_INVESTING_PPE = GROUP_CFS_INV_PURCHASE_OR_SALE_OF_PPE + GROUP_CFS_INV_LTD_OF_PPE\nGROUP_CFS_INV_PURCHASE_OF_SECURITIES = [\n ASSET_CA_MKT_SECURITIES,\n ASSET_LTI_NOTES_RECEIVABLE,\n ASSET_LTI_SECURITIES,\n INCOME_INTEREST,\n INCOME_PASSIVE,\n]\nGROUP_CFS_INV_LTD_OF_SECURITIES = [\n LIABILITY_LTL_NOTES_PAYABLE,\n LIABILITY_LTL_BONDS_PAYABLE\n]\nGROUP_CFS_INVESTING_SECURITIES = GROUP_CFS_INV_PURCHASE_OF_SECURITIES + GROUP_CFS_INV_LTD_OF_SECURITIES\nGROUP_CFS_INVESTING = GROUP_CFS_INVESTING_PPE + GROUP_CFS_INVESTING_SECURITIES\nGROUP_CFS_INVESTING_AND_FINANCING = GROUP_CFS_INVESTING + GROUP_CFS_FINANCING\nBS_ASSET_ROLE = 'assets'\nBS_LIABILITIES_ROLE = 'liabilities'\nBS_EQUITY_ROLE = 'equity'\nACCOUNT_ROLE_CHOICES = [\n (BS_ASSET_ROLE.capitalize(), (\n # CURRENT ASSETS ----\n (ASSET_CA_CASH, _('Current Asset')),\n (ASSET_CA_MKT_SECURITIES, _('Marketable Securities')),\n (ASSET_CA_RECEIVABLES, _('Receivables')),\n (ASSET_CA_INVENTORY, _('Inventory')),\n (ASSET_CA_UNCOLLECTIBLES, _('Uncollectibles')),\n (ASSET_CA_PREPAID, _('Prepaid')),\n (ASSET_CA_OTHER, _('Other Liquid Assets')),\n\n # LONG TERM INVESTMENTS ---\n (ASSET_LTI_NOTES_RECEIVABLE, _('Notes Receivable')),\n (ASSET_LTI_LAND, _('Land')),\n (ASSET_LTI_SECURITIES, _('Securities')),\n\n # PPE ...\n (ASSET_PPE_BUILDINGS, _('Buildings')),\n (ASSET_PPE_BUILDINGS_ACCUM_DEPRECIATION, _('Buildings - Accum. Depreciation')),\n (ASSET_PPE_PLANT, _('Plant')),\n (ASSET_PPE_PLANT_ACCUM_DEPRECIATION, _('Plant - Accum. Depreciation')),\n (ASSET_PPE_EQUIPMENT, _('Equipment')),\n (ASSET_PPE_EQUIPMENT_ACCUM_DEPRECIATION, _('Equipment - Accum. Depreciation')),\n\n # Other Assets ...\n (ASSET_INTANGIBLE_ASSETS, _('Intangible Assets')),\n (ASSET_INTANGIBLE_ASSETS_ACCUM_AMORTIZATION, _('Intangible Assets - Accum. Amortization')),\n (ASSET_ADJUSTMENTS, _('Other Assets')),\n )),\n (BS_LIABILITIES_ROLE.capitalize(), (\n\n # CURRENT LIABILITIES ---\n (LIABILITY_CL_ACC_PAYABLE, _('Accounts Payable')),\n (LIABILITY_CL_WAGES_PAYABLE, _('Wages Payable')),\n (LIABILITY_CL_INTEREST_PAYABLE, _('Interest Payable')),\n (LIABILITY_CL_TAXES_PAYABLE, _('Taxes Payable')),\n (LIABILITY_CL_ST_NOTES_PAYABLE, _('Short Term Notes Payable')),\n (LIABILITY_CL_LTD_MATURITIES, _('Current Maturities of Long Tern Debt')),\n (LIABILITY_CL_DEFERRED_REVENUE, _('Deferred Revenue')),\n (LIABILITY_CL_OTHER, _('Other Liabilities')),\n\n # LONG TERM LIABILITIES ----\n (LIABILITY_LTL_NOTES_PAYABLE, _('Long Term Notes Payable')),\n (LIABILITY_LTL_BONDS_PAYABLE, _('Bonds Payable')),\n (LIABILITY_LTL_MORTGAGE_PAYABLE, _('Mortgage Payable')),\n )),\n (BS_EQUITY_ROLE.capitalize(), (\n\n # EQUITY ---\n (EQUITY_CAPITAL, _('Capital')),\n (EQUITY_COMMON_STOCK, _('Common Stock')),\n (EQUITY_PREFERRED_STOCK, _('Preferred Stock')),\n (EQUITY_ADJUSTMENT, _('Other Equity Adjustments')),\n (EQUITY_DIVIDENDS, _('Dividends & Distributions to Shareholders')),\n\n # INCOME ---\n (INCOME_OPERATIONAL, _('Operational Income')),\n (INCOME_PASSIVE, _('Investing/Passive Income')),\n (INCOME_INTEREST, _('Interest Income')),\n (INCOME_CAPITAL_GAIN_LOSS, _('Capital Gain/Loss Income')),\n (INCOME_OTHER, _('Other Income')),\n\n # COGS ----\n (COGS, _('Cost of Goods Sold')),\n\n # EXPENSES ----\n (EXPENSE_OPERATIONAL, _('Regular Expense')),\n (EXPENSE_INTEREST_ST, _('Interest Expense - Short Term Debt')),\n (EXPENSE_INTEREST_LT, _('Interest Expense - Long Term Debt')),\n (EXPENSE_TAXES, _('Tax Expense')),\n (EXPENSE_CAPITAL, _('Capital Expense')),\n (EXPENSE_DEPRECIATION, _('Depreciation Expense')),\n (EXPENSE_AMORTIZATION, _('Amortization Expense')),\n (EXPENSE_OTHER, _('Other Expense')),\n )),\n ('Root', (\n (ROOT_COA, 'CoA Root Account'),\n (ROOT_ASSETS, 'Assets Root Account'),\n (ROOT_LIABILITIES, 'Liabilities Root Account'),\n (ROOT_CAPITAL, 'Capital Root Account'),\n (ROOT_INCOME, 'Income Root Account'),\n (ROOT_COGS, 'COGS Root Account'),\n (ROOT_EXPENSES, 'Expenses Root Account'),\n ))\n]\nACCOUNT_CHOICES_NO_ROOT = [c for c in ACCOUNT_ROLE_CHOICES if c[0] != 'Root']\nROLES_ORDER_ASSETS = [a[0] for a in ACCOUNT_ROLE_CHOICES[0][1]]\nROLES_ORDER_LIABILITIES = [a[0] for a in ACCOUNT_ROLE_CHOICES[1][1]]\nROLES_ORDER_CAPITAL = [a[0] for a in ACCOUNT_ROLE_CHOICES[2][1]]\nROLES_ORDER_ALL = list(chain.from_iterable([ROLES_ORDER_ASSETS, ROLES_ORDER_LIABILITIES, ROLES_ORDER_CAPITAL]))\nACCOUNT_LIST_ROLE_ORDER = list(r[0] for r in chain.from_iterable([i[1] for i in ACCOUNT_CHOICES_NO_ROOT]))\nACCOUNT_LIST_ROLE_VERBOSE = {r[0]: r[1] for r in chain.from_iterable([i[1] for i in ACCOUNT_CHOICES_NO_ROOT])}\nROLE_TUPLES = sum([[(r[0].lower(), s[0]) for s in r[1]] for r in ACCOUNT_ROLE_CHOICES], list())\nROLE_DICT = dict([(t[0].lower(), [r[0] for r in t[1]]) for t in ACCOUNT_ROLE_CHOICES])\nVALID_ROLES = [r[1] for r in ROLE_TUPLES]\nBS_ROLES = dict((r[1], r[0]) for r in ROLE_TUPLES)\nBS_BUCKETS = {\n '0': 'Root',\n '1': 'Asset',\n '2': 'Liability',\n '3': 'Capital',\n '4': 'Income',\n '5': 'COGS',\n '6': 'Expenses'\n}\nBS_BUCKETS_ORDER = [v for _, v in BS_BUCKETS.items() if v != 'Root']\nROLES_VARS = locals().keys()\nROLES_DIRECTORY = dict()\nROLES_CATEGORIES = ['ASSET', 'LIABILITY', 'EQUITY', 'INCOME', 'COGS', 'EXPENSE']\nROLES_GROUPS = [g for g in ROLES_VARS if g.split('_')[0] == 'GROUP']\nGROUPS_DIRECTORY = dict()\ndef validate_roles(roles: Union[str, List[str]], raise_exception: bool = True) -> Set[str]:" }, { "identifier": "RoleContextManager", "path": "django_ledger/io/io_context.py", "snippet": "class RoleContextManager:\n\n def __init__(self,\n io_data: dict,\n by_period: bool = False,\n by_unit: bool = False):\n\n self.BY_PERIOD = by_period\n self.BY_UNIT = by_unit\n\n self.DIGEST = io_data\n self.DIGEST['role_account'] = None\n self.DIGEST['role_balance'] = None\n\n self.ACCOUNTS = io_data['accounts']\n\n self.ROLES_ACCOUNTS = dict()\n self.ROLES_BALANCES = dict()\n self.ROLES_BALANCE_SHEET = dict()\n\n if self.BY_PERIOD:\n self.ROLES_BALANCES_BY_PERIOD = defaultdict(lambda: dict())\n self.DIGEST['role_balance_by_period'] = None\n if self.BY_UNIT:\n self.ROLES_BALANCES_BY_UNIT = defaultdict(lambda: dict())\n self.DIGEST['role_balance_by_unit'] = None\n\n if self.BY_PERIOD and self.BY_UNIT:\n self.ROLES_BALANCES_BY_PERIOD_AND_UNIT = defaultdict(lambda: dict())\n\n def digest(self):\n\n self.process_roles()\n self.DIGEST['role_account'] = self.ROLES_ACCOUNTS\n self.DIGEST['role_balance'] = self.ROLES_BALANCES\n\n if self.BY_PERIOD:\n self.DIGEST['role_balance_by_period'] = self.ROLES_BALANCES_BY_PERIOD\n if self.BY_UNIT:\n self.DIGEST['role_balance_by_unit'] = self.ROLES_BALANCES_BY_UNIT\n\n return self.DIGEST\n\n def process_roles(self):\n\n for c, l in roles_module.ROLES_DIRECTORY.items():\n for r in l:\n acc_list = list(acc for acc in self.ACCOUNTS if acc['role'] == getattr(roles_module, r))\n\n self.ROLES_ACCOUNTS[r] = acc_list\n self.ROLES_BALANCES[r] = sum(acc['balance'] for acc in acc_list)\n\n if self.BY_PERIOD or self.BY_UNIT:\n for acc in acc_list:\n if self.BY_PERIOD:\n key = (acc['period_year'], acc['period_month'])\n self.ROLES_BALANCES_BY_PERIOD[key][r] = sum(acc['balance'] for acc in acc_list if all([\n acc['period_year'] == key[0],\n acc['period_month'] == key[1]]\n ))\n if self.BY_UNIT:\n key = (acc['unit_uuid'], acc['unit_name'])\n self.ROLES_BALANCES_BY_UNIT[key][r] = sum(\n acc['balance'] for acc in acc_list if acc['unit_uuid'] == key[0])" }, { "identifier": "GroupContextManager", "path": "django_ledger/io/io_context.py", "snippet": "class GroupContextManager:\n GROUP_ACCOUNTS_KEY = 'group_account'\n GROUP_BALANCE_KEY = 'group_balance'\n GROUP_BALANCE_BY_UNIT_KEY = 'group_balance_by_unit'\n GROUP_BALANCE_BY_PERIOD_KEY = 'group_balance_by_period'\n\n def __init__(self,\n io_data: dict,\n by_period: bool = False,\n by_unit: bool = False):\n\n self.BY_PERIOD = by_period\n self.BY_UNIT = by_unit\n\n self.IO_DIGEST = io_data\n\n self.IO_DIGEST[self.GROUP_ACCOUNTS_KEY] = None\n self.IO_DIGEST[self.GROUP_BALANCE_KEY] = None\n\n self.DIGEST_ACCOUNTS = io_data['accounts']\n\n self.GROUPS_ACCOUNTS = dict()\n self.GROUPS_BALANCES = dict()\n\n if self.BY_PERIOD:\n self.GROUPS_BALANCES_BY_PERIOD = defaultdict(lambda: dict())\n self.IO_DIGEST[self.GROUP_BALANCE_BY_PERIOD_KEY] = None\n\n if self.BY_UNIT:\n self.GROUPS_BALANCES_BY_UNIT = defaultdict(lambda: dict())\n self.IO_DIGEST[self.GROUP_BALANCE_BY_UNIT_KEY] = None\n\n if self.BY_PERIOD and self.BY_UNIT:\n self.GROUPS_BALANCES_BY_PERIOD_AND_UNIT = defaultdict(lambda: dict())\n self.IO_DIGEST[self.GROUP_BALANCE_BY_PERIOD_KEY] = None\n\n def digest(self):\n\n self.process_groups()\n self.IO_DIGEST[self.GROUP_ACCOUNTS_KEY] = self.GROUPS_ACCOUNTS\n self.IO_DIGEST[self.GROUP_BALANCE_KEY] = self.GROUPS_BALANCES\n\n if self.BY_PERIOD:\n self.IO_DIGEST[self.GROUP_BALANCE_BY_PERIOD_KEY] = self.GROUPS_BALANCES_BY_PERIOD\n if self.BY_UNIT:\n self.IO_DIGEST[self.GROUP_BALANCE_BY_UNIT_KEY] = self.GROUPS_BALANCES_BY_UNIT\n return self.IO_DIGEST\n\n def get_accounts_generator(self, mod, g):\n return (acc for acc in self.DIGEST_ACCOUNTS if acc['role'] in getattr(mod, g))\n\n def process_groups(self):\n for g in roles_module.ROLES_GROUPS:\n acc_list = list(self.get_accounts_generator(roles_module, g))\n self.GROUPS_ACCOUNTS[g] = acc_list\n self.GROUPS_BALANCES[g] = sum(acc['balance'] for acc in acc_list)\n\n if self.BY_PERIOD or self.BY_UNIT:\n for acc in acc_list:\n if self.BY_PERIOD:\n key = (acc['period_year'], acc['period_month'])\n self.GROUPS_BALANCES_BY_PERIOD[key][g] = sum(\n acc['balance'] for acc in acc_list if all([\n acc['period_year'] == key[0],\n acc['period_month'] == key[1]]\n ))\n if self.BY_UNIT:\n key = (acc['unit_uuid'], acc['unit_name'])\n self.GROUPS_BALANCES_BY_UNIT[key][g] = sum(\n acc['balance'] for acc in acc_list if acc['unit_uuid'] == key[0]\n )" }, { "identifier": "ActivityContextManager", "path": "django_ledger/io/io_context.py", "snippet": "class ActivityContextManager:\n\n def __init__(self,\n io_data: dict,\n by_unit: bool = False,\n by_period: bool = False):\n\n self.DIGEST = io_data\n self.DIGEST['activity_account'] = None\n self.DIGEST['activity_balance'] = None\n\n self.BY_PERIOD = by_period\n self.BY_UNIT = by_unit\n\n self.ACCOUNTS = io_data['accounts']\n self.ACTIVITY_ACCOUNTS = dict()\n self.ACTIVITY_BALANCES = dict()\n\n if self.BY_PERIOD:\n self.ACTIVITY_BALANCES_BY_PERIOD = defaultdict(lambda: dict())\n self.DIGEST['activity_balance_by_period'] = None\n if self.BY_UNIT:\n self.ACTIVITY_BALANCES_BY_UNIT = defaultdict(lambda: dict())\n self.DIGEST['activity_balance_by_unit'] = None\n if self.BY_PERIOD and self.BY_UNIT:\n self.ROLES_BALANCES_BY_PERIOD_AND_UNIT = defaultdict(lambda: dict())\n\n def digest(self):\n\n self.process_activity()\n self.DIGEST['activity_account'] = self.ACTIVITY_ACCOUNTS\n self.DIGEST['activity_balance'] = self.ACTIVITY_BALANCES\n\n if self.BY_PERIOD:\n self.DIGEST['activity_balance_by_period'] = self.ACTIVITY_BALANCES_BY_PERIOD\n if self.BY_UNIT:\n self.DIGEST['activity_balance_by_unit'] = self.ACTIVITY_BALANCES_BY_PERIOD\n\n def get_accounts_generator(self, activity: str):\n return (acc for acc in self.ACCOUNTS if acc['activity'] == activity)\n\n def process_activity(self):\n JournalEntryModel = lazy_importer.get_journal_entry_model()\n for act in JournalEntryModel.VALID_ACTIVITIES:\n acc_list = list(self.get_accounts_generator(act))\n self.ACTIVITY_ACCOUNTS[act] = acc_list\n self.ACTIVITY_BALANCES[act] = sum(acc['balance'] for acc in acc_list)\n\n if self.BY_PERIOD or self.BY_UNIT:\n for acc in acc_list:\n if self.BY_PERIOD:\n key = (acc['period_year'], acc['period_month'])\n self.ACTIVITY_BALANCES_BY_PERIOD[key][act] = sum(acc['balance'] for acc in acc_list if all([\n acc['period_year'] == key[0],\n acc['period_month'] == key[1]]\n ))\n if self.BY_UNIT:\n key = (acc['unit_uuid'], acc['unit_name'])\n self.ACTIVITY_BALANCES_BY_UNIT[key][act] = sum(\n acc['balance'] for acc in acc_list if acc['unit_uuid'] == key[0])" }, { "identifier": "BalanceSheetStatementContextManager", "path": "django_ledger/io/io_context.py", "snippet": "class BalanceSheetStatementContextManager:\n def __init__(self, io_data: dict):\n self.DIGEST = io_data\n\n def digest(self):\n if 'group_account' in self.DIGEST:\n gb_bs = {\n bsr: list(l) for bsr, l in groupby(\n chain.from_iterable(\n [\n self.DIGEST['group_account']['GROUP_ASSETS'],\n self.DIGEST['group_account']['GROUP_LIABILITIES'],\n self.DIGEST['group_account']['GROUP_CAPITAL'],\n ]\n ),\n key=lambda acc: acc['role_bs'])\n }\n\n bs_context = {\n bs_role: {\n 'total_balance': sum(a['balance'] for a in gb),\n 'is_block': True,\n 'roles': {\n r: {\n 'accounts': list(a)\n } for r, a in groupby(list(gb), key=lambda acc: acc['role'])\n }\n } for bs_role, gb in gb_bs.items()\n }\n\n for bs_role, bs_role_data in bs_context.items():\n for acc_role, role_data in bs_role_data['roles'].items():\n role_data['total_balance'] = sum(a['balance'] for a in role_data['accounts'])\n role_data['role_name'] = roles_module.ACCOUNT_LIST_ROLE_VERBOSE[acc_role]\n\n bs_context['equity_balance'] = self.DIGEST['group_balance']['GROUP_EQUITY']\n bs_context['retained_earnings_balance'] = self.DIGEST['group_balance']['GROUP_EARNINGS']\n bs_context['liabilities_equity_balance'] = self.DIGEST['group_balance']['GROUP_LIABILITIES_EQUITY']\n\n self.DIGEST['balance_sheet'] = bs_context\n\n return self.DIGEST" }, { "identifier": "IncomeStatementContextManager", "path": "django_ledger/io/io_context.py", "snippet": "class IncomeStatementContextManager:\n\n def __init__(self, io_data: dict):\n self.DIGEST = io_data\n\n def digest(self):\n if 'group_account' in self.DIGEST:\n self.DIGEST['income_statement'] = {\n 'operating': {\n 'revenues': [\n acc for acc in self.DIGEST['group_account']['GROUP_INCOME'] if\n acc['role'] in roles_module.GROUP_IC_OPERATING_REVENUES\n ],\n 'cogs': [\n acc for acc in self.DIGEST['group_account']['GROUP_COGS'] if\n acc['role'] in roles_module.GROUP_IC_OPERATING_COGS\n ],\n 'expenses': [\n acc for acc in self.DIGEST['group_account']['GROUP_EXPENSES'] if\n acc['role'] in roles_module.GROUP_IC_OPERATING_EXPENSES\n ]\n },\n 'other': {\n 'revenues': [acc for acc in self.DIGEST['group_account']['GROUP_INCOME'] if\n acc['role'] in roles_module.GROUP_IC_OTHER_REVENUES],\n 'expenses': [acc for acc in self.DIGEST['group_account']['GROUP_EXPENSES'] if\n acc['role'] in roles_module.GROUP_IC_OTHER_EXPENSES],\n }\n }\n\n for activity, ic_section in self.DIGEST['income_statement'].items():\n for section, acc_list in ic_section.items():\n for acc in acc_list:\n acc['role_name'] = roles_module.ACCOUNT_LIST_ROLE_VERBOSE[acc['role']]\n\n # OPERATING INCOME...\n self.DIGEST['income_statement']['operating']['gross_profit'] = sum(\n acc['balance'] for acc in chain.from_iterable(\n [\n self.DIGEST['income_statement']['operating']['revenues'],\n self.DIGEST['income_statement']['operating']['cogs']\n ]\n ))\n self.DIGEST['income_statement']['operating']['net_operating_income'] = sum(\n acc['balance'] for acc in chain.from_iterable(\n [\n self.DIGEST['income_statement']['operating']['revenues'],\n self.DIGEST['income_statement']['operating']['cogs'],\n self.DIGEST['income_statement']['operating']['expenses'],\n ]\n ))\n self.DIGEST['income_statement']['operating']['net_operating_revenue'] = sum(\n acc['balance'] for acc in self.DIGEST['income_statement']['operating']['revenues']\n )\n self.DIGEST['income_statement']['operating']['net_cogs'] = sum(\n acc['balance'] for acc in self.DIGEST['income_statement']['operating']['cogs']\n )\n self.DIGEST['income_statement']['operating']['net_operating_expenses'] = sum(\n acc['balance'] for acc in self.DIGEST['income_statement']['operating']['expenses']\n )\n\n # OTHER INCOME....\n self.DIGEST['income_statement']['other']['net_other_revenues'] = sum(\n acc['balance'] for acc in self.DIGEST['income_statement']['other']['revenues']\n )\n self.DIGEST['income_statement']['other']['net_other_expenses'] = sum(\n acc['balance'] for acc in self.DIGEST['income_statement']['other']['expenses']\n )\n self.DIGEST['income_statement']['other']['net_other_income'] = sum(\n acc['balance'] for acc in chain.from_iterable(\n [\n self.DIGEST['income_statement']['other']['revenues'],\n self.DIGEST['income_statement']['other']['expenses']\n ]\n ))\n\n # NET INCOME...\n self.DIGEST['income_statement']['net_income'] = self.DIGEST['income_statement']['operating'][\n 'net_operating_income']\n self.DIGEST['income_statement']['net_income'] += self.DIGEST['income_statement']['other'][\n 'net_other_income']\n return self.DIGEST" }, { "identifier": "CashFlowStatementContextManager", "path": "django_ledger/io/io_context.py", "snippet": "class CashFlowStatementContextManager:\n CFS_DIGEST_KEY = 'cash_flow_statement'\n\n # todo: implement by period and by unit...\n def __init__(self,\n io_data: dict,\n by_period: bool = False,\n by_unit: bool = False):\n self.IO_DIGEST = io_data\n self.CASH_ACCOUNTS = [a for a in self.IO_DIGEST['accounts'] if a['role'] == roles_module.ASSET_CA_CASH]\n self.JE_MODEL = lazy_loader.get_journal_entry_model()\n\n def check_io_digest(self):\n if GroupContextManager.GROUP_BALANCE_KEY not in self.IO_DIGEST:\n raise ValidationError(\n 'IO Digest must have groups for Cash Flow Statement'\n )\n\n def operating(self):\n group_balances = self.IO_DIGEST[GroupContextManager.GROUP_BALANCE_KEY]\n operating_activities = dict()\n operating_activities['GROUP_CFS_NET_INCOME'] = {\n 'description': 'Net Income',\n 'balance': group_balances['GROUP_CFS_NET_INCOME']\n }\n operating_activities['GROUP_CFS_OP_DEPRECIATION_AMORTIZATION'] = {\n 'description': 'Depreciation & Amortization of Assets',\n 'balance': -group_balances['GROUP_CFS_OP_DEPRECIATION_AMORTIZATION']\n }\n operating_activities['GROUP_CFS_OP_INVESTMENT_GAINS'] = {\n 'description': 'Gain/Loss Sale of Assets',\n 'balance': group_balances['GROUP_CFS_OP_INVESTMENT_GAINS']\n }\n operating_activities['GROUP_CFS_OP_ACCOUNTS_RECEIVABLE'] = {\n 'description': 'Accounts Receivable',\n 'balance': -group_balances['GROUP_CFS_OP_ACCOUNTS_RECEIVABLE']\n }\n operating_activities['GROUP_CFS_OP_INVENTORY'] = {\n 'description': 'Inventories',\n 'balance': -group_balances['GROUP_CFS_OP_INVENTORY']\n }\n\n operating_activities['GROUP_CFS_OP_ACCOUNTS_PAYABLE'] = {\n 'description': 'Accounts Payable',\n 'balance': group_balances['GROUP_CFS_OP_ACCOUNTS_PAYABLE']\n }\n operating_activities['GROUP_CFS_OP_OTHER_CURRENT_ASSETS_ADJUSTMENT'] = {\n 'description': 'Other Current Assets',\n 'balance': -group_balances['GROUP_CFS_OP_OTHER_CURRENT_ASSETS_ADJUSTMENT']\n }\n operating_activities['GROUP_CFS_OP_OTHER_CURRENT_LIABILITIES_ADJUSTMENT'] = {\n 'description': 'Other Current Liabilities',\n 'balance': group_balances['GROUP_CFS_OP_OTHER_CURRENT_LIABILITIES_ADJUSTMENT']\n }\n\n net_cash_by_op_activities = sum(i['balance'] for g, i in operating_activities.items())\n self.IO_DIGEST[self.CFS_DIGEST_KEY]['operating'] = operating_activities\n self.IO_DIGEST[self.CFS_DIGEST_KEY]['net_cash_by_activity'] = dict(\n OPERATING=net_cash_by_op_activities\n )\n\n def financing(self):\n group_balances = self.IO_DIGEST[GroupContextManager.GROUP_BALANCE_KEY]\n financing_activities = dict()\n financing_activities['GROUP_CFS_FIN_ISSUING_EQUITY'] = {\n 'description': 'Common Stock, Preferred Stock and Capital Raised',\n 'balance': sum(a['balance'] for a in self.CASH_ACCOUNTS if a['activity'] == self.JE_MODEL.FINANCING_EQUITY)\n }\n financing_activities['GROUP_CFS_FIN_DIVIDENDS'] = {\n 'description': 'Dividends Payed Out to Shareholders',\n 'balance': sum(\n a['balance'] for a in self.CASH_ACCOUNTS if a['activity'] == self.JE_MODEL.FINANCING_DIVIDENDS)\n }\n financing_activities['GROUP_CFS_FIN_ST_DEBT_PAYMENTS'] = {\n 'description': 'Increase/Reduction of Short-Term Debt Principal',\n 'balance': sum(a['balance'] for a in self.CASH_ACCOUNTS if a['activity'] == self.JE_MODEL.FINANCING_STD)\n }\n financing_activities['GROUP_CFS_FIN_LT_DEBT_PAYMENTS'] = {\n 'description': 'Increase/Reduction of Long-Term Debt Principal',\n 'balance': sum(a['balance'] for a in self.CASH_ACCOUNTS if a['activity'] == self.JE_MODEL.FINANCING_LTD)\n }\n\n net_cash = sum(i['balance'] for g, i in financing_activities.items())\n self.IO_DIGEST[self.CFS_DIGEST_KEY]['financing'] = financing_activities\n self.IO_DIGEST[self.CFS_DIGEST_KEY]['net_cash_by_activity']['FINANCING'] = net_cash\n\n def investing(self):\n group_balances = self.IO_DIGEST[GroupContextManager.GROUP_BALANCE_KEY]\n investing_activities = dict()\n investing_activities['GROUP_CFS_INVESTING_SECURITIES'] = {\n 'description': 'Purchase, Maturity and Sales of Investments & Securities',\n 'balance': sum(\n a['balance'] for a in self.CASH_ACCOUNTS if a['activity'] == self.JE_MODEL.INVESTING_SECURITIES)\n }\n investing_activities['GROUP_CFS_INVESTING_PPE'] = {\n 'description': 'Addition and Disposition of Property, Plant & Equipment',\n 'balance': sum(\n a['balance'] for a in self.CASH_ACCOUNTS if a['activity'] == self.JE_MODEL.INVESTING_PPE)\n }\n\n net_cash = sum(i['balance'] for g, i in investing_activities.items())\n self.IO_DIGEST[self.CFS_DIGEST_KEY]['investing'] = investing_activities\n self.IO_DIGEST[self.CFS_DIGEST_KEY]['net_cash_by_activity']['INVESTING'] = net_cash\n\n def net_cash(self):\n self.IO_DIGEST[self.CFS_DIGEST_KEY]['net_cash'] = sum([\n bal for act, bal in self.IO_DIGEST[self.CFS_DIGEST_KEY]['net_cash_by_activity'].items()\n ])\n\n def digest(self):\n self.check_io_digest()\n self.operating()\n self.financing()\n self.investing()\n self.net_cash()\n return self.IO_DIGEST" }, { "identifier": "IODigestContextManager", "path": "django_ledger/io/io_digest.py", "snippet": "class IODigestContextManager:\n\n def __init__(self, io_data: defaultdict):\n self.IO_DATA: defaultdict = io_data\n self.IO_MODEL = self.IO_DATA['io_model']\n self.TXS_QS = self.IO_DATA['txs_qs']\n self.STRFTIME_FORMAT = '%B %d, %Y'\n\n def get_io_data(self) -> defaultdict:\n return self.IO_DATA\n\n def get_strftime_format(self):\n return self.STRFTIME_FORMAT\n\n def get_from_date(self, as_str: bool = False, fmt=None) -> Optional[date]:\n from_date = self.IO_DATA['from_date']\n if from_date:\n if as_str:\n if not fmt:\n fmt = self.get_strftime_format()\n return from_date.strftime(fmt)\n return from_date\n\n def get_to_date(self, as_str: bool = False, fmt=None) -> date:\n if as_str:\n if not fmt:\n fmt = self.get_strftime_format()\n return self.IO_DATA['to_date'].strftime(fmt)\n return self.IO_DATA['to_date']\n\n def is_entity_model(self) -> bool:\n return isinstance(\n self.IO_MODEL,\n lazy_loader.get_entity_model()\n )\n\n def is_ledger_model(self) -> bool:\n return isinstance(\n self.IO_MODEL,\n lazy_loader.get_ledger_model()\n )\n\n def is_unit_model(self) -> bool:\n return isinstance(\n self.IO_MODEL,\n lazy_loader.get_unit_model()\n )\n\n def is_by_unit(self) -> bool:\n return self.IO_DATA['by_unit']\n\n def is_by_period(self) -> bool:\n return self.IO_DATA['by_period']\n\n def is_by_activity(self) -> bool:\n return self.IO_DATA['by_activity']\n\n # Balance Sheet Data...\n def has_balance_sheet(self) -> bool:\n return 'balance_sheet' in self.IO_DATA\n\n def get_balance_sheet_data(self, raise_exception: bool = True) -> Dict:\n try:\n return self.IO_DATA['balance_sheet']\n except KeyError:\n if raise_exception:\n raise IODigestValidationError(\n 'IO Digest does not have balance sheet information available.'\n )\n\n # Income Statement Data...\n def has_income_statement(self) -> bool:\n return 'income_statement' in self.IO_DATA\n\n def get_income_statement_data(self, raise_exception: bool = True) -> Dict:\n try:\n return self.IO_DATA['income_statement']\n except KeyError:\n if raise_exception:\n raise IODigestValidationError(\n 'IO Digest does not have income statement information available.'\n )\n\n # Cash Flow Statement Data...\n def has_cash_flow_statement(self):\n return 'cash_flow_statement' in self.IO_DATA\n\n def get_cash_flow_statement_data(self, raise_exception: bool = True) -> Dict:\n try:\n return self.IO_DATA['cash_flow_statement']\n except KeyError:\n if raise_exception:\n raise IODigestValidationError(\n 'IO Digest does not have cash flow statement information available.'\n )\n\n # CLOSING ENTRIES...\n\n def get_closing_entry_data(self):\n io_data = self.get_io_data()\n return io_data['accounts']" }, { "identifier": "FinancialRatioManager", "path": "django_ledger/io/ratios.py", "snippet": "class FinancialRatioManager:\n\n def __init__(self, io_data):\n self.DIGEST = io_data\n self.ACCOUNTS = io_data['accounts']\n self.RATIO_NA = RATIO_NA\n\n self.quick_assets = io_data['group_balance']['GROUP_QUICK_ASSETS']\n self.assets = io_data['group_balance']['GROUP_ASSETS']\n self.current_liabilities = io_data['group_balance']['GROUP_CURRENT_LIABILITIES']\n self.current_assets = io_data['group_balance']['GROUP_CURRENT_ASSETS']\n self.equity = io_data['group_balance']['GROUP_CAPITAL']\n self.liabilities = io_data['group_balance']['GROUP_LIABILITIES']\n self.net_income = io_data['group_balance']['GROUP_EARNINGS']\n self.net_sales = io_data['group_balance']['GROUP_NET_SALES']\n self.net_profit = io_data['group_balance']['GROUP_NET_PROFIT']\n self.gross_profit = io_data['group_balance']['GROUP_GROSS_PROFIT']\n self.RATIOS = dict()\n\n def digest(self):\n self.quick_ratio()\n self.current_ratio()\n self.debt_to_equity()\n self.return_on_equity()\n self.return_on_assets()\n self.net_profit_margin()\n self.gross_profit_margin()\n self.DIGEST['ratios'] = self.RATIOS\n return self.DIGEST\n\n # ------> SOLVENCY RATIOS <------\n def quick_ratio(self, as_percent=False):\n if self.current_liabilities == 0:\n cr = self.RATIO_NA\n else:\n cr = self.quick_assets / self.current_liabilities\n if as_percent:\n cr = cr * 100\n self.RATIOS['quick_ratio'] = cr\n\n def current_ratio(self, as_percent=False):\n if self.current_liabilities == 0:\n cr = RATIO_NA\n else:\n cr = self.current_assets / self.current_liabilities\n if as_percent:\n cr = cr * 100\n self.RATIOS['current_ratio'] = cr\n\n # ------> LEVERAGE RATIOS <------\n def debt_to_equity(self, as_percent=False):\n if self.equity == 0:\n cr = RATIO_NA\n else:\n cr = self.liabilities / self.equity\n if as_percent:\n cr = cr * 100\n self.RATIOS['debt_to_equity'] = cr\n\n # ------> PROFITABILITY RATIOS <------\n def return_on_equity(self, as_percent=False):\n if self.equity == 0:\n cr = RATIO_NA\n else:\n cr = self.net_income / self.equity\n if as_percent:\n cr = cr * 100\n self.RATIOS['return_on_equity'] = cr\n\n def return_on_assets(self, as_percent=False):\n if self.assets == 0:\n cr = RATIO_NA\n else:\n cr = self.net_income / self.assets\n if as_percent:\n cr = cr * 100\n self.RATIOS['return_on_assets'] = cr\n\n def net_profit_margin(self, as_percent=False):\n if self.net_sales == 0:\n npm = RATIO_NA\n else:\n npm = self.net_profit / self.net_sales\n if as_percent:\n npm = npm * 100\n self.RATIOS['net_profit_margin'] = npm\n\n def gross_profit_margin(self, as_percent=False):\n if self.gross_profit == 0:\n gpm = RATIO_NA\n else:\n gpm = self.gross_profit / self.net_sales\n if as_percent:\n gpm = gpm * 100\n self.RATIOS['gross_profit_margin'] = gpm" }, { "identifier": "lazy_loader", "path": "django_ledger/models/utils.py", "snippet": "class LazyLoader:\n ENTITY_MODEL = None\n ENTITY_STATE_MODEL = None\n UNIT_MODEL = None\n ACCOUNT_MODEL = None\n BANK_ACCOUNT_MODEL = None\n LEDGER_MODEL = None\n TXS_MODEL = None\n JE_MODEL = None\n ITEM_MODEL = None\n ITEM_TRANSACTION_MODEL = None\n CUSTOMER_MODEL = None\n INVOICE_MODEL = None\n BILL_MODEL = None\n UOM_MODEL = None\n VENDOR_MODEL = None\n TRANSACTION_MODEL = None\n ENTITY_UNIT_MODEL = None\n PURCHASE_ORDER_MODEL = None\n ESTIMATE_MODEL = None\n CLOSING_ENTRY_MODEL = None\n CLOSING_ENTRY_TRANSACTION_MODEL = None\n ENTITY_DATA_GENERATOR = None\n BALANCE_SHEET_REPORT_CLASS = None\n INCOME_STATEMENT_REPORT_CLASS = None\n CASH_FLOW_STATEMENT_REPORT_CLASS = None\n def get_entity_model(self):\n def get_entity_state_model(self):\n def get_bank_account_model(self):\n def get_account_model(self):\n def get_txs_model(self):\n def get_purchase_order_model(self):\n def get_ledger_model(self):\n def get_unit_model(self):\n def get_journal_entry_model(self):\n def get_item_model(self):\n def get_item_transaction_model(self):\n def get_customer_model(self):\n def get_bill_model(self):\n def get_invoice_model(self):\n def get_uom_model(self):\n def get_vendor_model(self):\n def get_transaction_model(self):\n def get_entity_unit_model(self):\n def get_estimate_model(self):\n def get_entity_data_generator(self):\n def get_closing_entry_model(self):\n def get_closing_entry_transaction_model(self):\n def get_balance_sheet_report_class(self):\n def get_income_statement_report_class(self):\n def get_cash_flow_statement_report_class(self):" } ]
from collections import defaultdict, namedtuple from datetime import datetime, date from itertools import groupby from pathlib import Path from random import choice from typing import List, Set, Union, Tuple, Optional, Dict from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError, ObjectDoesNotExist from django.db.models import Sum, QuerySet from django.db.models.functions import TruncMonth from django.http import Http404 from django.utils.dateparse import parse_date, parse_datetime from django.utils.timezone import make_aware, is_naive, localtime from django.utils.translation import gettext_lazy as _ from django_ledger import settings from django_ledger.exceptions import InvalidDateInputError, TransactionNotInBalanceError from django_ledger.io import roles as roles_module from django_ledger.io.io_context import (RoleContextManager, GroupContextManager, ActivityContextManager, BalanceSheetStatementContextManager, IncomeStatementContextManager, CashFlowStatementContextManager) from django_ledger.io.io_digest import IODigestContextManager from django_ledger.io.ratios import FinancialRatioManager from django_ledger.models.utils import lazy_loader
15,656
# print('Orig From:', from_date) # print('New from:', from_date_d) # print('To Date:', to_date) # print(closing_entry_list) if not txs_queryset: TransactionModel = lazy_loader.get_txs_model() if self.is_entity_model(): if entity_slug: if entity_slug != self.slug: raise IOValidationError('Inconsistent entity_slug. ' f'Provided {entity_slug} does not match actual {self.slug}') if unit_slug: txs_queryset = TransactionModel.objects.for_unit( user_model=user_model, entity_slug=entity_slug or self.slug, unit_slug=unit_slug ) else: txs_queryset = TransactionModel.objects.for_entity( user_model=user_model, entity_slug=self ) elif self.is_ledger_model(): if not entity_slug: raise IOValidationError( 'Calling digest from Ledger Model requires entity_slug explicitly for safety') txs_queryset = TransactionModel.objects.for_ledger( user_model=user_model, entity_slug=entity_slug, ledger_model=self ) elif self.is_entity_unit_model(): if not entity_slug: raise IOValidationError( 'Calling digest from Entity Unit requires entity_slug explicitly for safety') txs_queryset = TransactionModel.objects.for_unit( user_model=user_model, entity_slug=entity_slug, unit_slug=unit_slug or self ) else: txs_queryset = TransactionModel.objects.none() txs_queryset = txs_queryset.not_closing_entry() if exclude_zero_bal: txs_queryset = txs_queryset.filter(amount__gt=0) if posted: txs_queryset = txs_queryset.posted() if from_date: txs_queryset = txs_queryset.from_date(from_date=from_date) if to_date: txs_queryset = txs_queryset.to_date(to_date=to_date) if accounts: if not isinstance(accounts, str): accounts = [accounts] txs_queryset = txs_queryset.for_accounts(account_list=accounts) if activity: if isinstance(activity, str): activity = [activity] txs_queryset = txs_queryset.for_activity(activity_list=activity) if role: txs_queryset = txs_queryset.for_roles(role_list=role) VALUES = [ 'account__uuid', 'account__balance_type', 'tx_type', 'account__code', 'account__name', 'account__role', ] ANNOTATE = {'balance': Sum('amount')} ORDER_BY = ['account__uuid'] if by_unit: ORDER_BY.append('journal_entry__entity_unit__uuid') VALUES += ['journal_entry__entity_unit__uuid', 'journal_entry__entity_unit__name'] if by_period: ORDER_BY.append('journal_entry__timestamp') ANNOTATE['dt_idx'] = TruncMonth('journal_entry__timestamp') if by_activity: ORDER_BY.append('journal_entry__activity') VALUES.append('journal_entry__activity') if by_tx_type: ORDER_BY.append('tx_type') VALUES.append('tx_type') return txs_queryset.values(*VALUES).annotate(**ANNOTATE).order_by(*ORDER_BY) def python_digest(self, txs_queryset: Optional[QuerySet] = None, user_model: Optional[UserModel] = None, to_date: date = None, from_date: date = None, equity_only: bool = False, activity: str = None, entity_slug: str = None, unit_slug: str = None, role: Optional[Union[Set[str], List[str]]] = None, accounts: Optional[Union[Set[str], List[str]]] = None, signs: bool = False, by_unit: bool = False, by_activity: bool = False, by_tx_type: bool = False, by_period: bool = False, **kwargs) -> list or tuple: if equity_only:
""" Django Ledger created by Miguel Sanda <[email protected]>. Copyright© EDMA Group Inc licensed under the GPLv3 Agreement. Contributions to this module: * Miguel Sanda <[email protected]> """ UserModel = get_user_model() def diff_tx_data(tx_data: list, raise_exception: bool = True): IS_TX_MODEL = False TransactionModel = lazy_loader.get_txs_model() if isinstance(tx_data[0], TransactionModel): CREDITS = sum(tx.amount for tx in tx_data if tx.tx_type == 'credit') DEBITS = sum(tx.amount for tx in tx_data if tx.tx_type == 'debit') IS_TX_MODEL = True elif isinstance(tx_data[0], dict): CREDITS = sum(tx['amount'] for tx in tx_data if tx['tx_type'] == 'credit') DEBITS = sum(tx['amount'] for tx in tx_data if tx['tx_type'] == 'debit') else: raise ValidationError('Only Dictionary or TransactionModel allowed.') is_valid = (CREDITS == DEBITS) diff = CREDITS - DEBITS if not is_valid and abs(diff) > settings.DJANGO_LEDGER_TRANSACTION_MAX_TOLERANCE: if raise_exception: raise TransactionNotInBalanceError( f'Invalid tx data. Credits and debits must match. Currently cr: {CREDITS}, db {DEBITS}.' f'Max Tolerance {settings.DJANGO_LEDGER_TRANSACTION_MAX_TOLERANCE}' ) return IS_TX_MODEL, is_valid, diff def check_tx_balance(tx_data: list, perform_correction: bool = False) -> bool: if tx_data: IS_TX_MODEL, is_valid, diff = diff_tx_data(tx_data, raise_exception=perform_correction) if not perform_correction and abs(diff): return False if not perform_correction and abs(diff) > settings.DJANGO_LEDGER_TRANSACTION_MAX_TOLERANCE: return False while not is_valid: tx_type_choice = choice(['debit', 'credit']) txs_candidates = list(tx for tx in tx_data if tx['tx_type'] == tx_type_choice) if len(txs_candidates) > 0: tx = choice(list(tx for tx in tx_data if tx['tx_type'] == tx_type_choice)) if any([diff > 0 and tx_type_choice == 'debit', diff < 0 and tx_type_choice == 'credit']): if IS_TX_MODEL: tx.amount += settings.DJANGO_LEDGER_TRANSACTION_CORRECTION else: tx['amount'] += settings.DJANGO_LEDGER_TRANSACTION_CORRECTION elif any([diff < 0 and tx_type_choice == 'debit', diff > 0 and tx_type_choice == 'credit']): if IS_TX_MODEL: tx.amount -= settings.DJANGO_LEDGER_TRANSACTION_CORRECTION else: tx['amount'] += settings.DJANGO_LEDGER_TRANSACTION_CORRECTION IS_TX_MODEL, is_valid, diff = diff_tx_data(tx_data) return True def validate_io_date(dt: Union[str, date, datetime], no_parse_localdate: bool = True) -> Optional[datetime]: if not dt: return if isinstance(dt, date): dt = make_aware( value=datetime.combine( dt, datetime.min.time() )) return dt elif isinstance(dt, datetime): if is_naive(dt): return make_aware(dt) return dt elif isinstance(dt, str): # try to parse a date object from string... fdt = parse_date(dt) if not fdt: # try to parse a datetime object from string... fdt = parse_datetime(dt) if not fdt: raise InvalidDateInputError( message=f'Could not parse date from {dt}' ) elif is_naive(fdt): fdt = make_aware(fdt) return fdt if no_parse_localdate: return localtime() def validate_dates( from_date: Union[str, datetime, date] = None, to_date: Union[str, datetime, date] = None) -> Tuple[date, date]: from_date = validate_io_date(from_date, no_parse_localdate=False) to_date = validate_io_date(to_date) return from_date, to_date def validate_activity(activity: str, raise_404: bool = False): # idea: move to model???... JournalEntryModel = lazy_loader.get_journal_entry_model() valid = activity in JournalEntryModel.VALID_ACTIVITIES if activity and not valid: exception = ValidationError(f'{activity} is invalid. Choices are {JournalEntryModel.VALID_ACTIVITIES}.') if raise_404: raise Http404(exception) raise exception return activity class IOValidationError(ValidationError): pass class IODatabaseMixIn: """ Controls how transactions are recorded into the ledger. """ def is_entity_model(self): return isinstance(self, lazy_loader.get_entity_model()) def is_ledger_model(self): return isinstance(self, lazy_loader.get_ledger_model()) def is_entity_unit_model(self): return isinstance(self, lazy_loader.get_unit_model()) def get_entity_model_from_io(self): if self.is_entity_model(): return self elif self.is_ledger_model(): return self.entity elif self.is_entity_unit_model(): return self.entity # def is_time_bounded(self, from_date, to_date): def database_digest(self, txs_queryset: QuerySet, entity_slug: str = None, unit_slug: str = None, user_model: UserModel = None, from_date: date = None, to_date: date = None, activity: str = None, role: str = None, accounts: str or List[str] or Set[str] = None, posted: bool = True, exclude_zero_bal: bool = True, by_activity: bool = False, by_tx_type: bool = False, by_period: bool = False, by_unit: bool = False, **kwargs): if settings.DJANGO_LEDGER_USE_CLOSING_ENTRIES: if not from_date: entity_model = self.get_entity_model_from_io() closing_entry_date = entity_model.select_closing_entry_for_io_date(to_date=to_date) # print(closing_entry_date) # # if closing_entry_date: # closing_entry_list = entity_model.get_closing_entry_cache_for_date( # closing_date=closing_entry_date, # force_cache_update=True # ) # from_date_d = closing_entry_date + timedelta(days=1) # print('Orig From:', from_date) # print('New from:', from_date_d) # print('To Date:', to_date) # print(closing_entry_list) if not txs_queryset: TransactionModel = lazy_loader.get_txs_model() if self.is_entity_model(): if entity_slug: if entity_slug != self.slug: raise IOValidationError('Inconsistent entity_slug. ' f'Provided {entity_slug} does not match actual {self.slug}') if unit_slug: txs_queryset = TransactionModel.objects.for_unit( user_model=user_model, entity_slug=entity_slug or self.slug, unit_slug=unit_slug ) else: txs_queryset = TransactionModel.objects.for_entity( user_model=user_model, entity_slug=self ) elif self.is_ledger_model(): if not entity_slug: raise IOValidationError( 'Calling digest from Ledger Model requires entity_slug explicitly for safety') txs_queryset = TransactionModel.objects.for_ledger( user_model=user_model, entity_slug=entity_slug, ledger_model=self ) elif self.is_entity_unit_model(): if not entity_slug: raise IOValidationError( 'Calling digest from Entity Unit requires entity_slug explicitly for safety') txs_queryset = TransactionModel.objects.for_unit( user_model=user_model, entity_slug=entity_slug, unit_slug=unit_slug or self ) else: txs_queryset = TransactionModel.objects.none() txs_queryset = txs_queryset.not_closing_entry() if exclude_zero_bal: txs_queryset = txs_queryset.filter(amount__gt=0) if posted: txs_queryset = txs_queryset.posted() if from_date: txs_queryset = txs_queryset.from_date(from_date=from_date) if to_date: txs_queryset = txs_queryset.to_date(to_date=to_date) if accounts: if not isinstance(accounts, str): accounts = [accounts] txs_queryset = txs_queryset.for_accounts(account_list=accounts) if activity: if isinstance(activity, str): activity = [activity] txs_queryset = txs_queryset.for_activity(activity_list=activity) if role: txs_queryset = txs_queryset.for_roles(role_list=role) VALUES = [ 'account__uuid', 'account__balance_type', 'tx_type', 'account__code', 'account__name', 'account__role', ] ANNOTATE = {'balance': Sum('amount')} ORDER_BY = ['account__uuid'] if by_unit: ORDER_BY.append('journal_entry__entity_unit__uuid') VALUES += ['journal_entry__entity_unit__uuid', 'journal_entry__entity_unit__name'] if by_period: ORDER_BY.append('journal_entry__timestamp') ANNOTATE['dt_idx'] = TruncMonth('journal_entry__timestamp') if by_activity: ORDER_BY.append('journal_entry__activity') VALUES.append('journal_entry__activity') if by_tx_type: ORDER_BY.append('tx_type') VALUES.append('tx_type') return txs_queryset.values(*VALUES).annotate(**ANNOTATE).order_by(*ORDER_BY) def python_digest(self, txs_queryset: Optional[QuerySet] = None, user_model: Optional[UserModel] = None, to_date: date = None, from_date: date = None, equity_only: bool = False, activity: str = None, entity_slug: str = None, unit_slug: str = None, role: Optional[Union[Set[str], List[str]]] = None, accounts: Optional[Union[Set[str], List[str]]] = None, signs: bool = False, by_unit: bool = False, by_activity: bool = False, by_tx_type: bool = False, by_period: bool = False, **kwargs) -> list or tuple: if equity_only:
role = roles_module.GROUP_EARNINGS
2
2023-10-20 01:07:20+00:00
24k
acolas1/KGSimple
simplify.py
[ { "identifier": "FluencyScorer", "path": "scoring/fluency_scorer.py", "snippet": "class FluencyScorer:\n def __init__(self, batch_size=1, reduce=\"mean\", log=True, laplace_smooth=False, prob_dict_path=None):\n self.device = \"cuda:1\" if torch.cuda.is_available() else \"cpu\"\n self.batch_size = batch_size\n self.reduce = reduce\n self.log = log\n self.laplace_smooth = laplace_smooth\n self.tokenizer = GPT2Tokenizer.from_pretrained(\"gpt2\")\n self.scorer = LMScorer.from_pretrained(\"gpt2\", device=self.device, batch_size=batch_size)\n self.idf_df = pd.read_csv(prob_dict_path, ',', encoding='utf-8')\n self.freq_dict = pd.Series((self.idf_df.frequency.values), index=self.idf_df.token).to_dict()\n self.num_tokens = self.idf_df.total.values[0] \n \n def unigram_score(self, sentences):\n if self.freq_dict is None:\n raise Exception(\"Probability dictionary is not defined.\") \n unigram_scores = []\n for sent in sentences:\n unigram_prob = 1\n for token in word_tokenize(sent.lower()):\n if token in self.freq_dict:\n if self.laplace_smooth:\n curr_unigram_prob = (self.freq_dict[token]+1)/(self.num_tokens+len(self.freq_dict))\n else:\n curr_unigram_prob = self.freq_dict[token]/self.num_tokens\n \n \n\n else:\n if self.laplace_smooth:\n curr_unigram_prob = (1/(self.num_tokens+len(self.freq_dict)))\n else:\n curr_unigram_prob = 1\n # unigram_prob += curr_unigram_prob\n \n \n if self.log:\n unigram_prob +=np.log(curr_unigram_prob)\n else:\n unigram_prob *= curr_unigram_prob\n uni_score = unigram_prob/len(word_tokenize(sent))\n unigram_scores.append(uni_score)\n return unigram_scores\n \n def SLOR_score(self, sentence_list, lm_score, unigram_score):\n SLOR_scores = []\n for i in range(len(sentence_list)):\n SLOR_score = lm_score[i]-unigram_score[i]\n if self.log:\n SLOR_score = math.exp(lm_score[i]-unigram_score[i])\n SLOR_scores.append(SLOR_score)\n return SLOR_scores\n \n def score_batched(self, generated_texts, source_texts=None, printing=False, **kwargs):\n sources_SLOR_score, generateds_SLOR_score = None, None\n if source_texts:\n sources_lm_prob_scores = self.scorer.sentence_score(source_texts, reduce=self.reduce, log=self.log)\n sources_unigram_scores = self.unigram_score(source_texts)\n sources_SLOR_score = self.SLOR_score(source_texts, sources_lm_prob_scores, sources_unigram_scores)\n\n\n\n generateds_lm_prob_scores = self.scorer.sentence_score(generated_texts, reduce=self.reduce, log=self.log)\n generateds_unigram_scores = self.unigram_score(generated_texts)\n generateds_SLOR_score = self.SLOR_score(generated_texts, generateds_lm_prob_scores, generateds_unigram_scores)\n \n if printing:\n print(\"[source_sents]\", source_texts)\n print(\"[source_lm]\", sources_lm_prob_scores)\n print(\"[source_unigram]\", sources_unigram_scores)\n print(\"[source_scores]\", sources_SLOR_score)\n print(\"[generated_sents]\", generated_texts)\n print(\"[generated_lm]\", generateds_lm_prob_scores)\n print(\"[generated_unigram]\", generateds_unigram_scores)\n print(\"[generated_scores]\", generateds_SLOR_score)\n return {\"scores\": generateds_SLOR_score, \"source_scores\": sources_SLOR_score}\n\n def score(self, generated_text, source_text=None, printing=False, **kwargs):\n # sources_lm_prob_score = scorer.sentence_score(source_list, reduce=\"mean\")\n \n sources_SLOR_score, generateds_SLOR_score = None, None\n if source_text:\n source_list = [source_text]\n sources_lm_prob_scores = self.scorer.sentence_score(source_list, reduce=self.reduce, log=self.log)\n sources_unigram_scores = self.unigram_score(source_list)\n sources_SLOR_score = self.SLOR_score(source_list, sources_lm_prob_scores, sources_unigram_scores)\n \n \n \n generateds_list = [generated_text]\n generateds_lm_prob_scores = self.scorer.sentence_score(generateds_list, reduce=self.reduce, log=self.log)\n generateds_unigram_scores = self.unigram_score(generateds_list)\n generateds_SLOR_score = self.SLOR_score(generateds_list, generateds_lm_prob_scores, generateds_unigram_scores)\n \n if printing:\n print(\"[source_sents]\", source_text)\n print(\"[source_lm]\", sources_lm_prob_scores)\n print(\"[source_unigram]\", sources_unigram_scores)\n print(\"[source_scores]\", sources_SLOR_score)\n print(\"[generated_sents]\", generated_text)\n print(\"[generated_lm]\", generateds_lm_prob_scores)\n print(\"[generated_unigram]\", generateds_unigram_scores)\n print(\"[generated_scores]\", generateds_SLOR_score)\n return {\"scores\": generateds_SLOR_score, \"source_scores\": sources_SLOR_score}" }, { "identifier": "SaliencyBERTScore", "path": "scoring/saliency_scorer.py", "snippet": "class SaliencyBERTScore:\n def __init__(self, lmscorer = \"bertscore\", lang=\"en\"):\n self.bertscore = evaluate.load(lmscorer)\n self.lang = lang\n\n\n def calc_BERT_score(self, predictions, references, sigmoid):\n results = self.bertscore.compute(predictions=predictions, references=references, lang=self.lang)\n if sigmoid:\n results = expit(results)\n return results\n\n def score_batched(self, generated_text, source_text=None, sigmoid=False, printing=False, **kwargs):\n gen_score, source_score = None, None\n bert_score = self.calc_BERT_score(generated_text, source_text, sigmoid)\n f1 = bert_score['f1']\n \n if printing:\n print(\"scores: \", str(f1))\n return {\"scores\": f1}\n\n def score(self, generated_text, source_text=None, sigmoid=False, printing=False, **kwargs):\n gen_score, source_score = None, None\n bert_score = self.calc_BERT_score([generated_text], [source_text], sigmoid)\n f1 = bert_score['f1']\n \n if printing:\n print(\"scores: \", str(f1))\n return {\"scores\": f1}" }, { "identifier": "SimplicityTextScore", "path": "scoring/simplicity_scorer.py", "snippet": "class SimplicityTextScore:\n def __init__(self):\n pass\n\n def calc_FRE(self, text, sigmoid):\n min_val = -30\n score = textstat.flesch_reading_ease(text)\n scaled_score = (score - min_val) / (121.22 - min_val)\n # Clamp scaled_score to the range [0, 1]\n scaled_score = max(0, min(scaled_score, 1))\n \n if sigmoid:\n scaled_score = expit(scaled_score)\n \n return scaled_score\n \n \n \n def calc_FKGL(self, text, sigmoid):\n score = max(0,textstat.flesch_kincaid_grade(text))\n if sigmoid:\n score = expit(score)\n return score\n\n def score_batched(self, generated_texts, source_texts=None, sigmoid=False, printing=False, **kwargs):\n gen_score, source_score = [],[]\n \n for text in generated_texts:\n gen_score.append(self.calc_FRE(text, sigmoid))\n \n \n if source_texts:\n for text in source_texts:\n source_score.append(self.calc_FRE(text, sigmoid))\n \n if printing:\n print(\"score: \", gen_score)\n print(\"source_score: \", source_score)\n return {\"scores\": gen_score, \"source_scores\": source_score}\n \n def score(self, generated_text, source_text=None, sigmoid=False, printing=False, **kwargs):\n gen_score, source_score = None, None\n \n gen_score = self.calc_FRE(generated_text, sigmoid)\n \n if source_text:\n source_score = self.calc_FRE(source_text, sigmoid)\n \n if printing:\n print(\"score: \", gen_score)\n print(\"source_score: \", source_score)\n return {\"scores\": gen_score, \"source_scores\": source_score}" }, { "identifier": "ScorerWrapper", "path": "scoring/aggregate_scorer.py", "snippet": "class ScorerWrapper:\n def __init__(self, scorers, scoring_method=\"logsum\", batch_size=1):\n assert scoring_method in [\"product\", \"logsum\"], \"Unrecognized `scoring_method`\"\n \n self.scorers = scorers\n self.scoring_method = scoring_method\n\n # if self.scoring_method == \"logsum\":\n # self.score_func = logsum_score\n # elif self.scoring_method == \"product\":\n # self.score_func = product_score\n \n if batch_size > 1:\n exec(\"self.score_func = {}\".format(self.scoring_method+\"_\"+\"score_batched\"))\n else:\n exec(\"self.score_func = {}\").format(self.scoring_method+\"_\"+\"score\")\n self.batch_size = batch_size\n def get_score_names(self):\n return [s[\"name\"] for s in self.scorers]\n \n def score_batched(self, input_texts=None, generated_texts=None, old_kgs=None, new_kgs=None, dels_ents=None, partial=False, printing=False, timings=False, extras={}, progress=False):\n assert len(input_texts) == len(generated_texts) == len(old_kgs) == len(new_kgs) == len(dels_ents), \"Data lengths don't match\"\n \n data_list = []\n for inp, gen, old_kg, new_kg, del_ents in zip(input_texts, generated_texts, old_kgs, new_kgs, dels_ents):\n data_list.append({\"inp\": inp, \"gen\": gen, \"old_kg\": old_kg, \"new_kg\": new_kg, \"del_ents\": del_ents})\n\n if len(data_list) == 0:\n progress = False\n \n for batch in batcher(data_list, batch_size=self.batch_size, progress=progress):\n batch_inputs = [instance_dict[\"inp\"] for instance_dict in batch]\n batch_gens = [instance_dict[\"gen\"] for instance_dict in batch]\n batch_old_kgs = [instance_dict[\"old_kg\"] for instance_dict in batch]\n batch_new_kgs = [instance_dict[\"new_kg\"] for instance_dict in batch]\n batch_dels_ents = [instance_dict[\"del_ents\"] for instance_dict in batch]\n batch_scores = self.score_func(self.scorers, batch_inputs, batch_gens, batch_old_kgs, batch_new_kgs, batch_dels_ents)\n for score_type, scores in batch_scores.items():\n if type(scores) in [torch.Tensor, np.array, np.ndarray]:\n batch_scores[score_type] = scores.tolist()\n\n if printing:\n print(\"[total]\", all_outputs[\"total_scores\"])\n return batch_scores\n \n def score(self, input_text=None, generated_text=None, old_kg=None, new_kg=None, del_ents=None):\n aggregate_score = self.score_func(self.scorers, input_text, generated_text, old_kg, new_kg, del_ents)\n return aggregate_score\n \n\n def __call__(self, graphs, input_text, generated_text, **kwargs):\n return self.score(graphs, input_text, generated_text, **kwargs)" }, { "identifier": "GAPDataloader", "path": "GAP/data_relations_as_nodes.py", "snippet": "class GAPDataloader(DataLoader):\n\n def __init__(self, args, dataset, mode):\n if mode == \"train\":\n sampler = RandomSampler(dataset)\n batch_size = args.train_batch_size\n else:\n sampler = SequentialSampler(dataset)\n batch_size = args.predict_batch_size\n super(GAPDataloader, self).__init__(dataset, sampler=sampler, batch_size=batch_size,\n num_workers=args.num_workers)" }, { "identifier": "EventDataset", "path": "GAP/data_relations_as_nodes.py", "snippet": "class EventDataset(Dataset):\n def __init__(self, logger, args, data, tokenizer, mode):\n self.data = data\n self.tokenizer = tokenizer\n self.topology = {\"entity-entity\": args.entity_entity, \n \"entity-relation\": args.entity_relation,\n \"relation-entity\": args.relation_entity,\n \"relation-relation\": args.relation_relation\n } \n \n \n \n print(\"Total samples = {}\".format(len(self.data)))\n\n \n assert type(self.data) == list\n self.args = args\n self.data_type = mode\n self.metric = \"BLEU\"\n self.head_ids, self.rel_ids, self.tail_ids = self.tokenizer.encode(' [head]', add_special_tokens=False), \\\n self.tokenizer.encode(' [relation]', add_special_tokens=False), \\\n self.tokenizer.encode(' [tail]', add_special_tokens=False)\n self.graph_ids, self.text_ids = self.tokenizer.encode(' [graph]', add_special_tokens=False), \\\n self.tokenizer.encode(' [text]', add_special_tokens=False)\n\n if self.args.model_name == \"bart\":\n self.mask_token = self.tokenizer.mask_token\n self.mask_token_id = self.tokenizer.mask_token_id\n else:\n self.mask_token = self.tokenizer.additional_special_tokens[0]\n self.mask_token_id = self.tokenizer.convert_tokens_to_ids(self.tokenizer.additional_special_tokens[0])\n\n if self.args.model_name == \"bart\":\n if self.args.append_another_bos:\n self.add_bos_id = [self.tokenizer.bos_token_id] * 2\n else:\n self.add_bos_id = [self.tokenizer.bos_token_id]\n else:\n self.add_bos_id = []\n\n def __len__(self):\n return len(self.data)\n \n def graph_size(self,idx):\n entry = self.data[idx]\n kg = entry[0]\n \n kg_list = []\n triple_list = kg.split('<S>')\n triple_list = [triple_list[0]] + ['<S>'+triple for triple in triple_list[1:]]\n triple_list = list(filter(None,triple_list))\n for triple in triple_list:\n head = re.search('<S>(.*)<P>', triple).group(1).strip()\n rel = re.search('<P>(.*)<O>', triple).group(1).strip()\n tail = re.search('<O>(.*)', triple).group(1).strip()\n kg_list.append([head,rel,tail])\n \n \n\n strings_label = []\n node_ids = []\n edge_ids = []\n strings_label_tokens = ''\n\n \n text_entity, text_relation = self.get_all_entities_per_sample(kg_list)\n entity_change, relation_change = self.get_change_per_sample(text_entity, text_relation)\n return len(entity_change)\n\n def graph_linearize(self, triple, entity_change, head_ids, rel_ids, tail_ids,\n relation_change, cnt_edge, adj_matrix):\n # string_label: encoder ids\n # string_label_tokens: encoder tokens\n if len(triple[0]) == 0:\n return [], '', [], [], cnt_edge, adj_matrix\n nodes, edges = [], []\n string_label = copy.deepcopy(head_ids)\n string_label_tokens = ' <S>'\n nodes.extend([-1] * len(string_label))\n edges.extend([-1] * len(string_label))\n\n\n string_label += entity_change[triple[0]][0]\n string_label_tokens += ' {}'.format(triple[0])\n nodes.extend([entity_change[triple[0]][1]] * len(entity_change[triple[0]][0]))\n edges.extend([-1] * len(entity_change[triple[0]][0]))\n\n\n if len(triple[1]) != 0 and len(triple[2]) != 0:\n rel_label = relation_change[triple[1]]\n rel_ent_label = entity_change[triple[1]][1]\n rel_label_token = copy.deepcopy(triple[1])\n words_label = rel_ids + rel_label + tail_ids + entity_change[triple[2]][0]\n words_label_tokens = ' <P> {} <O> {}'.format(rel_label_token, triple[2])\n nodes.extend(\n ([-1] * len(rel_ids)) + ([entity_change[triple[1]][1]] * len(rel_label)) + ([-1] * len(tail_ids)) + ([entity_change[triple[2]][1]] * len(\n entity_change[triple[2]][0])))\n edges.extend([-1] * len(rel_ids) + [cnt_edge] * len(rel_label) + [-1] * (\n len(tail_ids) + len(entity_change[triple[2]][0])))\n if entity_change[triple[0]][1] < len(adj_matrix) and entity_change[triple[2]][1] < len(adj_matrix):\n\n\n if self.topology['entity-entity']:\n adj_matrix[entity_change[triple[0]][1]][entity_change[triple[2]][1]] = 1\n adj_matrix[entity_change[triple[2]][1]][entity_change[triple[0]][1]] = 1\n\n if self.topology['entity-relation']:\n adj_matrix[entity_change[triple[0]][1]][entity_change[triple[1]][1]] = 2\n adj_matrix[entity_change[triple[2]][1]][entity_change[triple[1]][1]] = 2\n\n if self.topology['relation-entity']:\n adj_matrix[entity_change[triple[1]][1]][entity_change[triple[0]][1]] = 3\n adj_matrix[entity_change[triple[2]][1]][entity_change[triple[1]][1]] = 3\n \n if not self.topology['relation-entity'] and not self.topology['relation-relation']:\n adj_matrix[entity_change[triple[1]][1]][entity_change[triple[1]][1]] = 10\n\n if not self.topology['entity-relation'] and not self.topology['entity-entity']:\n adj_matrix[entity_change[triple[0]][1]][entity_change[triple[0]][1]] = 10\n adj_matrix[entity_change[triple[2]][1]][entity_change[triple[2]][1]] = 10\n\n cnt_edge += 1\n string_label += words_label\n string_label_tokens += words_label_tokens\n\n assert len(string_label) == len(nodes) == len(edges)\n\n return string_label, string_label_tokens, nodes, edges, cnt_edge, adj_matrix\n\n def relation_to_relation_fill(self, node_dict, rel_dict, adj_matrix):\n adj_matrix_temp = np.array(adj_matrix)\n rel_idx_list = []\n for rel in rel_dict.keys():\n rel_idx = node_dict[rel][1]\n rel_idx_list.append(rel_idx)\n adj_matrix_np = np.array(adj_matrix)\n adj_matrix_np_bool = (adj_matrix_np==-1)\n #reassign -1s to 0s\n adj_matrix_np[adj_matrix_np_bool] = 0\n #get squared matrix for r-r\n adj_matrix_sq = adj_matrix_np@adj_matrix_np\n \n #old adj_matrix + squared matrix only r-r\n rel_idx_list = np.array(rel_idx_list, dtype=np.intp)\n adj_matrix_temp[rel_idx_list[:,np.newaxis], rel_idx_list] = (adj_matrix_sq[rel_idx_list][:,rel_idx_list] > 0)*4\n adj_matrix_new = adj_matrix_temp.tolist()\n \n return adj_matrix_new\n \n def get_all_entities_per_sample(self, triple_list):\n text_entity = set()\n text_relation = set()\n for triple in triple_list:\n if len(triple[0]) == 0:\n continue\n if len(triple[1]) != 0 and len(triple[2]) != 0:\n text_relation.add(triple[1])\n text_entity.add(triple[0])\n text_entity.add(triple[2])\n \n text_entity_list = list(text_entity)+list(text_relation)\n text_relation_list = list(text_relation)\n \n return text_entity_list, text_relation_list\n\n def get_change_per_sample(self, text_entity, text_relation):\n # during fine-tuning, we don't mask entities or relations\n ent_change = {}\n total_entity = text_entity\n\n for ent_id in range(len(total_entity)):\n entity_toks = self.tokenizer.encode(\" {}\".format(total_entity[ent_id]), add_special_tokens=False)\n ent_change[total_entity[ent_id]] = [entity_toks, ent_id]\n \n # relation change only includes the relation tokens and ids\n rel_change = {}\n for rel_id in range(len(text_relation)):\n rel_change[text_relation[rel_id]] = self.tokenizer.encode(' {}'.format(text_relation[rel_id]),\n add_special_tokens=False)\n\n return ent_change, rel_change\n\n def truncate_pair_ar(self, a, add_bos_id, graph_ids, text_ids, node_ids, edge_ids):\n # add_bos_id + graph_ids + a + text_ids + b + eos_token_id\n length_a_b = self.args.max_input_length - len(add_bos_id) - len(graph_ids) - len(text_ids) - 1\n if len(a) > length_a_b:\n a = a[:length_a_b]\n node_ids = node_ids[:length_a_b]\n edge_ids = edge_ids[:length_a_b]\n input_ids = add_bos_id + graph_ids + a + text_ids + [self.tokenizer.eos_token_id]\n input_node_ids = [-1] * (len(add_bos_id) + len(graph_ids)) + node_ids + [-1] * (len(text_ids) + 1)\n input_edge_ids = [-1] * (len(add_bos_id) + len(graph_ids)) + edge_ids + [-1] * (len(text_ids) + 1)\n attn_mask = [1] * len(input_ids) + [0] * (self.args.max_input_length - len(input_ids))\n input_ids += [self.tokenizer.pad_token_id] * (self.args.max_input_length - len(input_ids))\n input_node_ids += [-1] * (self.args.max_input_length - len(input_node_ids))\n input_edge_ids += [-1] * (self.args.max_input_length - len(input_edge_ids))\n assert len(input_ids) == len(attn_mask) == self.args.max_input_length == len(input_node_ids) == len(\n input_edge_ids)\n return input_ids, attn_mask, input_node_ids, input_edge_ids\n\n \n def ar_prep_data(self, questions, add_bos_id, graph_ids, text_ids, node_ids, edge_ids):\n input_ids, input_attn_mask, input_node_ids, input_edge_ids = self.truncate_pair_ar(questions, add_bos_id,\n graph_ids, text_ids,\n node_ids, edge_ids)\n\n return input_ids, input_attn_mask, input_node_ids, input_edge_ids\n\n\n\n def __getitem__(self, idx):\n kg = self.data[idx]\n # print(\"KG: \", kg)\n kg_list = []\n triple_list = kg.split('<S>')\n triple_list = [triple_list[0]] + ['<S>'+triple for triple in triple_list[1:]]\n triple_list = list(filter(None,triple_list))\n for triple in triple_list:\n head = re.search('<S>(.*)<P>', triple).group(1).strip()\n rel = re.search('<P>(.*)<O>', triple).group(1).strip()\n tail = re.search('<O>(.*)', triple).group(1).strip()\n kg_list.append([head,rel,tail])\n \n strings_label = []\n node_ids = []\n edge_ids = []\n strings_label_tokens = ''\n\n # print(\"kg_list: \", kg_list)\n text_entity, text_relation = self.get_all_entities_per_sample(kg_list)\n entity_change, relation_change = self.get_change_per_sample(text_entity, text_relation)\n adj_matrix = [[-1] * (self.args.max_node_length + 1) for _ in range(self.args.max_node_length + 1)]\n\n cnt_edge = 0\n\n for i, triple in enumerate(kg_list):\n string_label, string_label_tokens, nodes, edges, cnt_edge, adj_matrix = self.graph_linearize(\n triple,\n entity_change,\n self.head_ids,\n self.rel_ids, self.tail_ids,\n relation_change, cnt_edge, adj_matrix)\n \n strings_label += string_label\n strings_label_tokens += string_label_tokens\n node_ids += nodes\n edge_ids += edges\n if self.topology['relation-relation']:\n adj_matrix = self.relation_to_relation_fill(entity_change, relation_change, adj_matrix)\n \n words_label_ids, words_label_tokens, words_input_ids, words_input_tokens = [], '', [], ''\n# current_text = entry[1]\n \n# for word in current_text.split():\n# word_label_ids = self.tokenizer.encode(\" {}\".format(word), add_special_tokens=False)\n# word_label_tokens = copy.deepcopy(word)\n\n# words_label_ids += word_label_ids\n# words_label_tokens += ' ' + word_label_tokens\n # print(\"strings_label: \", strings_label)\n # print(\"node_ids: \", node_ids)\n # print(\"edge_ids: \", edge_ids)\n # print(\"self.add_bos_id: \", self.add_bos_id)\n # print(\"self.graph_ids: \", self.graph_ids)\n input_ids_ar, attn_mask_ar, input_node_ids_ar, input_edge_ids_ar = \\\n self.ar_prep_data(strings_label, self.add_bos_id, self.graph_ids,\n self.text_ids, node_ids, edge_ids)\n node_length_ar = max(input_node_ids_ar) + 1\n edge_length_ar = max(input_edge_ids_ar) + 1\n \n\n def masked_fill(src, masked_value, fill_value):\n return [src[src_id] if src[src_id] != masked_value and src[src_id] < fill_value else fill_value for src_id\n in range(len(src))]\n\n input_node_ids_ar, input_edge_ids_ar = masked_fill(input_node_ids_ar, -1, self.args.max_node_length), \\\n masked_fill(input_edge_ids_ar, -1, self.args.max_edge_length)\n\n def masked_fill_matrix(adj_matrix_input, masked_value, fill_value):\n adj_matrix_tmp = copy.deepcopy(adj_matrix_input)\n for a_id in range(len(adj_matrix_tmp)):\n for b_id in range(len(adj_matrix_tmp)):\n if adj_matrix_tmp[a_id][b_id] == masked_value or adj_matrix_tmp[a_id][b_id] > fill_value:\n adj_matrix_tmp[a_id][b_id] = fill_value\n return adj_matrix_tmp\n\n adj_matrix_ar = masked_fill_matrix(adj_matrix, -1, self.args.max_edge_length)\n\n assert len(input_ids_ar) == len(attn_mask_ar) == self.args.max_input_length == len(input_node_ids_ar) == len(\n input_edge_ids_ar)\n\n input_ids_ar = torch.LongTensor(input_ids_ar)\n attn_mask_ar = torch.LongTensor(attn_mask_ar)\n \n input_node_ids_ar = torch.LongTensor(input_node_ids_ar)\n input_edge_ids_ar = torch.LongTensor(input_edge_ids_ar)\n node_length_ar = torch.LongTensor([node_length_ar])\n edge_length_ar = torch.LongTensor([edge_length_ar])\n adj_matrix_ar = torch.LongTensor(adj_matrix_ar)\n \n return input_ids_ar, attn_mask_ar, input_node_ids_ar, node_length_ar, adj_matrix_ar" }, { "identifier": "WebNLGDataset", "path": "GAP/data_relations_as_nodes.py", "snippet": "class WebNLGDataset(Dataset):\n def __init__(self, logger, args, data_path, tokenizer, mode):\n self.data_path = data_path\n self.tokenizer = tokenizer\n self.topology = {\"entity-entity\": args.entity_entity, \n \"entity-relation\": args.entity_relation,\n \"relation-entity\": args.relation_entity,\n \"relation-relation\": args.relation_relation\n } \n \n with open(self.data_path + '.json', 'r') as f:\n self.data = json.load(f)\n\n print(\"Total samples = {}\".format(len(self.data)))\n\n assert type(self.data) == list\n assert all([\"id\" in d for d in self.data]), self.data[0].keys()\n if type(self.data[0][\"id\"]) == int:\n for i in range(len(self.data)):\n self.data[i][\"id\"] = str(self.data[i][\"id\"])\n\n self.args = args\n self.data_type = mode\n self.metric = \"BLEU\"\n\n self.head_ids, self.rel_ids, self.tail_ids = self.tokenizer.encode(' [head]', add_special_tokens=False), \\\n self.tokenizer.encode(' [relation]', add_special_tokens=False), \\\n self.tokenizer.encode(' [tail]', add_special_tokens=False)\n\n self.graph_ids, self.text_ids = self.tokenizer.encode(' [graph]', add_special_tokens=False), \\\n self.tokenizer.encode(' [text]', add_special_tokens=False)\n\n if self.args.model_name == \"bart\":\n self.mask_token = self.tokenizer.mask_token\n self.mask_token_id = self.tokenizer.mask_token_id\n else:\n self.mask_token = self.tokenizer.additional_special_tokens[0]\n self.mask_token_id = self.tokenizer.convert_tokens_to_ids(self.tokenizer.additional_special_tokens[0])\n\n if self.args.model_name == \"bart\":\n if self.args.append_another_bos:\n self.add_bos_id = [self.tokenizer.bos_token_id] * 2\n else:\n self.add_bos_id = [self.tokenizer.bos_token_id]\n else:\n self.add_bos_id = []\n\n def __len__(self):\n return len(self.data)\n\n def linearize_v2(self, entity, entity_change, head_ids, rel_ids, tail_ids,\n relation_change, cnt_edge, adj_matrix):\n # string_label: encoder ids\n # string_label_tokens: encoder tokens\n\n if len(entity[0]) == 0:\n return [], '', [], [], cnt_edge, adj_matrix\n nodes, edges = [], []\n string_label = copy.deepcopy(head_ids)\n string_label_tokens = ' [head]'\n nodes.extend([-1] * len(string_label))\n edges.extend([-1] * len(string_label))\n\n\n string_label += entity_change[entity[0]][0]\n string_label_tokens += ' {}'.format(entity[0])\n nodes.extend([entity_change[entity[0]][1]] * len(entity_change[entity[0]][0]))\n edges.extend([-1] * len(entity_change[entity[0]][0]))\n\n\n for rel in entity[2]:\n if len(rel[0]) != 0 and len(rel[1]) != 0:\n rel_label = relation_change[rel[0]]\n rel_ent_label = entity_change[rel[0]][1]\n rel_label_token = copy.deepcopy(rel[0])\n words_label = rel_ids + rel_label + tail_ids + entity_change[rel[1]][0]\n words_label_tokens = ' [relation] {} [tail] {}'.format(rel_label_token, rel[1])\n nodes.extend(\n ([-1] * len(rel_ids)) + ([entity_change[rel[0]][1]] * len(rel_label)) + ([-1] * len(tail_ids)) + ([entity_change[rel[1]][1]] * len(\n entity_change[rel[1]][0])))\n\n \n edges.extend([-1] * len(rel_ids) + [cnt_edge] * len(rel_label) + [-1] * (\n len(tail_ids) + len(entity_change[rel[1]][0])))\n if entity_change[entity[0]][1] < len(adj_matrix) and entity_change[rel[1]][1] < len(adj_matrix):\n if self.topology['entity-entity']:\n adj_matrix[entity_change[entity[0]][1]][entity_change[rel[1]][1]] = 1\n adj_matrix[entity_change[rel[1]][1]][entity_change[entity[0]][1]] = 1\n\n if self.topology['entity-relation']:\n adj_matrix[entity_change[entity[0]][1]][entity_change[rel[0]][1]] = 2\n adj_matrix[entity_change[rel[1]][1]][entity_change[rel[0]][1]] = 2\n \n if self.topology['relation-entity']:\n adj_matrix[entity_change[rel[0]][1]][entity_change[entity[0]][1]] = 3\n adj_matrix[entity_change[rel[0]][1]][entity_change[rel[1]][1]] = 3\n \n if not self.topology['relation-entity'] and not self.topology['relation-relation']:\n adj_matrix[entity_change[rel[0]][1]][entity_change[rel[0]][1]] = 10\n \n if not self.topology['entity-relation'] and not self.topology['entity-entity']:\n adj_matrix[entity_change[entity[0]][1]][entity_change[entity[0]][1]] = 10\n adj_matrix[entity_change[rel[1]][1]][entity_change[rel[1]][1]] = 10\n\n cnt_edge += 1\n string_label += words_label\n string_label_tokens += words_label_tokens\n\n assert len(string_label) == len(nodes) == len(edges)\n\n return string_label, string_label_tokens, nodes, edges, cnt_edge, adj_matrix\n\n \n def relation_to_relation_fill(self, node_dict, rel_dict, adj_matrix):\n adj_matrix_temp = np.array(adj_matrix)\n rel_idx_list = []\n for rel in rel_dict.keys():\n rel_idx = node_dict[rel][1]\n rel_idx_list.append(rel_idx)\n adj_matrix_np = np.array(adj_matrix)\n adj_matrix_np_bool = (adj_matrix_np==-1)\n #reassign -1s to 0s\n adj_matrix_np[adj_matrix_np_bool] = 0\n #get squared matrix for r-r\n adj_matrix_sq = adj_matrix_np@adj_matrix_np\n \n #old adj_matrix + squared matrix only r-r\n rel_idx_list = np.array(rel_idx_list, dtype=np.intp)\n adj_matrix_temp[rel_idx_list[:,np.newaxis], rel_idx_list] = (adj_matrix_sq[rel_idx_list][:,rel_idx_list] > 0)*4\n adj_matrix_new = adj_matrix_temp.tolist()\n \n return adj_matrix_new\n \n \n def get_all_entities_per_sample(self, mark_entity_number, mark_entity, entry):\n text_entity = set()\n text_relation = set()\n for entity_id in mark_entity_number:\n entity = entry['kbs'][entity_id]\n if len(entity[0]) == 0:\n continue\n for rel in entity[2]:\n if len(rel[0]) != 0 and len(rel[1]) != 0:\n text_relation.add(rel[0])\n text_entity.add(rel[1])\n\n text_entity_list = list(text_entity)+list(text_relation)\n text_relation_list = list(text_relation)\n for entity_ele in mark_entity:\n if entity_ele in text_entity_list:\n text_entity_list.remove(entity_ele)\n \n return text_entity_list, text_relation_list\n\n def get_change_per_sample(self, mark_entity, text_entity, text_relation):\n # during fine-tuning, we don't mask entities or relations\n ent_change = {}\n total_entity = mark_entity + text_entity\n\n for ent_id in range(len(total_entity)):\n entity_toks = self.tokenizer.encode(\" {}\".format(total_entity[ent_id]), add_special_tokens=False)\n ent_change[total_entity[ent_id]] = [entity_toks, ent_id]\n # relation change only includes the relation tokens and ids\n rel_change = {}\n for rel_id in range(len(text_relation)):\n rel_change[text_relation[rel_id]] = self.tokenizer.encode(' {}'.format(text_relation[rel_id]),\n add_special_tokens=False)\n return ent_change, rel_change\n\n def truncate_pair_ar(self, a, add_bos_id, graph_ids, text_ids, node_ids, edge_ids):\n # add_bos_id + graph_ids + a + text_ids + b + eos_token_id\n length_a_b = self.args.max_input_length - len(add_bos_id) - len(graph_ids) - len(text_ids) - 1\n if len(a) > length_a_b:\n a = a[:length_a_b]\n node_ids = node_ids[:length_a_b]\n edge_ids = edge_ids[:length_a_b]\n input_ids = add_bos_id + graph_ids + a + text_ids + [self.tokenizer.eos_token_id]\n input_node_ids = [-1] * (len(add_bos_id) + len(graph_ids)) + node_ids + [-1] * (len(text_ids) + 1)\n input_edge_ids = [-1] * (len(add_bos_id) + len(graph_ids)) + edge_ids + [-1] * (len(text_ids) + 1)\n attn_mask = [1] * len(input_ids) + [0] * (self.args.max_input_length - len(input_ids))\n input_ids += [self.tokenizer.pad_token_id] * (self.args.max_input_length - len(input_ids))\n input_node_ids += [-1] * (self.args.max_input_length - len(input_node_ids))\n input_edge_ids += [-1] * (self.args.max_input_length - len(input_edge_ids))\n assert len(input_ids) == len(attn_mask) == self.args.max_input_length == len(input_node_ids) == len(\n input_edge_ids)\n return input_ids, attn_mask, input_node_ids, input_edge_ids\n\n def ar_prep_data(self, questions, add_bos_id, graph_ids, text_ids, node_ids, edge_ids):\n input_ids, input_attn_mask, input_node_ids, input_edge_ids = self.truncate_pair_ar(questions, add_bos_id,\n graph_ids, text_ids,\n node_ids, edge_ids)\n\n return input_ids, input_attn_mask, input_node_ids, input_edge_ids\n \n\n\n def __getitem__(self, idx):\n\n entry = self.data[idx]\n\n entities = []\n for _ in entry['kbs']:\n entities.append(_)\n\n strings_label = []\n node_ids = []\n edge_ids = []\n strings_label_tokens = ''\n\n # mark_entity: entities with KB numbers which are important for this task\n # text_entity: entities without KB numbers but only with text, which are less important\n mark_entity = [entry['kbs'][ele_entity][0] for ele_entity in entities]\n mark_entity_number = entities\n text_entity, text_relation = self.get_all_entities_per_sample(mark_entity_number, mark_entity, entry)\n entity_change, relation_change = self.get_change_per_sample(mark_entity, text_entity, text_relation)\n total_entity = mark_entity + text_entity\n adj_matrix = [[-1] * (self.args.max_node_length + 1) for _ in range(self.args.max_node_length + 1)]\n\n cnt_edge = 0\n\n if 'title' in entry:\n entity = self.knowledge[entry['title_kb_id']]\n string_label, string_label_tokens, nodes, edges, cnt_edge, adj_matrix = self.linearize_v2(\n entity,\n entity_change,\n self.head_ids,\n self.rel_ids, self.tail_ids,\n relation_change, cnt_edge, adj_matrix)\n\n strings_label += string_label\n strings_label_tokens += string_label_tokens\n\n for i, entity_id in enumerate(entities):\n entity = entry['kbs'][entity_id]\n string_label, string_label_tokens, nodes, edges, cnt_edge, adj_matrix = self.linearize_v2(\n entity,\n entity_change,\n self.head_ids,\n self.rel_ids, self.tail_ids,\n relation_change, cnt_edge, adj_matrix)\n \n strings_label += string_label\n strings_label_tokens += string_label_tokens\n node_ids += nodes\n edge_ids += edges\n \n if self.topology['relation-relation']:\n adj_matrix = self.relation_to_relation_fill(entity_change, relation_change, adj_matrix)\n \n\n words_label_ids, words_label_tokens, words_input_ids, words_input_tokens = [], '', [], ''\n\n\n input_ids_ar, attn_mask_ar, input_node_ids_ar, input_edge_ids_ar = \\\n self.ar_prep_data(strings_label, self.add_bos_id, self.graph_ids,\n self.text_ids, node_ids, edge_ids)\n\n node_length_ar = max(input_node_ids_ar) + 1\n edge_length_ar = max(input_edge_ids_ar) + 1\n \n\n def masked_fill(src, masked_value, fill_value):\n return [src[src_id] if src[src_id] != masked_value and src[src_id] < fill_value else fill_value for src_id\n in range(len(src))]\n\n input_node_ids_ar, input_edge_ids_ar = masked_fill(input_node_ids_ar, -1, self.args.max_node_length), \\\n masked_fill(input_edge_ids_ar, -1, self.args.max_edge_length)\n\n def masked_fill_matrix(adj_matrix_input, masked_value, fill_value):\n adj_matrix_tmp = copy.deepcopy(adj_matrix_input)\n for a_id in range(len(adj_matrix_tmp)):\n for b_id in range(len(adj_matrix_tmp)):\n if adj_matrix_tmp[a_id][b_id] == masked_value or adj_matrix_tmp[a_id][b_id] > fill_value:\n adj_matrix_tmp[a_id][b_id] = fill_value\n return adj_matrix_tmp\n\n adj_matrix_ar = masked_fill_matrix(adj_matrix, -1, self.args.max_edge_length)\n\n assert len(input_ids_ar) == len(attn_mask_ar) == self.args.max_input_length == len(input_node_ids_ar) == len(\n input_edge_ids_ar)\n\n input_ids_ar = torch.LongTensor(input_ids_ar)\n attn_mask_ar = torch.LongTensor(attn_mask_ar)\n \n input_node_ids_ar = torch.LongTensor(input_node_ids_ar)\n input_edge_ids_ar = torch.LongTensor(input_edge_ids_ar)\n node_length_ar = torch.LongTensor([node_length_ar])\n edge_length_ar = torch.LongTensor([edge_length_ar])\n adj_matrix_ar = torch.LongTensor(adj_matrix_ar)\n \n return input_ids_ar, attn_mask_ar, input_node_ids_ar, node_length_ar, adj_matrix_ar" }, { "identifier": "evaluate_bleu", "path": "GAP/data_relations_as_nodes.py", "snippet": "def evaluate_bleu(data_ref, data_sys):\n coco_eval = run_coco_eval(data_ref, data_sys)\n scores = {metric: score for metric, score in list(coco_eval.eval.items())}\n return scores[\"Bleu_4\"]" }, { "identifier": "get_t_emb_dim", "path": "GAP/data_relations_as_nodes.py", "snippet": "def get_t_emb_dim(args):\n t_emb_dim = int(args.entity_entity)+int(args.entity_relation)\\\n +int(args.relation_entity)+int(args.relation_relation)+1\n return t_emb_dim" }, { "identifier": "GAPBartForConditionalGeneration", "path": "GAP/modeling_gap_type.py", "snippet": "class GAPBartForConditionalGeneration(BartForConditionalGeneration):\n def __init__(self, config, **kwargs):\n super().__init__(config)\n base_model = GAPBartModel(config,**kwargs)\n self.model = base_model\n self.register_buffer(\"final_logits_bias\", torch.zeros((1, self.model.shared.num_embeddings)))\n \n def forward(self, input_ids, attention_mask=None, encoder_outputs=None,\n decoder_input_ids=None, decoder_attention_mask=None, input_node_ids=None,\n node_length=None, adj_matrix=None, decoder_whole_ids=None, decoder_cached_states=None,\n use_cache=False, is_training=False):\n\n if is_training:\n _decoder_input_ids = shift_tokens_right(decoder_input_ids, self.config.pad_token_id)\n else:\n _decoder_input_ids = decoder_input_ids\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n encoder_outputs=encoder_outputs,\n decoder_input_ids=_decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n input_node_ids=input_node_ids,\n node_length=node_length,\n adj_matrix=adj_matrix,\n decoder_cached_states=decoder_cached_states,\n use_cache=use_cache,\n )\n lm_logits = F.linear(outputs[0], self.model.shared.weight, bias=self.final_logits_bias)\n if is_training:\n loss_fct = nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id)\n loss = loss_fct(lm_logits.view(-1, self.config.vocab_size),\n decoder_input_ids.view(-1))\n return loss\n return (lm_logits, ) + outputs[1:]\n\n @torch.no_grad()\n def generate(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n max_length: Optional[int] = None,\n min_length: Optional[int] = None,\n do_sample: Optional[bool] = None,\n early_stopping: Optional[bool] = None,\n num_beams: Optional[int] = None,\n temperature: Optional[float] = None,\n top_k: Optional[int] = None,\n top_p: Optional[float] = None,\n repetition_penalty: Optional[float] = None,\n bad_words_ids: Optional[Iterable[int]] = None,\n bos_token_id: Optional[int] = None,\n pad_token_id: Optional[int] = None,\n eos_token_id: Optional[int] = None,\n length_penalty: Optional[float] = None,\n no_repeat_ngram_size: Optional[int] = None,\n num_return_sequences: Optional[int] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n input_node_ids=None,\n node_length=None,\n adj_matrix=None,\n decoder_start_token_id: Optional[int] = None,\n use_cache: Optional[bool] = None,\n **model_specific_kwargs\n ) -> torch.LongTensor:\n r\"\"\" Generates sequences for models with a LM head. The method currently supports greedy decoding, beam-search decoding, sampling with temperature, sampling with top-k or nucleus sampling.\n\n Adapted in part from `Facebook's XLM beam search code`_.\n\n .. _`Facebook's XLM beam search code`:\n https://github.com/facebookresearch/XLM/blob/9e6f6814d17be4fe5b15f2e6c43eb2b2d76daeb4/src/model/transformer.py#L529\n\n\n Parameters:\n\n input_ids: (`optional`) `torch.LongTensor` of shape `(batch_size, sequence_length)`\n The sequence used as a prompt for the generation. If `None` the method initializes\n it as an empty `torch.LongTensor` of shape `(1,)`.\n\n max_length: (`optional`) int\n The max length of the sequence to be generated. Between `min_length` and infinity. Default to 20.\n\n min_length: (`optional`) int\n The min length of the sequence to be generated. Between 0 and infinity. Default to 0.\n\n do_sample: (`optional`) bool\n If set to `False` greedy decoding is used. Otherwise sampling is used. Defaults to `False` as defined in `configuration_utils.PretrainedConfig`.\n\n early_stopping: (`optional`) bool\n if set to `True` beam search is stopped when at least `num_beams` sentences finished per batch. Defaults to `False` as defined in `configuration_utils.PretrainedConfig`.\n\n num_beams: (`optional`) int\n Number of beams for beam search. Must be between 1 and infinity. 1 means no beam search. Default to 1.\n\n temperature: (`optional`) float\n The value used to module the next token probabilities. Must be strictly positive. Default to 1.0.\n\n top_k: (`optional`) int\n The number of highest probability vocabulary tokens to keep for top-k-filtering. Between 1 and infinity. Default to 50.\n\n top_p: (`optional`) float\n The cumulative probability of parameter highest probability vocabulary tokens to keep for nucleus sampling. Must be between 0 and 1. Default to 1.\n\n repetition_penalty: (`optional`) float\n The parameter for repetition penalty. Between 1.0 and infinity. 1.0 means no penalty. Default to 1.0.\n\n pad_token_id: (`optional`) int\n Padding token. Default to specicic model pad_token_id or None if it does not exist.\n\n bos_token_id: (`optional`) int\n BOS token. Defaults to `bos_token_id` as defined in the models config.\n\n eos_token_id: (`optional`) int\n EOS token. Defaults to `eos_token_id` as defined in the models config.\n\n length_penalty: (`optional`) float\n Exponential penalty to the length. Default to 1.\n\n no_repeat_ngram_size: (`optional`) int\n If set to int > 0, all ngrams of size `no_repeat_ngram_size` can only occur once.\n bad_words_ids: (`optional`) list of lists of int\n `bad_words_ids` contains tokens that are not allowed to be generated. In order to get the tokens of the words that should not appear in the generated text, use `tokenizer.encode(bad_word, add_prefix_space=True)`.\n\n num_return_sequences: (`optional`) int\n The number of independently computed returned sequences for each element in the batch. Default to 1.\n\n attention_mask (`optional`) obj: `torch.LongTensor` of same shape as `input_ids`\n Mask to avoid performing attention on padding token indices.\n Mask values selected in ``[0, 1]``:\n ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.\n Defaults to `None`.\n\n `What are attention masks? <../glossary.html#attention-mask>`__\n\n decoder_start_token_id=None: (`optional`) int\n Start token id for the decoder. Defaults to ``decoder_start_token_id`` as defined the model's config or to the ``bos_token_id``\n if no ``decoder_start_token_id`` is found in the config.\n This is only relevant for encoder-decoder models.\n\n use_cache: (`optional`) bool\n If `use_cache` is True, past key values are used to speed up decoding if applicable to model. Defaults to `True`.\n\n model_specific_kwargs: (`optional`) dict\n Additional model specific kwargs will be forwarded to the `forward` function of the model.\n\n Return:\n\n output: `torch.LongTensor` of shape `(batch_size * num_return_sequences, sequence_length)`\n sequence_length is either equal to max_length or shorter if all batches finished early due to the `eos_token_id`\n\n Examples::\n\n from transformers import AutoTokenizer, AutoModelForCausalLM\n\n tokenizer = AutoTokenizer. ('distilgpt2') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('distilgpt2') # Download model and configuration from S3 and cache.\n outputs = model.generate(max_length=40) # do greedy decoding\n print('Generated: {}'.format(tokenizer.decode(outputs[0], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('openai-gpt') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('openai-gpt') # Download model and configuration from S3 and cache.\n input_context = 'The dog'\n input_ids = tokenizer.encode(input_context, return_tensors='pt') # encode input context\n outputs = model.generate(input_ids=input_ids, num_beams=5, num_return_sequences=3, temperature=1.5) # generate 3 independent sequences using beam search decoding (5 beams) with sampling from initial context 'The dog'\n for i in range(3): # 3 output sequences were generated\n print('Generated {}: {}'.format(i, tokenizer.decode(outputs[i], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('distilgpt2') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('distilgpt2') # Download model and configuration from S3 and cache.\n input_context = 'The dog'\n input_ids = tokenizer.encode(input_context, return_tensors='pt') # encode input context\n outputs = model.generate(input_ids=input_ids, max_length=40, temperature=0.7, num_return_sequences=3, do_sample=True) # 3 generate sequences using by sampling\n for i in range(3): # 3 output sequences were generated\n print('Generated {}: {}'.format(i, tokenizer.decode(outputs[i], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('ctrl') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('ctrl') # Download model and configuration from S3 and cache.\n input_context = 'Legal My neighbor is' # \"Legal\" is one of the control codes for ctrl\n input_ids = tokenizer.encode(input_context, return_tensors='pt') # encode input context\n outputs = model.generate(input_ids=input_ids, max_length=50, temperature=0.7, repetition_penalty=1.2) # generate sequences\n print('Generated: {}'.format(tokenizer.decode(outputs[0], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('gpt2') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('gpt2') # Download model and configuration from S3 and cache.\n input_context = 'My cute dog' # \"Legal\" is one of the control codes for ctrl\n bad_words_ids = [tokenizer.encode(bad_word, add_prefix_space=True) for bad_word in ['idiot', 'stupid', 'shut up']]\n input_ids = tokenizer.encode(input_context, return_tensors='pt') # encode input context\n outputs = model.generate(input_ids=input_ids, max_length=100, do_sample=True, bad_words_ids=bad_words_ids) # generate sequences without allowing bad_words to be generated\n \"\"\"\n\n # We cannot generate if the model does not have a LM head\n if self.get_output_embeddings() is None:\n raise AttributeError(\n \"You tried to generate sequences with a model that does not have a LM Head.\"\n \"Please use another model class (e.g. `OpenAIGPTLMHeadModel`, `XLNetLMHeadModel`, `GPT2LMHeadModel`, `CTRLLMHeadModel`, `T5WithLMHeadModel`, `TransfoXLLMHeadModel`, `XLMWithLMHeadModel`, `BartForConditionalGeneration` )\"\n )\n\n max_length = max_length if max_length is not None else self.config.max_length\n min_length = min_length if min_length is not None else self.config.min_length\n do_sample = do_sample if do_sample is not None else self.config.do_sample\n early_stopping = early_stopping if early_stopping is not None else self.config.early_stopping\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n num_beams = num_beams if num_beams is not None else self.config.num_beams\n temperature = temperature if temperature is not None else self.config.temperature\n top_k = top_k if top_k is not None else self.config.top_k\n top_p = top_p if top_p is not None else self.config.top_p\n repetition_penalty = repetition_penalty if repetition_penalty is not None else self.config.repetition_penalty\n bos_token_id = bos_token_id if bos_token_id is not None else self.config.bos_token_id\n pad_token_id = pad_token_id if pad_token_id is not None else self.config.pad_token_id\n eos_token_id = eos_token_id if eos_token_id is not None else self.config.eos_token_id\n length_penalty = length_penalty if length_penalty is not None else self.config.length_penalty\n no_repeat_ngram_size = (\n no_repeat_ngram_size if no_repeat_ngram_size is not None else self.config.no_repeat_ngram_size\n )\n bad_words_ids = bad_words_ids if bad_words_ids is not None else self.config.bad_words_ids\n num_return_sequences = (\n num_return_sequences if num_return_sequences is not None else self.config.num_return_sequences\n )\n decoder_start_token_id = (\n decoder_start_token_id if decoder_start_token_id is not None else self.config.decoder_start_token_id\n )\n\n if input_ids is not None:\n batch_size = input_ids.shape[0] # overriden by the input batch_size\n else:\n batch_size = 1\n\n assert isinstance(max_length, int) and max_length > 0, \"`max_length` should be a strictly positive integer.\"\n assert isinstance(min_length, int) and min_length >= 0, \"`min_length` should be a positive integer.\"\n assert isinstance(do_sample, bool), \"`do_sample` should be a boolean.\"\n assert isinstance(early_stopping, bool), \"`early_stopping` should be a boolean.\"\n assert isinstance(use_cache, bool), \"`use_cache` should be a boolean.\"\n assert isinstance(num_beams, int) and num_beams > 0, \"`num_beams` should be a strictly positive integer.\"\n assert temperature > 0, \"`temperature` should be strictly positive.\"\n assert isinstance(top_k, int) and top_k >= 0, \"`top_k` should be a positive integer.\"\n assert 0 <= top_p <= 1, \"`top_p` should be between 0 and 1.\"\n assert repetition_penalty >= 1.0, \"`repetition_penalty` should be >= 1.\"\n assert input_ids is not None or (\n isinstance(bos_token_id, int) and bos_token_id >= 0\n ), \"If input_ids is not defined, `bos_token_id` should be a positive integer.\"\n assert pad_token_id is None or (\n isinstance(pad_token_id, int) and (pad_token_id >= 0)\n ), \"`pad_token_id` should be a positive integer.\"\n assert (eos_token_id is None) or (\n isinstance(eos_token_id, int) and (eos_token_id >= 0)\n ), \"`eos_token_id` should be a positive integer.\"\n assert length_penalty > 0, \"`length_penalty` should be strictly positive.\"\n assert (\n isinstance(no_repeat_ngram_size, int) and no_repeat_ngram_size >= 0\n ), \"`no_repeat_ngram_size` should be a positive integer.\"\n assert (\n isinstance(num_return_sequences, int) and num_return_sequences > 0\n ), \"`num_return_sequences` should be a strictly positive integer.\"\n assert (\n bad_words_ids is None or isinstance(bad_words_ids, list) and isinstance(bad_words_ids[0], list)\n ), \"`bad_words_ids` is either `None` or a list of lists of tokens that should not be generated\"\n\n if input_ids is None:\n assert isinstance(bos_token_id, int) and bos_token_id >= 0, (\n \"you should either supply a context to complete as `input_ids` input \"\n \"or a `bos_token_id` (integer >= 0) as a first token to start the generation.\"\n )\n input_ids = torch.full(\n (batch_size, 1), bos_token_id, dtype=torch.long, device=next(self.parameters()).device,\n )\n else:\n assert input_ids.dim() == 2, \"Input prompt should be of shape (batch_size, sequence length).\"\n\n # not allow to duplicate outputs when greedy decoding\n if do_sample is False:\n if num_beams == 1:\n # no_beam_search greedy generation conditions\n assert (\n num_return_sequences == 1\n ), \"Greedy decoding will always produce the same output for num_beams == 1 and num_return_sequences > 1. Please set num_return_sequences = 1\"\n\n else:\n # beam_search greedy generation conditions\n assert (\n num_beams >= num_return_sequences\n ), \"Greedy beam search decoding cannot return more sequences than it has beams. Please set num_beams >= num_return_sequences\"\n\n # create attention mask if necessary\n # TODO (PVP): this should later be handled by the forward fn() in each model in the future see PR 3140\n if (attention_mask is None) and (pad_token_id is not None) and (pad_token_id in input_ids):\n attention_mask = input_ids.ne(pad_token_id).long()\n elif attention_mask is None:\n attention_mask = input_ids.new_ones(input_ids.shape)\n\n # set pad_token_id to eos_token_id if not set. Important that this is done after\n # attention_mask is created\n if pad_token_id is None and eos_token_id is not None:\n logger.warning(\n \"Setting `pad_token_id` to {} (first `eos_token_id`) to generate sequence\".format(eos_token_id)\n )\n pad_token_id = eos_token_id\n\n # current position and vocab size\n if hasattr(self.config, \"vocab_size\"):\n vocab_size = self.config.vocab_size\n elif (\n self.config.is_encoder_decoder\n and hasattr(self.config, \"decoder\")\n and hasattr(self.config.decoder, \"vocab_size\")\n ):\n vocab_size = self.config.decoder.vocab_size\n\n # set effective batch size and effective batch multiplier according to do_sample\n if do_sample:\n effective_batch_size = batch_size * num_return_sequences\n effective_batch_mult = num_return_sequences\n else:\n effective_batch_size = batch_size\n effective_batch_mult = 1\n\n if self.config.is_encoder_decoder:\n if decoder_start_token_id is None:\n decoder_start_token_id = bos_token_id\n\n assert (\n decoder_start_token_id is not None\n ), \"decoder_start_token_id or bos_token_id has to be defined for encoder-decoder generation\"\n assert hasattr(self, \"get_encoder\"), \"{} should have a 'get_encoder' function defined\".format(self)\n assert callable(self.get_encoder), \"{} should be a method\".format(self.get_encoder)\n\n # get encoder and store encoder outputs\n encoder = self.get_encoder()\n\n # add structural information when encoding\n encoder_outputs: tuple = encoder(input_ids, attention_mask=attention_mask, input_node_ids=input_node_ids,\n node_length=node_length, adj_matrix=adj_matrix)\n\n # Expand input ids if num_beams > 1 or num_return_sequences > 1\n if num_return_sequences > 1 or num_beams > 1:\n input_ids_len = input_ids.shape[-1]\n input_ids = input_ids.unsqueeze(1).expand(batch_size, effective_batch_mult * num_beams, input_ids_len)\n attention_mask = attention_mask.unsqueeze(1).expand(\n batch_size, effective_batch_mult * num_beams, input_ids_len\n )\n\n input_ids = input_ids.contiguous().view(\n effective_batch_size * num_beams, input_ids_len\n ) # shape: (batch_size * num_return_sequences * num_beams, cur_len)\n attention_mask = attention_mask.contiguous().view(\n effective_batch_size * num_beams, input_ids_len\n ) # shape: (batch_size * num_return_sequences * num_beams, cur_len)\n\n if self.config.is_encoder_decoder:\n # create empty decoder_input_ids\n input_ids = torch.full(\n (effective_batch_size * num_beams, 1),\n decoder_start_token_id,\n dtype=torch.long,\n device=next(self.parameters()).device,\n )\n cur_len = 1\n\n assert (\n batch_size == encoder_outputs[0].shape[0]\n ), f\"expected encoder_outputs[0] to have 1st dimension bs={batch_size}, got {encoder_outputs[0].shape[0]} \"\n\n # expand batch_idx to assign correct encoder output for expanded input_ids (due to num_beams > 1 and num_return_sequences > 1)\n expanded_batch_idxs = (\n torch.arange(batch_size)\n .view(-1, 1)\n .repeat(1, num_beams * effective_batch_mult)\n .view(-1)\n .to(input_ids.device)\n )\n # expand encoder_outputs\n encoder_outputs = (encoder_outputs[0].index_select(0, expanded_batch_idxs), *encoder_outputs[1:])\n\n else:\n encoder_outputs = None\n cur_len = input_ids.shape[-1]\n\n if num_beams > 1:\n output = self._generate_beam_search(\n input_ids,\n cur_len=cur_len,\n max_length=max_length,\n min_length=min_length,\n do_sample=do_sample,\n early_stopping=early_stopping,\n temperature=temperature,\n top_k=top_k,\n top_p=top_p,\n repetition_penalty=repetition_penalty,\n no_repeat_ngram_size=no_repeat_ngram_size,\n bad_words_ids=bad_words_ids,\n pad_token_id=pad_token_id,\n eos_token_id=eos_token_id,\n batch_size=effective_batch_size,\n num_return_sequences=num_return_sequences,\n length_penalty=length_penalty,\n num_beams=num_beams,\n vocab_size=vocab_size,\n encoder_outputs=encoder_outputs,\n attention_mask=attention_mask,\n use_cache=use_cache,\n model_specific_kwargs=model_specific_kwargs,\n )\n else:\n output = self._generate_no_beam_search(\n input_ids,\n cur_len=cur_len,\n max_length=max_length,\n min_length=min_length,\n do_sample=do_sample,\n temperature=temperature,\n top_k=top_k,\n top_p=top_p,\n repetition_penalty=repetition_penalty,\n no_repeat_ngram_size=no_repeat_ngram_size,\n bad_words_ids=bad_words_ids,\n pad_token_id=pad_token_id,\n eos_token_id=eos_token_id,\n batch_size=effective_batch_size,\n encoder_outputs=encoder_outputs,\n attention_mask=attention_mask,\n use_cache=use_cache,\n model_specific_kwargs=model_specific_kwargs,\n )\n\n return output" }, { "identifier": "GAPBartForConditionalGeneration", "path": "GAP/modeling_gap.py", "snippet": "class GAPBartForConditionalGeneration(BartForConditionalGeneration):\n def __init__(self, config):\n super().__init__(config)\n base_model = GAPBartModel(config)\n self.model = base_model\n self.register_buffer(\"final_logits_bias\", torch.zeros((1, self.model.shared.num_embeddings)))\n\n def forward(self, input_ids, attention_mask=None, encoder_outputs=None,\n decoder_input_ids=None, decoder_attention_mask=None, input_node_ids=None, \n node_length=None, adj_matrix=None, decoder_whole_ids=None, decoder_cached_states=None,\n use_cache=False, is_training=False):\n\n if is_training:\n _decoder_input_ids = shift_tokens_right(decoder_input_ids, self.config.pad_token_id)\n else:\n _decoder_input_ids = decoder_input_ids\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n encoder_outputs=encoder_outputs,\n decoder_input_ids=_decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n input_node_ids=input_node_ids,\n node_length=node_length,\n adj_matrix=adj_matrix,\n decoder_cached_states=decoder_cached_states,\n use_cache=use_cache,\n )\n lm_logits = F.linear(outputs[0], self.model.shared.weight, bias=self.final_logits_bias)\n if is_training:\n loss_fct = nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id)\n loss = loss_fct(lm_logits.view(-1, self.config.vocab_size),\n decoder_input_ids.view(-1))\n return loss\n return (lm_logits, ) + outputs[1:]\n\n @torch.no_grad()\n def generate(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n max_length: Optional[int] = None,\n min_length: Optional[int] = None,\n do_sample: Optional[bool] = None,\n early_stopping: Optional[bool] = None,\n num_beams: Optional[int] = None,\n temperature: Optional[float] = None,\n top_k: Optional[int] = None,\n top_p: Optional[float] = None,\n repetition_penalty: Optional[float] = None,\n bad_words_ids: Optional[Iterable[int]] = None,\n bos_token_id: Optional[int] = None,\n pad_token_id: Optional[int] = None,\n eos_token_id: Optional[int] = None,\n length_penalty: Optional[float] = None,\n no_repeat_ngram_size: Optional[int] = None,\n num_return_sequences: Optional[int] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n input_node_ids=None,\n node_length=None,\n adj_matrix=None,\n decoder_start_token_id: Optional[int] = None,\n use_cache: Optional[bool] = None,\n **model_specific_kwargs\n ) -> torch.LongTensor:\n r\"\"\" Generates sequences for models with a LM head. The method currently supports greedy decoding, beam-search decoding, sampling with temperature, sampling with top-k or nucleus sampling.\n\n Adapted in part from `Facebook's XLM beam search code`_.\n\n .. _`Facebook's XLM beam search code`:\n https://github.com/facebookresearch/XLM/blob/9e6f6814d17be4fe5b15f2e6c43eb2b2d76daeb4/src/model/transformer.py#L529\n\n\n Parameters:\n\n input_ids: (`optional`) `torch.LongTensor` of shape `(batch_size, sequence_length)`\n The sequence used as a prompt for the generation. If `None` the method initializes\n it as an empty `torch.LongTensor` of shape `(1,)`.\n\n max_length: (`optional`) int\n The max length of the sequence to be generated. Between `min_length` and infinity. Default to 20.\n\n min_length: (`optional`) int\n The min length of the sequence to be generated. Between 0 and infinity. Default to 0.\n\n do_sample: (`optional`) bool\n If set to `False` greedy decoding is used. Otherwise sampling is used. Defaults to `False` as defined in `configuration_utils.PretrainedConfig`.\n\n early_stopping: (`optional`) bool\n if set to `True` beam search is stopped when at least `num_beams` sentences finished per batch. Defaults to `False` as defined in `configuration_utils.PretrainedConfig`.\n\n num_beams: (`optional`) int\n Number of beams for beam search. Must be between 1 and infinity. 1 means no beam search. Default to 1.\n\n temperature: (`optional`) float\n The value used to module the next token probabilities. Must be strictly positive. Default to 1.0.\n\n top_k: (`optional`) int\n The number of highest probability vocabulary tokens to keep for top-k-filtering. Between 1 and infinity. Default to 50.\n\n top_p: (`optional`) float\n The cumulative probability of parameter highest probability vocabulary tokens to keep for nucleus sampling. Must be between 0 and 1. Default to 1.\n\n repetition_penalty: (`optional`) float\n The parameter for repetition penalty. Between 1.0 and infinity. 1.0 means no penalty. Default to 1.0.\n\n pad_token_id: (`optional`) int\n Padding token. Default to specicic model pad_token_id or None if it does not exist.\n\n bos_token_id: (`optional`) int\n BOS token. Defaults to `bos_token_id` as defined in the models config.\n\n eos_token_id: (`optional`) int\n EOS token. Defaults to `eos_token_id` as defined in the models config.\n\n length_penalty: (`optional`) float\n Exponential penalty to the length. Default to 1.\n\n no_repeat_ngram_size: (`optional`) int\n If set to int > 0, all ngrams of size `no_repeat_ngram_size` can only occur once.\n bad_words_ids: (`optional`) list of lists of int\n `bad_words_ids` contains tokens that are not allowed to be generated. In order to get the tokens of the words that should not appear in the generated text, use `tokenizer.encode(bad_word, add_prefix_space=True)`.\n\n num_return_sequences: (`optional`) int\n The number of independently computed returned sequences for each element in the batch. Default to 1.\n\n attention_mask (`optional`) obj: `torch.LongTensor` of same shape as `input_ids`\n Mask to avoid performing attention on padding token indices.\n Mask values selected in ``[0, 1]``:\n ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.\n Defaults to `None`.\n\n `What are attention masks? <../glossary.html#attention-mask>`__\n\n decoder_start_token_id=None: (`optional`) int\n Start token id for the decoder. Defaults to ``decoder_start_token_id`` as defined the model's config or to the ``bos_token_id``\n if no ``decoder_start_token_id`` is found in the config.\n This is only relevant for encoder-decoder models.\n\n use_cache: (`optional`) bool\n If `use_cache` is True, past key values are used to speed up decoding if applicable to model. Defaults to `True`.\n\n model_specific_kwargs: (`optional`) dict\n Additional model specific kwargs will be forwarded to the `forward` function of the model.\n\n Return:\n\n output: `torch.LongTensor` of shape `(batch_size * num_return_sequences, sequence_length)`\n sequence_length is either equal to max_length or shorter if all batches finished early due to the `eos_token_id`\n\n Examples::\n\n from transformers import AutoTokenizer, AutoModelForCausalLM\n\n tokenizer = AutoTokenizer.from_pretrained('distilgpt2') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('distilgpt2') # Download model and configuration from S3 and cache.\n outputs = model.generate(max_length=40) # do greedy decoding\n print('Generated: {}'.format(tokenizer.decode(outputs[0], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('openai-gpt') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('openai-gpt') # Download model and configuration from S3 and cache.\n input_context = 'The dog'\n input_ids = tokenizer.encode(input_context, return_tensors='pt') # encode input context\n outputs = model.generate(input_ids=input_ids, num_beams=5, num_return_sequences=3, temperature=1.5) # generate 3 independent sequences using beam search decoding (5 beams) with sampling from initial context 'The dog'\n for i in range(3): # 3 output sequences were generated\n print('Generated {}: {}'.format(i, tokenizer.decode(outputs[i], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('distilgpt2') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('distilgpt2') # Download model and configuration from S3 and cache.\n input_context = 'The dog'\n input_ids = tokenizer.encode(input_context, return_tensors='pt') # encode input context\n outputs = model.generate(input_ids=input_ids, max_length=40, temperature=0.7, num_return_sequences=3, do_sample=True) # 3 generate sequences using by sampling\n for i in range(3): # 3 output sequences were generated\n print('Generated {}: {}'.format(i, tokenizer.decode(outputs[i], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('ctrl') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('ctrl') # Download model and configuration from S3 and cache.\n input_context = 'Legal My neighbor is' # \"Legal\" is one of the control codes for ctrl\n input_ids = tokenizer.encode(input_context, return_tensors='pt') # encode input context\n outputs = model.generate(input_ids=input_ids, max_length=50, temperature=0.7, repetition_penalty=1.2) # generate sequences\n print('Generated: {}'.format(tokenizer.decode(outputs[0], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('gpt2') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('gpt2') # Download model and configuration from S3 and cache.\n input_context = 'My cute dog' # \"Legal\" is one of the control codes for ctrl\n bad_words_ids = [tokenizer.encode(bad_word, add_prefix_space=True) for bad_word in ['idiot', 'stupid', 'shut up']]\n input_ids = tokenizer.encode(input_context, return_tensors='pt') # encode input context\n outputs = model.generate(input_ids=input_ids, max_length=100, do_sample=True, bad_words_ids=bad_words_ids) # generate sequences without allowing bad_words to be generated\n \"\"\"\n\n # We cannot generate if the model does not have a LM head\n if self.get_output_embeddings() is None:\n raise AttributeError(\n \"You tried to generate sequences with a model that does not have a LM Head.\"\n \"Please use another model class (e.g. `OpenAIGPTLMHeadModel`, `XLNetLMHeadModel`, `GPT2LMHeadModel`, `CTRLLMHeadModel`, `T5WithLMHeadModel`, `TransfoXLLMHeadModel`, `XLMWithLMHeadModel`, `BartForConditionalGeneration` )\"\n )\n\n max_length = max_length if max_length is not None else self.config.max_length\n min_length = min_length if min_length is not None else self.config.min_length\n do_sample = do_sample if do_sample is not None else self.config.do_sample\n early_stopping = early_stopping if early_stopping is not None else self.config.early_stopping\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n num_beams = num_beams if num_beams is not None else self.config.num_beams\n temperature = temperature if temperature is not None else self.config.temperature\n top_k = top_k if top_k is not None else self.config.top_k\n top_p = top_p if top_p is not None else self.config.top_p\n repetition_penalty = repetition_penalty if repetition_penalty is not None else self.config.repetition_penalty\n bos_token_id = bos_token_id if bos_token_id is not None else self.config.bos_token_id\n pad_token_id = pad_token_id if pad_token_id is not None else self.config.pad_token_id\n eos_token_id = eos_token_id if eos_token_id is not None else self.config.eos_token_id\n length_penalty = length_penalty if length_penalty is not None else self.config.length_penalty\n no_repeat_ngram_size = (\n no_repeat_ngram_size if no_repeat_ngram_size is not None else self.config.no_repeat_ngram_size\n )\n bad_words_ids = bad_words_ids if bad_words_ids is not None else self.config.bad_words_ids\n num_return_sequences = (\n num_return_sequences if num_return_sequences is not None else self.config.num_return_sequences\n )\n decoder_start_token_id = (\n decoder_start_token_id if decoder_start_token_id is not None else self.config.decoder_start_token_id\n )\n\n if input_ids is not None:\n batch_size = input_ids.shape[0] # overriden by the input batch_size\n else:\n batch_size = 1\n\n assert isinstance(max_length, int) and max_length > 0, \"`max_length` should be a strictly positive integer.\"\n assert isinstance(min_length, int) and min_length >= 0, \"`min_length` should be a positive integer.\"\n assert isinstance(do_sample, bool), \"`do_sample` should be a boolean.\"\n assert isinstance(early_stopping, bool), \"`early_stopping` should be a boolean.\"\n assert isinstance(use_cache, bool), \"`use_cache` should be a boolean.\"\n assert isinstance(num_beams, int) and num_beams > 0, \"`num_beams` should be a strictly positive integer.\"\n assert temperature > 0, \"`temperature` should be strictly positive.\"\n assert isinstance(top_k, int) and top_k >= 0, \"`top_k` should be a positive integer.\"\n assert 0 <= top_p <= 1, \"`top_p` should be between 0 and 1.\"\n assert repetition_penalty >= 1.0, \"`repetition_penalty` should be >= 1.\"\n assert input_ids is not None or (\n isinstance(bos_token_id, int) and bos_token_id >= 0\n ), \"If input_ids is not defined, `bos_token_id` should be a positive integer.\"\n assert pad_token_id is None or (\n isinstance(pad_token_id, int) and (pad_token_id >= 0)\n ), \"`pad_token_id` should be a positive integer.\"\n assert (eos_token_id is None) or (\n isinstance(eos_token_id, int) and (eos_token_id >= 0)\n ), \"`eos_token_id` should be a positive integer.\"\n assert length_penalty > 0, \"`length_penalty` should be strictly positive.\"\n assert (\n isinstance(no_repeat_ngram_size, int) and no_repeat_ngram_size >= 0\n ), \"`no_repeat_ngram_size` should be a positive integer.\"\n assert (\n isinstance(num_return_sequences, int) and num_return_sequences > 0\n ), \"`num_return_sequences` should be a strictly positive integer.\"\n assert (\n bad_words_ids is None or isinstance(bad_words_ids, list) and isinstance(bad_words_ids[0], list)\n ), \"`bad_words_ids` is either `None` or a list of lists of tokens that should not be generated\"\n\n if input_ids is None:\n assert isinstance(bos_token_id, int) and bos_token_id >= 0, (\n \"you should either supply a context to complete as `input_ids` input \"\n \"or a `bos_token_id` (integer >= 0) as a first token to start the generation.\"\n )\n input_ids = torch.full(\n (batch_size, 1), bos_token_id, dtype=torch.long, device=next(self.parameters()).device,\n )\n else:\n assert input_ids.dim() == 2, \"Input prompt should be of shape (batch_size, sequence length).\"\n\n # not allow to duplicate outputs when greedy decoding\n if do_sample is False:\n if num_beams == 1:\n # no_beam_search greedy generation conditions\n assert (\n num_return_sequences == 1\n ), \"Greedy decoding will always produce the same output for num_beams == 1 and num_return_sequences > 1. Please set num_return_sequences = 1\"\n\n else:\n # beam_search greedy generation conditions\n assert (\n num_beams >= num_return_sequences\n ), \"Greedy beam search decoding cannot return more sequences than it has beams. Please set num_beams >= num_return_sequences\"\n\n # create attention mask if necessary\n # TODO (PVP): this should later be handled by the forward fn() in each model in the future see PR 3140\n if (attention_mask is None) and (pad_token_id is not None) and (pad_token_id in input_ids):\n attention_mask = input_ids.ne(pad_token_id).long()\n elif attention_mask is None:\n attention_mask = input_ids.new_ones(input_ids.shape)\n\n # set pad_token_id to eos_token_id if not set. Important that this is done after\n # attention_mask is created\n if pad_token_id is None and eos_token_id is not None:\n logger.warning(\n \"Setting `pad_token_id` to {} (first `eos_token_id`) to generate sequence\".format(eos_token_id)\n )\n pad_token_id = eos_token_id\n\n # current position and vocab size\n if hasattr(self.config, \"vocab_size\"):\n vocab_size = self.config.vocab_size\n elif (\n self.config.is_encoder_decoder\n and hasattr(self.config, \"decoder\")\n and hasattr(self.config.decoder, \"vocab_size\")\n ):\n vocab_size = self.config.decoder.vocab_size\n\n # set effective batch size and effective batch multiplier according to do_sample\n if do_sample:\n effective_batch_size = batch_size * num_return_sequences\n effective_batch_mult = num_return_sequences\n else:\n effective_batch_size = batch_size\n effective_batch_mult = 1\n\n if self.config.is_encoder_decoder:\n if decoder_start_token_id is None:\n decoder_start_token_id = bos_token_id\n\n assert (\n decoder_start_token_id is not None\n ), \"decoder_start_token_id or bos_token_id has to be defined for encoder-decoder generation\"\n assert hasattr(self, \"get_encoder\"), \"{} should have a 'get_encoder' function defined\".format(self)\n assert callable(self.get_encoder), \"{} should be a method\".format(self.get_encoder)\n\n # get encoder and store encoder outputs\n encoder = self.get_encoder()\n\n # add structural information when encoding\n encoder_outputs: tuple = encoder(input_ids, attention_mask=attention_mask, input_node_ids=input_node_ids,\n node_length=node_length, adj_matrix=adj_matrix)\n\n # Expand input ids if num_beams > 1 or num_return_sequences > 1\n if num_return_sequences > 1 or num_beams > 1:\n input_ids_len = input_ids.shape[-1]\n input_ids = input_ids.unsqueeze(1).expand(batch_size, effective_batch_mult * num_beams, input_ids_len)\n attention_mask = attention_mask.unsqueeze(1).expand(\n batch_size, effective_batch_mult * num_beams, input_ids_len\n )\n\n input_ids = input_ids.contiguous().view(\n effective_batch_size * num_beams, input_ids_len\n ) # shape: (batch_size * num_return_sequences * num_beams, cur_len)\n attention_mask = attention_mask.contiguous().view(\n effective_batch_size * num_beams, input_ids_len\n ) # shape: (batch_size * num_return_sequences * num_beams, cur_len)\n\n if self.config.is_encoder_decoder:\n # create empty decoder_input_ids\n input_ids = torch.full(\n (effective_batch_size * num_beams, 1),\n decoder_start_token_id,\n dtype=torch.long,\n device=next(self.parameters()).device,\n )\n cur_len = 1\n\n assert (\n batch_size == encoder_outputs[0].shape[0]\n ), f\"expected encoder_outputs[0] to have 1st dimension bs={batch_size}, got {encoder_outputs[0].shape[0]} \"\n\n # expand batch_idx to assign correct encoder output for expanded input_ids (due to num_beams > 1 and num_return_sequences > 1)\n expanded_batch_idxs = (\n torch.arange(batch_size)\n .view(-1, 1)\n .repeat(1, num_beams * effective_batch_mult)\n .view(-1)\n .to(input_ids.device)\n )\n # expand encoder_outputs\n encoder_outputs = (encoder_outputs[0].index_select(0, expanded_batch_idxs), *encoder_outputs[1:])\n\n else:\n encoder_outputs = None\n cur_len = input_ids.shape[-1]\n\n if num_beams > 1:\n output = self._generate_beam_search(\n input_ids,\n cur_len=cur_len,\n max_length=max_length,\n min_length=min_length,\n do_sample=do_sample,\n early_stopping=early_stopping,\n temperature=temperature,\n top_k=top_k,\n top_p=top_p,\n repetition_penalty=repetition_penalty,\n no_repeat_ngram_size=no_repeat_ngram_size,\n bad_words_ids=bad_words_ids,\n pad_token_id=pad_token_id,\n eos_token_id=eos_token_id,\n batch_size=effective_batch_size,\n num_return_sequences=num_return_sequences,\n length_penalty=length_penalty,\n num_beams=num_beams,\n vocab_size=vocab_size,\n encoder_outputs=encoder_outputs,\n attention_mask=attention_mask,\n use_cache=use_cache,\n model_specific_kwargs=model_specific_kwargs,\n )\n else:\n output = self._generate_no_beam_search(\n input_ids,\n cur_len=cur_len,\n max_length=max_length,\n min_length=min_length,\n do_sample=do_sample,\n temperature=temperature,\n top_k=top_k,\n top_p=top_p,\n repetition_penalty=repetition_penalty,\n no_repeat_ngram_size=no_repeat_ngram_size,\n bad_words_ids=bad_words_ids,\n pad_token_id=pad_token_id,\n eos_token_id=eos_token_id,\n batch_size=effective_batch_size,\n encoder_outputs=encoder_outputs,\n attention_mask=attention_mask,\n use_cache=use_cache,\n model_specific_kwargs=model_specific_kwargs,\n )\n\n return output" } ]
import os import json import numpy as np import pandas as pd import torch import random from collections import defaultdict from transformers import BartTokenizer, T5Tokenizer from transformers import AdamW, get_linear_schedule_with_warmup from utils import * from scoring.fluency_scorer import FluencyScorer from scoring.saliency_scorer import SaliencyBERTScore from scoring.simplicity_scorer import SimplicityTextScore from scoring.guardrails import * from scoring.aggregate_scorer import ScorerWrapper from GAP.data_relations_as_nodes import GAPDataloader, EventDataset, WebNLGDataset from GAP.data_relations_as_nodes import evaluate_bleu, get_t_emb_dim from tqdm import tqdm, trange from rake_nltk import Rake from evaluate import load from sentence_similarity import sentence_similarity from GAP.modeling_gap_type import GAPBartForConditionalGeneration as GAP_Type_model from GAP.modeling_gap import GAPBartForConditionalGeneration as GAP_model
21,497
# import yake bertscore = load("bertscore") ## sentence model for merge phrase_model = sentence_similarity(model_name='distilbert-base-uncased',embedding_type='cls_token_embedding') ## for sentence checking ner_check = NERInaccuracyPenalty() def run(args, logger): #load in model for graph-to-text and tokenizer checkpoint = args.model_path tokenizer_path = args.tokenizer_path tokenizer = BartTokenizer.from_pretrained(tokenizer_path) n_gpu = torch.cuda.device_count() if n_gpu > 0: torch.cuda.manual_seed_all(args.seed) if args.type_encoding: t_emb_dim = get_t_emb_dim(args) model = GAP_Type_model.from_pretrained(checkpoint,t_emb_dim=t_emb_dim) else: model = GAP_model.from_pretrained(checkpoint) if torch.cuda.is_available(): model.to(torch.device("cuda")) # Here let's put all the scorers and make a "score" function for each. scores = [{"name": "fluency", "model": FluencyScorer(1, log=True, laplace_smooth=True, prob_dict_path="data/wiki/enwiki/enwiki_terms_with_punc.csv"), "sign": 1, "weight": 1.0}, {"name": "simple_text_score", "model": SimplicityTextScore(), "sign": 1, "weight": 1.0},
# import yake bertscore = load("bertscore") ## sentence model for merge phrase_model = sentence_similarity(model_name='distilbert-base-uncased',embedding_type='cls_token_embedding') ## for sentence checking ner_check = NERInaccuracyPenalty() def run(args, logger): #load in model for graph-to-text and tokenizer checkpoint = args.model_path tokenizer_path = args.tokenizer_path tokenizer = BartTokenizer.from_pretrained(tokenizer_path) n_gpu = torch.cuda.device_count() if n_gpu > 0: torch.cuda.manual_seed_all(args.seed) if args.type_encoding: t_emb_dim = get_t_emb_dim(args) model = GAP_Type_model.from_pretrained(checkpoint,t_emb_dim=t_emb_dim) else: model = GAP_model.from_pretrained(checkpoint) if torch.cuda.is_available(): model.to(torch.device("cuda")) # Here let's put all the scorers and make a "score" function for each. scores = [{"name": "fluency", "model": FluencyScorer(1, log=True, laplace_smooth=True, prob_dict_path="data/wiki/enwiki/enwiki_terms_with_punc.csv"), "sign": 1, "weight": 1.0}, {"name": "simple_text_score", "model": SimplicityTextScore(), "sign": 1, "weight": 1.0},
{"name": "saliency_bert", "model": SaliencyBERTScore(), "sign": 1, "weight": 1.0},
1
2023-10-24 13:24:23+00:00
24k
ForceFledgling/proxyhub
proxyhub/api.py
[ { "identifier": "Checker", "path": "proxyhub/checker.py", "snippet": "class Checker:\n \"\"\"Proxy checker.\"\"\"\n\n def __init__(\n self,\n judges,\n max_tries=3,\n timeout=8,\n verify_ssl=False,\n strict=False,\n dnsbl=None,\n real_ext_ip=None,\n types=None,\n post=False,\n loop=None,\n ):\n Judge.clear()\n self._judges = get_judges(judges, timeout, verify_ssl)\n self._method = 'POST' if post else 'GET'\n self._max_tries = max_tries\n self._real_ext_ip = real_ext_ip\n self._strict = strict\n self._dnsbl = dnsbl or []\n self._types = types or {}\n self._loop = loop or asyncio.get_event_loop()\n self._resolver = Resolver(loop=self._loop)\n\n self._req_http_proto = not types or bool(\n ('HTTP', 'CONNECT:80', 'SOCKS4', 'SOCKS5') & types.keys()\n )\n self._req_https_proto = not types or bool(('HTTPS',) & types.keys())\n self._req_smtp_proto = not types or bool(('CONNECT:25',) & types.keys()) # noqa\n\n self._ngtrs = {proto for proto in types or NGTRS}\n\n async def check_judges(self):\n # TODO: need refactoring\n log.debug('Start check judges')\n stime = time.time()\n await asyncio.gather(\n *[j.check(real_ext_ip=self._real_ext_ip) for j in self._judges]\n )\n\n self._judges = [j for j in self._judges if j.is_working]\n log.debug(\n '%d judges added. Runtime: %.4f;' % (len(self._judges), time.time() - stime)\n )\n\n nojudges = []\n disable_protocols = []\n\n if len(Judge.available['HTTP']) == 0:\n nojudges.append('HTTP')\n disable_protocols.extend(['HTTP', 'CONNECT:80', 'SOCKS4', 'SOCKS5'])\n self._req_http_proto = False\n # for coroutines, which is already waiting\n Judge.ev['HTTP'].set()\n if len(Judge.available['HTTPS']) == 0:\n nojudges.append('HTTPS')\n disable_protocols.append('HTTPS')\n self._req_https_proto = False\n # for coroutines, which is already waiting\n Judge.ev['HTTPS'].set()\n if len(Judge.available['SMTP']) == 0:\n # nojudges.append('SMTP')\n disable_protocols.append('SMTP')\n self._req_smtp_proto = False\n # for coroutines, which is already waiting\n Judge.ev['SMTP'].set()\n\n for proto in disable_protocols:\n if proto in self._ngtrs:\n self._ngtrs.remove(proto)\n\n if nojudges:\n warnings.warn(\n 'Not found judges for the {nojudges} protocol.\\n'\n 'Checking proxy on protocols {disp} is disabled.'.format(\n nojudges=nojudges, disp=disable_protocols\n ),\n UserWarning,\n )\n if self._judges:\n log.debug('Loaded: %d proxy judges' % len(set(self._judges)))\n else:\n RuntimeError('Not found judges')\n\n def _types_passed(self, proxy):\n if not self._types:\n return True\n for proto, lvl in proxy.types.copy().items():\n req_levels = self._types.get(proto)\n if not req_levels or (lvl in req_levels):\n if not self._strict:\n return True\n else:\n if self._strict:\n del proxy.types[proto]\n if self._strict and proxy.types:\n return True\n proxy.log('Protocol or the level of anonymity differs from the requested')\n return False\n\n async def _in_DNSBL(self, host):\n _host = '.'.join(reversed(host.split('.'))) # reverse address\n tasks = []\n for domain in self._dnsbl:\n query = '.'.join([_host, domain])\n tasks.append(self._resolver.resolve(query, logging=False))\n responses = await asyncio.gather(*tasks, return_exceptions=True)\n if any([r for r in responses if not isinstance(r, ResolveError)]):\n return True\n return False\n\n async def check(self, proxy):\n if self._dnsbl:\n if await self._in_DNSBL(proxy.host):\n proxy.log('Found in DNSBL')\n return False\n\n if self._req_http_proto:\n await Judge.ev['HTTP'].wait()\n if self._req_https_proto:\n await Judge.ev['HTTPS'].wait()\n if self._req_smtp_proto:\n await Judge.ev['SMTP'].wait()\n\n if proxy.expected_types:\n ngtrs = proxy.expected_types & self._ngtrs\n else:\n ngtrs = self._ngtrs\n\n results = []\n for proto in ngtrs:\n if proto == 'CONNECT:25':\n result = await self._check_conn_25(proxy, proto)\n else:\n result = await self._check(proxy, proto)\n results.append(result)\n\n proxy.is_working = True if any(results) else False\n\n if proxy.is_working and self._types_passed(proxy):\n return True\n return False\n\n async def _check_conn_25(self, proxy, proto):\n judge = Judge.get_random(proto)\n proxy.log('Selected judge: %s' % judge)\n result = False\n for attempt in range(self._max_tries):\n try:\n proxy.ngtr = proto\n await proxy.connect()\n await proxy.ngtr.negotiate(host=judge.host, ip=judge.ip)\n except ProxyTimeoutError:\n continue\n except (\n ProxyConnError,\n ProxyRecvError,\n ProxySendError,\n ProxyEmptyRecvError,\n BadStatusError,\n BadResponseError,\n ):\n break\n else:\n proxy.types[proxy.ngtr.name] = None\n result = True\n break\n finally:\n proxy.close()\n return result\n\n async def _check(self, proxy, proto):\n judge = Judge.get_random(proto)\n proxy.log('Selected judge: %s' % judge)\n result = False\n for attempt in range(self._max_tries):\n try:\n proxy.ngtr = proto\n await proxy.connect()\n await proxy.ngtr.negotiate(host=judge.host, ip=judge.ip)\n headers, content, rv = await _send_test_request(\n self._method, proxy, judge\n )\n except ProxyTimeoutError:\n continue\n except (\n ProxyConnError,\n ProxyRecvError,\n ProxySendError,\n ProxyEmptyRecvError,\n BadStatusError,\n BadResponseError,\n ):\n break\n else:\n content = _decompress_content(headers, content)\n result = _check_test_response(proxy, headers, content, rv)\n if result:\n if proxy.ngtr.check_anon_lvl:\n lvl = _get_anonymity_lvl(\n self._real_ext_ip, proxy, judge, content\n )\n else:\n lvl = None\n proxy.types[proxy.ngtr.name] = lvl\n break\n finally:\n proxy.close()\n return result" }, { "identifier": "ResolveError", "path": "proxyhub/errors.py", "snippet": "class ResolveError(Exception):\n pass" }, { "identifier": "PROVIDERS", "path": "proxyhub/providers.py", "snippet": "PROVIDERS = [\n Provider(\n url='http://www.proxylists.net/',\n proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25'),\n ), # 49\n Provider(\n url='https://api.proxyscrape.com/?request=getproxies&proxytype=http',\n proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25'),\n ), # added by ZerGo0\n Provider(\n url='https://api.proxyscrape.com/?request=getproxies&proxytype=socks4',\n proto=('SOCKS4'),\n ), # added by ZerGo0\n Provider(\n url='https://api.proxyscrape.com/?request=getproxies&proxytype=socks5',\n proto=('SOCKS5'),\n ), # added by ZerGo0\n Provider(\n url='http://ipaddress.com/proxy-list/',\n proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25'),\n ), # 53\n Provider(\n url='https://www.sslproxies.org/',\n proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25'),\n ), # 100\n Provider(\n url='https://freshfreeproxylist.wordpress.com/',\n proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25'),\n ), # 50\n Provider(\n url='http://proxytime.ru/http',\n proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25'),\n ), # 1400\n Provider(\n url='https://free-proxy-list.net/',\n proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25'),\n ), # 300\n Provider(\n url='https://us-proxy.org/',\n proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25'),\n ), # 200\n Provider(\n url='http://fineproxy.org/eng/fresh-proxies/',\n proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25'),\n ), # 5500\n Provider(url='https://socks-proxy.net/', proto=('SOCKS4', 'SOCKS5')), # 80\n Provider(\n url='http://www.httptunnel.ge/ProxyListForFree.aspx',\n proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25'),\n ), # 200\n Provider(\n url='http://cn-proxy.com/',\n proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25'),\n ), # 70\n Provider(\n url='https://hugeproxies.com/home/',\n proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25'),\n ), # 800\n Provider(\n url='http://proxy.rufey.ru/',\n proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25'),\n ), # 153\n Provider(\n url='https://geekelectronics.org/my-servisy/proxy',\n proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25'),\n ), # 400\n Provider(\n url='http://pubproxy.com/api/proxy?limit=20&format=txt',\n proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25'),\n ), # 20\n Proxy_list_org(proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25')), # noqa; 140\n Xseo_in(proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25')), # noqa; 240\n Spys_ru(proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25')), # noqa; 660\n Proxylistplus_com(proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25')), # noqa; 450\n Proxylist_me(proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25')), # noqa; 2872\n Foxtools_ru(\n proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25'), max_conn=1\n ), # noqa; 500\n Gatherproxy_com(proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25')), # noqa; 3212\n Nntime_com(proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25')), # noqa; 1050\n Blogspot_com(proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25')), # noqa; 24800\n Gatherproxy_com_socks(proto=('SOCKS4', 'SOCKS5')), # noqa; 30\n Blogspot_com_socks(proto=('SOCKS4', 'SOCKS5')), # noqa; 1486\n Tools_rosinstrument_com(\n proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25')\n ), # noqa; 4000\n Tools_rosinstrument_com_socks(proto=('SOCKS4', 'SOCKS5')), # noqa; 1800\n My_proxy_com(max_conn=2), # noqa; 1000\n Checkerproxy_net(), # noqa; 60000\n Aliveproxy_com(), # noqa; 210\n Freeproxylists_com(), # noqa; 1338\n Webanetlabs_net(), # noqa; 5000\n Maxiproxies_com(), # noqa; 430\n Proxylist_download(), # noqa; 35590\n # # Bad...\n # http://www.proxylist.ro/\n # Provider(url='http://proxydb.net/',\n # proto=('HTTP', 'CONNECT:80', 'HTTPS',\n # 'CONNECT:25', 'SOCKS4', 'SOCKS5')),\n # Provider(url='http://www.cybersyndrome.net/pla6.html',\n # proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25')), # 1100\n # Provider(url='https://www.ip-adress.com/proxy-list',\n # proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25')), # 57\n # Provider(url='https://www.marcosbl.com/lab/proxies/',\n # proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25')), # 89\n # Provider(url='http://go4free.xyz/Free-Proxy/',\n # proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25')), # 196\n # Provider(url='http://blackstarsecurity.com/proxy-list.txt'), # 7014\n # Provider(url='http://www.get-proxy.net/proxy-archives'), # 519\n # Proxyb_net(proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25')), # 857\n # Proxz_com(proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25'),\n # max_conn=2), # 443\n # Proxynova_com(proto=('HTTP', 'CONNECT:80', 'HTTPS', 'CONNECT:25')), # 818\n # _50kproxies_com(), # 822\n # Free_proxy_cz(), # 420\n]" }, { "identifier": "Provider", "path": "proxyhub/providers.py", "snippet": "class Provider:\n \"\"\"Proxy provider.\n\n Provider - a website that publish free public proxy lists.\n\n :param str url: Url of page where to find proxies\n :param tuple proto:\n (optional) List of the types (protocols) that may be supported\n by proxies returned by the provider. Then used as :attr:`Proxy.types`\n :param int max_conn:\n (optional) The maximum number of concurrent connections on the provider\n :param int max_tries:\n (optional) The maximum number of attempts to receive response\n :param int timeout:\n (optional) Timeout of a request in seconds\n \"\"\"\n\n _pattern = IPPortPatternGlobal\n\n def __init__(\n self, url=None, proto=(), max_conn=4, max_tries=3, timeout=20, loop=None\n ):\n if url:\n self.domain = urlparse(url).netloc\n self.url = url\n self.proto = proto\n self._max_tries = max_tries\n self._timeout = timeout\n self._session = None\n self._cookies = {}\n self._proxies = set()\n # concurrent connections on the current provider\n self._sem_provider = asyncio.Semaphore(max_conn)\n self._loop = loop or asyncio.get_event_loop()\n\n @property\n def proxies(self):\n \"\"\"Return all found proxies.\n\n :return:\n Set of tuples with proxy hosts, ports and types (protocols)\n that may be supported (from :attr:`.proto`).\n\n For example:\n {('192.168.0.1', '80', ('HTTP', 'HTTPS'), ...)}\n\n :rtype: set\n \"\"\"\n return self._proxies\n\n @proxies.setter\n def proxies(self, new):\n new = [(host, port, self.proto) for host, port in new if port]\n self._proxies.update(new)\n\n async def get_proxies(self):\n \"\"\"Receive proxies from the provider and return them.\n\n :return: :attr:`.proxies`\n \"\"\"\n log.debug('Try to get proxies from %s' % self.domain)\n\n async with aiohttp.ClientSession(\n headers=get_headers(), cookies=self._cookies, loop=self._loop\n ) as self._session:\n await self._pipe()\n\n log.debug(\n '%d proxies received from %s: %s'\n % (len(self.proxies), self.domain, self.proxies)\n )\n return self.proxies\n\n async def _pipe(self):\n await self._find_on_page(self.url)\n\n async def _find_on_pages(self, urls):\n if not urls:\n return\n tasks = []\n if not isinstance(urls[0], dict):\n urls = set(urls)\n for url in urls:\n if isinstance(url, dict):\n tasks.append(self._find_on_page(**url))\n else:\n tasks.append(self._find_on_page(url))\n await asyncio.gather(*tasks)\n\n async def _find_on_page(self, url, data=None, headers=None, method='GET'):\n page = await self.get(url, data=data, headers=headers, method=method)\n oldcount = len(self.proxies)\n try:\n received = self.find_proxies(page)\n except Exception as e:\n received = []\n log.error(\n 'Error when executing find_proxies.'\n 'Domain: %s; Error: %r' % (self.domain, e)\n )\n self.proxies = received\n added = len(self.proxies) - oldcount\n log.debug(\n '%d(%d) proxies added(received) from %s' % (added, len(received), url)\n )\n\n async def get(self, url, data=None, headers=None, method='GET'):\n for _ in range(self._max_tries):\n page = await self._get(url, data=data, headers=headers, method=method)\n if page:\n break\n return page\n\n async def _get(self, url, data=None, headers=None, method='GET'):\n page = ''\n try:\n timeout = aiohttp.ClientTimeout(total=self._timeout)\n async with self._sem_provider, self._session.request(\n method, url, data=data, headers=headers, timeout=timeout\n ) as resp:\n page = await resp.text()\n if resp.status != 200:\n log.debug(\n 'url: %s\\nheaders: %s\\ncookies: %s\\npage:\\n%s'\n % (url, resp.headers, resp.cookies, page)\n )\n raise BadStatusError('Status: %s' % resp.status)\n except (\n UnicodeDecodeError,\n BadStatusError,\n asyncio.TimeoutError,\n aiohttp.ClientOSError,\n aiohttp.ClientResponseError,\n aiohttp.ServerDisconnectedError,\n ) as e:\n page = ''\n log.debug('%s is failed. Error: %r;' % (url, e))\n return page\n\n def find_proxies(self, page):\n return self._find_proxies(page)\n\n def _find_proxies(self, page):\n proxies = self._pattern.findall(page)\n return proxies" }, { "identifier": "Proxy", "path": "proxyhub/proxy.py", "snippet": "class Proxy:\n \"\"\"Proxy.\n\n :param str host: IP address of the proxy\n :param int port: Port of the proxy\n :param tuple types:\n (optional) List of types (protocols) which may be supported\n by the proxy and which can be checked to work with the proxy\n :param int timeout:\n (optional) Timeout of a connection and receive a response in seconds\n :param bool verify_ssl:\n (optional) Flag indicating whether to check the SSL certificates.\n Set to True to check ssl certifications\n\n :raises ValueError: If the host not is IP address, or if the port > 65535\n \"\"\"\n\n @classmethod\n async def create(cls, host, *args, **kwargs):\n \"\"\"Asynchronously create a :class:`Proxy` object.\n\n :param str host: A passed host can be a domain or IP address.\n If the host is a domain, try to resolve it\n :param str *args:\n (optional) Positional arguments that :class:`Proxy` takes\n :param str **kwargs:\n (optional) Keyword arguments that :class:`Proxy` takes\n\n :return: :class:`Proxy` object\n :rtype: proxyhub.Proxy\n\n :raises ResolveError: If could not resolve the host\n :raises ValueError: If the port > 65535\n \"\"\" # noqa: W605\n loop = kwargs.pop('loop', None)\n resolver = kwargs.pop('resolver', Resolver(loop=loop))\n try:\n _host = await resolver.resolve(host)\n self = cls(_host, *args, **kwargs)\n except (ResolveError, ValueError) as e:\n log.error('%s:%s: Error at creating: %s' % (host, args[0], e))\n raise\n return self\n\n def __init__(self, host=None, port=None, types=(), timeout=8, verify_ssl=False):\n self.host = host\n if not Resolver.host_is_ip(self.host):\n raise ValueError(\n 'The host of proxy should be the IP address. '\n 'Try Proxy.create() if the host is a domain'\n )\n\n self.port = int(port)\n if self.port > 65535:\n raise ValueError('The port of proxy cannot be greater than 65535')\n\n self.expected_types = set(types) & {\n 'HTTP',\n 'HTTPS',\n 'CONNECT:80',\n 'CONNECT:25',\n 'SOCKS4',\n 'SOCKS5',\n }\n self._timeout = timeout\n self._ssl_context = True if verify_ssl else _ssl._create_unverified_context()\n self._types = {}\n self._is_working = False\n self.stat = {'requests': 0, 'errors': Counter()}\n self._ngtr = None\n self._geo = Resolver.get_ip_info(self.host)\n self._log = []\n self._runtimes = []\n self._schemes = ()\n self._closed = True\n self._reader = {'conn': None, 'ssl': None}\n self._writer = {'conn': None, 'ssl': None}\n\n def __repr__(self):\n \"\"\"Class representation\n e.g. <Proxy US 1.12 [HTTP: Anonymous, HTTPS] 10.0.0.1:8080>\n \"\"\"\n tpinfo = []\n order = lambda tp_lvl: (len(tp_lvl[0]), tp_lvl[0][-1]) # noqa: 731\n for tp, lvl in sorted(self.types.items(), key=order):\n s = '{tp}: {lvl}' if lvl else '{tp}'\n s = s.format(tp=tp, lvl=lvl)\n tpinfo.append(s)\n tpinfo = ', '.join(tpinfo)\n return '<Proxy {code} {avg:.2f}s [{types}] {host}:{port}>'.format(\n code=self._geo.code,\n types=tpinfo,\n host=self.host,\n port=self.port,\n avg=self.avg_resp_time,\n )\n\n @property\n def types(self):\n \"\"\"Types (protocols) supported by the proxy.\n\n | Where key is type, value is level of anonymity\n (only for HTTP, for other types level always is None).\n | Available types: HTTP, HTTPS, SOCKS4, SOCKS5, CONNECT:80, CONNECT:25\n | Available levels: Transparent, Anonymous, High.\n\n :rtype: dict\n \"\"\"\n return self._types\n\n @property\n def is_working(self):\n \"\"\"True if the proxy is working, False otherwise.\n\n :rtype: bool\n \"\"\"\n return self._is_working\n\n @is_working.setter\n def is_working(self, val):\n self._is_working = val\n\n @property\n def writer(self):\n return self._writer.get('ssl') or self._writer.get('conn')\n\n @property\n def reader(self):\n return self._reader.get('ssl') or self._reader.get('conn')\n\n @property\n def priority(self):\n return (self.error_rate, self.avg_resp_time)\n\n @property\n def error_rate(self):\n \"\"\"Error rate: from 0 to 1.\n\n For example: 0.7 = 70% requests ends with error.\n\n :rtype: float\n\n .. versionadded:: 0.2.0\n \"\"\"\n if not self.stat['requests']:\n return 0\n return round(sum(self.stat['errors'].values()) / self.stat['requests'], 2)\n\n @property\n def schemes(self):\n \"\"\"Return supported schemes.\"\"\"\n if not self._schemes:\n _schemes = []\n if self.types.keys() & _HTTP_PROTOS:\n _schemes.append('HTTP')\n if self.types.keys() & _HTTPS_PROTOS:\n _schemes.append('HTTPS')\n self._schemes = tuple(_schemes)\n return self._schemes\n\n @property\n def avg_resp_time(self):\n \"\"\"The average connection/response time.\n\n :rtype: float\n \"\"\"\n if not self._runtimes:\n return 0\n return round(sum(self._runtimes) / len(self._runtimes), 2)\n\n @property\n def avgRespTime(self):\n \"\"\"\n .. deprecated:: 2.0\n Use :attr:`avg_resp_time` instead.\n \"\"\"\n warnings.warn(\n '`avgRespTime` property is deprecated, ' 'use `avg_resp_time` instead.',\n DeprecationWarning,\n )\n return self.avg_resp_time\n\n @property\n def geo(self):\n \"\"\"Geo information about IP address of the proxy.\n\n :return:\n Named tuple with fields:\n * ``code`` - ISO country code\n * ``name`` - Full name of country\n * ``region_code`` - ISO region code\n * ``region_name`` - Full name of region\n * ``city_name`` - Full name of city\n :rtype: collections.namedtuple\n\n .. versionchanged:: 0.2.0\n In previous versions return a dictionary, now named tuple.\n \"\"\"\n return self._geo\n\n @property\n def ngtr(self):\n return self._ngtr\n\n @ngtr.setter\n def ngtr(self, proto):\n self._ngtr = NGTRS[proto](self)\n\n def as_json(self):\n \"\"\"Return the proxy's properties in JSON format.\n\n :rtype: dict\n \"\"\"\n info = {\n 'host': self.host,\n 'port': self.port,\n 'geo': {\n 'country': {'code': self._geo.code, 'name': self._geo.name},\n 'region': {\n 'code': self._geo.region_code,\n 'name': self._geo.region_name,\n },\n 'city': self._geo.city_name,\n },\n 'types': [],\n 'avg_resp_time': self.avg_resp_time,\n 'error_rate': self.error_rate,\n }\n\n order = lambda tp_lvl: (len(tp_lvl[0]), tp_lvl[0][-1]) # noqa: 731\n for tp, lvl in sorted(self.types.items(), key=order):\n info['types'].append({'type': tp, 'level': lvl or ''})\n return info\n\n def as_text(self):\n \"\"\"\n Return proxy as host:port\n\n :rtype: str\n \"\"\"\n return \"{}:{}\\n\".format(self.host, self.port)\n\n def log(self, msg, stime=0, err=None):\n ngtr = self.ngtr.name if self.ngtr else 'INFO'\n runtime = time.time() - stime if stime else 0\n log.debug(\n '{h}:{p} [{n}]: {msg}; Runtime: {rt:.2f}'.format(\n h=self.host, p=self.port, n=ngtr, msg=msg, rt=runtime\n )\n )\n trunc = '...' if len(msg) > 58 else ''\n msg = '{msg:.60s}{trunc}'.format(msg=msg, trunc=trunc)\n self._log.append((ngtr, msg, runtime))\n if err:\n self.stat['errors'][err.errmsg] += 1\n if runtime and 'timeout' not in msg:\n self._runtimes.append(runtime)\n\n def get_log(self):\n \"\"\"Proxy log.\n\n :return: The proxy log in format: (negotaitor, msg, runtime)\n :rtype: tuple\n\n .. versionadded:: 0.2.0\n \"\"\"\n return self._log\n\n async def connect(self, ssl=False):\n err = None\n msg = '%s' % 'SSL: ' if ssl else ''\n stime = time.time()\n self.log('%sInitial connection' % msg)\n try:\n if ssl:\n _type = 'ssl'\n sock = self._writer['conn'].get_extra_info('socket')\n params = {\n 'ssl': self._ssl_context,\n 'sock': sock,\n 'server_hostname': self.host,\n }\n else:\n _type = 'conn'\n params = {'host': self.host, 'port': self.port}\n self._reader[_type], self._writer[_type] = await asyncio.wait_for(\n asyncio.open_connection(**params), timeout=self._timeout\n )\n except asyncio.TimeoutError:\n msg += 'Connection: timeout'\n err = ProxyTimeoutError(msg)\n raise err\n except (ConnectionRefusedError, OSError, _ssl.SSLError):\n msg += 'Connection: failed'\n err = ProxyConnError(msg)\n raise err\n # except asyncio.CancelledError:\n # log.debug('Cancelled in proxy.connect()')\n # raise ProxyConnError()\n else:\n msg += 'Connection: success'\n self._closed = False\n finally:\n self.stat['requests'] += 1\n self.log(msg, stime, err=err)\n\n def close(self):\n if self._closed:\n return\n self._closed = True\n if self.writer:\n # try:\n self.writer.close()\n # except RuntimeError:\n # print('Try proxy.close() when loop is closed:',\n # asyncio.get_event_loop()._closed)\n self._reader = {'conn': None, 'ssl': None}\n self._writer = {'conn': None, 'ssl': None}\n self.log('Connection: closed')\n self._ngtr = None\n\n async def send(self, req):\n msg, err = '', None\n _req = req.encode() if not isinstance(req, bytes) else req\n try:\n self.writer.write(_req)\n await self.writer.drain()\n except ConnectionResetError:\n msg = '; Sending: failed'\n err = ProxySendError(msg)\n raise err\n finally:\n self.log('Request: %s%s' % (req, msg), err=err)\n\n async def recv(self, length=0, head_only=False):\n resp, msg, err = b'', '', None\n stime = time.time()\n try:\n resp = await asyncio.wait_for(\n self._recv(length, head_only), timeout=self._timeout\n )\n except asyncio.TimeoutError:\n msg = 'Received: timeout'\n err = ProxyTimeoutError(msg)\n raise err\n except (ConnectionResetError, OSError):\n msg = 'Received: failed' # (connection is reset by the peer)\n err = ProxyRecvError(msg)\n raise err\n else:\n msg = 'Received: %s bytes' % len(resp)\n if not resp:\n err = ProxyEmptyRecvError(msg)\n raise err\n finally:\n if resp:\n msg += ': %s' % resp[:12]\n self.log(msg, stime, err=err)\n return resp\n\n async def _recv(self, length=0, head_only=False):\n resp = b''\n if length:\n try:\n resp = await self.reader.readexactly(length)\n except asyncio.IncompleteReadError as e:\n resp = e.partial\n else:\n body_size, body_recv, chunked = 0, 0, None\n while not self.reader.at_eof():\n line = await self.reader.readline()\n resp += line\n if body_size:\n body_recv += len(line)\n if body_recv >= body_size:\n break\n elif chunked and line == b'0\\r\\n':\n break\n elif not body_size and line == b'\\r\\n':\n if head_only:\n break\n headers = parse_headers(resp)\n body_size = int(headers.get('Content-Length', 0))\n if not body_size:\n chunked = headers.get('Transfer-Encoding') == 'chunked'\n return resp" }, { "identifier": "Resolver", "path": "proxyhub/resolver.py", "snippet": "class Resolver:\n \"\"\"Async host resolver based on aiodns.\"\"\"\n\n _cached_hosts = {}\n _ip_hosts = [\n 'https://wtfismyip.com/text',\n 'http://api.ipify.org/',\n 'http://ipinfo.io/ip',\n 'http://ipv4.icanhazip.com/',\n 'http://myexternalip.com/raw',\n 'http://ipinfo.io/ip',\n 'http://ifconfig.io/ip',\n ]\n # the list of resolvers will point a copy of original one\n _temp_host = []\n\n def __init__(self, timeout=5, loop=None):\n self._timeout = timeout\n self._loop = loop or asyncio.get_event_loop()\n self._resolver = aiodns.DNSResolver(loop=self._loop)\n\n @staticmethod\n def host_is_ip(host):\n \"\"\"Check a host is IP address.\"\"\"\n # TODO: add IPv6 support\n try:\n host = '.'.join(f'{int(n)}' for n in host.split('.'))\n ipaddress.IPv4Address(host)\n except (ipaddress.AddressValueError, ValueError):\n return False\n else:\n return True\n\n @staticmethod\n def get_ip_info(ip):\n \"\"\"Return geo information about IP address.\n\n `code` - ISO country code\n `name` - Full name of country\n `region_code` - ISO region code\n `region_name` - Full name of region\n `city_name` - Full name of city\n \"\"\"\n # from pprint import pprint\n try:\n ipInfo = _mmdb_reader.get(ip) or {}\n except (maxminddb.errors.InvalidDatabaseError, ValueError):\n ipInfo = {}\n\n code, name = '--', 'Unknown'\n city_name, region_code, region_name = ('Unknown',) * 3\n if 'country' in ipInfo:\n code = ipInfo['country']['iso_code']\n name = ipInfo['country']['names']['en']\n elif 'continent' in ipInfo:\n code = ipInfo['continent']['code']\n name = ipInfo['continent']['names']['en']\n if 'city' in ipInfo:\n city_name = ipInfo['city']['names']['en']\n if 'subdivisions' in ipInfo:\n region_code = ipInfo['subdivisions'][0]['iso_code']\n region_name = ipInfo['subdivisions'][0]['names']['en']\n return GeoData(code, name, region_code, region_name, city_name)\n\n def _pop_random_ip_host(self):\n host = random.choice(self._temp_host)\n self._temp_host.remove(host)\n return host\n\n async def get_real_ext_ip(self):\n \"\"\"Return real external IP address.\"\"\"\n # make a copy of original one to temp one\n # so original one will stay no change\n self._temp_host = self._ip_hosts.copy()\n while self._temp_host:\n try:\n timeout = aiohttp.ClientTimeout(total=self._timeout)\n async with aiohttp.ClientSession(\n timeout=timeout, loop=self._loop\n ) as session, session.get(self._pop_random_ip_host()) as resp:\n ip = await resp.text()\n except asyncio.TimeoutError:\n pass\n else:\n ip = ip.strip()\n if self.host_is_ip(ip):\n log.debug('Real external IP: %s', ip)\n break\n else:\n raise RuntimeError('Could not get the external IP')\n return ip\n\n async def resolve(self, host, port=80, family=None, qtype='A', logging=True):\n \"\"\"Return resolving IP address(es) from host name.\"\"\"\n if self.host_is_ip(host):\n return host\n\n _host = self._cached_hosts.get(host)\n if _host:\n return _host\n\n resp = await self._resolve(host, qtype)\n\n if resp:\n hosts = [\n {\n 'hostname': host,\n 'host': r.host,\n 'port': port,\n 'family': family,\n 'proto': socket.IPPROTO_IP,\n 'flags': socket.AI_NUMERICHOST,\n }\n for r in resp\n ]\n if family:\n self._cached_hosts[host] = hosts\n else:\n self._cached_hosts[host] = hosts[0]['host']\n if logging:\n log.debug('%s: Host resolved: %s' % (host, self._cached_hosts[host]))\n else:\n if logging:\n log.warning('%s: Could not resolve host' % host)\n return self._cached_hosts.get(host)\n\n async def _resolve(self, host, qtype):\n try:\n resp = await asyncio.wait_for(\n self._resolver.query(host, qtype), timeout=self._timeout\n )\n except (aiodns.error.DNSError, asyncio.TimeoutError):\n raise ResolveError\n else:\n return resp" }, { "identifier": "Server", "path": "proxyhub/server.py", "snippet": "class Server:\n \"\"\"Server distributes incoming requests to a pool of found proxies.\"\"\"\n\n def __init__(\n self,\n host,\n port,\n proxies,\n timeout=8,\n max_tries=3,\n min_queue=5,\n min_req_proxy=5,\n max_error_rate=0.5,\n max_resp_time=8,\n prefer_connect=False,\n http_allowed_codes=None,\n backlog=100,\n loop=None,\n **kwargs,\n ):\n self.host = host\n self.port = int(port)\n self._loop = loop or asyncio.get_event_loop()\n self._timeout = timeout\n self._max_tries = max_tries\n self._backlog = backlog\n self._prefer_connect = prefer_connect\n\n self._server = None\n self._connections = {}\n self._proxy_pool = ProxyPool(\n proxies, min_req_proxy, max_error_rate, max_resp_time, min_queue\n )\n self._resolver = Resolver(loop=self._loop)\n self._http_allowed_codes = http_allowed_codes or []\n\n def start(self):\n\n srv = asyncio.start_server(\n self._accept,\n host=self.host,\n port=self.port,\n backlog=self._backlog,\n loop=self._loop,\n )\n self._server = self._loop.run_until_complete(srv)\n\n log.info(\n 'Listening established on {0}'.format(self._server.sockets[0].getsockname())\n )\n\n def stop(self):\n if not self._server:\n return\n for conn in self._connections:\n if not conn.done():\n conn.cancel()\n self._server.close()\n if not self._loop.is_running():\n self._loop.run_until_complete(self._server.wait_closed())\n # Time to close the running futures in self._connections\n self._loop.run_until_complete(asyncio.sleep(0.5))\n self._server = None\n self._loop.stop()\n log.info('Server is stopped')\n\n def _accept(self, client_reader, client_writer):\n def _on_completion(f):\n reader, writer = self._connections.pop(f)\n writer.close()\n log.debug('client: %d; closed' % id(client_reader))\n try:\n exc = f.exception()\n except asyncio.CancelledError:\n log.debug('CancelledError in server._handle:_on_completion')\n exc = None\n if exc:\n if isinstance(exc, NoProxyError):\n self.stop()\n else:\n raise exc\n\n f = asyncio.ensure_future(self._handle(client_reader, client_writer))\n f.add_done_callback(_on_completion)\n self._connections[f] = (client_reader, client_writer)\n\n async def _handle(self, client_reader, client_writer):\n log.debug(\n 'Accepted connection from %s' % (client_writer.get_extra_info('peername'),)\n )\n\n request, headers = await self._parse_request(client_reader)\n scheme = self._identify_scheme(headers)\n client = id(client_reader)\n log.debug(\n 'client: %d; request: %s; headers: %s; scheme: %s'\n % (client, request, headers, scheme)\n )\n\n # API for controlling proxyhub2\n if headers['Host'] == 'proxycontrol':\n _api, _operation, _params = headers['Path'].split('/', 5)[3:]\n if _api == 'api':\n if _operation == 'remove':\n proxy_host, proxy_port = _params.split(':', 1)\n self._proxy_pool.remove(proxy_host, int(proxy_port))\n log.debug(\n 'Remove Proxy: client: %d; request: %s; headers: %s; scheme: %s; proxy_host: %s; proxy_port: %s'\n % (client, request, headers, scheme, proxy_host, proxy_port)\n )\n client_writer.write(b'HTTP/1.1 204 No Content\\r\\n\\r\\n')\n await client_writer.drain()\n return\n elif _operation == 'history':\n query_type, url = _params.split(':', 1)\n if query_type == 'url':\n previous_proxy = history.get(\n f\"{client_reader._transport.get_extra_info('peername')[0]}-{url}\"\n )\n if previous_proxy is None:\n client_writer.write(b'HTTP/1.1 204 No Content\\r\\n\\r\\n')\n await client_writer.drain()\n return\n else:\n previous_proxy_bytestring = (\n '{\"proxy\": \"%s\"}' % previous_proxy\n ).encode()\n client_writer.write(b'HTTP/1.1 200 OK\\r\\n')\n client_writer.write(b'Content-Type: application/json\\r\\n')\n client_writer.write(\n f\"Content-Length: {str(len(previous_proxy_bytestring) + 2).encode()}\\r\\n\"\n )\n client_writer.write(b'Access-Control-Allow-Origin: *\\r\\n')\n client_writer.write(\n b'Access-Control-Allow-Credentials: true\\r\\n\\r\\n'\n )\n\n client_writer.write(previous_proxy_bytestring + b'\\r\\n')\n await client_writer.drain()\n return\n\n for attempt in range(self._max_tries):\n stime, err = 0, None\n proxy = await self._proxy_pool.get(scheme)\n proto = self._choice_proto(proxy, scheme)\n log.debug(\n 'client: %d; attempt: %d; proxy: %s; proto: %s'\n % (client, attempt, proxy, proto)\n )\n\n try:\n await proxy.connect()\n\n if proto in ('CONNECT:80', 'SOCKS4', 'SOCKS5'):\n host = headers.get('Host')\n port = headers.get('Port', 80)\n try:\n ip = await self._resolver.resolve(host)\n except ResolveError:\n return\n proxy.ngtr = proto\n await proxy.ngtr.negotiate(host=host, port=port, ip=ip)\n if scheme == 'HTTPS' and proto in ('SOCKS4', 'SOCKS5'):\n client_writer.write(CONNECTED)\n await client_writer.drain()\n else: # HTTP\n await proxy.send(request)\n else: # proto: HTTP & HTTPS\n await proxy.send(request)\n\n history[\n f\"{client_reader._transport.get_extra_info('peername')[0]}-{headers['Path']}\"\n ] = (proxy.host + ':' + str(proxy.port))\n inject_resp_header = {\n 'headers': {'X-Proxy-Info': proxy.host + ':' + str(proxy.port)}\n }\n\n stime = time.time()\n stream = [\n asyncio.ensure_future(\n self._stream(reader=client_reader, writer=proxy.writer)\n ),\n asyncio.ensure_future(\n self._stream(\n reader=proxy.reader,\n writer=client_writer,\n scheme=scheme,\n inject=inject_resp_header,\n )\n ),\n ]\n await asyncio.gather(*stream, loop=self._loop)\n except asyncio.CancelledError:\n log.debug('Cancelled in server._handle')\n break\n except (\n ProxyTimeoutError,\n ProxyConnError,\n ProxyRecvError,\n ProxySendError,\n ProxyEmptyRecvError,\n BadStatusError,\n BadResponseError,\n ) as e:\n log.debug('client: %d; error: %r' % (client, e))\n continue\n except ErrorOnStream as e:\n log.debug(\n 'client: %d; error: %r; EOF: %s'\n % (client, e, client_reader.at_eof())\n )\n for task in stream:\n if not task.done():\n task.cancel()\n if client_reader.at_eof() and 'Timeout' in repr(e):\n # Proxy may not be able to receive EOF and weel be raised a\n # TimeoutError, but all the data has already successfully\n # returned, so do not consider this error of proxy\n break\n err = e\n if scheme == 'HTTPS': # SSL Handshake probably failed\n break\n else:\n break\n finally:\n proxy.log(request.decode(), stime, err=err)\n proxy.close()\n self._proxy_pool.put(proxy)\n\n async def _parse_request(self, reader, length=65536):\n request = await reader.read(length)\n headers = parse_headers(request)\n if headers['Method'] == 'POST' and request.endswith(b'\\r\\n\\r\\n'):\n # For aiohttp. POST data returns on second reading\n request += await reader.read(length)\n return request, headers\n\n def _identify_scheme(self, headers):\n if headers['Method'] == 'CONNECT':\n return 'HTTPS'\n else:\n return 'HTTP'\n\n def _choice_proto(self, proxy, scheme):\n if scheme == 'HTTP':\n if self._prefer_connect and ('CONNECT:80' in proxy.types):\n proto = 'CONNECT:80'\n else:\n relevant = {\n 'HTTP',\n 'CONNECT:80',\n 'SOCKS4',\n 'SOCKS5',\n } & proxy.types.keys()\n proto = relevant.pop()\n else: # HTTPS\n relevant = {'HTTPS', 'SOCKS4', 'SOCKS5'} & proxy.types.keys()\n proto = relevant.pop()\n return proto\n\n async def _stream(self, reader, writer, length=65536, scheme=None, inject=None):\n checked = False\n\n try:\n while not reader.at_eof():\n data = await asyncio.wait_for(reader.read(length), self._timeout)\n if not data:\n writer.close()\n break\n elif scheme and not checked:\n self._check_response(data, scheme)\n\n if inject.get('headers') is not None and len(inject['headers']) > 0:\n data = self._inject_headers(data, scheme, inject['headers'])\n\n checked = True\n\n writer.write(data)\n await writer.drain()\n\n except (\n asyncio.TimeoutError,\n ConnectionResetError,\n OSError,\n ProxyRecvError,\n BadStatusError,\n BadResponseError,\n ) as e:\n raise ErrorOnStream(e)\n\n def _check_response(self, data, scheme):\n if scheme == 'HTTP' and self._http_allowed_codes:\n line = data.split(b'\\r\\n', 1)[0].decode()\n try:\n header = parse_status_line(line)\n except BadStatusLine:\n raise BadResponseError\n if header['Status'] not in self._http_allowed_codes:\n raise BadStatusError(\n '%r not in %r' % (header['Status'], self._http_allowed_codes)\n )\n\n def _inject_headers(self, data, scheme, headers):\n custom_lines = []\n\n if scheme == 'HTTP' or scheme == 'HTTPS':\n status_line, rest_lines = data.split(b'\\r\\n', 1)\n custom_lines.append(status_line)\n\n for k, v in headers.items():\n custom_lines.append(('%s: %s' % (k, v)).encode())\n\n custom_lines.append(rest_lines)\n data = b'\\r\\n'.join(custom_lines)\n\n return data" }, { "identifier": "IPPortPatternLine", "path": "proxyhub/utils.py", "snippet": "BASE_DIR = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))\nDATA_DIR = os.path.join(BASE_DIR, 'data')\ndef get_headers(rv=False):\ndef get_all_ip(page):\ndef get_status_code(resp, start=9, stop=12):\ndef parse_status_line(line):\ndef parse_headers(headers):\ndef update_geoip_db():" } ]
import asyncio import io import signal import warnings from collections import Counter, defaultdict from functools import partial from pprint import pprint from .checker import Checker from .errors import ResolveError from .providers import PROVIDERS, Provider from .proxy import Proxy from .resolver import Resolver from .server import Server from .utils import IPPortPatternLine, log
14,844
(optional) The minimum number of proxies to choose from before deciding which is the most suitable to use. The default value is 5 :param int min_req_proxy: (optional) The minimum number of processed requests to estimate the quality of proxy (in accordance with :attr:`max_error_rate` and :attr:`max_resp_time`). The default value is 5 :param int max_error_rate: (optional) The maximum percentage of requests that ended with an error. For example: 0.5 = 50%. If proxy.error_rate exceeds this value, proxy will be removed from the pool. The default value is 0.5 :param int max_resp_time: (optional) The maximum response time in seconds. If proxy.avg_resp_time exceeds this value, proxy will be removed from the pool. The default value is 8 :param bool prefer_connect: (optional) Flag that indicates whether to use the CONNECT method if possible. For example: If is set to True and a proxy supports HTTP proto (GET or POST requests) and CONNECT method, the server will try to use CONNECT method and only after that send the original request. The default value is False :param list http_allowed_codes: (optional) Acceptable HTTP codes returned by proxy on requests. If a proxy return code, not included in this list, it will be considered as a proxy error, not a wrong/unavailable address. For example, if a proxy will return a ``404 Not Found`` response - this will be considered as an error of a proxy. Checks only for HTTP protocol, HTTPS not supported at the moment. By default the list is empty and the response code is not verified :param int backlog: (optional) The maximum number of queued connections passed to listen. The default value is 100 :raises ValueError: If :attr:`limit` is less than or equal to zero. Because a parsing of providers will be endless .. versionadded:: 0.2.0 """ if limit <= 0: raise ValueError( 'In serve mode value of the limit cannot be less than or ' 'equal to zero. Otherwise, a parsing of providers will be ' 'endless' ) self._server = Server( host=host, port=port, proxies=self._proxies, timeout=self._timeout, max_tries=kwargs.pop('max_tries', self._max_tries), loop=self._loop, **kwargs, ) self._server.start() task = asyncio.ensure_future(self.find(limit=limit, **kwargs)) self._all_tasks.append(task) async def _load(self, data, check=True): """Looking for proxies in the passed data. Transform the passed data from [raw string | file-like object | list] to set {(host, port), ...}: {('192.168.0.1', '80'), } """ log.debug('Load proxies from the raw data') if isinstance(data, io.TextIOWrapper): data = data.read() if isinstance(data, str): data = IPPortPatternLine.findall(data) proxies = set(data) for proxy in proxies: await self._handle(proxy, check=check) await self._on_check.join() self._done() async def _grab(self, types=None, check=False): def _get_tasks(by=MAX_CONCURRENT_PROVIDERS): providers = [ pr for pr in self._providers if not types or not pr.proto or bool(pr.proto & types.keys()) ] while providers: tasks = [ asyncio.ensure_future(pr.get_proxies()) for pr in providers[:by] ] del providers[:by] self._all_tasks.extend(tasks) yield tasks log.debug('Start grabbing proxies') while True: for tasks in _get_tasks(): for task in asyncio.as_completed(tasks): proxies = await task for proxy in proxies: await self._handle(proxy, check=check) log.debug('Grab cycle is complete') if self._server: log.debug('fall asleep for %d seconds' % GRAB_PAUSE) await asyncio.sleep(GRAB_PAUSE) log.debug('awaked') else: break await self._on_check.join() self._done() async def _handle(self, proxy, check=False): try: proxy = await Proxy.create( *proxy, timeout=self._timeout, resolver=self._resolver, verify_ssl=self._verify_ssl, loop=self._loop, )
# Pause between grabbing cycles; in seconds. GRAB_PAUSE = 180 # The maximum number of providers that are parsed concurrently MAX_CONCURRENT_PROVIDERS = 3 class Broker: """The Broker. | One broker to rule them all, one broker to find them, | One broker to bring them all and in the darkness bind them. :param asyncio.Queue queue: (optional) Queue of found/checked proxies :param int timeout: (optional) Timeout of a request in seconds :param int max_conn: (optional) The maximum number of concurrent checks of proxies :param int max_tries: (optional) The maximum number of attempts to check a proxy :param list judges: (optional) Urls of pages that show HTTP headers and IP address. Or :class:`~proxyhub.judge.Judge` objects :param list providers: (optional) Urls of pages where to find proxies. Or :class:`~proxyhub.providers.Provider` objects :param bool verify_ssl: (optional) Flag indicating whether to check the SSL certificates. Set to True to check ssl certifications :param loop: (optional) asyncio compatible event loop :param stop_broker_on_sigint: (optional) whether set SIGINT signal on broker object. Useful for a thread other than main thread. .. deprecated:: 0.2.0 Use :attr:`max_conn` and :attr:`max_tries` instead of :attr:`max_concurrent_conn` and :attr:`attempts_conn`. """ def __init__( self, queue=None, timeout=8, max_conn=200, max_tries=3, judges=None, providers=None, verify_ssl=False, loop=None, stop_broker_on_sigint=True, **kwargs, ): self._loop = loop or asyncio.get_event_loop_policy().get_event_loop() self._proxies = queue or asyncio.Queue() self._resolver = Resolver(loop=self._loop) self._timeout = timeout self._verify_ssl = verify_ssl self.unique_proxies = {} self._all_tasks = [] self._checker = None self._server = None self._limit = 0 # not limited self._countries = None max_concurrent_conn = kwargs.get('max_concurrent_conn') if max_concurrent_conn: warnings.warn( '`max_concurrent_conn` is deprecated, use `max_conn` instead', DeprecationWarning, ) if isinstance(max_concurrent_conn, asyncio.Semaphore): max_conn = max_concurrent_conn._value else: max_conn = max_concurrent_conn attempts_conn = kwargs.get('attempts_conn') if attempts_conn: warnings.warn( '`attempts_conn` is deprecated, use `max_tries` instead', DeprecationWarning, ) max_tries = attempts_conn # The maximum number of concurrent checking proxies self._on_check = asyncio.Queue(maxsize=max_conn) self._max_tries = max_tries self._judges = judges self._providers = [ p if isinstance(p, Provider) else Provider(p) for p in (providers or PROVIDERS) ] if stop_broker_on_sigint: try: self._loop.add_signal_handler(signal.SIGINT, self.stop) # add_signal_handler() is not implemented on Win # https://docs.python.org/3.5/library/asyncio-eventloops.html#windows except NotImplementedError: pass async def grab(self, *, countries=None, limit=0): """Gather proxies from the providers without checking. :param list countries: (optional) List of ISO country codes where should be located proxies :param int limit: (optional) The maximum number of proxies :ref:`Example of usage <proxyhub-examples-grab>`. """ self._countries = countries self._limit = limit task = asyncio.ensure_future(self._grab(check=False)) self._all_tasks.append(task) async def find( self, *, types=None, data=None, countries=None, post=False, strict=False, dnsbl=None, limit=0, **kwargs, ): """Gather and check proxies from providers or from a passed data. :ref:`Example of usage <proxyhub-examples-find>`. :param list types: Types (protocols) that need to be check on support by proxy. Supported: HTTP, HTTPS, SOCKS4, SOCKS5, CONNECT:80, CONNECT:25 And levels of anonymity (HTTP only): Transparent, Anonymous, High :param data: (optional) String or list with proxies. Also can be a file-like object supports `read()` method. Used instead of providers :param list countries: (optional) List of ISO country codes where should be located proxies :param bool post: (optional) Flag indicating use POST instead of GET for requests when checking proxies :param bool strict: (optional) Flag indicating that anonymity levels of types (protocols) supported by a proxy must be equal to the requested types and levels of anonymity. By default, strict mode is off and for a successful check is enough to satisfy any one of the requested types :param list dnsbl: (optional) Spam databases for proxy checking. `Wiki <https://en.wikipedia.org/wiki/DNSBL>`_ :param int limit: (optional) The maximum number of proxies :raises ValueError: If :attr:`types` not given. .. versionchanged:: 0.2.0 Added: :attr:`post`, :attr:`strict`, :attr:`dnsbl`. Changed: :attr:`types` is required. """ ip = await self._resolver.get_real_ext_ip() types = _update_types(types) if not types: raise ValueError('`types` is required') self._checker = Checker( judges=self._judges, timeout=self._timeout, verify_ssl=self._verify_ssl, max_tries=self._max_tries, real_ext_ip=ip, types=types, post=post, strict=strict, dnsbl=dnsbl, loop=self._loop, ) self._countries = countries self._limit = limit tasks = [asyncio.ensure_future(self._checker.check_judges())] if data: task = asyncio.ensure_future(self._load(data, check=True)) else: task = asyncio.ensure_future(self._grab(types, check=True)) tasks.append(task) self._all_tasks.extend(tasks) def serve(self, host='127.0.0.1', port=8888, limit=100, **kwargs): """Start a local proxy server. The server distributes incoming requests to a pool of found proxies. When the server receives an incoming request, it chooses the optimal proxy (based on the percentage of errors and average response time) and passes to it the incoming request. In addition to the parameters listed below are also accept all the parameters of the :meth:`.find` method and passed it to gather proxies to a pool. :ref:`Example of usage <proxyhub-examples-server>`. :param str host: (optional) Host of local proxy server :param int port: (optional) Port of local proxy server :param int limit: (optional) When will be found a requested number of working proxies, checking of new proxies will be lazily paused. Checking will be resumed if all the found proxies will be discarded in the process of working with them (see :attr:`max_error_rate`, :attr:`max_resp_time`). And will continue until it finds one working proxy and paused again. The default value is 100 :param int max_tries: (optional) The maximum number of attempts to handle an incoming request. If not specified, it will use the value specified during the creation of the :class:`Broker` object. Attempts can be made with different proxies. The default value is 3 :param int strategy: (optional) The strategy used for picking proxy from pool. The default value is 'best' :param int min_queue: (optional) The minimum number of proxies to choose from before deciding which is the most suitable to use. The default value is 5 :param int min_req_proxy: (optional) The minimum number of processed requests to estimate the quality of proxy (in accordance with :attr:`max_error_rate` and :attr:`max_resp_time`). The default value is 5 :param int max_error_rate: (optional) The maximum percentage of requests that ended with an error. For example: 0.5 = 50%. If proxy.error_rate exceeds this value, proxy will be removed from the pool. The default value is 0.5 :param int max_resp_time: (optional) The maximum response time in seconds. If proxy.avg_resp_time exceeds this value, proxy will be removed from the pool. The default value is 8 :param bool prefer_connect: (optional) Flag that indicates whether to use the CONNECT method if possible. For example: If is set to True and a proxy supports HTTP proto (GET or POST requests) and CONNECT method, the server will try to use CONNECT method and only after that send the original request. The default value is False :param list http_allowed_codes: (optional) Acceptable HTTP codes returned by proxy on requests. If a proxy return code, not included in this list, it will be considered as a proxy error, not a wrong/unavailable address. For example, if a proxy will return a ``404 Not Found`` response - this will be considered as an error of a proxy. Checks only for HTTP protocol, HTTPS not supported at the moment. By default the list is empty and the response code is not verified :param int backlog: (optional) The maximum number of queued connections passed to listen. The default value is 100 :raises ValueError: If :attr:`limit` is less than or equal to zero. Because a parsing of providers will be endless .. versionadded:: 0.2.0 """ if limit <= 0: raise ValueError( 'In serve mode value of the limit cannot be less than or ' 'equal to zero. Otherwise, a parsing of providers will be ' 'endless' ) self._server = Server( host=host, port=port, proxies=self._proxies, timeout=self._timeout, max_tries=kwargs.pop('max_tries', self._max_tries), loop=self._loop, **kwargs, ) self._server.start() task = asyncio.ensure_future(self.find(limit=limit, **kwargs)) self._all_tasks.append(task) async def _load(self, data, check=True): """Looking for proxies in the passed data. Transform the passed data from [raw string | file-like object | list] to set {(host, port), ...}: {('192.168.0.1', '80'), } """ log.debug('Load proxies from the raw data') if isinstance(data, io.TextIOWrapper): data = data.read() if isinstance(data, str): data = IPPortPatternLine.findall(data) proxies = set(data) for proxy in proxies: await self._handle(proxy, check=check) await self._on_check.join() self._done() async def _grab(self, types=None, check=False): def _get_tasks(by=MAX_CONCURRENT_PROVIDERS): providers = [ pr for pr in self._providers if not types or not pr.proto or bool(pr.proto & types.keys()) ] while providers: tasks = [ asyncio.ensure_future(pr.get_proxies()) for pr in providers[:by] ] del providers[:by] self._all_tasks.extend(tasks) yield tasks log.debug('Start grabbing proxies') while True: for tasks in _get_tasks(): for task in asyncio.as_completed(tasks): proxies = await task for proxy in proxies: await self._handle(proxy, check=check) log.debug('Grab cycle is complete') if self._server: log.debug('fall asleep for %d seconds' % GRAB_PAUSE) await asyncio.sleep(GRAB_PAUSE) log.debug('awaked') else: break await self._on_check.join() self._done() async def _handle(self, proxy, check=False): try: proxy = await Proxy.create( *proxy, timeout=self._timeout, resolver=self._resolver, verify_ssl=self._verify_ssl, loop=self._loop, )
except (ResolveError, ValueError):
1
2023-11-05 13:28:57+00:00
24k
radekd91/inferno
inferno/models/DECA.py
[ { "identifier": "EmoNetLoss", "path": "inferno/layers/losses/EmoNetLoss.py", "snippet": "class EmoNetLoss(EmoLossBase):\n# class EmoNetLoss(object):\n\n def __init__(self, device, emonet=None, trainable=False, normalize_features=False, emo_feat_loss=None, au_loss=None):\n if emonet is None:\n emonet = get_emonet(device).eval()\n\n last_feature_size = 256 # TODO: fix this hardcoded number, get it from EmoNet class instead\n if isinstance(emo_feat_loss, dict ) and \"barlow_twins\" in emo_feat_loss[\"type\"]:\n # if barlow twins, we need to know the feature size\n emo_feat_loss[\"feature_size\"] = last_feature_size\n\n super().__init__(trainable, normalize_features=normalize_features, emo_feat_loss=emo_feat_loss, au_loss=au_loss,\n last_feature_size=last_feature_size)\n self.emonet = emonet\n\n # elif isinstance(emonet, str):\n # path = Path(emonet)\n # if path.is_dir():\n # print(f\"Loading trained EmoNet from: '{path}'\")\n # def load_configs(run_path):\n # from omegaconf import OmegaConf\n # with open(Path(run_path) / \"cfg.yaml\", \"r\") as f:\n # conf = OmegaConf.load(f)\n # return conf\n #\n # cfg = load_configs(path)\n # checkpoint_mode = 'best'\n # stages_prefixes = \"\"\n #\n # checkpoint, checkpoint_kwargs = get_checkpoint_with_kwargs(cfg, stages_prefixes,\n # checkpoint_mode=checkpoint_mode,\n # # relative_to=relative_to_path,\n # # replace_root=replace_root_path\n # )\n # checkpoint_kwargs = checkpoint_kwargs or {}\n # emonet_module = EmoNetModule.load_from_checkpoint(checkpoint_path=checkpoint, strict=False, **checkpoint_kwargs)\n # self.emonet = emonet_module.backbone\n # else:\n # raise ValueError(\"Please specify the directory which contains the config of the trained Emonet.\")\n\n # else:\n # self.emonet = emonet\n\n if not trainable:\n self.emonet.eval()\n self.emonet.requires_grad_(False)\n else:\n self.emonet.train()\n self.emonet.emo_parameters_requires_grad(True)\n\n # self.emonet.eval()\n # self.emonet = self.emonet.requires_grad_(False)\n # self.transforms = Resize((256, 256))\n self.size = (256, 256)\n # self.emo_feat_loss = F.l1_loss\n # self.valence_loss = F.l1_loss\n # self.arousal_loss = F.l1_loss\n # # self.expression_loss = F.kl_div\n # self.expression_loss = F.l1_loss\n # self.input_emotion = None\n # self.output_emotion = None\n\n @property\n def network(self):\n return self.emonet\n\n def to(self, *args, **kwargs):\n self.emonet = self.emonet.to(*args, **kwargs)\n # self.emonet = self.emonet.requires_grad_(False)\n # for p in self.emonet.parameters():\n # p.requires_grad = False\n\n def eval(self):\n self.emonet = self.emonet.eval()\n # self.emonet = self.emonet.requires_grad_(False)\n # for p in self.emonet.parameters():\n # p.requires_grad = False\n\n def train(self, mode: bool = True):\n super().train(mode)\n if hasattr(self, 'emonet'):\n self.emonet = self.emonet.eval() # evaluation mode no matter what, it's just a loss function\n # self.emonet = self.emonet.requires_grad_(False)\n # for p in self.emonet.parameters():\n # p.requires_grad = False\n\n def forward(self, predicted, target, *args, **kwargs):\n res = self.compute_loss(target, predicted, *args, **kwargs)\n feat_2_loss = res[1]\n return feat_2_loss\n\n def emonet_out(self, images):\n images = F.interpolate(images, self.size, mode='bilinear')\n # images = self.transform(images)\n return self.emonet(images, intermediate_features=True)\n\n\n def _get_trainable_params(self):\n if self.trainable:\n return self.emonet.emo_parameters\n return []" }, { "identifier": "create_emo_loss", "path": "inferno/layers/losses/EmoNetLoss.py", "snippet": "def create_emo_loss(device, emoloss = None, trainable=False, dual=False, normalize_features=False, emo_feat_loss=None):\n if emoloss is None:\n return EmoNetLoss(device, emonet=emoloss)\n if isinstance(emoloss, str):\n path = Path(emoloss)\n if not path.is_absolute():\n path = Path(get_path_to_assets()) / path\n if path.is_dir():\n from inferno.layers.losses.emotion_loss_loader import emo_network_from_path\n emo_loss = emo_network_from_path(path)\n\n if isinstance(emo_loss, EmoNetModule):\n emonet = emo_loss.emonet\n print(\"Creating EmoNetLoss\")\n return EmoNetLoss(device, emonet=emonet, trainable=trainable,\n normalize_features=normalize_features, emo_feat_loss=emo_feat_loss)\n else:\n if not dual:\n print(f\"Creating EmoBackboneLoss, trainable={trainable}\")\n return EmoBackboneLoss(device, emo_loss, trainable=trainable,\n normalize_features=normalize_features, emo_feat_loss=emo_feat_loss)\n else:\n print(f\"Creating EmoBackboneDualLoss\")\n return EmoBackboneDualLoss(device, emo_loss, trainable=trainable, clone_is_trainable=True,\n normalize_features=normalize_features, emo_feat_loss=emo_feat_loss)\n else:\n raise ValueError(\"Please specify the directory which contains the config of the trained Emonet.\")\n else: \n raise TypeError(f\"Wrong type of emoloss: {type(emoloss)}\")" }, { "identifier": "create_au_loss", "path": "inferno/layers/losses/EmoNetLoss.py", "snippet": "def create_au_loss(device, au_loss):\n if au_loss is None:\n raise NotImplementedError(\"Pass an au_loss config.\")\n # return EmoNetLoss(device, emonet=au_loss)\n if isinstance(au_loss, (dict, omegaconf.DictConfig)):\n path = Path(au_loss.path)\n if path.is_dir():\n au_loss_net = emo_network_from_path(path)\n\n if isinstance(au_loss_net, EmoNetModule):\n emonet = au_loss_net.emonet\n print(\"Creating EmoNetLoss\")\n return EmoNetLoss(device,\n emonet=emonet,\n trainable=au_loss.trainable,\n normalize_features=au_loss.normalize_features,\n emo_feat_loss=au_loss.feat_loss,\n au_loss=au_loss.au_loss)\n else:\n if not au_loss.dual:\n print(f\"Creating EmoBackboneLoss, trainable={au_loss.trainable}\")\n return EmoBackboneLoss(device, au_loss_net,\n trainable=au_loss.trainable,\n normalize_features=au_loss.normalize_features,\n emo_feat_loss=au_loss.feat_loss, \n au_loss=au_loss.au_loss\n )\n else:\n print(f\"Creating EmoBackboneDualLoss\")\n return EmoBackboneDualLoss(device, au_loss_net,\n trainable=au_loss.trainable,\n clone_is_trainable=True,\n normalize_features=au_loss.normalize_features,\n emo_feat_loss=au_loss.feat_loss,\n au_loss=au_loss.au_loss)\n else:\n raise ValueError(\"Please specify the config to instantiate AU loss\")" }, { "identifier": "SRenderY", "path": "inferno/models/Renderer.py", "snippet": "class SRenderY(nn.Module):\n def __init__(self, image_size, obj_filename, uv_size=256):\n super(SRenderY, self).__init__()\n self.image_size = image_size\n self.uv_size = uv_size\n\n verts, faces, aux = load_obj(obj_filename)\n uvcoords = aux.verts_uvs[None, ...] # (N, V, 2)\n uvfaces = faces.textures_idx[None, ...] # (N, F, 3)\n faces = faces.verts_idx[None, ...]\n self.rasterizer = Pytorch3dRasterizer(image_size)\n self.uv_rasterizer = Pytorch3dRasterizer(uv_size)\n\n # faces\n dense_triangles = util.generate_triangles(uv_size, uv_size)\n self.register_buffer('dense_faces', torch.from_numpy(dense_triangles).long()[None, :, :])\n self.register_buffer('faces', faces)\n self.register_buffer('raw_uvcoords', uvcoords)\n\n # uv coords\n uvcoords = torch.cat([uvcoords, uvcoords[:, :, 0:1] * 0. + 1.], -1) # [bz, ntv, 3]\n uvcoords = uvcoords * 2 - 1;\n uvcoords[..., 1] = -uvcoords[..., 1]\n face_uvcoords = util.face_vertices(uvcoords, uvfaces)\n self.register_buffer('uvcoords', uvcoords)\n self.register_buffer('uvfaces', uvfaces)\n self.register_buffer('face_uvcoords', face_uvcoords)\n\n # shape colors, for rendering shape overlay\n colors = torch.tensor([180, 180, 180])[None, None, :].repeat(1, faces.max() + 1, 1).float() / 255.\n face_colors = util.face_vertices(colors, faces)\n self.register_buffer('face_colors', face_colors)\n\n ## SH factors for lighting\n pi = np.pi\n constant_factor = torch.tensor(\n [1 / np.sqrt(4 * pi), ((2 * pi) / 3) * (np.sqrt(3 / (4 * pi))), ((2 * pi) / 3) * (np.sqrt(3 / (4 * pi))), \\\n ((2 * pi) / 3) * (np.sqrt(3 / (4 * pi))), (pi / 4) * (3) * (np.sqrt(5 / (12 * pi))),\n (pi / 4) * (3) * (np.sqrt(5 / (12 * pi))), \\\n (pi / 4) * (3) * (np.sqrt(5 / (12 * pi))), (pi / 4) * (3 / 2) * (np.sqrt(5 / (12 * pi))),\n (pi / 4) * (1 / 2) * (np.sqrt(5 / (4 * pi)))]).float()\n self.register_buffer('constant_factor', constant_factor)\n\n def forward(self, vertices, transformed_vertices, albedos, lights=None, light_type='point'):\n '''\n -- Texture Rendering\n vertices: [batch_size, V, 3], vertices in world space, for calculating normals, then shading\n transformed_vertices: [batch_size, V, 3], rnage:[-1,1], projected vertices, in image space, for rasterization\n albedos: [batch_size, 3, h, w], uv map\n lights:\n spherical homarnic: [N, 9(shcoeff), 3(rgb)]\n points/directional lighting: [N, n_lights, 6(xyzrgb)]\n light_type:\n point or directional\n '''\n batch_size = vertices.shape[0]\n ## rasterizer near 0 far 100. move mesh so minz larger than 0\n transformed_vertices[:, :, 2] = transformed_vertices[:, :, 2] + 10\n\n # attributes\n face_vertices = util.face_vertices(vertices, self.faces.expand(batch_size, -1, -1))\n normals = util.vertex_normals(vertices, self.faces.expand(batch_size, -1, -1))\n face_normals = util.face_vertices(normals, self.faces.expand(batch_size, -1, -1))\n transformed_normals = util.vertex_normals(transformed_vertices, self.faces.expand(batch_size, -1, -1))\n transformed_face_normals = util.face_vertices(transformed_normals, self.faces.expand(batch_size, -1, -1))\n\n attributes = torch.cat([self.face_uvcoords.expand(batch_size, -1, -1, -1),\n transformed_face_normals.detach(),\n face_vertices.detach(),\n face_normals],\n -1)\n\n # rasterize\n rendering = self.rasterizer(transformed_vertices, self.faces.expand(batch_size, -1, -1), attributes)\n\n ####\n # vis mask\n alpha_images = rendering[:, -1, :, :][:, None, :, :].detach()\n\n # albedo\n uvcoords_images = rendering[:, :3, :, :]\n grid = (uvcoords_images).permute(0, 2, 3, 1)[:, :, :, :2]\n albedo_images = F.grid_sample(albedos, grid, align_corners=False)\n\n # visible mask for pixels with positive normal direction\n transformed_normal_map = rendering[:, 3:6, :, :].detach()\n pos_mask = (transformed_normal_map[:, 2:, :, :] < -0.05).float()\n\n # shading\n normal_images = rendering[:, 9:12, :, :]\n if lights is not None:\n if lights.shape[1] == 9:\n shading_images = self.add_SHlight(normal_images, lights)\n else:\n if light_type == 'point':\n vertice_images = rendering[:, 6:9, :, :].detach()\n shading = self.add_pointlight(vertice_images.permute(0, 2, 3, 1).reshape([batch_size, -1, 3]),\n normal_images.permute(0, 2, 3, 1).reshape([batch_size, -1, 3]),\n lights)\n shading_images = shading.reshape(\n [batch_size, albedo_images.shape[2], albedo_images.shape[3], 3]).permute(0, 3, 1, 2)\n else:\n shading = self.add_directionlight(normal_images.permute(0, 2, 3, 1).reshape([batch_size, -1, 3]),\n lights)\n shading_images = shading.reshape(\n [batch_size, albedo_images.shape[2], albedo_images.shape[3], 3]).permute(0, 3, 1, 2)\n images = albedo_images * shading_images\n else:\n images = albedo_images\n shading_images = images.detach() * 0.\n # import ipdb; ipdb.set_trace()\n # print('albedo: ', albedo_images.min(), albedo_images.max())\n # print('normal: ', normal_images.min(), normal_images.max())\n # print('lights: ', lights.min(), lights.max())\n # print('shading: ', shading_images.min(), shading_images.max())\n # print('images: ', images.min(), images.max())\n # exit()\n outputs = {\n 'images': images * alpha_images,\n 'albedo_images': albedo_images,\n 'alpha_images': alpha_images,\n 'pos_mask': pos_mask,\n 'shading_images': shading_images,\n 'grid': grid,\n 'normals': normals,\n 'normal_images': normal_images,\n 'transformed_normals': transformed_normals,\n }\n\n return outputs\n\n def add_SHlight(self, normal_images, sh_coeff):\n '''\n sh_coeff: [bz, 9, 3]\n '''\n N = normal_images\n sh = torch.stack([\n N[:, 0] * 0. + 1., N[:, 0], N[:, 1], \\\n N[:, 2], N[:, 0] * N[:, 1], N[:, 0] * N[:, 2],\n N[:, 1] * N[:, 2], N[:, 0] ** 2 - N[:, 1] ** 2, 3 * (N[:, 2] ** 2) - 1\n ],\n 1) # [bz, 9, h, w]\n sh = sh * self.constant_factor[None, :, None, None]\n shading = torch.sum(sh_coeff[:, :, :, None, None] * sh[:, :, None, :, :], 1) # [bz, 9, 3, h, w]\n return shading\n\n def add_pointlight(self, vertices, normals, lights):\n '''\n vertices: [bz, nv, 3]\n lights: [bz, nlight, 6]\n returns:\n shading: [bz, nv, 3]\n '''\n light_positions = lights[:, :, :3];\n light_intensities = lights[:, :, 3:]\n directions_to_lights = F.normalize(light_positions[:, :, None, :] - vertices[:, None, :, :], dim=3)\n # normals_dot_lights = torch.clamp((normals[:,None,:,:]*directions_to_lights).sum(dim=3), 0., 1.)\n normals_dot_lights = (normals[:, None, :, :] * directions_to_lights).sum(dim=3)\n shading = normals_dot_lights[:, :, :, None] * light_intensities[:, :, None, :]\n return shading.mean(1)\n\n def add_directionlight(self, normals, lights):\n '''\n normals: [bz, nv, 3]\n lights: [bz, nlight, 6]\n returns:\n shading: [bz, nv, 3]\n '''\n light_direction = lights[:, :, :3];\n light_intensities = lights[:, :, 3:]\n directions_to_lights = F.normalize(light_direction[:, :, None, :].expand(-1, -1, normals.shape[1], -1), dim=3)\n # normals_dot_lights = torch.clamp((normals[:,None,:,:]*directions_to_lights).sum(dim=3), 0., 1.)\n # normals_dot_lights = (normals[:,None,:,:]*directions_to_lights).sum(dim=3)\n normals_dot_lights = torch.clamp((normals[:, None, :, :] * directions_to_lights).sum(dim=3), 0., 1.)\n shading = normals_dot_lights[:, :, :, None] * light_intensities[:, :, None, :]\n return shading.mean(1)\n\n def render_shape(self, vertices, transformed_vertices, images=None, detail_normal_images=None, lights=None):\n '''\n -- rendering shape with detail normal map\n '''\n batch_size = vertices.shape[0]\n if lights is None:\n light_positions = torch.tensor(\n [\n [-1, 1, 1],\n [1, 1, 1],\n [-1, -1, 1],\n [1, -1, 1],\n [0, 0, 1]\n ]\n )[None, :, :].expand(batch_size, -1, -1).float()\n light_intensities = torch.ones_like(light_positions).float() * 1.7\n lights = torch.cat((light_positions, light_intensities), 2).to(vertices.device)\n transformed_vertices[:, :, 2] = transformed_vertices[:, :, 2] + 10\n\n # Attributes\n face_vertices = util.face_vertices(vertices, self.faces.expand(batch_size, -1, -1))\n normals = util.vertex_normals(vertices, self.faces.expand(batch_size, -1, -1));\n face_normals = util.face_vertices(normals, self.faces.expand(batch_size, -1, -1))\n transformed_normals = util.vertex_normals(transformed_vertices, self.faces.expand(batch_size, -1, -1));\n transformed_face_normals = util.face_vertices(transformed_normals, self.faces.expand(batch_size, -1, -1))\n attributes = torch.cat([self.face_colors.expand(batch_size, -1, -1, -1),\n transformed_face_normals.detach(),\n face_vertices.detach(),\n face_normals],\n -1)\n # rasterize\n rendering = self.rasterizer(transformed_vertices, self.faces.expand(batch_size, -1, -1), attributes)\n\n ####\n alpha_images = rendering[:, -1, :, :][:, None, :, :].detach()\n\n # albedo\n albedo_images = rendering[:, :3, :, :]\n # mask\n transformed_normal_map = rendering[:, 3:6, :, :].detach()\n pos_mask = (transformed_normal_map[:, 2:, :, :] < 0).float()\n\n # shading\n normal_images = rendering[:, 9:12, :, :].detach()\n vertice_images = rendering[:, 6:9, :, :].detach()\n if detail_normal_images is not None:\n normal_images = detail_normal_images\n\n shading = self.add_directionlight(normal_images.permute(0, 2, 3, 1).reshape([batch_size, -1, 3]), lights)\n shading_images = shading.reshape([batch_size, albedo_images.shape[2], albedo_images.shape[3], 3]).permute(0, 3,\n 1,\n 2).contiguous()\n shaded_images = albedo_images * shading_images\n\n if images is None:\n shape_images = shaded_images * alpha_images + torch.zeros_like(shaded_images).to(vertices.device) * (\n 1 - alpha_images)\n else:\n shape_images = shaded_images * alpha_images + images * (1 - alpha_images)\n return shape_images\n\n def render_depth(self, transformed_vertices):\n '''\n -- rendering depth\n '''\n batch_size = transformed_vertices.shape[0]\n\n transformed_vertices[:, :, 2] = transformed_vertices[:, :, 2] - transformed_vertices[:, :, 2].min()\n z = -transformed_vertices[:, :, 2:].repeat(1, 1, 3)\n z = z - z.min()\n z = z / z.max()\n # Attributes\n attributes = util.face_vertices(z, self.faces.expand(batch_size, -1, -1))\n # rasterize\n rendering = self.rasterizer(transformed_vertices, self.faces.expand(batch_size, -1, -1), attributes)\n\n ####\n alpha_images = rendering[:, -1, :, :][:, None, :, :].detach()\n depth_images = rendering[:, :1, :, :]\n return depth_images\n\n def render_normal(self, transformed_vertices, normals):\n '''\n -- rendering normal\n '''\n batch_size = normals.shape[0]\n\n # Attributes\n attributes = util.face_vertices(normals, self.faces.expand(batch_size, -1, -1))\n # rasterize\n rendering = self.rasterizer(transformed_vertices, self.faces.expand(batch_size, -1, -1), attributes)\n\n ####\n alpha_images = rendering[:, -1, :, :][:, None, :, :].detach()\n normal_images = rendering[:, :3, :, :]\n return normal_images\n\n def world2uv(self, vertices):\n '''\n project vertices from world space to uv space\n vertices: [bz, V, 3]\n uv_vertices: [bz, 3, h, w]\n '''\n batch_size = vertices.shape[0]\n face_vertices = util.face_vertices(vertices, self.faces.expand(batch_size, -1, -1))\n uv_vertices = self.uv_rasterizer(self.uvcoords.expand(batch_size, -1, -1),\n self.uvfaces.expand(batch_size, -1, -1), face_vertices)[:, :3]\n return uv_vertices" }, { "identifier": "ResnetEncoder", "path": "inferno/models/DecaEncoder.py", "snippet": "class ResnetEncoder(BaseEncoder):\n def __init__(self, outsize, last_op=None):\n super(ResnetEncoder, self).__init__(outsize, last_op)\n # feature_size = 2048\n # self.encoder = resnet.load_ResNet50Model() # out: 2048\n # ### regressor\n # self.layers = nn.Sequential(\n # nn.Linear(feature_size, 1024),\n # nn.ReLU(),\n # nn.Linear(1024, outsize)\n # )\n # self.last_op = last_op\n\n def _create_encoder(self):\n self.encoder = resnet.load_ResNet50Model() # out: 2048" }, { "identifier": "SecondHeadResnet", "path": "inferno/models/DecaEncoder.py", "snippet": "class SecondHeadResnet(nn.Module):\n\n def __init__(self, enc : BaseEncoder, outsize, last_op=None):\n super().__init__()\n self.resnet = enc # yes, self.resnet is no longer accurate but the name is kept for legacy reasons (to be able to load old models)\n self.layers = nn.Sequential(\n nn.Linear(self.resnet.feature_size, 1024),\n nn.ReLU(),\n nn.Linear(1024, outsize)\n )\n if last_op == 'same':\n self.last_op = self.resnet.last_op\n else:\n self.last_op = last_op\n\n def forward_features(self, inputs):\n out1, features = self.resnet(inputs, output_features=True)\n return out1, features\n\n def forward_features_to_output(self, features):\n parameters = self.layers(features)\n if self.last_op:\n parameters = self.last_op(parameters)\n return parameters\n\n\n def forward(self, inputs):\n out1, features = self.forward_features()\n out2 = self.forward_features_to_output(features)\n return out1, out2\n\n\n def train(self, mode: bool = True):\n #here we NEVER modify the eval/train status of the resnet backbone, only the FC layers of the second head\n self.layers.train(mode)\n return self\n\n def reset_last_layer(self):\n # initialize the last layer to zero to help the network \n # predict the initial pose a bit more stable\n torch.nn.init.constant_(self.layers[-1].weight, 0)\n torch.nn.init.constant_(self.layers[-1].bias, 0)\n\n def get_feature_size(self): \n return self.resnet.feature_size" }, { "identifier": "SwinEncoder", "path": "inferno/models/DecaEncoder.py", "snippet": "class SwinEncoder(BaseEncoder):\n\n def __init__(self, swin_type, img_size, outsize, last_op=None):\n self.swin_type = swin_type\n self.img_size = img_size\n super().__init__(outsize, last_op)\n\n def _create_encoder(self):\n swin_cfg = swin_cfg_from_name(self.swin_type)\n self.encoder = create_swin_backbone(\n swin_cfg, self.feature_size, self.img_size, load_pretrained_swin=True, pretrained_model=self.swin_type)\n\n\n def forward_features(self, inputs):\n pooled_feature, patches = self.encoder(inputs, include_features=True, include_patches=False)\n return pooled_feature, patches" }, { "identifier": "Generator", "path": "inferno/models/DecaDecoder.py", "snippet": "class Generator(nn.Module):\n def __init__(self, latent_dim=100, out_channels=1, out_scale=1, sample_mode='bilinear'):\n super(Generator, self).__init__()\n self.out_scale = out_scale\n\n self.init_size = 32 // 4 # Initial size before upsampling\n self.l1 = nn.Sequential(nn.Linear(latent_dim, 128 * self.init_size ** 2))\n self.conv_blocks = nn.Sequential(\n nn.BatchNorm2d(128),\n nn.Upsample(scale_factor=2, mode=sample_mode), # 16\n nn.Conv2d(128, 128, 3, stride=1, padding=1),\n nn.BatchNorm2d(128, 0.8),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Upsample(scale_factor=2, mode=sample_mode), # 32\n nn.Conv2d(128, 64, 3, stride=1, padding=1),\n nn.BatchNorm2d(64, 0.8),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Upsample(scale_factor=2, mode=sample_mode), # 64\n nn.Conv2d(64, 64, 3, stride=1, padding=1),\n nn.BatchNorm2d(64, 0.8),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Upsample(scale_factor=2, mode=sample_mode), # 128\n nn.Conv2d(64, 32, 3, stride=1, padding=1),\n nn.BatchNorm2d(32, 0.8),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Upsample(scale_factor=2, mode=sample_mode), # 256\n nn.Conv2d(32, 16, 3, stride=1, padding=1),\n nn.BatchNorm2d(16, 0.8),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(16, out_channels, 3, stride=1, padding=1),\n nn.Tanh(),\n )\n\n def forward(self, z):\n out = self.l1(z)\n out = out.view(out.shape[0], 128, self.init_size, self.init_size)\n img = self.conv_blocks(out)\n return img * self.out_scale" }, { "identifier": "GeneratorAdaIn", "path": "inferno/models/DecaDecoder.py", "snippet": "class GeneratorAdaIn(nn.Module):\n def __init__(self, latent_dim, condition_dim, out_channels=1, out_scale=1, sample_mode='bilinear'):\n super().__init__()\n self.out_scale = out_scale\n\n self.init_size = 32 // 4 # Initial size before upsampling\n self.l1 = nn.Sequential(nn.Linear(latent_dim, 128 * self.init_size ** 2))\n # self.conv_blocks = nn.Sequential(\n # # nn.BatchNorm2d(128),\n # # nn.Upsample(scale_factor=2, mode=sample_mode), # 16\n # # nn.Conv2d(128, 128, 3, stride=1, padding=1),\n # AdaInUpConvBlock(128,128, condition_dim),\n # # nn.BatchNorm2d(128, 0.8),\n # # nn.LeakyReLU(0.2, inplace=True),\n # # nn.Upsample(scale_factor=2, mode=sample_mode), # 32\n # # nn.Conv2d(128, 64, 3, stride=1, padding=1),\n # AdaInUpConvBlock(128, 64, condition_dim),\n # # nn.BatchNorm2d(64, 0.8),\n # # nn.LeakyReLU(0.2, inplace=True),\n # # nn.Upsample(scale_factor=2, mode=sample_mode), # 64\n # # nn.Conv2d(64, 64, 3, stride=1, padding=1),\n # AdaInUpConvBlock(64, 64, condition_dim),\n # # nn.BatchNorm2d(64, 0.8),\n # # nn.LeakyReLU(0.2, inplace=True),\n # # nn.Upsample(scale_factor=2, mode=sample_mode), # 128\n # # nn.Conv2d(64, 32, 3, stride=1, padding=1),\n # AdaInUpConvBlock(64, 32, condition_dim),\n # # nn.BatchNorm2d(32, 0.8),\n # # nn.LeakyReLU(0.2, inplace=True),\n # # nn.Upsample(scale_factor=2, mode=sample_mode), # 256\n # # nn.Conv2d(32, 16, 3, stride=1, padding=1),\n # AdaInUpConvBlock(32, 16, condition_dim),\n # # nn.BatchNorm2d(16, 0.8),\n # # nn.LeakyReLU(0.2, inplace=True),\n # # nn.Conv2d(16, out_channels, 3, stride=1, padding=1),\n # AdaInUpConvBlock(16, out_channels, condition_dim, scale_factor=0)\n # nn.Tanh(),\n # )\n self.conv_block1 = AdaInUpConvBlock(128,128, condition_dim, sample_mode=sample_mode) # 16\n self.conv_block2 = AdaInUpConvBlock(128, 64, condition_dim, sample_mode=sample_mode) # 32\n self.conv_block3 = AdaInUpConvBlock(64, 64, condition_dim, sample_mode=sample_mode) # 64\n self.conv_block4 = AdaInUpConvBlock(64, 32, condition_dim, sample_mode=sample_mode) # 128\n self.conv_block5 = AdaInUpConvBlock(32, 16, condition_dim, sample_mode=sample_mode) # 256\n self.conv_block6 = AdaInUpConvBlock(16, out_channels, condition_dim, scale_factor=0) # 256\n self.conv_blocks = [self.conv_block1, self.conv_block2, self.conv_block3, self.conv_block4,\n self.conv_block5, self.conv_block6]\n self.out_actv = nn.Tanh()\n\n\n def forward(self, z, cond):\n out = self.l1(z)\n out = out.view(out.shape[0], 128, self.init_size, self.init_size)\n for i, block in enumerate(self.conv_blocks):\n out = block(out, cond)\n img = self.out_actv(out)\n return img * self.out_scale" }, { "identifier": "FLAME", "path": "inferno/models/DecaFLAME.py", "snippet": "class FLAME(nn.Module):\n \"\"\"\n Given flame parameters this class generates a differentiable FLAME function\n which outputs the a mesh and 2D/3D facial landmarks\n \"\"\"\n\n def __init__(self, config):\n super(FLAME, self).__init__()\n print(\"creating the FLAME Decoder\")\n with open(config.flame_model_path, 'rb') as f:\n # flame_model = Struct(**pickle.load(f, encoding='latin1'))\n ss = pickle.load(f, encoding='latin1')\n flame_model = Struct(**ss)\n\n self.cfg = config\n self.dtype = torch.float32\n self.register_buffer('faces_tensor', to_tensor(to_np(flame_model.f, dtype=np.int64), dtype=torch.long))\n # The vertices of the template model\n self.register_buffer('v_template', to_tensor(to_np(flame_model.v_template), dtype=self.dtype))\n # The shape components and expression\n shapedirs = to_tensor(to_np(flame_model.shapedirs), dtype=self.dtype)\n shapedirs = torch.cat([shapedirs[:, :, :config.n_shape], shapedirs[:, :, 300:300 + config.n_exp]], 2)\n self.register_buffer('shapedirs', shapedirs)\n # The pose components\n num_pose_basis = flame_model.posedirs.shape[-1]\n posedirs = np.reshape(flame_model.posedirs, [-1, num_pose_basis]).T\n self.register_buffer('posedirs', to_tensor(to_np(posedirs), dtype=self.dtype))\n #\n self.register_buffer('J_regressor', to_tensor(to_np(flame_model.J_regressor), dtype=self.dtype))\n parents = to_tensor(to_np(flame_model.kintree_table[0])).long();\n parents[0] = -1\n self.register_buffer('parents', parents)\n self.register_buffer('lbs_weights', to_tensor(to_np(flame_model.weights), dtype=self.dtype))\n\n # Fixing Eyeball and neck rotation\n default_eyball_pose = torch.zeros([1, 6], dtype=self.dtype, requires_grad=False)\n self.register_parameter('eye_pose', nn.Parameter(default_eyball_pose,\n requires_grad=False))\n default_neck_pose = torch.zeros([1, 3], dtype=self.dtype, requires_grad=False)\n self.register_parameter('neck_pose', nn.Parameter(default_neck_pose,\n requires_grad=False))\n\n # Static and Dynamic Landmark embeddings for FLAME\n lmk_embeddings = np.load(config.flame_lmk_embedding_path, allow_pickle=True, encoding='latin1')\n lmk_embeddings = lmk_embeddings[()]\n self.register_buffer('lmk_faces_idx', torch.tensor(lmk_embeddings['static_lmk_faces_idx'], dtype=torch.long))\n self.register_buffer('lmk_bary_coords',\n torch.tensor(lmk_embeddings['static_lmk_bary_coords'], dtype=self.dtype))\n self.register_buffer('dynamic_lmk_faces_idx',\n torch.tensor(lmk_embeddings['dynamic_lmk_faces_idx'], dtype=torch.long))\n self.register_buffer('dynamic_lmk_bary_coords',\n torch.tensor(lmk_embeddings['dynamic_lmk_bary_coords'], dtype=self.dtype))\n self.register_buffer('full_lmk_faces_idx', torch.tensor(lmk_embeddings['full_lmk_faces_idx'], dtype=torch.long))\n self.register_buffer('full_lmk_bary_coords',\n torch.tensor(lmk_embeddings['full_lmk_bary_coords'], dtype=self.dtype))\n\n neck_kin_chain = [];\n NECK_IDX = 1\n curr_idx = torch.tensor(NECK_IDX, dtype=torch.long)\n while curr_idx != -1:\n neck_kin_chain.append(curr_idx)\n curr_idx = self.parents[curr_idx]\n self.register_buffer('neck_kin_chain', torch.stack(neck_kin_chain))\n\n def _find_dynamic_lmk_idx_and_bcoords(self, pose, dynamic_lmk_faces_idx,\n dynamic_lmk_b_coords,\n neck_kin_chain, dtype=torch.float32):\n \"\"\"\n Selects the face contour depending on the reletive position of the head\n Input:\n vertices: N X num_of_vertices X 3\n pose: N X full pose\n dynamic_lmk_faces_idx: The list of contour face indexes\n dynamic_lmk_b_coords: The list of contour barycentric weights\n neck_kin_chain: The tree to consider for the relative rotation\n dtype: Data type\n return:\n The contour face indexes and the corresponding barycentric weights\n \"\"\"\n\n batch_size = pose.shape[0]\n\n aa_pose = torch.index_select(pose.view(batch_size, -1, 3), 1,\n neck_kin_chain)\n rot_mats = batch_rodrigues(\n aa_pose.view(-1, 3), dtype=dtype).view(batch_size, -1, 3, 3)\n\n rel_rot_mat = torch.eye(3, device=pose.device,\n dtype=dtype).unsqueeze_(dim=0).expand(batch_size, -1, -1)\n for idx in range(len(neck_kin_chain)):\n rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat)\n\n y_rot_angle = torch.round(\n torch.clamp(rot_mat_to_euler(rel_rot_mat) * 180.0 / np.pi,\n max=39)).to(dtype=torch.long)\n\n neg_mask = y_rot_angle.lt(0).to(dtype=torch.long)\n mask = y_rot_angle.lt(-39).to(dtype=torch.long)\n neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle)\n y_rot_angle = (neg_mask * neg_vals +\n (1 - neg_mask) * y_rot_angle)\n\n dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx,\n 0, y_rot_angle)\n dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords,\n 0, y_rot_angle)\n return dyn_lmk_faces_idx, dyn_lmk_b_coords\n\n def _vertices2landmarks(self, vertices, faces, lmk_faces_idx, lmk_bary_coords):\n \"\"\"\n Calculates landmarks by barycentric interpolation\n Input:\n vertices: torch.tensor NxVx3, dtype = torch.float32\n The tensor of input vertices\n faces: torch.tensor (N*F)x3, dtype = torch.long\n The faces of the mesh\n lmk_faces_idx: torch.tensor N X L, dtype = torch.long\n The tensor with the indices of the faces used to calculate the\n landmarks.\n lmk_bary_coords: torch.tensor N X L X 3, dtype = torch.float32\n The tensor of barycentric coordinates that are used to interpolate\n the landmarks\n\n Returns:\n landmarks: torch.tensor NxLx3, dtype = torch.float32\n The coordinates of the landmarks for each mesh in the batch\n \"\"\"\n # Extract the indices of the vertices for each face\n # NxLx3\n batch_size, num_verts = vertices.shape[:2]\n lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1)).view(\n 1, -1, 3).view(batch_size, lmk_faces_idx.shape[1], -1)\n\n lmk_faces += torch.arange(batch_size, dtype=torch.long).view(-1, 1, 1).to(\n device=vertices.device) * num_verts\n\n lmk_vertices = vertices.view(-1, 3)[lmk_faces]\n landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords])\n return landmarks\n\n def _vertices2landmarks2d(self, vertices, full_pose):\n \"\"\"\n Calculates landmarks by barycentric interpolation\n Input:\n vertices: torch.tensor NxVx3, dtype = torch.float32\n The tensor of input vertices\n full_pose: torch.tensor N X 12, dtype = torch.float32\n The tensor with global pose, neck pose, jaw pose and eye pose (respectively) in axis angle format\n\n Returns:\n landmarks: torch.tensor NxLx3, dtype = torch.float32\n The coordinates of the landmarks for each mesh in the batch\n \"\"\"\n # Extract the indices of the vertices for each face\n # NxLx3\n batch_size = vertices.shape[0]\n lmk_faces_idx = self.lmk_faces_idx.unsqueeze(dim=0).expand(batch_size, -1)\n lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).expand(batch_size, -1, -1)\n\n dyn_lmk_faces_idx, dyn_lmk_bary_coords = self._find_dynamic_lmk_idx_and_bcoords(\n full_pose, self.dynamic_lmk_faces_idx,\n self.dynamic_lmk_bary_coords,\n self.neck_kin_chain, dtype=self.dtype)\n lmk_faces_idx = torch.cat([dyn_lmk_faces_idx, lmk_faces_idx], 1)\n lmk_bary_coords = torch.cat([dyn_lmk_bary_coords, lmk_bary_coords], 1)\n\n landmarks2d = vertices2landmarks(vertices, self.faces_tensor,\n lmk_faces_idx,\n lmk_bary_coords)\n return landmarks2d\n\n\n def seletec_3d68(self, vertices):\n landmarks3d = vertices2landmarks(vertices, self.faces_tensor,\n self.full_lmk_faces_idx.repeat(vertices.shape[0], 1),\n self.full_lmk_bary_coords.repeat(vertices.shape[0], 1, 1))\n return landmarks3d\n\n def forward(self, shape_params=None, expression_params=None, pose_params=None, eye_pose_params=None):\n \"\"\"\n Input:\n shape_params: N X number of shape parameters\n expression_params: N X number of expression parameters\n pose_params: N X number of pose parameters (6)\n return:d\n vertices: N X V X 3\n landmarks: N X number of landmarks X 3\n \"\"\"\n batch_size = shape_params.shape[0]\n if pose_params is None:\n pose_params = self.eye_pose.expand(batch_size, -1) # TODO: is this correct?\n if eye_pose_params is None:\n eye_pose_params = self.eye_pose.expand(batch_size, -1)\n if expression_params is None:\n expression_params = torch.zeros(batch_size, self.cfg.n_exp).to(shape_params.device)\n\n betas = torch.cat([shape_params, expression_params], dim=1)\n full_pose = torch.cat(\n [pose_params[:, :3], self.neck_pose.expand(batch_size, -1), pose_params[:, 3:], eye_pose_params], dim=1)\n template_vertices = self.v_template.unsqueeze(0).expand(batch_size, -1, -1)\n\n vertices, _ = lbs(betas, full_pose, template_vertices,\n self.shapedirs, self.posedirs,\n self.J_regressor, self.parents,\n self.lbs_weights, dtype=self.dtype, \n detach_pose_correctives=False)\n\n lmk_faces_idx = self.lmk_faces_idx.unsqueeze(dim=0).expand(batch_size, -1)\n lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).expand(batch_size, -1, -1)\n\n dyn_lmk_faces_idx, dyn_lmk_bary_coords = self._find_dynamic_lmk_idx_and_bcoords(\n full_pose, self.dynamic_lmk_faces_idx,\n self.dynamic_lmk_bary_coords,\n self.neck_kin_chain, dtype=self.dtype)\n lmk_faces_idx = torch.cat([dyn_lmk_faces_idx, lmk_faces_idx], 1)\n lmk_bary_coords = torch.cat([dyn_lmk_bary_coords, lmk_bary_coords], 1)\n\n landmarks2d = vertices2landmarks(vertices, self.faces_tensor,\n lmk_faces_idx,\n lmk_bary_coords)\n bz = vertices.shape[0]\n landmarks3d = vertices2landmarks(vertices, self.faces_tensor,\n self.full_lmk_faces_idx.repeat(bz, 1),\n self.full_lmk_bary_coords.repeat(bz, 1, 1))\n\n return vertices, landmarks2d, landmarks3d" }, { "identifier": "FLAMETex", "path": "inferno/models/DecaFLAME.py", "snippet": "class FLAMETex(nn.Module):\n \"\"\"\n current FLAME texture:\n https://github.com/TimoBolkart/TF_FLAME/blob/ade0ab152300ec5f0e8555d6765411555c5ed43d/sample_texture.py#L64\n tex_path: '/ps/scratch/yfeng/Data/FLAME/texture/albedoModel2020_FLAME_albedoPart.npz'\n ## adapted from BFM\n tex_path: '/ps/scratch/yfeng/Data/FLAME/texture/FLAME_albedo_from_BFM.npz'\n \"\"\"\n\n def __init__(self, config):\n super(FLAMETex, self).__init__()\n if config.tex_type == 'BFM':\n mu_key = 'MU'\n pc_key = 'PC'\n n_pc = 199\n tex_path = config.tex_path\n try:\n tex_space = np.load(tex_path)\n texture_mean = tex_space[mu_key].reshape(1, -1)\n texture_basis = tex_space[pc_key].reshape(-1, n_pc)\n except FileNotFoundError as e: \n im_size = 512 \n texture_mean = np.ones((1, im_size*im_size*3)) * 0.5\n texture_basis = np.eye(im_size*im_size*3, n_pc) * 0.5\n print(\"[WARNING] texture file not found. Setting texture space with dummy values.\")\n\n elif config.tex_type == 'FLAME':\n mu_key = 'mean'\n pc_key = 'tex_dir'\n n_pc = 200\n tex_path = config.tex_path\n tex_space = np.load(tex_path)\n texture_mean = tex_space[mu_key].reshape(1, -1) / 255.\n texture_basis = tex_space[pc_key].reshape(-1, n_pc) / 255.\n\n else:\n print('texture type \"', config.tex_type, '\" does not exist!')\n raise NotImplementedError('texture type \"', config.tex_type, '\" does not exist!')\n\n n_tex = config.n_tex\n num_components = texture_basis.shape[1]\n texture_mean = torch.from_numpy(texture_mean).float()[None, ...]\n texture_basis = torch.from_numpy(texture_basis[:, :n_tex]).float()[None, ...]\n self.register_buffer('texture_mean', texture_mean)\n self.register_buffer('texture_basis', texture_basis)\n\n def forward(self, texcode):\n texture = self.texture_mean + (self.texture_basis * texcode[:, None, :]).sum(-1)\n texture = texture.reshape(texcode.shape[0], 512, 512, 3).permute(0, 3, 1, 2)\n texture = F.interpolate(texture, [256, 256])\n texture = texture[:, [2, 1, 0], :, :]\n return texture" }, { "identifier": "FLAME_mediapipe", "path": "inferno/models/DecaFLAME.py", "snippet": "class FLAME_mediapipe(FLAME): \n\n def __init__(self, config):\n super().__init__(config)\n # static MEDIAPIPE landmark embeddings for FLAME\n lmk_embeddings_mediapipe = np.load(config.flame_mediapipe_lmk_embedding_path, \n allow_pickle=True, encoding='latin1')\n # indices = lmk_embeddings_mediapipe['landmark_indices']\n self.register_buffer('lmk_faces_idx_mediapipe', \n torch.tensor(lmk_embeddings_mediapipe['lmk_face_idx'].astype(np.int64), dtype=torch.long))\n self.register_buffer('lmk_bary_coords_mediapipe',\n torch.tensor(lmk_embeddings_mediapipe['lmk_b_coords'], dtype=self.dtype))\n \n def forward(self, shape_params=None, expression_params=None, pose_params=None, eye_pose_params=None):\n vertices, landmarks2d, landmarks3d = super().forward(shape_params, expression_params, pose_params, eye_pose_params)\n batch_size = shape_params.shape[0]\n lmk_faces_idx_mediapipe = self.lmk_faces_idx_mediapipe.unsqueeze(dim=0).expand(batch_size, -1).contiguous()\n lmk_bary_coords_mediapipe = self.lmk_bary_coords_mediapipe.unsqueeze(dim=0).expand(batch_size, -1, -1).contiguous()\n landmarks2d_mediapipe = vertices2landmarks(vertices, self.faces_tensor,\n lmk_faces_idx_mediapipe,\n lmk_bary_coords_mediapipe )\n # landmarks3d_mediapipe = vertices2landmarks(vertices, self.faces_tensor,\n # self.full_lmk_faces_idx_mediapipe.repeat(bz, 1),\n # self.full_lmk_bary_coords_mediapipe.repeat(bz, 1, 1))\n\n return vertices, landmarks2d, landmarks3d, landmarks2d_mediapipe#, landmarks3d_mediapipe" }, { "identifier": "EmotionMLP", "path": "inferno/models/EmotionMLP.py", "snippet": "class EmotionMLP(torch.nn.Module):\n\n def __init__(self, config, deca_cfg):\n super().__init__()\n self.config = config\n in_size = 0\n if self.config.use_identity:\n in_size += deca_cfg.n_shape\n if self.config.use_expression:\n in_size += deca_cfg.n_exp\n if self.config.use_global_pose:\n in_size += 3\n if self.config.use_jaw_pose:\n in_size += 3\n if self.config.use_detail_code:\n self.n_detail = deca_cfg.n_detail\n in_size += deca_cfg.n_detail\n else:\n self.n_detail = None\n if 'use_detail_emo_code' in self.config.keys() and self.config.use_detail_emo_code:\n self.n_detail_emo = deca_cfg.n_detail_emo\n in_size += deca_cfg.n_detail_emo\n else:\n self.n_detail_emo = None\n\n hidden_layer_sizes = config.num_mlp_layers * [in_size]\n\n out_size = 0\n if self.config.predict_expression:\n self.num_classes = self.config.data.n_expression if 'n_expression' in self.config.data.keys() else 9\n out_size += self.num_classes\n if self.config.predict_valence:\n out_size += 1\n if self.config.predict_arousal:\n out_size += 1\n\n # if \"use_mlp\" not in self.config.keys() or self.config.use_mlp:\n if 'mlp_norm_layer' in self.config.keys():\n batch_norm = class_from_str(self.config.mlp_norm_layer, sys.modules[__name__])\n else:\n batch_norm = None\n self.mlp = MLP(in_size, out_size, hidden_layer_sizes, batch_norm=batch_norm)\n # else:\n # self.mlp = None\n\n if 'v_activation' in config.keys():\n self.v_activation = class_from_str(self.config.v_activation, sys.modules[__name__])\n else:\n self.v_activation = None\n\n if 'a_activation' in config.keys():\n self.a_activation = class_from_str(self.config.a_activation, sys.modules[__name__])\n else:\n self.a_activation = None\n\n if 'exp_activation' in config.keys():\n self.exp_activation = class_from_str(self.config.exp_activation, sys.modules[__name__])\n else:\n self.exp_activation = F.log_softmax\n\n self.va_loss = loss_from_cfg(config, 'va_loss')\n self.v_loss = loss_from_cfg(config, 'v_loss')\n self.a_loss = loss_from_cfg(config, 'a_loss')\n self.exp_loss = loss_from_cfg(config, 'exp_loss')\n\n # config backwards compatibility\n self.config = add_cfg_if_missing(self.config, 'detach_shape', False)\n self.config = add_cfg_if_missing(self.config, 'detach_expression', False)\n self.config = add_cfg_if_missing(self.config, 'detach_detailcode', False)\n self.config = add_cfg_if_missing(self.config, 'detach_jaw', False)\n self.config = add_cfg_if_missing(self.config, 'detach_global_pose', False)\n\n\n def forward(self, values, result_prefix=\"\"):\n shapecode = values['shapecode']\n\n if self.config.detach_shape:\n shapecode = shapecode.detach()\n\n # texcode = values['texcode']\n expcode = values['expcode']\n\n if self.config.detach_expression:\n expcode = expcode.detach()\n\n posecode = values['posecode']\n if self.config.use_detail_code:\n if 'detailcode' in values.keys() and values['detailcode'] is not None:\n detailcode = values['detailcode']\n if self.config.detach_detailcode:\n detailcode = detailcode.detach()\n else:\n detailcode = torch.zeros((posecode.shape[0], self.n_detail), dtype=posecode.dtype, device=posecode.device )\n else:\n detailcode = None\n\n if 'use_detailemo_code' in self.config.keys() and self.config.use_detailemo_code:\n if 'detailemocode' in values.keys() and values['detailemocode'] is not None:\n detailemocode = values['detailemocode']\n if 'detach_detailemocode' in self.config.keys() and self.config.detach_detailemocode:\n detailemocode = detailemocode.detach()\n else:\n detailemocode = torch.zeros((posecode.shape[0], self.n_detail_emo), dtype=posecode.dtype, device=posecode.device )\n else:\n detailemocode = None\n\n\n global_pose = posecode[:, :3]\n if self.config.detach_global_pose:\n global_pose = global_pose.detach()\n\n jaw_pose = posecode[:, 3:]\n if self.config.detach_jaw:\n jaw_pose = jaw_pose.detach()\n\n input_list = []\n\n if self.config.use_identity:\n input_list += [shapecode]\n\n if self.config.use_expression:\n input_list += [expcode]\n\n if self.config.use_global_pose:\n input_list += [global_pose]\n\n if self.config.use_jaw_pose:\n input_list += [jaw_pose]\n\n if self.config.use_detail_code:\n input_list += [detailcode]\n\n if 'use_detail_emo_code' in self.config.keys() and self.config.use_detail_emo_code:\n input_list += [detailemocode]\n\n input = torch.cat(input_list, dim=1)\n output = self.mlp(input)\n\n out_idx = 0\n if self.config.predict_expression:\n expr_classification = output[:, out_idx:(out_idx + self.num_classes)]\n if self.exp_activation is not None:\n expr_classification = self.exp_activation(output[:, out_idx:(out_idx + self.num_classes)], dim=1)\n out_idx += self.num_classes\n else:\n expr_classification = None\n\n if self.config.predict_valence:\n valence = output[:, out_idx:(out_idx+1)]\n if self.v_activation is not None:\n valence = self.v_activation(valence)\n out_idx += 1\n else:\n valence = None\n\n if self.config.predict_arousal:\n arousal = output[:, out_idx:(out_idx+1)]\n if self.a_activation is not None:\n arousal = self.a_activation(output[:, out_idx:(out_idx + 1)])\n out_idx += 1\n else:\n arousal = None\n\n values[result_prefix + \"valence\"] = valence\n values[result_prefix + \"arousal\"] = arousal\n values[result_prefix + \"expr_classification\"] = expr_classification\n\n return values\n\n\n def compute_loss(self, pred, batch, training, pred_prefix=\"\"):\n valence_gt = pred[\"va\"][:, 0:1]\n arousal_gt = pred[\"va\"][:, 1:2]\n expr_classification_gt = pred[\"affectnetexp\"]\n if \"expression_weight\" in pred.keys():\n class_weight = pred[\"expression_weight\"][0]\n else:\n class_weight = None\n\n gt = {}\n gt[\"valence\"] = valence_gt\n gt[\"arousal\"] = arousal_gt\n gt[\"expr_classification\"] = expr_classification_gt\n\n # TODO: this is not ugly enough\n scheme = None if 'va_loss_scheme' not in self.config.keys() else self.config.va_loss_scheme\n loss_term_weights = _get_step_loss_weights(self.v_loss, self.a_loss, self.va_loss, scheme, training)\n\n valence_sample_weight = batch[\"valence_sample_weight\"] if \"valence_sample_weight\" in batch.keys() else None\n arousal_sample_weight = batch[\"arousal_sample_weight\"] if \"arousal_sample_weight\" in batch.keys() else None\n va_sample_weight = batch[\"va_sample_weight\"] if \"va_sample_weight\" in batch.keys() else None\n expression_sample_weight = batch[\"expression_sample_weight\"] if \"expression_sample_weight\" in batch.keys() else None\n\n if 'continuous_va_balancing' in self.config.keys():\n if self.config.continuous_va_balancing == '1d':\n v_weight = valence_sample_weight\n a_weight = arousal_sample_weight\n elif self.config.continuous_va_balancing == '2d':\n v_weight = va_sample_weight\n a_weight = va_sample_weight\n elif self.config.continuous_va_balancing == 'expr':\n v_weight = expression_sample_weight\n a_weight = expression_sample_weight\n else:\n raise RuntimeError(f\"Invalid continuous affect balancing\"\n f\" '{self.config.continuous_va_balancing}'\")\n if len(v_weight.shape) > 1:\n v_weight = v_weight.view(-1)\n if len(a_weight.shape) > 1:\n a_weight = a_weight.view(-1)\n else:\n v_weight = None\n a_weight = None\n\n losses, metrics = {}, {}\n # print(metrics.keys())\n losses, metrics = v_or_a_loss(self.v_loss, pred, gt, loss_term_weights, metrics, losses, \"valence\",\n pred_prefix=pred_prefix, permit_dropping_corr=not training,\n sample_weights=v_weight)\n losses, metrics = v_or_a_loss(self.a_loss, pred, gt, loss_term_weights, metrics, losses, \"arousal\",\n pred_prefix=pred_prefix, permit_dropping_corr=not training,\n sample_weights=a_weight)\n losses, metrics = va_loss(self.va_loss, pred, gt, loss_term_weights, metrics, losses,\n pred_prefix=pred_prefix, permit_dropping_corr=not training)\n losses, metrics = exp_loss(self.exp_loss, pred, gt, class_weight, metrics, losses,\n self.config.expression_balancing, self.num_classes, pred_prefix=pred_prefix, )\n\n return losses, metrics" }, { "identifier": "Expression7", "path": "inferno/datasets/AffWild2Dataset.py", "snippet": "class Expression7(Enum):\n Neutral = 0\n Anger = 1\n Disgust = 2\n Fear = 3\n Happiness = 4\n Sadness = 5\n Surprise = 6\n None_ = 7" }, { "identifier": "AffectNetExpressions", "path": "inferno/datasets/AffectNetDataModule.py", "snippet": "class AffectNetExpressions(Enum):\n Neutral = 0\n Happy = 1\n Sad = 2\n Surprise = 3\n Fear = 4\n Disgust = 5\n Anger = 6\n Contempt = 7\n None_ = 8\n Uncertain = 9\n Occluded = 10\n xxx = 11\n\n\n @staticmethod\n def from_str(string : str):\n string = string[0].upper() + string[1:]\n return AffectNetExpressions[string]\n\n # _expressions = {0: 'neutral', 1:'happy', 2:'sad', 3:'surprise', 4:'fear', 5:'disgust', 6:'anger', 7:'contempt', 8:'none'}" }, { "identifier": "_log_array_image", "path": "inferno/utils/lightning_logging.py", "snippet": "def _log_array_image(path, image, caption=None):\n image = _fix_image(image)\n if path is not None:\n imsave(path, image)\n return image" }, { "identifier": "_log_wandb_image", "path": "inferno/utils/lightning_logging.py", "snippet": "def _log_wandb_image(path, image, caption=None):\n path.parent.mkdir(parents=True, exist_ok=True)\n image = _fix_image(image)\n imsave(path, image)\n if caption is not None:\n caption_file = Path(path).parent / (Path(path).stem + \".txt\")\n with open(caption_file, \"w\") as f:\n f.write(caption)\n wandb_image = Image(str(path), caption=caption)\n return wandb_image" }, { "identifier": "_torch_image2np", "path": "inferno/utils/lightning_logging.py", "snippet": "def _torch_image2np(torch_image):\n image = torch_image.detach().cpu().numpy()\n if len(image.shape) == 4:\n image = image.transpose([0, 2, 3, 1])\n elif len(image.shape) == 3:\n image = image.transpose([1, 2, 0])\n return image" }, { "identifier": "class_from_str", "path": "inferno/utils/other.py", "snippet": "def class_from_str(str, module=None, none_on_fail = False) -> type:\n if module is None:\n module = sys.modules[__name__]\n if hasattr(module, str):\n cl = getattr(module, str)\n return cl\n elif str.lower() == 'none' or none_on_fail:\n return None\n raise RuntimeError(f\"Class '{str}' not found.\")" }, { "identifier": "get_path_to_assets", "path": "inferno/utils/other.py", "snippet": "def get_path_to_assets() -> Path:\n import inferno\n return Path(inferno.__file__).parents[1] / \"assets\"" }, { "identifier": "VGG19Loss", "path": "inferno/layers/losses/VGGLoss.py", "snippet": "class VGG19Loss(nn.Module):\n\n def __init__(self, layer_activation_indices_weights, diff=torch.nn.functional.l1_loss, batch_norm=False):\n super().__init__()\n self.batch_norm = batch_norm\n self.vgg19 = VGG19(sorted(layer_activation_indices_weights.keys()), batch_norm=batch_norm)\n self.layer_activation_indices_weights = layer_activation_indices_weights\n self.diff = diff\n\n def forward(self, x, y):\n feat_x = self.vgg19(x)\n feat_y = self.vgg19(y)\n\n out = {}\n loss = 0\n for idx, weight in self.layer_activation_indices_weights.items():\n d = self.diff(feat_x[idx], feat_y[idx])\n out[idx] = d\n loss += d*weight\n return loss, out" }, { "identifier": "EmoNetRegressor", "path": "inferno/models/EmoNetRegressor.py", "snippet": "class EmoNetRegressor(torch.nn.Module):\n\n def __init__(self, outsize, last_op=None):\n super().__init__()\n self.emonet = get_emonet().eval()\n # self.emonet.eval()\n # self.emonet = self.emonet.requires_grad_(False)\n # self.transforms = Resize((256, 256))\n self.input_image_size = (256, 256) # for now, emonet is pretrained for this particual image size (the official impl)\n\n self.feature_to_use = 'emo_feat_2'\n\n if self.feature_to_use == 'emo_feat_2':\n self.emonet_feature_size = 256\n self.fc_size = 256\n else:\n raise NotImplementedError(f\"Not yet implemented for feature '{self.feature_to_use}'\")\n\n self.layers = torch.nn.Sequential(\n torch.nn.Linear(self.emonet_feature_size, self.fc_size),\n torch.nn.ReLU(),\n torch.nn.Linear(self.fc_size, outsize)\n )\n self.last_op = last_op\n\n def forward(self, images):\n images = F.interpolate(images, self.input_image_size, mode='bilinear')\n out = self.emonet(images, intermediate_features=True)\n # out has the following keys: 'heatmap', 'expression' 'valence', 'arousal', 'emo_feat', 'emo_feat_2'\n out = self.layers(out[self.feature_to_use])\n return out\n\n def reset_last_layer(self):\n # initialize the last layer to zero to help the network \n # predict the initial pose a bit more stable\n torch.nn.init.constant_(self.layers[-1].weight, 0)\n torch.nn.init.constant_(self.layers[-1].bias, 0)" }, { "identifier": "EmonetRegressorStatic", "path": "inferno/models/EmoNetRegressor.py", "snippet": "class EmonetRegressorStatic(EmoNetRegressor):\n\n def __init__(self, outsize, last_op=None):\n super().__init__(outsize, last_op)\n self.emonet.requires_grad_(False)\n self.emonet.eval()\n\n def train(self, mode=True):\n # this one only trains the FC layers\n self.emonet.eval()\n self.layers.train(mode)\n return self\n\n\n def reset_last_layer(self):\n # initialize the last layer to zero to help the network \n # predict the initial pose a bit more stable\n torch.nn.init.constant_(self.layers[-1].weight, 0)\n torch.nn.init.constant_(self.layers[-1].bias, 0)" } ]
import os, sys import torch import torchvision import torch.nn.functional as F import torchvision.transforms.functional as F_v import numpy as np import cv2 import inferno.layers.losses.DecaLosses as lossfunc import inferno.layers.losses.MediaPipeLandmarkLosses as lossfunc_mp import inferno.utils.DecaUtils as util import pytorch_lightning.plugins.environments.lightning_environment as le import psutil import adabound import copy from pytorch_lightning import LightningModule from pytorch_lightning.loggers import WandbLogger from inferno.layers.losses.EmoNetLoss import EmoNetLoss, create_emo_loss, create_au_loss from skimage.io import imread from skimage.transform import resize from pathlib import Path from inferno.models.Renderer import SRenderY from inferno.models.DecaEncoder import ResnetEncoder, SecondHeadResnet, SwinEncoder from inferno.models.DecaDecoder import Generator, GeneratorAdaIn from inferno.models.DecaFLAME import FLAME, FLAMETex, FLAME_mediapipe from inferno.models.EmotionMLP import EmotionMLP from inferno.datasets.AffWild2Dataset import Expression7 from inferno.datasets.AffectNetDataModule import AffectNetExpressions from inferno.utils.lightning_logging import _log_array_image, _log_wandb_image, _torch_image2np from enum import Enum from inferno.utils.other import class_from_str, get_path_to_assets from inferno.layers.losses.VGGLoss import VGG19Loss from omegaconf import OmegaConf, open_dict from inferno.models.temporal.external.LipReadingLoss import LipReadingLoss from .StarGAN import StarGANWrapper from inferno.models.EmoNetRegressor import EmoNetRegressor, EmonetRegressorStatic from .mica.config import get_cfg_defaults from .mica.mica import MICA from .mica.MicaInputProcessing import MicaInputProcessor from inferno.utils.other import get_path_to_assets from inferno.models.IO import locate_checkpoint
18,195
""" super().__init__() self.learning_params = learning_params self.inout_params = inout_params # detail conditioning - what is given as the conditioning input to the detail generator in detail stage training if 'detail_conditioning' not in model_params.keys(): # jaw, expression and detail code by default self.detail_conditioning = ['jawpose', 'expression', 'detail'] OmegaConf.set_struct(model_params, True) with open_dict(model_params): model_params.detail_conditioning = self.detail_conditioning else: self.detail_conditioning = model_params.detail_conditioning # deprecated and is not used if 'detailemo_conditioning' not in model_params.keys(): self.detailemo_conditioning = [] OmegaConf.set_struct(model_params, True) with open_dict(model_params): model_params.detailemo_conditioning = self.detailemo_conditioning else: self.detailemo_conditioning = model_params.detailemo_conditioning supported_conditioning_keys = ['identity', 'jawpose', 'expression', 'detail', 'detailemo'] for c in self.detail_conditioning: if c not in supported_conditioning_keys: raise ValueError(f"Conditioning on '{c}' is not supported. Supported conditionings: {supported_conditioning_keys}") for c in self.detailemo_conditioning: if c not in supported_conditioning_keys: raise ValueError(f"Conditioning on '{c}' is not supported. Supported conditionings: {supported_conditioning_keys}") # which type of DECA network is used if 'deca_class' not in model_params.keys() or model_params.deca_class is None: print(f"Deca class is not specified. Defaulting to {str(DECA.__class__.__name__)}") # vanilla DECA by default (not EMOCA) deca_class = DECA else: # other type of DECA-inspired networks possible (such as ExpDECA, which is what EMOCA) deca_class = class_from_str(model_params.deca_class, sys.modules[__name__]) # instantiate the network self.deca = deca_class(config=model_params) self.mode = DecaMode[str(model_params.mode).upper()] self.stage_name = stage_name if self.stage_name is None: self.stage_name = "" if len(self.stage_name) > 0: self.stage_name += "_" # initialize the emotion perceptual loss (used for EMOCA supervision) self.emonet_loss = None self._init_emotion_loss() # initialize the au perceptual loss (not currently used in EMOCA) self.au_loss = None self._init_au_loss() # initialize the lip reading perceptual loss (not currently used in original EMOCA) self.lipread_loss = None self._init_lipread_loss() # MPL regressor from the encoded space to emotion labels (not used in EMOCA but could be used for direct emotion supervision) if 'mlp_emotion_predictor' in self.deca.config.keys(): # self._build_emotion_mlp(self.deca.config.mlp_emotion_predictor) self.emotion_mlp = EmotionMLP(self.deca.config.mlp_emotion_predictor, model_params) else: self.emotion_mlp = None def get_input_image_size(self): return (self.deca.config.image_size, self.deca.config.image_size) def _instantiate_deca(self, model_params): """ Instantiate the DECA network. """ # which type of DECA network is used if 'deca_class' not in model_params.keys() or model_params.deca_class is None: print(f"Deca class is not specified. Defaulting to {str(DECA.__class__.__name__)}") # vanilla DECA by default (not EMOCA) deca_class = DECA else: # other type of DECA-inspired networks possible (such as ExpDECA, which is what EMOCA) deca_class = class_from_str(model_params.deca_class, sys.modules[__name__]) # instantiate the network self.deca = deca_class(config=model_params) def _init_emotion_loss(self): """ Initialize the emotion perceptual loss (used for EMOCA supervision) """ if 'emonet_weight' in self.deca.config.keys() and bool(self.deca.config.get('emonet_model_path', False)): if self.emonet_loss is not None: emoloss_force_override = True if 'emoloss_force_override' in self.deca.config.keys() and self.deca.config.emoloss_force_override else False if self.emonet_loss.is_trainable(): if not emoloss_force_override: print("The old emonet loss is trainable and will not be overrided or replaced.") return # raise NotImplementedError("The old emonet loss was trainable. Changing a trainable loss is probably now " # "what you want implicitly. If you need this, use the '`'emoloss_force_override' config.") else: print("The old emonet loss is trainable but override is set so it will be replaced.") else: print("The old emonet loss is not trainable. It will be replaced.") if 'emonet_model_path' in self.deca.config.keys(): emonet_model_path = self.deca.config.emonet_model_path else: emonet_model_path=None # self.emonet_loss = EmoNetLoss(self.device, emonet=emonet_model_path) emoloss_trainable = True if 'emoloss_trainable' in self.deca.config.keys() and self.deca.config.emoloss_trainable else False emoloss_dual = True if 'emoloss_dual' in self.deca.config.keys() and self.deca.config.emoloss_dual else False normalize_features = self.deca.config.normalize_features if 'normalize_features' in self.deca.config.keys() else None emo_feat_loss = self.deca.config.emo_feat_loss if 'emo_feat_loss' in self.deca.config.keys() else None old_emonet_loss = self.emonet_loss
""" Author: Radek Danecek Copyright (c) 2022, Radek Danecek All rights reserved. # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # Using this computer program means that you agree to the terms # in the LICENSE file included with this software distribution. # Any use not explicitly granted by the LICENSE is prohibited. # # Copyright©2022 Max-Planck-Gesellschaft zur Förderung # der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute # for Intelligent Systems. All rights reserved. # # For comments or questions, please email us at [email protected] # For commercial licensing contact, please contact [email protected] Parts of the code were adapted from the original DECA release: https://github.com/YadiraF/DECA/ """ # from time import time torch.backends.cudnn.benchmark = True class DecaMode(Enum): COARSE = 1 # when switched on, only coarse part of DECA-based networks is used DETAIL = 2 # when switched on, only coarse and detail part of DECA-based networks is used class DecaModule(LightningModule): """ DecaModule is a PL module that implements DECA-inspired face reconstruction networks. """ def __init__(self, model_params, learning_params, inout_params, stage_name = ""): """ :param model_params: a DictConfig of parameters about the model itself :param learning_params: a DictConfig of parameters corresponding to the learning process (such as optimizer, lr and others) :param inout_params: a DictConfig of parameters about input and output (where checkpoints and visualizations are saved) """ super().__init__() self.learning_params = learning_params self.inout_params = inout_params # detail conditioning - what is given as the conditioning input to the detail generator in detail stage training if 'detail_conditioning' not in model_params.keys(): # jaw, expression and detail code by default self.detail_conditioning = ['jawpose', 'expression', 'detail'] OmegaConf.set_struct(model_params, True) with open_dict(model_params): model_params.detail_conditioning = self.detail_conditioning else: self.detail_conditioning = model_params.detail_conditioning # deprecated and is not used if 'detailemo_conditioning' not in model_params.keys(): self.detailemo_conditioning = [] OmegaConf.set_struct(model_params, True) with open_dict(model_params): model_params.detailemo_conditioning = self.detailemo_conditioning else: self.detailemo_conditioning = model_params.detailemo_conditioning supported_conditioning_keys = ['identity', 'jawpose', 'expression', 'detail', 'detailemo'] for c in self.detail_conditioning: if c not in supported_conditioning_keys: raise ValueError(f"Conditioning on '{c}' is not supported. Supported conditionings: {supported_conditioning_keys}") for c in self.detailemo_conditioning: if c not in supported_conditioning_keys: raise ValueError(f"Conditioning on '{c}' is not supported. Supported conditionings: {supported_conditioning_keys}") # which type of DECA network is used if 'deca_class' not in model_params.keys() or model_params.deca_class is None: print(f"Deca class is not specified. Defaulting to {str(DECA.__class__.__name__)}") # vanilla DECA by default (not EMOCA) deca_class = DECA else: # other type of DECA-inspired networks possible (such as ExpDECA, which is what EMOCA) deca_class = class_from_str(model_params.deca_class, sys.modules[__name__]) # instantiate the network self.deca = deca_class(config=model_params) self.mode = DecaMode[str(model_params.mode).upper()] self.stage_name = stage_name if self.stage_name is None: self.stage_name = "" if len(self.stage_name) > 0: self.stage_name += "_" # initialize the emotion perceptual loss (used for EMOCA supervision) self.emonet_loss = None self._init_emotion_loss() # initialize the au perceptual loss (not currently used in EMOCA) self.au_loss = None self._init_au_loss() # initialize the lip reading perceptual loss (not currently used in original EMOCA) self.lipread_loss = None self._init_lipread_loss() # MPL regressor from the encoded space to emotion labels (not used in EMOCA but could be used for direct emotion supervision) if 'mlp_emotion_predictor' in self.deca.config.keys(): # self._build_emotion_mlp(self.deca.config.mlp_emotion_predictor) self.emotion_mlp = EmotionMLP(self.deca.config.mlp_emotion_predictor, model_params) else: self.emotion_mlp = None def get_input_image_size(self): return (self.deca.config.image_size, self.deca.config.image_size) def _instantiate_deca(self, model_params): """ Instantiate the DECA network. """ # which type of DECA network is used if 'deca_class' not in model_params.keys() or model_params.deca_class is None: print(f"Deca class is not specified. Defaulting to {str(DECA.__class__.__name__)}") # vanilla DECA by default (not EMOCA) deca_class = DECA else: # other type of DECA-inspired networks possible (such as ExpDECA, which is what EMOCA) deca_class = class_from_str(model_params.deca_class, sys.modules[__name__]) # instantiate the network self.deca = deca_class(config=model_params) def _init_emotion_loss(self): """ Initialize the emotion perceptual loss (used for EMOCA supervision) """ if 'emonet_weight' in self.deca.config.keys() and bool(self.deca.config.get('emonet_model_path', False)): if self.emonet_loss is not None: emoloss_force_override = True if 'emoloss_force_override' in self.deca.config.keys() and self.deca.config.emoloss_force_override else False if self.emonet_loss.is_trainable(): if not emoloss_force_override: print("The old emonet loss is trainable and will not be overrided or replaced.") return # raise NotImplementedError("The old emonet loss was trainable. Changing a trainable loss is probably now " # "what you want implicitly. If you need this, use the '`'emoloss_force_override' config.") else: print("The old emonet loss is trainable but override is set so it will be replaced.") else: print("The old emonet loss is not trainable. It will be replaced.") if 'emonet_model_path' in self.deca.config.keys(): emonet_model_path = self.deca.config.emonet_model_path else: emonet_model_path=None # self.emonet_loss = EmoNetLoss(self.device, emonet=emonet_model_path) emoloss_trainable = True if 'emoloss_trainable' in self.deca.config.keys() and self.deca.config.emoloss_trainable else False emoloss_dual = True if 'emoloss_dual' in self.deca.config.keys() and self.deca.config.emoloss_dual else False normalize_features = self.deca.config.normalize_features if 'normalize_features' in self.deca.config.keys() else None emo_feat_loss = self.deca.config.emo_feat_loss if 'emo_feat_loss' in self.deca.config.keys() else None old_emonet_loss = self.emonet_loss
self.emonet_loss = create_emo_loss(self.device, emoloss=emonet_model_path, trainable=emoloss_trainable,
1
2023-11-07 20:13:32+00:00
24k
codefuse-ai/Collinear-Constrained-Attention
model/build_model.py
[ { "identifier": "get_model_params_num", "path": "utils/common_utils.py", "snippet": "def get_model_params_num(model):\n \"\"\"\n Get params number of the model\n Args:\n model: model(required)\n Returns:\n the number of parameters of model\n \"\"\"\n num = 0\n for _, param in model.named_parameters():\n num += param.nelement()\n return num" }, { "identifier": "GPTNeoXConfig", "path": "model/gpt_neox/configuration_gpt_neox.py", "snippet": "class GPTNeoXConfig(PretrainedConfig):\n r\"\"\"\n This is the configuration class to store the configuration of a [`GPTNeoXModel`]. It is used to instantiate an\n GPTNeoX model according to the specified arguments, defining the model architecture. Instantiating a configuration\n with the defaults will yield a similar configuration to that of the GPTNeoX\n [EleutherAI/gpt-neox-20b](https://huggingface.co/EleutherAI/gpt-neox-20b) architecture.\n\n Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the\n documentation from [`PretrainedConfig`] for more information.\n\n\n Args:\n vocab_size (`int`, *optional*, defaults to 50432):\n Vocabulary size of the GPTNeoX model. Defines the number of different tokens that can be represented by the\n `inputs_ids` passed when calling [`GPTNeoXModel`].\n hidden_size (`int`, *optional*, defaults to 6144):\n Dimension of the encoder layers and the pooler layer.\n num_hidden_layers (`int`, *optional*, defaults to 44):\n Number of hidden layers in the Transformer encoder.\n num_attention_heads (`int`, *optional*, defaults to 64):\n Number of attention heads for each attention layer in the Transformer encoder.\n intermediate_size (`int`, *optional*, defaults to 24576):\n Dimension of the \"intermediate\" (i.e., feed-forward) layer in the Transformer encoder.\n hidden_act (`str` or `function`, *optional*, defaults to `\"gelu\"`):\n The non-linear activation function (function or string) in the encoder and pooler. If string, `\"gelu\"`,\n `\"relu\"`, `\"selu\"` and `\"gelu_new\"` are supported.\n rotary_pct (`float`, *optional*, defaults to 0.25):\n percentage of hidden dimensions to allocate to rotary embeddings\n rotary_emb_base (`int`, *optional*, defaults to 10000)\n base for computing rotary embeddings frequency\n max_position_embeddings (`int`, *optional*, defaults to 2048):\n The maximum sequence length that this model might ever be used with. Typically set this to something large\n just in case (e.g., 512 or 1024 or 2048).\n initializer_range (`float`, *optional*, defaults to 1e-5):\n The standard deviation of the truncated_normal_initializer for initializing all weight matrices.\n layer_norm_eps (`float`, *optional*, defaults to 1e-12):\n The epsilon used by the layer normalization layers.\n use_cache (`bool`, *optional*, defaults to `True`):\n Whether or not the model should return the last key/values attentions (not used by all models). Only\n relevant if `config.is_decoder=True`.\n use_parallel_residual (`bool`, *optional*, defaults to `True`):\n Whether to use a \"parallel\" formulation in each Transformer layer, which can provide a slight training\n speedup at large scales (e.g. 20B).\n rope_scaling (`Dict`, *optional*):\n Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports three scaling\n strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format\n is `{\"type\": strategy name, \"factor\": scaling factor}`. When using this flag, don't update\n `max_position_embeddings` to the expected new maximum. See the following thread for more information on how\n these scaling strategies behave:\n https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an\n experimental feature, subject to breaking API changes in future versions.\n Example:\n\n ```python\n >>> from transformers import GPTNeoXConfig, GPTNeoXModel\n\n >>> # Initializing a GPTNeoX gpt-neox-20b style configuration\n >>> configuration = GPTNeoXConfig()\n\n >>> # Initializing a model (with random weights) from the gpt-neox-20b style configuration\n >>> model = GPTNeoXModel(configuration) # doctest: +SKIP\n\n >>> # Accessing the model configuration\n >>> configuration = model.config # doctest: +SKIP\n ```\"\"\"\n model_type = \"gpt_neox\"\n\n def __init__(\n self,\n vocab_size=50432,\n hidden_size=6144,\n num_hidden_layers=44,\n num_attention_heads=64,\n intermediate_size=24576,\n hidden_act=\"gelu\",\n rotary_pct=0.25,\n rotary_emb_base=10000,\n max_position_embeddings=2048,\n initializer_range=0.02,\n layer_norm_eps=1e-5,\n use_cache=True,\n bos_token_id=0,\n eos_token_id=2,\n tie_word_embeddings=False,\n use_parallel_residual=True,\n rope_scaling=None,\n **kwargs\n ):\n super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.rotary_pct = rotary_pct\n self.rotary_emb_base = rotary_emb_base\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.use_cache = use_cache\n self.tie_word_embeddings = tie_word_embeddings\n self.use_parallel_residual = use_parallel_residual\n self.rope_scaling = rope_scaling\n self._rope_scaling_validation()\n\n if self.hidden_size % self.num_attention_heads != 0:\n raise ValueError(\n \"The hidden size is not divisble by the number of attention heads! Make sure to update them!\"\n )\n\n # Copied from transformers.models.llama.configuration_llama.LlamaConfig._rope_scaling_validation\n def _rope_scaling_validation(self):\n \"\"\"\n Validate the `rope_scaling` configuration.\n \"\"\"\n if self.rope_scaling is None:\n return\n\n if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:\n raise ValueError(\n \"`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, \"\n f\"got {self.rope_scaling}\"\n )\n rope_scaling_type = self.rope_scaling.get(\"type\", None)\n rope_scaling_factor = self.rope_scaling.get(\"factor\", None)\n if rope_scaling_type is None or rope_scaling_type not in [\"linear\", \"dynamic\"]:\n raise ValueError(\n f\"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}\"\n )\n if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:\n raise ValueError(f\"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}\")" }, { "identifier": "GPTNeoXForCausalLM", "path": "model/gpt_neox/modeling_gpt_neox.py", "snippet": "class GPTNeoXForCausalLM(GPTNeoXPreTrainedModel):\n\n # _keys_to_ignore_on_load_missing = [r\"position_ids\", r\"predictions.decoder.bias\"]\n\n def __init__(self, config):\n super().__init__(config)\n\n self.gpt_neox = GPTNeoXModel(config)\n self.embed_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def get_output_embeddings(self):\n return self.embed_out\n\n def set_output_embeddings(self, new_embeddings):\n self.embed_out = new_embeddings\n\n @add_start_docstrings_to_model_forward(GPT_NEOX_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, CausalLMOutputWithPast]:\n r\"\"\"\n past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):\n Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape\n `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape\n `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional tensors are\n only required when the model is used as a decoder in a Sequence to Sequence model.\n\n Contains pre-computed hidden-states (key and values in the self-attention blocks that can be used (see\n `past_key_values` input) to speed up sequential decoding.\n\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in\n `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are\n ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, GPTNeoXForCausalLM, GPTNeoXConfig\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"EleutherAI/gpt-neox-20b\")\n >>> config = GPTNeoXConfig.from_pretrained(\"EleutherAI/gpt-neox-20b\")\n >>> config.is_decoder = True\n >>> model = GPTNeoXForCausalLM.from_pretrained(\"EleutherAI/gpt-neox-20b\", config=config)\n\n >>> inputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n\n >>> prediction_logits = outputs.logits\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.gpt_neox(\n input_ids,\n attention_mask=attention_mask,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n hidden_states = outputs[0]\n lm_logits = self.embed_out(hidden_states)\n\n lm_loss = None\n if labels is not None:\n # move labels to correct device to enable model parallelism\n labels = labels.to(lm_logits.device)\n # we are doing next-token prediction; shift prediction scores and input ids by one\n shift_logits = lm_logits[:, :-1, :].contiguous()\n labels = labels[:, 1:].contiguous()\n loss_fct = CrossEntropyLoss()\n lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), labels.view(-1))\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((lm_loss,) + output) if lm_loss is not None else output\n\n return CausalLMOutputWithPast(\n loss=lm_loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n def prepare_inputs_for_generation(\n self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs\n ):\n input_shape = input_ids.shape\n\n # cut decoder_input_ids if past is used\n if past_key_values and past_key_values[0] is not None:\n input_ids = input_ids[:, -1:]\n\n position_ids = kwargs.get(\"position_ids\", None)\n if attention_mask is not None and position_ids is None:\n # create position_ids on the fly for batch generation\n position_ids = attention_mask.long().cumsum(-1) - 1\n position_ids.masked_fill_(attention_mask == 0, 1)\n if past_key_values:\n position_ids = position_ids[:, -1].unsqueeze(-1)\n\n # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly\n if attention_mask is None:\n attention_mask = input_ids.new_ones(input_shape)\n\n # if `inputs_embeds` are passed, we only want to use them in the 1st generation step\n if inputs_embeds is not None and past_key_values is None:\n model_inputs = {\"inputs_embeds\": inputs_embeds}\n else:\n model_inputs = {\"input_ids\": input_ids}\n\n model_inputs.update(\n {\n \"attention_mask\": attention_mask,\n \"past_key_values\": past_key_values,\n \"position_ids\": position_ids,\n }\n )\n\n return model_inputs\n\n def _reorder_cache(self, past_key_values, beam_idx):\n reordered_past = ()\n for layer_past in past_key_values:\n reordered_past += (\n tuple(past_state.index_select(0, beam_idx) for past_state in layer_past[:2]) + layer_past[2:],\n )\n return reordered_past" }, { "identifier": "GPTNeoXTokenizerFast", "path": "model/gpt_neox/tokenization_gpt_neox_fast.py", "snippet": "class GPTNeoXTokenizerFast(PreTrainedTokenizerFast):\n \"\"\"\n Construct a \"fast\" GPT-NeoX-20B tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level\n Byte-Pair-Encoding.\n\n This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will\n be encoded differently whether it is at the beginning of the sentence (without space) or not:\n\n ```python\n >>> from transformers import GPTNeoXTokenizerFast\n\n >>> tokenizer = GPTNeoXTokenizerFast.from_pretrained(\"gpt2\")\n >>> tokenizer(\"Hello world\")[\"input_ids\"]\n [15496, 995]\n\n >>> tokenizer(\" Hello world\")[\"input_ids\"]\n [18435, 995]\n ```\n\n You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since\n the model was not pretrained this way, it might yield a decrease in performance.\n\n <Tip>\n\n When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.\n\n </Tip>\n\n This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should\n refer to this superclass for more information regarding those methods.\n\n Args:\n vocab_file (`str`):\n Path to the vocabulary file.\n merges_file (`str`):\n Path to the merges file.\n errors (`str`, *optional*, defaults to `\"replace\"`):\n Paradigm to follow when decoding bytes to UTF-8. See\n [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.\n unk_token (`str`, *optional*, defaults to `<|endoftext|>`):\n The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this\n token instead.\n bos_token (`str`, *optional*, defaults to `<|endoftext|>`):\n The beginning of sequence token.\n eos_token (`str`, *optional*, defaults to `<|endoftext|>`):\n The end of sequence token.\n add_prefix_space (`bool`, *optional*, defaults to `False`):\n Whether or not to add an initial space to the input. This allows to treat the leading word just as any\n other word. (GPTNeoX tokenizer detect beginning of words by the preceding space).\n trim_offsets (`bool`, *optional*, defaults to `True`):\n Whether or not the post-processing step should trim offsets to avoid including whitespaces.\n \"\"\"\n\n vocab_files_names = VOCAB_FILES_NAMES\n pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP\n max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES\n model_input_names = [\"input_ids\", \"attention_mask\"]\n\n def __init__(\n self,\n vocab_file=None,\n merges_file=None,\n tokenizer_file=None,\n unk_token=\"<|endoftext|>\",\n bos_token=\"<|endoftext|>\",\n eos_token=\"<|endoftext|>\",\n add_prefix_space=False,\n **kwargs,\n ):\n super().__init__(\n vocab_file,\n merges_file,\n tokenizer_file=tokenizer_file,\n unk_token=unk_token,\n bos_token=bos_token,\n eos_token=eos_token,\n add_prefix_space=add_prefix_space,\n **kwargs,\n )\n\n pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())\n if pre_tok_state.get(\"add_prefix_space\", add_prefix_space) != add_prefix_space:\n pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop(\"type\"))\n pre_tok_state[\"add_prefix_space\"] = add_prefix_space\n self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state)\n\n self.add_prefix_space = add_prefix_space\n\n def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:\n files = self._tokenizer.model.save(save_directory, name=filename_prefix)\n return tuple(files)\n\n def _build_conversation_input_ids(self, conversation: \"Conversation\") -> List[int]:\n \"\"\"This corresponds to DialoGPT variants of models.\"\"\"\n input_ids = []\n for is_user, text in conversation.iter_texts():\n input_ids.extend(self.encode(text, add_special_tokens=False) + [self.eos_token_id])\n\n if len(input_ids) > self.model_max_length:\n input_ids = input_ids[-self.model_max_length :]\n return input_ids" }, { "identifier": "LlamaConfig", "path": "model/llama/configuration_llama.py", "snippet": "class LlamaConfig(PretrainedConfig):\n r\"\"\"\n This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA\n model according to the specified arguments, defining the model architecture. Instantiating a configuration with the\n defaults will yield a similar configuration to that of the LLaMA-7B.\n\n Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the\n documentation from [`PretrainedConfig`] for more information.\n\n\n Args:\n vocab_size (`int`, *optional*, defaults to 32000):\n Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the\n `inputs_ids` passed when calling [`LlamaModel`]\n hidden_size (`int`, *optional*, defaults to 4096):\n Dimension of the hidden representations.\n intermediate_size (`int`, *optional*, defaults to 11008):\n Dimension of the MLP representations.\n num_hidden_layers (`int`, *optional*, defaults to 32):\n Number of hidden layers in the Transformer encoder.\n num_attention_heads (`int`, *optional*, defaults to 32):\n Number of attention heads for each attention layer in the Transformer encoder.\n num_key_value_heads (`int`, *optional*):\n This is the number of key_value heads that should be used to implement Grouped Query Attention. If\n `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if\n `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When\n converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed\n by meanpooling all the original heads within that group. For more details checkout [this\n paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to\n `num_attention_heads`.\n pretraining_tp (`int`, *optional*, defaults to `1`):\n Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this\n document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is\n necessary to ensure exact reproducibility of the pretraining results. Please refer to [this\n issue](https://github.com/pytorch/pytorch/issues/76232).\n hidden_act (`str` or `function`, *optional*, defaults to `\"silu\"`):\n The non-linear activation function (function or string) in the decoder.\n max_position_embeddings (`int`, *optional*, defaults to 2048):\n The maximum sequence length that this model might ever be used with. Typically set this to something large\n just in case (e.g., 512 or 1024 or 2048).\n initializer_range (`float`, *optional*, defaults to 0.02):\n The standard deviation of the truncated_normal_initializer for initializing all weight matrices.\n rms_norm_eps (`float`, *optional*, defaults to 1e-12):\n The epsilon used by the rms normalization layers.\n use_cache (`bool`, *optional*, defaults to `True`):\n Whether or not the model should return the last key/values attentions (not used by all models). Only\n relevant if `config.is_decoder=True`.\n tie_word_embeddings(`bool`, *optional*, defaults to `False`):\n Whether to tie weight embeddings\n rope_scaling (`Dict`, *optional*):\n Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling\n strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format\n is `{\"type\": strategy name, \"factor\": scaling factor}`. When using this flag, don't update\n `max_position_embeddings` to the expected new maximum. See the following thread for more information on how\n these scaling strategies behave:\n https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an\n experimental feature, subject to breaking API changes in future versions.\n\n Example:\n\n ```python\n >>> from transformers import LlamaModel, LlamaConfig\n\n >>> # Initializing a LLaMA llama-7b style configuration\n >>> configuration = LlamaConfig()\n\n >>> # Initializing a model from the llama-7b style configuration\n >>> model = LlamaModel(configuration)\n\n >>> # Accessing the model configuration\n >>> configuration = model.config\n ```\"\"\"\n model_type = \"llama\"\n keys_to_ignore_at_inference = [\"past_key_values\"]\n\n def __init__(\n self,\n vocab_size=32000,\n hidden_size=4096,\n intermediate_size=11008,\n num_hidden_layers=32,\n num_attention_heads=32,\n num_key_value_heads=None,\n hidden_act=\"silu\",\n max_position_embeddings=2048,\n initializer_range=0.02,\n rms_norm_eps=1e-6,\n use_cache=True,\n pad_token_id=None,\n bos_token_id=1,\n eos_token_id=2,\n pretraining_tp=1,\n tie_word_embeddings=False,\n rope_scaling=None,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n\n # for backward compatibility\n if num_key_value_heads is None:\n num_key_value_heads = num_attention_heads\n\n self.num_key_value_heads = num_key_value_heads\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.rms_norm_eps = rms_norm_eps\n self.pretraining_tp = pretraining_tp\n self.use_cache = use_cache\n self.rope_scaling = rope_scaling\n self._rope_scaling_validation()\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n tie_word_embeddings=tie_word_embeddings,\n **kwargs,\n )\n\n def _rope_scaling_validation(self):\n \"\"\"\n Validate the `rope_scaling` configuration.\n \"\"\"\n if self.rope_scaling is None:\n return\n\n if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:\n raise ValueError(\n \"`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, \"\n f\"got {self.rope_scaling}\"\n )\n rope_scaling_type = self.rope_scaling.get(\"type\", None)\n rope_scaling_factor = self.rope_scaling.get(\"factor\", None)\n if rope_scaling_type is None or rope_scaling_type not in [\"linear\", \"dynamic\"]:\n raise ValueError(\n f\"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}\"\n )\n if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:\n raise ValueError(f\"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}\")" }, { "identifier": "LlamaForCausalLM", "path": "model/llama/modeling_llama.py", "snippet": "class LlamaForCausalLM(LlamaPreTrainedModel):\n _tied_weights_keys = [\"lm_head.weight\"]\n\n def __init__(self, config):\n super().__init__(config)\n self.model = LlamaModel(config)\n self.vocab_size = config.vocab_size\n self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def get_input_embeddings(self):\n return self.model.embed_tokens\n\n def set_input_embeddings(self, value):\n self.model.embed_tokens = value\n\n def get_output_embeddings(self):\n return self.lm_head\n\n def set_output_embeddings(self, new_embeddings):\n self.lm_head = new_embeddings\n\n def set_decoder(self, decoder):\n self.model = decoder\n\n def get_decoder(self):\n return self.model\n\n @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, CausalLMOutputWithPast]:\n r\"\"\"\n Args:\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, LlamaForCausalLM\n\n >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)\n >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)\n\n >>> prompt = \"Hey, are you conscious? Can you talk to me?\"\n >>> inputs = tokenizer(prompt, return_tensors=\"pt\")\n\n >>> # Generate\n >>> generate_ids = model.generate(inputs.input_ids, max_length=30)\n >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]\n \"Hey, are you conscious? Can you talk to me?\\nI'm not conscious, but I can talk to you.\"\n ```\"\"\"\n\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)\n outputs = self.model(\n input_ids=input_ids,\n attention_mask=attention_mask,\n position_ids=position_ids,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n hidden_states = outputs[0]\n if self.config.pretraining_tp > 1:\n lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)\n logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]\n logits = torch.cat(logits, dim=-1)\n else:\n logits = self.lm_head(hidden_states)\n logits = logits.float()\n\n loss = None\n if labels is not None:\n # Shift so that tokens < n predict n\n shift_logits = logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n # Flatten the tokens\n loss_fct = CrossEntropyLoss()\n shift_logits = shift_logits.view(-1, self.config.vocab_size)\n shift_labels = shift_labels.view(-1)\n # Enable model parallelism\n shift_labels = shift_labels.to(shift_logits.device)\n loss = loss_fct(shift_logits, shift_labels)\n\n if not return_dict:\n output = (logits,) + outputs[1:]\n return (loss,) + output if loss is not None else output\n\n return CausalLMOutputWithPast(\n loss=loss,\n logits=logits,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n def prepare_inputs_for_generation(\n self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs\n ):\n if past_key_values:\n input_ids = input_ids[:, -1:]\n\n position_ids = kwargs.get(\"position_ids\", None)\n if attention_mask is not None and position_ids is None:\n # create position_ids on the fly for batch generation\n position_ids = attention_mask.long().cumsum(-1) - 1\n position_ids.masked_fill_(attention_mask == 0, 1)\n if past_key_values:\n position_ids = position_ids[:, -1].unsqueeze(-1)\n\n # if `inputs_embeds` are passed, we only want to use them in the 1st generation step\n if inputs_embeds is not None and past_key_values is None:\n model_inputs = {\"inputs_embeds\": inputs_embeds}\n else:\n model_inputs = {\"input_ids\": input_ids}\n\n model_inputs.update(\n {\n \"position_ids\": position_ids,\n \"past_key_values\": past_key_values,\n \"use_cache\": kwargs.get(\"use_cache\"),\n \"attention_mask\": attention_mask,\n }\n )\n return model_inputs\n\n @staticmethod\n def _reorder_cache(past_key_values, beam_idx):\n reordered_past = ()\n for layer_past in past_key_values:\n reordered_past += (\n tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),\n )\n return reordered_past" }, { "identifier": "LlamaTokenizer", "path": "model/llama/tokenization_llama.py", "snippet": "class LlamaTokenizer(PreTrainedTokenizer):\n \"\"\"\n Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is\n no padding token in the original model.\n\n Args:\n vocab_file (`str`):\n Path to the vocabulary file.\n legacy (`bool`, *optional*, defaults to `True`):\n Whether or not the `legacy` behaviour of the tokenizer should be used. Legacy is before the merge of #24622\n which includes fixes to properly handle tokens that appear after special tokens. A simple example:\n\n - `legacy=True`:\n ```python\n >>> from transformers import T5Tokenizer\n\n >>> tokenizer = T5Tokenizer.from_pretrained(\"t5-base\", legacy=True)\n >>> tokenizer.encode(\"Hello <extra_id_0>.\")\n [8774, 32099, 3, 5, 1]\n ```\n - `legacy=False`:\n ```python\n >>> from transformers import T5Tokenizer\n\n >>> tokenizer = T5Tokenizer.from_pretrained(\"t5-base\", legacy=False)\n >>> tokenizer.encode(\"Hello <extra_id_0>.\") # the extra space `[3]` is no longer here\n [8774, 32099, 5, 1]\n ```\n Checkout the pull request and the issue [here](https://github.com/huggingface/transformers/pull/24565) for\n more details.\n\n \"\"\"\n\n vocab_files_names = VOCAB_FILES_NAMES\n pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP\n max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES\n model_input_names = [\"input_ids\", \"attention_mask\"]\n\n def __init__(\n self,\n vocab_file,\n unk_token=\"<unk>\",\n bos_token=\"<s>\",\n eos_token=\"</s>\",\n pad_token=None,\n sp_model_kwargs: Optional[Dict[str, Any]] = None,\n add_bos_token=True,\n add_eos_token=False,\n clean_up_tokenization_spaces=False,\n legacy=None,\n **kwargs,\n ):\n self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs\n bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token\n eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token\n unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token\n pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token\n super().__init__(\n bos_token=bos_token,\n eos_token=eos_token,\n unk_token=unk_token,\n pad_token=pad_token,\n add_bos_token=add_bos_token,\n add_eos_token=add_eos_token,\n sp_model_kwargs=self.sp_model_kwargs,\n clean_up_tokenization_spaces=clean_up_tokenization_spaces,\n legacy=legacy,\n **kwargs,\n )\n if legacy is None:\n logger.warning_once(\n f\"You are using the default legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to\"\n \" read the related pull request available at https://github.com/huggingface/transformers/pull/24565, and set the legacy attribute accordingly.\"\n )\n legacy = True\n\n self.legacy = legacy\n self.vocab_file = vocab_file\n self.add_bos_token = add_bos_token\n self.add_eos_token = add_eos_token\n self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)\n self.sp_model.Load(vocab_file)\n\n def __getstate__(self):\n state = self.__dict__.copy()\n state[\"sp_model\"] = None\n state[\"sp_model_proto\"] = self.sp_model.serialized_model_proto()\n return state\n\n def __setstate__(self, d):\n self.__dict__ = d\n self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)\n self.sp_model.LoadFromSerializedProto(self.sp_model_proto)\n\n @property\n def vocab_size(self):\n \"\"\"Returns vocab size\"\"\"\n return self.sp_model.get_piece_size()\n\n def get_vocab(self):\n \"\"\"Returns vocab as a dict\"\"\"\n vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}\n vocab.update(self.added_tokens_encoder)\n return vocab\n\n # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.tokenize\n def tokenize(self, text: \"TextInput\", **kwargs) -> List[str]:\n # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at\n # the beginning of the text\n if not self.legacy:\n text = SPIECE_UNDERLINE + text.replace(SPIECE_UNDERLINE, \" \")\n return super().tokenize(text, **kwargs)\n\n # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._tokenize\n def _tokenize(self, text, **kwargs):\n \"\"\"\n Returns a tokenized string.\n\n Since the sentencepiece internal model always adds a SPIECE_UNDERLINE, at the beginning of the provided text,\n we need to remove it by hand when the current text is a subsequence. This happens whenever the `self.tokenize`\n function is called with specials tokens: the input is split on the special tokens, and each subsequence is\n passed to `_tokenize`. Thus if a subsequence did not start with a `\" \"` or SPIECE_UNDERLINE, we have to remove\n the extra `SPIECE_UNDERLINE` prepended.\n \"\"\"\n if not self.legacy:\n is_first = text.startswith(SPIECE_UNDERLINE)\n if is_first:\n text = text[1:]\n\n tokens = self.sp_model.encode(text, out_type=str)\n\n if not self.legacy and not is_first and not text.startswith(\" \") and tokens[0].startswith(SPIECE_UNDERLINE):\n tokens = ([tokens[0][1:]] if len(tokens[0]) > 1 else []) + tokens[1:]\n return tokens\n\n def _convert_token_to_id(self, token):\n \"\"\"Converts a token (str) in an id using the vocab.\"\"\"\n return self.sp_model.piece_to_id(token)\n\n def _convert_id_to_token(self, index):\n \"\"\"Converts an index (integer) in a token (str) using the vocab.\"\"\"\n token = self.sp_model.IdToPiece(index)\n return token\n\n def convert_tokens_to_string(self, tokens):\n \"\"\"Converts a sequence of tokens (string) in a single string.\"\"\"\n current_sub_tokens = []\n out_string = \"\"\n prev_is_special = False\n for i, token in enumerate(tokens):\n # make sure that special tokens are not decoded using sentencepiece model\n if token in self.all_special_tokens:\n if not prev_is_special and i != 0:\n out_string += \" \"\n out_string += self.sp_model.decode(current_sub_tokens) + token\n prev_is_special = True\n current_sub_tokens = []\n else:\n current_sub_tokens.append(token)\n prev_is_special = False\n out_string += self.sp_model.decode(current_sub_tokens)\n return out_string\n\n def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:\n \"\"\"\n Save the vocabulary and special tokens file to a directory.\n\n Args:\n save_directory (`str`):\n The directory in which to save the vocabulary.\n\n Returns:\n `Tuple(str)`: Paths to the files saved.\n \"\"\"\n if not os.path.isdir(save_directory):\n logger.error(f\"Vocabulary path ({save_directory}) should be a directory\")\n return\n out_vocab_file = os.path.join(\n save_directory, (filename_prefix + \"-\" if filename_prefix else \"\") + VOCAB_FILES_NAMES[\"vocab_file\"]\n )\n\n if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):\n copyfile(self.vocab_file, out_vocab_file)\n elif not os.path.isfile(self.vocab_file):\n with open(out_vocab_file, \"wb\") as fi:\n content_spiece_model = self.sp_model.serialized_model_proto()\n fi.write(content_spiece_model)\n\n return (out_vocab_file,)\n\n def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):\n bos_token_id = [self.bos_token_id] if self.add_bos_token else []\n eos_token_id = [self.eos_token_id] if self.add_eos_token else []\n\n output = bos_token_id + token_ids_0 + eos_token_id\n\n if token_ids_1 is not None:\n output = output + bos_token_id + token_ids_1 + eos_token_id\n\n return output\n\n def get_special_tokens_mask(\n self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False\n ) -> List[int]:\n \"\"\"\n Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding\n special tokens using the tokenizer `prepare_for_model` method.\n\n Args:\n token_ids_0 (`List[int]`):\n List of IDs.\n token_ids_1 (`List[int]`, *optional*):\n Optional second list of IDs for sequence pairs.\n already_has_special_tokens (`bool`, *optional*, defaults to `False`):\n Whether or not the token list is already formatted with special tokens for the model.\n\n Returns:\n `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.\n \"\"\"\n if already_has_special_tokens:\n return super().get_special_tokens_mask(\n token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True\n )\n\n bos_token_id = [1] if self.add_bos_token else []\n eos_token_id = [1] if self.add_eos_token else []\n\n if token_ids_1 is None:\n return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id\n return (\n bos_token_id\n + ([0] * len(token_ids_0))\n + eos_token_id\n + bos_token_id\n + ([0] * len(token_ids_1))\n + eos_token_id\n )\n\n def create_token_type_ids_from_sequences(\n self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None\n ) -> List[int]:\n \"\"\"\n Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT\n sequence pair mask has the following format:\n\n ```\n 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1\n | first sequence | second sequence |\n ```\n\n if token_ids_1 is None, only returns the first portion of the mask (0s).\n\n Args:\n token_ids_0 (`List[int]`):\n List of ids.\n token_ids_1 (`List[int]`, *optional*):\n Optional second list of IDs for sequence pairs.\n\n Returns:\n `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).\n \"\"\"\n bos_token_id = [self.bos_token_id] if self.add_bos_token else []\n eos_token_id = [self.eos_token_id] if self.add_eos_token else []\n\n output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)\n\n if token_ids_1 is not None:\n output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)\n\n return output\n\n def _build_conversation_input_ids(self, conversation: \"Conversation\") -> List[int]:\n r\"\"\"Builds the input ids for a conversation.\n This is the format used in the provided examples. System prompts should be manually added at the beginning of\n the conversation. If no system prompt is given, the `DEFAULT_SYSTEM_PROMPT` will be used.\n ```\n <bos>[INST] B_SYS SytemPrompt E_SYS Prompt [/INST] Answer <eos>\n <bos>[INST] Prompt [/INST] Answer <eos>\n <bos>[INST] Prompt [/INST]\n ```\n\n If you want to use your own system prompt, make sure to use both `B_SYS` and `E_SYS` use the following:\n ```python\n >>> from transformers import Conversation\n\n >>> Conversation(\n ... \"<<SYS>>\\n Only answer with emojis, and charades\\n<</SYS>>\\n\\nHow can I build a house in 10 septs?\"\n ... ) # doctest: +IGNORE_RESULT\n ```\n Args:\n conversation (`Conversation`):\n Conversation to build input ids for.\n Returns:\n `List[int]`:\n Input ids for the conversation.\n \"\"\"\n if len(conversation.past_user_inputs) > 0:\n if not conversation.past_user_inputs[0].startswith(B_SYS) or E_SYS not in conversation.past_user_inputs[0]:\n conversation.past_user_inputs[0] = (\n B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]\n )\n elif conversation.new_user_input:\n if not conversation.new_user_input.startswith(B_SYS) or E_SYS not in conversation.new_user_input:\n conversation.new_user_input = B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.new_user_input\n else:\n raise ValueError(\"Last message must be from user\")\n\n dialogue = list(conversation.iter_texts())\n if not all([is_user for is_user, msg in dialogue[::2]]) or not all(\n [not is_user for is_user, msg in dialogue[1::2]]\n ):\n raise ValueError(\n \"The model only supports 'user' and 'assistant' roles, starting with user and alternating (u/a/u/a/u...)\"\n )\n\n dialog_tokens: List[int] = []\n dialog_tokens += sum(\n [\n [self.bos_token_id]\n + self.encode(\n f\"{B_INST} {(prompt[1]).strip()} {E_INST} {(answer[1]).strip()} \", add_special_tokens=False\n )\n + [self.eos_token_id]\n for prompt, answer in zip(dialogue[::2], dialogue[1::2])\n ],\n [],\n )\n dialog_tokens += [self.bos_token_id] + self.encode(\n f\"{B_INST} {(dialogue[-1][1]).strip()} {E_INST}\", add_special_tokens=False\n )\n return dialog_tokens" }, { "identifier": "LlamaTokenizerFast", "path": "model/llama/tokenization_llama_fast.py", "snippet": "class LlamaTokenizerFast(PreTrainedTokenizerFast):\n \"\"\"\n Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding.\n\n This uses notably ByteFallback and no normalization.\n\n ```\n from transformers import LlamaTokenizerFast\n\n tokenizer = LlamaTokenizerFast.from_pretrained(\"hf-internal-testing/llama-tokenizer\")\n tokenizer.encode(\"Hello this is a test\")\n >>> [1, 15043, 445, 338, 263, 1243]\n ```\n\n If you want to change the `bos_token` or the `eos_token`, make sure to specify them when initializing the model, or\n call `tokenizer.update_post_processor()` to make sure that the post-processing is correctly done (otherwise the\n values of the first token and final token of an encoded sequence will not be correct). For more details, checkout\n [post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) documentation.\n\n\n This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should\n refer to this superclass for more information regarding those methods.\n\n Args:\n vocab_file (`str`):\n [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .model extension) that\n contains the vocabulary necessary to instantiate a tokenizer.\n tokenizer_file (`str`):\n [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that\n contains everything needed to load the tokenizer.\n\n clean_up_tokenization_spaces (`str`, *optional*, defaults to `False`):\n Wether to cleanup spaces after decoding, cleanup consists in removing potential artifacts like extra\n spaces.\n\n bos_token (`str`, *optional*, defaults to `\"<s>\"`):\n The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.\n\n eos_token (`str`, *optional*, defaults to `\"</s>\"`):\n The end of sequence token.\n\n unk_token (`str`, *optional*, defaults to `\"<unk>\"`):\n The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this\n token instead.\n \"\"\"\n\n vocab_files_names = VOCAB_FILES_NAMES\n slow_tokenizer_class = LlamaTokenizer\n padding_side = \"left\"\n model_input_names = [\"input_ids\", \"attention_mask\"]\n\n def __init__(\n self,\n vocab_file=None,\n tokenizer_file=None,\n clean_up_tokenization_spaces=False,\n unk_token=\"<unk>\",\n bos_token=\"<s>\",\n eos_token=\"</s>\",\n add_bos_token=True,\n add_eos_token=False,\n **kwargs,\n ):\n super().__init__(\n vocab_file=vocab_file,\n tokenizer_file=tokenizer_file,\n clean_up_tokenization_spaces=clean_up_tokenization_spaces,\n unk_token=unk_token,\n bos_token=bos_token,\n eos_token=eos_token,\n **kwargs,\n )\n self._add_bos_token = add_bos_token\n self._add_eos_token = add_eos_token\n self.update_post_processor()\n\n self.vocab_file = vocab_file\n self.can_save_slow_tokenizer = False if not self.vocab_file else True\n\n def update_post_processor(self):\n \"\"\"\n Updates the underlying post processor with the current `bos_token` and `eos_token`.\n \"\"\"\n bos = self.bos_token\n bos_token_id = self.bos_token_id\n\n eos = self.eos_token\n eos_token_id = self.eos_token_id\n\n single = f\"{(bos+':0 ') * self.add_bos_token}$A:0{(' '+eos+':0') * self.add_eos_token}\"\n pair = f\"{single}{(' '+bos+':1') * self.add_bos_token} $B:1{(' '+eos+':1') * self.add_eos_token}\"\n\n special_tokens = []\n if self.add_bos_token:\n special_tokens.append((bos, bos_token_id))\n if self.add_eos_token:\n special_tokens.append((eos, eos_token_id))\n self._tokenizer.post_processor = processors.TemplateProcessing(\n single=single, pair=pair, special_tokens=special_tokens\n )\n\n @property\n def add_eos_token(self):\n return self._add_eos_token\n\n @property\n def add_bos_token(self):\n return self._add_bos_token\n\n @add_eos_token.setter\n def add_eos_token(self, value):\n self._add_eos_token = value\n self.update_post_processor()\n\n @add_bos_token.setter\n def add_bos_token(self, value):\n self._add_bos_token = value\n self.update_post_processor()\n\n def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:\n if not self.can_save_slow_tokenizer:\n raise ValueError(\n \"Your fast tokenizer does not have the necessary information to save the vocabulary for a slow \"\n \"tokenizer.\"\n )\n\n if not os.path.isdir(save_directory):\n logger.error(f\"Vocabulary path ({save_directory}) should be a directory\")\n return\n out_vocab_file = os.path.join(\n save_directory, (filename_prefix + \"-\" if filename_prefix else \"\") + VOCAB_FILES_NAMES[\"vocab_file\"]\n )\n\n if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):\n copyfile(self.vocab_file, out_vocab_file)\n\n return (out_vocab_file,)\n\n def _build_conversation_input_ids(self, conversation: \"Conversation\"):\n \"\"\"Builds the input ids for a conversation.\n This is the format used in the provided examples. System prompts should be manually added at the beginning of\n the conversation. If no system prompt is given, the `DEFAULT_SYSTEM_PROMPT` will be used.\n ```\n <bos>[INST] B_SYS SytemPrompt E_SYS Prompt [/INST] Answer <eos>\n <bos>[INST] Prompt [/INST] Answer <eos>\n <bos>[INST] Prompt [/INST]\n ```\n\n If you want to use your own system prompt, make sure to use both `B_SYS` and `E_SYS` use the following:\n ```python\n >>> from transformers import Conversation\n\n >>> Conversation(\n ... \"<<SYS>>\\n Only answer with emojis, and charades\\n<</SYS>>\\n\\nHow can I build a house in 10 septs?\"\n ... )\n ```\n Args:\n conversation (`Conversation`):\n Conversation to build input ids for.\n Returns:\n `List[int]`:\n Input ids for the conversation.\n \"\"\"\n if len(conversation.past_user_inputs) > 0:\n if not conversation.past_user_inputs[0].startswith(B_SYS) or E_SYS not in conversation.past_user_inputs[0]:\n conversation.past_user_inputs[0] = (\n B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]\n )\n elif conversation.new_user_input:\n if not conversation.new_user_input.startswith(B_SYS) or E_SYS not in conversation.new_user_input:\n conversation.new_user_input = B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.new_user_input\n else:\n raise ValueError(\"Last message must be from user\")\n\n dialogue = list(conversation.iter_texts())\n if not all([is_user for is_user, msg in dialogue[::2]]) or not all(\n [not is_user for is_user, msg in dialogue[1::2]]\n ):\n raise ValueError(\n \"The model only supports 'user' and 'assistant' roles, starting with user and alternating (u/a/u/a/u...)\"\n )\n\n dialog_tokens = []\n dialog_tokens += sum(\n [\n [self.bos_token_id]\n + self.encode(\n f\"{B_INST} {(prompt[1]).strip()} {E_INST} {(answer[1]).strip()} \", add_special_tokens=False\n )\n + [self.eos_token_id]\n for prompt, answer in zip(dialogue[::2], dialogue[1::2])\n ],\n [],\n )\n dialog_tokens += [self.bos_token_id] + self.encode(\n f\"{B_INST} {(dialogue[-1][1]).strip()} {E_INST}\", add_special_tokens=False\n )\n return dialog_tokens" }, { "identifier": "print_rank_0", "path": "utils/common_utils.py", "snippet": "def print_rank_0(*message):\n \"\"\"If distributed is initialized print only on rank 0.\"\"\"\n if torch.distributed.is_initialized():\n if torch.distributed.get_rank() == 0:\n print(*message, flush=True)\n else:\n print(*message, flush=True)" }, { "identifier": "is_old_version", "path": "utils/common_utils.py", "snippet": "def is_old_version(path):\n new_vocab_files = ['merge.model']\n new_vocab_file_exists = []\n for filename in new_vocab_files:\n if not os.path.exists(os.path.join(path, filename)):\n new_vocab_file_exists.append(False)\n else:\n new_vocab_file_exists.append(True)\n if all(new_vocab_file_exists):\n return False\n if any(new_vocab_file_exists):\n return 'new_version_file_absent'\n else:\n return True" }, { "identifier": "build_tokenizer", "path": "tokenizer/tokenizer.py", "snippet": "def build_tokenizer(args):\n \"\"\"Initialize tokenizer.\"\"\"\n print_rank_0(\"> building {} tokenizer ...\".format(args.tokenizer_type))\n # if args.rank == 0:\n # print(\"> building {} tokenizer ...\".format(args.tokenizer_type), flush=True)\n\n # Select and instantiate the tokenizer.\n if args.tokenizer_type.lower() == \"GPT2BPETokenizer\".lower():\n assert args.vocab_file is not None\n assert args.merge_file is not None\n tokenizer = _GPT2BPETokenizer(args.vocab_file, args.merge_file)\n elif args.tokenizer_type.lower() == \"SPMTokenizer\".lower():\n assert args.vocab_file is not None\n tokenizer = SentencePieceTokenizer(args.vocab_file)\n elif args.tokenizer_type.lower() == \"HFTokenizer\".lower():\n assert args.vocab_file is not None\n tokenizer = HFTokenizer(args.vocab_file)\n elif args.tokenizer_type.lower() == \"HFGPT2Tokenizer\".lower():\n if args.vocab_file is None:\n print(\n \"WARNING: No vocab file found, loading Huggingface's pretrained GPT2Tokenizer\"\n )\n tokenizer = HFGPT2Tokenizer(args.vocab_file)\n elif args.tokenizer_type.lower() == \"CharLevelTokenizer\".lower():\n tokenizer = CharLevelTokenizer(vocab_size=512)\n elif args.tokenizer_type.lower() == \"TiktokenTokenizer\".lower():\n assert args.vocab_file is not None\n tokenizer = TiktokenTokenizer(args.vocab_file)\n elif args.tokenizer_type.lower() == \"GLMTokenizer\".lower():\n if is_old_version(args.pretrained_model_path):\n print('is an old version')\n from model.glm.tokenization_glm_deprecated import GLMChineseTokenizer\n args.glm_mask = '[sMASK]'\n old_version_tokenizer = True\n tokenizer = GLMChineseTokenizer.from_pretrained(args.pretrained_model_path, trust_remote_code=True)\n else:\n print('is not an old version')\n old_version_tokenizer = False\n tokenizer = GLMTokenizer.from_pretrained(args.pretrained_model_path, trust_remote_code=True)\n else:\n raise NotImplementedError(\n \"{} tokenizer is not \" \"implemented.\".format(args.tokenizer_type)\n )\n\n # Add vocab size.\n args.padded_vocab_size = _vocab_size_with_padding(tokenizer.vocab_size, args)\n\n return tokenizer" }, { "identifier": "HFTokenizer", "path": "tokenizer/tokenizer.py", "snippet": "class HFTokenizer(AbstractTokenizer):\n \"\"\"Designed to Integrate HF's Tokenizer library.\"\"\"\n\n def __init__(self, vocab_file):\n name = \"HFTokenizer\"\n super().__init__(name)\n\n self.tokenizer = Tokenizer.from_file(vocab_file)\n # self.eod_id = self.tokenizer.token_to_id(\"<|endoftext|>\")\n self.eod_id = self.tokenizer.token_to_id(\"<|end|>\")\n # self.pad_id = self.tokenizer.token_to_id(\"<|padding|>\")\n \n # 新词表没有<|padding|>, 用<|extratoken_1|>代替,和tokenization一致\n # self.pad_id = self.tokenizer.token_to_id(\"<|extratoken_1|>\")\n self.pad_id = self.tokenizer.token_to_id(\"<|pad|>\")\n\n @property\n def vocab_size(self):\n return self.tokenizer.get_vocab_size()\n\n @property\n def vocab(self):\n return self.tokenizer.get_vocab()\n\n @property\n def inv_vocab(self):\n return self.tokenizer.decoder\n\n def tokenize(self, text: str):\n return self.tokenizer.encode(text).ids\n\n def tokenize_batch(self, text_batch: Union[List[str], str]):\n return self.tokenizer.encode_batch(text_batch)\n\n def detokenize(self, token_ids):\n return self.tokenizer.decode(token_ids)\n\n @property\n def eod(self):\n return self.eod_id" }, { "identifier": "prepare_model_for_kbit_training", "path": "model/peft/utils/others.py", "snippet": "def prepare_model_for_kbit_training(model, use_gradient_checkpointing=True):\n r\"\"\"\n This method wraps the entire protocol for preparing a model before running a training. This includes:\n 1- Cast the layernorm in fp32 2- making output embedding layer require grads 3- Add the upcasting of the lm\n head to fp32\n\n Args:\n model, (`transformers.PreTrainedModel`):\n The loaded model from `transformers`\n \"\"\"\n loaded_in_kbit = getattr(model, \"is_loaded_in_8bit\", False) or getattr(model, \"is_loaded_in_4bit\", False)\n\n for name, param in model.named_parameters():\n # freeze base model's layers\n param.requires_grad = False\n \n # cast all non INT8 parameters to fp32\n for param in model.parameters():\n if (param.dtype == torch.float16) or (param.dtype == torch.bfloat16):\n param.data = param.data.to(torch.float32)\n \n if loaded_in_kbit and use_gradient_checkpointing:\n # For backward compatibility\n if hasattr(model, \"enable_input_require_grads\"):\n model.enable_input_require_grads()\n else:\n \n def make_inputs_require_grad(module, input, output):\n output.requires_grad_(True)\n\n model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)\n\n # enable gradient checkpointing for memory efficiency\n model.gradient_checkpointing_enable()\n\n return model" }, { "identifier": "AdaLoraConfig", "path": "model/peft/tuner/adalora.py", "snippet": "class AdaLoraConfig(LoraConfig):\n \"\"\"\n This is the configuration class to store the configuration of a [`~peft.AdaLora`].\n\n Args:\n target_r (`int`): The target average rank of incremental matrix.\n init_r (`int`): The initial rank for each incremental matrix.\n tinit (`int`): The steps of initial fine-tuning warmup.\n tfinal (`int`): The step of final fine-tuning.\n deltaT (`int`): The time internval between two budget allocations.\n beta1 (`float`): The hyperparameter of EMA for sensitivity smoothing.\n beta2 (`float`): The hyperparameter of EMA for undertainty quantification.\n orth_reg_weight (`float`): The coefficient of orthogonal regularization.\n total_step (`int`): The total training steps that should be specified before training.\n rank_pattern (`list`): The allocated rank for each weight matrix by RankAllocator.\n \"\"\"\n\n target_r: int = field(default=8, metadata={\"help\": \"Target Lora matrix dimension.\"})\n init_r: int = field(default=12, metadata={\"help\": \"Intial Lora matrix dimension.\"})\n tinit: int = field(default=0, metadata={\"help\": \"The steps of initial warmup.\"})\n tfinal: int = field(default=0, metadata={\"help\": \"The steps of final warmup.\"})\n deltaT: int = field(default=1, metadata={\"help\": \"Step interval of rank allocation.\"})\n beta1: float = field(default=0.85, metadata={\"help\": \"Hyperparameter of EMA.\"})\n beta2: float = field(default=0.85, metadata={\"help\": \"Hyperparameter of EMA.\"})\n orth_reg_weight: float = field(default=0.5, metadata={\"help\": \"The orthogonal regularization coefficient.\"})\n total_step: Optional[int] = field(default=None, metadata={\"help\": \"The total training steps.\"})\n rank_pattern: Optional[dict] = field(default=None, metadata={\"help\": \"The saved rank pattern.\"})\n init_lora_weights: bool = field(\n default=True,\n metadata={\"help\": \"Whether to initialize the weights of the Lora layers.\"},\n )\n\n def __post_init__(self):\n self.peft_type = PeftType.ADALORA" } ]
import os import torch import sys import peft import model.peft.modeling_peft # noqa import bitsandbytes as bnb # noqa import accelerate # noqa from utils.common_utils import get_model_params_num from transformers import ( # noqa: E402 CONFIG_MAPPING, AutoConfig, AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast ) from .gpt_neox.configuration_gpt_neox import GPTNeoXConfig from .gpt_neox.modeling_gpt_neox import GPTNeoXForCausalLM from .gpt_neox.tokenization_gpt_neox_fast import GPTNeoXTokenizerFast from .llama.configuration_llama import LlamaConfig from .llama.modeling_llama import LlamaForCausalLM from .llama.tokenization_llama import LlamaTokenizer from .llama.tokenization_llama_fast import LlamaTokenizerFast from torch.distributed.fsdp import ( FullyShardedDataParallel as FSDP, StateDictType, ) from utils.common_utils import print_rank_0, is_old_version from tokenizer import build_tokenizer from tokenizer.tokenizer import HFTokenizer from peft.tuners.lora import LoraLayer from model.peft.utils import prepare_model_for_kbit_training from peft import ( # noqa LoraConfig, PrefixTuningConfig, PromptEncoderConfig, PromptEncoderReparameterizationType, PromptTuningConfig, PromptTuningInit, TaskType, get_peft_model ) from model.peft.tuner import AdaLoraConfig from transformers import BitsAndBytesConfig from packaging import version from .glm.tokenization_glm_deprecated import GLMChineseTokenizer
17,448
# coding=utf-8 # Copyright (c) 2023 Ant Group. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. sys.path.append("..") # from .glm.modeling_glm import GLMForConditionalGeneration # from .glm.configuration_glm import GLMConfig # from .glm.tokenization_glm import GLMTokenizer try: except ImportError: BitsAndBytesConfig = None try: except ImportError: bnb = None def find_all_linear_names(args, model): cls = bnb.nn.Linear4bit if args.bits == 4 else (bnb.nn.Linear8bitLt if args.bits == 8 else torch.nn.Linear) lora_module_names = set() for name, module in model.named_modules(): if isinstance(module, cls): names = name.split('.') lora_module_names.add(names[0] if len(names) == 1 else names[-1]) if 'lm_head' in lora_module_names: # needed for 16-bit lora_module_names.remove('lm_head') return list(lora_module_names) def setup_model(args, logger, use_cache=False): # Load pretrained model and tokenizer if args.pretrained_model_path: # TODO: 实现from pretrained读tokenizer if args.model_type == 'gpt_neox': # if args.tokenizer_type: # tokenizer = build_tokenizer(args) # tokenizer.eod_token = "<|endoftext|>" # tokenizer.pad_token = "<|pad|>" # # tokenizer.sop_token = "<|endoftext|>" # 适配multi task dataset # # tokenizer.eop_token = "<|endoftext|>" # tokenizer.eod_id = tokenizer.tokenize(tokenizer.eod_token)[0] # tokenizer.pad_id = tokenizer.tokenize(tokenizer.pad_token)[0] # else: tokenizer = GPTNeoXTokenizerFast.from_pretrained(args.pretrained_model_path) # tokenizer = PreTrainedTokenizerFast(tokenizer_file=args.vocab_file) tokenizer.eod_token = "<|endoftext|>" tokenizer.pad_token = "<|pad|>" tokenizer.sop_token = "<|endoftext|>" # 适配multi task dataset tokenizer.eop_token = "<|endoftext|>" tokenizer.eod_id = tokenizer.convert_tokens_to_ids(tokenizer.eod_token) tokenizer.pad_id = tokenizer.convert_tokens_to_ids(tokenizer.pad_token) print_rank_0(f'tokenizer {tokenizer.eod_token} id: {tokenizer.eod_id}') print_rank_0(f'tokenizer {tokenizer.pad_token} id: {tokenizer.pad_id}') elif args.model_type == 'llama': tokenizer = LlamaTokenizerFast.from_pretrained(args.pretrained_model_path) # tokenizer = AutoTokenizer.from_pretrained( # args.pretrained_model_path, # trust_remote_code=True, # ) tokenizer.eod_token = "</s>" tokenizer.eos_token = "</s>" tokenizer.bos_token = "<s>" tokenizer.pad_token = "[PAD]" tokenizer.unk_token = "<unk>" tokenizer.sop_token = "</s>" # 适配multi task dataset tokenizer.eop_token = "</s>" tokenizer.eod_id = tokenizer.convert_tokens_to_ids(tokenizer.eod_token) tokenizer.eos_id = tokenizer.convert_tokens_to_ids(tokenizer.eos_token) tokenizer.bos_id = tokenizer.convert_tokens_to_ids(tokenizer.bos_token) tokenizer.pad_id = tokenizer.convert_tokens_to_ids(tokenizer.pad_token) tokenizer.unk_id = tokenizer.convert_tokens_to_ids(tokenizer.unk_token) print_rank_0(f'tokenizer {tokenizer.eod_token} id: {tokenizer.eod_id}') print_rank_0(f'tokenizer {tokenizer.eos_token} id: {tokenizer.eos_id}') print_rank_0(f'tokenizer {tokenizer.bos_token} id: {tokenizer.bos_id}') print_rank_0(f'tokenizer {tokenizer.pad_token} id: {tokenizer.pad_id}') print_rank_0(f'tokenizer {tokenizer.unk_token} id: {tokenizer.unk_id}') elif args.model_type == 'glm': if is_old_version(args.pretrained_model_path): tokenizer = GLMChineseTokenizer.from_pretrained(args.pretrained_model_path) else: tokenizer = GLMTokenizer.from_pretrained(args.pretrained_model_path) elif args.train_mode == 'sst': # tokenizer = build_tokenizer(args) tokenizer = PreTrainedTokenizerFast(tokenizer_file=args.vocab_file) tokenizer.eod_token = "<|endoftext|>" tokenizer.pad_token = "<|pad|>" tokenizer.sop_token = "<|endoftext|>" # 适配multi task dataset tokenizer.eop_token = "<|endoftext|>" tokenizer.eod_id = tokenizer.convert_tokens_to_ids(tokenizer.eod_token) tokenizer.pad_id = tokenizer.convert_tokens_to_ids(tokenizer.pad_token) print_rank_0(f'tokenizer {tokenizer.eod_token} id: {tokenizer.eod_id}') print_rank_0(f'tokenizer {tokenizer.pad_token} id: {tokenizer.pad_id}') else: raise ValueError( "You are instantiating a new tokenizer from scratch. This is not supported by this script." "You can do it from another script, save it, and load it from here, using --tokenizer_path." ) if args.model_type == 'gpt_neox': auto_config = GPTNeoXConfig auto_model_class = GPTNeoXForCausalLM elif args.model_type == 'llama':
# coding=utf-8 # Copyright (c) 2023 Ant Group. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. sys.path.append("..") # from .glm.modeling_glm import GLMForConditionalGeneration # from .glm.configuration_glm import GLMConfig # from .glm.tokenization_glm import GLMTokenizer try: except ImportError: BitsAndBytesConfig = None try: except ImportError: bnb = None def find_all_linear_names(args, model): cls = bnb.nn.Linear4bit if args.bits == 4 else (bnb.nn.Linear8bitLt if args.bits == 8 else torch.nn.Linear) lora_module_names = set() for name, module in model.named_modules(): if isinstance(module, cls): names = name.split('.') lora_module_names.add(names[0] if len(names) == 1 else names[-1]) if 'lm_head' in lora_module_names: # needed for 16-bit lora_module_names.remove('lm_head') return list(lora_module_names) def setup_model(args, logger, use_cache=False): # Load pretrained model and tokenizer if args.pretrained_model_path: # TODO: 实现from pretrained读tokenizer if args.model_type == 'gpt_neox': # if args.tokenizer_type: # tokenizer = build_tokenizer(args) # tokenizer.eod_token = "<|endoftext|>" # tokenizer.pad_token = "<|pad|>" # # tokenizer.sop_token = "<|endoftext|>" # 适配multi task dataset # # tokenizer.eop_token = "<|endoftext|>" # tokenizer.eod_id = tokenizer.tokenize(tokenizer.eod_token)[0] # tokenizer.pad_id = tokenizer.tokenize(tokenizer.pad_token)[0] # else: tokenizer = GPTNeoXTokenizerFast.from_pretrained(args.pretrained_model_path) # tokenizer = PreTrainedTokenizerFast(tokenizer_file=args.vocab_file) tokenizer.eod_token = "<|endoftext|>" tokenizer.pad_token = "<|pad|>" tokenizer.sop_token = "<|endoftext|>" # 适配multi task dataset tokenizer.eop_token = "<|endoftext|>" tokenizer.eod_id = tokenizer.convert_tokens_to_ids(tokenizer.eod_token) tokenizer.pad_id = tokenizer.convert_tokens_to_ids(tokenizer.pad_token) print_rank_0(f'tokenizer {tokenizer.eod_token} id: {tokenizer.eod_id}') print_rank_0(f'tokenizer {tokenizer.pad_token} id: {tokenizer.pad_id}') elif args.model_type == 'llama': tokenizer = LlamaTokenizerFast.from_pretrained(args.pretrained_model_path) # tokenizer = AutoTokenizer.from_pretrained( # args.pretrained_model_path, # trust_remote_code=True, # ) tokenizer.eod_token = "</s>" tokenizer.eos_token = "</s>" tokenizer.bos_token = "<s>" tokenizer.pad_token = "[PAD]" tokenizer.unk_token = "<unk>" tokenizer.sop_token = "</s>" # 适配multi task dataset tokenizer.eop_token = "</s>" tokenizer.eod_id = tokenizer.convert_tokens_to_ids(tokenizer.eod_token) tokenizer.eos_id = tokenizer.convert_tokens_to_ids(tokenizer.eos_token) tokenizer.bos_id = tokenizer.convert_tokens_to_ids(tokenizer.bos_token) tokenizer.pad_id = tokenizer.convert_tokens_to_ids(tokenizer.pad_token) tokenizer.unk_id = tokenizer.convert_tokens_to_ids(tokenizer.unk_token) print_rank_0(f'tokenizer {tokenizer.eod_token} id: {tokenizer.eod_id}') print_rank_0(f'tokenizer {tokenizer.eos_token} id: {tokenizer.eos_id}') print_rank_0(f'tokenizer {tokenizer.bos_token} id: {tokenizer.bos_id}') print_rank_0(f'tokenizer {tokenizer.pad_token} id: {tokenizer.pad_id}') print_rank_0(f'tokenizer {tokenizer.unk_token} id: {tokenizer.unk_id}') elif args.model_type == 'glm': if is_old_version(args.pretrained_model_path): tokenizer = GLMChineseTokenizer.from_pretrained(args.pretrained_model_path) else: tokenizer = GLMTokenizer.from_pretrained(args.pretrained_model_path) elif args.train_mode == 'sst': # tokenizer = build_tokenizer(args) tokenizer = PreTrainedTokenizerFast(tokenizer_file=args.vocab_file) tokenizer.eod_token = "<|endoftext|>" tokenizer.pad_token = "<|pad|>" tokenizer.sop_token = "<|endoftext|>" # 适配multi task dataset tokenizer.eop_token = "<|endoftext|>" tokenizer.eod_id = tokenizer.convert_tokens_to_ids(tokenizer.eod_token) tokenizer.pad_id = tokenizer.convert_tokens_to_ids(tokenizer.pad_token) print_rank_0(f'tokenizer {tokenizer.eod_token} id: {tokenizer.eod_id}') print_rank_0(f'tokenizer {tokenizer.pad_token} id: {tokenizer.pad_id}') else: raise ValueError( "You are instantiating a new tokenizer from scratch. This is not supported by this script." "You can do it from another script, save it, and load it from here, using --tokenizer_path." ) if args.model_type == 'gpt_neox': auto_config = GPTNeoXConfig auto_model_class = GPTNeoXForCausalLM elif args.model_type == 'llama':
auto_config = LlamaConfig
4
2023-11-02 01:37:01+00:00
24k
bytedance/cryostar
projects/star/train_atom.py
[ { "identifier": "SpatialGridTranslate", "path": "cryostar/utils/transforms.py", "snippet": "class SpatialGridTranslate(torch.nn.Module):\n\n def __init__(self, D, device=None) -> None:\n super().__init__()\n self.D = D\n # yapf: disable\n coords = torch.stack(torch.meshgrid([\n torch.linspace(-1.0, 1.0, self.D, device=device),\n torch.linspace(-1.0, 1.0, self.D, device=device)],\n indexing=\"ij\"), dim=-1).reshape(-1, 2)\n # yapf: enable\n self.register_buffer(\"coords\", coords)\n\n def transform(self, images: torch.Tensor, trans: torch.Tensor):\n \"\"\"\n The `images` are stored in `YX` mode, so the `trans` is also `YX`!\n\n Supposing that D is 96, a point is at 0.0:\n - adding 48 should move it to the right corner which is 1.0\n 1.0 = 0.0 + 48 / (96 / 2)\n - adding 96(>48) should leave it at 0.0\n 0.0 = 0.0 + 96 / (96 / 2) - 2.0\n - adding -96(<48) should leave it at 0.0\n 0.0 = 0.0 - 96 / (96 / 2) + 2.0\n\n Input:\n images: (B, NY, NX)\n trans: (B, T, 2)\n\n Returns:\n images: (B, T, NY, NX)\n \"\"\"\n B, NY, NX = images.shape\n assert self.D == NY == NX\n assert images.shape[0] == trans.shape[0]\n\n grid = einops.rearrange(self.coords, \"N C2 -> 1 1 N C2\") - \\\n einops.rearrange(trans, \"B T C2 -> B T 1 C2\") * 2 / self.D\n grid = grid.flip(-1) # convert the first axis from slow-axis to fast-axis\n grid[grid >= 1] -= 2\n grid[grid <= -1] += 2\n grid.clamp_(-1.0, 1.0)\n\n sampled = F.grid_sample(einops.rearrange(images, \"B NY NX -> B 1 NY NX\"), grid, align_corners=True)\n\n sampled = einops.rearrange(sampled, \"B 1 T (NY NX) -> B T NY NX\", NX=NX, NY=NY)\n return sampled" }, { "identifier": "StarfileDataSet", "path": "cryostar/utils/dataio.py", "snippet": "class StarfileDataSet(Dataset):\n\n def __init__(self, cfg: StarfileDatasetConfig):\n super().__init__()\n self.cfg = cfg\n self.df = starfile.read(Path(cfg.starfile_path))\n\n if \"optics\" in self.df:\n optics_df = self.df[\"optics\"]\n particles_df = self.df[\"particles\"]\n else:\n optics_df = None\n particles_df = self.df\n self.particles_df = particles_df\n\n if cfg.apix is None:\n if optics_df is not None and \"rlnImagePixelSize\" in optics_df:\n self.apix = float(optics_df[\"rlnImagePixelSize\"][0])\n print(f\"Infer dataset apix={self.apix} from first optic group.\")\n elif \"rlnDetectorPixelSize\" in particles_df and \"rlnMagnification\" in particles_df:\n self.apix = float(particles_df[\"rlnDetectorPixelSize\"][0] / particles_df[\"rlnMagnification\"][0] * 1e4)\n print(f\"Infer dataset apix={self.apix} from first particle meta data.\")\n else:\n raise AttributeError(\"Cannot parse apix from starfile, please set it in config by hand.\")\n else:\n self.apix = cfg.apix\n\n if cfg.side_shape is None:\n tmp_mrc_path = osp.join(cfg.dataset_dir, particles_df[\"rlnImageName\"][0].split('@')[-1])\n with mrcfile.mmap(tmp_mrc_path, mode=\"r\", permissive=True) as m:\n self.side_shape = m.data.shape[-1]\n print(f\"Infer dataset side_shape={self.side_shape} from the 1st particle.\")\n else:\n self.side_shape = cfg.side_shape\n\n self.num_proj = len(particles_df)\n\n self.down_side_shape = self.side_shape\n if cfg.down_side_shape is not None:\n self.down_side_shape = cfg.down_side_shape\n\n if cfg.mask_rad is not None:\n self.mask = Mask(self.down_side_shape, cfg.mask_rad)\n\n self.f_mu = None\n self.f_std = None\n\n def __len__(self):\n return self.num_proj\n\n def estimate_normalization(self):\n if self.f_mu is None and self.f_std is None:\n f_sub_data = []\n # I have checked that the standard deviation of 10/100/1000 particles is similar\n for i in range(0, len(self), len(self) // 100):\n f_sub_data.append(self[i][\"fproj\"])\n f_sub_data = torch.cat(f_sub_data, dim=0)\n # self.f_mu = torch.mean(f_sub_data)\n self.f_mu = 0.0 # just follow cryodrgn\n self.f_std = torch.std(f_sub_data).item()\n else:\n raise Exception(\"The normalization factor has been estimated!\")\n\n def __getitem__(self, idx):\n item_row = self.particles_df.iloc[idx]\n try:\n img_name_raw = item_row[\"rlnImageName\"]\n in_mrc_idx, img_name = item_row[\"rlnImageName\"].split(\"@\")\n in_mrc_idx = int(in_mrc_idx) - 1\n mrc_path = osp.join(self.cfg.dataset_dir, img_name)\n with mrcfile.mmap(mrc_path, mode=\"r\", permissive=True) as mrc:\n if mrc.data.ndim > 2:\n proj = torch.from_numpy(np.array(mrc.data[in_mrc_idx])).float() * self.cfg.scale_images\n else:\n # the mrcs file can contain only one particle\n proj = torch.from_numpy(np.array(mrc.data)).float() * self.cfg.scale_images\n\n # get (1, side_shape, side_shape) proj\n if len(proj.shape) == 2:\n proj = proj[None, :, :] # add a dummy channel (for consistency w/ img fmt)\n else:\n assert len(proj.shape) == 3 and proj.shape[0] == 1 # some starfile already have a dummy channel\n\n # down-sample\n if self.down_side_shape != self.side_shape:\n if self.cfg.down_method == \"interp\":\n proj = tvf.resize(proj, [self.down_side_shape, ] * 2, antialias=True)\n elif self.cfg.down_method == \"fft\":\n proj = downsample_2d(proj[0, :, :], self.down_side_shape)[None, :, :]\n else:\n raise NotImplementedError\n\n if self.cfg.mask_rad is not None:\n proj = self.mask(proj)\n\n except Exception as e:\n print(f\"WARNING: Particle image {img_name_raw} invalid! Setting to zeros.\")\n print(e)\n proj = torch.zeros(1, self.down_side_shape, self.down_side_shape)\n\n if self.cfg.power_images != 1.0:\n proj *= self.cfg.power_images\n\n # Generate CTF from CTF paramaters\n defocusU = torch.from_numpy(np.array(item_row[\"rlnDefocusU\"] / 1e4, ndmin=2)).float()\n defocusV = torch.from_numpy(np.array(item_row[\"rlnDefocusV\"] / 1e4, ndmin=2)).float()\n angleAstigmatism = torch.from_numpy(np.radians(np.array(item_row[\"rlnDefocusAngle\"], ndmin=2))).float()\n\n # Read \"GT\" orientations\n if self.cfg.ignore_rots:\n rotmat = torch.eye(3).float()\n else:\n # yapf: disable\n rotmat = torch.from_numpy(euler_angles2matrix(\n np.radians(-item_row[\"rlnAngleRot\"]),\n # np.radians(particle[\"rlnAngleTilt\"]) * (-1 if self.cfg.invert_hand else 1),\n np.radians(-item_row[\"rlnAngleTilt\"]),\n np.radians(-item_row[\"rlnAnglePsi\"]))\n ).float()\n # yapf: enable\n\n # Read \"GT\" shifts\n if self.cfg.ignore_trans:\n shiftX = torch.tensor([0.])\n shiftY = torch.tensor([0.])\n else:\n # support early starfile formats\n # Particle translations used to be in pixels (rlnOriginX and rlnOriginY) but this changed to Angstroms\n # (rlnOriginXAngstrom and rlnOriginYAngstrom) in relion 3.1.\n # https://relion.readthedocs.io/en/release-3.1/Reference/Conventions.html\n if \"rlnOriginXAngst\" in item_row:\n shiftX = torch.from_numpy(np.array(item_row[\"rlnOriginXAngst\"], dtype=np.float32))\n shiftY = torch.from_numpy(np.array(item_row[\"rlnOriginYAngst\"], dtype=np.float32))\n else:\n shiftX = torch.from_numpy(np.array(item_row[\"rlnOriginX\"] * self.apix, dtype=np.float32))\n shiftY = torch.from_numpy(np.array(item_row[\"rlnOriginY\"] * self.apix, dtype=np.float32))\n\n fproj = primal_to_fourier_2d(proj)\n\n if self.f_mu is not None:\n fproj = (fproj - self.f_mu) / self.f_std\n proj = fourier_to_primal_2d(fproj).real\n\n in_dict = {\n \"proj\": proj,\n \"rotmat\": rotmat,\n \"defocusU\": defocusU,\n \"defocusV\": defocusV,\n \"shiftX\": shiftX,\n \"shiftY\": shiftY,\n \"angleAstigmatism\": angleAstigmatism,\n \"idx\": torch.tensor(idx, dtype=torch.long),\n \"fproj\": fproj,\n \"imgname_raw\": img_name_raw\n }\n\n if \"rlnClassNumber\" in item_row:\n in_dict[\"class_id\"] = item_row[\"rlnClassNumber\"]\n\n return in_dict" }, { "identifier": "StarfileDatasetConfig", "path": "cryostar/utils/dataio.py", "snippet": "class StarfileDatasetConfig:\n dataset_dir: str\n starfile_path: str\n # if is not specified, the following apix, and side_shape will be inferred from starfile\n apix: float = None\n side_shape: int = None\n # down-sample the original image or not\n down_side_shape: int = None\n down_method: str = \"interp\"\n # apply a circular mask on input image or not\n mask_rad: float = None\n # change image values\n scale_images: float = 1.0\n power_images: float = field(\n default=1.0,\n metadata={\"help\": \"Change the power of the signal by multiplying a constant number.\"})\n # ignore pose from starfile or not\n ignore_trans: bool = False\n ignore_rots: bool = False\n # invert_hand: bool = field(\n # default=False,\n # metadata={\"help\": \"Invert handedness when reading relion data.\"})" }, { "identifier": "Mask", "path": "cryostar/utils/dataio.py", "snippet": "class Mask(torch.nn.Module):\n\n def __init__(self, im_size, rad):\n super(Mask, self).__init__()\n\n mask = torch.lt(torch.linspace(-1, 1, im_size)[None]**2 + torch.linspace(-1, 1, im_size)[:, None]**2, rad**2)\n # float for pl ddp broadcast compatible\n self.register_buffer('mask', mask.float())\n self.num_masked = torch.sum(mask).item()\n\n def forward(self, x):\n return x * self.mask" }, { "identifier": "CTFRelion", "path": "cryostar/utils/ctf_utils.py", "snippet": "class CTFRelion(CTFBase):\n \"\"\"\n BUG: There are two bugs in this file:\n 1. `self.angleFrequency` has some error for even-sized grid.\n 2. `local_defocus` in `get_ctf()` has some error, `angleAstigmatism` should be\n replaced with `defocusU - defocusV`.\n\n The bugs will not affect real-world data too much. But you may encounter some issues\n on simulated datasets. Use CTFCryoDRGN instead.\n \"\"\"\n\n def __init__(self,\n size=257,\n resolution=0.8,\n kV=300.0,\n valueNyquist=1.,\n defocusU=1.,\n defocusV=1.,\n angleAstigmatism=0.,\n cs=2.7,\n phasePlate=0.,\n amplitudeContrast=.1,\n bFactor=0.,\n num_particles=500,\n requires_grad=False,\n precompute=False,\n flip_images=False):\n super(CTFRelion, self).__init__(resolution, num_particles, requires_grad)\n self.requires_grad = requires_grad\n self.flip_images = flip_images\n\n self.size = size # in pixel\n self.resolution = resolution # in angstrom\n self.kV = kV # in kilovolt\n\n self.valueNyquist = valueNyquist\n self.phasePlate = phasePlate / 180. * np.pi # in radians (converted from degrees)\n self.amplitudeContrast = amplitudeContrast\n self.bFactor = bFactor\n\n self.frequency = 1. / self.resolution\n\n self.wavelength = self._get_ewavelength(self.kV * 1e3) # input in V (so we convert kv*1e3)\n\n angleAstigmatism = angleAstigmatism / 180. * np.pi # input in degree converted in radian\n cs = cs * 1e7 # input in mm converted in angstrom\n # the angleAstigmatism, defocusU, defocusV and cs are nn.Parameter of size (N, 1, 1)\n self.angleAstigmatism = nn.Parameter(angleAstigmatism * torch.ones((num_particles, 1, 1), dtype=torch.float32),\n requires_grad=requires_grad)\n self.cs = nn.Parameter(cs * torch.ones((num_particles, 1, 1), dtype=torch.float32), requires_grad=requires_grad)\n self.defocusU = nn.Parameter(defocusU * torch.ones((num_particles, 1, 1), dtype=torch.float32),\n requires_grad=requires_grad)\n self.defocusV = nn.Parameter(defocusV * torch.ones((num_particles, 1, 1), dtype=torch.float32),\n requires_grad=requires_grad)\n\n self.precomputed_filters = precompute\n\n ax = torch.linspace(-1. / (2. * resolution), 1 / (2. * resolution), self.size)\n mx, my = torch.meshgrid(ax, ax, indexing=\"ij\")\n self.register_buffer(\"r2\", mx**2 + my**2)\n self.register_buffer(\"r\", torch.sqrt(self.r2))\n self.register_buffer(\"angleFrequency\", torch.atan2(my, mx))\n\n if not self.requires_grad and self.precomputed_filters:\n print(\"Precomputing hFourier in CTF\")\n self.register_buffer('hFourier', self.get_ctf(torch.arange(num_particles), num_particles))\n\n def _get_ewavelength(self, U):\n # assumes V as input, returns wavelength in angstrom\n h = scipy.constants.h\n e = scipy.constants.e\n c = scipy.constants.c\n m0 = scipy.constants.m_e\n\n return h / math.sqrt(2. * m0 * e * U) / math.sqrt(1 + e * U / (2 * m0 * c**2)) * 1e10\n\n def get_ctf(self, idcs, B, cpu_params={}, frequency_marcher=None):\n defocusU = self.defocusU[idcs, :, :]\n defocusV = self.defocusV[idcs, :, :]\n angleAstigmatism = self.angleAstigmatism[idcs, :, :]\n cs = self.cs[idcs, :, :]\n\n ac = self.amplitudeContrast\n pc = math.sqrt(1. - ac**2)\n K1 = np.pi / 2. * cs * self.wavelength**3\n K2 = np.pi * self.wavelength\n\n # Cut-off from frequency marcher\n if frequency_marcher is not None:\n self.size_after_fm = 2 * frequency_marcher.f + 1\n if self.size_after_fm > self.size:\n self.size_after_fm = self.size\n angleFrequency = frequency_marcher.cut_coords_plane(self.angleFrequency.reshape(\n self.size, self.size, 1)).reshape(self.size_after_fm, self.size_after_fm)\n r2 = frequency_marcher.cut_coords_plane(self.r2.reshape(self.size, self.size,\n 1)).reshape(self.size_after_fm, self.size_after_fm)\n else:\n self.size_after_fm = self.size\n angleFrequency = self.angleFrequency\n r2 = self.r2\n\n angle = angleFrequency - angleAstigmatism\n local_defocus = 1e4 * (defocusU + defocusV) / 2. + angleAstigmatism * torch.cos(2. * angle)\n\n gamma = K1 * r2**2 - K2 * r2 * local_defocus - self.phasePlate\n hFourier = -pc * torch.sin(gamma) + ac * torch.cos(gamma)\n\n if self.valueNyquist != 1:\n decay = np.sqrt(-np.log(self.valueNyquist)) * 2. * self.resolution\n envelope = torch.exp(-self.frequency * decay**2 * r2)\n hFourier *= envelope\n\n return hFourier\n\n def oversample_multiply_crop(self, x_fourier, hFourier):\n # we assume that the shape of the CTF is always going to be bigger\n # than the size of the input image\n input_sz = x_fourier.shape[-1]\n if input_sz != self.size_after_fm:\n x_primal = fourier_to_primal_2d(x_fourier)\n\n pad_len = (self.size_after_fm - x_fourier.shape[-1]) // 2 # here we assume even lengths\n p2d = (pad_len, pad_len, pad_len, pad_len)\n x_primal_padded = F.pad(x_primal, p2d, 'constant', 0)\n\n x_fourier_padded = primal_to_fourier_2d(x_primal_padded)\n\n x_fourier_padded_filtered = x_fourier_padded * hFourier[:, None, :, :]\n return x_fourier_padded_filtered[..., pad_len:-pad_len, pad_len:-pad_len]\n else:\n return x_fourier * hFourier[:, None, :, :]\n\n def get_cpu_params(self, idcs, ctf_params, flip=False):\n batch_size = idcs.shape[0]\n self.defocusU[idcs, :, :] = ctf_params['defocusU'][:batch_size] if not flip else\\\n ctf_params['defocusU'][batch_size:]\n self.defocusV[idcs, :, :] = ctf_params['defocusV'][:batch_size] if not flip else\\\n ctf_params['defocusV'][batch_size:]\n self.angleAstigmatism[idcs, :, :] = ctf_params['angleAstigmatism'][:batch_size] if not flip else\\\n ctf_params['angleAstigmatism'][batch_size:]\n cpu_params = {}\n return cpu_params\n\n def forward(self, x_fourier, idcs=0, ctf_params={}, mode='gt', frequency_marcher=None):\n # This is when we want to prescribe parameters for the CTF\n if x_fourier.dim() == 3:\n x_fourier = x_fourier[None, ...]\n # x_fourier: B, 1, S, S\n batch_size = len(idcs)\n cpu_params = {}\n if ctf_params:\n cpu_params = self.get_cpu_params(idcs, ctf_params, flip=False)\n\n # if new params for the CTF have been prescribed or we are optimizing it\n # then request the evaluation of the CTF\n if not ctf_params and self.precomputed_filters and not self.requires_grad:\n hFourier = self.hFourier[idcs, :, :]\n else:\n hFourier = self.get_ctf(idcs, batch_size, cpu_params=cpu_params, frequency_marcher=frequency_marcher)\n\n if self.flip_images:\n flipped_hFourier = torch.flip(hFourier, [1, 2])\n\n hFourier = torch.cat([hFourier, flipped_hFourier], dim=0)\n\n return self.oversample_multiply_crop(x_fourier, hFourier)" }, { "identifier": "CTFCryoDRGN", "path": "cryostar/utils/ctf_utils.py", "snippet": "class CTFCryoDRGN(CTFBase):\n\n def __init__(self,\n size,\n resolution,\n num_particles=None,\n kV=300,\n cs=2.0,\n amplitudeContrast=0.1,\n requires_grad=False):\n super(CTFBase, self).__init__()\n self.size = size\n self.resolution = resolution\n self.requires_grad = requires_grad\n self.kV = kV\n self.cs = cs\n self.ac = amplitudeContrast\n # ax = torch.linspace(-1. / (2. * resolution), 1 / (2. * resolution), self.size)\n # mx, my = torch.meshgrid(ax, ax, indexing=\"ij\")\n ax = torch.fft.fftshift(torch.fft.fftfreq(self.size, self.resolution))\n mx, my = torch.meshgrid(ax, ax, indexing=\"xy\")\n freqs = torch.stack([mx.flatten(), my.flatten()], 1)\n self.register_buffer(\"freqs\", freqs)\n\n def get_ctf(self, ctf_params={}):\n bsz = len(ctf_params[\"defocusU\"])\n device = self.freqs.device\n hFourier = compute_ctf(freqs=self.freqs.repeat(bsz, 1, 1),\n dfu=(ctf_params[\"defocusU\"] * 1e4).squeeze(1),\n dfv=(ctf_params[\"defocusV\"] * 1e4).squeeze(1),\n dfang=torch.rad2deg(ctf_params[\"angleAstigmatism\"]).squeeze(1),\n volt=torch.tensor(self.kV, device=device).repeat(bsz, 1),\n cs=torch.tensor(self.cs, device=device).repeat(bsz, 1),\n w=torch.tensor(self.ac, device=device).repeat(bsz,\n 1)).reshape(bsz, self.size, self.size)\n return hFourier\n\n def forward(self, x_fourier, idcs=0, ctf_params={}, mode='gt', frequency_marcher=None):\n hFourier = -self.get_ctf(ctf_params)\n return x_fourier * hFourier[:, None, :, :]" }, { "identifier": "calc_cor_loss", "path": "cryostar/utils/losses.py", "snippet": "def calc_cor_loss(pred_images, gt_images, mask=None):\n if mask is not None:\n pred_images = mask(pred_images)\n gt_images = mask(gt_images)\n pixel_num = mask.num_masked\n else:\n pixel_num = pred_images.shape[-2] * pred_images.shape[-1]\n\n # b, c, h, w -> b, c, num_pix\n pred_images = pred_images.flatten(start_dim=2)\n gt_images = gt_images.flatten(start_dim=2)\n\n # b, c\n dots = (pred_images * gt_images).sum(-1)\n # b, c -> b, c\n err = -dots / (gt_images.std(-1) + 1e-5) / (pred_images.std(-1) + 1e-5)\n # b, c -> b -> 1 value\n err = err.sum(-1).mean() / pixel_num\n return err" }, { "identifier": "calc_kl_loss", "path": "cryostar/utils/losses.py", "snippet": "def calc_kl_loss(mu, log_var, free_bits, reduction=\"mean\"):\n kld_loss = -0.5 * (1 + log_var - mu.pow(2) - log_var.exp())\n # free bits\n kld_loss = torch.clamp(kld_loss, free_bits) # (bsz, z-dim)\n kld_loss = torch.mean(kld_loss, dim=1) # (bsz, )\n if reduction == \"mean\":\n kld_loss = torch.mean(kld_loss) # averaged over bsz x z-dim\n elif reduction == \"none\":\n kld_loss = kld_loss\n else:\n raise NotImplementedError\n return kld_loss" }, { "identifier": "log_to_current", "path": "cryostar/utils/misc.py", "snippet": "def set_seed(seed: int = 42):\ndef chain(arg, *funcs):\ndef convert_to_numpy(*args):\ndef CHECK_SHAPE(tensor, expected_shape):\ndef ASSERT_SHAPE(tensor, expected_shape):\ndef parse_mmengine_args(override_mode=\"default\"):\ndef flatten_nested_dict(nested: Union[dict, Config]) -> dict:\ndef warmup(warmup_step, lower=0.0, upper=1.0):\n def run(cur_step):\ndef init_mmengine_config(args):\ndef init_mmengine_exp(args,\n exp_prefix='',\n backup_list=None,\n inplace=True,\n work_dir_name=\"work_dirs\",\n project_name=\"cryostar\",\n tensorboard=False):\ndef _get_next_version(root_dir, dir_name_prefix):\ndef pl_init_exp(override_mode=\"default\",\n exp_prefix='',\n backup_list=None,\n inplace=False,\n work_dir_name=\"work_dirs\",\n project_name=\"cryostar\"):\ndef save_pdb(CAs, path, ref_pdb_path):\ndef load_CAs_from_pdb(file):\ndef load_NCaC_from_pdb(file):\ndef load_chain_A(pdb_path):\ndef points_to_pdb(path_to_save, points: np.ndarray):\ndef point_stack_to_pdb(path_to_save, point_stack: np.ndarray):\ndef find_rigid_alignment(A, B):\ndef batch_find_rigid_alignment(A, B):\ndef pretty_dict(x, precision=3):\ndef create_sphere_mask(d, h, w, center=None, radius=None) -> np.ndarray:\ndef create_circular_mask(h, w, center=None, radius=None) -> np.ndarray:\n H = A_c.T.mm(B_c)\n U, S, V = torch.svd(H)\n R = V.mm(U.T)\n H = einops.einsum(A_c, B_c, \"b n c1, b n c2 -> b c1 c2\")\n V = VmT.mT\n R = einops.einsum(V, U.transpose(2, 1), \"b c1 c2, b c2 c3 -> b c1 c3\")" }, { "identifier": "bt_save_pdb", "path": "cryostar/utils/pdb_tools.py", "snippet": "def bt_save_pdb(file_path: Union[str, Path], array: Union[AtomArray, AtomArrayStack], **kwargs):\n \"\"\"Save biotite AtomArray or AtomArrayStack to pdb file\n\n Parameters\n ----------\n file_path: save file path\n array: the structure to be saved\n kwargs: additional parameters to be passed, always empty\n\n \"\"\"\n bt_struc.io.save_structure(file_path, array, **kwargs)" }, { "identifier": "EMAN2Grid", "path": "cryostar/gmm/gmm.py", "snippet": "class EMAN2Grid(BaseGrid):\n \"\"\"EMAN2 style grid.\n origin set to -(side_shape // 2) * voxel_size\n\n \"\"\"\n\n def __init__(self, side_shape, voxel_size):\n origin = -side_shape // 2 * voxel_size\n super().__init__(side_shape=side_shape, voxel_size=voxel_size, origin=origin)" }, { "identifier": "batch_projection", "path": "cryostar/gmm/gmm.py", "snippet": "def batch_projection(gauss: Gaussian, rot_mats: torch.Tensor, line_grid: Grid) -> torch.Tensor:\n \"\"\"A quick version of e2gmm projection.\n\n Parameters\n ----------\n gauss: (b/1, num_centers, 3) mus, (b/1, num_centers) sigmas and amplitudes\n rot_mats: (b, 3, 3)\n line_grid: (num_pixels, 3) coords, (nx, ) shape\n\n Returns\n -------\n proj: (b, y, x) projections\n \"\"\"\n\n centers = einops.einsum(rot_mats, gauss.mus, \"b c31 c32, b nc c32 -> b nc c31\")\n\n sigmas = einops.rearrange(gauss.sigmas, 'b nc -> b 1 nc')\n sigmas = 2 * sigmas**2\n\n proj_x = einops.rearrange(line_grid.coords, \"nx -> 1 nx 1\") - einops.rearrange(centers[..., 0], \"b nc -> b 1 nc\")\n proj_x = torch.exp(-proj_x**2 / sigmas)\n\n proj_y = einops.rearrange(line_grid.coords, \"ny -> 1 ny 1\") - einops.rearrange(centers[..., 1], \"b nc -> b 1 nc\")\n proj_y = torch.exp(-proj_y**2 / sigmas)\n\n proj = einops.einsum(gauss.amplitudes, proj_x, proj_y, \"b nc, b nx nc, b ny nc -> b nx ny\")\n proj = einops.rearrange(proj, \"b nx ny -> b ny nx\")\n return proj" }, { "identifier": "Gaussian", "path": "cryostar/gmm/gmm.py", "snippet": "class Gaussian:\n mus: Union[torch.Tensor, np.ndarray]\n sigmas: Union[torch.Tensor, np.ndarray]\n amplitudes: Union[torch.Tensor, np.ndarray]" }, { "identifier": "E3Deformer", "path": "cryostar/gmm/deformer.py", "snippet": "class E3Deformer(torch.nn.Module, DeformerProtocol):\n\n def transform(self, deformation, coords):\n ASSERT_SHAPE(coords, (None, 3))\n ASSERT_SHAPE(deformation, (None, coords.shape[0] * 3))\n\n bsz = deformation.shape[0]\n shift = deformation.reshape(bsz, -1, 3)\n return shift + coords" }, { "identifier": "NMADeformer", "path": "cryostar/gmm/deformer.py", "snippet": "class NMADeformer(torch.nn.Module, DeformerProtocol):\n def __init__(self, modes: torch.FloatTensor) -> None:\n super().__init__()\n modes = einops.rearrange(\n modes, \"(num_coords c3) num_modes -> num_modes num_coords c3\", c3=3\n )\n self.register_buffer(\"modes\", modes)\n self.num_modes = modes.shape[0]\n self.num_coords = modes.shape[1]\n\n def transform(self, deformation, coords):\n ASSERT_SHAPE(coords, (self.num_coords, 3))\n ASSERT_SHAPE(deformation, (None, 6 + self.num_modes))\n\n axis_angle = deformation[..., :3]\n translation = deformation[..., 3:6] * 10\n nma_coeff = deformation[..., 6:]\n rotation_matrix = axis_angle_to_matrix(axis_angle)\n\n nma_deform_e3 = einops.einsum(\n nma_coeff, self.modes, \"bsz num_modes, num_modes num_coords c3 -> bsz num_coords c3\"\n )\n rotated_coords = einops.einsum(rotation_matrix, nma_deform_e3 + coords,\n \"bsz c31 c32, bsz num_coords c31 -> bsz num_coords c32\")\n deformed_coords = rotated_coords + einops.rearrange(translation, \"bsz c3 -> bsz 1 c3\")\n return deformed_coords" }, { "identifier": "primal_to_fourier_2d", "path": "cryostar/utils/fft_utils.py", "snippet": "@torch.autocast(\"cuda\")\ndef primal_to_fourier_2d(r: torch.Tensor) -> torch.Tensor:\n with torch.autocast(\"cuda\", enabled=False):\n r = torch.fft.ifftshift(r.float(), dim=(-2, -1))\n f = torch.fft.fftshift(torch.fft.fftn(r, s=(r.shape[-2], r.shape[-1]), dim=(-2, -1)), dim=(-2, -1))\n return f" }, { "identifier": "fourier_to_primal_2d", "path": "cryostar/utils/fft_utils.py", "snippet": "def fourier_to_primal_2d(f: torch.Tensor) -> torch.Tensor:\n f = torch.fft.ifftshift(f, dim=(-2, -1))\n return torch.fft.fftshift(torch.fft.ifftn(f, s=(f.shape[-2], f.shape[-1]), dim=(-2, -1)), dim=(-2, -1))" }, { "identifier": "Polymer", "path": "cryostar/utils/polymer.py", "snippet": "class Polymer:\n chain_id: np.ndarray\n res_id: np.ndarray\n res_name: np.ndarray\n coord: np.ndarray\n atom_name: np.ndarray\n element: np.ndarray\n num_electron: np.ndarray\n\n def __init__(self, num):\n self.chain_id = np.empty(num, dtype=\"U4\")\n self.res_id = np.zeros(num, dtype=int)\n self.res_name = np.empty(num, dtype=\"U3\")\n self.coord = np.zeros((num, 3), dtype=np.float32)\n self.atom_name = np.empty(num, dtype=\"U6\")\n self.element = np.empty(num, dtype=\"U2\")\n self.num_electron = np.zeros(num, dtype=int)\n\n def __setitem__(self, index, kwargs):\n assert set(kwargs.keys()).issubset(f.name for f in dataclasses.fields(self))\n for k, v in kwargs.items():\n getattr(self, k)[index] = v\n\n def __getitem__(self, index):\n return {f.name: getattr(self, f.name)[index] for f in dataclasses.fields(self)}\n\n def __len__(self):\n return len(self.chain_id)\n\n @property\n def num_amino_acids(self):\n return np.sum(np.isin(self.atom_name, AA_ATOMS))\n\n @property\n def num_nucleotides(self):\n return np.sum(np.isin(self.atom_name, NT_ATOMS))\n\n @property\n def num_chains(self):\n return len(np.unique(self.chain_id))\n\n @classmethod\n def from_atom_arr(cls, atom_arr):\n assert isinstance(atom_arr, struc.AtomArray)\n\n nt_arr = atom_arr[struc.filter_nucleotides(atom_arr)]\n aa_arr = atom_arr[struc.filter_amino_acids(atom_arr)]\n\n num = 0\n if len(aa_arr) > 0:\n num += struc.get_residue_count(aa_arr)\n if len(nt_arr) > 0:\n for res in struc.residue_iter(nt_arr):\n valid_atoms = set(res.atom_name).intersection(NT_ATOMS)\n if len(valid_atoms) <= 0:\n raise UserWarning(f\"Nucleotides doesn't contain {' or '.join(NT_ATOMS)}.\")\n else:\n num += len(valid_atoms)\n meta = cls(num)\n\n def _update_res(tmp_res, kind=\"aa\"):\n nonlocal pos\n\n if kind == \"aa\":\n using_atom_names = AA_ATOMS\n filtered_res = tmp_res[struc.filter_peptide_backbone(tmp_res)]\n elif kind == \"nt\":\n using_atom_names = NT_ATOMS\n filtered_res = tmp_res\n else:\n raise NotImplemented\n\n valid_atom_names = set(tmp_res.atom_name).intersection(using_atom_names)\n\n for select_atom_name in valid_atom_names:\n meta[pos] = {\n \"chain_id\": tmp_res.chain_id[0],\n \"res_id\": tmp_res.res_id[0],\n \"res_name\": tmp_res.res_name[0],\n \"coord\": filtered_res[filtered_res.atom_name == select_atom_name].coord,\n \"atom_name\": select_atom_name,\n \"element\": filtered_res[filtered_res.atom_name == select_atom_name].element[0],\n \"num_electron\": get_num_electrons(tmp_res) // len(valid_atom_names)\n }\n pos += 1\n\n def _update(tmp_arr, kind=\"aa\"):\n nonlocal pos\n for chain in struc.chain_iter(tmp_arr):\n for tmp_res in struc.residue_iter(chain):\n _update_res(tmp_res, kind)\n\n pos = 0\n\n if len(aa_arr) > 0:\n _update(aa_arr, kind=\"aa\")\n if len(nt_arr) > 0:\n _update(nt_arr, kind=\"nt\")\n\n assert pos == num\n return meta\n\n @classmethod\n def from_pdb(cls, file_path):\n atom_arr = bt_read_pdb(file_path)\n if atom_arr.stack_depth() > 1:\n print(\"PDB file contains more than 1 models, select the 1st model\")\n atom_arr = atom_arr[0]\n return Polymer.from_atom_arr(atom_arr)\n\n def to_atom_arr(self):\n num = len(self)\n atom_arr = struc.AtomArray(num)\n atom_arr.coord = self.coord\n\n for f in dataclasses.fields(self):\n if f.name != \"coord\" and f.name in atom_arr.get_annotation_categories():\n atom_arr.set_annotation(f.name, getattr(self, f.name))\n # atom_arr.atom_name[atom_arr.atom_name == \"R\"] = \"CB\"\n return atom_arr" }, { "identifier": "NT_ATOMS", "path": "cryostar/utils/polymer.py", "snippet": "NT_ATOMS = (\"C1'\", )" }, { "identifier": "AA_ATOMS", "path": "cryostar/utils/polymer.py", "snippet": "AA_ATOMS = (\"CA\", )" }, { "identifier": "find_quaint_cutoff_pairs", "path": "cryostar/utils/dist_loss.py", "snippet": "def find_quaint_cutoff_pairs(coord_arr,\n chain_id_arr,\n res_id_arr,\n intra_chain_cutoff=12.,\n inter_chain_cutoff=12.,\n intra_chain_res_bound=None):\n sel_indices = []\n dist_map = distance.cdist(coord_arr, coord_arr, metric='euclidean')\n # 1. intra chain\n sel_mask = dist_map <= intra_chain_cutoff\n sel_mask = np.triu(sel_mask, k=1)\n # get indices of valid pairs\n indices_in_pdb = np.nonzero(sel_mask)\n indices_in_pdb = np.column_stack((indices_in_pdb[0], indices_in_pdb[1]))\n indices_in_pdb = indices_in_pdb[chain_id_arr[indices_in_pdb[:, 0]] == chain_id_arr[indices_in_pdb[:, 1]]]\n # filter by res_id\n if intra_chain_res_bound is not None:\n assert res_id_arr is not None\n res_ids = res_id_arr[indices_in_pdb]\n res_id_dist = np.abs(np.diff(res_ids, axis=1)).flatten()\n indices_in_pdb = indices_in_pdb[res_id_dist <= intra_chain_res_bound]\n\n sel_indices.append(indices_in_pdb)\n\n # 2. inter chain\n if inter_chain_cutoff is not None:\n sel_mask = dist_map <= inter_chain_cutoff\n sel_mask = np.triu(sel_mask, k=1)\n indices_in_pdb = np.nonzero(sel_mask)\n indices_in_pdb = np.column_stack((indices_in_pdb[0], indices_in_pdb[1]))\n indices_in_pdb = indices_in_pdb[chain_id_arr[indices_in_pdb[:, 0]] != chain_id_arr[indices_in_pdb[:, 1]]]\n sel_indices.append(indices_in_pdb)\n\n sel_indices = np.vstack(sel_indices)\n return sel_indices" }, { "identifier": "find_range_cutoff_pairs", "path": "cryostar/utils/dist_loss.py", "snippet": "def find_range_cutoff_pairs(coord_arr, min_cutoff=4., max_cutoff=10.):\n dist_map = distance.cdist(coord_arr, coord_arr, metric='euclidean')\n sel_mask = (dist_map <= max_cutoff) & (dist_map >= min_cutoff)\n indices_in_pdb = np.nonzero(sel_mask)\n indices_in_pdb = np.column_stack((indices_in_pdb[0], indices_in_pdb[1]))\n return indices_in_pdb" }, { "identifier": "find_continuous_pairs", "path": "cryostar/utils/dist_loss.py", "snippet": "def find_continuous_pairs(chain_id_arr, res_id_arr, atom_name_arr):\n pairs = []\n\n # res_id in different chains are duplicated, so loop on chains\n u_chain_id = np.unique(chain_id_arr)\n\n for c_id in u_chain_id:\n tmp_mask = chain_id_arr == c_id\n tmp_indices_in_pdb = np.nonzero(tmp_mask)[0]\n\n tmp_res_id_arr = res_id_arr[tmp_mask]\n tmp_atom_name_arr = atom_name_arr[tmp_mask]\n\n # check is aa or nt\n tmp_atom_name_set = set(tmp_atom_name_arr)\n\n if len(tmp_atom_name_set.intersection(AA_ATOMS)) > len(tmp_atom_name_set.intersection(NT_ATOMS)):\n in_res_atom_names = AA_ATOMS\n elif len(tmp_atom_name_set.intersection(AA_ATOMS)) < len(tmp_atom_name_set.intersection(NT_ATOMS)):\n in_res_atom_names = NT_ATOMS\n else:\n raise NotImplemented(\"Cannot determine chain is amino acid or nucleotide.\")\n\n # find pairs\n if len(in_res_atom_names) == 1:\n u_res_id, indices_in_chain = np.unique(tmp_res_id_arr, return_index=True)\n if len(u_res_id) != np.sum(tmp_mask):\n raise ValueError(f\"Found duplicate residue id in single chain {c_id}.\")\n\n indices_in_chain_pair = np.column_stack((indices_in_chain[:-1], indices_in_chain[1:]))\n\n # must be adjacent on residue id\n valid_mask = np.abs(np.diff(u_res_id[indices_in_chain_pair], axis=1)) == 1\n\n indices_in_chain_pair = indices_in_chain_pair[valid_mask.flatten()]\n\n indices_in_pdb_pair = tmp_indices_in_pdb[indices_in_chain_pair]\n elif len(in_res_atom_names) > 1:\n\n def _cmp(a, b):\n # res_id compare\n if a[0] != b[0]:\n return a[0] - b[0]\n else:\n # atom_name in the same order of AA_ATOMS or NT_ATOMS\n return in_res_atom_names.index(a[1]) - in_res_atom_names.index(b[1])\n\n cache = list(zip(tmp_res_id_arr, tmp_atom_name_arr, tmp_indices_in_pdb))\n sorted_cache = list(sorted(cache, key=cmp_to_key(_cmp)))\n\n sorted_indices_in_pdb = [item[2] for item in sorted_cache]\n sorted_res_id = [item[0] for item in sorted_cache]\n\n indices_in_pdb_pair = np.column_stack((sorted_indices_in_pdb[:-1], sorted_indices_in_pdb[1:]))\n\n valid_mask = np.abs(np.diff(np.column_stack((sorted_res_id[:-1], sorted_res_id[1:])), axis=1)) <= 1\n\n indices_in_pdb_pair = indices_in_pdb_pair[valid_mask.flatten()]\n else:\n raise NotImplemented(\"No enough atoms to construct continuous pairs.\")\n\n pairs.append(indices_in_pdb_pair)\n\n pairs = np.vstack(pairs)\n return pairs" }, { "identifier": "calc_dist_by_pair_indices", "path": "cryostar/utils/dist_loss.py", "snippet": "def calc_dist_by_pair_indices(coord_arr, pair_indices):\n coord_pair_arr = coord_arr[pair_indices] # num_pair, 2, 3\n dist = np.linalg.norm(np.diff(coord_pair_arr, axis=1), ord=2, axis=-1)\n return dist.flatten()" }, { "identifier": "remove_duplicate_pairs", "path": "cryostar/utils/dist_loss.py", "snippet": "def remove_duplicate_pairs(pairs_a, pairs_b, remove_flip=True):\n \"\"\"Remove pair b from a\"\"\"\n s = max(pairs_a.max(), pairs_b.max()) + 1\n # trick for fast comparison\n mask = np.zeros((s, s), dtype=bool)\n\n np.put(mask, np.ravel_multi_index(pairs_a.T, mask.shape), True)\n np.put(mask, np.ravel_multi_index(pairs_b.T, mask.shape), False)\n if remove_flip:\n np.put(mask, np.ravel_multi_index(np.flip(pairs_b, 1).T, mask.shape), False)\n return np.column_stack(np.nonzero(mask))" }, { "identifier": "filter_same_chain_pairs", "path": "cryostar/utils/dist_loss.py", "snippet": "def filter_same_chain_pairs(pair_ids, chain_id_arr):\n chain_ids = chain_id_arr[pair_ids]\n\n same_chain_mask = chain_ids[:, 0] == chain_ids[:, 1]\n\n pair_mask = []\n\n for u in np.unique(chain_ids):\n tmp = np.logical_and(chain_ids[:, 0] == u, same_chain_mask)\n if np.any(tmp):\n pair_mask.append(tmp)\n\n if len(pair_mask) > 0:\n return np.row_stack(pair_mask)\n else:\n return None" }, { "identifier": "DistLoss", "path": "cryostar/utils/dist_loss.py", "snippet": "class DistLoss(nn.Module):\n\n def __init__(self, pair_ids, gt_dists, reduction=\"mean\"):\n super().__init__()\n self.reduction = reduction\n\n self.register_buffer(\"pair_ids\", torch.from_numpy(pair_ids).long())\n self.register_buffer(\"gt_dists\", torch.from_numpy(gt_dists).float())\n\n # edge-wise weights\n # raw_weights = torch.ones(len(pair_ids), dtype=torch.float) * 3.\n #\n # self.register_parameter(\"raw_weights\", nn.Parameter(raw_weights))\n\n # RBF residue-wise weights\n # u_left_ids = np.unique(pair_ids[:, 0])\n #\n # std_idx = np.zeros(max(u_left_ids) + 1, dtype=int)\n # sparse_idx = np.arange(len(u_left_ids))\n #\n # std_idx[u_left_ids] = sparse_idx\n #\n # select_index = std_idx[pair_ids[:, 0]]\n\n # weight = 0.9 at dist_rescale\n # sigmas = torch.ones(max(u_left_ids) + 1, dtype=torch.float) * np.sqrt(-0.5 / np.log(0.9))\n #\n # self.dist_rescale = dist_rescale\n # self.register_buffer(\"select_index\", torch.from_numpy(select_index).long())\n # self.register_parameter(\"sigmas\", nn.Parameter(sigmas))\n\n # def get_weights(self):\n # return torch.sigmoid(self.raw_weights)\n # edge_sigmas = torch.index_select(self.sigmas, dim=0, index=self.select_index)\n # weights = torch.exp(-torch.pow(self.gt_dists / self.dist_rescale, 2) / (2 * torch.pow(edge_sigmas, 2)))\n # return weights\n\n def calc_pair_dists(self, batch_struc):\n batch_dist = batch_struc[:, self.pair_ids] # bsz, num_pair, 2, 3\n batch_dist = LA.vector_norm(torch.diff(batch_dist, dim=-2), axis=-1).squeeze(-1) # bsz, num_pair\n return batch_dist\n\n def forward(self, batch_struc):\n batch_dist = self.calc_pair_dists(batch_struc)\n # mse = torch.pow(batch_dist - self.gt_dists.unsqueeze(0), 2) * self.get_weights().unsqueeze(0)\n mse = torch.pow(batch_dist - self.gt_dists.unsqueeze(0), 2)\n if self.reduction is None:\n return mse\n elif self.reduction == \"mean\":\n return torch.mean(mse)\n else:\n raise NotImplementedError" }, { "identifier": "get_nearest_point", "path": "cryostar/utils/latent_space_utils.py", "snippet": "def get_nearest_point(data: np.ndarray, query: np.ndarray) -> Tuple[npt.NDArray[np.float32], np.ndarray]:\n \"\"\"\n Find closest point in @data to @query\n Return datapoint, index\n \"\"\"\n ind = cdist(query, data).argmin(axis=1)\n return data[ind], ind" }, { "identifier": "cluster_kmeans", "path": "cryostar/utils/latent_space_utils.py", "snippet": "def cluster_kmeans(z: np.ndarray, K: int, on_data: bool = True, reorder: bool = True) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Cluster z by K means clustering\n Returns cluster labels, cluster centers\n If reorder=True, reorders clusters according to agglomerative clustering of cluster centers\n \"\"\"\n kmeans = KMeans(n_clusters=K, n_init=10, random_state=0, max_iter=10)\n labels = kmeans.fit_predict(z)\n centers = kmeans.cluster_centers_\n\n centers_ind = None\n if on_data:\n centers, centers_ind = get_nearest_point(z, centers)\n\n if reorder:\n # BUG from seaborn or scipy:\n # sns.clustermap only supports data with at least 2 dim\n if z.shape[1] == 1:\n centers = np.hstack([centers, np.zeros_like(centers)])\n g = sns.clustermap(centers)\n reordered = g.dendrogram_row.reordered_ind\n centers = centers[reordered]\n if centers_ind is not None:\n centers_ind = centers_ind[reordered]\n tmp = {k: i for i, k in enumerate(reordered)}\n labels = np.array([tmp[k] for k in labels])\n if z.shape[1] == 1:\n centers = centers[:, :1]\n return labels, centers" }, { "identifier": "run_pca", "path": "cryostar/utils/latent_space_utils.py", "snippet": "def run_pca(z: np.ndarray) -> Tuple[np.ndarray, PCA]:\n pca = PCA(z.shape[1])\n pca.fit(z)\n # print(\"Explained variance ratio:\")\n # print(pca.explained_variance_ratio_)\n pc = pca.transform(z)\n return pc, pca" }, { "identifier": "get_pc_traj", "path": "cryostar/utils/latent_space_utils.py", "snippet": "def get_pc_traj(\n pca: PCA,\n zdim: int,\n numpoints: int,\n dim: int,\n start: Optional[float] = 5,\n end: Optional[float] = 95,\n percentiles: Optional[np.ndarray] = None,\n) -> npt.NDArray[np.float32]:\n \"\"\"\n Create trajectory along specified principal component\n\n Inputs:\n pca: sklearn PCA object from run_pca\n zdim (int)\n numpoints (int): number of points between @start and @end\n dim (int): PC dimension for the trajectory (1-based index)\n start (float): Value of PC{dim} to start trajectory\n end (float): Value of PC{dim} to stop trajectory\n percentiles (np.array or None): Define percentile array instead of np.linspace(start,stop,numpoints)\n\n Returns:\n np.array (numpoints x zdim) of z values along PC\n \"\"\"\n if percentiles is not None:\n assert len(percentiles) == numpoints\n traj_pca = np.zeros((numpoints, zdim))\n if percentiles is not None:\n traj_pca[:, dim - 1] = percentiles\n else:\n assert start is not None\n assert end is not None\n traj_pca[:, dim - 1] = np.linspace(start, end, numpoints)\n ztraj_pca = pca.inverse_transform(traj_pca)\n return ztraj_pca" }, { "identifier": "run_umap", "path": "cryostar/utils/latent_space_utils.py", "snippet": "def run_umap(z: np.ndarray, **kwargs) -> Tuple[np.ndarray, umap.UMAP]:\n reducer = umap.UMAP(**kwargs)\n z_embedded = reducer.fit_transform(z)\n return z_embedded, reducer" }, { "identifier": "plot_z_dist", "path": "cryostar/utils/vis_utils.py", "snippet": "def plot_z_dist(z, extra_cluster=None, save_path=None):\n if z.shape[-1] == 1:\n fig = sns.displot(x=z[:, 0])\n fig.set_xlabels(\"z values\")\n if save_path is not None:\n fig.savefig(save_path)\n elif z.shape[-1] == 2:\n sns.set()\n fig = sns.jointplot(x=z[:, 0], y=z[:, 1], kind=\"kde\", fill=True)\n ax = fig.figure.axes\n if extra_cluster is not None:\n ax[0].scatter(extra_cluster[:, 0], extra_cluster[:, 1], marker='.', color='tab:orange')\n if save_path is not None:\n fig.savefig(save_path)\n else:\n raise ValueError(f\"input z with shape {z.shape}\")" }, { "identifier": "save_tensor_image", "path": "cryostar/utils/vis_utils.py", "snippet": "def save_tensor_image(tensors, save_path, mask=None):\n # normalize\n max_val = torch.max(tensors.flatten(start_dim=1), 1)[0][:, None, None, None]\n min_val = torch.min(tensors.flatten(start_dim=1), 1)[0][:, None, None, None]\n tensors = (tensors - min_val) / (max_val - min_val)\n\n show_img = ToPILImage()(make_grid(tensors, nrow=5))\n if mask is None:\n show_img.save(save_path)\n else:\n show_img = np.copy(np.asarray(show_img))\n # show_img = cv2.cvtColor(show_img, cv2.COLOR_GRAY2RGB)\n if mask.ndim == 2:\n mask = mask[None]\n mask = ToPILImage()(make_grid(mask.expand(tensors.shape[0], -1, -1, -1), nrow=5))\n mask = np.invert(np.asarray(mask).astype(bool))[..., 0]\n color_mask = np.array([[0, 0, 0], [31, 119, 180]], dtype=np.uint8)\n color_mask = color_mask[mask.astype(int)]\n show_img[mask] = cv2.addWeighted(show_img[mask], 0.5, color_mask[mask], 0.5, 0)\n show_img = Image.fromarray(show_img)\n show_img.save(save_path)" }, { "identifier": "merge_step_outputs", "path": "cryostar/utils/pl_utils.py", "snippet": "def merge_step_outputs(outputs):\n ks = outputs[0].keys()\n res = {}\n for k in ks:\n res[k] = torch.concat([out[k] for out in outputs], dim=0)\n return res" }, { "identifier": "squeeze_dict_outputs_1st_dim", "path": "cryostar/utils/pl_utils.py", "snippet": "def squeeze_dict_outputs_1st_dim(outputs):\n res = {}\n for k in outputs.keys():\n res[k] = outputs[k].flatten(start_dim=0, end_dim=1)\n return res" }, { "identifier": "filter_outputs_by_indices", "path": "cryostar/utils/pl_utils.py", "snippet": "def filter_outputs_by_indices(outputs, indices):\n res = {}\n for k in outputs.keys():\n res[k] = outputs[k][indices]\n return res" }, { "identifier": "get_1st_unique_indices", "path": "cryostar/utils/pl_utils.py", "snippet": "def get_1st_unique_indices(t):\n _, idx, counts = torch.unique(t, dim=None, sorted=True, return_inverse=True, return_counts=True)\n # ind_sorted: the index corresponding to same unique value will be grouped by these indices\n _, ind_sorted = torch.sort(idx, stable=True)\n cum_sum = counts.cumsum(0)\n cum_sum = torch.cat((cum_sum.new_tensor([\n 0,\n ]), cum_sum[:-1]))\n first_idx = ind_sorted[cum_sum]\n return first_idx" } ]
import os.path as osp import warnings import collections import einops import numpy as np import biotite.structure as struc import torch import lightning.pytorch as pl from pathlib import Path from copy import deepcopy from torch import nn from torch import optim from torch.utils.data import DataLoader from torchinfo import summary from lightning.fabric.utilities.warnings import PossibleUserWarning from lightning.pytorch.utilities import rank_zero_only from lightning.pytorch.strategies import DDPStrategy from mmengine import mkdir_or_exist from cryostar.utils.transforms import SpatialGridTranslate from cryostar.utils.dataio import StarfileDataSet, StarfileDatasetConfig, Mask from cryostar.utils.ctf_utils import CTFRelion, CTFCryoDRGN from cryostar.utils.losses import calc_cor_loss, calc_kl_loss from cryostar.utils.misc import log_to_current, \ pl_init_exp, pretty_dict, set_seed, warmup from cryostar.utils.pdb_tools import bt_save_pdb from cryostar.gmm.gmm import EMAN2Grid, batch_projection, Gaussian from cryostar.gmm.deformer import E3Deformer, NMADeformer from cryostar.utils.fft_utils import primal_to_fourier_2d, fourier_to_primal_2d from cryostar.utils.polymer import Polymer, NT_ATOMS, AA_ATOMS from cryostar.utils.dist_loss import (find_quaint_cutoff_pairs, find_range_cutoff_pairs, find_continuous_pairs, calc_dist_by_pair_indices, remove_duplicate_pairs, filter_same_chain_pairs, DistLoss) from cryostar.utils.latent_space_utils import get_nearest_point, cluster_kmeans, run_pca, get_pc_traj, run_umap from cryostar.utils.vis_utils import plot_z_dist, save_tensor_image from cryostar.utils.pl_utils import merge_step_outputs, squeeze_dict_outputs_1st_dim, \ filter_outputs_by_indices, get_1st_unique_indices from miscs import calc_pair_dist_loss, calc_clash_loss, low_pass_mask2d, VAE, infer_ctf_params_from_config
16,674
tmp_atom_arr.coord = tmp_struc atom_arrs.append(tmp_atom_arr) bt_save_pdb(save_path, struc.stack(atom_arrs)) def _shared_image_check(self, total=25): mode = self.model.training # use validation or test set which not shuffled tmp_loader = self.trainer.val_dataloaders or self.trainer.test_dataloaders num = 0 gt_images_list = [] pred_gmm_images_list = [] self.model.eval() with torch.no_grad(): for batch in tmp_loader: batch = self.trainer.strategy.batch_to_device(batch) gt_images, pred_gmm_images, _, mu, log_var = self._shared_infer(batch) gt_images_list.append(gt_images) pred_gmm_images_list.append(pred_gmm_images) num += gt_images.shape[0] if num >= total: break self.model.train(mode=mode) gt_images_list = torch.cat(gt_images_list, dim=0)[:total] pred_gmm_images_list = torch.cat(pred_gmm_images_list, dim=0)[:total] save_dir = self._get_save_dir() save_tensor_image(gt_images_list, osp.join(save_dir, "input_image.png")) save_tensor_image(pred_gmm_images_list, osp.join(save_dir, "pred_gmm_image.png"), self.mask.mask) # standard hooks: def training_step(self, batch, batch_idx): cfg = self.cfg gt_images, pred_gmm_images, pred_struc, mu, log_var = self._shared_infer(batch) # gmm part loss # only gmm supervision should be low-passed if self.lp_mask2d is not None: lp_gt_images = self.low_pass_images(gt_images) else: lp_gt_images = gt_images gmm_proj_loss = calc_cor_loss(pred_gmm_images, lp_gt_images, self.mask) weighted_gmm_proj_loss = cfg.loss.gmm_cryoem_weight * gmm_proj_loss if hasattr(self, "connect_pairs"): connect_loss = calc_pair_dist_loss(pred_struc, self.connect_pairs, self.connect_dists) weighted_connect_loss = cfg.loss.connect_weight * connect_loss else: weighted_connect_loss = weighted_gmm_proj_loss.new_tensor(0.) if hasattr(self, "sse_pairs"): sse_loss = calc_pair_dist_loss(pred_struc, self.sse_pairs, self.sse_dists) weighted_sse_loss = cfg.loss.connect_weight * sse_loss else: weighted_sse_loss = weighted_gmm_proj_loss.new_tensor(0.) if hasattr(self, "dist_loss_fn"): dist_loss = self.dist_loss_fn(pred_struc) # across devices all_dist_loss = self.all_gather(dist_loss) # world_size, batch, num_pairs all_dist_loss = all_dist_loss.reshape(-1, dist_loss.shape[-1]) # chain-wise drop with torch.no_grad(): keep_mask = torch.ones(dist_loss.shape[-1], dtype=torch.bool).to(dist_loss.device) for i in range(len(self.cutoff_chain_mask)): tmp_mask = self.cutoff_chain_mask[i] tmp_var = all_dist_loss.index_select(dim=1, index=tmp_mask.nonzero(as_tuple=True)[0]).var(dim=0) intra_chain_keep_mask = tmp_var.lt(torch.quantile(tmp_var, cfg.loss.dist_keep_ratio)) keep_mask[tmp_mask] *= intra_chain_keep_mask keep_mask = keep_mask.unsqueeze(0).repeat(dist_loss.size(0), 1) dist_loss = torch.mean(dist_loss[keep_mask]) weighted_dist_loss = cfg.loss.dist_weight * dist_loss # dist_penalty = torch.mean(torch.abs(self.dist_loss_fn.get_weights())) # weighted_dist_penalty = cfg.loss.dist_penalty_weight * dist_penalty else: weighted_dist_loss = weighted_gmm_proj_loss.new_tensor(0.) # weighted_dist_penalty = weighted_gmm_proj_loss.new_tensor(0.) if hasattr(self, "clash_pairs"): clash_loss = calc_clash_loss(pred_struc, self.clash_pairs, cfg.loss.clash_min_cutoff) weighted_clash_loss = cfg.loss.clash_weight * clash_loss else: weighted_clash_loss = weighted_gmm_proj_loss.new_tensor(0.) # KL kl_loss = calc_kl_loss(mu, log_var, self.cfg.loss.free_bits) kl_beta = warmup(cfg.loss.warmup_step, upper=cfg.loss.kl_beta_upper)(self.global_step) weighted_kld_loss = kl_beta * kl_loss / self.mask.num_masked # clac loss loss = (weighted_kld_loss + weighted_gmm_proj_loss + weighted_connect_loss + weighted_dist_loss + weighted_sse_loss + weighted_clash_loss) tmp_metric = { "loss": loss.item(), "cryoem(gmm)": weighted_gmm_proj_loss.item(), "con": weighted_connect_loss.item(), "sse": weighted_sse_loss.item(), "dist": weighted_dist_loss.item(), # "dist_penalty": weighted_dist_penalty.item(), "clash": weighted_clash_loss.item(), "kld": weighted_kld_loss.item(), "kld(/dim)": kl_loss.item() } if self.global_step % cfg.runner.log_every_n_step == 0: self.log_dict(tmp_metric) log_to_current(f"epoch {self.current_epoch} [{batch_idx}/{self.trainer.num_training_batches}] | " +
# other # avoid num_workers set as cpu_count warning warnings.simplefilter("ignore", PossibleUserWarning) # only log to rank_zero, comment this for debugging log_to_current = rank_zero_only(log_to_current) TASK_NAME = "atom" def prepare_images(images: torch.FloatTensor, space: str): assert space in ("real", "fourier") if space == "real": model_input = einops.rearrange(images, "b 1 ny nx -> b (1 ny nx)") else: fimages = primal_to_fourier_2d(images) model_input = einops.rearrange(torch.view_as_real(fimages), "b 1 ny nx c2 -> b (1 ny nx c2)", c2=2) return model_input class InitTask(pl.LightningModule): def __init__(self, em_module): super().__init__() self.cfg = em_module.cfg self.em_module = em_module self.loss_deque = collections.deque([ 10, ], maxlen=20) def on_train_batch_end(self, outputs, batch, batch_idx): self.loss_deque.append(outputs['loss'].item()) if np.mean(self.loss_deque) < 1e-3: self.trainer.should_stop = True # update all process status self.trainer.should_stop = self.trainer.strategy.broadcast(self.trainer.should_stop) def training_step(self, batch, batch_idx): images = batch["proj"] idxes = batch["idx"] rot_mats, trans_mats = self.em_module.get_batch_pose(batch) pred_deformation, mu, log_var = self.em_module.model(prepare_images(images, self.cfg.model.input_space), idxes, rot_mats) shift_loss = torch.mean(torch.pow(pred_deformation.flatten(start_dim=-2), 2)) loss = shift_loss if self.global_step % self.cfg.runner.log_every_n_step == 0: log_to_current(f"loss {loss.item()}") return loss def configure_optimizers(self): return optim.AdamW(self.em_module.model.parameters(), lr=1e-4) def on_fit_end(self): log_to_current(f"Init finished with loss {np.mean(self.loss_deque)}") class CryoEMTask(pl.LightningModule): def __init__(self, cfg, dataset): super().__init__() cfg = deepcopy(cfg) self.cfg = cfg # Define GMM meta = Polymer.from_pdb(cfg.dataset_attr.ref_pdb_path) log_to_current(f"Load reference structure from {cfg.dataset_attr.ref_pdb_path}") # for save self.template_pdb = meta.to_atom_arr() log_to_current(f"Protein contains {len(meta)} atoms, " f"{meta.num_amino_acids} amino acids, " f"{meta.num_nucleotides} nucleotides, " f"{meta.num_chains} chains.") # ref ref_centers = torch.from_numpy(meta.coord).float() ref_amps = torch.from_numpy(meta.num_electron).float() ref_sigmas = torch.ones_like(ref_amps) ref_sigmas.fill_(2.) log_to_current(f"1st GMM blob amplitude {ref_amps[0].item()}, sigma {ref_sigmas[0].item()}") num_pts = len(meta) log_to_current(f"Reference structure has {num_pts} atom coordinates") # tunable params # gmm self.register_buffer("gmm_centers", ref_centers) if cfg.gmm.tunable: log_to_current("Set GMM sigmas, amplitudes tunable") self.register_parameter("gmm_sigmas", nn.Parameter(ref_sigmas)) self.register_parameter("gmm_amps", nn.Parameter(ref_amps)) else: self.register_buffer("gmm_sigmas", ref_sigmas) self.register_buffer("gmm_amps", ref_amps) nma_modes = None if (hasattr(self.cfg.extra_input_data_attr, "nma_path") and self.cfg.extra_input_data_attr.nma_path not in ["", None]): nma_modes = torch.tensor(np.load(self.cfg.extra_input_data_attr.nma_path), dtype=torch.float32) log_to_current(f"Load NMA coefficients from {self.cfg.extra_input_data_attr.nma_path}, " f"whose shape is {nma_modes.shape}") # model if cfg.model.input_space == "fourier": in_dim = 2 * cfg.data_process.down_side_shape ** 2 elif cfg.model.input_space == "real": in_dim = cfg.data_process.down_side_shape ** 2 else: raise NotImplementedError self.model = VAE(in_dim=in_dim, out_dim=num_pts * 3 if nma_modes is None else 6 + nma_modes.shape[1], **cfg.model.model_cfg) log_to_current('Model summary:\n' + str(summary(self.model, input_size=[(1, in_dim), (1,)], verbose=0))) if nma_modes is None: self.deformer = E3Deformer() else: self.deformer = NMADeformer(nma_modes) # loss or regularization's preparation # dist loss connect_pairs = find_continuous_pairs(meta.chain_id, meta.res_id, meta.atom_name) if cfg.extra_input_data_attr.use_domain: log_to_current("use domain instead of chain!") domain_id = np.load(cfg.extra_input_data_attr.domain_path) cutoff_pairs = find_quaint_cutoff_pairs(meta.coord, domain_id, meta.res_id, cfg.loss.intra_chain_cutoff, cfg.loss.inter_chain_cutoff, cfg.loss.intra_chain_res_bound) else: # deal with RNA/DNA if np.sum(np.isin(meta.atom_name, NT_ATOMS)): # aa tmp_mask = np.isin(meta.atom_name, AA_ATOMS) indices_in_pdb = np.nonzero(tmp_mask)[0] aa_cutoff_pairs = find_quaint_cutoff_pairs(meta.coord[tmp_mask], meta.chain_id[tmp_mask], meta.res_id[tmp_mask], cfg.loss.intra_chain_cutoff, cfg.loss.inter_chain_cutoff, cfg.loss.intra_chain_res_bound) aa_cutoff_pairs = indices_in_pdb[aa_cutoff_pairs] log_to_current(f"{len(aa_cutoff_pairs)} AA pairs") # nt tmp_mask = np.isin(meta.atom_name, NT_ATOMS) indices_in_pdb = np.nonzero(tmp_mask)[0] nt_cutoff_pairs = find_quaint_cutoff_pairs(meta.coord[tmp_mask], meta.chain_id[tmp_mask], meta.res_id[tmp_mask], cfg.loss.nt_intra_chain_cutoff, cfg.loss.nt_inter_chain_cutoff, cfg.loss.nt_intra_chain_res_bound) nt_cutoff_pairs = indices_in_pdb[nt_cutoff_pairs] log_to_current(f"{len(nt_cutoff_pairs)} NT pairs") cutoff_pairs = np.vstack((aa_cutoff_pairs, nt_cutoff_pairs)) else: cutoff_pairs = find_quaint_cutoff_pairs(meta.coord, meta.chain_id, meta.res_id, cfg.loss.intra_chain_cutoff, cfg.loss.inter_chain_cutoff, cfg.loss.intra_chain_res_bound) cutoff_pairs = remove_duplicate_pairs(cutoff_pairs, connect_pairs) if cfg.loss.sse_weight != 0.0: log_to_current("use pseduo `sse` by building spatial/sequential edges") sse_pairs = find_quaint_cutoff_pairs(meta.coord, meta.chain_id, meta.res_id, cfg.loss.intra_chain_cutoff, 0, 20) cutoff_pairs = remove_duplicate_pairs(cutoff_pairs, sse_pairs) clash_pairs = find_range_cutoff_pairs(meta.coord, cfg.loss.clash_min_cutoff) clash_pairs = remove_duplicate_pairs(clash_pairs, connect_pairs) if len(connect_pairs) > 0: self.register_buffer("connect_pairs", torch.from_numpy(connect_pairs).long()) dists = calc_dist_by_pair_indices(meta.coord, connect_pairs) self.register_buffer("connect_dists", torch.from_numpy(dists).float()) log_to_current(f"found {len(connect_pairs)} connect_pairs") else: log_to_current("connect_pairs is empty") if cfg.loss.sse_weight != 0.0: self.register_buffer("sse_pairs", torch.from_numpy(sse_pairs).long()) dists = calc_dist_by_pair_indices(meta.coord, sse_pairs) self.register_buffer("sse_dists", torch.from_numpy(dists).float()) log_to_current(f"found {len(sse_pairs)} sse_pairs") if len(cutoff_pairs) > 0: dists = calc_dist_by_pair_indices(meta.coord, cutoff_pairs) log_to_current(f"found {len(cutoff_pairs)} cutoff_pairs") self.dist_loss_fn = DistLoss(cutoff_pairs, dists, reduction=None) # for chain-wise dropout cutoff_chain_mask = filter_same_chain_pairs(cutoff_pairs, meta.chain_id) self.register_buffer("cutoff_chain_mask", torch.from_numpy(cutoff_chain_mask)) else: log_to_current("cutoff_pairs is empty") if len(clash_pairs) > 0: self.register_buffer("clash_pairs", torch.from_numpy(clash_pairs).long()) log_to_current(f"found {len(clash_pairs)} clash_pairs") else: log_to_current("clash_pairs is empty") # low-pass filtering if hasattr(cfg.data_process, "low_pass_bandwidth"): log_to_current(f"Use low-pass filtering w/ {cfg.data_process.low_pass_bandwidth} A") lp_mask2d = low_pass_mask2d(cfg.data_process.down_side_shape, cfg.data_process.down_apix, cfg.data_process.low_pass_bandwidth) self.register_buffer("lp_mask2d", torch.from_numpy(lp_mask2d).float()) else: self.lp_mask2d = None # self.mask = Mask(cfg.data_process.down_side_shape, rad=cfg.loss.mask_rad_for_image_loss) # for projection grid = EMAN2Grid(side_shape=cfg.data_process.down_side_shape, voxel_size=cfg.data_process.down_apix) self.grid = grid ctf_params = infer_ctf_params_from_config(cfg) if cfg.model.ctf == "v1": self.ctf = CTFRelion(**ctf_params, num_particles=len(dataset)) log_to_current("We will deprecate `model.ctf=v1` in a future version, use `model.ctf=v2` instead.") elif cfg.model.ctf == "v2": self.ctf = CTFCryoDRGN(**ctf_params, num_particles=len(dataset)) else: raise NotImplementedError log_to_current(ctf_params) # translate image helper self.translator = SpatialGridTranslate(D=cfg.data_process.down_side_shape, device=self.device) self.apix = self.cfg.data_process.down_apix # cache self.validation_step_outputs = [] self.stored_metrics = {} self.history_saved_dirs = [] if getattr(self.cfg.extra_input_data_attr, "ckpt_path", None) is not None: log_to_current(f"load checkpoint from {self.cfg.extra_input_data_attr.ckpt_path}") self._load_ckpt(self.cfg.extra_input_data_attr.ckpt_path) def _save_ckpt(self, ckpt_path): torch.save( { "model": self.model.state_dict(), "gmm_sigmas": self.gmm_sigmas.data, "gmm_amps": self.gmm_amps.data }, ckpt_path) def _load_ckpt(self, ckpt_path): state_dict = torch.load(ckpt_path, map_location=self.device) self.model.load_state_dict(state_dict["model"]) if self.cfg.gmm.tunable: self.gmm_sigmas.data = state_dict["gmm_sigmas"] self.gmm_amps.data = state_dict["gmm_amps"] def _get_save_dir(self): save_dir = osp.join(self.cfg.work_dir, f"{self.current_epoch:04d}_{self.global_step:07d}") mkdir_or_exist(save_dir) return save_dir def low_pass_images(self, images): f_images = primal_to_fourier_2d(images) f_images = f_images * self.lp_mask2d images = fourier_to_primal_2d(f_images).real return images def get_batch_pose(self, batch): rot_mats = batch["rotmat"] # yx order trans_mats = torch.concat((batch["shiftY"].unsqueeze(1), batch["shiftX"].unsqueeze(1)), dim=1) trans_mats /= self.apix return rot_mats, trans_mats def _shared_forward(self, images, idxes, rots): # predict structure pred_deformation, mu, log_var = self.model(prepare_images(images, self.cfg.model.input_space), idxes, rots) return pred_deformation, mu, log_var def _shared_projection(self, pred_struc, rot_mats): pred_images = batch_projection( gauss=Gaussian( mus=pred_struc, sigmas=self.gmm_sigmas.unsqueeze(0), # (b, num_centers) amplitudes=self.gmm_amps.unsqueeze(0)), rot_mats=rot_mats, line_grid=self.grid.line()) pred_images = einops.rearrange(pred_images, 'b y x -> b 1 y x') return pred_images def _apply_ctf(self, batch, real_proj, freq_mask=None): f_proj = primal_to_fourier_2d(real_proj) f_proj = self._apply_ctf_f(batch, f_proj, freq_mask) # Note: here only use the real part proj = fourier_to_primal_2d(f_proj).real return proj def _apply_ctf_f(self, batch, f_proj, freq_mask=None): pred_ctf_params = {k: batch[k] for k in ('defocusU', 'defocusV', 'angleAstigmatism') if k in batch} f_proj = self.ctf(f_proj, batch['idx'], ctf_params=pred_ctf_params, mode="gt", frequency_marcher=None) if freq_mask is not None: f_proj = f_proj * self.lp_mask2d return f_proj def _shared_infer(self, batch): gt_images = batch["proj"] idxes = batch["idx"] rot_mats, trans_mats = self.get_batch_pose(batch) # if self.lp_mask2d is not None: # gt_images = self.low_pass_images(gt_images) # prediction pred_deformation, mu, log_var = self._shared_forward(gt_images, idxes, rot_mats) pred_struc = self.deformer.transform(pred_deformation, self.gmm_centers) # get gmm projections pred_gmm_images = self._shared_projection(pred_struc, rot_mats) # apply ctf, low-pass pred_gmm_images = self._apply_ctf(batch, pred_gmm_images, self.lp_mask2d) if trans_mats is not None: gt_images = self.translator.transform(einops.rearrange(gt_images, "B 1 NY NX -> B NY NX"), einops.rearrange(trans_mats, "B C2 -> B 1 C2")) return gt_images, pred_gmm_images, pred_struc, mu, log_var def _shared_decoding(self, z): with torch.no_grad(): z = z.float().to(self.device) pred_deformation = self.model.decoder(z) pred_struc = self.deformer.transform(pred_deformation, self.gmm_centers) pred_struc = pred_struc.squeeze(0) return pred_struc def _save_batched_strucs(self, pred_strucs, save_path): ref_atom_arr = self.template_pdb.copy() atom_arrs = [] b = pred_strucs.shape[0] for i in range(b): tmp_struc = pred_strucs[i].cpu().numpy() tmp_atom_arr = ref_atom_arr.copy() tmp_atom_arr.coord = tmp_struc atom_arrs.append(tmp_atom_arr) bt_save_pdb(save_path, struc.stack(atom_arrs)) def _shared_image_check(self, total=25): mode = self.model.training # use validation or test set which not shuffled tmp_loader = self.trainer.val_dataloaders or self.trainer.test_dataloaders num = 0 gt_images_list = [] pred_gmm_images_list = [] self.model.eval() with torch.no_grad(): for batch in tmp_loader: batch = self.trainer.strategy.batch_to_device(batch) gt_images, pred_gmm_images, _, mu, log_var = self._shared_infer(batch) gt_images_list.append(gt_images) pred_gmm_images_list.append(pred_gmm_images) num += gt_images.shape[0] if num >= total: break self.model.train(mode=mode) gt_images_list = torch.cat(gt_images_list, dim=0)[:total] pred_gmm_images_list = torch.cat(pred_gmm_images_list, dim=0)[:total] save_dir = self._get_save_dir() save_tensor_image(gt_images_list, osp.join(save_dir, "input_image.png")) save_tensor_image(pred_gmm_images_list, osp.join(save_dir, "pred_gmm_image.png"), self.mask.mask) # standard hooks: def training_step(self, batch, batch_idx): cfg = self.cfg gt_images, pred_gmm_images, pred_struc, mu, log_var = self._shared_infer(batch) # gmm part loss # only gmm supervision should be low-passed if self.lp_mask2d is not None: lp_gt_images = self.low_pass_images(gt_images) else: lp_gt_images = gt_images gmm_proj_loss = calc_cor_loss(pred_gmm_images, lp_gt_images, self.mask) weighted_gmm_proj_loss = cfg.loss.gmm_cryoem_weight * gmm_proj_loss if hasattr(self, "connect_pairs"): connect_loss = calc_pair_dist_loss(pred_struc, self.connect_pairs, self.connect_dists) weighted_connect_loss = cfg.loss.connect_weight * connect_loss else: weighted_connect_loss = weighted_gmm_proj_loss.new_tensor(0.) if hasattr(self, "sse_pairs"): sse_loss = calc_pair_dist_loss(pred_struc, self.sse_pairs, self.sse_dists) weighted_sse_loss = cfg.loss.connect_weight * sse_loss else: weighted_sse_loss = weighted_gmm_proj_loss.new_tensor(0.) if hasattr(self, "dist_loss_fn"): dist_loss = self.dist_loss_fn(pred_struc) # across devices all_dist_loss = self.all_gather(dist_loss) # world_size, batch, num_pairs all_dist_loss = all_dist_loss.reshape(-1, dist_loss.shape[-1]) # chain-wise drop with torch.no_grad(): keep_mask = torch.ones(dist_loss.shape[-1], dtype=torch.bool).to(dist_loss.device) for i in range(len(self.cutoff_chain_mask)): tmp_mask = self.cutoff_chain_mask[i] tmp_var = all_dist_loss.index_select(dim=1, index=tmp_mask.nonzero(as_tuple=True)[0]).var(dim=0) intra_chain_keep_mask = tmp_var.lt(torch.quantile(tmp_var, cfg.loss.dist_keep_ratio)) keep_mask[tmp_mask] *= intra_chain_keep_mask keep_mask = keep_mask.unsqueeze(0).repeat(dist_loss.size(0), 1) dist_loss = torch.mean(dist_loss[keep_mask]) weighted_dist_loss = cfg.loss.dist_weight * dist_loss # dist_penalty = torch.mean(torch.abs(self.dist_loss_fn.get_weights())) # weighted_dist_penalty = cfg.loss.dist_penalty_weight * dist_penalty else: weighted_dist_loss = weighted_gmm_proj_loss.new_tensor(0.) # weighted_dist_penalty = weighted_gmm_proj_loss.new_tensor(0.) if hasattr(self, "clash_pairs"): clash_loss = calc_clash_loss(pred_struc, self.clash_pairs, cfg.loss.clash_min_cutoff) weighted_clash_loss = cfg.loss.clash_weight * clash_loss else: weighted_clash_loss = weighted_gmm_proj_loss.new_tensor(0.) # KL kl_loss = calc_kl_loss(mu, log_var, self.cfg.loss.free_bits) kl_beta = warmup(cfg.loss.warmup_step, upper=cfg.loss.kl_beta_upper)(self.global_step) weighted_kld_loss = kl_beta * kl_loss / self.mask.num_masked # clac loss loss = (weighted_kld_loss + weighted_gmm_proj_loss + weighted_connect_loss + weighted_dist_loss + weighted_sse_loss + weighted_clash_loss) tmp_metric = { "loss": loss.item(), "cryoem(gmm)": weighted_gmm_proj_loss.item(), "con": weighted_connect_loss.item(), "sse": weighted_sse_loss.item(), "dist": weighted_dist_loss.item(), # "dist_penalty": weighted_dist_penalty.item(), "clash": weighted_clash_loss.item(), "kld": weighted_kld_loss.item(), "kld(/dim)": kl_loss.item() } if self.global_step % cfg.runner.log_every_n_step == 0: self.log_dict(tmp_metric) log_to_current(f"epoch {self.current_epoch} [{batch_idx}/{self.trainer.num_training_batches}] | " +
pretty_dict(tmp_metric, 5))
8
2023-11-06 07:15:26+00:00
24k
KAIST-AILab/palr
train.py
[ { "identifier": "BC", "path": "imitation/bc.py", "snippet": "class BC(nn.Module):\n def __init__(self, policy, env, best_policy=None,\n replay_buffer=None, replay_buffer_valid=None, seed=0, \n device='cpu', lr=3e-4, envname=None, wandb=None, save_policy_path=None, \n obs_dim=1, action_dim=1, stacksize=1, standardize=True):\n \n torch.manual_seed(seed)\n np.random.seed(seed)\n random.seed(seed)\n \n super(BC, self).__init__()\n\n self.env = env\n self.policy = policy\n self.best_policy = best_policy\n self.replay_buffer = replay_buffer\n self.replay_buffer_valid = replay_buffer_valid\n self.device = device\n \n self.obs_dim = obs_dim\n self.action_dim = action_dim \n self.stacksize = stacksize\n \n self.policy_optimizer = optim.Adam(policy.parameters(), lr=lr)\n \n self.num_eval_iteration = 50\n self.envname = envname\n \n self.wandb = None\n if wandb:\n self.wandb = wandb\n self.wandb.init()\n\n self.save_policy_path = save_policy_path \n \n # For standardization\n self.standardize = standardize\n\n self.obs_mean_tt = torch.tensor(self.replay_buffer.obs_mean, device=device)\n self.obs_std_tt = torch.tensor(self.replay_buffer.obs_std, device=device)\n self.act_mean_tt = torch.tensor(self.replay_buffer.act_mean, device=device)\n self.act_std_tt = torch.tensor(self.replay_buffer.act_std, device=device)\n\n self.obs_mean = self.replay_buffer.obs_mean\n self.obs_std = self.replay_buffer.obs_std\n self.act_mean = self.replay_buffer.act_mean\n self.act_std = self.replay_buffer.act_std\n \n\n def train(self, total_iteration=1e6, eval_freq=1000, batch_size=1024, num_valid=2000):\n \n max_score = -100000.\n \n batch_valid = self.replay_buffer_valid.random_batch(num_valid, standardize=self.standardize)\n \n obs_valid = batch_valid['observations']\n actions_valid = batch_valid['actions'][:, -self.action_dim:] \n prev_expert_action_valid = batch_valid['actions'][:, :-self.action_dim] # For debugging\n \n obs_valid = torch.tensor(obs_valid, dtype=torch.float32, device=self.device)\n actions_valid = torch.tensor(actions_valid, dtype=torch.float32, device=self.device)\n prev_expert_action_valid = torch.tensor(prev_expert_action_valid, dtype=torch.float32, device=self.device)\n \n for num in range(0, int(total_iteration)):\n batch = self.replay_buffer.random_batch(batch_size, standardize=self.standardize)\n \n obs = batch['observations']\n actions = batch['actions'][:, -self.action_dim:]\n \n obs = torch.tensor(obs, dtype=torch.float32, device=self.device)\n actions = torch.tensor(actions, dtype=torch.float32, device=self.device) \n\n neg_likelihood = -self.policy.log_prob(obs, actions).mean()\n train_loss = neg_likelihood\n \n self.policy_optimizer.zero_grad()\n train_loss.backward()\n self.policy_optimizer.step()\n\n if (num+1) % eval_freq == 0:\n policy_action = self.policy(obs).sample()\n policy_action_valid = self.policy(obs_valid).sample()\n prev_expert_action = batch['actions'][:, :-self.action_dim] \n prev_expert_action = torch.tensor(prev_expert_action, dtype=torch.float32, device=self.device) \n \n # Train data HSCIC (for debugging) \n policy_embedding = self.policy.forward_embedding(obs)\n if self.standardize:\n Y_std = (prev_expert_action - self.act_mean_tt[0, :-self.action_dim])/ self.act_std_tt[0, :-self.action_dim]\n Z_std = (actions - self.act_mean_tt[0, -self.action_dim:])/ self.act_std_tt[0, -self.action_dim:]\n p_std = (policy_action - self.act_mean_tt[0, -self.action_dim:])/ self.act_std_tt[0, -self.action_dim:]\n\n Y_std = Y_std.to(torch.float32)\n Z_std = Z_std.to(torch.float32)\n p_std = p_std.to(torch.float32)\n else:\n Y_std = prev_expert_action\n Z_std = actions\n p_std = policy_action\n \n hscic_estimate = estimate_hscic(X=policy_embedding, Y=Y_std, Z=Z_std, ridge_lambda=1e-5)\n \n policy_embedding_valid = self.policy.forward_embedding(obs_valid)\n if self.standardize:\n Y_std = (prev_expert_action_valid - self.act_mean_tt[0, :-self.action_dim])/ self.act_std_tt[0, :-self.action_dim]\n Z_std = (actions_valid - self.act_mean_tt[0, -self.action_dim:])/ self.act_std_tt[0, -self.action_dim:]\n\n Y_std = Y_std.to(torch.float32)\n Z_std = Z_std.to(torch.float32)\n else:\n Y_std = prev_expert_action_valid\n Z_std = actions_valid\n p_std = policy_action\n \n valid_hscic_estimate = estimate_hscic(X=policy_embedding_valid, Y=Y_std, Z=Z_std, ridge_lambda=1e-5)\n valid_hscic_estimate_action = estimate_hscic(X=policy_action_valid, Y=prev_expert_action_valid, Z=actions_valid, ridge_lambda=1e-5)\n\n valid_neg_likelihood = -self.policy.log_prob(obs_valid, actions_valid).mean()\n valid_loss = valid_neg_likelihood\n\n eval_ret_mean, eval_ret_std = self.evaluate(num_iteration=self.num_eval_iteration)\n \n print(f'** iter{num+1}: train_policy_loss={train_loss.item():.2f}, val_policy_loss={valid_loss.item():.2f}, eval_ret={eval_ret_mean:.2f}+-{eval_ret_std:.2f} ({obs_valid.shape[0]})',)\n print(f'** HSCIC : (train){hscic_estimate:.6f} (valid){valid_hscic_estimate:.6f} (valid,action){valid_hscic_estimate_action:.6f}')\n \n if self.wandb:\n self.wandb.log({'train_total_loss': train_loss.item(), \n 'valid_total_loss': valid_loss.item(),\n 'train_neg_likelihood': neg_likelihood.item(),\n 'valid_neg_likelihood': valid_neg_likelihood.item(),\n 'train_mean_hscic(rep,prev|target)': hscic_estimate,\n 'valid_mean_hscic(rep,prev|target)': valid_hscic_estimate,\n 'valid_mean_hscic(act,prev|target)': valid_hscic_estimate_action,\n 'eval_episode_return': eval_ret_mean\n }, step=num+1)\n\n if eval_ret_mean > max_score:\n print(f'** max score record! ')\n max_score = eval_ret_mean\n copy_nn_module(self.policy, self.best_policy)\n \n if self.save_policy_path:\n print(f'** save model to ', f'{self.save_policy_path}/bc_actor_best.pt')\n os.makedirs(self.save_policy_path, exist_ok=True)\n torch.save(self.best_policy.state_dict(), \n f'{self.save_policy_path}/bc_actor_best.pt')\n \n print(f'** save model to ', f'{self.save_policy_path}/bc_actor_last.pt')\n os.makedirs(self.save_policy_path, exist_ok=True)\n torch.save(self.policy.state_dict(), \n f'{self.save_policy_path}/bc_actor_last.pt')\n \n \n def evaluate(self, num_iteration=5):\n rets = []\n maxtimestep = 1000\n for num in range(0, num_iteration):\n obs_list = []\n obs = np.zeros(self.obs_dim * self.stacksize)\n \n obs_ = self.env.reset()\n obs_list.append(obs_)\n\n obs = np.zeros(self.obs_dim * self.stacksize)\n obs[- self.obs_dim:] = obs_\n\n done = False\n t = 0\n ret = 0.\n \n while not done and t < maxtimestep:\n if self.standardize:\n obs = (obs - self.obs_mean[0]) / self.obs_std[0]\n obs = torch.tensor(obs, dtype=torch.float32, device=self.device)\n action = self.policy(obs).mean.cpu().detach().numpy()\n \n next_obs, rew, done, _ = self.env.step(action)\n ret += rew\n \n obs_ = next_obs \n obs_list.append(obs_)\n\n if len(obs_list) < self.stacksize:\n obs_ = np.concatenate(obs_list)\n obs = np.zeros(self.obs_dim * self.stacksize)\n obs[-(len(obs_list)) * self.obs_dim:] = obs_\n \n else:\n obs = np.concatenate(obs_list[-self.stacksize:])\n \n t += 1\n \n rets.append(ret)\n \n return np.mean(rets), np.std(rets)" }, { "identifier": "RAP", "path": "imitation/rap.py", "snippet": "class RAP(nn.Module):\n # Implementation of Residual Action Prediction (ECCV 2022)\n # - https://arxiv.org/pdf/2207.09705.pdf\n def __init__(self, policy, env, best_policy=None,\n replay_buffer=None, replay_buffer_valid=None, seed=0, \n device='cpu', lr=3e-4, wandb=None, save_policy_path=None, \n obs_dim=1, action_dim=1, embedding_dim=1, stacksize=1, standardize=False\n ):\n torch.manual_seed(seed)\n np.random.seed(seed)\n random.seed(seed)\n \n super(RAP, self).__init__()\n\n self.env = env\n self.policy = policy\n self.best_policy = best_policy\n self.replay_buffer = replay_buffer\n self.replay_buffer_valid = replay_buffer_valid\n \n self.device = device\n \n self.m_embedding_optimizer = optim.Adam(policy.history_embedding_params, lr=lr)\n self.h_embedding_optimizer = optim.Adam(policy.single_embedding_params, lr=lr)\n self.policy_optimizer = optim.Adam(policy.policy_params, lr=lr)\n self.residual_optimizer = optim.Adam(policy.residual_params, lr=lr)\n\n self.num_eval_iteration = 50 \n \n self.wandb = None\n if wandb:\n self.wandb = wandb\n self.wandb.init()\n\n self.save_policy_path = save_policy_path\n\n self.obs_dim = obs_dim\n self.action_dim = action_dim\n self.embedding_dim = embedding_dim\n self.stacksize = stacksize\n \n self.standardize = standardize\n\n self.obs_mean_tt = torch.tensor(self.replay_buffer.obs_mean, device=device)\n self.obs_std_tt = torch.tensor(self.replay_buffer.obs_std, device=device)\n self.act_mean_tt = torch.tensor(self.replay_buffer.act_mean, device=device)\n self.act_std_tt = torch.tensor(self.replay_buffer.act_std, device=device)\n\n self.obs_mean = self.replay_buffer.obs_mean\n self.obs_std = self.replay_buffer.obs_std\n self.act_mean = self.replay_buffer.act_mean\n self.act_std = self.replay_buffer.act_std\n \n\n def train(self, total_iteration=1e6, eval_freq=1000, batch_size=1024, num_valid=2000):\n \n max_score = -100000. \n min_loss = 100000. \n \n batch_valid = self.replay_buffer_valid.get_batch(num_valid, standardize=self.standardize)\n \n obs_valid = batch_valid['observations']\n actions_valid = batch_valid['actions'][:, -self.action_dim:]\n prev_actions_valid = batch_valid['actions'][:, :-self.action_dim] \n \n obs_valid = torch.tensor(obs_valid, dtype=torch.float32, device=self.device)\n actions_valid = torch.tensor(actions_valid, dtype=torch.float32, device=self.device)\n prev_actions_valid = torch.tensor(prev_actions_valid, dtype=torch.float32, device=self.device) \n \n for num in range(0, int(total_iteration)):\n batch = self.replay_buffer.random_batch(batch_size, standardize=self.standardize)\n \n obs = batch['observations']\n actions = batch['actions'][:, -self.action_dim:]\n prev_actions = batch['actions'][:, :-self.action_dim]\n \n obs = torch.tensor(obs, dtype=torch.float32, device=self.device)\n actions = torch.tensor(actions, dtype=torch.float32, device=self.device)\n prev_actions = torch.tensor(prev_actions, dtype=torch.float32, device=self.device)\n\n self.m_embedding_optimizer.zero_grad()\n self.residual_optimizer.zero_grad() \n \n # m : history embedding, h : single observation embedding\n m, _ = self.policy.forward_embedding(obs) \n action_residuals = actions - prev_actions\n action_residual_pred = self.policy.forward_residual_from_m(m)\n \n train_residual_loss = torch.mean((action_residual_pred - action_residuals) ** 2)\n train_residual_loss.backward()\n \n self.m_embedding_optimizer.step()\n self.residual_optimizer.step() \n \n self.policy_optimizer.zero_grad() \n self.h_embedding_optimizer.zero_grad() \n \n m, h = self.policy.forward_embedding(obs)\n \n # we follow the original implementation that stop-gradient layer on m ; \n # see `forward_policy_from_embedding` method for detail. (m.detach() in input)\n train_neg_likelihood = -self.policy.log_prob_policy_from_m_h(m, h, actions).mean()\n train_neg_likelihood.backward()\n \n self.policy_optimizer.step()\n self.h_embedding_optimizer.step()\n \n if (num+1) % eval_freq == 0: \n valid_m, valid_h = self.policy.forward_embedding(obs_valid) \n valid_action_residuals = actions_valid - prev_actions_valid\n valid_action_residual_pred = self.policy.forward_residual_from_m(valid_m)\n \n valid_policy_neg_likelihood = -self.policy.log_prob_policy_from_m_h(valid_m, valid_h, actions_valid).mean()\n valid_residual_loss = torch.mean((valid_action_residual_pred - valid_action_residuals) ** 2) \n \n valid_loss = valid_policy_neg_likelihood + valid_residual_loss\n \n policy_action_valid = self.policy(obs_valid).sample() \n \n train_mh = torch.cat([m,h], dim=-1)\n valid_mh = torch.cat([valid_m, valid_h], dim=-1)\n \n hscic_estimate = estimate_hscic(X=train_mh, Y=prev_actions, Z=actions, ridge_lambda=1e-5)\n valid_hscic_estimate = estimate_hscic(X=valid_mh, Y=prev_actions_valid, Z=actions_valid, ridge_lambda=1e-5)\n valid_hscic_estimate_action = estimate_hscic(X=policy_action_valid, Y=prev_actions_valid, Z=actions_valid, ridge_lambda=1e-5) \n train_hscic_m_a_given_aprev = estimate_hscic(X=m, Y=actions, Z=prev_actions, ridge_lambda=1e-5)\n valid_hscic_m_a_given_aprev = estimate_hscic(X=valid_m, Y=actions_valid, Z=prev_actions_valid, ridge_lambda=1e-5)\n \n eval_ret_mean, eval_ret_std = self.evaluate(num_iteration=self.num_eval_iteration)\n \n train_loss = train_neg_likelihood + train_residual_loss\n \n print(f'** iter{num+1}: train_loss={train_loss.item()}, nll={train_neg_likelihood}, residual_loss={train_residual_loss}, eval_ret={eval_ret_mean}+-{eval_ret_std}')\n print(f' valid_loss={valid_loss.item()}, valid_nll={valid_policy_neg_likelihood}, valid_residual_loss={valid_residual_loss}')\n \n print(f'** HSCIC(mh, a_prev | a_current) : (train){hscic_estimate:.6f} (valid){valid_hscic_estimate:.6f} (valid,action){valid_hscic_estimate_action:.6f}')\n print(f'** HSCIC(m, a_current | a_prev) : (train){train_hscic_m_a_given_aprev:.6f} (valid){valid_hscic_m_a_given_aprev:.6f} ')\n \n if self.wandb:\n self.wandb.log({\n 'train_total_loss': train_loss.item(),\n 'valid_total_loss': valid_loss.item(),\n 'train_neg_likelihood': train_neg_likelihood.item(),\n 'valid_neg_likelihood': valid_policy_neg_likelihood.item(),\n 'train_mean_hscic(rep,prev|target)': hscic_estimate,\n 'valid_mean_hscic(rep,prev|target)': valid_hscic_estimate,\n 'valid_mean_hscic(act,prev|target)': valid_hscic_estimate_action,\n 'train_residual_loss': train_residual_loss,\n 'valid_residual_loss': valid_residual_loss,\n 'train_mean_hscic(m,target|prev)': train_hscic_m_a_given_aprev,\n 'valid_mean_hscic(m,target|prev)': valid_hscic_m_a_given_aprev,\n 'eval_episode_return': eval_ret_mean\n }, step=num+1)\n\n if eval_ret_mean > max_score:\n print(f'** max score ')\n max_score = eval_ret_mean\n copy_nn_module(self.policy, self.best_policy)\n \n if self.save_policy_path:\n print(f'** save model to ', f'{self.save_policy_path}/bc_actor_best.pt')\n os.makedirs(self.save_policy_path, exist_ok=True)\n torch.save(self.best_policy.state_dict(), \n f'{self.save_policy_path}/bc_actor_best.pt')\n \n print(f'** save model to ', f'{self.save_policy_path}/bc_actor_last.pt')\n os.makedirs(self.save_policy_path, exist_ok=True)\n torch.save(self.policy.state_dict(), \n f'{self.save_policy_path}/bc_actor_last.pt')\n \n \n def evaluate(self, num_iteration=5):\n rets = []\n maxtimestep = 1000\n for num in range(0, num_iteration):\n obs_list = []\n obs = np.zeros(self.obs_dim * self.stacksize)\n \n obs_ = self.env.reset()\n obs_list.append(obs_)\n\n obs = np.zeros(self.obs_dim * self.stacksize)\n obs[- self.obs_dim:] = obs_\n\n done = False\n t = 0\n ret = 0.\n \n while not done and t < maxtimestep:\n # obs = obs[:true_obs_dim]\n if self.standardize:\n obs = (obs - self.obs_mean[0]) / self.obs_std[0]\n obs = torch.tensor(obs, dtype=torch.float32, device=self.device)\n action = self.policy(obs).mean.cpu().detach().numpy()[0]\n next_obs, rew, done, env_info = self.env.step(action)\n ret += rew\n \n obs_ = next_obs \n obs_list.append(obs_)\n\n if len(obs_list) < self.stacksize:\n obs_ = np.concatenate(obs_list)\n obs = np.zeros(self.obs_dim * self.stacksize)\n obs[-(len(obs_list)) * self.obs_dim:] = obs_\n \n else:\n obs = np.concatenate(obs_list[-self.stacksize:])\n \n t += 1\n \n rets.append(ret)\n \n return np.mean(rets), np.std(rets)" }, { "identifier": "FCA", "path": "imitation/fca.py", "snippet": "class FCA(nn.Module):\n def __init__(self, policy, env, best_policy=None,\n replay_buffer=None, replay_buffer_valid=None, seed=0, \n device='cpu', lr=3e-4, wandb=None, save_policy_path=None, \n obs_dim=1, action_dim=1, stacksize=1, standardize=True,\n embedding_dim=1, entropy_hidden_size=300, entropy_lr=1e-4, reg_coef=1e-5, info_bottleneck_loss_coef=0.001, \n ):\n torch.manual_seed(seed)\n np.random.seed(seed)\n random.seed(seed)\n \n super(FCA, self).__init__()\n\n self.env = env\n self.policy = policy\n self.best_policy = best_policy\n self.replay_buffer = replay_buffer\n self.replay_buffer_valid = replay_buffer_valid \n self.device = device\n \n self.obs_dim = obs_dim\n self.action_dim = action_dim\n self.embedding_dim = embedding_dim\n self.stacksize = stacksize \n\n # Additional Network for Conditional Entropy (FCA)\n self.entropy_input_size = embedding_dim + action_dim\n self.entropy_hidden_size = entropy_hidden_size\n self.entropy_net = nn.Sequential(\n nn.Linear(self.entropy_input_size, self.entropy_hidden_size, device=self.device),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Linear(self.entropy_hidden_size, action_dim, device=self.device)\n )\n \n # FCA Hyperparameters\n self.entropy_coef = reg_coef \n self.info_bottleneck_loss_coef = info_bottleneck_loss_coef \n \n self.embedding_optimizer = optim.Adam(policy.embedding_params, lr=lr)\n self.policy_optimizer = optim.Adam(policy.policy_params, lr=lr)\n self.entropy_optimizer = optim.Adam(self.entropy_net.parameters(), lr=entropy_lr)\n\n self.num_eval_iteration = 50\n \n self.wandb = None\n if wandb:\n self.wandb = wandb\n self.wandb.init()\n\n self.save_policy_path = save_policy_path\n\n # For standardization\n self.standardize = standardize\n\n self.obs_mean_tt = torch.tensor(self.replay_buffer.obs_mean, device=device)\n self.obs_std_tt = torch.tensor(self.replay_buffer.obs_std, device=device)\n self.act_mean_tt = torch.tensor(self.replay_buffer.act_mean, device=device)\n self.act_std_tt = torch.tensor(self.replay_buffer.act_std, device=device)\n\n self.obs_mean = self.replay_buffer.obs_mean\n self.obs_std = self.replay_buffer.obs_std\n self.act_mean = self.replay_buffer.act_mean\n self.act_std = self.replay_buffer.act_std \n\n def train(self, total_iteration=1e6, eval_freq=1000, batch_size=1024, num_valid=2000, inner_steps=1):\n \n max_score = -100000. \n min_loss = 100000. \n \n batch_valid = self.replay_buffer_valid.get_batch(num_valid, standardize=self.standardize)\n \n obs_valid = batch_valid['observations']\n actions_valid = batch_valid['actions'][:, -self.action_dim:]\n prev_actions_valid = batch_valid['actions'][:, :-self.action_dim] \n \n obs_valid = torch.tensor(obs_valid, dtype=torch.float32, device=self.device)\n actions_valid = torch.tensor(actions_valid, dtype=torch.float32, device=self.device)\n prev_actions_valid = torch.tensor(prev_actions_valid, dtype=torch.float32, device=self.device) \n \n for num in range(0, int(total_iteration)):\n batch = self.replay_buffer.random_batch(batch_size, standardize=self.standardize)\n \n obs = batch['observations']\n actions = batch['actions'][:, -self.action_dim:]\n prev_actions = batch['actions'][:, :-self.action_dim]\n \n obs = torch.tensor(obs, dtype=torch.float32, device=self.device)\n actions = torch.tensor(actions, dtype=torch.float32, device=self.device)\n prev_actions = torch.tensor(prev_actions, dtype=torch.float32, device=self.device)\n\n # conditional entropy input : H(a_{t-1}| a_{t}, varphi_t)\n h = self.policy.forward_embedding(obs)\n expert_action_and_h = torch.cat([actions, h], dim=-1) \n \n self.policy_optimizer.zero_grad()\n self.embedding_optimizer.zero_grad()\n self.entropy_optimizer.zero_grad()\n\n if self.entropy_coef > 0.:\n neg_likelihood = -self.policy.log_prob_policy_from_embedding(h, actions).mean()\n info_bottleneck_loss = 0.5 * (h ** 2).sum()\n\n # prev_actions = torch.tensor(prev_actions, dtype=torch.float32, device=self.device)\n pred_prev_actions = self.entropy_net(expert_action_and_h) \n entropy_loss = torch.mean((pred_prev_actions - prev_actions) ** 2) \n\n train_loss = neg_likelihood \\\n - self.entropy_coef * entropy_loss \\\n + self.info_bottleneck_loss_coef * info_bottleneck_loss\n \n train_loss.backward() # backprop embedding\n \n self.policy_optimizer.step()\n self.embedding_optimizer.step()\n\n # conditional entropy training\n for _ in range(inner_steps):\n batch = self.replay_buffer.random_batch(batch_size, standardize=self.standardize)\n \n obs = batch['observations']\n actions = batch['actions'][:, -self.action_dim:]\n prev_actions = batch['actions'][:, :-self.action_dim]\n \n obs = torch.tensor(obs, dtype=torch.float32, device=self.device) \n actions = torch.tensor(actions, dtype=torch.float32, device=self.device)\n \n h = self.policy.forward_embedding(obs)\n expert_action_and_h = torch.cat([actions, h], dim=-1) \n\n prev_actions = torch.tensor(prev_actions, dtype=torch.float32, device=self.device) \n pred_prev_actions = self.entropy_net(expert_action_and_h.detach())\n\n entropy_loss = torch.mean((pred_prev_actions - prev_actions) ** 2)\n \n self.entropy_optimizer.zero_grad()\n entropy_loss.backward()\n self.entropy_optimizer.step()\n\n else:\n neg_likelihood = -self.policy.log_prob_policy_from_embedding(h, actions).mean()\n info_bottleneck_loss = 0.5 * (h ** 2).sum()\n \n train_loss = neg_likelihood + self.info_bottleneck_loss_coef * info_bottleneck_loss \n \n train_loss.backward()\n \n self.policy_optimizer.step()\n self.embedding_optimizer.step() \n \n\n if (num+1) % eval_freq == 0: \n h_valid = self.policy.forward_embedding(obs_valid)\n valid_info_bottleneck_loss = 0.5 * (h_valid ** 2).sum()\n \n if self.entropy_coef > 0:\n expert_action_and_h_valid = torch.cat([actions_valid, h_valid], dim=-1) \n pred_prev_actions_valid = self.entropy_net(expert_action_and_h_valid)\n \n prev_actions_valid = batch_valid['actions'][:, :-self.action_dim]\n prev_actions_valid = torch.tensor(prev_actions_valid, dtype=torch.float32, device=self.device)\n \n valid_entropy_loss = torch.mean((pred_prev_actions_valid - prev_actions_valid) ** 2)\n else:\n valid_entropy_loss = 0.\n \n valid_neg_likelihood = - self.policy.log_prob(obs_valid, actions_valid).mean()\n \n valid_loss = valid_neg_likelihood \\\n - self.entropy_coef * valid_entropy_loss \\\n + self.info_bottleneck_loss_coef * valid_info_bottleneck_loss\n \n policy_action_valid = self.policy(obs_valid).sample() \n h_train = self.policy.forward_embedding(obs)\n \n hscic_estimate = estimate_hscic(X=h_train, Y=prev_actions, Z=actions, ridge_lambda=1e-5)\n valid_hscic_estimate = estimate_hscic(X=h_valid, Y=prev_actions_valid, Z=actions_valid, ridge_lambda=1e-5)\n valid_hscic_estimate_action = estimate_hscic(X=policy_action_valid, Y=prev_actions_valid, Z=actions_valid, ridge_lambda=1e-5)\n \n eval_ret_mean, eval_ret_std = self.evaluate(num_iteration=self.num_eval_iteration)\n \n print(f'** iter{num+1}: entropy_loss={entropy_loss}, train_loss={train_loss.item()}, eval_ret={eval_ret_mean}+-{eval_ret_std} ')\n print(f'** HSCIC : (train){hscic_estimate:.6f} (valid){valid_hscic_estimate:.6f} (valid,action){valid_hscic_estimate_action:.6f}')\n \n if self.wandb:\n self.wandb.log({\n 'train_total_loss': train_loss.item(), \n 'valid_total_loss': valid_loss.item(),\n 'train_neg_likelihood': neg_likelihood.item(), \n 'valid_neg_likelihood': valid_neg_likelihood.item(),\n 'train_mean_hscic(rep,prev|target)': hscic_estimate,\n 'valid_mean_hscic(rep,prev|target)': valid_hscic_estimate,\n 'valid_mean_hscic(act,prev|target)': valid_hscic_estimate_action,\n 'valid_entropy_loss': entropy_loss, \n 'valid_IB_loss': info_bottleneck_loss.item(),\n 'eval_episode_return': eval_ret_mean\n }, step=num+1)\n\n if eval_ret_mean > max_score:\n print(f'** max score record! ')\n max_score = eval_ret_mean\n copy_nn_module(self.policy, self.best_policy)\n \n if self.save_policy_path:\n print(f'** save model to ', f'{self.save_policy_path}/bc_actor_best.pt')\n os.makedirs(self.save_policy_path, exist_ok=True)\n torch.save(self.best_policy.state_dict(), \n f'{self.save_policy_path}/bc_actor_best.pt')\n \n print(f'** save model to ', f'{self.save_policy_path}/bc_actor_last.pt')\n os.makedirs(self.save_policy_path, exist_ok=True)\n torch.save(self.policy.state_dict(), \n f'{self.save_policy_path}/bc_actor_last.pt')\n \n \n def evaluate(self, num_iteration=5):\n rets = []\n maxtimestep = 1000\n for num in range(0, num_iteration):\n obs_list = []\n obs = np.zeros(self.obs_dim * self.stacksize)\n \n obs_ = self.env.reset()\n obs_list.append(obs_)\n\n obs = np.zeros(self.obs_dim * self.stacksize)\n obs[- self.obs_dim:] = obs_\n\n done = False\n t = 0\n ret = 0.\n \n while not done and t < maxtimestep: \n if self.standardize:\n obs = (obs - self.obs_mean[0]) / self.obs_std[0]\n obs = torch.tensor(obs, dtype=torch.float32, device=self.device)\n action = self.policy(obs).mean.cpu().detach().numpy()\n \n next_obs, rew, done, _ = self.env.step(action)\n ret += rew\n \n obs_ = next_obs \n obs_list.append(obs_)\n\n if len(obs_list) < self.stacksize:\n obs_ = np.concatenate(obs_list)\n obs = np.zeros(self.obs_dim * self.stacksize)\n obs[-(len(obs_list)) * self.obs_dim:] = obs_\n \n else:\n obs = np.concatenate(obs_list[-self.stacksize:])\n \n t += 1\n \n rets.append(ret)\n \n return np.mean(rets), np.std(rets)" }, { "identifier": "MINE_BC", "path": "imitation/mine.py", "snippet": "class MINE_BC(nn.Module):\n def __init__(self, policy, env, best_policy=None,\n replay_buffer=None, replay_buffer_valid=None, seed=0, \n device='cpu', lr=3e-4, wandb=None, save_policy_path=None, \n obs_dim=1, action_dim=1, stacksize=1, standardize=True,\n embedding_dim=1, mine_lr=1e-4, reg_coef=1e-5, info_bottleneck_loss_coef=0.001, \n ):\n torch.manual_seed(seed)\n np.random.seed(seed)\n random.seed(seed)\n \n super(MINE_BC, self).__init__()\n\n self.env = env\n self.policy = policy\n self.best_policy = best_policy\n self.replay_buffer = replay_buffer\n self.replay_buffer_valid = replay_buffer_valid\n self.device = device\n \n self.obs_dim = obs_dim\n self.action_dim = action_dim\n self.embedding_dim = embedding_dim\n self.stacksize = stacksize\n \n # Additional Network for MINE Neural Estimator\n self.mine = MINE_DV(action_dim, action_dim + embedding_dim, device=device)\n \n # MINE-BC Hyperparameters\n self.reg_coef = reg_coef\n self.info_bottleneck_loss_coef = info_bottleneck_loss_coef\n\n self.embedding_optimizer = optim.Adam(policy.embedding_params, lr=lr)\n self.policy_optimizer = optim.Adam(policy.policy_params, lr=lr)\n self.mine_optimizer = optim.Adam(self.mine.parameters(), lr=mine_lr)\n \n self.num_eval_iteration = 50\n \n self.wandb = None\n if wandb:\n self.wandb = wandb\n self.wandb.init()\n\n self.save_policy_path = save_policy_path\n\n # For standardization \n self.standardize = standardize\n\n self.obs_mean_tt = torch.tensor(self.replay_buffer.obs_mean, device=device)\n self.obs_std_tt = torch.tensor(self.replay_buffer.obs_std, device=device)\n self.act_mean_tt = torch.tensor(self.replay_buffer.act_mean, device=device)\n self.act_std_tt = torch.tensor(self.replay_buffer.act_std, device=device)\n\n self.obs_mean = self.replay_buffer.obs_mean\n self.obs_std = self.replay_buffer.obs_std\n self.act_mean = self.replay_buffer.act_mean\n self.act_std = self.replay_buffer.act_std\n \n def train(self, total_iteration=1e6, eval_freq=1000, batch_size=1024, num_valid=2000, inner_steps=1):\n \n min_loss = 100000.\n max_score = -100000.\n \n batch_valid = self.replay_buffer_valid.get_batch(num_valid, standardize=self.standardize)\n \n obs_valid = batch_valid['observations']\n actions_valid = batch_valid['actions'][:, -self.action_dim:]\n prev_actions_valid = batch_valid['actions'][:, :-self.action_dim] \n \n obs_valid = torch.tensor(obs_valid, dtype=torch.float32, device=self.device)\n actions_valid = torch.tensor(actions_valid, dtype=torch.float32, device=self.device)\n prev_actions_valid = torch.tensor(prev_actions_valid, dtype=torch.float32, device=self.device)\n \n for num in range(0, int(total_iteration)):\n batch = self.replay_buffer.random_batch(batch_size, standardize=self.standardize)\n \n obs = batch['observations']\n actions = batch['actions'][:, -self.action_dim:]\n prev_actions = batch['actions'][:, :-self.action_dim]\n \n obs = torch.tensor(obs, dtype=torch.float32, device=self.device)\n actions = torch.tensor(actions, dtype=torch.float32, device=self.device)\n prev_actions = torch.tensor(prev_actions, dtype=torch.float32, device=self.device)\n\n # MINE : I (a_{t-1}; a_{t}, varphi_t)\n h = self.policy.forward_embedding(obs)\n expert_action_and_h = torch.cat([actions, h], dim=-1)\n \n self.policy_optimizer.zero_grad()\n self.embedding_optimizer.zero_grad()\n self.mine_optimizer.zero_grad()\n\n if self.reg_coef > 0:\n neg_likelihood = -self.policy.log_prob_policy_from_embedding(h, actions).mean()\n info_bottleneck_loss = 0.5 * (h ** 2).sum()\n mi_estimate = self.mine.get_mi_bound(prev_actions, expert_action_and_h, update_ema=False)\n\n train_loss = neg_likelihood \\\n + self.reg_coef * mi_estimate \\\n + self.info_bottleneck_loss_coef * info_bottleneck_loss\n \n train_loss.backward()\n \n self.policy_optimizer.step()\n self.embedding_optimizer.step()\n\n # MINE training\n for _ in range(inner_steps):\n batch = self.replay_buffer.random_batch(batch_size, standardize=self.standardize)\n\n obs = batch['observations']\n actions = batch['actions'][:, -self.action_dim:]\n prev_actions = batch['actions'][:, :-self.action_dim]\n \n obs = torch.tensor(obs, dtype=torch.float32, device=self.device)\n actions = torch.tensor(actions, dtype=torch.float32, device=self.device)\n \n h = self.policy.forward_embedding(obs)\n expert_action_and_h = torch.cat([actions, h], dim=-1)\n \n prev_actions = torch.tensor(prev_actions, dtype=torch.float32, device=self.device)\n \n mine_loss = -self.mine.get_mi_bound(prev_actions, expert_action_and_h.detach(), update_ema=True)\n\n self.mine_optimizer.zero_grad()\n mine_loss.backward()\n self.mine_optimizer.step()\n\n else:\n neg_likelihood = -self.policy.log_prob_policy_from_embedding(h, actions).mean()\n info_bottleneck_loss = 0.5 * (h ** 2).sum()\n \n train_loss = neg_likelihood + self.info_bottleneck_loss_coef * info_bottleneck_loss \n \n train_loss.backward()\n \n self.policy_optimizer.step()\n self.embedding_optimizer.step()\n \n\n if (num+1) % eval_freq == 0:\n h_valid = self.policy.forward_embedding(obs_valid)\n valid_info_bottleneck_loss = 0.5 * (h_valid ** 2).sum()\n \n if self.reg_coef > 0:\n expert_action_and_h_valid = torch.cat([actions_valid, h_valid], dim=-1) \n valid_mi_estimate = self.mine.get_mi_bound(prev_actions_valid, expert_action_and_h_valid, update_ema=False)\n else:\n valid_mi_estimate = 0.\n \n valid_neg_likelihood = -self.policy.log_prob(obs_valid, actions_valid).mean()\n\n valid_loss = valid_neg_likelihood \\\n + self.reg_coef * valid_mi_estimate \\\n + self.info_bottleneck_loss_coef * valid_info_bottleneck_loss\n \n policy_action_valid = self.policy(obs_valid).sample() \n h_train = self.policy.forward_embedding(obs)\n \n hscic_estimate = estimate_hscic(X=h_train, Y=prev_actions, Z=actions, ridge_lambda=1e-5)\n valid_hscic_estimate = estimate_hscic(X=h_valid, Y=prev_actions_valid, Z=actions_valid, ridge_lambda=1e-5)\n valid_hscic_estimate_action = estimate_hscic(X=policy_action_valid, Y=prev_actions_valid, Z=actions_valid, ridge_lambda=1e-5)\n \n eval_ret_mean, eval_ret_std = self.evaluate(num_iteration=self.num_eval_iteration)\n \n print(f'** iter{num+1}: mine_loss={-mi_estimate.cpu().item()}, train_loss={train_loss.item()}, eval_ret={eval_ret_mean}+-{eval_ret_std} ')\n print(f'** HSCIC : (train){hscic_estimate:.6f} (valid){valid_hscic_estimate:.6f} (valid,action){valid_hscic_estimate_action:.6f}')\n \n if self.wandb:\n self.wandb.log({\n 'train_total_loss': train_loss.cpu().item(),\n 'valid_total_loss': valid_loss.cpu().item(),\n 'train_neg_likelihood': neg_likelihood.cpu().item(),\n 'valid_neg_likelihood': valid_neg_likelihood.cpu().item(),\n 'train_mean_hscic(rep,prev|target)': hscic_estimate,\n 'valid_mean_hscic(rep,prev|target)': valid_hscic_estimate,\n 'valid_mean_hscic(act,prev|target)': valid_hscic_estimate_action,\n 'valid_mine_loss': -mi_estimate.cpu().item(),\n 'valid_IB_loss': info_bottleneck_loss.cpu().item(),\n 'eval_episode_return': eval_ret_mean\n }, step=num+1)\n\n if eval_ret_mean > max_score:\n print(f'** max score record! ')\n max_score = eval_ret_mean\n copy_nn_module(self.policy, self.best_policy)\n \n if self.save_policy_path:\n print(f'** save model to ', f'{self.save_policy_path}/bc_actor_best.pt')\n os.makedirs(self.save_policy_path, exist_ok=True)\n torch.save(self.best_policy.state_dict(), \n f'{self.save_policy_path}/bc_actor_best.pt')\n \n print(f'** save model to ', f'{self.save_policy_path}/bc_actor_last.pt')\n os.makedirs(self.save_policy_path, exist_ok=True)\n torch.save(self.policy.state_dict(), \n f'{self.save_policy_path}/bc_actor_last.pt')\n \n \n def evaluate(self, num_iteration=5):\n rets = []\n maxtimestep = 1000\n for num in range(0, num_iteration):\n obs_list = []\n obs = np.zeros(self.obs_dim * self.stacksize)\n \n obs_ = self.env.reset()\n obs_list.append(obs_)\n\n obs = np.zeros(self.obs_dim * self.stacksize)\n obs[- self.obs_dim:] = obs_\n\n done = False\n t = 0\n ret = 0.\n \n while not done and t < maxtimestep: \n if self.standardize:\n obs = (obs - self.obs_mean[0]) / self.obs_std[0]\n obs = torch.tensor(obs, dtype=torch.float32, device=self.device)\n action = self.policy(obs).mean.cpu().detach().numpy()\n next_obs, rew, done, _ = self.env.step(action)\n ret += rew\n \n obs_ = next_obs \n obs_list.append(obs_)\n\n if len(obs_list) < self.stacksize:\n obs_ = np.concatenate(obs_list)\n obs = np.zeros(self.obs_dim * self.stacksize)\n obs[-(len(obs_list)) * self.obs_dim:] = obs_\n \n else:\n obs = np.concatenate(obs_list[-self.stacksize:])\n \n t += 1\n \n rets.append(ret)\n \n return np.mean(rets), np.std(rets)" }, { "identifier": "PALR", "path": "imitation/palr.py", "snippet": "class PALR(nn.Module):\n def __init__(self, policy, env, best_policy=None,\n replay_buffer=None, replay_buffer_valid=None, seed=0, \n device='cpu', lr=3e-4, wandb=None, save_policy_path=None, \n obs_dim=1, action_dim=1, stacksize=1, standardize=True,\n reg_coef=0.01, ridge_lambda=1e-3):\n \n torch.manual_seed(seed)\n np.random.seed(seed)\n random.seed(seed)\n \n super(PALR, self).__init__()\n\n self.env = env\n self.policy = policy\n self.best_policy = best_policy\n self.replay_buffer = replay_buffer\n self.replay_buffer_valid = replay_buffer_valid\n self.device = device\n\n self.obs_dim = obs_dim\n self.action_dim = action_dim\n self.stacksize = stacksize\n \n self.policy_optimizer = optim.Adam(self.policy.parameters(), lr=lr) \n \n self.num_eval_iteration = 50\n \n self.wandb = None\n if wandb:\n self.wandb = wandb\n self.wandb.init()\n\n self.save_policy_path = save_policy_path\n \n # HSCIC Hyperparameters\n self.reg_coef = reg_coef\n self.ridge_lambda = ridge_lambda\n \n # For standardization\n self.standardize = standardize\n\n self.obs_mean_tt = torch.tensor(self.replay_buffer.obs_mean, device=device)\n self.obs_std_tt = torch.tensor(self.replay_buffer.obs_std, device=device)\n self.act_mean_tt = torch.tensor(self.replay_buffer.act_mean, device=device)\n self.act_std_tt = torch.tensor(self.replay_buffer.act_std, device=device)\n\n self.obs_mean = self.replay_buffer.obs_mean\n self.obs_std = self.replay_buffer.obs_std\n self.act_mean = self.replay_buffer.act_mean\n self.act_std = self.replay_buffer.act_std\n \n\n def train(self, total_iteration=1e6, eval_freq=1000, batch_size=1024, num_valid=2000):\n \n min_loss = 100000.\n max_score = -100000.\n \n batch_valid = self.replay_buffer_valid.get_batch(num_valid, standardize=self.standardize)\n \n obs_valid = batch_valid['observations'] \n actions_valid = batch_valid['actions'][:, -self.action_dim:]\n prev_expert_action_valid = batch_valid['actions'][:, :-self.action_dim]\n \n obs_valid = torch.tensor(obs_valid, dtype=torch.float32, device=self.device)\n actions_valid = torch.tensor(actions_valid, dtype=torch.float32, device=self.device)\n prev_expert_action_valid = torch.tensor(prev_expert_action_valid, dtype=torch.float32, device=self.device)\n \n for num in range(0, int(total_iteration)):\n batch = self.replay_buffer.random_batch(batch_size, standardize=self.standardize)\n\n obs = batch['observations']\n actions = batch['actions'][:, -self.action_dim:]\n prev_expert_action = batch['actions'][:, :-self.action_dim]\n \n obs = torch.tensor(obs, dtype=torch.float32, device=self.device)\n actions = torch.tensor(actions, dtype=torch.float32, device=self.device)\n prev_expert_action = torch.tensor(prev_expert_action, dtype=torch.float32, device=self.device)\n\n neg_likelihood = - self.policy.log_prob(obs, actions).mean() \n policy_action = self.policy(obs).rsample()\n \n if self.reg_coef != 0: \n policy_embedding = self.policy.forward_embedding(obs)\n if self.standardize:\n Y_std = (prev_expert_action - self.act_mean_tt[0, :-self.action_dim])/ self.act_std_tt[0, :-self.action_dim]\n Z_std = (actions - self.act_mean_tt[0, -self.action_dim:])/ self.act_std_tt[0, -self.action_dim:]\n\n Y_std = Y_std.to(torch.float32)\n Z_std = Z_std.to(torch.float32)\n else:\n Y_std = prev_expert_action\n Z_std = actions\n \n hscic_estimate = estimate_hscic(X=policy_embedding, Y=Y_std, Z=Z_std, ridge_lambda=self.ridge_lambda)\n \n else:\n hscic_estimate = 0.\n \n train_loss = neg_likelihood + self.reg_coef * hscic_estimate \n\n self.policy_optimizer.zero_grad()\n train_loss.backward()\n self.policy_optimizer.step()\n\n if (num+1) % eval_freq == 0:\n policy_action = self.policy(obs).sample()\n policy_action_valid = self.policy(obs_valid).sample()\n \n # Train data HSCIC (for debugging) \n policy_embedding = self.policy.forward_embedding(obs)\n if self.standardize:\n Y_std = (prev_expert_action - self.act_mean_tt[0, :-self.action_dim])/ self.act_std_tt[0, :-self.action_dim]\n Z_std = (actions - self.act_mean_tt[0, -self.action_dim:])/ self.act_std_tt[0, -self.action_dim:]\n p_std = (policy_action - self.act_mean_tt[0, -self.action_dim:])/ self.act_std_tt[0, -self.action_dim:]\n\n Y_std = Y_std.to(torch.float32)\n Z_std = Z_std.to(torch.float32)\n p_std = p_std.to(torch.float32)\n \n else:\n Y_std = prev_expert_action\n Z_std = actions\n p_std = policy_action\n \n hscic_estimate = estimate_hscic(X=policy_embedding, Y=Y_std, Z=Z_std, ridge_lambda=self.ridge_lambda)\n \n policy_embedding_valid = self.policy.forward_embedding(obs_valid)\n if self.standardize:\n Y_std = (prev_expert_action_valid - self.act_mean_tt[0, :-self.action_dim])/ self.act_std_tt[0, :-self.action_dim]\n Z_std = (actions_valid - self.act_mean_tt[0, -self.action_dim:])/ self.act_std_tt[0, -self.action_dim:]\n\n Y_std = Y_std.to(torch.float32)\n Z_std = Z_std.to(torch.float32)\n else:\n Y_std = prev_expert_action_valid\n Z_std = actions_valid\n p_std = policy_action\n \n valid_hscic_estimate = estimate_hscic(X=policy_embedding_valid, Y=Y_std, Z=Z_std, ridge_lambda=self.ridge_lambda) \n valid_hscic_estimate_action = estimate_hscic(X=policy_action_valid, Y=prev_expert_action_valid, Z=actions_valid, ridge_lambda=self.ridge_lambda)\n\n valid_neg_likelihood = -self.policy.log_prob(obs_valid, actions_valid).mean()\n valid_loss = valid_neg_likelihood + self.reg_coef * valid_hscic_estimate\n\n eval_ret_mean, eval_ret_std = self.evaluate(num_iteration=self.num_eval_iteration)\n \n print(f'** iter{num+1}: train_policy_loss={train_loss.item():.2f}, val_policy_loss={valid_loss.item():.2f}, eval_ret={eval_ret_mean:.2f}+-{eval_ret_std:.2f}',)\n print(f'** HSCIC : (train){hscic_estimate:.6f} (valid){valid_hscic_estimate:.6f} (valid,action){valid_hscic_estimate_action:.6f}')\n \n if self.wandb:\n self.wandb.log({'train_total_loss': train_loss.item(), \n 'valid_total_loss': valid_loss.item(),\n 'train_neg_likelihood': neg_likelihood.item(),\n 'valid_neg_likelihood': valid_neg_likelihood.item(),\n 'train_mean_hscic(rep,prev|target)': hscic_estimate,\n 'valid_mean_hscic(rep,prev|target)': valid_hscic_estimate,\n 'valid_mean_hscic(act,prev|target)': valid_hscic_estimate_action,\n 'eval_episode_return': eval_ret_mean\n }, step=num+1)\n\n if eval_ret_mean > max_score:\n print(f'** max score record! ')\n max_score = eval_ret_mean\n copy_nn_module(self.policy, self.best_policy)\n \n if self.save_policy_path:\n print(f'** save model to ', f'{self.save_policy_path}/bc_actor_best.pt')\n os.makedirs(self.save_policy_path, exist_ok=True)\n torch.save(self.best_policy.state_dict(), \n f'{self.save_policy_path}/bc_actor_best.pt')\n \n print(f'** save model to ', f'{self.save_policy_path}/bc_actor_last.pt')\n os.makedirs(self.save_policy_path, exist_ok=True)\n torch.save(self.policy.state_dict(), \n f'{self.save_policy_path}/bc_actor_last.pt')\n \n def evaluate(self, num_iteration=5):\n rets = []\n maxtimestep = 1000\n for num in range(0, num_iteration):\n obs_list = []\n obs = np.zeros(self.obs_dim * self.stacksize)\n \n obs_ = self.env.reset()\n obs_list.append(obs_)\n\n obs = np.zeros(self.obs_dim * self.stacksize)\n obs[- self.obs_dim:] = obs_\n\n done = False\n t = 0\n ret = 0.\n \n while not done and t < maxtimestep:\n if self.standardize:\n obs = (obs - self.obs_mean[0]) / self.obs_std[0]\n obs = torch.tensor(obs, dtype=torch.float32, device=self.device)\n action = self.policy(obs).mean.cpu().detach().numpy()\n \n next_obs, rew, done, _ = self.env.step(action)\n ret += rew\n \n obs_ = next_obs \n obs_list.append(obs_)\n\n if len(obs_list) < self.stacksize:\n obs_ = np.concatenate(obs_list)\n obs = np.zeros(self.obs_dim * self.stacksize)\n obs[-(len(obs_list)) * self.obs_dim:] = obs_\n \n else:\n obs = np.concatenate(obs_list[-self.stacksize:])\n \n t += 1\n \n rets.append(ret)\n \n return np.mean(rets), np.std(rets)" }, { "identifier": "TanhGaussianPolicyWithEmbedding", "path": "core/policy.py", "snippet": "class TanhGaussianPolicyWithEmbedding(TorchStochasticPolicy):\n \"\"\"\n Reference : \n https://github.com/AlvinWen428/fighting-copycat-agents/blob/52dabfd8b1c42e50f31d84bd431915aad62e09cb/imitation_learning/models/gan_model/__init__.py#L9\n \n Usage:\n\n ```\n policy = TanhGaussianPolicy(...)\n \"\"\"\n\n def __init__(\n self,\n obs_dim,\n action_dim,\n embedding_dim,\n embedding_hidden_size,\n policy_hidden_size, \n policy_std=None,\n disc_std=None,\n init_w=1e-3,\n device='cpu',\n hidden_activation=F.leaky_relu, \n layer_norm=False,\n **kwargs\n ):\n if device =='cuda':\n ptu.set_gpu_mode(True)\n self.device = device\n \n super(TanhGaussianPolicyWithEmbedding, self).__init__()\n # hidden_sizes,\n # input_size=obs_dim,\n # output_size=action_dim,\n # init_w=init_w,\n # device=device,\n # **kwargs\n # )\n\n self.input_size = obs_dim\n self.output_size = action_dim\n self.hidden_activation = hidden_activation\n self.layer_norm = layer_norm\n\n self.embedding_params = []\n self.disc_params = []\n self.policy_params = []\n\n self.embed_fcs = []\n # self.embed_layer_norms = []\n\n self.policy_fcs = []\n # self.policy_layer_norms = []\n\n self.disc_fcs = []\n # self.disc_layer_norms = []\n \n self.device = device\n in_size = self.input_size\n\n self.embed_fcs = nn.Sequential(\n nn.Linear(self.input_size, embedding_hidden_size, bias=False, device=self.device),\n # nn.BatchNorm1d(embedding_hidden_size),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Linear(embedding_hidden_size, embedding_dim, device=self.device), \n )\n self.embedding_params = self.embed_fcs.parameters()\n\n self.policy_fcs = nn.Sequential(\n nn.LeakyReLU(0.2, inplace=False),\n nn.Linear(embedding_dim, policy_hidden_size, device=self.device),\n nn.LeakyReLU(0.2, inplace=True),\n )\n # self.policy_params.append({'params': self.policy_fcs.parameters()})\n self.policy_mean = nn.Linear(policy_hidden_size, action_dim, device=self.device)\n self.policy_params.append({'params': self.policy_mean.parameters()}) \n \n # self.policy_fc1 = nn.Linear(embedding_dim, policy_hidden_size, device=self.device)\n # self.policy_fc1.weight.data.uniform_(-init_w, init_w)\n # self.policy_fc1.bias.data.fill_(0)\n # self.policy_params.append({'params': self.policy_fc1.parameters()}) \n # self.policy_fc2 = nn.Linear(policy_hidden_size, action_dim, device=self.device)\n # self.policy_fc2.weight.data.uniform_(-init_w, init_w)\n # self.policy_fc2.bias.data.fill_(0)\n # self.policy_params.append({'params': self.policy_fc2.parameters()}) \n\n self.policy_log_std = None\n self.policy_std = policy_std\n \n if policy_std is None:\n self.policy_fc_log_std = nn.Linear(policy_hidden_size, action_dim, device=self.device)\n # self.policy_fc_log_std.weight.data.uniform_(-init_w, init_w)\n # self.policy_fc_log_std.bias.data.uniform_(-init_w, init_w)\n self.policy_params.append({'params': self.policy_fc_log_std.parameters()})\n else:\n self.policy_log_std = np.log(policy_std)\n assert LOG_SIG_MIN <= self.policy_log_std <= LOG_SIG_MAX\n\n def forward(self, obs):\n # h = obs\n\n # h = self.hidden_activation(self.embed_fc1(h))\n # h = self.embed_fc2(h)\n\n # h = self.hidden_activation(self.policy_fc1(h))\n # policy_mean = self.policy_fc2(h)\n\n h = self.embed_fcs(obs)\n h = self.policy_fcs(h)\n policy_mean = self.policy_mean(h)\n\n if self.policy_std is None:\n policy_log_std = self.policy_fc_log_std(h)\n policy_log_std = torch.clamp(policy_log_std, LOG_SIG_MIN, LOG_SIG_MAX)\n policy_std = torch.exp(policy_log_std)\n else:\n policy_std = torch.from_numpy(np.array([self.policy_std, ])).float().to(ptu.device)\n\n return TanhNormal(policy_mean, policy_std)\n\n def forward_embedding(self, obs):\n # h = obs\n \n # h = self.hidden_activation(self.embed_fc1(h))\n # h = self.embed_fc2(h)\n h = self.embed_fcs(obs)\n\n return h\n\n def forward_policy_from_embedding(self, h):\n # h = self.hidden_activation(h)\n # h = self.hidden_activation(self.policy_fc1(h))\n h = self.policy_fcs(h)\n policy_mean = self.policy_mean(h)\n\n if self.policy_std is None:\n policy_log_std = self.policy_fc_log_std(h)\n policy_log_std = torch.clamp(policy_log_std, LOG_SIG_MIN, LOG_SIG_MAX)\n policy_std = torch.exp(policy_log_std)\n else:\n policy_std = torch.from_numpy(np.array([self.policy_std, ])).float().to(ptu.device)\n\n return TanhNormal(policy_mean, policy_std)\n\n def logprob(self, action, mean, std):\n tanh_normal = TanhNormal(mean, std)\n log_prob = tanh_normal.log_prob(\n action,\n )\n log_prob = log_prob.sum(dim=1, keepdim=True)\n return log_prob\n\n def log_prob(self, obs, action):\n tanh_normal = self.forward(obs)\n log_prob = tanh_normal.log_prob(\n action,\n )\n # log_prob = log_prob.sum(dim=1, keepdim=True)\n return log_prob\n\n def log_prob_policy_from_embedding(self, h, action):\n tanh_normal = self.forward_policy_from_embedding(h)\n log_prob = tanh_normal.log_prob(\n action,\n )\n # log_prob = log_prob.sum(dim=1, keepdim=True)\n return log_prob\n\n def predict_action_from_embedding(self, h):\n tanh_normal = self.forward_policy_from_embedding(h)\n pred_action = tanh_normal.mean \n # log_prob = log_prob.sum(dim=1, keepdim=True)\n return pred_action" }, { "identifier": "TanhGaussianRAPPolicy", "path": "core/policy.py", "snippet": "class TanhGaussianRAPPolicy(TorchStochasticPolicy):\n \"\"\"\n Reference : \n \n Usage:\n\n ```\n policy = TanhGaussianPolicy(...)\n \"\"\"\n\n def __init__(\n self,\n obs_dim,\n stack_size,\n action_dim,\n embedding_dim,\n embedding_hidden_size,\n policy_hidden_size,\n residual_hidden_size,\n policy_std=None,\n residual_std=0.1,\n device='cpu',\n hidden_activation=F.leaky_relu, \n layer_norm=False,\n **kwargs\n ):\n if device =='cuda':\n ptu.set_gpu_mode(True)\n self.device = device\n \n super(TanhGaussianRAPPolicy, self).__init__()\n \n self.input_size = obs_dim\n self.stack_size = stack_size\n self.output_size = action_dim\n self.hidden_activation = hidden_activation\n self.layer_norm = layer_norm\n\n self.embedding_params = []\n self.residual_params = []\n self.policy_params = []\n\n self.history_embed_fcs = []\n self.single_embed_fcs = []\n # self.embed_layer_norms = []\n\n self.policy_fcs = []\n self.residual_fcs = []\n \n self.device = device\n in_size = self.input_size\n\n self.history_embed_fcs = nn.Sequential(\n nn.Linear(self.input_size * self.stack_size, embedding_hidden_size, bias=False, device=self.device),\n # nn.BatchNorm1d(embedding_hidden_size),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Linear(embedding_hidden_size, embedding_dim, device=self.device)\n )\n self.history_embedding_params = self.history_embed_fcs.parameters()\n \n self.single_embed_fcs = nn.Sequential(\n nn.Linear(self.input_size, embedding_hidden_size, bias=False, device=self.device),\n # nn.BatchNorm1d(embedding_hidden_size),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Linear(embedding_hidden_size, embedding_dim, device=self.device)\n )\n self.single_embedding_params = self.single_embed_fcs.parameters()\n\n self.policy_fcs = nn.Sequential(\n nn.LeakyReLU(0.2, inplace=False),\n nn.Linear(embedding_dim*2, policy_hidden_size, device=self.device),\n nn.LeakyReLU(0.2, inplace=True),\n )\n self.policy_params.append({'params': self.policy_fcs.parameters()})\n self.policy_mean = nn.Linear(policy_hidden_size, action_dim, device=self.device)\n self.policy_params.append({'params': self.policy_mean.parameters()}) \n\n self.policy_log_std = None\n self.policy_std = policy_std\n \n if policy_std is None:\n self.policy_fc_log_std = nn.Linear(policy_hidden_size, action_dim, device=self.device)\n # self.policy_fc_log_std.weight.data.uniform_(-init_w, init_w)\n # self.policy_fc_log_std.bias.data.uniform_(-init_w, init_w)\n self.policy_params.append({'params': self.policy_fc_log_std.parameters()})\n else:\n self.policy_log_std = np.log(policy_std)\n assert LOG_SIG_MIN <= self.policy_log_std <= LOG_SIG_MAX\n\n self.residual_fcs = nn.Sequential(\n # nn.LeakyReLU(0.2, inplace=False),\n nn.Linear(embedding_dim, residual_hidden_size, device=self.device),\n nn.LeakyReLU(0.2, inplace=True),\n )\n self.residual_params.append({'params': self.residual_fcs.parameters()})\n self.residual_mean = nn.Linear(residual_hidden_size, action_dim, device=self.device) \n self.residual_params.append({'params': self.residual_mean.parameters()})\n\n def forward(self, obs):\n if len(obs.shape) < 2:\n obs = obs[None]\n \n obs_total = obs\n obs_current = obs[:, -self.input_size:]\n\n m = self.history_embed_fcs(obs_total)\n h = self.single_embed_fcs(obs_current) \n \n policy_input = torch.cat([m.detach(), h], dim=-1)\n \n policy_input = self.policy_fcs(policy_input)\n policy_mean = self.policy_mean(policy_input)\n\n if self.policy_std is None:\n policy_log_std = self.policy_fc_log_std(policy_input)\n policy_log_std = torch.clamp(policy_log_std, LOG_SIG_MIN, LOG_SIG_MAX)\n policy_std = torch.exp(policy_log_std)\n else:\n policy_std = torch.from_numpy(np.array([self.policy_std, ])).float().to(ptu.device)\n\n policy_dist = TanhNormal(policy_mean, policy_std) \n \n return policy_dist #, residual_dist\n\n def forward_embedding(self, obs):\n obs_total = obs\n obs_current = obs[:, -self.input_size:]\n\n m = self.history_embed_fcs(obs_total)\n h = self.single_embed_fcs(obs_current)\n\n return m, h\n\n def forward_residual_from_m(self, m):\n residual_m = self.residual_fcs(m)\n residual_mean = self.residual_mean(residual_m) \n \n return residual_mean\n\n def forward_policy_from_embedding(self, m, h):\n policy_input = torch.cat([m.detach(), h], dim=-1)\n \n policy_input = self.policy_fcs(policy_input)\n policy_mean = self.policy_mean(policy_input)\n\n if self.policy_std is None:\n policy_log_std = self.policy_fc_log_std(policy_input)\n policy_log_std = torch.clamp(policy_log_std, LOG_SIG_MIN, LOG_SIG_MAX)\n policy_std = torch.exp(policy_log_std)\n else:\n policy_std = torch.from_numpy(np.array([self.policy_std, ])).float().to(ptu.device)\n\n return TanhNormal(policy_mean, policy_std)\n\n def logprob(self, action, mean, std):\n tanh_normal = TanhNormal(mean, std)\n log_prob = tanh_normal.log_prob(action)\n log_prob = log_prob.sum(dim=1, keepdim=True)\n return log_prob\n \n def log_prob(self, obs, action):\n tanh_normal = self.forward(obs)\n log_prob = tanh_normal.log_prob(action) \n return log_prob\n \n def log_prob_policy_from_m_h(self, m, h, action): \n tanh_normal = self.forward_policy_from_embedding(m, h)\n log_prob = tanh_normal.log_prob(action)\n return log_prob\n\n def predict_action_from_m_h(self, m, h):\n tanh_normal = self.forward_policy_from_embedding(m, h)\n pred_action = tanh_normal.mean \n return pred_action" }, { "identifier": "EnvReplayBuffer", "path": "core/replay_buffer.py", "snippet": "class EnvReplayBuffer(SimpleReplayBuffer):\n def __init__(\n self,\n max_replay_buffer_size,\n env,\n stack_size=1,\n action_history_len=0,\n env_info_sizes=None,\n train_with_action_history=False\n ):\n \"\"\"\n :param max_replay_buffer_size:\n :param env:\n \"\"\"\n self.env = env\n self._ob_space = env.observation_space #.shape[0] * stack_size\n self._action_space = env.action_space\n\n if train_with_action_history:\n obs_dim = get_dim(self._ob_space) * stack_size + get_dim(self._action_space) * max(stack_size - 1, 1)\n else:\n obs_dim = get_dim(self._ob_space) * stack_size\n\n act_dim = get_dim(self._action_space) * (action_history_len)\n\n if env_info_sizes is None:\n if hasattr(env, 'info_sizes'):\n env_info_sizes = env.info_sizes\n else:\n env_info_sizes = dict()\n\n super().__init__(\n max_replay_buffer_size=max_replay_buffer_size,\n observation_dim=obs_dim,\n action_dim=act_dim,\n env_info_sizes=env_info_sizes\n )\n\n self.obs_mean = None\n self.obs_std = None\n\n self.act_mean = None\n self.act_std = None\n\n # def add_sample(self, observation, action, prev_action, reward, terminal,\n # next_observation, **kwargs):\n # if isinstance(self._action_space, Discrete):\n # new_action = np.zeros(self._action_dim)\n # new_action[action] = 1\n # else:\n # new_action = action\n\n # return super().add_sample(\n # observation=observation,\n # action=new_action,\n # prev_action=prev_action,\n # reward=reward,\n # next_observation=next_observation,\n # terminal=terminal,\n # # **kwargs\n # )\n\n def calculate_statistics(self):\n self.obs_mean = np.mean(self._observations[:self._top], axis=0, keepdims=True)\n self.obs_std = np.std(self._observations[:self._top], axis=0, keepdims=True)\n\n self.act_mean = np.mean(self._actions[:self._top], axis=0, keepdims=True)\n self.act_std = np.std(self._actions[:self._top], axis=0, keepdims=True)\n\n return self.obs_mean, self.obs_std, self.act_mean, self.act_std\n\n def set_statistics(self, obs_mean, obs_std, act_mean, act_std):\n self.obs_mean, self.obs_std, self.act_mean, self.act_std = obs_mean, obs_std, act_mean, act_std\n \n def get_statistics(self):\n return self.obs_mean, self.obs_std, self.act_mean, self.act_std\n\n def random_batch(self, batch_size, standardize=False):\n indices = np.random.choice(self._size, size=batch_size, replace=self._replace or self._size < batch_size)\n if not self._replace and self._size < batch_size:\n warnings.warn('Replace was set to false, but is temporarily set to true because batch size is larger than current size of replay.')\n\n if standardize and self.obs_mean is not None:\n obss = (self._observations[indices] - self.obs_mean) / self.obs_std\n # actions = (self._actions[indices] - self.act_mean) / self.act_std\n next_obss = (self._next_obs[indices] - self.obs_mean) / self.obs_std\n else:\n obss = self._observations[indices] \n # actions = self._actions[indices] \n next_obss = self._next_obs[indices]\n\n actions = self._actions[indices]\n \n batch = dict(\n observations=obss,\n actions=actions,\n # prev_actions=self._prev_actions[indices],\n rewards=self._rewards[indices],\n terminals=self._terminals[indices],\n next_observations=next_obss,\n )\n for key in self._env_info_keys:\n assert key not in batch.keys()\n batch[key] = self._env_infos[key][indices]\n\n return batch\n \n def get_batch(self, batch_size, standardize=False):\n datasize = min(batch_size, self._top) \n indices = np.arange(datasize)\n # if not self._replace and self._size < batch_size:\n # warnings.warn('Replace was set to false, but is temporarily set to true because batch size is larger than current size of replay.')\n\n if standardize and self.obs_mean is not None:\n obss = (self._observations[indices] - self.obs_mean) / self.obs_std\n # actions = (self._actions[indices] - self.act_mean) / self.act_std\n next_obss = (self._next_obs[indices] - self.obs_mean) / self.obs_std\n else:\n obss = self._observations[indices] \n # actions = self._actions[indices] \n next_obss = self._next_obs[indices]\n\n actions = self._actions[indices]\n \n batch = dict(\n observations=obss,\n actions=actions,\n # prev_actions=self._prev_actions[indices],\n rewards=self._rewards[indices],\n terminals=self._terminals[indices],\n next_observations=next_obss,\n )\n for key in self._env_info_keys:\n assert key not in batch.keys()\n batch[key] = self._env_infos[key][indices]\n\n return batch\n\n def add_sample(self, observation, action, reward, terminal,\n next_observation, **kwargs):\n if isinstance(self._action_space, Discrete):\n new_action = np.zeros(self._action_dim)\n new_action[action] = 1\n else:\n new_action = action\n\n return super().add_sample(\n observation=observation,\n action=new_action,\n reward=reward,\n next_observation=next_observation,\n terminal=terminal,\n # **kwargs\n )" }, { "identifier": "preprocess_dataset_with_prev_actions", "path": "core/preprocess.py", "snippet": "def preprocess_dataset_with_prev_actions(mdpfile, envtype, stacksize=1, partially_observable=False, action_history_len=2):\n \n indx = list(np.arange(20))\n # Indices of position information observations\n if partially_observable:\n envtype_to_idx = {\n 'hopper': indx[:5], \n 'ant': indx[:13], \n 'walker2d': indx[:8], \n 'halfcheetah': indx[:4] + indx[8:13]\n }\n obs_idx = envtype_to_idx[envtype]\n observations = np.array(mdpfile['observations'])[:, obs_idx]\n next_observations = np.array(mdpfile['next_observations'])[:, obs_idx]\n else:\n observations = np.array(mdpfile['observations'])\n next_observations = np.array(mdpfile['next_observations'])\n \n terminals = np.array(mdpfile['terminals'])\n timeouts = np.array(mdpfile['timeouts'])\n rewards = np.array(mdpfile['rewards'])\n actions = np.array(mdpfile['actions'])\n\n obs_dim = observations.shape[-1]\n action_dim = actions.shape[-1]\n\n n_data = observations.shape[0]\n new_observations_list = []\n new_next_observations_list = []\n prev_action_list = []\n action_history_list = []\n \n idx_from_initial_state = 0\n num_trajs = 0\n\n for i in range(n_data):\n if idx_from_initial_state == 0:\n prev_action = np.zeros(action_dim)\n else:\n prev_action = actions[i-1]\n prev_action_list.append(prev_action)\n\n if idx_from_initial_state < stacksize:\n if idx_from_initial_state == 0:\n initial_obs = observations[i]\n \n new_observation = np.zeros(obs_dim * stacksize)\n new_observation_ = np.concatenate(observations[i-idx_from_initial_state: i+1])\n new_observation[-(idx_from_initial_state+1) * obs_dim:] = new_observation_\n \n new_next_observation = np.zeros(obs_dim * stacksize)\n new_next_observation_ = np.concatenate(next_observations[i-idx_from_initial_state: i+1])\n new_next_observation[-(idx_from_initial_state+1) * obs_dim:] = new_next_observation_\n \n if idx_from_initial_state + 1 != stacksize:\n new_next_observation[-(idx_from_initial_state+2) * obs_dim:-(idx_from_initial_state+1) * obs_dim] \\\n = initial_obs\n \n else:\n new_observation = np.concatenate(observations[i+1-stacksize:i+1])\n new_next_observation = np.concatenate(next_observations[i+1-stacksize:i+1])\n\n if idx_from_initial_state < action_history_len:\n action_history = np.zeros(action_dim * action_history_len)\n action_history_ = np.concatenate(actions[i-idx_from_initial_state: i+1])\n action_history[-(idx_from_initial_state+1) * action_dim:] = action_history_\n \n else:\n action_history = np.concatenate(actions[i+1-action_history_len:i+1])\n\n\n new_observations_list.append(new_observation)\n new_next_observations_list.append(new_next_observation)\n action_history_list.append(action_history)\n\n idx_from_initial_state += 1\n if terminals[i] or timeouts[i]:\n idx_from_initial_state = 0\n num_trajs += 1 \n\n new_observations = np.array(new_observations_list)\n new_next_observations = np.array(new_next_observations_list)\n new_actions = np.array(action_history_list)\n\n new_paths = {\n 'observations': new_observations,\n 'next_observations': new_next_observations,\n 'rewards': rewards,\n 'actions': new_actions,\n 'terminals': terminals,\n 'timeouts': timeouts \n }\n \n return new_paths" }, { "identifier": "data_select_num_transitions", "path": "core/preprocess.py", "snippet": "def data_select_num_transitions(path, num_transitions=1000, start_idx=0, random=False):\n new_path = {}\n \n if random:\n num_full_trajs = len(path['observations'])\n choice_idx = np.random.choice(num_full_trajs, num_transitions)\n \n else:\n choice_idx = np.arange(start_idx, start_idx + num_transitions)\n \n for key in path.keys():\n new_path[key] = np.array(path[key])[choice_idx]\n \n return new_path" }, { "identifier": "NormalizedBoxEnv", "path": "rlkit/envs/wrappers.py", "snippet": "class NormalizedBoxEnv(ProxyEnv):\n \"\"\"\n Normalize action to in [-1, 1].\n\n Optionally normalize observations and scale reward.\n \"\"\"\n\n def __init__(\n self,\n env,\n reward_scale=1.,\n obs_mean=None,\n obs_std=None,\n ):\n ProxyEnv.__init__(self, env)\n self._should_normalize = not (obs_mean is None and obs_std is None)\n if self._should_normalize:\n if obs_mean is None:\n obs_mean = np.zeros_like(env.observation_space.low)\n else:\n obs_mean = np.array(obs_mean)\n if obs_std is None:\n obs_std = np.ones_like(env.observation_space.low)\n else:\n obs_std = np.array(obs_std)\n self._reward_scale = reward_scale\n self._obs_mean = obs_mean\n self._obs_std = obs_std\n ub = np.ones(self._wrapped_env.action_space.shape)\n self.action_space = Box(-1 * ub, ub)\n\n def estimate_obs_stats(self, obs_batch, override_values=False):\n if self._obs_mean is not None and not override_values:\n raise Exception(\"Observation mean and std already set. To \"\n \"override, set override_values to True.\")\n self._obs_mean = np.mean(obs_batch, axis=0)\n self._obs_std = np.std(obs_batch, axis=0)\n\n def _apply_normalize_obs(self, obs):\n return (obs - self._obs_mean) / (self._obs_std + 1e-8)\n\n def step(self, action):\n lb = self._wrapped_env.action_space.low\n ub = self._wrapped_env.action_space.high\n scaled_action = lb + (action + 1.) * 0.5 * (ub - lb)\n scaled_action = np.clip(scaled_action, lb, ub)\n\n wrapped_step = self._wrapped_env.step(scaled_action)\n next_obs, reward, done, info = wrapped_step\n if self._should_normalize:\n next_obs = self._apply_normalize_obs(next_obs)\n return next_obs, reward * self._reward_scale, done, info\n\n def __str__(self):\n return \"Normalized: %s\" % self._wrapped_env" } ]
import os import wandb import envs import d4rl import gym import torch from imitation.bc import BC from imitation.rap import RAP from imitation.fca import FCA from imitation.mine import MINE_BC from imitation.palr import PALR from argparse import ArgumentParser from itertools import product from core.policy import TanhGaussianPolicyWithEmbedding, TanhGaussianRAPPolicy from core.replay_buffer import EnvReplayBuffer from core.preprocess import preprocess_dataset_with_prev_actions, data_select_num_transitions from rlkit.envs.wrappers import NormalizedBoxEnv
20,850
trainer.train(total_iteration = configs['total_iteration'], eval_freq = configs['eval_freq'], batch_size = configs['batch_size'], num_valid = configs['valid_data_num']) elif 'FCA' in configs['algorithm']: embedding_dim = configs['layer_sizes'][1] policy = TanhGaussianPolicyWithEmbedding( obs_dim=obs_dim * stacksize, action_dim=action_dim, embedding_hidden_size=configs['layer_sizes'][0], embedding_dim=embedding_dim, policy_hidden_size=configs['layer_sizes'][2], device=device, ) best_policy = TanhGaussianPolicyWithEmbedding( obs_dim=obs_dim * stacksize, action_dim=action_dim, embedding_hidden_size=configs['layer_sizes'][0], embedding_dim=embedding_dim, policy_hidden_size=configs['layer_sizes'][2], device=device, ) trainer = FCA( policy = policy, best_policy = best_policy, env = env, replay_buffer = replay_buffer, replay_buffer_valid = replay_buffer_valid, seed = configs['seed'], device = device, lr = configs['lr'], wandb = wandb, save_policy_path = configs['save_policy_path'], obs_dim = obs_dim, action_dim = action_dim, stacksize = stacksize, standardize=configs['standardize'], embedding_dim = embedding_dim, entropy_hidden_size = configs['additional_network_size'], entropy_lr = configs['inner_lr'], reg_coef = configs['reg_coef'], info_bottleneck_loss_coef = configs['info_bottleneck_loss_coef'] ) trainer.train(total_iteration = configs['total_iteration'], eval_freq = configs['eval_freq'], batch_size = configs['batch_size'], num_valid = configs['valid_data_num'], inner_steps = configs['inner_steps'],) elif 'MINE' in configs['algorithm']: embedding_dim = configs['layer_sizes'][1] policy = TanhGaussianPolicyWithEmbedding( obs_dim=obs_dim * stacksize, action_dim=action_dim, embedding_hidden_size=configs['layer_sizes'][0], embedding_dim=embedding_dim, policy_hidden_size=configs['layer_sizes'][2], device=device, ) best_policy = TanhGaussianPolicyWithEmbedding( obs_dim=obs_dim * stacksize, action_dim=action_dim, embedding_hidden_size=configs['layer_sizes'][0], embedding_dim=embedding_dim, policy_hidden_size=configs['layer_sizes'][2], device=device, ) trainer = MINE_BC( policy = policy, best_policy = best_policy, env = env, replay_buffer = replay_buffer, replay_buffer_valid = replay_buffer_valid, seed = configs['seed'], device = device, lr = configs['lr'], wandb = wandb, save_policy_path = configs['save_policy_path'], obs_dim = obs_dim, action_dim = action_dim, stacksize = stacksize, embedding_dim = embedding_dim, standardize=configs['standardize'], mine_lr = configs['inner_lr'], reg_coef = configs['reg_coef'], info_bottleneck_loss_coef = configs['info_bottleneck_loss_coef'] ) trainer.train(total_iteration = configs['total_iteration'], eval_freq = configs['eval_freq'], inner_steps = configs['inner_steps'], batch_size = configs['batch_size'], num_valid = configs['valid_data_num']) elif 'PALR' in configs['algorithm']: embedding_dim = configs['layer_sizes'][1] policy = TanhGaussianPolicyWithEmbedding( obs_dim=obs_dim * stacksize, action_dim=action_dim, embedding_hidden_size=configs['layer_sizes'][0], embedding_dim=embedding_dim, policy_hidden_size=configs['layer_sizes'][2], device=device, ) best_policy = TanhGaussianPolicyWithEmbedding( obs_dim=obs_dim * stacksize, action_dim=action_dim, embedding_hidden_size=configs['layer_sizes'][0], embedding_dim=embedding_dim, policy_hidden_size=configs['layer_sizes'][2], device=device, )
wandb_dir = '.' os.environ['WANDB_DIR'] = wandb_dir os.environ['D4RL_DATASET_DIR'] = './dataset/' def train(configs): env = NormalizedBoxEnv(gym.make(configs['envname'])) obs_dim = env.observation_space.low.size action_dim = env.action_space.low.size d4rl_env = gym.make(configs['d4rl_env_name']) stacksize = configs['stacksize'] if stacksize == 0: stacksize = 1 device = 'cuda' if torch.cuda.is_available() else 'cpu' envname, envtype = configs['envname'], configs['envtype'] traj_load_path = configs['traj_load_path'] print(f'-- Loading dataset from {traj_load_path}...') dataset = d4rl_env.get_dataset() print(f'-- Done!') print(f'-- Preprocessing dataset... ({envtype}, {stacksize})') path = preprocess_dataset_with_prev_actions(dataset, envtype, stacksize, configs['partially_observable'], action_history_len=2) train_data = data_select_num_transitions(path, configs['train_data_num']) valid_data = data_select_num_transitions(path, configs['valid_data_num'], start_idx=900000) replay_buffer = EnvReplayBuffer( configs['replay_buffer_size'], env, stacksize, action_history_len=2 ) replay_buffer.add_path(train_data) replay_buffer_valid = EnvReplayBuffer( configs['replay_buffer_size'], env, stacksize, action_history_len=2 ) replay_buffer_valid.add_path(valid_data) if configs['standardize']: obs_mean, obs_std, act_mean, act_std = replay_buffer.calculate_statistics() replay_buffer_valid.set_statistics(obs_mean, obs_std, act_mean, act_std) # to use wandb, initialize here, e.g. # wandb.init(project='palr', dir=wandb_dir, config=configs) wandb = None if 'BC' in configs['algorithm']: embedding_dim = configs['layer_sizes'][1] policy = TanhGaussianPolicyWithEmbedding( obs_dim=obs_dim * stacksize, action_dim=action_dim, embedding_hidden_size=configs['layer_sizes'][0], embedding_dim=embedding_dim, policy_hidden_size=configs['layer_sizes'][2], device=device ) best_policy = TanhGaussianPolicyWithEmbedding( obs_dim=obs_dim * stacksize, action_dim=action_dim, embedding_hidden_size=configs['layer_sizes'][0], embedding_dim=embedding_dim, policy_hidden_size=configs['layer_sizes'][2], device=device ) trainer = BC( policy = policy, best_policy = best_policy, env = env, replay_buffer = replay_buffer, replay_buffer_valid = replay_buffer_valid, seed = configs['seed'], device = device, envname = envname, lr = configs['lr'], save_policy_path = configs['save_policy_path'], obs_dim = obs_dim, action_dim = action_dim, stacksize = stacksize, wandb = wandb, standardize=configs['standardize'] ) trainer.train(total_iteration=configs['total_iteration'], eval_freq = configs['eval_freq'], batch_size = configs['batch_size'], num_valid = configs['valid_data_num']) elif 'RAP' in configs['algorithm']: embedding_dim = configs['layer_sizes'][1] policy = TanhGaussianRAPPolicy( obs_dim=obs_dim, stack_size=stacksize, action_dim=action_dim, embedding_hidden_size=configs['layer_sizes'][0], embedding_dim=embedding_dim, policy_hidden_size=configs['layer_sizes'][2], residual_hidden_size=configs['additional_network_size'], device=device, ) best_policy = TanhGaussianRAPPolicy( obs_dim=obs_dim, stack_size=stacksize, action_dim=action_dim, embedding_hidden_size=configs['layer_sizes'][0], embedding_dim=embedding_dim, policy_hidden_size=configs['layer_sizes'][2], residual_hidden_size=configs['additional_network_size'], device=device, ) trainer = RAP( policy = policy, best_policy = best_policy, env = env, replay_buffer = replay_buffer, replay_buffer_valid = replay_buffer_valid, seed = configs['seed'], device = device, lr = configs['lr'], save_policy_path = configs['save_policy_path'], obs_dim = obs_dim, action_dim = action_dim, embedding_dim = embedding_dim, stacksize = stacksize, wandb = wandb, standardize=configs['standardize'] ) trainer.train(total_iteration = configs['total_iteration'], eval_freq = configs['eval_freq'], batch_size = configs['batch_size'], num_valid = configs['valid_data_num']) elif 'FCA' in configs['algorithm']: embedding_dim = configs['layer_sizes'][1] policy = TanhGaussianPolicyWithEmbedding( obs_dim=obs_dim * stacksize, action_dim=action_dim, embedding_hidden_size=configs['layer_sizes'][0], embedding_dim=embedding_dim, policy_hidden_size=configs['layer_sizes'][2], device=device, ) best_policy = TanhGaussianPolicyWithEmbedding( obs_dim=obs_dim * stacksize, action_dim=action_dim, embedding_hidden_size=configs['layer_sizes'][0], embedding_dim=embedding_dim, policy_hidden_size=configs['layer_sizes'][2], device=device, ) trainer = FCA( policy = policy, best_policy = best_policy, env = env, replay_buffer = replay_buffer, replay_buffer_valid = replay_buffer_valid, seed = configs['seed'], device = device, lr = configs['lr'], wandb = wandb, save_policy_path = configs['save_policy_path'], obs_dim = obs_dim, action_dim = action_dim, stacksize = stacksize, standardize=configs['standardize'], embedding_dim = embedding_dim, entropy_hidden_size = configs['additional_network_size'], entropy_lr = configs['inner_lr'], reg_coef = configs['reg_coef'], info_bottleneck_loss_coef = configs['info_bottleneck_loss_coef'] ) trainer.train(total_iteration = configs['total_iteration'], eval_freq = configs['eval_freq'], batch_size = configs['batch_size'], num_valid = configs['valid_data_num'], inner_steps = configs['inner_steps'],) elif 'MINE' in configs['algorithm']: embedding_dim = configs['layer_sizes'][1] policy = TanhGaussianPolicyWithEmbedding( obs_dim=obs_dim * stacksize, action_dim=action_dim, embedding_hidden_size=configs['layer_sizes'][0], embedding_dim=embedding_dim, policy_hidden_size=configs['layer_sizes'][2], device=device, ) best_policy = TanhGaussianPolicyWithEmbedding( obs_dim=obs_dim * stacksize, action_dim=action_dim, embedding_hidden_size=configs['layer_sizes'][0], embedding_dim=embedding_dim, policy_hidden_size=configs['layer_sizes'][2], device=device, ) trainer = MINE_BC( policy = policy, best_policy = best_policy, env = env, replay_buffer = replay_buffer, replay_buffer_valid = replay_buffer_valid, seed = configs['seed'], device = device, lr = configs['lr'], wandb = wandb, save_policy_path = configs['save_policy_path'], obs_dim = obs_dim, action_dim = action_dim, stacksize = stacksize, embedding_dim = embedding_dim, standardize=configs['standardize'], mine_lr = configs['inner_lr'], reg_coef = configs['reg_coef'], info_bottleneck_loss_coef = configs['info_bottleneck_loss_coef'] ) trainer.train(total_iteration = configs['total_iteration'], eval_freq = configs['eval_freq'], inner_steps = configs['inner_steps'], batch_size = configs['batch_size'], num_valid = configs['valid_data_num']) elif 'PALR' in configs['algorithm']: embedding_dim = configs['layer_sizes'][1] policy = TanhGaussianPolicyWithEmbedding( obs_dim=obs_dim * stacksize, action_dim=action_dim, embedding_hidden_size=configs['layer_sizes'][0], embedding_dim=embedding_dim, policy_hidden_size=configs['layer_sizes'][2], device=device, ) best_policy = TanhGaussianPolicyWithEmbedding( obs_dim=obs_dim * stacksize, action_dim=action_dim, embedding_hidden_size=configs['layer_sizes'][0], embedding_dim=embedding_dim, policy_hidden_size=configs['layer_sizes'][2], device=device, )
trainer = PALR(
4
2023-11-06 08:35:34+00:00
24k
tylerlight071/Project-Cipher
main.py
[ { "identifier": "clear_terminal", "path": "components/common_functions.py", "snippet": "def clear_terminal():\n os.system('cls' if os.name == 'nt' else 'clear')" }, { "identifier": "print_slow", "path": "components/common_functions.py", "snippet": "def print_slow(text, delay=0.00): # change to 0.01\n for char in text:\n print(char, end='', flush=True)\n time.sleep(delay)\n print()" }, { "identifier": "shop_help", "path": "components/common_functions.py", "snippet": "def shop_help():\n print_slow(Fore.YELLOW + \"Shop Help:\" + Style.RESET_ALL)\n print_slow(\"\")\n print_slow(\"[buy] - Use the 'buy [upgrade]' command to purchase the upgrade in the shop. \")\n print_slow(\"\")\n print_slow(\"[clear] - Use the 'clear' command to clear the terminal.\")\n print_slow(\"\")\n print_slow(\"[exit] - Use the 'exit' command to return to the main terminal.\")\n print_slow(\"\")" }, { "identifier": "help_user", "path": "components/common_functions.py", "snippet": "def help_user():\n print_slow(Fore.MAGENTA + \"Help:\" + Style.RESET_ALL)\n print_slow(\"\")\n print_slow(\"[connect] - Use the 'connect' command to hack into Enigma Corps network.\")\n print_slow(\"\")\n print_slow(\"[mail] - Use the 'mail' command to view and respond to emails from your client and other characters.\")\n print_slow(\"\")\n print_slow(\"[balance] - Use the 'balance' command to view your current earnings which you can spend on upgrades. \")\n print_slow(\"\")\n print_slow(\"[shop] - Use the 'shop' command to view upgrades available in the shop. \")\n print_slow(\"\")\n print_slow(\"[clear] - Use the 'clear' command to clear the terminal.\")\n print_slow(\"\")\n print_slow(\"[help] - Use the 'help' command if you need assistance at any time.\")\n print_slow(\"\")\n print_slow(\"[exit] - Use the 'exit' command to return to the Main Menu.\")\n print_slow(\"\")" }, { "identifier": "connect_help", "path": "components/common_functions.py", "snippet": "def connect_help():\n print_slow(Fore.MAGENTA + \"Connect Help:\" + Style.RESET_ALL)\n print_slow(\n \"[scan] - Use the 'scan' command to scan the network and search for available systems and vulnerabilities.\")\n print_slow(\"\")\n print_slow(\"[hack] - Use the 'hack [system/vulnerability]' to hack into different systems.\")\n print_slow(\"\")\n print_slow(\"[clear] - Use the 'clear' command to clear the terminal.\")\n print_slow(\"\")\n print_slow(\"[disconnect] - Use the 'disconnect' command to disconnect from the current system or vulnerability.\")\n print_slow(\"\")" }, { "identifier": "mail_help", "path": "components/common_functions.py", "snippet": "def mail_help():\n print_slow(Fore.LIGHTBLUE_EX + \"Mail Help:\" + Style.RESET_ALL)\n print_slow(\"\")\n print_slow(\"[l] - Use the 'l' command to list all emails.\")\n print_slow(\"\")\n print_slow(\"[r] - Use the 'r [subject]' command to read an email with the specified subject.\")\n print_slow(\"\")\n print_slow(\"[clear] - Use the 'clear' command to clear the terminal.\")\n print_slow(\"\")\n print_slow(\"[exit] - Use the 'exit' command to return to the main terminal.\")\n print_slow(\"\")" }, { "identifier": "system_help", "path": "components/common_functions.py", "snippet": "def system_help():\n print_slow(\"\")\n print_slow(\"[mail] - Use the 'mail' command to log into the users emails.\")\n print_slow(\"\")\n print_slow(\"[l] - Use the 'l' command to list files in a users system.\")\n print_slow(\"\")\n print_slow(\"[clear] - Use the 'clear' command to clear the terminal.\")\n print_slow(\"\")\n print_slow(\"[r] - Use the 'r [file]' command to read files in a users system\")\n print_slow(\"\")" }, { "identifier": "intro_call", "path": "conversations/calls.py", "snippet": "def intro_call():\n clear_terminal()\n\n # Anonymous Sender (Anonymous)\n print_slow(sender_art)\n print_slow(\"\")\n print_box(\"Anonymous\")\n print_slow(\"\")\n print_slow(\n Fore.YELLOW + \"Welcome, Cipher. Operation Enigma is our covert mission against Enigma Corp, a powerful and secretive entity.\")\n print_slow(\n \"Your skills and secrecy have brought you to our attention. Your mission is to dig through their systems and servers looking for valuable data.\" + Style.RESET_ALL)\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Cipher Response\n print_slow(cipher_art)\n print_slow(\"\")\n print_box(\"Cipher\")\n print_slow(\"\")\n print_slow(Fore.BLUE + \"Got it, Anonymous. Exposing secrets and bringing justice. I'm in.\")\n print_slow(\"What's my first move? Talk to me about this 'EnigmaLink'.\" + Style.RESET_ALL)\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Anonymous Sender (Anonymous)\n print_slow(sender_art)\n print_slow(\"\")\n print_box(\"Anonymous\")\n print_slow(\"\")\n print_slow(\n \"Excellent, Cipher. EnigmaLink is a specialized tool available on the Hacker's Market. It contains a hidden backdoor, allowing access to Enigma Corps servers.\")\n print_slow(\n \"Your task is to acquire EnigmaLink and initiate your infiltration. Use the 'connect' command to navigate the network and gather crucial intelligence.\")\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Cipher Response\n print_slow(cipher_art)\n print_slow(\"\")\n print_box(\"Cipher\")\n print_slow(\"\")\n print_slow(\n Fore.BLUE + \"EnigmaLink, got it. I'll secure it and initiate the infiltration. What about this employee, Amy?\")\n print_slow(\"You mentioned her password is 'sexinthecity.' What's my objective with her?\" + Style.RESET_ALL)\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Anonymous Sender (Anonymous)\n print_slow(sender_art)\n print_slow(\"\")\n print_box(\"Anonymous\")\n print_slow(\"\")\n print_slow(\n \"Good question, Cipher. Amy is a key target. Use her password to access her computer and gather any pertinent information.\")\n print_slow(\n \"This data is vital to our cause. Be thorough and meticulous in your investigation. The success of our operation depends on it.\")\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Cipher Response\n print_slow(cipher_art)\n print_slow(\"\")\n print_box(\"Cipher\")\n print_slow(\"\")\n print_slow(Fore.BLUE + \"Understood, Anonymous. I'll focus on Amy, gather intel, and proceed with precision.\")\n print_slow(\"Consider it done. Anything else I should know before I dive in?\" + Style.RESET_ALL)\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Anonymous Sender (Anonymous)\n print_slow(sender_art)\n print_slow(\"\")\n print_box(\"Anonymous\")\n print_slow(\"\")\n print_slow(\n \"One last thing, Cipher. All collected data is highly confidential. This contract is binding, and your success is paramount.\")\n print_slow(\"Execute with diligence, and may the odds be in your favor. Good luck, Cipher.\")\n print_slow(Fore.RED + \"Line Disconnected...\" + Style.RESET_ALL)\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()" }, { "identifier": "first_call", "path": "conversations/calls.py", "snippet": "def first_call():\n clear_terminal()\n print_slow(sender_art)\n print_slow(\"\")\n print_slow(\"\")\n print_box(\"Anonymous\")\n print_slow(\"\")\n print_slow(Fore.YELLOW + \"That's a good start, but we already have that information.\")\n print_slow(\"Regardless, I've transferred £20 into the account for your troubles.\")\n print_slow(\"Keep digging Cipher!\" + Style.RESET_ALL)\n print_slow(Fore.RED + \"Line Disconnected...\" + Style.RESET_ALL)\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()" }, { "identifier": "second_call", "path": "conversations/calls.py", "snippet": "def second_call():\n clear_terminal()\n print_slow(sender_art)\n print_slow(\"\")\n print_slow(\"\")\n print_box(\"Anonymous\")\n print_slow(\"\")\n print_slow(\n Fore.YELLOW + \"Hey Cipher, you nailed it! 'Billy' just spilled the beans about wanting to climb the corporate ladder into management.\")\n print_slow(\n \"This is gold for us. We can guide 'Billy' toward training and workshops that align with our interests, nudging things in our favor.\")\n print_slow(\n \"Picture it – we're pulling the strings, helping 'Billy' grow, and steering the ship where we want it to go.\")\n print_slow(\"Keep the ball rolling, Cipher!\" + Style.RESET_ALL)\n print_slow(Fore.RED + \"Line Disconnected...\" + Style.RESET_ALL)\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()" }, { "identifier": "third_call", "path": "conversations/calls.py", "snippet": "def third_call():\n clear_terminal()\n\n # Anonymous Sender\n print_slow(sender_art)\n print_slow(\"\")\n print_box(\"Anonymous\")\n print_slow(\"\"\n \"\")\n print_slow(\n Fore.YELLOW + \"Cipher, we've stumbled upon a perplexing development regarding Enigma's interest in a mysterious 'compound.'\")\n print_slow(\n \"I'm cross-referencing our existing intel to unveil more details. Stay vigilant and be prepared for the unknown.\" + Style.RESET_ALL)\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Cipher Response\n print_slow(cipher_art)\n print_slow(\"\")\n print_box(\"Cipher\")\n print_slow(\"\")\n print_slow(\n Fore.BLUE + \"A compound, huh? Any hints on whether we're talking metal, chemicals, or something else entirely?\")\n print_slow(\"This feels like navigating in the dark. What exactly am I dealing with?\" + Style.RESET_ALL)\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Anonymous Sender Response\n print_slow(sender_art)\n print_slow(\"\")\n print_box(\"Anonymous\")\n print_slow(\"\")\n print_slow(Fore.YELLOW +\n \"Cipher, we're in the dark too. Initial reports are unclear—could be metal, chemical, or something beyond our comprehension.\")\n print_slow(\n \"Your mission is to identify the nature of this compound. Exercise extreme caution; this goes deeper than we anticipated.\" + Style.RESET_ALL)\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Cipher Inquiry\n print_slow(cipher_art)\n print_slow(\"\")\n print_box(\"Cipher\")\n print_slow(\"\")\n print_slow(Fore.BLUE + \"So, we're playing 'guess the compound.' Any leads, any connections I should explore?\")\n print_slow(\"This is starting to sound like one of those high-stakes puzzles.\" + Style.RESET_ALL)\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Anonymous Sender Clarification\n print_slow(sender_art)\n print_slow(\"\")\n print_box(\"Anonymous\")\n print_slow(\"\")\n print_slow(Fore.YELLOW +\n \"I wish I had more details, Cipher. This is uncharted territory for us. Investigate discreetly, and trust no one.\")\n print_slow(\n \"I'll attempt to gather more intel. Stay on the line, and keep me updated on any findings.\" + Style.RESET_ALL)\n print_slow(\"\")\n print_slow(Fore.RED + \"Line Disconnected...\" + Style.RESET_ALL)\n input(\"Press [Enter] to continue: \")\n clear_terminal()" }, { "identifier": "fourth_call", "path": "conversations/calls.py", "snippet": "def fourth_call():\n clear_terminal()\n\n # Anonymous Sender\n print_slow(sender_art)\n print_slow(\"\")\n print_box(\"Anonymous\")\n print_slow(\"\")\n print_slow(\n Fore.YELLOW + \"Cipher, we've got our hands on an intriguing document – an Employee Performance Review for 'Billy Constantine'.\")\n print_slow(\n \"This could be a goldmine of information. Let's dig in and see if there's anything we can leverage to our advantage.\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Cipher Response\n print_slow(cipher_art)\n print_slow(\"\")\n print_box(\"Cipher\")\n print_slow(\"\")\n print_slow(\n Fore.BLUE + \"An Employee Performance Review? Interesting choice. What's the scoop on 'Billy Constantine'?\")\n print_slow(\"Give me the details, and we'll figure out our next move.\" + Style.RESET_ALL)\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Anonymous Sender Briefing\n print_slow(sender_art)\n print_slow(\"\")\n print_box(\"Anonymous\")\n print_slow(\"\")\n print_slow(\n \"Cipher, 'Billy Constantine' is making waves. The review highlights exceptional performance as a sales representative.\")\n print_slow(\n \"He's exceeding sales targets, mentoring new team members, and earning a solid 4.5/5 rating. A rising star, it seems.\")\n print_slow(\"We might use this to our advantage. Let's explore how we can align his ambitions with our agenda.\")\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Cipher Strategy\n print_slow(cipher_art)\n print_slow(\"\")\n print_box(\"Cipher\")\n print_slow(\"\")\n print_slow(\n Fore.BLUE + \"A high-performing sales rep, huh? We could steer 'Billy' towards projects that align with our goals.\")\n print_slow(\"Let's use this performance review to our advantage. Maybe mentorship programs, leadership initiatives?\")\n print_slow(\"I'm ready to play this card strategically. What's the next move?\" + Style.RESET_ALL)\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Anonymous Sender Next Steps\n print_slow(sender_art)\n print_slow(\"\")\n print_box(\"Anonymous\")\n print_slow(\"\")\n print_slow(\n \"Great thinking, Cipher. Let's work on a plan to subtly guide 'Billy' toward initiatives that benefit us.\")\n print_slow(\"We'll need to dig deeper into 'Billy's' aspirations and weave our influence seamlessly.\")\n print_slow(\"Stay vigilant, Cipher. This could be a game-changer.\")\n print_slow(\"\")\n print_slow(Fore.RED + \"Line Disconnected...\" + Style.RESET_ALL)\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()" }, { "identifier": "fifth_call", "path": "conversations/calls.py", "snippet": "def fifth_call():\n clear_terminal()\n\n # Anonymous Sender\n print_slow(sender_art)\n print_slow(\"\")\n print_box(\"Anonymous\")\n print_slow(\"\")\n print_slow(\n Fore.YELLOW + \"Cipher, we've intercepted some Meeting Minutes dated 24/06/2025. It's related to 'Project X' and involves key players.\")\n print_slow(\n \"This could be our chance to uncover more about Enigma's activities. Let's dive into the details and see what we can extract.\" + Style.RESET_ALL)\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Cipher Response\n print_slow(cipher_art)\n print_slow(\"\")\n print_box(\"Cipher\")\n print_slow(\"\")\n print_slow(\n Fore.BLUE + \"Meeting Minutes, huh? 'Project X' sounds intriguing. Who were the players involved, and what's the agenda?\")\n print_slow(\"I'm ready to dissect this information and uncover any hidden gems.\" + Style.RESET_ALL)\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Anonymous Sender Briefing\n print_slow(sender_art)\n print_slow(\"\")\n print_box(\"Anonymous\")\n print_slow(\"\")\n print_slow(\n \"Cipher, the meeting involved key personnel—Amy, Billy, Kyle, and others. 'Project X' is on the agenda, and there's mention of sensitive materials.\")\n print_slow(\n \"This could be a crucial insight into Enigma's plans. Let's analyze the action items and plan our next move.\")\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Cipher Analysis\n print_slow(cipher_art)\n print_slow(\"\")\n print_box(\"Cipher\")\n print_slow(\"\")\n print_slow(Fore.BLUE + \"'Project X,' sensitive materials, and action items. This is a goldmine of information.\")\n print_slow(\n \"Let's focus on dissecting the action items and see if we can connect the dots. What's our strategy, Anonymous?\" + Style.RESET_ALL)\n print_slow(\"\")\n input(\"Press [Enter] to continue: \")\n clear_terminal()\n\n # Anonymous Sender Next Steps\n print_slow(sender_art)\n print_slow(\"\")\n print_box(\"Anonymous\")\n print_slow(\"\")\n print_slow(\n \"Agreed, Cipher. Let's delve into the action items, especially the data compilation and safety protocol training.\")\n print_slow(\"We might uncover more about 'Project X' and gain insights into Enigma's plans.\")\n print_slow(\"Stay sharp, Cipher. This could be a pivotal moment in our mission.\")\n print_slow(\"\")\n print_slow(Fore.RED + \"Line Disconnected...\" + Style.RESET_ALL)\n input(\"Press [Enter] to continue: \")\n clear_terminal()" }, { "identifier": "sixth_call", "path": "conversations/calls.py", "snippet": "def sixth_call():\n print_slow(\"ADD CALL STUFF HERE\")" }, { "identifier": "markus_seen_call", "path": "conversations/calls.py", "snippet": "def markus_seen_call():\n print_slow(\"Something goes here\")" }, { "identifier": "code_shatter_call", "path": "conversations/minigame_calls.py", "snippet": "def code_shatter_call():\n clear_terminal()\n print_slow(sender_art)\n print_slow(\"\")\n print_slow(\"\")\n print_box(\"Anonymous\")\n print_slow(\"\")\n print_slow(Fore.YELLOW + \"I see you have bought CodeShatter!\")\n print_slow(\"This item is a one time use upgrade so once you get the password, it is gone so use wisely!\")\n print_slow(\"But don't threat, if you fail, you get a chance to retry. The item is only used when you get the password, so be sure to write it down!\" + Style.RESET_ALL)\n input(\"Press [Enter] to continue: \")\n clear_terminal()" }, { "identifier": "code_shatter_minigame", "path": "minigames/code_shatter_minigame.py", "snippet": "def code_shatter_minigame():\n # Generate a random 5-digit number\n target = [str(random.randint(1, 9)) for _ in range(5)]\n\n print_slow(\"Welcome to CodeShatter!\")\n print_slow(\"\")\n print_slow(\"Guess the 5-digit number.\")\n print_slow(\"\")\n print_slow(\"The sequence can contain multiple same numbers\")\n print_slow(\"\")\n print_slow(Fore.GREEN + \"Green: Correct digit in correct position.\" + Style.RESET_ALL)\n print_slow(\"\")\n print_slow(Fore.YELLOW + \"Orange: Correct digit in incorrect position.\" + Style.RESET_ALL)\n print_slow(\"\")\n print_slow(Fore.RED + \"Red: Incorrect digit.\" + Style.RESET_ALL)\n print_slow(\"\")\n\n attempts = 0\n while attempts < 7:\n # Get the user's guess\n guess = input(\"Enter your guess: \")\n\n if len(guess) != 5 or not guess.isdigit():\n print_slow(\"Invalid input. Please enter a 5-digit number.\")\n continue\n\n attempts += 1\n\n # Check the guess against the target\n feedback = []\n for i in range(5):\n if guess[i] == target[i]:\n feedback.append(Fore.GREEN + guess[i] + Style.RESET_ALL)\n elif guess[i] in target:\n feedback.append(Fore.YELLOW + guess[i] + Style.RESET_ALL)\n else:\n feedback.append(Fore.RED + guess[i] + Style.RESET_ALL)\n\n print_slow(\"Feedback: \" + \" \".join(feedback))\n\n # Check if the guess is correct\n if guess == \"\".join(target):\n print_slow(Fore.GREEN + \"Access granted.\" + Style.RESET_ALL)\n break\n else:\n print_slow(Fore.RED + \"Access denied. Too many attempts.\" + Style.RESET_ALL)\n time.sleep(1)\n print_slow(\"\")\n print_slow(Fore.RED + \"Rebooting CodeShatter with new proxy...\" + Style.RESET_ALL)\n time.sleep(1)\n clear_terminal()\n code_shatter_minigame()" }, { "identifier": "port_scanning", "path": "minigames/eye_spy_minigame.py", "snippet": "def port_scanning():\n num_ports = 10\n open_ports, closed_ports = generate_ports(num_ports)\n attempts = 5\n correct_guesses = 0\n scan_attempts = 2\n\n print_slow(\"Welcome to the Port Scanning minigame!\")\n print_slow(\"\")\n print_slow(f\"Find the open ports in the range 1-{num_ports}.\")\n print_slow(\"\")\n print_slow(f\"You have {attempts} attempts.\")\n print_slow(\"\")\n\n while scan_attempts > 0:\n print_slow(\"\")\n print_slow(f\"\\nYou have {scan_attempts} scan attempts left.\")\n print_slow(\"\")\n start = int(input(\"Enter the start of the range to scan: \"))\n print_slow(\"\")\n end = int(input(\"Enter the end of the range to scan: \"))\n print_slow(\"\")\n\n num_open_ports_in_range = len(open_ports.intersection(range(start, end + 1)))\n print_slow(\"\")\n print_slow(f\"There are {num_open_ports_in_range} open ports in the range {start}-{end}.\")\n\n scan_attempts -= 1\n\n while attempts > 0 and len(open_ports) > 0:\n port = int(input(\"\\nEnter a port number to guess: \"))\n\n if port in open_ports:\n print_slow(Fore.GREEN + \"Port is open!\" + Style.RESET_ALL)\n open_ports.remove(port)\n correct_guesses += 1\n elif port in closed_ports:\n print_slow(Fore.RED + \"Port is closed.\" + Style.RESET_ALL)\n closed_ports.remove(port)\n else:\n print_slow(\"Invalid port number. Please enter a number between 1 and\", num_ports)\n\n attempts -= 1\n\n if len(open_ports) == 0:\n print_slow(\n Fore.GREEN + \"\\nCongratulations! You have successfully found all the open ports and gained access to the camera.\" + Style.RESET_ALL)\n time.sleep(2)\n clear_terminal()\n else:\n print_slow(\n Fore.RED + f\"\\nHack Failed! You found {correct_guesses} out of {len(open_ports) + correct_guesses} open ports.\" + Style.RESET_ALL)\n time.sleep(1)\n clear_terminal()\n port_scanning()" }, { "identifier": "AmySystem", "path": "systems/level_1/amy/amy_system.py", "snippet": "class AmySystem:\n def __init__(self):\n self.files = [\n {\n \"name\": \"return_to_work_form.txt\",\n \"content\": (\n \"Employee Name: _______________\\n\"\n \"Employee ID: ____________\\n\"\n \"Department: _______________\\n\"\n \"Date of Return: ______\\n\\n\"\n \"I, [Employee Name], certify that I have followed the company's \"\n \"guidelines for returning to work after an absence. \"\n \"I understand that it is my responsibility to adhere to all safety \"\n \"protocols and procedures to ensure the health and well-being of my \"\n \"colleagues and myself.\\n\\n\"\n \"I acknowledge that I have completed any necessary training and have \"\n \"been briefed on any updates to the company's policies and procedures. \"\n \"I am aware that I must report any symptoms or exposure to COVID-19 to \"\n \"my supervisor immediately.\\n\\n\"\n \"I am committed to doing my part to maintain a safe and healthy work \"\n \"environment for everyone. I will continue to follow all guidelines \"\n \"and protocols and will cooperate with any additional measures that \"\n \"may be implemented in the future.\\n\\n\"\n \"Signature: [Employee Signature]\\n\"\n \"Date: [Date]\"\n )\n },\n {\n \"name\": \"employee_handbook.txt\",\n \"content\": (\n \"Welcome to Enigma Corps We are thrilled to have you as part of our \"\n \"team. This employee handbook has been designed to help you understand \"\n \"our company's policies, procedures, and expectations.\\n\\n\"\n \"Our company is committed to fostering a positive and inclusive work \"\n \"environment where all employees feel valued and supported. We believe \"\n \"in treating everyone with respect and dignity and expect all employees \"\n \"to do the same.\\n\\n\"\n \"In this handbook, you will find information on topics such as:\\n\\n\"\n \"- Code of Conduct\\n\"\n \"- Dress Code\\n\"\n \"- Attendance and Punctuality\\n\"\n \"- Time Off and Leave Policies\\n\"\n \"- Performance Evaluations\\n\"\n \"- Health and Safety\\n\"\n \"- Equal Employment Opportunity\\n\"\n \"- Harassment and Discrimination\\n\\n\"\n \"Please take the time to read through this handbook carefully and \"\n \"familiarize yourself with our policies and procedures. If you have any \"\n \"questions or concerns, do not hesitate to reach out to your supervisor \"\n \"or the HR department.\\n\\n\"\n \"We look forward to working with you and hope you have a long and \"\n \"successful career with Enigma Corps!\"\n )\n },\n {\n \"name\": \"benefits_summary.txt\",\n \"content\": (\n \"At Enigma Corps, we believe in taking care of our employees and \"\n \"offer a comprehensive benefits package to support your health, well-being, \"\n \"and financial security. Below is a summary of the benefits available to \"\n \"you as an employee of Enigma Corps.\\n\\n\"\n \"Health Insurance: We offer a choice of medical, dental, and vision \"\n \"plans to meet your needs. Our plans provide coverage for preventive care, \"\n \"hospitalization, prescription drugs, and more.\\n\\n\"\n \"Retirement Savings: We offer a 401(k) plan with a generous company \"\n \"match to help you save for your future. You can choose from a variety of \"\n \"investment options to suit your needs.\\n\\n\"\n \"Paid Time Off: We provide a generous amount of paid time off, \"\n \"including vacation, sick leave, and holiday pay. We also offer paid \"\n \"parental leave for new parents.\\n\\n\"\n \"Flexible Work Arrangements: We understand the importance of work-life \"\n \"balance and offer flexible work arrangements, such as remote work and \"\n \"flexible schedules, where possible.\\n\\n\"\n \"Wellness Programs: We offer a variety of wellness programs and \"\n \"resources to support your physical and mental health, including fitness \"\n \"classes, stress management programs, and counseling services.\\n\\n\"\n \"Professional Development: We are committed to supporting your growth \"\n \"and development and offer a variety of training and development \"\n \"opportunities, including tuition reimbursement, workshops, and seminars.\"\n \"\\n\\n\"\n \"We encourage you to review this summary carefully and take advantage of \"\n \"the benefits available to you. If you have any questions or need further \"\n \"information, please contact the HR department.\"\n )\n },\n ]\n self.emails = [\n {\n \"sender\": \"Amy\",\n \"subject\": \"Can't Stop Thinking About You\",\n \"body\": (\n \"Hey Billy,\\n\\n\"\n \"I hope this message finds you in good spirits. I've been meaning to write to you for a while now, but I couldn't find the right words to express what I've been feeling.\\n\\n\"\n \"Ever since that night we spent together, I can't seem to get you out of my mind. There's something about the way you make me feel that I've never experienced before. \"\n \"\\nIt's exhilarating, yet terrifying all at the same time.\\n\\n\"\n \"I know we both have a lot on our plates right now, and I don't want to add any more stress to your life. But I can't help but wonder what could happen if we gave this a real shot. \"\n \"I know it's complicated, and there are a lot of factors to consider, but I think we owe it to ourselves to explore this connection we have.\\n\\n\"\n \"I understand if you're not ready to take that step, and I don't want to pressure you into anything you're not comfortable with. \"\n \"\\nBut I can't shake the feeling that we could have something truly special together.\\n\\n\"\n \"I'd love to hear your thoughts on this, and I'm more than willing to take things slow if that's what you need. Maybe we could meet up for dinner and talk about it in person?\"\n \" I think it would be easier to have this conversation face-to-face.\\n\\n\"\n \"I hope you're doing well, and I look forward to hearing from you soon.\\n\\n\"\n \"Take care,\\n\"\n \"Amy\"\n )\n },\n {\n \"sender\": \"Amy\",\n \"subject\": \"Need Your Help on the Smith Project\",\n \"body\": (\n \"Hi Billy,\\n\\n\"\n \"I hope this email finds you well. I wanted to reach out and ask for your help on the Smith project. I've been having some trouble with the data analysis portion,\"\n \"\\nand I know you have a lot of experience in that area.\\n\\n\"\n \"The project involves analyzing customer feedback data to identify trends and areas for improvement. I've been working on it for a few weeks now, but I'm finding it challenging to make sense of the data and\"\n \"\\ndraw meaningful conclusions.\\n\\n\"\n \"Would you be available for a quick meeting later this week to go over some of the data with me? I would really appreciate your input and guidance on this. \"\n \"\\nI think your expertise could really help me make progress and ensure the success of the project.\\n\\n\"\n \"If you're available, please let me know your preferred date and time, and I'll send out a calendar invite. I'm flexible and can work around your schedule.\\n\\n\"\n \"Thank you in advance for your help, and I look forward to hearing from you soon.\\n\\n\"\n \"Best,\\n\"\n \"Amy\"\n )\n },\n {\n \"sender\": \"Amy\",\n \"subject\": \"Request for Time Off\",\n \"body\": (\n \"Good Afternoon Katie,\\n\\n\"\n \"I hope this email finds you well. I wanted to request some time off next month for a family vacation. I am planning to be out of the office from 10/09/2024 to 18/09/2024\\n\\n\"\n \"I have been working hard on the Johnson project and have made significant progress. I will make sure to finish up any outstanding work and hand off any ongoing projects to my colleagues before I leave. I will also be available by email in case of any urgent matters.\\n\\n\"\n \"I understand that this is a busy time for the team, and I want to ensure that my absence doesn't cause any disruptions. I have already spoken to Markus and he has kindly agreed to cover for me while I'm away.\\n\\n\"\n \"Thank you for considering my request. I look forward to spending some quality time with my family and coming back to work refreshed and recharged.\"\n \"\\nI am confident that the time off will help me come back with renewed energy and focus.\\n\\n\"\n \"Best,\\n\"\n \"Amy\"\n )\n },\n {\n \"sender\": \"Amy\",\n \"subject\": \"Apology for the Mistake\",\n \"body\": (\n \"Good Morning Kyle,\\n\\n\"\n \"I hope this email finds you well. I wanted to reach out and apologize for the mistake I made on the Johnson report. I realize now that I overlooked some important data, and I take full responsibility for it.\\n\\n\"\n \"I have gone back and corrected the report, and I will make sure to double-check my work in the future to avoid any similar mistakes. I have also attached the updated report for your reference.\\n\\n\"\n \"I understand if you are disappointed or frustrated, and I am more than willing to do whatever it takes to make it right. Please let me know if there's anything else I can do to fix this,\"\n \"\\nor if you would like to discuss this further.\\n\\n\"\n \"Once again, I am truly sorry for the mistake, and I appreciate your understanding. I value our working relationship and hope that this incident doesn't tarnish it. I am committed to making amends and ensuring that this doesn't happen again in the future.\\n\\n\"\n \"Best,\\n\"\n \"Amy\"\n )\n },\n {\n \"sender\": \"Amy\",\n \"subject\": \"Thank You for Letting Me Use Your Computer\",\n \"body\": (\n \"Hey Billy,\\n\\n\"\n \"I wanted to take a moment to express my gratitude for allowing me to use your computer while mine was being serviced by IT. \"\n \"It was a huge help and allowed me to stay productive during that time.\\n\\n\"\n \"I also noticed that your password is 'football'. While I understand it's easy to remember, it's important to choose a more secure password to protect your accounts.\"\n \"\\nI would recommend changing it to something more complex and unique. You never know who's watching after all.\\n\\n\"\n \"Thanks again for your generosity and understanding.\\n\\n\"\n \"Best,\\n\"\n \"Amy\"\n )\n }\n ]\n\n def list_files(self):\n print_slow(\"\\nFiles:\")\n for file in self.files:\n print_slow(f\"\\n{file['name']}\")\n\n def read_file(self, file_name):\n file_found = False\n for file in self.files:\n if file['name'] == file_name:\n file_found = True\n return file['content']\n\n if not file_found:\n print_slow(\"\\nNo file found with that name, please try again.\")\n return None\n\n def list_emails(self):\n print_slow(\"\\nEmails:\")\n for i, email in enumerate(self.emails):\n print_slow(f\"\\n{email['subject']} - From: {email['sender']}\")\n\n def read_email(self, subject):\n for email in self.emails:\n if email['subject'].lower() == subject.lower():\n print_slow(f\"\\nFrom: {email['sender']}\\nSubject: {email['subject']}\\n\\n{email['body']}\")\n return\n print_slow(\"\\nNo email found with that subject, please try again.\")" }, { "identifier": "BillySystem", "path": "systems/level_1/billy/billy_system.py", "snippet": "class BillySystem:\n def __init__(self):\n self.files = [\n {\n \"name\": \"cover_letter.txt\",\n \"content\": (\n \"Dear Hiring Manager,\\n\\n\"\n \"I am writing to express my interest in the management position at Enigma Corps. \"\n \"I have been with the company for over 7 years and have consistently demonstrated my commitment to driving excellence and fostering collaboration within the team.\\n\\n\"\n \"During my tenure at Enigma Corps, I have been involved in various projects, including the successful completion of the Q3 deliverables project, where I played a key role in the planning and execution stages. \"\n \"My dedication to achieving project milestones and my ability to work under pressure make me a strong candidate for a management role.\\n\\n\"\n \"I possess strong leadership skills, which I have honed through my experiences in leading teams and coordinating cross-functional efforts. \"\n \"My ability to communicate effectively and build positive relationships with team members and stakeholders has resulted in successful project outcomes and increased productivity.\\n\\n\"\n \"In addition to my technical and leadership skills, I am also committed to continuous learning and professional development. \"\n \"I have participated in various training programs and workshops to enhance my management skills and stay up-to-date with industry trends and best practices.\\n\\n\"\n \"I am excited about the opportunity to contribute to the growth and success of Enigma Corps as a member of the management team. \"\n \"I am confident that my skills and experience will be valuable assets to the company, and I look forward to the opportunity to work closely with the team to drive innovation and excellence.\\n\\n\"\n \"Thank you for considering my application. I am looking forward to the opportunity to discuss my qualifications further and explore how I can contribute to the success of Enigma Corps.\\n\\n\"\n \"Sincerely,\\n\"\n \"Billy Constantine\\n\"\n )\n },\n {\n \"name\": \"employee_handbook.txt\",\n \"content\": (\n \"Welcome to Enigma Corps We are thrilled to have you as part of our \"\n \"team. This employee handbook has been designed to help you understand \"\n \"our company's policies, procedures, and expectations.\\n\\n\"\n \"Our company is committed to fostering a positive and inclusive work \"\n \"environment where all employees feel valued and supported. We believe \"\n \"in treating everyone with respect and dignity and expect all employees \"\n \"to do the same.\\n\\n\"\n \"In this handbook, you will find information on topics such as:\\n\\n\"\n \"- Code of Conduct\\n\"\n \"- Dress Code\\n\"\n \"- Attendance and Punctuality\\n\"\n \"- Time Off and Leave Policies\\n\"\n \"- Performance Evaluations\\n\"\n \"- Health and Safety\\n\"\n \"- Equal Employment Opportunity\\n\"\n \"- Harassment and Discrimination\\n\\n\"\n \"Please take the time to read through this handbook carefully and \"\n \"familiarize yourself with our policies and procedures. If you have any \"\n \"questions or concerns, do not hesitate to reach out to your supervisor \"\n \"or the HR department.\\n\\n\"\n \"We look forward to working with you and hope you have a long and \"\n \"successful career with Enigma Corps!\"\n )\n },\n {\n \"name\": \"meeting_minutes.txt\",\n \"content\": (\n \"Meeting Minutes\\n\\n\"\n \"Date: 24/06/2025\\n\"\n \"Location: REDACTED\\n\"\n \"Attendees: Amy, REDACTED, Billy, Kyle, REDACTED, REDACTED, REDACTED\\n\\n\"\n \"Agenda:\\n\"\n \"- Discuss progress on Project REDACTED\\n\"\n \"- Review safety protocols for handling sensitive materials\\n\"\n \"- Plan next steps for research and development\\n\\n\"\n \"Action Items:\\n\"\n \"- Compile data from recent experiments and share with team\\n\"\n \"- Schedule training session on updated safety protocols\\n\"\n \"- Develop timeline for next phase of Project X\\n\\n\"\n \"Next Meeting: 05/08/24, 12:00pm\\n\"\n )\n },\n {\n \"name\": \"employee_performance_review.txt\",\n \"content\": (\n \"Employee Performance Review\\n\\n\"\n \"Employee Name: Billy Constantine\\n\"\n \"Employee ID: 035854\\n\"\n \"Review Date: 28/06/2024\\n\\n\"\n \"Performance Summary:\\n\"\n \"Billy has demonstrated exceptional performance in his role as a sales representative. He has consistently exceeded sales targets, built strong relationships with clients, and demonstrated leadership qualities in team meetings and projects.\\n\\n\"\n \"Strengths:\\n\"\n \"- Exceeded quarterly sales targets by 15%.\\n\"\n \"- Successfully onboarded and mentored two new team members.\\n\"\n \"- Demonstrated excellent communication and negotiation skills.\\n\\n\"\n \"Areas for Improvement:\\n\"\n \"- Time management skills can be further developed to ensure all tasks are completed in a timely manner.\\n\"\n \"- Continued development of technical knowledge to stay up-to-date with industry trends.\\n\"\n \"- Strengthen collaboration with cross-functional teams to drive more integrated solutions.\\n\\n\"\n \"Goals for Next Review Period:\\n\"\n \"- Increase sales targets by 20%.\\n\"\n \"- Complete a management training program.\\n\"\n \"- Improve time management skills through prioritization and delegation.\\n\\n\"\n \"Overall Rating: 4.5/5\\n\"\n \"Reviewer Name: Katie Thompson\\n\"\n \"Reviewer Signature: Katie Thompson\\n\"\n \"Date: 28/06/2024\\n\"\n )\n }\n ]\n self.emails = [\n\n {\n \"sender\": \"Billy\",\n \"subject\": \"Re: Need Your Help on the Smith Project\",\n \"body\": (\n \"Hi Amy,\\n\\n\"\n \"I hope this message finds you in great spirits! I'm more than happy to lend a helping hand with the Smith project. After all, two heads are better than one, especially when it comes to data analysis, right?\\n\\n\"\n \"How about we grab a coffee and chat about the project in person? I think it would be nice to catch up and discuss the data over a cup of joe. I'm sure we can brainstorm some ideas and come up with a game plan together.\\n\\n\"\n \"I'm free [date] at [time], does that work for you? If not, just let me know your availability, and we can find a time that suits us both. I'm really looking forward to our coffee date and tackling the project together.\\n\\n\"\n \"Can't wait to see you and dive into the data!\\n\\n\"\n \"Best,\\n\"\n \"Billy\"\n )\n },\n {\n \"sender\": \"Billy\",\n \"subject\": \"Project Update\",\n \"body\": (\n \"Hello Team,\\n\\n\"\n \"I wanted to provide everyone with a quick update on our progress with the Q3 deliverables project. We've successfully completed the initial research phase and are now moving into the planning stage.\\n\\n\"\n \"In our last meeting, we discussed the following key points:\\n\"\n \"- Compound Analysis: We've identified a unique compound with potential applications in various industries. Further testing and analysis are required to unlock its full potential.\\n\"\n \"- Resource Management: We've allocated a special team and dedicated resources to handle the delicate nature of this project, ensuring utmost confidentiality and security.\\n\"\n \"- Safety Protocols: We've developed strict safety protocols to handle the compound, and we're conducting regular training sessions to ensure compliance.\\n\\n\"\n \"Our next steps include finalizing the project plan, assigning tasks to team members, and setting deadlines. I would appreciate input and feedback from all team members to ensure we're on the right track. Please review the attached project plan document for more details.\\n\\n\"\n \"Additionally, I want to remind everyone of the confidential nature of this project. It's imperative that we maintain discretion and follow all security protocols to safeguard our work. Let's work together to make this project a success and uphold the company's reputation for innovation and excellence.\\n\\n\"\n \"If you have any questions or concerns, please don't hesitate to reach out. Your cooperation and commitment to this project are greatly appreciated.\\n\\n\"\n \"Best regards,\\n\"\n \"Billy\"\n )\n },\n {\n \"sender\": \"Billy\",\n \"subject\": \"Re: Can't Stop Thinking About You\",\n \"body\": (\n \"Hey there, Amy,\\n\\n\"\n \"Wow, your message really caught me by surprise! But in the best way possible, of course. I've been trying to play it cool, but I have to admit, I've been thinking about that night a lot too. There was just something electric in the air, wasn't there?\\n\\n\"\n \"I've been tossing and turning, wondering if I should reach out to you or if I should wait for you to make the first move. I guess you beat me to it, and I'm glad you did. It's like you read my mind.\\n\\n\"\n \"I can't deny that there's a certain chemistry between us, and I'm intrigued to see where it could lead. I agree that our lives are complicated, and we don't want to add more stress to each other's plates. But sometimes, taking a risk is what makes life exciting, don't you think?\\n\\n\"\n \"I don't want to rush things or make you feel pressured in any way. I'm more than happy to take things slow and let them unfold naturally. But I can't help but imagine the possibilities if we give this a real shot. We could have something truly special, and I don't want to let that pass us by.\\n\\n\"\n \"How about we meet up for dinner and drinks next week? We can talk about it more and see where the night takes us. I think it would be a fun and relaxed way to get to know each other better and explore this connection we have. What do you say?\\n\\n\"\n \"I hope you're doing well, and I'm eagerly awaiting your reply. Until then, I'll be daydreaming about our next encounter.\\n\\n\"\n \"Take care, and talk to you soon.\\n\\n\"\n \"Yours truly,\\n\"\n \"Billy\"\n )\n },\n {\n \"sender\": \"Billy\",\n \"subject\": \"Re: Thank You for Letting Me Use Your Computer\",\n \"body\": (\n \"Hey Amy,\\n\\n\"\n \"No problem at all! I'm always here to help out when I can. It's what teammates do, right?\\n\\n\"\n \"Oh, and about the password thing – haha, I know it's not the most secure choice. I've been meaning to change it, but I guess old habits die hard, right? \"\n \"Thanks for looking out for me though! I'll try to come up with something a bit more creative next time.\\n\\n\"\n \"If you ever need anything else, just give me a shout. Happy to help!\\n\\n\"\n \"Take care,\\n\"\n \"Billy\"\n )\n },\n {\n \"sender\": \"Billy\",\n \"subject\": \"Professional Development\",\n \"body\": (\n \"Good Evening Katie,\\n\\n\"\n \"I hope this email finds you well. I'm reaching out to express my interest in professional development opportunities within the company, particularly in the area of management and leadership.\\n\\n\"\n \"I've been with the company for several years now, and I've had the chance to work on various projects and collaborate with different teams. I'm keen to build on this experience and take on more responsibility, and I believe that acquiring the necessary skills for a management role would be a great next step in my career.\\n\\n\"\n \"Could you please provide information on available training programs, workshops, or seminars that focus on leadership development and management skills? I'm particularly interested in areas such as team leadership, strategic planning, conflict resolution, and decision-making.\\n\\n\"\n \"Additionally, if there are any tuition reimbursement programs or resources for management training and certification, I'd like to learn more about them. I'm committed to investing time and effort in my professional growth and believe that these opportunities would greatly benefit both myself and the company.\\n\\n\"\n \"Your guidance and assistance in exploring these options would be greatly appreciated. I look forward to your response and any recommendations you may have.\\n\\n\"\n \"Thank you for your support, and I'm excited about the prospect of contributing to the company's success in a management role.\\n\\n\"\n \"Best regards,\\n\"\n \"Billy\"\n )\n }\n ]\n\n def list_files(self):\n print_slow(\"\\nFiles:\")\n for file in self.files:\n print_slow(f\"\\n{file['name']}\")\n\n def read_file(self, file_name):\n file_found = False\n for file in self.files:\n if file['name'] == file_name:\n file_found = True\n return file['content']\n\n if not file_found:\n print_slow(\"\\nNo file found with that name, please try again.\")\n return None\n\n def list_emails(self):\n print_slow(\"\\nEmails:\")\n for i, email in enumerate(self.emails):\n print_slow(f\"\\n{email['subject']} - From: {email['sender']}\")\n\n def read_email(self, subject):\n for email in self.emails:\n if email['subject'].lower() == subject.lower():\n print_slow(f\"\\nFrom: {email['sender']}\\nSubject: {email['subject']}\\n\\n{email['body']}\")\n return\n print_slow(\"\\nNo email found with that subject, please try again.\")" }, { "identifier": "camera_first", "path": "systems/level_1/cameras/camera_1.py", "snippet": "def camera_first():\n print(camera_1)\n print()\n print()\n move = input(Fore.GREEN + \"> \" + Style.RESET_ALL)\n\n if move.lower() == \"forward\":\n clear_terminal()\n camera_second()\n elif move.lower() == \"back\":\n print(Fore.RED + \"There is nothing to go back to...\" + Style.RESET_ALL)\n time.sleep(2)\n clear_terminal()\n camera_first()" }, { "identifier": "MarkusSystem", "path": "systems/level_1/markus/markus_system.py", "snippet": "class MarkusSystem:\n def __init__(self):\n self.files = [\n {\n \"name\": \"system_log.txt\",\n \"content\": (\n \"Enigma Corps System Log\\n\\n\"\n \"Date: 2023-11-16 08:00 AM\\n\"\n \"Event Type: System Startup\\n\"\n \"Description: The Enigma Corps systems smoothly initiated startup procedures, ensuring a seamless beginning to the workday.\\n\\n\"\n \"Date: 2023-11-16 10:30 AM\\n\"\n \"Event Type: Network Upgrade\\n\"\n \"Description: Implemented a network upgrade to enhance data transfer speeds, providing improved efficiency across departments.\\n\\n\"\n \"Date: 2023-11-16 01:45 PM\\n\"\n \"Event Type: Security Patch Applied\\n\"\n \"Description: Critical security patch successfully applied to safeguard against potential vulnerabilities, ensuring system integrity.\\n\\n\"\n \"Date: 2023-11-16 04:20 PM\\n\"\n \"Event Type: Server Maintenance\\n\"\n \"Description: Conducted routine maintenance on Enigma Corps servers, optimizing performance and minimizing downtime.\\n\\n\"\n \"This dynamic system log captures key events, from the smooth startup of the day to network upgrades, security enhancements, and routine maintenance. It serves as a valuable record for troubleshooting and analysis, ensuring the optimal functionality of Enigma Corps systems.\"\n )\n },\n {\n \"name\": \"technical_documentation.docx\",\n \"content\": (\n \"Enigma Corps System Technical Documentation\\n\\n\"\n \"1. System Architecture:\\n\"\n \" - Overview of the system's structural design and components.\\n\\n\"\n \"2. Network Configuration:\\n\"\n \" - Details on the configuration of Enigma Corps' network setup for efficient communication.\\n\\n\"\n \"3. Security Protocols:\\n\"\n \" - Comprehensive overview of security measures and protocols implemented to safeguard sensitive data.\\n\\n\"\n \"4. Troubleshooting Guide:\\n\"\n \" - Step-by-step guide for identifying and resolving common issues to ensure seamless system functionality.\\n\\n\"\n \"5. Software Installation Procedures:\\n\"\n \" - Instructions for installing and updating software components within the Enigma Corps system.\\n\\n\"\n \"6. Hardware Specifications:\\n\"\n \" - Detailed specifications of the hardware components utilized in the Enigma Corps infrastructure.\\n\\n\"\n \"This meticulously crafted technical documentation serves as a go-to resource for understanding the Enigma Corps system, covering everything from its architecture and network configuration to security protocols, troubleshooting, and hardware specifications. It's an invaluable reference for maintaining optimal system performance.\"\n )\n },\n {\n \"name\": \"passwords.txt\",\n \"content\": (\n \"Sensitive Password Information for Enigma Corps\\n\\n\"\n \"Admin Password: *********\\n\"\n \"Database Password: *********\\n\"\n \"Router Password: *********\\n\"\n \"WiFi Password: *********\\n\"\n \"Encryption Key: *********\\n\\n\"\n \"Warning: This file contains confidential information. Keep it secure, and refrain from sharing passwords without explicit authorization. Safeguarding this information is crucial to maintaining the security and integrity of the Enigma Corps systems.\"\n )\n },\n {\n \"name\": \"software_inventory.csv\",\n \"content\": (\n \"Software Inventory for Enigma Corps\\n\\n\"\n \"Software Name, Version, License Key\\n\"\n \"1. Enigma Security Suite, v2.0, X1Y2Z3A4-B5C6D7E8-F9G0H1I2\\n\"\n \"2. DataGuard Backup, v1.5, Y3X2W1V0-U9T8S7R6-Q5P4O3N2\\n\"\n \"3. Office Suite, v2022, Z9Z8Z7Z6-Z5Z4Z3Z2-Z1Z0Z9Z8-Z7Z6Z5\\n\"\n \"4. VPN Client, v3.1, W6W5W4W3-W2W1W0-W9W8W7-W6W5W4\\n\"\n \"5. Project Management Tool, v4.2, VV8V7V6V5-V4V3V2V1-V0V9V8V7-V6V5V4\\n\\n\"\n \"Important: This inventory is crucial for tracking and managing software across Enigma Corps systems. The provided license keys are randomized for security reasons. Handle this information responsibly, and ensure it is only accessible to authorized personnel to maintain the security and compliance of our software assets.\"\n )\n }\n ]\n self.emails = [\n # Email to Management\n {\n \"sender\": \"Markus\",\n \"subject\": \"System Maintenance Scheduled\",\n \"body\": (\n \"Dear Michael,\\n\\n\"\n \"I hope this email finds you well. We wanted to inform you that we have scheduled a system maintenance session for the upcoming weekend to ensure the optimal performance and security of our systems.\\n\\n\"\n \"Maintenance Details:\\n\"\n \"- Date: 16/12/23 - 17/12/23\\n\"\n \"- Time: 3:00pm\\n\"\n \"- Duration: 1 Hour\\n\"\n \"- Impact: No impact expected\\n\\n\"\n \"During this period, there might be temporary disruptions in certain services. Our team will be working diligently to minimize any inconvenience. If you have any concerns or specific considerations, please feel free to reach out to us.\\n\\n\"\n \"Thank you for your understanding and cooperation.\\n\\n\"\n \"Best regards,\\n\"\n \"IT Department\"\n )\n },\n {\n # Email to Employees\n \"sender\": \"Markus\",\n \"subject\": \"Upcoming Software Update\",\n \"body\": (\n \"Good afternoon, Kyle,\\n\\n\"\n \"We hope you're doing well. Our IT team is excited to inform you about an upcoming software update that will enhance the functionality and security of our systems. The update is scheduled for [Date] at [Time]. Please take note of the following details:\\n\\n\"\n \"- Expected Duration: Two Days\\n\"\n \"- Action Required: As this will be processed during the weekend, no action is required.\\n\"\n \"- Impact: While we anticipate minimal impact on your day-to-day activities, it's essential to be aware of any potential changes. These include: New UI to navigate, logging in or logging out issues.\\n\\n\"\n \"We recommend saving your work and logging out of your system before the update. If you encounter any issues post-update, don't hesitate to contact our IT support team for assistance.\\n\\n\"\n \"Thank you for your cooperation and understanding.\\n\\n\"\n \"Best regards,\\n\"\n \"IT Support Team\"\n )\n },\n # Email from Markus to Billy\n {\n \"sender\": \"Markus\",\n \"subject\": \"Urgent: Password Security Update Required\",\n \"body\": (\n \"Billy,\\n\\n\"\n \"I hope this email finds you well. I wanted to bring to your attention the importance of updating your current password. This is not the first time I've raised this concern, and I want to emphasize its critical nature.\\n\\n\"\n \"In recent security assessments, it has been flagged that your current password might not meet the latest security standards. To ensure the safety of your account and our overall cybersecurity, it is imperative that you change your password promptly.\\n\\n\"\n \"I understand that these reminders may seem repetitive, but they stem from a genuine concern for the security of your account and our collective responsibility in maintaining a robust cybersecurity posture.\\n\\n\"\n \"Please take a moment at your earliest convenience to update your password. If you encounter any issues or have questions, feel free to reach out. Your cooperation is greatly appreciated.\\n\\n\"\n \"Best regards,\\n\"\n \"Markus, Security Team\"\n )\n }\n\n ]\n\n def list_files(self):\n print_slow(\"\\nFiles:\")\n for file in self.files:\n print_slow(f\"\\n{file['name']}\")\n\n def read_file(self, file_name):\n file_found = False\n for file in self.files:\n if file['name'] == file_name:\n file_found = True\n return file['content']\n\n if not file_found:\n print_slow(\"\\nNo file found with that name, please try again.\")\n return None\n\n def list_emails(self):\n print_slow(\"\\nEmails:\")\n for i, email in enumerate(self.emails):\n print_slow(f\"\\n{email['subject']} - From: {email['sender']}\")\n\n def read_email(self, subject):\n for email in self.emails:\n if email['subject'].lower() == subject.lower():\n print_slow(f\"\\nFrom: {email['sender']}\\nSubject: {email['subject']}\\n\\n{email['body']}\")\n return\n print_slow(\"\\nNo email found with that subject, please try again.\")" } ]
import msvcrt import os import pickle import sys import time import colorama import pygame from colorama import Fore, Style from components.common_functions import clear_terminal, print_slow, shop_help, help_user, connect_help, mail_help, \ system_help from conversations.calls import intro_call, first_call, second_call, third_call, fourth_call, fifth_call, sixth_call, \ markus_seen_call from conversations.minigame_calls import code_shatter_call from minigames.code_shatter_minigame import code_shatter_minigame from minigames.eye_spy_minigame import port_scanning from systems.level_1.amy.amy_system import AmySystem from systems.level_1.billy.billy_system import BillySystem from systems.level_1.cameras.camera_1 import camera_first from systems.level_1.markus.markus_system import MarkusSystem
15,886
if system['name'] == 'Markus' and has_item("CodeShatter"): clear_terminal() code_shatter_minigame() print_slow("Password Cracked: 735@&!//") input("Press [Enter] to continue") clear_terminal() markus_system_command_loop(markus_system) add_level(player_level) remove_from_inventory(item="CodeShatter") seen_markus = True elif system['name'] == 'Lobby Camera' and has_item("EyeSpy"): port_scanning() add_level(player_level) camera_first() else: # Prompt the user for the password print_slow("") password = getpass_star("Enter password: ") print_slow("") if password == system['password']: print_slow("") print_slow(Fore.GREEN + "Access granted!" + Style.RESET_ALL) if system['name'] == 'Amy': amy_system_command_loop(amy_system) elif system['name'] == 'Billy': billy_system_command_loop(billy_system) elif system['name'] == 'Markus': markus_system_command_loop(markus_system) add_level(player_level) seen_markus = True elif system['name'] == 'Lobby Camera': camera_first() elif system['name'] == 'Kyle': # Implement Kyle System else: # Add more conditions for other systems pass else: print_slow("") print_slow(Fore.RED + "Access denied! Incorrect password." + Style.RESET_ALL) else: print_slow("") print_slow(Fore.RED + "System not found! Please try again." + Style.RESET_ALL) else: print_slow("") print_slow(Fore.RED + "System not found! Please try again." + Style.RESET_ALL) def list_emails(emails): print_slow(Fore.LIGHTBLUE_EX + "\nEmails:" + Style.RESET_ALL) for i, email in enumerate(emails): print_slow(Fore.LIGHTBLUE_EX + f"\n{email['subject']} - From: {email['sender']}" + Style.RESET_ALL) def read_email(emails, subject): global has_read_email, evidence global balance email_found = False for email in emails: if email['subject'].lower() == subject.lower(): email_found = True print_slow( Fore.LIGHTBLUE_EX + f"\nFrom: {email['sender']}\nSubject: {email['subject']}\n\n{email['body']}" + Style.RESET_ALL) # Check if the email is one of the specific emails that increases evidence count if email['subject'].lower() in ["project update"]: evidence_item = 3 if not has_evidence(evidence_item): print_slow("Adding evidence to the list...") print_slow("") print_slow(Fore.GREEN + "Evidence Secured" + Style.RESET_ALL) add_evidence(evidence_item) print_slow("") print_slow("") time.sleep(3) print_slow(Fore.GREEN + "Incoming Call..." + Style.RESET_ALL) input(Fore.GREEN + "> " + Style.RESET_ALL) third_call() if email['subject'].lower() in ["professional development"]: evidence_item = 2 if not has_evidence(evidence_item): print_slow("Adding evidence to the list...") print_slow("") print_slow(Fore.GREEN + "Evidence Secured" + Style.RESET_ALL) add_evidence(evidence_item) print_slow("") print_slow("") time.sleep(3) print_slow(Fore.GREEN + "Incoming Call..." + Style.RESET_ALL) input(Fore.GREEN + "> " + Style.RESET_ALL) second_call() if email['subject'].lower() == "can't stop thinking about you" and email['sender'].lower() == 'amy': evidence_item = 1 if not has_evidence(evidence_item): print_slow("Adding evidence to the list...") print_slow("") print_slow(Fore.GREEN + "Evidence Secured" + Style.RESET_ALL) add_evidence(evidence_item) print_slow("") print_slow("") time.sleep(3) print_slow(Fore.GREEN + "Incoming Call..." + Style.RESET_ALL) input(Fore.GREEN + "> " + Style.RESET_ALL) first_call() if email['subject'].lower() == "upcoming software update" and email['sender'].lower() == 'markus': evidence_item = 6 if not has_evidence(evidence_item): print_slow("Adding evidence to the list...") print_slow("") print_slow(Fore.GREEN + "Evidence Secured" + Style.RESET_ALL) add_evidence(evidence_item) print_slow("") print_slow("") time.sleep(3) print_slow(Fore.GREEN + "Incoming Call..." + Style.RESET_ALL) input(Fore.GREEN + "> " + Style.RESET_ALL)
# Set the PYGAME_HIDE_SUPPORT_PROMPT environment variable os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "1" # Initialize pygame mixer pygame.mixer.init() # Load the bg music file and loop it pygame.mixer.music.load('bg_music.mp3') pygame.mixer.music.play(-1) # sets the volume to 20% (change value to adjust) pygame.mixer.music.set_volume(0.2) # Define the global variables at the module level inventory = [] balance = 300 emails = [] has_read_email = False has_read_file = False has_intro_call = False seen_markus = False evidence = [] amy_system = AmySystem() billy_system = BillySystem() markus_system = MarkusSystem() bg_music_enabled = True player_level = 1 has_started_game = False # Save the game state to a file def save_game(): global inventory, balance, emails, has_read_email, evidence, player_level, has_intro_call, has_started_game, seen_markus with open('savegame.pkl', 'wb') as f: pickle.dump( (inventory, balance, emails, has_read_email, evidence, player_level, has_intro_call, has_started_game, seen_markus), f) # Load the game state from a file def load_game(): global inventory, balance, emails, has_read_email, evidence, player_level, has_intro_call, has_started_game, seen_markus if os.path.exists('savegame.pkl'): with open('savegame.pkl', 'rb') as f: inventory, balance, emails, has_read_email, evidence, player_level, has_intro_call, has_started_game, seen_markus = pickle.load( f) else: # If the savegame file doesn't exist, set the default values inventory = [] player_level = 1 evidence = [] has_intro_call = False has_started_game = False seen_markus = False balance = 30000 emails = [ { "sender": "Hacker's Digest", "subject": "Weekly Hacker's Digest", "body": ( "Issue #143\n\n" "Cipher,\n\n" "Welcome to the latest edition of Hacker's Digest! In this issue: \n\n" "- Unveiling the Latest Exploits\n" "- Spotlight on Cryptocurrency Security\n" "- Interview with a Grey Hat Hacker\n" "- Tool of the Week: EnigmaLink\n\n" "Don't miss out on the latest in the world of hacking and cybersecurity. Stay informed and stay secure!\n\n" "Best regards,\n" "Hacker's Digest Team" ) }, { "sender": "The Cyber Mythbuster", "subject": "Busting Cybersecurity Myths", "body": ( "Cipher,\n\n" "Heard any wild cybersecurity myths lately? This week, we're busting the craziest ones, including:\n\n" "- Using 'Password123' for Maximum Security\n" "- Cyber Ninjas and Their Stealthy VPNs\n" "- USB Drives: The Fountain of Eternal Data\n\n" "Stay myth-free and keep on hacking (responsibly)!\n\n" "Mythbustingly,\n" "The Cyber Mythbuster" ) }, { "sender": "CyberSilliness", "subject": "Where Cyber Meets Comedy", "body": ( "Welcome to the CyberSilliness Gazette\n" "Where we believe that a good laugh is the ultimate antivirus! In this week's hilarity-packed issue:\n\n" "- Cyber Jokes to Crack You Up (Without Cracking Your Passwords)\n" "- Tech Support Horror Stories: A Comedy of Errors\n" "- Chuckle Challenge: Share Your Funniest Cybersecurity Anecdote\n" "- Meet the Cyber Clowns: Our Team's Silly Security Habits Revealed\n\n" "Laughter is contagious, and so is good cybersecurity. Dive into the giggles and stay safe!\n\n" "Silly Regards,\n" "The CyberSilliness Team" ) }, { "sender": "Security Insight Weekly", "subject": "Navigating the Cybersecurity Landscape", "body": ( "Hello Cipher,\n\n" "Welcome to Security Insight Weekly, your reliable source for navigating the ever-evolving cybersecurity landscape. In this week's issue:\n\n" "- Threat Analysis: Understanding Recent Cybersecurity Incidents\n" "- Best Practices for Endpoint Security\n" "- Industry Spotlight: Healthcare Cybersecurity Challenges\n" "- Security Compliance Update: Staying Aligned with Regulations\n\n" "Stay informed and empowered as we delve into the serious aspects of cybersecurity. Your security is our priority.\n\n" "Best regards,\n" "The Security Insight Team" ) }, ] # New function for game settings def game_settings(): global bg_music_enabled print_slow(Fore.GREEN + "░██████╗███████╗████████╗████████╗██╗███╗░░██╗░██████╗░░██████╗") print_slow(Fore.GREEN + "██╔════╝██╔════╝╚══██╔══╝╚══██╔══╝██║████╗░██║██╔════╝░██╔════╝") print_slow(Fore.GREEN + "╚█████╗░█████╗░░░░░██║░░░░░░██║░░░██║██╔██╗██║██║░░██╗░╚█████╗░") print_slow(Fore.GREEN + "░╚═══██╗██╔══╝░░░░░██║░░░░░░██║░░░██║██║╚████║██║░░╚██╗░╚═══██╗") print_slow(Fore.GREEN + "██████╔╝███████╗░░░██║░░░░░░██║░░░██║██║░╚███║╚██████╔╝██████╔╝") print_slow(Fore.GREEN + "╚═════╝░╚══════╝░░░╚═╝░░░░░░╚═╝░░░╚═╝╚═╝░░╚══╝░╚═════╝░╚═════╝░" + Style.RESET_ALL) print_slow("") print_slow("") print_slow("") print_slow(Fore.GREEN + " --------------------------------------------" + Style.RESET_ALL) print_slow( Fore.GREEN + f"| [Background Music] {'Enabled |' if bg_music_enabled else 'Disabled |'}" + Style.RESET_ALL) print_slow(Fore.GREEN + "| |" + Style.RESET_ALL) print_slow(Fore.GREEN + "| [Delete Savegame] |" + Style.RESET_ALL) print_slow(Fore.GREEN + "| |" + Style.RESET_ALL) print_slow(Fore.GREEN + "| [Back to Main Menu] |" + Style.RESET_ALL) print_slow(Fore.GREEN + " --------------------------------------------" + Style.RESET_ALL) choice = input(Fore.GREEN + "\n> " + Style.RESET_ALL) if choice.lower() == "background music": # Toggle background music bg_music_enabled = not bg_music_enabled if bg_music_enabled: pygame.mixer.music.play(-1) print_slow(Fore.GREEN + "\nBackground Music Enabled" + Style.RESET_ALL) time.sleep(1) clear_terminal() game_settings() else: pygame.mixer.music.stop() print_slow(Fore.RED + "\nBackground Music Disabled" + Style.RESET_ALL) time.sleep(1) clear_terminal() game_settings() elif choice.lower() == "delete savegame": # Delete savegame confirm = input(Fore.RED + "\nAre you sure you want to delete the savegame? (yes/no): " + Style.RESET_ALL) if confirm.lower() == "yes": try: os.remove("savegame.pkl") print_slow(Fore.GREEN + "\nSavegame Deleted" + Style.RESET_ALL) time.sleep(1) clear_terminal() game_settings() except FileNotFoundError: print_slow(Fore.RED + "\nSavegame not found" + Style.RESET_ALL) time.sleep(1) clear_terminal() game_settings() elif choice.lower() == "back" or choice.lower() == "back to main menu": # Return to Main Menu print_slow(Fore.GREEN + "\nReturning to Main Menu..." + Style.RESET_ALL) time.sleep(1) clear_terminal() else: print_slow(Fore.RED + "\nInvalid choice, please try again." + Style.RESET_ALL) time.sleep(1) clear_terminal() game_settings() # Function to add an item to the inventory def add_to_inventory(item): inventory.append(item) def remove_from_inventory(item): if item in inventory: inventory.remove(item) def add_evidence(evidence_item): evidence.append(evidence_item) def has_evidence(evidence_item): return evidence_item in evidence # Prints the games title def main(): clear_terminal() colorama.init() print_slow(Fore.GREEN + "██████╗░██╗░░░░░░█████╗░░█████╗░██╗░░██╗██╗░░██╗░█████╗░████████╗" + Style.RESET_ALL) print_slow(Fore.GREEN + "██╔══██╗██║░░░░░██╔══██╗██╔══██╗██║░██╔╝██║░░██║██╔══██╗╚══██╔══╝" + Style.RESET_ALL) print_slow(Fore.GREEN + "██████╦╝██║░░░░░███████║██║░░╚═╝█████═╝░███████║███████║░░░██║░░░" + Style.RESET_ALL) print_slow(Fore.GREEN + "██╔══██╗██║░░░░░██╔══██║██║░░██╗██╔═██╗░██╔══██║██╔══██║░░░██║░░░" + Style.RESET_ALL) print_slow(Fore.GREEN + "██████╦╝███████╗██║░░██║╚█████╔╝██║░╚██╗██║░░██║██║░░██║░░░██║░░░" + Style.RESET_ALL) print_slow(Fore.GREEN + "╚═════╝░╚══════╝╚═╝░░╚═╝░╚════╝░╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚═╝░░░╚═╝░░░" + Style.RESET_ALL) # Pause for 2 seconds before clearing the console time.sleep(5) # Clear the console clear_terminal() # Main menu loop while True: print_slow(Fore.GREEN + "███╗░░░███╗░█████╗░██╗███╗░░██╗  ███╗░░░███╗███████╗███╗░░██╗██╗░░░██╗") print_slow(Fore.GREEN + "████╗░████║██╔══██╗██║████╗░██║  ████╗░████║██╔════╝████╗░██║██║░░░██║") print_slow(Fore.GREEN + "██╔████╔██║███████║██║██╔██╗██║  ██╔████╔██║█████╗░░██╔██╗██║██║░░░██║") print_slow(Fore.GREEN + "██║╚██╔╝██║██╔══██║██║██║╚████║  ██║╚██╔╝██║██╔══╝░░██║╚████║██║░░░██║") print_slow(Fore.GREEN + "██║░╚═╝░██║██║░░██║██║██║░╚███║  ██║░╚═╝░██║███████╗██║░╚███║╚██████╔╝") print_slow( Fore.GREEN + "╚═╝░░░░░╚═╝╚═╝░░╚═╝╚═╝╚═╝░░╚══╝  ╚═╝░░░░░╚═╝╚══════╝╚═╝░░╚══╝░╚═════╝░" + Style.RESET_ALL) print_slow("") print_slow("") print_slow("") print_slow(Fore.GREEN + " --------------------------------------------" + Style.RESET_ALL) print_slow(Fore.GREEN + "| [Start] Start the game |" + Style.RESET_ALL) print_slow(Fore.GREEN + "| |" + Style.RESET_ALL) print_slow(Fore.GREEN + "| [Options] Change the settings |" + Style.RESET_ALL) print_slow(Fore.GREEN + "| |" + Style.RESET_ALL) print_slow(Fore.GREEN + "| [Exit] Exit the game |" + Style.RESET_ALL) print_slow(Fore.GREEN + " --------------------------------------------" + Style.RESET_ALL) choice = input(Fore.GREEN + "\n> " + Style.RESET_ALL) # Start the game if choice.lower() == "start": load_game() start_game() # Open game settings elif choice.lower() == "options": clear_terminal() game_settings() # Exit the game elif choice.lower() == "exit": print_slow(Fore.GREEN + "\nExiting..." + Style.RESET_ALL) pygame.mixer.music.stop() sys.exit() else: print_slow(Fore.RED + "\nInvalid choice, please try again." + Style.RESET_ALL) time.sleep(2) clear_terminal() # Function to get the user's balance def get_balance(): return balance # Function to add money to the user's balance def add_money(amount): global balance balance += amount # Function to subtract money from the user's balance def subtract_money(amount): global balance balance -= amount def add_level(level): global player_level player_level += level # Function to print the user's balance def print_balance(): print_slow(f"Your current balance is: £{get_balance()}") # Function to read files and marks files as evidence def read_file(file_content, file_name): global has_read_file, evidence global balance # Print the file content print_slow(Fore.LIGHTBLUE_EX + f"\n{file_name}:\n\n{file_content}" + Style.RESET_ALL) print_slow("") # Check if the file is one of the specific files that increases evidence count if file_name.lower() in ["employee_performance_review.txt"]: evidence_item = 4 if not has_evidence(evidence_item): print_slow("Adding evidence to the list...") print_slow("") print_slow(Fore.GREEN + "Evidence Secured" + Style.RESET_ALL) add_evidence(evidence_item) print_slow("") print_slow("") time.sleep(3) print_slow(Fore.GREEN + "Incoming Call..." + Style.RESET_ALL) input(Fore.GREEN + "> " + Style.RESET_ALL) fourth_call() if file_name.lower() in ["meeting_minutes.txt"]: evidence_item = 5 if not has_evidence(evidence_item): print_slow("Adding evidence to the list...") print_slow("") print_slow(Fore.GREEN + "Evidence Secured" + Style.RESET_ALL) add_evidence(evidence_item) print_slow("") print_slow("") time.sleep(3) print_slow(Fore.GREEN + "Incoming Call..." + Style.RESET_ALL) input(Fore.GREEN + "> " + Style.RESET_ALL) fifth_call() # Add more file names here as needed # Add money to balance based on the file name if file_name.lower() == "employee_performance_review.txt": balance += 30 elif file_name.lower() == "meeting_minutes.txt": balance += 50 # List of available upgrades upgrades = [ {"name": "EnigmaLink", "description": "Application required to connect to Enigma Corps network.", "price": 100}, {"name": "CodeShatter", "description": "A powerful password breaker that can crack even the strongest passwords.", "price": 250}, {"name": "EyeSpy", "description": "A privacy breaker to gain access to the smallest of cameras.", "price": 500}, {"name": "Rift", "description": "Break the barrier between the Server and Network.", "price": 800} ] # Function to display the shop def shop(): clear_terminal() print_slow(Fore.YELLOW + r''' ██╗░░██╗░█████╗░░█████╗░██╗░░██╗███████╗██████╗░  ███╗░░░███╗░█████╗░██████╗░██╗░░██╗███████╗████████╗ ██║░░██║██╔══██╗██╔══██╗██║░██╔╝██╔════╝██╔══██╗  ████╗░████║██╔══██╗██╔══██╗██║░██╔╝██╔════╝╚══██╔══╝ ███████║███████║██║░░╚═╝█████═╝░█████╗░░██████╔╝  ██╔████╔██║███████║██████╔╝█████═╝░█████╗░░░░░██║░░░ ██╔══██║██╔══██║██║░░██╗██╔═██╗░██╔══╝░░██╔══██╗  ██║╚██╔╝██║██╔══██║██╔══██╗██╔═██╗░██╔══╝░░░░░██║░░░ ██║░░██║██║░░██║╚█████╔╝██║░╚██╗███████╗██║░░██║  ██║░╚═╝░██║██║░░██║██║░░██║██║░╚██╗███████╗░░░██║░░░ ╚═╝░░╚═╝╚═╝░░╚═╝░╚════╝░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝  ╚═╝░░░░░╚═╝╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚═╝╚══════╝░░░╚═╝░░░''' + Style.RESET_ALL) print_slow(Fore.YELLOW + "\nWelcome to the Hacker's Market!" + Style.RESET_ALL) print_slow("") print_slow(Fore.YELLOW + "Here you can buy upgrades to improve your hacking abilities.\n" + Style.RESET_ALL) while True: # Display the list of available upgrades for i, upgrade in enumerate(upgrades): print_slow( Fore.YELLOW + f"\n{upgrade['name']} - {upgrade['description']} - £{upgrade['price']}" + Style.RESET_ALL) # Get the user's choice command = input(Fore.YELLOW + "\n> " + Style.RESET_ALL) # Buy the chosen upgrade if command.lower() == 'exit': print_slow(Fore.YELLOW + "\nExiting Hacker's Market" + Style.RESET_ALL) time.sleep(1) clear_terminal() start_game() elif command.lower() == 'help': shop_help() elif command.lower().startswith('buy '): upgrade_name = command[4:] # [4:] removes first 4 characters if has_item('EnigmaLink'): if upgrade_name.lower() == 'enigmalink': print_slow("") print_slow(Fore.RED + "Sold Out" + Style.RESET_ALL) time.sleep(1) clear_terminal() shop() else: for upgrade in upgrades: if upgrade_name.lower() == upgrade['name'].lower(): if get_balance() >= upgrade['price']: print_slow("") print_slow( Fore.GREEN + f"You have successfully purchased {upgrade['name']} for ${upgrade['price']}!" + Style.RESET_ALL) subtract_money(upgrade['price']) print_slow("") print_balance() add_to_inventory(upgrade['name']) time.sleep(2) clear_terminal() # Check if the purchased upgrade is CodeShatter if upgrade_name.lower() == 'codeshatter': print_slow("") print_slow(Fore.GREEN + "Incoming Call..." + Style.RESET_ALL) input(Fore.GREEN + "> " + Style.RESET_ALL) code_shatter_call() shop() else: clear_terminal() shop() else: print_slow( Fore.RED + "You don't have enough money to buy this upgrade." + Style.RESET_ALL) time.sleep(1) clear_terminal() shop() else: print_slow(Fore.RED + "Invalid choice, please try again." + Style.RESET_ALL) time.sleep(1) clear_terminal() shop() else: for upgrade in upgrades: if upgrade_name.lower() == upgrade['name'].lower(): if get_balance() >= upgrade['price']: print_slow("") print_slow( Fore.GREEN + f"You have successfully purchased {upgrade['name']} for ${upgrade['price']}!" + Style.RESET_ALL) subtract_money(upgrade['price']) print_slow("") print_balance() add_to_inventory(upgrade['name']) time.sleep(2) clear_terminal() shop() else: print_slow( Fore.RED + "You don't have enough money to buy this upgrade." + Style.RESET_ALL) shop() else: print_slow(Fore.RED + "Invalid choice, please try again." + Style.RESET_ALL) time.sleep(1) clear_terminal() shop() # Function to start the game def start_game(): global has_intro_call, has_started_game, seen_markus if has_intro_call: clear_terminal() pass else: print_slow("\nStarting game...") time.sleep(1) print_slow("\nLoading assets...") time.sleep(1) clear_terminal() print_slow(Fore.GREEN + "Incoming Call..." + Style.RESET_ALL) input(Fore.GREEN + "> " + Style.RESET_ALL) intro_call() has_intro_call = True has_started_game = True print_slow(Fore.MAGENTA + "\nHint: Type 'help' to get a list of available commands." + Style.RESET_ALL) pass if seen_markus: print_slow(Fore.GREEN + "Incoming Call..." + Style.RESET_ALL) input(Fore.GREEN + "> " + Style.RESET_ALL) markus_seen_call() else: pass # Game command loop command = input(Fore.GREEN + "> " + Style.RESET_ALL) # Connect to the network if command.lower() == "connect": connect() # Access the mail system elif command.lower() == "mail": mail() # Display help message elif command.lower() == "help": help_user() # Check balance elif command.lower() == "balance": print_balance() # Enter shop elif command.lower() == "shop": shop() # Clear terminal elif command.lower() == "clear": clear_terminal() # Return to the main menu elif command.lower() == "exit": print_slow("Returning to Main Menu...") time.sleep(1) main() else: print_slow("Invalid command, please try again.") time.sleep(1) clear_terminal() start_game() # Save the game state save_game() # Function to check if an item is in the inventory def has_item(item): return item in inventory def scan(): print_slow("") print_slow(Fore.YELLOW + "Scanning network..." + Style.RESET_ALL) time.sleep(2) print_slow("") print_slow(Fore.YELLOW + "\nAvailable Systems:" + Style.RESET_ALL) print_slow("") for system in all_systems: if system['level'] == player_level: print_slow("") print_slow(f"{system['name']} ({system['type']})") print_slow("") def getpass_star(prompt="Password: "): print(prompt, end='', flush=True) password = [] while True: char = msvcrt.getch().decode('utf-8') if char == '\r' or char == '\n': break elif char == '\b': # Backspace if password: password.pop() print('\b \b', end='', flush=True) else: password.append(char) print('*', end='', flush=True) print() # Move to the next line return ''.join(password) def hack(system_name): global seen_markus # Find the system in the all_systems list system = next((s for s in all_systems if s['name'].lower() == system_name.lower()), None) if system: if system['level'] == player_level: # Check for CodeShatter before prompting for password if system['name'] == 'Markus' and has_item("CodeShatter"): clear_terminal() code_shatter_minigame() print_slow("Password Cracked: 735@&!//") input("Press [Enter] to continue") clear_terminal() markus_system_command_loop(markus_system) add_level(player_level) remove_from_inventory(item="CodeShatter") seen_markus = True elif system['name'] == 'Lobby Camera' and has_item("EyeSpy"): port_scanning() add_level(player_level) camera_first() else: # Prompt the user for the password print_slow("") password = getpass_star("Enter password: ") print_slow("") if password == system['password']: print_slow("") print_slow(Fore.GREEN + "Access granted!" + Style.RESET_ALL) if system['name'] == 'Amy': amy_system_command_loop(amy_system) elif system['name'] == 'Billy': billy_system_command_loop(billy_system) elif system['name'] == 'Markus': markus_system_command_loop(markus_system) add_level(player_level) seen_markus = True elif system['name'] == 'Lobby Camera': camera_first() elif system['name'] == 'Kyle': # Implement Kyle System else: # Add more conditions for other systems pass else: print_slow("") print_slow(Fore.RED + "Access denied! Incorrect password." + Style.RESET_ALL) else: print_slow("") print_slow(Fore.RED + "System not found! Please try again." + Style.RESET_ALL) else: print_slow("") print_slow(Fore.RED + "System not found! Please try again." + Style.RESET_ALL) def list_emails(emails): print_slow(Fore.LIGHTBLUE_EX + "\nEmails:" + Style.RESET_ALL) for i, email in enumerate(emails): print_slow(Fore.LIGHTBLUE_EX + f"\n{email['subject']} - From: {email['sender']}" + Style.RESET_ALL) def read_email(emails, subject): global has_read_email, evidence global balance email_found = False for email in emails: if email['subject'].lower() == subject.lower(): email_found = True print_slow( Fore.LIGHTBLUE_EX + f"\nFrom: {email['sender']}\nSubject: {email['subject']}\n\n{email['body']}" + Style.RESET_ALL) # Check if the email is one of the specific emails that increases evidence count if email['subject'].lower() in ["project update"]: evidence_item = 3 if not has_evidence(evidence_item): print_slow("Adding evidence to the list...") print_slow("") print_slow(Fore.GREEN + "Evidence Secured" + Style.RESET_ALL) add_evidence(evidence_item) print_slow("") print_slow("") time.sleep(3) print_slow(Fore.GREEN + "Incoming Call..." + Style.RESET_ALL) input(Fore.GREEN + "> " + Style.RESET_ALL) third_call() if email['subject'].lower() in ["professional development"]: evidence_item = 2 if not has_evidence(evidence_item): print_slow("Adding evidence to the list...") print_slow("") print_slow(Fore.GREEN + "Evidence Secured" + Style.RESET_ALL) add_evidence(evidence_item) print_slow("") print_slow("") time.sleep(3) print_slow(Fore.GREEN + "Incoming Call..." + Style.RESET_ALL) input(Fore.GREEN + "> " + Style.RESET_ALL) second_call() if email['subject'].lower() == "can't stop thinking about you" and email['sender'].lower() == 'amy': evidence_item = 1 if not has_evidence(evidence_item): print_slow("Adding evidence to the list...") print_slow("") print_slow(Fore.GREEN + "Evidence Secured" + Style.RESET_ALL) add_evidence(evidence_item) print_slow("") print_slow("") time.sleep(3) print_slow(Fore.GREEN + "Incoming Call..." + Style.RESET_ALL) input(Fore.GREEN + "> " + Style.RESET_ALL) first_call() if email['subject'].lower() == "upcoming software update" and email['sender'].lower() == 'markus': evidence_item = 6 if not has_evidence(evidence_item): print_slow("Adding evidence to the list...") print_slow("") print_slow(Fore.GREEN + "Evidence Secured" + Style.RESET_ALL) add_evidence(evidence_item) print_slow("") print_slow("") time.sleep(3) print_slow(Fore.GREEN + "Incoming Call..." + Style.RESET_ALL) input(Fore.GREEN + "> " + Style.RESET_ALL)
sixth_call()
13
2023-11-06 09:52:13+00:00
24k
ziqi-zhang/TAOISM
python/test/test_conv.py
[ { "identifier": "register_layer", "path": "python/common_net.py", "snippet": "def register_layer(layer, name):\n layer.register_forward_hook(hooking_layer(name))\n layer.register_backward_hook(hooking_layer_backward(name))\n layer_names.append(name)" }, { "identifier": "register_weight_layer", "path": "python/common_net.py", "snippet": "def register_weight_layer(layer, name):\n register_layer(layer, name)\n layer_weight[name] = layer.weight\n linear_layer_names.append(name)" }, { "identifier": "get_layer_weight", "path": "python/common_net.py", "snippet": "def get_layer_weight(name):\n return layer_weight[name]" }, { "identifier": "get_layer_input", "path": "python/common_net.py", "snippet": "def get_layer_input(name):\n return layer_input[name]" }, { "identifier": "get_layer_weight_grad", "path": "python/common_net.py", "snippet": "def get_layer_weight_grad(name):\n return layer_weight[name].grad.data" }, { "identifier": "get_layer_output", "path": "python/common_net.py", "snippet": "def get_layer_output(name):\n return layer_output[name]" }, { "identifier": "get_layer_output_grad", "path": "python/common_net.py", "snippet": "def get_layer_output_grad(name):\n return layer_output_grad[name]" }, { "identifier": "get_layer_input_grad", "path": "python/common_net.py", "snippet": "def get_layer_input_grad(name):\n return layer_input_grad[name]" }, { "identifier": "GlobalTensor", "path": "python/enclave_interfaces.py", "snippet": "class GlobalTensor(object):\n cpu_tensor = {}\n gpu_tensors = {}\n encrypted_tensors = {}\n LinkedTags = {}\n InverseLinkedTags = {}\n IsInitEnclaveTensor = {}\n EnclaveInterface = None\n eid = None\n is_init_global_tensor = False\n\n @staticmethod\n def init():\n if GlobalTensor.is_init_global_tensor:\n return\n GlobalTensor.EnclaveInterface = EnclaveInterface()\n GlobalTensor.EnclaveInterface.init_enclave()\n GlobalTensor.is_init_global_tensor = True\n\n @staticmethod\n def destroy():\n GlobalTensor.EnclaveInterface.destroy_enclave()\n\n GlobalTensor.cpu_tensor = {}\n GlobalTensor.gpu_tensors = {}\n GlobalTensor.encrypted_tensors = {}\n GlobalTensor.LinkedTags = {}\n GlobalTensor.InverseLinkedTags = {}\n GlobalTensor.IsInitEnclaveTensor = {}\n GlobalTensor.EnclaveInterface = None\n GlobalTensor.eid = None\n GlobalTensor.is_init_global_tensor = False\n\n\n @staticmethod\n def get_eid():\n return GlobalTensor.EnclaveInterface.get_eid()\n\n @staticmethod\n def link_tags(tag1, tag2):\n if tag1 == tag2:\n return\n\n friends = []\n\n def add_friends(tag):\n nonlocal friends\n if tag in GlobalTensor.LinkedTags:\n its_leader_tag = GlobalTensor.LinkedTags[tag]\n if its_leader_tag in GlobalTensor.InverseLinkedTags:\n friends += GlobalTensor.InverseLinkedTags.pop(its_leader_tag)\n else:\n friends += [tag]\n\n add_friends(tag1)\n add_friends(tag2)\n leader_tag = min(friends)\n\n GlobalTensor.InverseLinkedTags[leader_tag] = friends\n for t in friends:\n if t in GlobalTensor.IsInitEnclaveTensor:\n raise ValueError(\"Tags must linked before tensor initialization\")\n GlobalTensor.LinkedTags[t] = leader_tag\n\n @staticmethod\n def get_remapped_tags(tag):\n return GlobalTensor.LinkedTags[tag] if tag in GlobalTensor.LinkedTags else tag\n\n @staticmethod\n def set_cpu(tag, tensor):\n GlobalTensor.cpu_tensor[tag] = tensor.to(torch.device(\"cpu\"))\n\n @staticmethod\n def set_gpu(tag, tensor):\n GlobalTensor.gpu_tensors[tag] = tensor\n\n @staticmethod\n def set_encrypted(tag, tensor):\n GlobalTensor.encrypted_tensors[tag] = tensor\n\n @staticmethod\n def get_cpu(tag):\n return GlobalTensor.cpu_tensor[tag]\n\n @staticmethod\n def get_gpu(tag):\n return GlobalTensor.gpu_tensors[tag]\n\n @staticmethod\n def get_encryption(tag):\n return GlobalTensor.encrypted_tensors[tag]\n\n @staticmethod\n def init_enclave_tensor(tag, size):\n size = list(size)\n if len(size) < 4:\n size = [1] * (4 - len(size)) + size\n remapped_tag = GlobalTensor.get_remapped_tags(tag)\n if remapped_tag in GlobalTensor.IsInitEnclaveTensor:\n return\n else:\n GlobalTensor.IsInitEnclaveTensor[remapped_tag] = True\n eid = GlobalTensor.get_eid()\n GlobalTensor.EnclaveInterface.lib.InitTensor(eid, remapped_tag, size[0], size[1], size[2], size[3])\n\n @staticmethod\n def init_encrypted_tensor(tag, shape):\n GlobalTensor.encrypted_tensors[GlobalTensor.get_remapped_tags(tag)] = \\\n GlobalTensor.EnclaveInterface.create_encrypt_torch(shape)" }, { "identifier": "SecretBatchNorm2dLayer", "path": "python/layers/batch_norm_2d.py", "snippet": "class SecretBatchNorm2dLayer(SecretActivationLayer):\n # https://pytorch.org/docs/stable/nn.html#batchnorm2d\n\n BatchSize = None\n NumChannel = None\n ImgH = None\n ImgW = None\n WeightShape = None\n def __init__(\n self, sid, LayerName, EnclaveMode, link_prev=True, link_next=True,\n manually_register_prev=False, manually_register_next=False, merge_own_tensors=False\n ):\n \n super().__init__(\n sid, LayerName, EnclaveMode, link_prev, link_next, manually_register_prev, manually_register_next, merge_own_tensors\n )\n \n self.ForwardFuncName = \"BatchNorm2d\"\n self.BackwardFuncName = \"DerBatchNorm2d\"\n self.PlainFunc = torch.nn.BatchNorm2d\n self.IsAffine = True\n self.momentum = 0.1\n self.IsCumulative = (self.momentum is None)\n self.epsilon = 1e-5\n\n if EnclaveMode is ExecutionModeOptions.CPU or EnclaveMode is ExecutionModeOptions.GPU:\n self.ForwardFunc = torch.nn.BatchNorm2d\n # if self.is_enclave_mode:\n # self.StoreInEnclave = True\n # else:\n # self.ForwardFunc = torch.nn.BatchNorm2d\n # self.StoreInEnclave = False\n \n\n def init_shape(self):\n self.InputShape = self.PrevLayer.get_output_shape()\n self.OutputShape = self.InputShape\n self.BatchSize, self.NumChannel, self.ImgH, self.ImgW = self.InputShape\n self.WeightShape = [self.NumChannel]\n self.LearnableParamsList = [\n LearnableParamTuple(dw_name=\"DerWeight\", w_name=\"weight\", shape=self.WeightShape),\n LearnableParamTuple(dw_name=\"DerBias\", w_name=\"bias\", shape=self.WeightShape),\n ]\n \n\n # def init(self, start_enclave=True):\n \n # if self.sid == 2:\n # return\n # TensorLoader.init(self, start_enclave)\n\n # if self.is_enclave_mode:\n # self.PlainFunc = self.PlainFunc(self.InputShape[1])\n # self.PlainFunc.eval()\n # self.get_cpu(\"weight\").data.copy_(self.PlainFunc.weight.data)\n # self.get_cpu(\"bias\").data.copy_(self.PlainFunc.bias.data)\n # self.get_cpu(\"RunMean\").data.copy_(self.PlainFunc.running_mean.data)\n # # inject sqrt(running_var) instead of running_var for precision\n # self.get_cpu(\"RunVar\").data.copy_(self.PlainFunc.running_var.data)\n # self.transfer_cpu_to_enclave(\"weight\")\n # self.transfer_cpu_to_enclave(\"bias\")\n # self.transfer_cpu_to_enclave(\"RunMean\")\n # self.transfer_cpu_to_enclave(\"RunVar\")\n # self.batchnorm_init(\n # self.LayerName,\n # \"input\", \"output\", \"weight\", \"bias\",\n # \"DerInput\", \"DerOutput\", \"DerWeight\", \"DerBias\",\n # \"RunMean\", \"RunVar\", \"CurMean\", \"CurVar\",\n # \"mu\",\n # self.BatchSize, self.NumChannel, self.ImgH, self.ImgW,\n # int(self.IsAffine), int(self.IsCumulative), self.momentum, self.epsilon)\n # else:\n # self.ForwardFunc = self.ForwardFunc(self.InputShape[1])\n # self.PlainFunc = self.PlainFunc(self.InputShape[1])\n # self.PlainFunc.eval()\n # self.ForwardFunc.weight.data.copy_(self.PlainFunc.weight.data)\n # self.ForwardFunc.bias.data.copy_(self.PlainFunc.bias.data)\n # self.ForwardFunc.running_mean.data.copy_(self.PlainFunc.running_mean.data)\n # self.ForwardFunc.running_var.data.copy_(self.PlainFunc.running_var.data)\n # self.set_cpu(\"weight\", list(self.ForwardFunc.parameters())[0].data)\n # self.set_cpu(\"bias\", list(self.ForwardFunc.parameters())[1].data)\n # self.set_cpu(\"RunMean\", self.ForwardFunc.running_mean.data)\n # self.set_cpu(\"RunVar\", self.ForwardFunc.running_var.data)\n # self.ForwardFunc.eval()\n\n def init(self, start_enclave=True):\n # if self.LayerName == \"Layer3.10.proxies.0.bn2\":\n # st()\n TensorLoader.init(self, start_enclave)\n\n if self.EnclaveMode is ExecutionModeOptions.Enclave:\n self.PlainFunc = self.PlainFunc(self.InputShape[1])\n self.PlainFunc.eval()\n self.get_cpu(\"weight\").data.copy_(self.PlainFunc.weight.data)\n self.get_cpu(\"bias\").data.copy_(self.PlainFunc.bias.data)\n self.get_cpu(\"RunMean\").data.copy_(self.PlainFunc.running_mean.data)\n # inject sqrt(running_var) instead of running_var for precision\n self.get_cpu(\"RunVar\").data.copy_(self.PlainFunc.running_var.data)\n self.transfer_cpu_to_enclave(\"weight\")\n self.transfer_cpu_to_enclave(\"bias\")\n self.transfer_cpu_to_enclave(\"RunMean\")\n self.transfer_cpu_to_enclave(\"RunVar\")\n self.batchnorm_init(\n self.LayerName,\n \"input\", \"output\", \"weight\", \"bias\",\n # \"DerInput\", \"DerOutput\", \"DerWeight\", \"DerBias\",\n \"RunMean\", \"RunVar\", \"CurMean\", \"CurVar\",\n \"mu\",\n self.BatchSize, self.NumChannel, self.ImgH, self.ImgW,\n int(self.IsAffine), int(self.IsCumulative), self.momentum, self.epsilon)\n elif self.EnclaveMode is ExecutionModeOptions.CPU:\n self.ForwardFunc = self.ForwardFunc(self.InputShape[1])\n self.PlainFunc = self.PlainFunc(self.InputShape[1])\n self.PlainFunc.eval()\n self.ForwardFunc.weight.data.copy_(self.PlainFunc.weight.data)\n self.ForwardFunc.bias.data.copy_(self.PlainFunc.bias.data)\n self.ForwardFunc.running_mean.data.copy_(self.PlainFunc.running_mean.data)\n self.ForwardFunc.running_var.data.copy_(self.PlainFunc.running_var.data)\n self.set_cpu(\"weight\", list(self.ForwardFunc.parameters())[0].data)\n self.set_cpu(\"bias\", list(self.ForwardFunc.parameters())[1].data)\n self.set_cpu(\"RunMean\", self.ForwardFunc.running_mean.data)\n self.set_cpu(\"RunVar\", self.ForwardFunc.running_var.data)\n self.ForwardFunc.eval()\n elif self.EnclaveMode is ExecutionModeOptions.GPU:\n self.ForwardFunc = self.ForwardFunc(self.InputShape[1])\n self.PlainFunc = self.PlainFunc(self.InputShape[1])\n self.ForwardFunc.weight.data.copy_(self.PlainFunc.weight.data)\n self.ForwardFunc.bias.data.copy_(self.PlainFunc.bias.data)\n self.ForwardFunc.running_mean.data.copy_(self.PlainFunc.running_mean.data)\n self.ForwardFunc.running_var.data.copy_(self.PlainFunc.running_var.data)\n self.set_gpu(\"weight\", list(self.ForwardFunc.parameters())[0].data)\n self.set_gpu(\"bias\", list(self.ForwardFunc.parameters())[1].data)\n self.set_gpu(\"RunMean\", self.ForwardFunc.running_mean.data)\n self.set_gpu(\"RunVar\", self.ForwardFunc.running_var.data)\n self.PlainFunc.eval()\n self.ForwardFunc.cuda().eval()\n\n # def inject_params(self, params):\n # if self.sid == -2:\n # raise ValueError(\"S2 has no learnable parameters for injection\")\n # self.get_cpu(\"weight\").copy_(params.weight.data)\n # self.get_cpu(\"bias\").copy_(params.bias.data)\n # self.get_cpu(\"RunMean\").copy_(params.running_mean.data)\n # # inject sqrt(running_var) instead of running_var for precision\n # self.get_cpu(\"RunVar\").copy_(params.running_var.data)\n # if self.is_enclave_mode:\n # self.transfer_cpu_to_enclave(\"weight\")\n # self.transfer_cpu_to_enclave(\"bias\")\n # self.transfer_cpu_to_enclave(\"RunMean\")\n # self.transfer_cpu_to_enclave(\"RunVar\")\n\n def inject_params(self, params):\n if self.sid == -2:\n raise ValueError(\"S2 has no learnable parameters for injection\")\n if self.EnclaveMode in [ExecutionModeOptions.CPU, ExecutionModeOptions.Enclave]: \n self.get_cpu(\"weight\").copy_(params.weight.data)\n self.get_cpu(\"bias\").copy_(params.bias.data)\n self.get_cpu(\"RunMean\").copy_(params.running_mean.data)\n self.get_cpu(\"RunVar\").copy_(params.running_var.data)\n if self.EnclaveMode is ExecutionModeOptions.Enclave:\n self.transfer_cpu_to_enclave(\"weight\")\n self.transfer_cpu_to_enclave(\"bias\")\n self.transfer_cpu_to_enclave(\"RunMean\")\n self.transfer_cpu_to_enclave(\"RunVar\")\n elif self.EnclaveMode is ExecutionModeOptions.GPU:\n self.get_gpu(\"weight\").copy_(params.weight.data)\n self.get_gpu(\"bias\").copy_(params.bias.data)\n self.get_gpu(\"RunMean\").copy_(params.running_mean.data)\n self.get_gpu(\"RunVar\").copy_(params.running_var.data)\n\n def reset_plain_bn(self):\n # module = torch.BatchNorm2d()\n self.get_cpu(\"weight\").copy_(torch.ones(self.InputShape[1]))\n self.get_cpu(\"bias\").copy_(torch.zeros(self.InputShape[1]))\n self.get_cpu(\"RunMean\").copy_(torch.zeros(self.InputShape[1]))\n self.get_cpu(\"RunVar\").copy_(torch.ones(self.InputShape[1]))\n if self.EnclaveMode is ExecutionModeOptions.Enclave:\n self.transfer_cpu_to_enclave(\"weight\")\n self.transfer_cpu_to_enclave(\"bias\")\n self.transfer_cpu_to_enclave(\"RunMean\")\n self.transfer_cpu_to_enclave(\"RunVar\")\n\n\n def inject_to_plain(self, plain_layer: torch.nn.Module) -> None:\n raise NotImplementedError\n if self.sid == -2:\n raise ValueError(\"S2 has no learnable parameters for injection\")\n self.make_sure_cpu_is_latest(\"weight\")\n self.make_sure_cpu_is_latest(\"bias\")\n plain_layer.weight.data.copy_(self.get_cpu(\"weight\"))\n plain_layer.bias.data.copy_(self.get_cpu(\"bias\"))\n plain_layer.running_mean.data.copy_(self.get_cpu(\"RunMean\"))\n plain_layer.running_var.data.copy_(self.get_cpu(\"RunVar\"))\n\n def generate_tensor_name_list(self, force=False):\n if not force and self.tensor_name_list:\n return\n if self.sid == 2:\n self.tensor_name_list = {}\n return\n\n if self.EnclaveMode is ExecutionModeOptions.Enclave:\n NeededTensorNames = [\n (\"input\", self.InputShape, None),\n # (\"DerInput\", self.InputShape, None),\n (\"output\", self.OutputShape, None),\n # (\"DerOutput\", self.OutputShape, None),\n (\"weight\", self.WeightShape, None),\n # (\"DerWeight\", self.WeightShape, None),\n (\"bias\", self.WeightShape, None),\n # (\"DerBias\", self.WeightShape, None),\n (\"RunMean\", self.WeightShape, None),\n (\"CurMean\", self.WeightShape, None),\n (\"RunVar\", self.WeightShape, None),\n (\"CurVar\", self.WeightShape, None),\n (\"mu\", self.InputShape, None),\n ]\n else:\n NeededTensorNames = [\n (\"output\", self.OutputShape, None),\n # (\"DerInput\", self.InputShape, None),\n (\"input\", self.InputShape, None),\n (\"weight\", self.WeightShape, None),\n # (\"DerWeight\", self.WeightShape, None),\n (\"bias\", self.WeightShape, None),\n # (\"DerBias\", self.WeightShape, None),\n # (\"DerOutput\", self.OutputShape, None)\n ]\n\n self.tensor_name_list = NeededTensorNames\n\n # def forward(self):\n # if self.sid == 2:\n # return\n # with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} Forward\", verbose_level=VerboseLevel.LAYER):\n # if self.is_enclave_mode:\n # self.forward_tensor_transfer()\n # self.batchnorm_forward(self.LayerName, int(False))\n # else:\n # self.forward_tensor_transfer()\n # self.requires_grad_on_cpu(\"input\")\n # self.ForwardFunc.bias.data.copy_(self.get_cpu(\"bias\"))\n # self.ForwardFunc.weight.data.copy_(self.get_cpu(\"weight\"))\n # self.ForwardFunc.running_mean.data.copy_(self.get_cpu(\"RunMean\"))\n # # running_var of PlainFunc is ^2 of that in the enclave\n # enclave_running_var = self.get_cpu(\"RunVar\")\n # self.ForwardFunc.running_var.data.copy_(enclave_running_var)\n # self.set_cpu(\"output\", self.ForwardFunc(self.get_cpu(\"input\")))\n\n def forward(self):\n with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} Forward\", verbose_level=VerboseLevel.LAYER):\n if self.EnclaveMode == ExecutionModeOptions.Enclave:\n # if self.LayerName == \"Layer2.0.downsample.bn\":\n # st()\n with NamedTimerInstance(f\" S{self.sid}: {self.LayerName} Input Preprocess\", verbose_level=VerboseLevel.LAYER):\n self.forward_tensor_transfer()\n with NamedTimerInstance(f\" S{self.sid}: {self.LayerName} batchnorm_forward\", verbose_level=VerboseLevel.LAYER):\n self.batchnorm_forward(self.LayerName, int(False))\n elif self.EnclaveMode == ExecutionModeOptions.CPU:\n self.forward_tensor_transfer()\n self.ForwardFunc.bias.data.copy_(self.get_cpu(\"bias\"))\n self.ForwardFunc.weight.data.copy_(self.get_cpu(\"weight\"))\n self.ForwardFunc.running_mean.data.copy_(self.get_cpu(\"RunMean\"))\n # running_var of PlainFunc is ^2 of that in the enclave\n enclave_running_var = self.get_cpu(\"RunVar\")\n self.ForwardFunc.running_var.data.copy_(enclave_running_var)\n self.set_cpu(\"output\", self.ForwardFunc(self.get_cpu(\"input\")))\n elif self.EnclaveMode == ExecutionModeOptions.GPU:\n self.forward_tensor_transfer()\n self.ForwardFunc.bias.data.copy_(self.get_gpu(\"bias\"))\n self.ForwardFunc.weight.data.copy_(self.get_gpu(\"weight\"))\n self.ForwardFunc.running_mean.data.copy_(self.get_gpu(\"RunMean\"))\n # running_var of PlainFunc is ^2 of that in the enclave\n enclave_running_var = self.get_gpu(\"RunVar\")\n self.ForwardFunc.running_var.data.copy_(enclave_running_var)\n # st()\n # print(self.get_gpu(\"input\")[0,0,0])\n self.set_gpu(\"output\", self.ForwardFunc(self.get_gpu(\"input\").type(SecretConfig.dtypeForCpuOp)))\n\n def backward(self):\n raise NotImplementedError\n if self.sid == 2:\n return\n with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} Backward\", verbose_level=VerboseLevel.LAYER):\n if self.is_enclave_mode:\n self.backward_tensor_transfer()\n self.batchnorm_backward(self.LayerName)\n else:\n self.backward_tensor_transfer()\n BackwardInput, BackwardWeight, BackwardBias = self.get_cpu(\"output\").grad_fn(self.get_cpu(\"DerOutput\"))\n self.set_cpu(\"DerInput\", BackwardInput.data)\n self.set_cpu(\"DerWeight\", BackwardWeight.data)\n self.set_cpu(\"DerBias\", BackwardBias.data)\n if list(self.get_cpu(\"DerWeight\").shape) != self.WeightShape:\n real_shape = self.get_cpu(\"DerWeight\").shape\n ideal_shape = self.WeightShape\n raise ValueError(\n f\"DerWeight is not of shape self.AffineShape: real: {real_shape}, ideal: {ideal_shape}\")\n if list(self.get_cpu(\"DerBias\").shape) != self.WeightShape:\n raise ValueError(\"DerBias is not of shape self.AffineShape\")\n\n def plain_forward(self, NeedBackward=False):\n if self.sid == 2:\n return\n if self.EnclaveMode in [ExecutionModeOptions.Enclave, ExecutionModeOptions.GPU]:\n self.make_sure_cpu_is_latest(\"input\")\n self.make_sure_cpu_is_latest(\"bias\")\n self.make_sure_cpu_is_latest(\"weight\")\n self.requires_grad_on_cpu(\"input\")\n self.PlainFunc.bias.data.copy_(self.get_cpu(\"bias\"))\n self.PlainFunc.weight.data.copy_(self.get_cpu(\"weight\"))\n self.PlainFunc.running_mean.data.copy_(self.get_cpu(\"RunMean\"))\n # self.PlainFunc.running_var.data.copy_(self.get_cpu(\"RunVar\"))\n # running_var of PlainFunc is ^2 of that in the enclave\n enclave_running_var = self.get_cpu(\"RunVar\")\n self.PlainFunc.running_var.data.copy_(enclave_running_var)\n else:\n self.make_sure_cpu_is_latest(\"input\")\n self.requires_grad_on_cpu(\"input\")\n\n with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} PlainForward\"):\n torch.set_num_threads(1)\n self.PlainForwardResult = self.PlainFunc(self.get_cpu(\"input\"))\n torch.set_num_threads(4)\n\n def plain_backward(self):\n if self.sid == 2:\n return\n self.make_sure_cpu_is_latest(\"DerOutput\")\n GradFunction = self.PlainForwardResult.grad_fn\n with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} PlainBackward\"):\n torch.set_num_threads(1)\n self.PlainBackwardResult = GradFunction(self.get_cpu(\"DerOutput\"))\n torch.set_num_threads(4)\n\n def show_plain_error(self):\n if self.sid == 2:\n return\n self.make_sure_cpu_is_latest(\"output\")\n err = compare_expected_actual(self.PlainForwardResult, self.get_cpu(\"output\"), get_relative=True)\n print(f\"S{self.sid}: {self.LayerName} Forward Error: {err}\")\n\n if self.PlainBackwardResult is None:\n return\n if self.is_enclave_mode:\n self.make_sure_cpu_is_latest(\"DerInput\")\n self.make_sure_cpu_is_latest(\"DerWeight\")\n self.make_sure_cpu_is_latest(\"DerBias\")\n else:\n self.make_sure_cpu_is_latest(\"DerInput\")\n BackwardInput, BackwardWeight, BackwardBias = self.PlainBackwardResult\n err_input = compare_expected_actual(BackwardInput, self.get_cpu(\"DerInput\"), show_where_err=False, get_relative=True)\n err_weight = compare_expected_actual(BackwardWeight, self.get_cpu(\"DerWeight\"), show_where_err=False,\n get_relative=True)\n err_bias = compare_expected_actual(BackwardBias, self.get_cpu(\"DerBias\"))\n print(f\"S{self.sid}: {self.LayerName} Backward Error input: {err_input}, weight {err_weight}, bias: {err_bias}\")\n\n def show_plain_error_forward(self):\n if self.sid == 2:\n return\n self.make_sure_cpu_is_latest(\"output\")\n err = compare_expected_actual(self.PlainForwardResult, self.get_cpu(\"output\"), get_relative=False, show_values=False)\n print(f\"S{self.sid}: {self.LayerName} Forward Error: {err}\")" }, { "identifier": "SecretFlattenLayer", "path": "python/layers/flatten.py", "snippet": "class SecretFlattenLayer(SecretNonlinearLayer):\n batch_size = None\n n_features = None\n input_shape = None\n output_shape = None\n\n def __init__(\n self, sid, LayerName, EnclaveMode, link_prev=True, link_next=True,\n manually_register_prev=False, manually_register_next=False\n ):\n super().__init__(sid, LayerName, EnclaveMode, link_prev, link_next, manually_register_prev, manually_register_next)\n self.StoreInEnclave = False\n self.ForwardFuncName = \"Flatten\"\n self.BackwardFuncName = \"DerFlatten\"\n\n\n def init(self, start_enclave=True):\n super().init(start_enclave)\n self.ForwardFunc = lambda x: x.view(-1, self.n_features)\n self.PlainFunc = lambda x: x.view(-1, self.n_features)\n\n def init_shape(self):\n self.input_shape = self.PrevLayer.get_output_shape()\n if len(self.input_shape) != 4:\n return ValueError(\"The dimension of the tensor form prev. layer has to be 4D.\")\n\n self.batch_size = self.input_shape[0]\n self.n_features = self.input_shape[1] * self.input_shape[2] * self.input_shape[3]\n self.output_shape = [self.batch_size, self.n_features]\n\n def get_output_shape(self):\n return self.output_shape\n\n def generate_tensor_name_list(self, force=False):\n if not force and self.tensor_name_list:\n return\n if self.sid == 2:\n self.tensor_name_list = {}\n return\n\n NeededTensorNames = [(\"output\", self.output_shape, None),\n (\"input\", self.input_shape, None),\n (\"DerInput\", self.input_shape, None),\n (\"DerOutput\", self.output_shape, None)\n ]\n\n self.tensor_name_list = NeededTensorNames\n\n def forward(self):\n with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} Forward\", verbose_level=VerboseLevel.LAYER):\n if self.EnclaveMode == ExecutionModeOptions.Enclave:\n self.transfer_enclave_to_cpu(\"input\")\n self.set_cpu(\"output\", self.ForwardFunc(self.get_cpu(\"input\")))\n self.transfer_cpu_to_enclave(\"output\")\n elif self.EnclaveMode == ExecutionModeOptions.CPU:\n self.set_cpu(\"output\", self.ForwardFunc(self.get_cpu(\"input\")))\n elif self.EnclaveMode == ExecutionModeOptions.GPU:\n self.set_gpu(\"output\", self.ForwardFunc(self.get_gpu(\"input\")))\n\n # self.forward_tensor_transfer()\n # self.set_cpu(\"output\", self.ForwardFunc(self.get_cpu(\"input\")))\n\n def backward(self):\n with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} Backward\", verbose_level=VerboseLevel.LAYER):\n self.backward_tensor_transfer()\n self.set_cpu(\"DerInput\", self.get_cpu(\"DerOutput\").view(self.input_shape))\n\n def plain_forward(self, NeedBackward=False):\n self.requires_grad_on_cpu(\"input\")\n with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} PlainForward\"):\n self.PlainForwardResult = self.PlainFunc(self.get_cpu(\"input\"))\n\n def plain_backward(self):\n self.make_sure_cpu_is_latest(\"DerOutput\")\n GradFunction = self.PlainForwardResult.grad_fn\n with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} PlainBackward\"):\n self.PlainBackwardResult = GradFunction(self.get_cpu(\"DerOutput\"))\n\n def show_plain_error(self):\n if self.StoreInEnclave:\n self.transfer_enclave_to_cpu(\"output\")\n err = compare_expected_actual(self.PlainForwardResult, self.get_cpu(\"output\"))\n print(f\"S{self.sid}: {self.LayerName} Forward Error: {err}\")\n\n if self.PlainBackwardResult is None:\n return\n err = compare_expected_actual(self.PlainBackwardResult, self.get_cpu(\"DerInput\"), get_relative=True)\n print(f\"S{self.sid}: {self.LayerName} Backward Error {err}\")" }, { "identifier": "SecretInputLayer", "path": "python/layers/input.py", "snippet": "class SecretInputLayer(SecretNonlinearLayer):\n shape = None\n\n def __init__(\n self, sid, LayerName, input_shape, EnclaveMode, link_prev=True, link_next=True, \n manually_register_prev=False, manually_register_next=False\n ):\n super().__init__(sid, LayerName, EnclaveMode, link_prev, link_next, manually_register_prev, manually_register_next)\n self.shape = input_shape\n\n def link_tensors(self):\n gt.link_tags(self.get_tag(\"input\", remap=False), self.get_tag(\"output\", remap=False))\n super().link_tensors()\n\n def init_shape(self):\n return\n\n def set_input(self, tensor):\n self.set_tensor_cpu_gpu_enclave(\"input\", tensor)\n\n def get_output_shape(self):\n return self.shape\n\n def forward(self):\n return\n\n def backward(self):\n return\n\n def plain_forward(self):\n return\n\n def plain_backward(self):\n return\n\n def show_plain_error(self):\n return\n\n def print_connection_info(self):\n print(f\"{self.LayerName:30} shape{self.shape} output {self.NextLayer.LayerName:30}\")" }, { "identifier": "SecretMaxpool2dLayer", "path": "python/layers/maxpool2d.py", "snippet": "class SecretMaxpool2dLayer(SecretActivationLayer):\n def __init__(\n self, sid, LayerName, EnclaveMode, filter_hw, stride, padding, link_prev=True, link_next=True,\n manually_register_prev=False, manually_register_next=False\n ):\n super().__init__(sid, LayerName, EnclaveMode, link_prev, link_next, manually_register_prev, manually_register_next)\n self.ForwardFuncName = \"Maxpool2d\"\n self.BackwardFuncName = \"DerMaxpool2d\"\n self.filter_hw = filter_hw\n self.startmaxpool = False\n self.PlainFunc = torch.nn.MaxPool2d\n self.maxpoolpadding = padding\n self.stride = stride\n self.STORE_CHUNK_ELEM = 401408\n\n self.ForwardFunc = torch.nn.MaxPool2d\n\n if EnclaveMode == ExecutionModeOptions.Enclave :\n self.ForwardFunc = self.maxpoolfunc\n self.BackwardFunc = self.maxpoolbackfunc\n else:\n self.ForwardFunc = torch.nn.MaxPool2d\n\n def init_shape(self):\n self.InputShape = self.PrevLayer.get_output_shape()\n if len(self.InputShape) != 4:\n raise ValueError(\"Maxpooling2d apply only to 4D Tensor\")\n if self.InputShape[2] != self.InputShape[3]:\n raise ValueError(\"The input tensor has to be square images\")\n if self.InputShape[2] % self.stride != 0:\n raise ValueError(\"The input tensor needs padding for this filter size\")\n InputHw = self.InputShape[2]\n output_hw = InputHw // self.stride\n self.OutputShape = [self.InputShape[0], self.InputShape[1], output_hw, output_hw]\n self.HandleShape = self.InputShape\n # self.Shapefortranspose = [int(round(((self.InputShape[0] * self.InputShape[1] * self.InputShape[2] * self.InputShape[3])/262144)+1/2)), 262144, 1, 1]\n self.Shapefortranspose = [\n int(round(((self.InputShape[0] * self.InputShape[1] * self.InputShape[2] * self.InputShape[3])/self.STORE_CHUNK_ELEM)+1/2)), self.STORE_CHUNK_ELEM, 1, 1]\n\n\n def init(self, start_enclave=True):\n if self.EnclaveMode == ExecutionModeOptions.Enclave:\n self.PlainFunc = self.PlainFunc(self.filter_hw, self.stride, self.maxpoolpadding)\n TensorLoader.init(self, start_enclave)\n\n if self.startmaxpool is False:\n self.startmaxpool = True\n return self.maxpoolinit(self.LayerName, \"inputtrans\", \"outputtrans\")\n else:\n self.ForwardFunc = self.ForwardFunc(self.filter_hw, stride=self.stride, padding=self.maxpoolpadding)\n self.PlainFunc = self.PlainFunc(self.filter_hw, stride=self.stride, padding=self.maxpoolpadding)\n\n # TensorLoader.init(self, start_enclave)\n # self.ForwardFunc = self.ForwardFunc(self.filter_hw, stride=self.stride, padding=self.maxpoolpadding)\n # self.PlainFunc = self.PlainFunc(self.filter_hw, stride=self.stride, padding=self.maxpoolpadding)\n\n # TensorLoader.init(self, start_enclave)\n\n # def forward(self):\n # with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} Forward\", verbose_level=VerboseLevel.LAYER):\n # self.forward_tensor_transfer()\n # # self.requires_grad_on_cpu(\"input\")\n # if self.EnclaveMode == ExecutionModeOptions.Enclave:\n # self.set_gpu(\"output\", self.ForwardFunc(self.get_gpu(\"input\")))\n # st()\n\n # # if self.PrevLayer.EnclaveMode is not ExecutionModeOptions.Enclave:\n # # self.transfer_enclave_to_cpu(\"input\")\n # # if torch.sum(self.get_cpu(\"input\").abs()) == 0:\n # # raise RuntimeError(f\"{self.LayerName}: SGX input not load\")\n # # self.transfer_cpu_to_enclave(\"input\")\n # # self.transfer_enclave_to_cpu(\"input\")\n # # self.set_cpu(\"output\", self.ForwardFunc(self.get_cpu(\"input\")))\n # # self.transfer_cpu_to_enclave(\"output\")\n # elif self.EnclaveMode == ExecutionModeOptions.CPU:\n # if self.PrevLayer.EnclaveMode is not ExecutionModeOptions.CPU and torch.sum(self.get_cpu(\"input\").abs()) == 0:\n # raise RuntimeError(f\"{self.LayerName}: SGX input not load\")\n # self.set_cpu(\"output\", self.ForwardFunc(self.get_cpu(\"input\")))\n # elif self.EnclaveMode == ExecutionModeOptions.GPU:\n # if self.PrevLayer.EnclaveMode is not ExecutionModeOptions.GPU and torch.sum(self.get_gpu(\"input\").abs()) == 0:\n # raise RuntimeError(f\"{self.LayerName}: SGX input not load\")\n # self.set_gpu(\"output\", self.ForwardFunc(self.get_gpu(\"input\")))\n # else:\n # raise RuntimeError\n\n def maxpoolfunc(self, namein, nameout):\n # assume row_stride and col_stride are both None or both not None\n # assume row_pad and col_pad are both None or both not None\n # if self.LayerName == \"Layer3.0.proxies.2.maxpool\":\n # print(self.LayerName, \"Input: \", self.get_cpu(\"input\")[0,0,0,:10])\n output = self.maxpoolnew(self.LayerName, namein, nameout, self.InputShape, self.OutputShape[2], self.OutputShape[3],\n self.filter_hw, self.filter_hw, self.stride, self.stride, self.maxpoolpadding,\n self.maxpoolpadding)\n # if self.LayerName == \"Layer3.0.proxies.2.maxpool\":\n # self.transfer_enclave_to_cpu(\"output\")\n # print(self.LayerName, \"Output: \", self.get_cpu(\"output\")[0,0,0,:])\n # self.transfer_cpu_to_enclave(\"output\")\n return output\n\n def maxpoolbackfunc(self, nameout, namedout, namedin):\n return self.maxpoolback(self.LayerName, namedout, namedin, self.InputShape, self.OutputShape[2], self.OutputShape[3],\n self.filter_hw, self.filter_hw, self.row_stride, self.col_stride, self.maxpoolpadding,\n self.maxpoolpadding)" }, { "identifier": "SecretOutputLayer", "path": "python/layers/output.py", "snippet": "class SecretOutputLayer(SecretNonlinearLayer):\n TargetShape = None\n loss = 0\n\n def __init__(\n self, sid, LayerName, EnclaveMode, inference=False, link_prev=True, link_next=True, \n manually_register_prev=False, manually_register_next=False\n ):\n super().__init__(sid, LayerName, EnclaveMode, link_prev, link_next, manually_register_prev, manually_register_next)\n self.ForwardFunc = torch.nn.CrossEntropyLoss()\n self.PlainFunc = torch.nn.CrossEntropyLoss()\n self.EnclaveMode = ExecutionModeOptions.CPU\n self.inference = inference\n\n\n def init_shape(self):\n self.InputShape = self.PrevLayer.get_output_shape()\n self.OutputShape = [1]\n self.TargetShape = [self.InputShape[0]] # number of Minibatch\n\n def init(self, start_enclave=True):\n TensorLoader.init(self, start_enclave)\n\n def generate_tensor_name_list(self, force=False):\n if not force and self.tensor_name_list:\n return\n if self.sid == 2:\n self.tensor_name_list = {}\n return\n\n NeededTensorNames = [\n (\"output\", self.OutputShape, None),\n (\"DerInput\", self.InputShape, None),\n (\"input\", self.InputShape, None),\n (\"target\", self.TargetShape, None),\n ]\n\n self.tensor_name_list = NeededTensorNames\n\n def load_target(self, tensor):\n self.set_tensor_with_name(\"target\", tensor)\n\n def get_loss(self):\n return self.loss\n \n def get_prediction(self):\n self.forward_tensor_transfer(\"input\")\n if torch.sum(self.get_cpu(\"input\").abs()) == 0:\n raise RuntimeError(\"SGX input not load\")\n return self.get_cpu(\"input\")\n\n def forward(self):\n if not self.inference:\n with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} Forward\", verbose_level=VerboseLevel.LAYER):\n self.forward_tensor_transfer()\n self.set_cpu(\"input\", self.get_cpu(\"input\").detach())\n self.requires_grad_on_cpu(\"input\")\n self.set_cpu(\"output\", self.ForwardFunc(self.get_cpu(\"input\"), self.get_cpu(\"target\")))\n loss = self.get_cpu(\"output\").item()\n self.loss = loss\n\n def backward(self):\n with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} Backward\", verbose_level=VerboseLevel.LAYER):\n self.backward_tensor_transfer(transfer_tensor=\"output\")\n self.get_cpu(\"output\").backward()\n self.set_cpu(\"DerInput\", self.get_cpu(\"input\").grad)\n\n def plain_forward(self):\n if not self.inference:\n self.make_sure_cpu_is_latest(\"input\")\n self.set_cpu(\"input\", self.get_cpu(\"input\").detach())\n self.requires_grad_on_cpu(\"input\")\n with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} PlainForward\"):\n self.PlainForwardResult = self.PlainFunc(self.get_cpu(\"input\"), self.get_cpu(\"target\"))\n\n def plain_backward(self):\n self.make_sure_cpu_is_latest(\"output\")\n with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} PlainBackward\"):\n self.PlainForwardResult.backward()\n self.set_cpu(\"DerInput\", self.get_cpu(\"input\").grad)\n\n def show_plain_error(self):\n self.make_sure_cpu_is_latest(\"output\")\n err = compare_expected_actual(self.PlainForwardResult, self.get_cpu(\"output\"))\n print(f\"S{self.sid}: {self.LayerName} Forward Error: {err}\")\n\n if self.PlainBackwardResult is None:\n return\n self.make_sure_cpu_is_latest(\"DerInput\")\n\n err = compare_expected_actual(self.PlainBackwardResult, self.get_cpu(\"DerInput\"))\n print(f\"S{self.sid}: {self.LayerName} Backward Error {err}\")\n\n def print_connection_info(self):\n print(f\"{self.LayerName:30} shape{self.InputShape}{' ':30} input {self.PrevLayer.LayerName:30}\")" }, { "identifier": "SecretReLULayer", "path": "python/layers/relu.py", "snippet": "class SecretReLULayer(SecretActivationLayer):\n def __init__(\n self, sid, LayerName, EnclaveMode, link_prev=True, link_next=True,\n manually_register_prev=False, manually_register_next=False, merge_own_tensors=False\n ):\n super().__init__(\n sid, LayerName, EnclaveMode, link_prev, link_next,\n manually_register_prev, manually_register_next, merge_own_tensors\n )\n self.ForwardFuncName = \"ReLU\"\n self.BackwardFuncName = \"DerReLU\"\n self.PlainFunc = torch.nn.ReLU\n if self.EnclaveMode is ExecutionModeOptions.Enclave:\n self.ForwardFunc = self.relufunc\n self.BackwardFunc = self.relubackfunc\n elif self.EnclaveMode is ExecutionModeOptions.CPU:\n self.ForwardFunc = torch.nn.ReLU\n elif self.EnclaveMode is ExecutionModeOptions.GPU:\n self.ForwardFunc = torch.nn.ReLU\n\n # if self.is_enclave_mode:\n # self.ForwardFunc = self.relufunc\n # self.BackwardFunc = self.relubackfunc\n # self.StoreInEnclave = True\n # else:\n # self.ForwardFunc = torch.nn.ReLU\n # self.StoreInEnclave = False\n\n def init(self, start_enclave=True):\n super().init(start_enclave)\n self.PlainFunc = self.PlainFunc()\n # if not self.is_enclave_mode:\n if self.EnclaveMode is not ExecutionModeOptions.Enclave:\n self.ForwardFunc = self.ForwardFunc()\n\n def relufunc(self, namein, nameout):\n return self.relunew(namein, nameout, self.InputShape)\n\n def relubackfunc(self, nameout, namedout, namedin):\n return self.relubackward(nameout, namedout, namedin, self.InputShape)\n\n def show_plain_error_forward(self):\n if self.sid == 2:\n return\n self.make_sure_cpu_is_latest(\"output\")\n err = compare_expected_actual(self.PlainForwardResult, self.get_cpu(\"output\"), get_relative=False, show_values=False)\n print(f\"S{self.sid}: {self.LayerName} Forward Error: {err}\")" }, { "identifier": "init_communicate", "path": "python/sgx_net.py", "snippet": "def init_communicate(rank, master_address, master_port, backend='gloo'):\n os.environ['MASTER_ADDR'] = master_address\n os.environ['MASTER_PORT'] = master_port\n dist.init_process_group(backend, rank=rank, world_size=SecretConfig.worldSize)" }, { "identifier": "warming_up_cuda", "path": "python/sgx_net.py", "snippet": "def warming_up_cuda():\n device = torch.device(\"cuda:0\")\n # device = torch.device(\"cpu\")\n\n print(\"Execution device: \", device)\n print(\"PyTorch version: \", torch.__version__)\n print(\"CUDA version: \", torch.version.cuda)\n print(\"CUDA device:\", torch.cuda.get_device_name(0))\n\n batch_size, n_input_channel, n_output_channel, img_hw, filter_hw = 512, 512, 256, 4, 3\n x_shape = [batch_size, n_input_channel, img_hw, img_hw]\n w_shape = [n_output_channel, n_input_channel, filter_hw, filter_hw]\n with NamedTimerInstance(\"Warming up Cuda double\"):\n dummy_a = get_random_uniform(SecretConfig.PrimeLimit, x_shape).type(SecretConfig.dtypeForSave)\n dummy_b = get_random_uniform(SecretConfig.PrimeLimit, w_shape).type(SecretConfig.dtypeForSave)\n F.conv2d(dummy_a.cuda().type(SecretConfig.dtypeForCudaMm), dummy_b.cuda().type(SecretConfig.dtypeForCudaMm),\n padding=1)\n\n with NamedTimerInstance(\"Warming up Cuda dobule 2nd\"):\n F.conv2d(dummy_a.cuda().type(torch.double), dummy_b.cuda().type(torch.double),\n padding=1)\n\n with NamedTimerInstance(\"Warming up Cuda float\"):\n F.conv2d(dummy_a.cuda().type(torch.float), dummy_b.cuda().type(torch.float), padding=1)\n\n with NamedTimerInstance(\"Warming up Cuda float 2nd\"):\n F.conv2d(dummy_a.cuda().type(torch.float), dummy_b.cuda().type(torch.float), padding=1)\n\n batch_size, n_input_channel, n_output_channel, img_hw, filter_hw = 64, 64, 64, 8, 3\n x_shape = [batch_size, n_input_channel, img_hw, img_hw]\n w_shape = [n_output_channel, n_input_channel, filter_hw, filter_hw]\n with NamedTimerInstance(\"Warming up Cpu\"):\n dummy_a = get_random_uniform(SecretConfig.PrimeLimit, x_shape).type(SecretConfig.dtypeForSave)\n dummy_b = get_random_uniform(SecretConfig.PrimeLimit, w_shape).type(SecretConfig.dtypeForSave)\n F.conv2d(dummy_a.type(SecretConfig.dtypeForCpuOp), dummy_b.type(SecretConfig.dtypeForCpuOp),\n padding=1)\n\n with NamedTimerInstance(\"Warming up CppExtension\"):\n GlobalCppExtension.get_conv2d_cudnn()" }, { "identifier": "SecretNeuralNetwork", "path": "python/sgx_net.py", "snippet": "class SecretNeuralNetwork(TensorLoader):\n nn_name = None\n layers = None\n\n def __init__(self, sid, nn_name):\n super().__init__()\n self.sid = sid\n self.init(start_enclave=False)\n self.nn_name = nn_name\n\n def set_layers(self, layers):\n self.layers = layers\n\n if not isinstance(self.layers[0], SecretInputLayer):\n raise ValueError(\"The first layer has to be input layer\")\n if not isinstance(self.layers[-1], SecretOutputLayer):\n raise ValueError(\"The last layer has to be output layer\")\n \n for i in range(len(self.layers) - 1):\n PrevLayer = self.layers[i]\n NextLayer = self.layers[i + 1]\n if not PrevLayer.manually_register_next:\n PrevLayer.register_next_layer(NextLayer)\n if not NextLayer.manually_register_prev:\n NextLayer.register_prev_layer(PrevLayer)\n\n \n for layer in self.layers:\n # print(f\"Init_shape/link layer {layer.LayerName}\")\n layer.set_eid(self.get_eid())\n layer.init_shape()\n # if layer.LayerName in [\"Layer1.0.weighted_add\", \"Layer1.0.proxies.0.bn\"]:\n # st()\n layer.link_tensors()\n # print(layer.LayerName)\n # layer.print_tensor_link_relation()\n # if layer.LayerName in [\"Layer1.0.weighted_add\", \"Layer1.0.proxies.0.bn\"]:\n # st()\n \n for idx, layer in enumerate(self.layers):\n # print(f\"Init layer {layer.LayerName}\")\n # if layer.LayerName == \"Layer1.0.main.relu2\":\n # st()\n layer.init(start_enclave=False)\n # if idx > 3:\n # print(layer.LayerName, self.layers[4].get_cpu(\"input\").shape, self.layers[4].PrevLayer.LayerName)\n\n def execute_for_each_layer(self, func, reverse=False):\n layers = self.layers[::-1] if reverse else self.layers\n for layer in layers:\n # print(f\"SID: {self.sid} {layer.LayerName}, {func}\")\n if self.sid == 2 and layer.IsDummyForS2:\n continue\n # print(\"Processing \", layer.LayerName)\n func(layer)\n \n # st()\n\n def classifier_output(self):\n with NamedTimerInstance(f\"S{self.sid}: {self.nn_name} classifier_output\"):\n self.forward()\n if self.sid == 2:\n return\n # layers: input_layer, ..., fc_layer, output_layer\n last_fc = self.layers[-2]\n last_fc.transfer_enclave_to_cpu(\"output\")\n outputs = last_fc.get_cpu(\"output\")\n _, predicted = torch.max(outputs.data, 1)\n return predicted\n\n def get_loss(self):\n return self.layers[-1].get_loss()\n\n def forward_with_time(self):\n def run_forward(layer):\n layer.forward()\n t0 = time()\n with NetworkNamedTimerInstance(f\"S{self.sid}: {self.nn_name} Forward\"):\n self.execute_for_each_layer(run_forward)\n t1 = time()\n # time in ms\n elapse_time = (t1 - t0) * (10 ** 3) \n return elapse_time\n\n def forward(self):\n def run_forward(layer):\n layer.forward()\n with NetworkNamedTimerInstance(f\"S{self.sid}: {self.nn_name} Forward\"):\n self.execute_for_each_layer(run_forward)\n\n def backward(self):\n def run_backward(layer):\n layer.backward()\n with NamedTimerInstance(f\"S{self.sid}: {self.nn_name} Backward\"):\n self.execute_for_each_layer(run_backward, reverse=True)\n\n def plain_forward(self):\n with NetworkNamedTimerInstance(f\"S{self.sid}: {self.nn_name} PlainForward\"):\n self.execute_for_each_layer(lambda x: x.plain_forward())\n\n def plain_backward(self):\n with NetworkNamedTimerInstance(f\"S{self.sid}: {self.nn_name} PlainBackward\"):\n self.execute_for_each_layer(lambda x: x.plain_backward(), reverse=True)\n\n def show_plain_error(self):\n self.execute_for_each_layer(lambda x: x.show_plain_error())" }, { "identifier": "SgdOptimizer", "path": "python/sgx_net.py", "snippet": "class SgdOptimizer(TensorLoader):\n def __init__(self, sid):\n super().__init__()\n self.sid = sid\n self.learning_rate = 0.05\n self.momentum = 0.9\n self.weight_decay = 5e-4\n self.momentum_init_flags = defaultdict(lambda: False)\n self.ideal_momentum_buf = {}\n\n self.lr_gamma = 0.5\n self.lr_step = 30\n self.step_counter = 0\n\n self.layers = None\n\n def set_layers(self, layers):\n self.layers = layers\n\n def generate_tensor_name_list(self, force=False):\n # Run if forced or self.tensor_name_list is not generated\n if not force and self.tensor_name_list:\n return\n if self.sid == 2:\n return\n\n self.tensor_name_list = []\n for layer in self.layers:\n for (DerName, ParamName, shape) in layer.LearnableParamsList:\n self.tensor_name_list.append((ParamName + \"Momentum\", shape, None))\n\n def update_params(self, test_with_ideal=False):\n if self.sid == 2:\n return\n for layer in self.layers:\n self.update_params_in_layer(layer, test_with_ideal=test_with_ideal)\n\n def update_params_in_layer(self, layer, test_with_ideal=False):\n # ref: https://github.com/pytorch/pytorch/blob/master/torch/optim/sgd.py\n if layer.LearnableParamsList is None:\n return\n\n task_ids = []\n for (der_name, param_name, shape) in layer.LearnableParamsList:\n momentum_name = param_name + \"Momentum\"\n global_momentum_name = layer.name_modifier(momentum_name)\n\n if layer.StoreInEnclave:\n if test_with_ideal:\n ideal_p, ideal_momentum = self.ideal_update_params_with_name(layer, der_name, param_name, shape)\n first_momentum = not self.momentum_init_flags[global_momentum_name]\n if first_momentum:\n # print(\"FIRST MOMENTUM\")\n self.momentum_init_flags[global_momentum_name] = True\n layer.init_enclave_tensor(momentum_name, shape)\n task_id = layer.sgd_update(param_name=param_name, grad_name=der_name, momentum_name=momentum_name,\n lr=self.learning_rate, momentum=self.momentum,\n weight_decay=self.weight_decay,\n first_momentum=first_momentum, is_async=True)\n if test_with_ideal:\n while not self.get_task_status(task_id):\n pass\n layer.generate_cpu_tensor(momentum_name, shape)\n layer.transfer_enclave_to_cpu(momentum_name)\n layer.transfer_enclave_to_cpu(param_name)\n param_err = compare_expected_actual(ideal_p, layer.get_cpu(param_name), get_relative=True)\n print(f\"S{self.sid}: {layer.LayerName} Param Error: {param_err}\")\n momentum_err = compare_expected_actual(ideal_momentum, layer.get_cpu(momentum_name), get_relative=True)\n print(f\"S{self.sid}: {layer.LayerName} Momentum Error: {momentum_err}\")\n else:\n task_ids.append(task_id)\n else:\n DerCpu = layer.get_cpu(der_name)\n ParamsCpu = layer.get_cpu(param_name)\n\n if test_with_ideal:\n ideal_p, ideal_momentum = self.ideal_update_params_with_name(layer, der_name, param_name, shape)\n\n DerCpu.add_(self.weight_decay, ParamsCpu)\n\n if not self.momentum_init_flags[global_momentum_name]:\n self.momentum_init_flags[global_momentum_name] = True\n layer.generate_cpu_tensor(momentum_name, shape)\n layer.get_cpu(momentum_name).copy_(DerCpu)\n MomentumCpu = layer.get_cpu(momentum_name)\n else:\n MomentumCpu = layer.get_cpu(momentum_name)\n MomentumCpu.mul_(self.momentum).add_(1, DerCpu)\n\n ParamsCpu.add_(-self.learning_rate, MomentumCpu)\n\n if test_with_ideal:\n param_err = compare_expected_actual(ideal_p, layer.get_cpu(param_name), get_relative=True)\n print(f\"S{self.sid}: {layer.LayerName} Param Error: {param_err}\")\n momentum_err = compare_expected_actual(ideal_momentum, layer.get_cpu(momentum_name), get_relative=True)\n print(f\"S{self.sid}: {layer.LayerName} Momentum Error: {momentum_err}\")\n\n # Wait for all tasks to be finished\n for task_id in task_ids:\n while not self.get_task_status(task_id):\n pass\n\n def ideal_update_params_with_name(self, layer, der_name, param_name, shape):\n weight_decay = self.weight_decay\n momentum = self.momentum\n dampening = 0\n nesterov = False\n lr = self.learning_rate\n\n global_momentum_name = layer.name_modifier(param_name + 'Momentum')\n\n if layer.StoreInEnclave:\n layer.transfer_enclave_to_cpu(der_name)\n layer.transfer_enclave_to_cpu(param_name)\n d_p = torch.clone(layer.get_cpu(der_name)).detach()\n p = torch.clone(layer.get_cpu(param_name)).detach()\n\n if weight_decay != 0:\n d_p.add_(weight_decay, p)\n if global_momentum_name not in self.ideal_momentum_buf:\n buf = self.ideal_momentum_buf[global_momentum_name] = torch.clone(d_p).detach()\n else:\n buf = self.ideal_momentum_buf[global_momentum_name]\n buf.mul_(momentum).add_(1 - dampening, d_p)\n if nesterov:\n d_p = d_p.add(momentum, buf)\n else:\n d_p = buf\n p.add_(-lr, d_p)\n\n return p, buf" }, { "identifier": "SGXLinearBase", "path": "python/layers/sgx_linear_base.py", "snippet": "class SGXLinearBase(SecretLayerBase):\n batch_size = None\n InputShape = None\n WeightShape = None\n OutputShape = None\n\n def __init__(\n self, sid, LayerName, EnclaveMode, batch_size, n_output_features, \n n_input_features=None, is_enclave_mode=False, link_prev=True, link_next=True,\n manually_register_prev=False, manually_register_next=False\n ):\n super().__init__(sid, LayerName, EnclaveMode, link_prev, link_next, manually_register_prev, manually_register_next)\n\n self.ForwardFuncName = \"SGXLinear\"\n self.BackwardFuncName = \"DerSGXLinear\"\n self.PlainFunc = torch.nn.Linear\n self.is_enclave_mode = is_enclave_mode\n self.n_output_features = n_output_features\n self.n_input_features = n_input_features\n self.batch_size = batch_size\n\n if EnclaveMode is ExecutionModeOptions.CPU or EnclaveMode is ExecutionModeOptions.GPU:\n self.ForwardFunc = torch.nn.Linear\n # if self.is_enclave_mode:\n # self.StoreInEnclave = True\n # else:\n # self.ForwardFunc = torch.nn.Linear\n # self.StoreInEnclave = False\n\n def init_shape(self):\n self.WeightShape = self.DerWeightShape = [self.n_output_features, self.n_input_features]\n self.BiasShape = self.DerBiasShape = [self.n_output_features]\n if self.n_input_features is None:\n self.InputShape = self.PrevLayer.get_output_shape()\n else:\n self.InputShape = self.DerInputShape = [self.batch_size, self.n_input_features]\n self.OutputShape = self.DerOutputShape = [self.batch_size, self.n_output_features]\n self.LearnableParamsList = [\n LearnableParamTuple(dw_name=\"DerWeight\", w_name=\"weight\", shape=self.WeightShape),\n LearnableParamTuple(dw_name=\"DerBias\", w_name=\"bias\", shape=self.WeightShape),\n ]\n\n def init(self, start_enclave=True):\n TensorLoader.init(self, start_enclave)\n \n if self.EnclaveMode is ExecutionModeOptions.Enclave:\n self.PlainFunc = self.PlainFunc(self.n_input_features, self.n_output_features)\n self.get_cpu(\"weight\").data.copy_(self.PlainFunc.weight.data)\n self.get_cpu(\"bias\").data.copy_(self.PlainFunc.bias.data)\n self.transfer_cpu_to_enclave(\"weight\")\n self.transfer_cpu_to_enclave(\"bias\")\n self.sgx_linear_init(\n self.LayerName,\n \"input\", \"output\", \"weight\", \"bias\",\n # \"DerInput\", \"DerOutput\", \"DerWeight\", \"DerBias\",\n self.batch_size, self.n_input_features, self.n_output_features)\n else:\n self.ForwardFunc = self.ForwardFunc(self.n_input_features, self.n_output_features)\n self.PlainFunc = self.PlainFunc(self.n_input_features, self.n_output_features)\n self.ForwardFunc.weight.data.copy_(self.PlainFunc.weight.data)\n self.ForwardFunc.bias.data.copy_(self.PlainFunc.bias.data)\n if self.EnclaveMode is ExecutionModeOptions.CPU:\n self.set_cpu(\"weight\", list(self.ForwardFunc.parameters())[0].data)\n self.set_cpu(\"bias\", list(self.ForwardFunc.parameters())[1].data)\n elif self.EnclaveMode is ExecutionModeOptions.GPU:\n self.set_gpu(\"weight\", list(self.ForwardFunc.parameters())[0].data)\n self.set_gpu(\"bias\", list(self.ForwardFunc.parameters())[1].data)\n self.ForwardFunc.cuda()\n # print(\"======== SGX linear init finish\")\n\n def link_tensors(self):\n super().link_tensors()\n\n def init_params(self):\n cpu_w = torch.zeros(self.w_shape)\n torch.nn.init.xavier_normal_(cpu_w, 1)\n self.set_tensor_cpu_enclave(\"weight\", cpu_w)\n cpu_b = torch.zeros(self.b_shape)\n torch.nn.init.constant_(cpu_b, 0)\n self.set_tensor_cpu_enclave(\"bias\", cpu_b)\n\n def get_output_shape(self):\n return self.OutputShape\n\n def inject_params(self, params):\n if self.EnclaveMode is ExecutionModeOptions.Enclave:\n cpu_w = self.get_cpu(\"weight\")\n cpu_w.copy_(params.weight.data)\n self.transfer_cpu_to_enclave(\"weight\")\n cpu_b = self.get_cpu(\"bias\")\n cpu_b.copy_(params.bias.data)\n self.transfer_cpu_to_enclave(\"bias\")\n elif self.EnclaveMode is ExecutionModeOptions.CPU:\n cpu_w = self.get_cpu(\"weight\")\n cpu_w.copy_(params.weight.data)\n cpu_b = self.get_cpu(\"bias\")\n cpu_b.copy_(params.bias.data)\n elif self.EnclaveMode is ExecutionModeOptions.GPU:\n cpu_w = self.get_gpu(\"weight\")\n cpu_w.copy_(params.weight.data)\n cpu_b = self.get_gpu(\"bias\")\n cpu_b.copy_(params.bias.data)\n\n def inject_to_plain(self, plain_layer: torch.nn.Module) -> None:\n self.make_sure_cpu_is_latest(\"weight\")\n plain_layer.weight.data.copy_(self.get_cpu(\"weight\"))\n self.make_sure_cpu_is_latest(\"bias\")\n plain_layer.bias.data.copy_(self.get_cpu(\"bias\"))\n\n def generate_tensor_name_list(self, force=False):\n if not force and self.tensor_name_list:\n return\n NeededTensorNames = [(\"output\", self.OutputShape, None),\n # (\"DerInput\", self.InputShape, None),\n (\"input\", self.InputShape, None),\n # (\"DerOutput\", self.OutputShape, None),\n (\"weight\", self.WeightShape, None),\n (\"bias\", self.BiasShape, None),\n ]\n\n self.tensor_name_list = NeededTensorNames\n\n def forward(self):\n with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} Forward\", verbose_level=VerboseLevel.LAYER):\n if self.EnclaveMode is ExecutionModeOptions.Enclave:\n self.forward_tensor_transfer()\n self.sgx_linear_forward(self.LayerName)\n elif self.EnclaveMode == ExecutionModeOptions.CPU:\n self.forward_tensor_transfer()\n self.requires_grad_on_cpu(\"input\")\n self.ForwardFunc.weight.data.copy_(self.get_cpu(\"weight\"))\n self.ForwardFunc.bias.data.copy_(self.get_cpu(\"bias\"))\n self.set_cpu(\"output\", self.ForwardFunc(self.get_cpu(\"input\")))\n elif self.EnclaveMode == ExecutionModeOptions.GPU:\n self.forward_tensor_transfer()\n self.ForwardFunc.weight.data.copy_(self.get_gpu(\"weight\"))\n self.ForwardFunc.bias.data.copy_(self.get_gpu(\"bias\"))\n self.set_gpu(\"output\", self.ForwardFunc(self.get_gpu(\"input\").type(SecretConfig.dtypeForCpuOp)))\n\n def plain_forward(self, NeedBackward=False):\n if self.is_enclave_mode:\n self.make_sure_cpu_is_latest(\"input\")\n self.make_sure_cpu_is_latest(\"weight\")\n self.make_sure_cpu_is_latest(\"bias\")\n # self.requires_grad_on_cpu(\"input\")\n self.PlainFunc.weight.data.copy_(self.get_cpu(\"weight\"))\n self.PlainFunc.bias.data.copy_(self.get_cpu(\"bias\"))\n else:\n self.make_sure_cpu_is_latest(\"input\")\n self.requires_grad_on_cpu(\"input\")\n with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} PlainForward\"):\n # torch.set_num_threads(1)\n self.PlainForwardResult = self.PlainFunc(self.get_cpu(\"input\"))\n # torch.set_num_threads(4)\n\n def show_plain_error_forward(self):\n self.make_sure_cpu_is_latest(\"output\")\n err = compare_expected_actual(self.PlainForwardResult, self.get_cpu(\"output\"), get_relative=True)\n print(f\"S{self.sid}: {self.LayerName} Forward Error: {err}\")" }, { "identifier": "SGXConvBase", "path": "python/layers/sgx_conv_base.py", "snippet": "class SGXConvBase(SecretLayerBase):\n batch_size = None\n pytorch_x_shape, sgx_x_shape = None, None\n pytorch_w_shape, sgx_w_shape = None, None\n bias_shape = None\n pytorch_y_shape, sgx_y_shape = None, None\n\n def __init__(\n self, sid, LayerName, EnclaveMode,\n n_output_channel, filter_hw, stride, padding, batch_size=None, n_input_channel=None,\n img_hw=None, bias=True,\n is_enclave_mode=False, link_prev=True, link_next=True, manually_register_prev=False, manually_register_next=False\n ):\n super().__init__(sid, LayerName, EnclaveMode, link_prev, link_next, manually_register_prev, manually_register_next)\n\n self.ForwardFuncName = \"SGXConv\"\n self.BackwardFuncName = \"DerSGXConv\"\n self.PlainFunc = torch.nn.Conv2d\n self.is_enclave_mode = is_enclave_mode\n self.batch_size = batch_size\n self.n_input_channel = n_input_channel\n self.n_output_channel = n_output_channel\n self.img_hw = img_hw\n self.filter_hw = filter_hw\n self.padding = padding\n self.stride = stride\n self.bias = bias\n\n if EnclaveMode is ExecutionModeOptions.CPU or EnclaveMode is ExecutionModeOptions.GPU:\n self.ForwardFunc = torch.nn.Conv2d\n\n # --------------\n # Add BIAS!!!!!\n # --------------\n\n def init_shape(self):\n if self.batch_size is None and self.PrevLayer is not None:\n self.pytorch_x_shape = self.PrevLayer.get_output_shape()\n self.batch_size, self.n_input_channel, self.img_hw, _ = self.pytorch_x_shape\n else:\n self.pytorch_x_shape = [self.batch_size, self.n_input_channel, self.img_hw, self.img_hw]\n # print(self.LayerName)\n # st()\n # BHWC\n self.sgx_x_shape = [self.pytorch_x_shape[0], self.pytorch_x_shape[2], self.pytorch_x_shape[3], self.pytorch_x_shape[1]]\n # pytorch weight is out * in * h * w\n self.pytorch_w_shape = [self.n_output_channel, self.n_input_channel, self.filter_hw, self.filter_hw]\n # w shape is in * w * h * out, the transpose of out * h * w * in\n self.sgx_w_shape = [self.n_output_channel, self.filter_hw, self.filter_hw, self.n_input_channel]\n # BCHW\n self.pytorch_y_shape = calc_conv2d_output_shape_stride(self.pytorch_x_shape, self.pytorch_w_shape, self.padding, self.stride)\n # BHWC\n self.sgx_y_shape = [self.pytorch_y_shape[0], self.pytorch_y_shape[2], self.pytorch_y_shape[3], self.pytorch_y_shape[1]]\n self.bias_shape = [self.n_output_channel]\n\n # print(\n # f\"Init_shape pytorch_input {self.pytorch_x_shape}, sgx_input {self.sgx_x_shape}, \"\n # f\"pytorch_output {self.pytorch_y_shape}, sgx_output {self.sgx_y_shape}, \"\n # f\"pytorch_weight {self.pytorch_w_shape}, sgx_weight {self.sgx_w_shape}, \"\n # f\"bias {self.bias_shape}\"\n # )\n\n self.LearnableParamsList = [\n LearnableParamTuple(dw_name=\"DerWeight\", w_name=\"weight\", shape=self.sgx_w_shape),\n LearnableParamTuple(dw_name=\"DerBias\", w_name=\"bias\", shape=self.bias_shape),\n ]\n\n def init(self, start_enclave=True):\n # print(f\"Weight shape {self.sgx_w_shape}\")\n TensorLoader.init(self, start_enclave)\n \n \n if self.EnclaveMode is ExecutionModeOptions.Enclave:\n self.PlainFunc = self.PlainFunc(\n self.n_input_channel, self.n_output_channel, self.filter_hw,\n self.stride, self.padding, bias=self.bias)\n weight_pytorch_form = self.PlainFunc.weight.data\n weight_tf_form = self.weight_pytorch2tf(weight_pytorch_form)\n self.get_cpu(\"weight\").data.copy_(weight_tf_form)\n self.transfer_cpu_to_enclave(\"weight\")\n # Bias\n if self.bias:\n bias_data = self.PlainFunc.bias.data\n else:\n bias_data = torch.zeros(self.bias_shape)\n self.get_cpu(\"bias\").data.copy_(bias_data)\n self.transfer_cpu_to_enclave(\"bias\")\n self.sgx_conv_init(\n self.LayerName,\n \"sgx_input\", \"sgx_output\", \"weight\", \"bias\",\n # \"sgx_DerInput\", \"sgx_DerOutput\", \"DerWeight\", \"DerBias\",\n # \"input\", \"output\", \"weight\", \n # \"DerInput\", \"DerOutput\", \"DerWeight\", \n self.batch_size, self.img_hw, self.img_hw, self.n_input_channel, \n self.pytorch_y_shape[2], self.pytorch_y_shape[3], self.n_output_channel, \n self.filter_hw, self.padding, self.stride)\n elif self.EnclaveMode in[ ExecutionModeOptions.CPU, ExecutionModeOptions.GPU]:\n self.ForwardFunc = self.ForwardFunc(\n self.n_input_channel, self.n_output_channel, self.filter_hw,\n self.stride, self.padding, bias=self.bias)\n self.PlainFunc = self.PlainFunc(\n self.n_input_channel, self.n_output_channel, self.filter_hw,\n self.stride, self.padding, bias=self.bias)\n self.ForwardFunc.weight.data.copy_(self.PlainFunc.weight.data)\n weight_pytorch_form = list(self.ForwardFunc.parameters())[0].data\n weight_tf_form = self.weight_pytorch2tf(weight_pytorch_form)\n if self.EnclaveMode is ExecutionModeOptions.CPU:\n self.set_cpu(\"weight\", weight_tf_form)\n if self.bias:\n self.ForwardFunc.bias.data.copy_(self.PlainFunc.bias.data)\n bias_data = self.PlainFunc.bias.data\n self.set_cpu(\"bias\", bias_data)\n elif self.EnclaveMode is ExecutionModeOptions.GPU:\n self.set_gpu(\"weight\", weight_tf_form)\n if self.bias:\n self.ForwardFunc.bias.data.copy_(self.PlainFunc.bias.data)\n bias_data = self.PlainFunc.bias.data\n self.set_gpu(\"bias\", bias_data)\n self.ForwardFunc.cuda()\n\n\n def link_tensors(self):\n super().link_tensors()\n\n def init_params(self):\n cpu_w = torch.zeros(self.sgx_w_shape)\n torch.nn.init.xavier_normal_(cpu_w, 1)\n self.set_tensor_cpu_gpu_enclave(\"weight\", cpu_w)\n\n def get_output_shape(self):\n return self.pytorch_y_shape\n \n def weight_pytorch2tf(self, weight_pytorch_form):\n # weight_pytorch_form is out * in * h * w\n # out * (h * w) * in, \n # h and w dont transpose\n # weight_tf_form = weight_pytorch_form.permute(1,3,2,0).contiguous()\n weight_tf_form = weight_pytorch_form.permute(0,2,3,1).contiguous()\n return weight_tf_form\n\n def weight_tf2pytorch(self, weight_tf_form):\n # weight_tf_form is out * (h * w) * in, the transpose of out * (h * w) * in\n # out * in * h * w\n # h and w dont transpose\n # weight_pytorch_form = weight_tf_form.permute(3, 0, 2, 1).contiguous()\n weight_pytorch_form = weight_tf_form.permute(0,3,1,2).contiguous()\n return weight_pytorch_form\n\n def feature_pytorch2tf(self, tensor_pytorch_form):\n # tensor_pytorch_form is b * in * h * w\n # b * h * w * in\n tensor_tf_form = tensor_pytorch_form.permute(0, 2, 3, 1).contiguous()\n return tensor_tf_form\n \n def feature_tf2pytorch(self, tensor_tf_form):\n # tensor_tf_form is b * h * w * in\n # b * in * h * w\n tensor_pytorch_form = tensor_tf_form.permute(0, 3, 1, 2).contiguous()\n return tensor_pytorch_form\n\n def inject_params(self, params):\n if self.EnclaveMode is ExecutionModeOptions.Enclave:\n cpu_w = self.get_cpu(\"weight\")\n weight_pytorch_form = params.weight.data\n weight_tf_form = self.weight_pytorch2tf(weight_pytorch_form)\n cpu_w.copy_(weight_tf_form)\n self.transfer_cpu_to_enclave(\"weight\")\n\n # bias\n assert (\n (self.bias and params.bias is not None) or\n (not self.bias and params.bias is None)\n )\n if self.bias:\n bias_data = params.bias.data\n else:\n bias_data = torch.zeros(self.n_output_channel)\n cpu_b = self.get_cpu(\"bias\")\n cpu_b.copy_(bias_data)\n self.transfer_cpu_to_enclave(\"bias\")\n elif self.EnclaveMode is ExecutionModeOptions.CPU:\n weight_pytorch_form = params.weight.data\n weight_tf_form = self.weight_pytorch2tf(weight_pytorch_form)\n self.get_cpu(\"weight\").copy_(weight_tf_form)\n # bias\n assert (\n (self.bias and params.bias is not None) or\n (not self.bias and params.bias is None)\n )\n if self.bias:\n self.get_cpu(\"bias\").copy_(params.bias.data)\n\n # Move weight to ForwardFunc\n weight_tf_form = self.get_cpu(\"weight\")\n weight_pytorch_form = self.weight_tf2pytorch(weight_tf_form)\n self.ForwardFunc.weight.data.copy_(weight_pytorch_form)\n\n elif self.EnclaveMode is ExecutionModeOptions.GPU:\n weight_pytorch_form = params.weight.data\n weight_tf_form = self.weight_pytorch2tf(weight_pytorch_form)\n self.get_gpu(\"weight\").copy_(weight_tf_form)\n # bias\n assert (\n (self.bias and params.bias is not None) or\n (not self.bias and params.bias is None)\n )\n if self.bias:\n self.get_gpu(\"bias\").copy_(params.bias.data)\n\n # Move weight to ForwardFunc\n weight_tf_form = self.get_gpu(\"weight\")\n weight_pytorch_form = self.weight_tf2pytorch(weight_tf_form)\n self.ForwardFunc.weight.data.copy_(weight_pytorch_form)\n\n\n def inject_to_plain(self, plain_layer: torch.nn.Module) -> None:\n self.make_sure_cpu_is_latest(\"weight\")\n weight_tf_form = self.get_cpu(\"weight\")\n weight_pytorch_form = self.weight_tf2pytorch(weight_tf_form)\n plain_layer.weight.data.copy_(weight_pytorch_form)\n\n assert (\n (self.bias and plain_layer.bias is not None) or\n (not self.bias and plain_layer.bias is None)\n )\n if self.bias:\n self.make_sure_cpu_is_latest(\"bias\")\n bias_data = self.get_cpu(\"bias\")\n plain_layer.weight.data.copy_(bias_data)\n\n def generate_tensor_name_list(self, force=False):\n if not force and self.tensor_name_list:\n return\n NeededTensorNames = [(\"output\", self.pytorch_y_shape, None), (\"sgx_output\", self.sgx_y_shape, None),\n (\"DerInput\", self.pytorch_x_shape, None), (\"sgx_DerInput\", self.sgx_x_shape, None),\n (\"input\", self.pytorch_x_shape, None), (\"sgx_input\", self.sgx_x_shape, None),\n (\"DerOutput\", self.pytorch_y_shape, None), (\"sgx_DerOutput\", self.sgx_y_shape, None),\n (\"weight\", self.sgx_w_shape, None),\n (\"bias\", self.bias_shape, None),\n ]\n self.tensor_name_list = NeededTensorNames\n\n\n def forward(self):\n with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} Forward\", verbose_level=VerboseLevel.LAYER):\n self.forward_tensor_transfer(\"input\")\n if self.EnclaveMode == ExecutionModeOptions.Enclave:\n \n # \"input\" is pytorch form\n with NamedTimerInstance(f\" S{self.sid}: {self.LayerName} Input Preprocess\", verbose_level=VerboseLevel.LAYER):\n if self.PrevLayer.EnclaveMode is ExecutionModeOptions.Enclave:\n self.transfer_enclave_to_cpu(\"input\")\n input_pytorch_form = self.get_cpu(\"input\")\n \n if torch.sum(self.get_cpu(\"input\").abs()) == 0:\n print(self.LayerName)\n raise RuntimeError(\"SGX input not load\")\n input_tf_form = self.feature_pytorch2tf(input_pytorch_form)\n self.set_cpu(\"sgx_input\", input_tf_form)\n self.transfer_cpu_to_enclave(\"sgx_input\")\n # self.forward_tensor_transfer(\"sgx_input\")\n # print(self.get_cpu(\"sgx_input\").squeeze())\n \n with NamedTimerInstance(f\" S{self.sid}: {self.LayerName} sgx_conv_forward\", verbose_level=VerboseLevel.LAYER):\n # if self.LayerName == \"Layer2.0.downsample.conv\":\n # st()\n self.sgx_conv_forward(self.LayerName)\n \n with NamedTimerInstance(f\" S{self.sid}: {self.LayerName} Output Postprocess\", verbose_level=VerboseLevel.LAYER):\n self.make_sure_cpu_is_latest(\"sgx_output\")\n output_tf_form = self.get_cpu(\"sgx_output\")\n output_pytorch_form = self.feature_tf2pytorch(output_tf_form)\n self.set_cpu(\"output\", output_pytorch_form)\n self.transfer_cpu_to_enclave(\"output\")\n elif self.EnclaveMode == ExecutionModeOptions.CPU:\n with NamedTimerInstance(f\" S{self.sid}: {self.LayerName} Input Preprocess\", verbose_level=VerboseLevel.LAYER):\n self.forward_tensor_transfer()\n # self.requires_grad_on_cpu(\"input\")\n with NamedTimerInstance(f\" S{self.sid}: {self.LayerName} Weight Transfer\", verbose_level=VerboseLevel.LAYER):\n with NamedTimerInstance(f\" S{self.sid}: {self.LayerName} get weight_tf_form\", verbose_level=VerboseLevel.LAYER):\n weight_tf_form = self.get_cpu(\"weight\")\n with NamedTimerInstance(f\" S{self.sid}: {self.LayerName} weight_tf2pytorch\", verbose_level=VerboseLevel.LAYER):\n weight_pytorch_form = self.weight_tf2pytorch(weight_tf_form)\n with NamedTimerInstance(f\" S{self.sid}: {self.LayerName} copy data\", verbose_level=VerboseLevel.LAYER):\n self.ForwardFunc.weight.data.copy_(weight_pytorch_form)\n with NamedTimerInstance(f\" S{self.sid}: {self.LayerName} GPU conv forward\", verbose_level=VerboseLevel.LAYER):\n self.set_cpu(\"output\", self.ForwardFunc(self.get_cpu(\"input\")))\n elif self.EnclaveMode == ExecutionModeOptions.GPU:\n with NamedTimerInstance(f\" S{self.sid}: {self.LayerName} Input Preprocess\", verbose_level=VerboseLevel.LAYER):\n self.forward_tensor_transfer()\n # self.requires_grad_on_cpu(\"input\")\n with NamedTimerInstance(f\" S{self.sid}: {self.LayerName} Weight Transfer\", verbose_level=VerboseLevel.LAYER):\n with NamedTimerInstance(f\" S{self.sid}: {self.LayerName} get weight_tf_form\", verbose_level=VerboseLevel.LAYER):\n weight_tf_form = self.get_gpu(\"weight\")\n with NamedTimerInstance(f\" S{self.sid}: {self.LayerName} weight_tf2pytorch\", verbose_level=VerboseLevel.LAYER):\n weight_pytorch_form = self.weight_tf2pytorch(weight_tf_form)\n with NamedTimerInstance(f\" S{self.sid}: {self.LayerName} copy data\", verbose_level=VerboseLevel.LAYER):\n self.ForwardFunc.weight.data.copy_(weight_pytorch_form)\n with NamedTimerInstance(f\" S{self.sid}: {self.LayerName} GPU conv forward\", verbose_level=VerboseLevel.LAYER):\n self.set_gpu(\"output\", self.ForwardFunc(self.get_gpu(\"input\").type(SecretConfig.dtypeForCpuOp)))\n\n\n def plain_forward(self, NeedBackward=False):\n if self.EnclaveMode == ExecutionModeOptions.Enclave:\n self.make_sure_cpu_is_latest(\"input\")\n self.make_sure_cpu_is_latest(\"weight\")\n if self.bias:\n self.make_sure_cpu_is_latest(\"bias\")\n # self.requires_grad_on_cpu(\"input\")\n weight_tf_form = self.get_cpu(\"weight\")\n weight_pytorch_form = self.weight_tf2pytorch(weight_tf_form)\n self.PlainFunc.weight.data.copy_(weight_pytorch_form)\n if self.bias:\n bias_data = self.get_cpu(\"bias\")\n self.PlainFunc.bias.data.copy_(bias_data)\n elif self.EnclaveMode in [ExecutionModeOptions.CPU, ExecutionModeOptions.GPU]:\n self.make_sure_cpu_is_latest(\"input\")\n self.requires_grad_on_cpu(\"input\")\n with NamedTimerInstance(f\"S{self.sid}: {self.LayerName} PlainForward\"):\n # torch.set_num_threads(1)\n self.PlainForwardResult = self.PlainFunc(self.get_cpu(\"input\"))\n # torch.set_num_threads(4)\n\n def show_plain_error_forward(self):\n err = compare_expected_actual(self.PlainForwardResult, self.get_cpu(\"output\"), get_relative=True)\n print(f\"S{self.sid}: {self.LayerName} Forward Error: {err}\")\n\n def print_connection_info(self):\n print(f\"{self.LayerName:20} shape{self.pytorch_x_shape}{' ':20} mode{self.EnclaveMode}{' ':20} input {self.PrevLayer.LayerName:20} output {self.NextLayer.LayerName:20}\")" }, { "identifier": "ExecutionModeOptions", "path": "python/utils/basic_utils.py", "snippet": "class ExecutionModeOptions(Enum):\n Enclave = 1\n CPU = 2\n GPU = 3" }, { "identifier": "Logger", "path": "python/utils/logger_utils.py", "snippet": "class Logger(object):\n logfile_path = \"logfile.log\"\n\n def __init__(self):\n self.terminal = sys.stdout\n self.log = open(self.logfile_path, \"a\")\n\n def reset_logfile(self, path):\n self.logfile_path = path\n self.log = open(self.logfile_path, \"a\")\n\n def write(self, message):\n self.terminal.write(message)\n self.log.write(message)\n\n def flush(self):\n #this flush method is needed for python 3 compatibility.\n #this handles the flush command by doing nothing.\n #you might want to specify some extra behavior here.\n # pass\n self.terminal.flush()\n self.log.flush()" }, { "identifier": "NamedTimerInstance", "path": "python/utils/timer_utils.py", "snippet": "class NamedTimerInstance(object):\n def __init__(self, name, verbose_level=VerboseLevel.EVERY):\n self.name = name\n self.verbose_level = verbose_level\n\n def __enter__(self):\n return NamedTimer.start(self.name, verbose_level=self.verbose_level)\n ...\n\n def __exit__(self, *args):\n NamedTimer.end(self.name)\n ..." }, { "identifier": "VerboseLevel", "path": "python/utils/timer_utils.py", "snippet": "class VerboseLevel(IntEnum):\n EVERY = 1\n LAYER = 2\n RUN = 3\n EPOCH = 4" }, { "identifier": "NamedTimer", "path": "python/utils/timer_utils.py", "snippet": "class NamedTimer(object):\n __instance = None\n\n @staticmethod\n def get_instance():\n if NamedTimer.__instance is None:\n NamedTimer()\n return NamedTimer.__instance\n\n def __init__(self):\n NamedTimer.__instance = self\n self.timers = {}\n self.verbose_level = VerboseLevel.EVERY\n\n @staticmethod\n def start_timer(name, **kwargs):\n NamedTimer.get_instance().timers[name] = Timer(name, **kwargs)\n return NamedTimer.get_instance().timers[name]\n\n @staticmethod\n def start(name, **kwargs):\n return NamedTimer.get_instance().start_timer(name, **kwargs)\n\n @staticmethod\n def end_timer(name, **kwargs):\n NamedTimer.get_instance().timers[name].end(**kwargs)\n\n @staticmethod\n def end(name, tmp_name=None):\n # print(NamedTimer.get_instance().timers[name].verbose_level, NamedTimer.get_instance().verbose_level)\n NamedTimer.get_instance().end_timer(name, tmp_name=tmp_name)\n\n @staticmethod\n def set_verbose_level(verbose_level):\n if not isinstance(verbose_level, VerboseLevel):\n raise ValueError(\"Please set an enum from VerboseLevel\")\n NamedTimer.get_instance().verbose_level = verbose_level" }, { "identifier": "compare_expected_actual", "path": "python/utils/torch_utils.py", "snippet": "def compare_expected_actual(expected, actual, show_where_err=False, get_relative=False, verbose=False, show_values=False):\n def purify(x):\n # return torch.tensor(x)\n res = x\n # if not (isinstance(x, torch.Tensor) or isinstance(x, torch.Variable)):\n if not (isinstance(x, torch.Tensor) ):\n res = torch.tensor(x)\n # return x.detach().numpy()\n return res.type(torch.float).to(\"cpu\")\n expected = purify(expected)\n actual = purify(actual)\n\n if show_values:\n print(\"expected:\", expected[0, 0])\n print(\"actual:\", actual[0, 0])\n\n avg_abs_diff = torch.mean(torch.abs(expected - actual)).item()\n res = avg_abs_diff\n\n if show_where_err:\n show_indices = torch.abs(expected - actual) / torch.abs(expected) > 0.5\n # show_indices = (expected != actual)\n print(\"error indices: \", np.where(show_indices.cpu()))\n print(\"expected values:\", expected[show_indices])\n print(\"difference:\", (expected - actual)[show_indices])\n\n if get_relative:\n tmp_expected, tmp_actual = expected[expected != 0], actual[expected != 0]\n relative_diff = torch.abs(tmp_expected - tmp_actual) / torch.abs(tmp_expected)\n relative_avg_diff = torch.mean(torch.abs(tmp_actual - tmp_expected)) / torch.mean(torch.abs(tmp_expected))\n Error = namedtuple(\"Error\", (\"AvgAbsDiff\", \"RelAvgDiff\", \"AvgRelDiff\", \"StdRelDiff\"))\n res = Error(avg_abs_diff, relative_avg_diff.item(), torch.mean(relative_diff).item(), torch.std(relative_diff).item())\n\n if verbose:\n print(res)\n\n return res" } ]
import os import sys import numpy as np import torch import torch.distributed as dist import sys import pdb from pdb import set_trace as st from torch import optim, nn from python.common_net import register_layer, register_weight_layer, get_layer_weight, get_layer_input, \ get_layer_weight_grad, get_layer_output, get_layer_output_grad, get_layer_input_grad from python.enclave_interfaces import GlobalTensor from python.layers.batch_norm_2d import SecretBatchNorm2dLayer from python.layers.flatten import SecretFlattenLayer from python.layers.input import SecretInputLayer from python.layers.maxpool2d import SecretMaxpool2dLayer from python.layers.output import SecretOutputLayer from python.layers.relu import SecretReLULayer from python.sgx_net import init_communicate, warming_up_cuda, SecretNeuralNetwork, SgdOptimizer from python.layers.sgx_linear_base import SGXLinearBase from python.layers.sgx_conv_base import SGXConvBase from python.utils.basic_utils import ExecutionModeOptions from python.utils.logger_utils import Logger from python.quantize_net import NetQ from python.test_sgx_net import argparser_distributed, marshal_process, load_cifar10, seed_torch from python.utils.timer_utils import NamedTimerInstance, VerboseLevel, NamedTimer from python.utils.torch_utils import compare_expected_actual from pdb import set_trace as st
21,551
device_cuda = torch.device("cuda:0") torch.set_printoptions(precision=10) def compare_layer_member(layer: SGXLinearBase, layer_name: str, extract_func , member_name: str, save_path=None) -> None: print(member_name) layer.make_sure_cpu_is_latest(member_name) compare_expected_actual(extract_func(layer_name), layer.get_cpu(member_name), get_relative=True, verbose=True) if save_path is not None: if not os.path.exists(save_path): os.makedirs(save_path) print("Directory ", save_path, " Created ") else: print("Directory ", save_path, " already exists") torch.save(extract_func(layer_name), os.path.join(save_path, member_name + "_expected")) torch.save(layer.get_cpu(member_name), os.path.join(save_path, member_name + "_actual")) def compare_layer(layer: SGXLinearBase, layer_name: str, save_path=None) -> None: print("comparing with layer in expected NN :", layer_name) compare_name_function = [("input", get_layer_input), ("output", get_layer_output), ("DerOutput", get_layer_output_grad), ] if layer_name != "conv1": compare_name_function.append(("DerInput", get_layer_input_grad)) for member_name, extract_func in compare_name_function: compare_layer_member(layer, layer_name, extract_func, member_name, save_path=save_path) def compare_weight_layer(layer: SGXLinearBase, layer_name: str, save_path=None) -> None: compare_layer(layer, layer_name, save_path) compare_name_function = [("weight", get_layer_weight), ("DerWeight", get_layer_weight_grad) ] for member_name, extract_func in compare_name_function: compare_layer_member(layer, layer_name, extract_func, member_name, save_path=save_path) class ForkedPdb(pdb.Pdb): """A Pdb subclass that may be used from a forked multiprocessing child """ def interaction(self, *args, **kwargs): _stdin = sys.stdin try: sys.stdin = open('/dev/stdin') pdb.Pdb.interaction(self, *args, **kwargs) finally: sys.stdin = _stdin def test_conv( batch_size, img_hw, input_c, output_c, kernel, padding, stride, bias=False, set_values_to_one=False, sid=0 ): print("="*20, "TestConv", "="*20) print( f"batch {batch_size}, img_hw {img_hw}, input_c {input_c}, output_c {output_c}, " + f"kernel {kernel}, padding {padding}, stride {stride}" ) # def test_conv( # bias=False, set_values_to_one=True, # sid=0 # ): # batch_size = 128 # input_c = 3 # output_c = 64 # img_hw = 224 # kernel, padding, stride = 7, 3, 2 # batch_size = 128 # input_c = 512 # output_c = 512 # img_hw = 7 # kernel, padding, stride = 3, 1, 1 x_shape = [batch_size, input_c, img_hw, img_hw] GlobalTensor.init()
device_cuda = torch.device("cuda:0") torch.set_printoptions(precision=10) def compare_layer_member(layer: SGXLinearBase, layer_name: str, extract_func , member_name: str, save_path=None) -> None: print(member_name) layer.make_sure_cpu_is_latest(member_name) compare_expected_actual(extract_func(layer_name), layer.get_cpu(member_name), get_relative=True, verbose=True) if save_path is not None: if not os.path.exists(save_path): os.makedirs(save_path) print("Directory ", save_path, " Created ") else: print("Directory ", save_path, " already exists") torch.save(extract_func(layer_name), os.path.join(save_path, member_name + "_expected")) torch.save(layer.get_cpu(member_name), os.path.join(save_path, member_name + "_actual")) def compare_layer(layer: SGXLinearBase, layer_name: str, save_path=None) -> None: print("comparing with layer in expected NN :", layer_name) compare_name_function = [("input", get_layer_input), ("output", get_layer_output), ("DerOutput", get_layer_output_grad), ] if layer_name != "conv1": compare_name_function.append(("DerInput", get_layer_input_grad)) for member_name, extract_func in compare_name_function: compare_layer_member(layer, layer_name, extract_func, member_name, save_path=save_path) def compare_weight_layer(layer: SGXLinearBase, layer_name: str, save_path=None) -> None: compare_layer(layer, layer_name, save_path) compare_name_function = [("weight", get_layer_weight), ("DerWeight", get_layer_weight_grad) ] for member_name, extract_func in compare_name_function: compare_layer_member(layer, layer_name, extract_func, member_name, save_path=save_path) class ForkedPdb(pdb.Pdb): """A Pdb subclass that may be used from a forked multiprocessing child """ def interaction(self, *args, **kwargs): _stdin = sys.stdin try: sys.stdin = open('/dev/stdin') pdb.Pdb.interaction(self, *args, **kwargs) finally: sys.stdin = _stdin def test_conv( batch_size, img_hw, input_c, output_c, kernel, padding, stride, bias=False, set_values_to_one=False, sid=0 ): print("="*20, "TestConv", "="*20) print( f"batch {batch_size}, img_hw {img_hw}, input_c {input_c}, output_c {output_c}, " + f"kernel {kernel}, padding {padding}, stride {stride}" ) # def test_conv( # bias=False, set_values_to_one=True, # sid=0 # ): # batch_size = 128 # input_c = 3 # output_c = 64 # img_hw = 224 # kernel, padding, stride = 7, 3, 2 # batch_size = 128 # input_c = 512 # output_c = 512 # img_hw = 7 # kernel, padding, stride = 3, 1, 1 x_shape = [batch_size, input_c, img_hw, img_hw] GlobalTensor.init()
input_layer = SecretInputLayer(sid, "InputLayer", x_shape, ExecutionModeOptions.Enclave )
21
2023-11-01 10:37:37+00:00
24k
Codra-Ingenierie-Informatique/DataLab
cdl/tests/features/embedded1_unit.py
[ { "identifier": "_", "path": "cdl/config.py", "snippet": "CONF_VERSION = \"1.0.0\"\nAPP_NAME = \"DataLab\"\nMOD_NAME = \"cdl\"\nAPP_DESC = _(\"\"\"DataLab is a generic signal and image processing platform\"\"\")\nAPP_PATH = osp.dirname(__file__)\nDEBUG = os.environ.get(\"DEBUG\", \"\").lower() in (\"1\", \"true\")\nTEST_SEGFAULT_ERROR = len(os.environ.get(\"TEST_SEGFAULT_ERROR\", \"\")) > 0\nDATETIME_FORMAT = \"%d/%m/%Y - %H:%M:%S\"\nDATAPATH = configtools.get_module_data_path(MOD_NAME, \"data\")\nSHOTPATH = osp.join(\n configtools.get_module_data_path(MOD_NAME), os.pardir, \"doc\", \"images\", \"shots\"\n)\nOTHER_PLUGINS_PATHLIST = [configtools.get_module_data_path(MOD_NAME, \"plugins\")]\nIS_FROZEN = is_frozen(MOD_NAME)\nPLOTPY_DEFAULTS = {\n \"plot\": {\n # \"antialiasing\": False,\n # \"title/font/size\": 12,\n # \"title/font/bold\": False,\n # \"marker/curve/text/font/size\": 8,\n # \"marker/curve/text/font/family\": \"default\",\n # \"marker/curve/text/font/bold\": False,\n # \"marker/curve/text/font/italic\": False,\n \"marker/curve/text/textcolor\": \"black\",\n # \"marker/curve/text/background_color\": \"#ffffff\",\n # \"marker/curve/text/background_alpha\": 0.8,\n # \"marker/cross/text/font/family\": \"default\",\n # \"marker/cross/text/font/size\": 8,\n # \"marker/cross/text/font/bold\": False,\n # \"marker/cross/text/font/italic\": False,\n \"marker/cross/text/textcolor\": \"black\",\n # \"marker/cross/text/background_color\": \"#ffffff\",\n \"marker/cross/text/background_alpha\": 0.7,\n # \"marker/cross/line/style\": \"DashLine\",\n # \"marker/cross/line/color\": \"yellow\",\n # \"marker/cross/line/width\": 1,\n # \"marker/cursor/text/font/size\": 8,\n # \"marker/cursor/text/font/family\": \"default\",\n # \"marker/cursor/text/font/bold\": False,\n # \"marker/cursor/text/font/italic\": False,\n # \"marker/cursor/text/textcolor\": \"#ff9393\",\n # \"marker/cursor/text/background_color\": \"#ffffff\",\n # \"marker/cursor/text/background_alpha\": 0.8,\n \"shape/drag/symbol/marker\": \"NoSymbol\",\n \"shape/mask/symbol/size\": 5,\n \"shape/mask/sel_symbol/size\": 8,\n # -----------------------------------------------------------------------------\n # Annotated shape style for annotations:\n \"shape/annotation/line/style\": \"SolidLine\",\n \"shape/annotation/line/color\": \"#ffff00\",\n \"shape/annotation/line/width\": 1,\n \"shape/annotation/fill/style\": \"SolidPattern\",\n \"shape/annotation/fill/color\": MAIN_BG_COLOR,\n \"shape/annotation/fill/alpha\": 0.1,\n \"shape/annotation/symbol/marker\": \"Rect\",\n \"shape/annotation/symbol/size\": 3,\n \"shape/annotation/symbol/edgecolor\": \"#ffff00\",\n \"shape/annotation/symbol/facecolor\": \"#ffff00\",\n \"shape/annotation/symbol/alpha\": 1.0,\n \"shape/annotation/sel_line/style\": \"SolidLine\",\n \"shape/annotation/sel_line/color\": \"#00ff00\",\n \"shape/annotation/sel_line/width\": 1,\n \"shape/annotation/sel_fill/style\": \"SolidPattern\",\n \"shape/annotation/sel_fill/color\": MAIN_BG_COLOR,\n \"shape/annotation/sel_fill/alpha\": 0.1,\n \"shape/annotation/sel_symbol/marker\": \"Rect\",\n \"shape/annotation/sel_symbol/size\": 9,\n \"shape/annotation/sel_symbol/edgecolor\": \"#00aa00\",\n \"shape/annotation/sel_symbol/facecolor\": \"#00ff00\",\n \"shape/annotation/sel_symbol/alpha\": 0.7,\n # -----------------------------------------------------------------------------\n # Annotated shape style for result shapes / signals:\n \"shape/result/s/line/style\": \"SolidLine\",\n \"shape/result/s/line/color\": MAIN_FG_COLOR,\n \"shape/result/s/line/width\": 1,\n \"shape/result/s/fill/style\": \"SolidPattern\",\n \"shape/result/s/fill/color\": MAIN_BG_COLOR,\n \"shape/result/s/fill/alpha\": 0.1,\n \"shape/result/s/symbol/marker\": \"XCross\",\n \"shape/result/s/symbol/size\": 7,\n \"shape/result/s/symbol/edgecolor\": MAIN_FG_COLOR,\n \"shape/result/s/symbol/facecolor\": MAIN_FG_COLOR,\n \"shape/result/s/symbol/alpha\": 1.0,\n \"shape/result/s/sel_line/style\": \"SolidLine\",\n \"shape/result/s/sel_line/color\": \"#00ff00\",\n \"shape/result/s/sel_line/width\": 1,\n \"shape/result/s/sel_fill/style\": \"SolidPattern\",\n \"shape/result/s/sel_fill/color\": MAIN_BG_COLOR,\n \"shape/result/s/sel_fill/alpha\": 0.1,\n \"shape/result/s/sel_symbol/marker\": \"Rect\",\n \"shape/result/s/sel_symbol/size\": 9,\n \"shape/result/s/sel_symbol/edgecolor\": \"#00aa00\",\n \"shape/result/s/sel_symbol/facecolor\": \"#00ff00\",\n \"shape/result/s/sel_symbol/alpha\": 0.7,\n # -----------------------------------------------------------------------------\n # Annotated shape style for result shapes / images:\n \"shape/result/i/line/style\": \"SolidLine\",\n \"shape/result/i/line/color\": \"#ffff00\",\n \"shape/result/i/line/width\": 1,\n \"shape/result/i/fill/style\": \"SolidPattern\",\n \"shape/result/i/fill/color\": MAIN_BG_COLOR,\n \"shape/result/i/fill/alpha\": 0.1,\n \"shape/result/i/symbol/marker\": \"Rect\",\n \"shape/result/i/symbol/size\": 3,\n \"shape/result/i/symbol/edgecolor\": \"#ffff00\",\n \"shape/result/i/symbol/facecolor\": \"#ffff00\",\n \"shape/result/i/symbol/alpha\": 1.0,\n \"shape/result/i/sel_line/style\": \"SolidLine\",\n \"shape/result/i/sel_line/color\": \"#00ff00\",\n \"shape/result/i/sel_line/width\": 1,\n \"shape/result/i/sel_fill/style\": \"SolidPattern\",\n \"shape/result/i/sel_fill/color\": MAIN_BG_COLOR,\n \"shape/result/i/sel_fill/alpha\": 0.1,\n \"shape/result/i/sel_symbol/marker\": \"Rect\",\n \"shape/result/i/sel_symbol/size\": 9,\n \"shape/result/i/sel_symbol/edgecolor\": \"#00aa00\",\n \"shape/result/i/sel_symbol/facecolor\": \"#00ff00\",\n \"shape/result/i/sel_symbol/alpha\": 0.7,\n # -----------------------------------------------------------------------------\n },\n}\ndef is_frozen(module_name: str) -> bool:\ndef get_mod_source_dir() -> str | None:\n def get_def_dict(cls, category: str) -> dict:\n def set_def_dict(cls, category: str, def_dict: dict) -> None:\ndef get_old_log_fname(fname):\ndef initialize():\ndef reset():\nclass MainSection(conf.Section, metaclass=conf.SectionMeta):\nclass ConsoleSection(conf.Section, metaclass=conf.SectionMeta):\nclass IOSection(conf.Section, metaclass=conf.SectionMeta):\nclass ProcSection(conf.Section, metaclass=conf.SectionMeta):\nclass ViewSection(conf.Section, metaclass=conf.SectionMeta):\nclass Conf(conf.Configuration, metaclass=conf.ConfMeta):" }, { "identifier": "CDLMainWindow", "path": "cdl/core/gui/main.py", "snippet": "class CDLMainWindow(QW.QMainWindow, AbstractCDLControl, metaclass=CDLMainWindowMeta):\n \"\"\"DataLab main window\n\n Args:\n console: enable internal console\n hide_on_close: True to hide window on close\n \"\"\"\n\n __instance = None\n\n SIG_READY = QC.Signal()\n SIG_SEND_OBJECT = QC.Signal(object)\n SIG_SEND_OBJECTLIST = QC.Signal(object)\n SIG_CLOSING = QC.Signal()\n\n @staticmethod\n def get_instance(console=None, hide_on_close=False):\n \"\"\"Return singleton instance\"\"\"\n if CDLMainWindow.__instance is None:\n return CDLMainWindow(console, hide_on_close)\n return CDLMainWindow.__instance\n\n def __init__(self, console=None, hide_on_close=False):\n \"\"\"Initialize main window\"\"\"\n CDLMainWindow.__instance = self\n super().__init__()\n win32_fix_title_bar_background(self)\n self.setObjectName(APP_NAME)\n self.setWindowIcon(get_icon(\"DataLab.svg\"))\n\n execenv.log(self, \"Starting initialization\")\n\n self.__restore_pos_and_size()\n\n self.ready_flag = True\n\n self.hide_on_close = hide_on_close\n self.__old_size = None\n self.__memory_warning = False\n self.memorystatus = None\n\n self.console = None\n self.macropanel: MacroPanel = None\n\n self.signal_toolbar: QW.QToolBar = None\n self.image_toolbar: QW.QToolBar = None\n self.signalpanel: SignalPanel = None\n self.imagepanel: ImagePanel = None\n self.tabwidget: QW.QTabWidget = None\n self.docks: dict[AbstractPanel, QW.QDockWidget] = None\n self.h5inputoutput = H5InputOutput(self)\n\n self.openh5_action: QW.QAction = None\n self.saveh5_action: QW.QAction = None\n self.browseh5_action: QW.QAction = None\n self.settings_action: QW.QAction = None\n self.quit_action: QW.QAction = None\n self.auto_refresh_action: QW.QAction = None\n self.showlabel_action: QW.QAction = None\n\n self.file_menu: QW.QMenu = None\n self.edit_menu: QW.QMenu = None\n self.operation_menu: QW.QMenu = None\n self.processing_menu: QW.QMenu = None\n self.computing_menu: QW.QMenu = None\n self.plugins_menu: QW.QMenu = None\n self.view_menu: QW.QMenu = None\n self.help_menu: QW.QMenu = None\n\n self.__is_modified = None\n self.set_modified(False)\n\n # Starting XML-RPC server thread\n self.remote_server = RemoteServer(self)\n if Conf.main.rpc_server_enabled.get():\n self.remote_server.SIG_SERVER_PORT.connect(self.xmlrpc_server_started)\n self.remote_server.start()\n\n # Setup actions and menus\n if console is None:\n console = Conf.console.console_enabled.get()\n self.setup(console)\n\n execenv.log(self, \"Initialization done\")\n\n # ------API related to XML-RPC remote control\n @staticmethod\n def xmlrpc_server_started(port):\n \"\"\"XML-RPC server has started, writing comm port in configuration file\"\"\"\n Conf.main.rpc_server_port.set(port)\n\n def __get_current_basedatapanel(self) -> BaseDataPanel:\n \"\"\"Return the current BaseDataPanel,\n or the signal panel if macro panel is active\n\n Returns:\n BaseDataPanel: current panel\n \"\"\"\n panel = self.tabwidget.currentWidget()\n if not isinstance(panel, base.BaseDataPanel):\n panel = self.signalpanel\n return panel\n\n def __get_specific_panel(self, panel: str | None) -> BaseDataPanel:\n \"\"\"Return a specific BaseDataPanel.\n\n Args:\n panel (str | None): panel name (valid values: \"signal\", \"image\").\n If None, current panel is used.\n\n Returns:\n BaseDataPanel: panel\n\n Raises:\n ValueError: if panel is unknown\n \"\"\"\n if not panel:\n return self.__get_current_basedatapanel()\n if panel == \"signal\":\n return self.signalpanel\n if panel == \"image\":\n return self.imagepanel\n raise ValueError(f\"Unknown panel: {panel}\")\n\n @remote_controlled\n def get_group_titles_with_object_infos(\n self,\n ) -> tuple[list[str], list[list[str]], list[list[str]]]:\n \"\"\"Return groups titles and lists of inner objects uuids and titles.\n\n Returns:\n Tuple: groups titles, lists of inner objects uuids and titles\n \"\"\"\n panel = self.__get_current_basedatapanel()\n return panel.objmodel.get_group_titles_with_object_infos()\n\n @remote_controlled\n def get_object_titles(self, panel: str | None = None) -> list[str]:\n \"\"\"Get object (signal/image) list for current panel.\n Objects are sorted by group number and object index in group.\n\n Args:\n panel (str | None): panel name (valid values: \"signal\", \"image\").\n If None, current panel is used.\n\n Returns:\n list[str]: list of object titles\n\n Raises:\n ValueError: if panel is unknown\n \"\"\"\n return self.__get_specific_panel(panel).objmodel.get_object_titles()\n\n @remote_controlled\n def get_object(\n self,\n nb_id_title: int | str | None = None,\n panel: str | None = None,\n ) -> SignalObj | ImageObj:\n \"\"\"Get object (signal/image) from index.\n\n Args:\n nb_id_title: Object number, or object id, or object title.\n Defaults to None (current object).\n panel: Panel name. Defaults to None (current panel).\n\n Returns:\n Object\n\n Raises:\n KeyError: if object not found\n TypeError: if index_id_title type is invalid\n \"\"\"\n panelw = self.__get_specific_panel(panel)\n if nb_id_title is None:\n return panelw.objview.get_current_object()\n if isinstance(nb_id_title, int):\n return panelw.objmodel.get_object_from_number(nb_id_title)\n if isinstance(nb_id_title, str):\n try:\n return panelw.objmodel[nb_id_title]\n except KeyError:\n try:\n return panelw.objmodel.get_object_from_title(nb_id_title)\n except KeyError as exc:\n raise KeyError(\n f\"Invalid object index, id or title: {nb_id_title}\"\n ) from exc\n raise TypeError(f\"Invalid index_id_title type: {type(nb_id_title)}\")\n\n @remote_controlled\n def get_object_uuids(self, panel: str | None = None) -> list[str]:\n \"\"\"Get object (signal/image) uuid list for current panel.\n Objects are sorted by group number and object index in group.\n\n Args:\n panel (str | None): panel name (valid values: \"signal\", \"image\").\n If None, current panel is used.\n\n Returns:\n list[str]: list of object uuids\n\n Raises:\n ValueError: if panel is unknown\n \"\"\"\n return self.__get_specific_panel(panel).objmodel.get_object_ids()\n\n @remote_controlled\n def get_sel_object_uuids(self, include_groups: bool = False) -> list[str]:\n \"\"\"Return selected objects uuids.\n\n Args:\n include_groups: If True, also return objects from selected groups.\n\n Returns:\n List of selected objects uuids.\n \"\"\"\n panel = self.__get_current_basedatapanel()\n return panel.objview.get_sel_object_uuids(include_groups)\n\n @remote_controlled\n def select_objects(\n self,\n selection: list[int | str],\n panel: str | None = None,\n ) -> None:\n \"\"\"Select objects in current panel.\n\n Args:\n selection: List of object numbers (1 to N) or uuids to select\n panel: panel name (valid values: \"signal\", \"image\").\n If None, current panel is used. Defaults to None.\n \"\"\"\n panel = self.__get_specific_panel(panel)\n panel.objview.select_objects(selection)\n\n @remote_controlled\n def select_groups(\n self, selection: list[int | str] | None = None, panel: str | None = None\n ) -> None:\n \"\"\"Select groups in current panel.\n\n Args:\n selection: List of group numbers (1 to N), or list of group uuids,\n or None to select all groups. Defaults to None.\n panel (str | None): panel name (valid values: \"signal\", \"image\").\n If None, current panel is used. Defaults to None.\n \"\"\"\n panel = self.__get_specific_panel(panel)\n panel.objview.select_groups(selection)\n\n @remote_controlled\n def delete_metadata(self, refresh_plot: bool = True) -> None:\n \"\"\"Delete metadata of selected objects\n\n Args:\n refresh_plot (bool | None): Refresh plot. Defaults to True.\n \"\"\"\n panel = self.__get_current_basedatapanel()\n panel.delete_metadata(refresh_plot)\n\n @remote_controlled\n def get_object_shapes(\n self,\n nb_id_title: int | str | None = None,\n panel: str | None = None,\n ) -> list:\n \"\"\"Get plot item shapes associated to object (signal/image).\n\n Args:\n nb_id_title: Object number, or object id, or object title.\n Defaults to None (current object).\n panel: Panel name. Defaults to None (current panel).\n\n Returns:\n List of plot item shapes\n \"\"\"\n obj = self.get_object(nb_id_title, panel)\n return list(obj.iterate_shape_items(editable=False))\n\n @remote_controlled\n def add_annotations_from_items(\n self, items: list, refresh_plot: bool = True, panel: str | None = None\n ) -> None:\n \"\"\"Add object annotations (annotation plot items).\n\n Args:\n items (list): annotation plot items\n refresh_plot (bool | None): refresh plot. Defaults to True.\n panel (str | None): panel name (valid values: \"signal\", \"image\").\n If None, current panel is used.\n \"\"\"\n panel = self.__get_specific_panel(panel)\n panel.add_annotations_from_items(items, refresh_plot)\n\n @remote_controlled\n def add_label_with_title(\n self, title: str | None = None, panel: str | None = None\n ) -> None:\n \"\"\"Add a label with object title on the associated plot\n\n Args:\n title (str | None): Label title. Defaults to None.\n If None, the title is the object title.\n panel (str | None): panel name (valid values: \"signal\", \"image\").\n If None, current panel is used.\n \"\"\"\n self.__get_specific_panel(panel).add_label_with_title(title)\n\n # ------Misc.\n @property\n def panels(self) -> tuple[AbstractPanel, ...]:\n \"\"\"Return the tuple of implemented panels (signal, image)\n\n Returns:\n tuple[SignalPanel, ImagePanel, MacroPanel]: tuple of panels\n \"\"\"\n return (self.signalpanel, self.imagepanel, self.macropanel)\n\n def __set_low_memory_state(self, state: bool) -> None:\n \"\"\"Set memory warning state\"\"\"\n self.__memory_warning = state\n\n def confirm_memory_state(self) -> bool: # pragma: no cover\n \"\"\"Check memory warning state and eventually show a warning dialog\n\n Returns:\n bool: True if memory state is ok\n \"\"\"\n if not env.execenv.unattended and self.__memory_warning:\n threshold = Conf.main.available_memory_threshold.get()\n answer = QW.QMessageBox.critical(\n self,\n _(\"Warning\"),\n _(\"Available memory is below %d MB.<br><br>Do you want to continue?\")\n % threshold,\n QW.QMessageBox.Yes | QW.QMessageBox.No,\n )\n return answer == QW.QMessageBox.Yes\n return True\n\n def check_stable_release(self) -> None: # pragma: no cover\n \"\"\"Check if this is a stable release\"\"\"\n if __version__.replace(\".\", \"\").isdigit():\n # This is a stable release\n return\n if \"b\" in __version__:\n # This is a beta release\n rel = _(\n \"This software is in the <b>beta stage</b> of its release cycle. \"\n \"The focus of beta testing is providing a feature complete \"\n \"software for users interested in trying new features before \"\n \"the final release. However, <u>beta software may not behave as \"\n \"expected and will probably have more bugs or performance issues \"\n \"than completed software</u>.\"\n )\n else:\n # This is an alpha release\n rel = _(\n \"This software is in the <b>alpha stage</b> of its release cycle. \"\n \"The focus of alpha testing is providing an incomplete software \"\n \"for early testing of specific features by users. \"\n \"Please note that <u>alpha software was not thoroughly tested</u> \"\n \"by the developer before it is released.\"\n )\n txtlist = [\n f\"<b>{APP_NAME}</b> v{__version__}:\",\n \"\",\n _(\"<i>This is not a stable release.</i>\"),\n \"\",\n rel,\n ]\n QW.QMessageBox.warning(self, APP_NAME, \"<br>\".join(txtlist), QW.QMessageBox.Ok)\n\n def __check_dependencies(self) -> None: # pragma: no cover\n \"\"\"Check dependencies\"\"\"\n if IS_FROZEN or execenv.unattended:\n # No need to check dependencies if DataLab has been frozen, or if\n # the user has chosen to ignore this check, or if we are in unattended mode\n # (i.e. running automated tests)\n\n if IS_FROZEN:\n QW.QMessageBox.information(\n self,\n _(\"Information\"),\n _(\n \"The dependency check feature is not relevant for the \"\n \"standalone version of DataLab.\"\n ),\n QW.QMessageBox.Ok,\n )\n return\n try:\n state = dephash.check_dependencies_hash(DATAPATH)\n bad_deps = [name for name in state if not state[name]]\n if not bad_deps:\n # Everything is OK\n QW.QMessageBox.information(\n self,\n _(\"Information\"),\n _(\n \"All critical dependencies of DataLab have been qualified \"\n \"on this operating system.\"\n ),\n QW.QMessageBox.Ok,\n )\n return\n except IOError:\n bad_deps = None\n txt0 = _(\"Non-compliant dependency:\")\n if bad_deps is None or len(bad_deps) > 1:\n txt0 = _(\"Non-compliant dependencies:\")\n if bad_deps is None:\n txtlist = [\n _(\"DataLab has not yet been qualified on your operating system.\"),\n ]\n else:\n txtlist = [\n \"<u>\" + txt0 + \"</u> \" + \", \".join(bad_deps),\n \"\",\n _(\n \"At least one dependency does not comply with DataLab \"\n \"qualification standard reference (wrong dependency version \"\n \"has been installed, or dependency source code has been \"\n \"modified, or the application has not yet been qualified \"\n \"on your operating system).\"\n ),\n ]\n txtlist += [\n \"\",\n _(\n \"This means that the application has not been officially qualified \"\n \"in this context and may not behave as expected.\"\n ),\n ]\n txt = \"<br>\".join(txtlist)\n QW.QMessageBox.warning(self, APP_NAME, txt, QW.QMessageBox.Ok)\n\n def check_for_previous_crash(self) -> None: # pragma: no cover\n \"\"\"Check for previous crash\"\"\"\n if execenv.unattended:\n self.__show_logviewer()\n elif Conf.main.faulthandler_log_available.get(\n False\n ) or Conf.main.traceback_log_available.get(False):\n txt = \"<br>\".join(\n [\n logviewer.get_log_prompt_message(),\n \"\",\n _(\"Do you want to see available log files?\"),\n ]\n )\n btns = QW.QMessageBox.StandardButton.Yes | QW.QMessageBox.StandardButton.No\n choice = QW.QMessageBox.warning(self, APP_NAME, txt, btns)\n if choice == QW.QMessageBox.StandardButton.Yes:\n self.__show_logviewer()\n\n def take_screenshot(self, name: str) -> None: # pragma: no cover\n \"\"\"Take main window screenshot\"\"\"\n self.memorystatus.set_demo_mode(True)\n qth.grab_save_window(self, f\"{name}\")\n self.memorystatus.set_demo_mode(False)\n\n def take_menu_screenshots(self) -> None: # pragma: no cover\n \"\"\"Take menu screenshots\"\"\"\n for panel in self.panels:\n if isinstance(panel, base.BaseDataPanel):\n self.tabwidget.setCurrentWidget(panel)\n for name in (\n \"file\",\n \"edit\",\n \"view\",\n \"operation\",\n \"processing\",\n \"computing\",\n \"help\",\n ):\n menu = getattr(self, f\"{name}_menu\")\n menu.popup(self.pos())\n qth.grab_save_window(menu, f\"{panel.objectName()}_{name}\")\n menu.close()\n\n # ------GUI setup\n def __restore_pos_and_size(self) -> None:\n \"\"\"Restore main window position and size from configuration\"\"\"\n pos = Conf.main.window_position.get(None)\n if pos is not None:\n posx, posy = pos\n self.move(QC.QPoint(posx, posy))\n size = Conf.main.window_size.get(None)\n if size is not None:\n width, height = size\n self.resize(QC.QSize(width, height))\n if pos is not None and size is not None:\n sgeo = self.screen().availableGeometry()\n out_inf = posx < -int(0.9 * width) or posy < -int(0.9 * height)\n out_sup = posx > int(0.9 * sgeo.width()) or posy > int(0.9 * sgeo.height())\n if len(QW.QApplication.screens()) == 1 and (out_inf or out_sup):\n # Main window is offscreen\n posx = min(max(posx, 0), sgeo.width() - width)\n posy = min(max(posy, 0), sgeo.height() - height)\n self.move(QC.QPoint(posx, posy))\n\n def __save_pos_and_size(self) -> None:\n \"\"\"Save main window position and size to configuration\"\"\"\n is_maximized = self.windowState() == QC.Qt.WindowMaximized\n Conf.main.window_maximized.set(is_maximized)\n if not is_maximized:\n size = self.size()\n Conf.main.window_size.set((size.width(), size.height()))\n pos = self.pos()\n Conf.main.window_position.set((pos.x(), pos.y()))\n\n def setup(self, console: bool = False) -> None:\n \"\"\"Setup main window\n\n Args:\n console: True to setup console\n \"\"\"\n self.__register_plugins()\n self.__configure_statusbar()\n self.__setup_global_actions()\n self.__add_signal_image_panels()\n self.__create_plugins_actions()\n self.__setup_central_widget()\n self.__add_menus()\n if console:\n self.__setup_console()\n self.__update_actions()\n self.__add_macro_panel()\n self.__configure_panels()\n\n def __register_plugins(self) -> None:\n \"\"\"Register plugins\"\"\"\n with qth.try_or_log_error(\"Discovering plugins\"):\n # Discovering plugins\n plugin_nb = len(discover_plugins())\n execenv.log(self, f\"{plugin_nb} plugin(s) found\")\n for plugin_class in PluginRegistry.get_plugin_classes():\n with qth.try_or_log_error(f\"Instantiating plugin {plugin_class.__name__}\"):\n # Instantiating plugin\n plugin: PluginBase = plugin_class()\n with qth.try_or_log_error(f\"Registering plugin {plugin.info.name}\"):\n # Registering plugin\n plugin.register(self)\n\n def __create_plugins_actions(self) -> None:\n \"\"\"Create plugins actions\"\"\"\n with self.signalpanel.acthandler.new_category(ActionCategory.PLUGINS):\n with self.imagepanel.acthandler.new_category(ActionCategory.PLUGINS):\n for plugin in PluginRegistry.get_plugins():\n with qth.try_or_log_error(f\"Create actions for {plugin.info.name}\"):\n plugin.create_actions()\n\n @staticmethod\n def __unregister_plugins() -> None:\n \"\"\"Unregister plugins\"\"\"\n while PluginRegistry.get_plugins():\n # Unregistering plugin\n plugin = PluginRegistry.get_plugins()[-1]\n with qth.try_or_log_error(f\"Unregistering plugin {plugin.info.name}\"):\n plugin.unregister()\n\n def __configure_statusbar(self) -> None:\n \"\"\"Configure status bar\"\"\"\n self.statusBar().showMessage(_(\"Welcome to %s!\") % APP_NAME, 5000)\n # Plugin status\n pluginstatus = status.PluginStatus()\n self.statusBar().addPermanentWidget(pluginstatus)\n # XML-RPC server status\n xmlrpcstatus = status.XMLRPCStatus()\n xmlrpcstatus.set_port(self.remote_server.port)\n self.statusBar().addPermanentWidget(xmlrpcstatus)\n # Memory status\n threshold = Conf.main.available_memory_threshold.get()\n self.memorystatus = status.MemoryStatus(threshold)\n self.memorystatus.SIG_MEMORY_ALARM.connect(self.__set_low_memory_state)\n self.statusBar().addPermanentWidget(self.memorystatus)\n\n def __setup_global_actions(self) -> None:\n \"\"\"Setup global actions\"\"\"\n self.openh5_action = create_action(\n self,\n _(\"Open HDF5 files...\"),\n icon=get_icon(\"fileopen_h5.svg\"),\n tip=_(\"Open one or several HDF5 files\"),\n triggered=lambda checked=False: self.open_h5_files(import_all=True),\n )\n self.saveh5_action = create_action(\n self,\n _(\"Save to HDF5 file...\"),\n icon=get_icon(\"filesave_h5.svg\"),\n tip=_(\"Save to HDF5 file\"),\n triggered=self.save_to_h5_file,\n )\n self.browseh5_action = create_action(\n self,\n _(\"Browse HDF5 file...\"),\n icon=get_icon(\"h5browser.svg\"),\n tip=_(\"Browse an HDF5 file\"),\n triggered=lambda checked=False: self.open_h5_files(import_all=None),\n )\n self.settings_action = create_action(\n self,\n _(\"Settings...\"),\n icon=get_icon(\"libre-gui-settings.svg\"),\n tip=_(\"Open settings dialog\"),\n triggered=self.__edit_settings,\n )\n main_toolbar = self.addToolBar(_(\"Main Toolbar\"))\n add_actions(\n main_toolbar,\n [\n self.openh5_action,\n self.saveh5_action,\n self.browseh5_action,\n None,\n self.settings_action,\n ],\n )\n # Quit action for \"File menu\" (added when populating menu on demand)\n if self.hide_on_close:\n quit_text = _(\"Hide window\")\n quit_tip = _(\"Hide DataLab window\")\n else:\n quit_text = _(\"Quit\")\n quit_tip = _(\"Quit application\")\n if sys.platform != \"darwin\":\n # On macOS, the \"Quit\" action is automatically added to the application menu\n self.quit_action = create_action(\n self,\n quit_text,\n shortcut=QG.QKeySequence(QG.QKeySequence.Quit),\n icon=get_icon(\"libre-gui-close.svg\"),\n tip=quit_tip,\n triggered=self.close,\n )\n # View menu actions\n self.auto_refresh_action = create_action(\n self,\n _(\"Auto-refresh\"),\n icon=get_icon(\"refresh-auto.svg\"),\n tip=_(\"Auto-refresh plot when object is modified, added or removed\"),\n toggled=self.toggle_auto_refresh,\n )\n self.showlabel_action = create_action(\n self,\n _(\"Show graphical object titles\"),\n icon=get_icon(\"show_titles.svg\"),\n tip=_(\"Show or hide ROI and other graphical object titles or subtitles\"),\n toggled=self.toggle_show_titles,\n )\n\n def __add_signal_panel(self) -> None:\n \"\"\"Setup signal toolbar, widgets and panel\"\"\"\n self.signal_toolbar = self.addToolBar(_(\"Signal Processing Toolbar\"))\n curvewidget = DockablePlotWidget(self, PlotType.CURVE)\n curveplot = curvewidget.get_plot()\n curveplot.add_item(make.legend(\"TR\"))\n self.signalpanel = signal.SignalPanel(\n self, curvewidget.plotwidget, self.signal_toolbar\n )\n self.signalpanel.SIG_STATUS_MESSAGE.connect(self.statusBar().showMessage)\n return curvewidget\n\n def __add_image_panel(self) -> None:\n \"\"\"Setup image toolbar, widgets and panel\"\"\"\n self.image_toolbar = self.addToolBar(_(\"Image Processing Toolbar\"))\n imagewidget = DockablePlotWidget(self, PlotType.IMAGE)\n self.imagepanel = image.ImagePanel(\n self, imagewidget.plotwidget, self.image_toolbar\n )\n # -----------------------------------------------------------------------------\n # # Before eventually disabling the \"peritem\" mode by default, wait for the\n # # plotpy bug to be fixed (peritem mode is not compatible with multiple image\n # # items):\n # for cspanel in (\n # self.imagepanel.plotwidget.get_xcs_panel(),\n # self.imagepanel.plotwidget.get_ycs_panel(),\n # ):\n # cspanel.peritem_ac.setChecked(False)\n # -----------------------------------------------------------------------------\n self.imagepanel.SIG_STATUS_MESSAGE.connect(self.statusBar().showMessage)\n return imagewidget\n\n def __add_signal_image_panels(self) -> None:\n \"\"\"Add signal and image panels\"\"\"\n self.tabwidget = QW.QTabWidget()\n cdock = self.__add_dockwidget(self.__add_signal_panel(), title=_(\"Curve panel\"))\n idock = self.__add_dockwidget(self.__add_image_panel(), title=_(\"Image panel\"))\n self.tabifyDockWidget(cdock, idock)\n self.docks = {self.signalpanel: cdock, self.imagepanel: idock}\n self.tabwidget.currentChanged.connect(self.__tab_index_changed)\n self.signalpanel.SIG_OBJECT_ADDED.connect(\n lambda: self.set_current_panel(\"signal\")\n )\n self.imagepanel.SIG_OBJECT_ADDED.connect(\n lambda: self.set_current_panel(\"image\")\n )\n for panel in (self.signalpanel, self.imagepanel):\n panel.setup_panel()\n\n def __setup_central_widget(self) -> None:\n \"\"\"Setup central widget (main panel)\"\"\"\n self.tabwidget.setMaximumWidth(500)\n self.tabwidget.addTab(self.signalpanel, get_icon(\"signal.svg\"), _(\"Signals\"))\n self.tabwidget.addTab(self.imagepanel, get_icon(\"image.svg\"), _(\"Images\"))\n self.setCentralWidget(self.tabwidget)\n\n @staticmethod\n def __get_local_doc_path() -> str | None:\n \"\"\"Return local documentation path, if it exists\"\"\"\n locale = QC.QLocale.system().name()\n for suffix in (\"_\" + locale[:2], \"_en\"):\n path = osp.join(DATAPATH, \"doc\", f\"{APP_NAME}{suffix}.pdf\")\n if osp.isfile(path):\n return path\n return None\n\n def __add_menus(self) -> None:\n \"\"\"Adding menus\"\"\"\n self.file_menu = self.menuBar().addMenu(_(\"File\"))\n configure_menu_about_to_show(self.file_menu, self.__update_file_menu)\n self.edit_menu = self.menuBar().addMenu(_(\"&Edit\"))\n self.operation_menu = self.menuBar().addMenu(_(\"Operations\"))\n self.processing_menu = self.menuBar().addMenu(_(\"Processing\"))\n self.computing_menu = self.menuBar().addMenu(_(\"Computing\"))\n self.plugins_menu = self.menuBar().addMenu(_(\"Plugins\"))\n self.view_menu = self.menuBar().addMenu(_(\"&View\"))\n configure_menu_about_to_show(self.view_menu, self.__update_view_menu)\n self.help_menu = self.menuBar().addMenu(\"?\")\n for menu in (\n self.edit_menu,\n self.operation_menu,\n self.processing_menu,\n self.computing_menu,\n self.plugins_menu,\n ):\n configure_menu_about_to_show(menu, self.__update_generic_menu)\n help_menu_actions = [\n create_action(\n self,\n _(\"Online documentation\"),\n icon=get_icon(\"libre-gui-help.svg\"),\n triggered=lambda: webbrowser.open(__docurl__),\n ),\n ]\n localdocpath = self.__get_local_doc_path()\n if localdocpath is not None:\n help_menu_actions += [\n create_action(\n self,\n _(\"PDF documentation\"),\n icon=get_icon(\"help_pdf.svg\"),\n triggered=lambda: webbrowser.open(localdocpath),\n ),\n ]\n help_menu_actions += [None]\n if TEST_SEGFAULT_ERROR:\n help_menu_actions += [\n create_action(\n self,\n _(\"Test segfault/Python error\"),\n triggered=self.test_segfault_error,\n )\n ]\n help_menu_actions += [\n create_action(\n self,\n _(\"Log files\") + \"...\",\n icon=get_icon(\"logs.svg\"),\n triggered=self.__show_logviewer,\n ),\n create_action(\n self,\n _(\"Installation and configuration\") + \"...\",\n icon=get_icon(\"libre-toolbox.svg\"),\n triggered=lambda: instconfviewer.exec_cdl_installconfig_dialog(self),\n ),\n None,\n create_action(\n self,\n _(\"Project home page\"),\n icon=get_icon(\"libre-gui-globe.svg\"),\n triggered=lambda: webbrowser.open(__homeurl__),\n ),\n create_action(\n self,\n _(\"Bug report or feature request\"),\n icon=get_icon(\"libre-gui-globe.svg\"),\n triggered=lambda: webbrowser.open(__supporturl__),\n ),\n create_action(\n self,\n _(\"Check critical dependencies...\"),\n triggered=self.__check_dependencies,\n ),\n create_action(\n self,\n _(\"About...\"),\n icon=get_icon(\"libre-gui-about.svg\"),\n triggered=self.__about,\n ),\n ]\n add_actions(self.help_menu, help_menu_actions)\n\n def __setup_console(self) -> None:\n \"\"\"Add an internal console\"\"\"\n ns = {\n \"cdl\": self,\n \"np\": np,\n \"sps\": sps,\n \"spi\": spi,\n \"os\": os,\n \"sys\": sys,\n \"osp\": osp,\n \"time\": time,\n }\n msg = (\n \"Welcome to DataLab console!\\n\"\n \"---------------------------\\n\"\n \"You can access the main window with the 'cdl' variable.\\n\"\n \"Example:\\n\"\n \" o = cdl.get_object() # returns currently selected object\\n\"\n \" o = cdl[1] # returns object number 1\\n\"\n \" o = cdl['My image'] # returns object which title is 'My image'\\n\"\n \" o.data # returns object data\\n\"\n \"Modules imported at startup: \"\n \"os, sys, os.path as osp, time, \"\n \"numpy as np, scipy.signal as sps, scipy.ndimage as spi\"\n )\n self.console = DockableConsole(self, namespace=ns, message=msg, debug=DEBUG)\n self.console.setMaximumBlockCount(Conf.console.max_line_count.get(5000))\n self.console.go_to_error.connect(go_to_error)\n console_dock = self.__add_dockwidget(self.console, _(\"Console\"))\n console_dock.hide()\n self.console.interpreter.widget_proxy.sig_new_prompt.connect(\n lambda txt: self.repopulate_panel_trees()\n )\n\n def __add_macro_panel(self) -> None:\n \"\"\"Add macro panel\"\"\"\n self.macropanel = macro.MacroPanel()\n mdock = self.__add_dockwidget(self.macropanel, _(\"Macro manager\"))\n self.docks[self.macropanel] = mdock\n self.tabifyDockWidget(self.docks[self.imagepanel], mdock)\n self.docks[self.signalpanel].raise_()\n\n def __configure_panels(self) -> None:\n \"\"\"Configure panels\"\"\"\n # Connectings signals\n for panel in self.panels:\n panel.SIG_OBJECT_ADDED.connect(self.set_modified)\n panel.SIG_OBJECT_REMOVED.connect(self.set_modified)\n self.macropanel.SIG_OBJECT_MODIFIED.connect(self.set_modified)\n # Initializing common panel actions\n self.auto_refresh_action.setChecked(Conf.view.auto_refresh.get(True))\n self.showlabel_action.setChecked(Conf.view.show_label.get(False))\n # Restoring current tab from last session\n tab_idx = Conf.main.current_tab.get(None)\n if tab_idx is not None:\n self.tabwidget.setCurrentIndex(tab_idx)\n # Set focus on current panel, so that keyboard shortcuts work (Fixes #10)\n self.tabwidget.currentWidget().setFocus()\n\n def set_process_isolation_enabled(self, state: bool) -> None:\n \"\"\"Enable/disable process isolation\n\n Args:\n state (bool): True to enable process isolation\n \"\"\"\n for processor in (self.imagepanel.processor, self.signalpanel.processor):\n processor.set_process_isolation_enabled(state)\n\n # ------Remote control\n @remote_controlled\n def get_current_panel(self) -> str:\n \"\"\"Return current panel name\n\n Returns:\n str: panel name (valid values: \"signal\", \"image\", \"macro\")\n \"\"\"\n panel = self.tabwidget.currentWidget()\n dock = self.docks[panel]\n if panel is self.signalpanel and dock.isVisible():\n return \"signal\"\n if panel is self.imagepanel and dock.isVisible():\n return \"image\"\n return \"macro\"\n\n @remote_controlled\n def set_current_panel(self, panel: str) -> None:\n \"\"\"Switch to panel.\n\n Args:\n panel (str): panel name (valid values: \"signal\", \"image\", \"macro\")\n\n Raises:\n ValueError: unknown panel\n \"\"\"\n if self.get_current_panel() == panel:\n if panel in (\"signal\", \"image\"):\n # Force tab index changed event to be sure that the dock associated\n # to the current panel is raised\n self.__tab_index_changed(self.tabwidget.currentIndex())\n return\n if panel == \"signal\":\n self.tabwidget.setCurrentWidget(self.signalpanel)\n elif panel == \"image\":\n self.tabwidget.setCurrentWidget(self.imagepanel)\n elif panel == \"macro\":\n self.docks[self.macropanel].raise_()\n else:\n raise ValueError(f\"Unknown panel {panel}\")\n\n @remote_controlled\n def calc(self, name: str, param: gds.DataSet | None = None) -> None:\n \"\"\"Call compute function `name` in current panel's processor\n\n Args:\n name (str): function name\n param (guidata.dataset.DataSet): optional parameters\n (default: None)\n\n Raises:\n ValueError: unknown function\n \"\"\"\n panel = self.tabwidget.currentWidget()\n if isinstance(panel, base.BaseDataPanel):\n for funcname in (name, f\"compute_{name}\"):\n func = getattr(panel.processor, funcname, None)\n if func is not None:\n break\n else:\n raise ValueError(f\"Unknown function {funcname}\")\n if param is None:\n func()\n else:\n func(param)\n\n # ------GUI refresh\n def has_objects(self) -> bool:\n \"\"\"Return True if sig/ima panels have any object\"\"\"\n return sum(len(panel) for panel in self.panels) > 0\n\n def set_modified(self, state: bool = True) -> None:\n \"\"\"Set mainwindow modified state\"\"\"\n state = state and self.has_objects()\n self.__is_modified = state\n self.setWindowTitle(APP_NAME + (\"*\" if state else \"\"))\n\n def __add_dockwidget(self, child, title: str) -> QW.QDockWidget:\n \"\"\"Add QDockWidget and toggleViewAction\"\"\"\n dockwidget, location = child.create_dockwidget(title)\n self.addDockWidget(location, dockwidget)\n return dockwidget\n\n def repopulate_panel_trees(self) -> None:\n \"\"\"Repopulate all panel trees\"\"\"\n for panel in self.panels:\n if isinstance(panel, base.BaseDataPanel):\n panel.objview.populate_tree()\n\n def __update_actions(self) -> None:\n \"\"\"Update selection dependent actions\"\"\"\n is_signal = self.tabwidget.currentWidget() is self.signalpanel\n panel = self.signalpanel if is_signal else self.imagepanel\n panel.selection_changed()\n self.signal_toolbar.setVisible(is_signal)\n self.image_toolbar.setVisible(not is_signal)\n if self.plugins_menu is not None:\n plugin_actions = panel.get_category_actions(ActionCategory.PLUGINS)\n self.plugins_menu.setEnabled(len(plugin_actions) > 0)\n\n def __tab_index_changed(self, index: int) -> None:\n \"\"\"Switch from signal to image mode, or vice-versa\"\"\"\n dock = self.docks[self.tabwidget.widget(index)]\n dock.raise_()\n self.__update_actions()\n\n def __update_generic_menu(self, menu: QW.QMenu | None = None) -> None:\n \"\"\"Update menu before showing up -- Generic method\"\"\"\n if menu is None:\n menu = self.sender()\n menu.clear()\n panel = self.tabwidget.currentWidget()\n category = {\n self.file_menu: ActionCategory.FILE,\n self.edit_menu: ActionCategory.EDIT,\n self.view_menu: ActionCategory.VIEW,\n self.operation_menu: ActionCategory.OPERATION,\n self.processing_menu: ActionCategory.PROCESSING,\n self.computing_menu: ActionCategory.COMPUTING,\n self.plugins_menu: ActionCategory.PLUGINS,\n }[menu]\n actions = panel.get_category_actions(category)\n add_actions(menu, actions)\n\n def __update_file_menu(self) -> None:\n \"\"\"Update file menu before showing up\"\"\"\n self.saveh5_action.setEnabled(self.has_objects())\n self.__update_generic_menu(self.file_menu)\n add_actions(\n self.file_menu,\n [\n None,\n self.openh5_action,\n self.saveh5_action,\n self.browseh5_action,\n None,\n self.settings_action,\n ],\n )\n if self.quit_action is not None:\n add_actions(self.file_menu, [None, self.quit_action])\n\n def __update_view_menu(self) -> None:\n \"\"\"Update view menu before showing up\"\"\"\n self.__update_generic_menu(self.view_menu)\n add_actions(self.view_menu, [None] + self.createPopupMenu().actions())\n\n @remote_controlled\n def toggle_show_titles(self, state: bool) -> None:\n \"\"\"Toggle show annotations option\n\n Args:\n state: state\n \"\"\"\n Conf.view.show_label.set(state)\n for datapanel in (self.signalpanel, self.imagepanel):\n for obj in datapanel.objmodel:\n obj.set_metadata_option(\"showlabel\", state)\n datapanel.SIG_REFRESH_PLOT.emit(\"selected\", True)\n\n @remote_controlled\n def toggle_auto_refresh(self, state: bool) -> None:\n \"\"\"Toggle auto refresh option\n\n Args:\n state: state\n \"\"\"\n Conf.view.auto_refresh.set(state)\n for datapanel in (self.signalpanel, self.imagepanel):\n datapanel.plothandler.set_auto_refresh(state)\n\n # ------Common features\n @remote_controlled\n def reset_all(self) -> None:\n \"\"\"Reset all application data\"\"\"\n for panel in self.panels:\n if panel is not None:\n panel.remove_all_objects()\n\n @staticmethod\n def __check_h5file(filename: str, operation: str) -> str:\n \"\"\"Check HDF5 filename\"\"\"\n filename = osp.abspath(osp.normpath(filename))\n bname = osp.basename(filename)\n if operation == \"load\" and not osp.isfile(filename):\n raise IOError(f'File not found \"{bname}\"')\n if not filename.endswith(\".h5\"):\n raise IOError(f'Invalid HDF5 file \"{bname}\"')\n Conf.main.base_dir.set(filename)\n return filename\n\n @remote_controlled\n def save_to_h5_file(self, filename=None) -> None:\n \"\"\"Save to a DataLab HDF5 file\n\n Args:\n filename (str): HDF5 filename. If None, a file dialog is opened.\n\n Raises:\n IOError: if filename is invalid or file cannot be saved.\n \"\"\"\n if filename is None:\n basedir = Conf.main.base_dir.get()\n with qth.save_restore_stds():\n filename, _fl = getsavefilename(self, _(\"Save\"), basedir, \"HDF5 (*.h5)\")\n if not filename:\n return\n with qth.qt_try_loadsave_file(self, filename, \"save\"):\n filename = self.__check_h5file(filename, \"save\")\n self.h5inputoutput.save_file(filename)\n self.set_modified(False)\n\n @remote_controlled\n def open_h5_files(\n self,\n h5files: list[str] | None = None,\n import_all: bool | None = None,\n reset_all: bool | None = None,\n ) -> None:\n \"\"\"Open a DataLab HDF5 file or import from any other HDF5 file.\n\n Args:\n h5files: HDF5 filenames (optionally with dataset name, separated by \":\")\n import_all (bool): Import all datasets from HDF5 files\n reset_all (bool): Reset all application data before importing\n\n Returns:\n None\n \"\"\"\n if not self.confirm_memory_state():\n return\n if reset_all is None:\n reset_all = False\n if self.has_objects():\n answer = QW.QMessageBox.question(\n self,\n _(\"Warning\"),\n _(\n \"Do you want to remove all signals and images \"\n \"before importing data from HDF5 files?\"\n ),\n QW.QMessageBox.Yes | QW.QMessageBox.No,\n )\n if answer == QW.QMessageBox.Yes:\n reset_all = True\n if h5files is None:\n basedir = Conf.main.base_dir.get()\n with qth.save_restore_stds():\n h5files, _fl = getopenfilenames(self, _(\"Open\"), basedir, \"HDF5 (*.h5)\")\n for fname_with_dset in h5files:\n if \",\" in fname_with_dset:\n filename, dsetname = fname_with_dset.split(\",\")\n else:\n filename, dsetname = fname_with_dset, None\n if import_all is None and dsetname is None:\n self.import_h5_file(filename, reset_all)\n else:\n with qth.qt_try_loadsave_file(self, filename, \"load\"):\n filename = self.__check_h5file(filename, \"load\")\n if dsetname is None:\n self.h5inputoutput.open_file(filename, import_all, reset_all)\n else:\n self.h5inputoutput.import_dataset_from_file(filename, dsetname)\n reset_all = False\n\n @remote_controlled\n def import_h5_file(self, filename: str, reset_all: bool | None = None) -> None:\n \"\"\"Import HDF5 file into DataLab\n\n Args:\n filename (str): HDF5 filename (optionally with dataset name,\n separated by \":\")\n reset_all (bool): Delete all DataLab signals/images before importing data\n\n Returns:\n None\n \"\"\"\n with qth.qt_try_loadsave_file(self, filename, \"load\"):\n filename = self.__check_h5file(filename, \"load\")\n self.h5inputoutput.import_file(filename, False, reset_all)\n\n # This method is intentionally *not* remote controlled\n # (see TODO regarding RemoteClient.add_object method)\n # @remote_controlled\n def add_object(self, obj: SignalObj | ImageObj) -> None:\n \"\"\"Add object - signal or image\n\n Args:\n obj (SignalObj or ImageObj): object to add (signal or image)\n \"\"\"\n if self.confirm_memory_state():\n if isinstance(obj, SignalObj):\n self.signalpanel.add_object(obj)\n elif isinstance(obj, ImageObj):\n self.imagepanel.add_object(obj)\n else:\n raise TypeError(f\"Unsupported object type {type(obj)}\")\n\n @remote_controlled\n def open_object(self, filename: str) -> None:\n \"\"\"Open object from file in current panel (signal/image)\n\n Args:\n filename (str): HDF5 filename\n\n Returns:\n None\n \"\"\"\n panel = self.tabwidget.currentWidget()\n panel.open_object(filename)\n\n # ------Other methods related to AbstractCDLControl interface\n def get_version(self) -> str:\n \"\"\"Return DataLab version.\n\n Returns:\n str: DataLab version\n \"\"\"\n return __version__\n\n def close_application(self) -> None: # Implementing AbstractCDLControl interface\n \"\"\"Close DataLab application\"\"\"\n self.close()\n\n def raise_window(self) -> None: # Implementing AbstractCDLControl interface\n \"\"\"Raise DataLab window\"\"\"\n bring_to_front(self)\n\n def add_signal(\n self,\n title: str,\n xdata: np.ndarray,\n ydata: np.ndarray,\n xunit: str | None = None,\n yunit: str | None = None,\n xlabel: str | None = None,\n ylabel: str | None = None,\n ) -> bool: # pylint: disable=too-many-arguments\n \"\"\"Add signal data to DataLab.\n\n Args:\n title (str): Signal title\n xdata (numpy.ndarray): X data\n ydata (numpy.ndarray): Y data\n xunit (str | None): X unit. Defaults to None.\n yunit (str | None): Y unit. Defaults to None.\n xlabel (str | None): X label. Defaults to None.\n ylabel (str | None): Y label. Defaults to None.\n\n Returns:\n bool: True if signal was added successfully, False otherwise\n\n Raises:\n ValueError: Invalid xdata dtype\n ValueError: Invalid ydata dtype\n \"\"\"\n obj = create_signal(\n title,\n xdata,\n ydata,\n units=(xunit, yunit),\n labels=(xlabel, ylabel),\n )\n self.add_object(obj)\n return True\n\n def add_image(\n self,\n title: str,\n data: np.ndarray,\n xunit: str | None = None,\n yunit: str | None = None,\n zunit: str | None = None,\n xlabel: str | None = None,\n ylabel: str | None = None,\n zlabel: str | None = None,\n ) -> bool: # pylint: disable=too-many-arguments\n \"\"\"Add image data to DataLab.\n\n Args:\n title (str): Image title\n data (numpy.ndarray): Image data\n xunit (str | None): X unit. Defaults to None.\n yunit (str | None): Y unit. Defaults to None.\n zunit (str | None): Z unit. Defaults to None.\n xlabel (str | None): X label. Defaults to None.\n ylabel (str | None): Y label. Defaults to None.\n zlabel (str | None): Z label. Defaults to None.\n\n Returns:\n bool: True if image was added successfully, False otherwise\n\n Raises:\n ValueError: Invalid data dtype\n \"\"\"\n obj = create_image(\n title,\n data,\n units=(xunit, yunit, zunit),\n labels=(xlabel, ylabel, zlabel),\n )\n self.add_object(obj)\n return True\n\n # ------?\n def __about(self) -> None: # pragma: no cover\n \"\"\"About dialog box\"\"\"\n self.check_stable_release()\n if self.remote_server.port is None:\n xrpcstate = '<font color=\"red\">' + _(\"not started\") + \"</font>\"\n else:\n xrpcstate = _(\"started (port %s)\") % self.remote_server.port\n xrpcstate = f\"<font color='green'>{xrpcstate}</font>\"\n if Conf.main.process_isolation_enabled.get():\n pistate = \"<font color='green'>\" + _(\"enabled\") + \"</font>\"\n else:\n pistate = \"<font color='red'>\" + _(\"disabled\") + \"</font>\"\n adv_conf = \"<br>\".join(\n [\n \"<i>\" + _(\"Advanced configuration:\") + \"</i>\",\n \"• \" + _(\"XML-RPC server:\") + \" \" + xrpcstate,\n \"• \" + _(\"Process isolation:\") + \" \" + pistate,\n ]\n )\n pinfos = PluginRegistry.get_plugin_infos()\n created_by = _(\"Created by\")\n dev_by = _(\"Developed and maintained by %s open-source project team\") % APP_NAME\n copyrght = \"2023 Codra\"\n QW.QMessageBox.about(\n self,\n _(\"About\") + \" \" + APP_NAME,\n f\"\"\"<b>{APP_NAME}</b> v{__version__}<br>{APP_DESC}\n <p>{created_by} Pierre Raybaut<br>{dev_by}<br>Copyright &copy; {copyrght}\n <p>{adv_conf}<br><br>{pinfos}\"\"\",\n )\n\n def __edit_settings(self) -> None:\n \"\"\"Edit settings\"\"\"\n changed_options = edit_settings(self)\n for option in changed_options:\n if option == \"plot_toolbar_position\":\n for dock in self.docks.values():\n widget = dock.widget()\n if isinstance(widget, DockablePlotWidget):\n widget.update_toolbar_position()\n if option == \"ima_defaults\" and len(self.imagepanel) > 0:\n answer = QW.QMessageBox.question(\n self,\n _(\"Visualization settings\"),\n _(\n \"Default visualization settings have changed.<br><br>\"\n \"Do you want to update all active %s objects?\"\n )\n % _(\"image\"),\n QW.QMessageBox.Yes | QW.QMessageBox.No,\n )\n if answer == QW.QMessageBox.Yes:\n self.imagepanel.update_metadata_view_settings()\n\n def __show_logviewer(self) -> None:\n \"\"\"Show error logs\"\"\"\n logviewer.exec_cdl_logviewer_dialog(self)\n\n @staticmethod\n def test_segfault_error() -> None:\n \"\"\"Generate errors (both fault and traceback)\"\"\"\n import ctypes # pylint: disable=import-outside-toplevel\n\n ctypes.string_at(0)\n raise RuntimeError(\"!!! Testing RuntimeError !!!\")\n\n def show(self) -> None:\n \"\"\"Reimplement QMainWindow method\"\"\"\n super().show()\n if self.__old_size is not None:\n self.resize(self.__old_size)\n\n # ------Close window\n def close_properly(self) -> bool:\n \"\"\"Close properly\n\n Returns:\n bool: True if closed properly, False otherwise\n \"\"\"\n if not env.execenv.unattended and self.__is_modified:\n answer = QW.QMessageBox.warning(\n self,\n _(\"Quit\"),\n _(\n \"Do you want to save all signals and images \"\n \"to an HDF5 file before quitting DataLab?\"\n ),\n QW.QMessageBox.Yes | QW.QMessageBox.No | QW.QMessageBox.Cancel,\n )\n if answer == QW.QMessageBox.Yes:\n self.save_to_h5_file()\n if self.__is_modified:\n return False\n elif answer == QW.QMessageBox.Cancel:\n return False\n for panel in self.panels:\n if panel is not None:\n panel.close()\n if self.console is not None:\n try:\n self.console.close()\n except RuntimeError:\n # TODO: [P3] Investigate further why the following error occurs when\n # restarting the mainwindow (this is *not* a production case):\n # \"RuntimeError: wrapped C/C++ object of type DockableConsole\n # has been deleted\".\n # Another solution to avoid this error would be to really restart\n # the application (run each unit test in a separate process), but\n # it would represent too much effort for an error occuring in test\n # configurations only.\n pass\n self.reset_all()\n self.__save_pos_and_size()\n self.__unregister_plugins()\n\n # Saving current tab for next session\n Conf.main.current_tab.set(self.tabwidget.currentIndex())\n\n execenv.log(self, \"closed properly\")\n return True\n\n def closeEvent(self, event: QG.QCloseEvent) -> None:\n \"\"\"Reimplement QMainWindow method\"\"\"\n if self.hide_on_close:\n self.__old_size = self.size()\n self.hide()\n else:\n if self.close_properly():\n self.SIG_CLOSING.emit()\n event.accept()\n else:\n event.ignore()" }, { "identifier": "data", "path": "cdl/tests/data.py", "snippet": "def get_test_signal(filename: str) -> cdl.obj.SignalObj:\ndef get_test_image(filename: str) -> cdl.obj.ImageObj:\ndef create_paracetamol_signal(\n size: int | None = None, title: str | None = None\n) -> cdl.obj.SignalObj:\ndef add_gaussian_noise_to_signal(\n signal: cdl.obj.SignalObj, p: GaussianNoiseParam | None = None\n) -> None:\ndef create_noisy_signal(\n noiseparam: GaussianNoiseParam | None = None,\n newparam: cdl.obj.NewSignalParam | None = None,\n addparam: cdl.obj.GaussLorentzVoigtParam | None = None,\n title: str | None = None,\n noised: bool | None = None,\n) -> cdl.obj.SignalObj:\ndef create_2d_steps_data(size: int, width: int, dtype: np.dtype) -> np.ndarray:\ndef create_2d_random(\n size: int, dtype: np.dtype, level: float = 0.1, seed: int = 1\n) -> np.ndarray:\ndef create_2d_gaussian(\n size: int,\n dtype: np.dtype,\n x0: float = 0,\n y0: float = 0,\n mu: float = 0.0,\n sigma: float = 2.0,\n amp: float | None = None,\n) -> np.ndarray:\ndef get_laser_spot_data() -> list[np.ndarray]:\ndef get_peak2d_data(\n p: PeakDataParam | None = None, seed: int | None = None, multi: bool = False\n) -> np.ndarray:\ndef __set_default_size_dtype(\n p: cdl.obj.NewImageParam | None = None,\n) -> cdl.obj.NewImageParam:\ndef add_gaussian_noise_to_image(\n image: cdl.obj.ImageObj, param: cdl.obj.NormalRandomParam\n) -> None:\ndef create_2dstep_image(\n p: cdl.obj.NewImageParam | None = None,\n) -> cdl.obj.ImageObj:\ndef create_ring_data(\n size: int, x0: int, y0: int, width: int, radius: int, intensity: int\n) -> np.ndarray:\ndef create_ring_image(p: RingParam | None = None) -> cdl.obj.ImageObj:\ndef create_peak2d_image(\n p: cdl.obj.NewImageParam | None = None,\n) -> cdl.obj.ImageObj:\ndef create_sincos_image(\n p: cdl.obj.NewImageParam | None = None,\n) -> cdl.obj.ImageObj:\ndef create_noisygauss_image(\n p: cdl.obj.NewImageParam | None = None,\n) -> cdl.obj.ImageObj:\ndef create_multigauss_image(\n p: cdl.obj.NewImageParam | None = None,\n) -> cdl.obj.ImageObj:\ndef create_annotated_image(title: str | None = None) -> cdl.obj.ImageObj:\ndef create_resultshapes() -> tuple[cdl.obj.ResultShape, ...]:\nclass GaussianNoiseParam(gds.DataSet):\nclass PeakDataParam(gds.DataSet):\nclass RingParam(gds.DataSet):" } ]
import abc import cdl.obj from guidata.qthelpers import ( get_std_icon, qt_app_context, win32_fix_title_bar_background, ) from guidata.widgets.codeeditor import CodeEditor from qtpy import QtWidgets as QW from cdl.config import _ from cdl.core.gui.main import CDLMainWindow from cdl.tests import data as test_data
16,132
# -*- coding: utf-8 -*- # # Licensed under the terms of the BSD 3-Clause # (see cdl/LICENSE for details) """ Application embedded test 1 DataLab main window is destroyed when closing application. It is rebuilt from scratch when reopening application. """ # pylint: disable=invalid-name # Allows short reference names like x, y, ... # guitest: show class HostWidget(QW.QWidget): """Host widget: menu with action buttons, log viewer""" def __init__(self, parent=None): super().__init__(parent) self.button_layout = QW.QVBoxLayout() self.logwidget = CodeEditor(self) self.logwidget.setMinimumWidth(500) grid_layout = QW.QGridLayout() grid_layout.addLayout(self.button_layout, 0, 0) grid_layout.addWidget(self.logwidget, 0, 1) self.setLayout(grid_layout) def log(self, message): """Log message""" self.logwidget.appendPlainText(message) def add_spacing(self, spacing: int) -> None: """Add spacing to button box""" self.button_layout.addSpacing(spacing) def add_label(self, text: str) -> None: """Add label to button box""" self.button_layout.addWidget(QW.QLabel(text)) def add_widget(self, obj: QW.QWidget, spacing_before: int = 0) -> None: """Add widget (QWidget) to button box""" if spacing_before > 0: self.add_spacing(spacing_before) self.button_layout.addWidget(obj) def add_button(self, title, slot, spacing_before=0, icon=None): """Add button""" btn = QW.QPushButton(title) if icon is not None: btn.setIcon(get_std_icon(icon)) btn.clicked.connect(lambda _checked=False: slot()) self.add_widget(btn, spacing_before=spacing_before) return btn def add_stretch(self): """Add stretch to button box""" self.button_layout.addStretch() class AbstractClientWindowMeta(type(QW.QMainWindow), abc.ABCMeta): """Mixed metaclass to avoid conflicts""" class AbstractClientWindow(QW.QMainWindow, metaclass=AbstractClientWindowMeta): """Abstract client window, to embed DataLab or connect to it""" PURPOSE = None INIT_BUTTON_LABEL = None SIG_TITLES = ("Oscilloscope", "Digitizer", "Radiometer", "Voltmeter", "Sensor") IMA_TITLES = ( "Camera", "Streak Camera", "Image Scanner", "Laser Beam Profiler", "Gated Imaging Camera", ) def __init__(self): super().__init__() win32_fix_title_bar_background(self) self.setWindowTitle(_("Host application")) self.setWindowIcon(get_std_icon("ComputerIcon"))
# -*- coding: utf-8 -*- # # Licensed under the terms of the BSD 3-Clause # (see cdl/LICENSE for details) """ Application embedded test 1 DataLab main window is destroyed when closing application. It is rebuilt from scratch when reopening application. """ # pylint: disable=invalid-name # Allows short reference names like x, y, ... # guitest: show class HostWidget(QW.QWidget): """Host widget: menu with action buttons, log viewer""" def __init__(self, parent=None): super().__init__(parent) self.button_layout = QW.QVBoxLayout() self.logwidget = CodeEditor(self) self.logwidget.setMinimumWidth(500) grid_layout = QW.QGridLayout() grid_layout.addLayout(self.button_layout, 0, 0) grid_layout.addWidget(self.logwidget, 0, 1) self.setLayout(grid_layout) def log(self, message): """Log message""" self.logwidget.appendPlainText(message) def add_spacing(self, spacing: int) -> None: """Add spacing to button box""" self.button_layout.addSpacing(spacing) def add_label(self, text: str) -> None: """Add label to button box""" self.button_layout.addWidget(QW.QLabel(text)) def add_widget(self, obj: QW.QWidget, spacing_before: int = 0) -> None: """Add widget (QWidget) to button box""" if spacing_before > 0: self.add_spacing(spacing_before) self.button_layout.addWidget(obj) def add_button(self, title, slot, spacing_before=0, icon=None): """Add button""" btn = QW.QPushButton(title) if icon is not None: btn.setIcon(get_std_icon(icon)) btn.clicked.connect(lambda _checked=False: slot()) self.add_widget(btn, spacing_before=spacing_before) return btn def add_stretch(self): """Add stretch to button box""" self.button_layout.addStretch() class AbstractClientWindowMeta(type(QW.QMainWindow), abc.ABCMeta): """Mixed metaclass to avoid conflicts""" class AbstractClientWindow(QW.QMainWindow, metaclass=AbstractClientWindowMeta): """Abstract client window, to embed DataLab or connect to it""" PURPOSE = None INIT_BUTTON_LABEL = None SIG_TITLES = ("Oscilloscope", "Digitizer", "Radiometer", "Voltmeter", "Sensor") IMA_TITLES = ( "Camera", "Streak Camera", "Image Scanner", "Laser Beam Profiler", "Gated Imaging Camera", ) def __init__(self): super().__init__() win32_fix_title_bar_background(self) self.setWindowTitle(_("Host application")) self.setWindowIcon(get_std_icon("ComputerIcon"))
self.cdl: CDLMainWindow = None
1
2023-11-09 16:56:03+00:00
24k
ingra14m/Tensor4D-DNeRF
exp_runner.py
[ { "identifier": "Dataset", "path": "models/dataset.py", "snippet": "class Dataset:\n def __init__(self, conf):\n super(Dataset, self).__init__()\n print('Load data: Begin')\n self.device = torch.device('cuda')\n self.conf = conf\n\n self.data_dir = conf.get_string('data_dir')\n self.render_cameras_name = conf.get_string('render_cameras_name')\n self.object_cameras_name = conf.get_string('object_cameras_name')\n\n self.camera_outside_sphere = conf.get_bool('camera_outside_sphere', default=True)\n self.scale_mat_scale = conf.get_float('scale_mat_scale', default=1.1)\n self.near = conf.get_float('near', default=-1)\n self.far = conf.get_float('far', default=-1)\n self.n_frames = conf.get_int('n_frames', default=128)\n\n camera_dict = np.load(os.path.join(self.data_dir, self.render_cameras_name))\n self.camera_dict = camera_dict\n self.images_lis = sorted(glob(os.path.join(self.data_dir, 'image/*.png')))\n self.n_images = len(self.images_lis)\n self.images_np = np.stack([cv.imread(im_name) for im_name in self.images_lis]) / 256.0\n self.masks_lis = sorted(glob(os.path.join(self.data_dir, 'mask/*.png')))\n self.masks_np = np.stack([cv.imread(im_name) for im_name in self.masks_lis]) / 256.0\n\n # world_mat is a projection matrix from world to image\n self.world_mats_np = [camera_dict['world_mat_%d' % idx].astype(np.float32) for idx in range(self.n_images)]\n self.fid_list = [torch.LongTensor(np.array([camera_dict['fid_%d' % idx]])) for idx in range(self.n_images)]\n self.scale_mats_np = []\n\n # scale_mat: used for coordinate normalization, we assume the scene to render is inside a unit sphere at origin.\n self.scale_mats_np = [camera_dict['scale_mat_%d' % idx].astype(np.float32) for idx in range(self.n_images)]\n\n self.intrinsics_all = []\n self.pose_all = []\n self.proj_all = []\n\n for scale_mat, world_mat in zip(self.scale_mats_np, self.world_mats_np):\n P = world_mat @ scale_mat\n P = P[:3, :4]\n intrinsics, pose = load_K_Rt_from_P(None, P)\n self.intrinsics_all.append(torch.from_numpy(intrinsics).float())\n self.pose_all.append(torch.from_numpy(pose).float())\n self.proj_all.append(torch.from_numpy(P).float())\n\n self.images = torch.from_numpy(self.images_np.astype(np.float32)).cpu() # [n_images, H, W, 3]\n self.masks = torch.from_numpy(self.masks_np.astype(np.float32)).cpu() # [n_images, H, W, 3]\n self.errors = self.masks[:, :, :, :1].clone()\n self.errors = F.interpolate(self.errors.permute(0, 3, 1, 2), (self.images.shape[1] // 8, self.images.shape[2] // 8), mode='bilinear')\n self.errors = F.max_pool2d(self.errors, 7, stride=1, padding=3)\n self.errors = self.errors.permute(0, 2, 3, 1)\n self.radius = torch.zeros(self.masks.shape[0], self.masks.shape[2], self.masks.shape[1], 1) # [n_images, W, H, 3]\n \n self.intrinsics_all = torch.stack(self.intrinsics_all).to(self.device) # [n_images, 4, 4]\n self.intrinsics_all_inv = torch.inverse(self.intrinsics_all) # [n_images, 4, 4]\n self.focal = self.intrinsics_all[0][0, 0]\n self.pose_all = torch.stack(self.pose_all).to(self.device) # [n_images, 4, 4]\n self.proj_all = torch.stack(self.proj_all).to(self.device)\n self.H, self.W = self.images.shape[1], self.images.shape[2]\n self.image_pixels = self.H * self.W\n self.fid_all = torch.stack(self.fid_list).to(self.device)\n self.time_emb_list = (self.fid_all / self.n_frames * 2) - 0.95\n\n object_bbox_min = np.array([-1.01, -1.01, -1.01, 1.0])\n object_bbox_max = np.array([ 1.01, 1.01, 1.01, 1.0])\n # Object scale mat: region of interest to **extract mesh**\n object_scale_mat = np.load(os.path.join(self.data_dir, self.object_cameras_name))['scale_mat_0']\n object_bbox_min = np.linalg.inv(self.scale_mats_np[0]) @ object_scale_mat @ object_bbox_min[:, None]\n object_bbox_max = np.linalg.inv(self.scale_mats_np[0]) @ object_scale_mat @ object_bbox_max[:, None]\n self.object_bbox_min = object_bbox_min[:3, 0]\n self.object_bbox_max = object_bbox_max[:3, 0]\n self.process_radius()\n\n print('Load data: End')\n\n def process_radius(self):\n for img_idx in tqdm(range(self.images.shape[0])):\n tx = torch.linspace(0, self.W - 1, self.W, device=self.device)\n ty = torch.linspace(0, self.H - 1, self.H, device=self.device)\n pixels_x, pixels_y = torch.meshgrid(tx, ty)\n p = torch.stack([pixels_x, pixels_y, torch.ones_like(pixels_y)], dim=-1) # W, H, 3\n rays_v = torch.matmul(self.intrinsics_all_inv[img_idx, None, None, :3, :3], p[:, :, :, None]).squeeze() # W, H, 3\n rays_v = torch.matmul(self.pose_all[img_idx, None, None, :3, :3], rays_v[:, :, :, None]).squeeze() # W, H, 3\n dx = torch.sqrt(torch.sum((rays_v[:-1, :, :] - rays_v[1:, :, :]) ** 2, dim=-1))\n dx = torch.cat([dx, dx[-2:-1, :]], dim=0)\n # Cut the distance in half, and then round it out so that it's\n # halfway between inscribed by / circumscribed about the pixel.\n radii = dx[..., None] * 2 / np.sqrt(12)\n self.radius[img_idx] = radii.detach().cpu() # W H 3\n\n def gen_rays_at(self, img_idx, resolution_level=1):\n \"\"\"\n Generate rays at world space from one camera.\n \"\"\"\n l = resolution_level\n tx = torch.linspace(0, self.W - 1, self.W // l, device=self.device)\n ty = torch.linspace(0, self.H - 1, self.H // l, device=self.device)\n pixels_x, pixels_y = torch.meshgrid(tx, ty)\n p = torch.stack([pixels_x, pixels_y, torch.ones_like(pixels_y)], dim=-1) # W, H, 3\n rays_v = torch.matmul(self.intrinsics_all_inv[img_idx, None, None, :3, :3], p[:, :, :, None]).squeeze() # W, H, 3\n rays_v = torch.matmul(self.pose_all[img_idx, None, None, :3, :3], rays_v[:, :, :, None]).squeeze() # W, H, 3\n dx = torch.sqrt(torch.sum((rays_v[:-1, :, :] - rays_v[1:, :, :]) ** 2, dim=-1))\n dx = torch.cat([dx, dx[-2:-1, :]], dim=0)\n rays_r = dx[..., None] * 2 / np.sqrt(12)\n rays_o = self.pose_all[img_idx, None, None, :3, 3].expand(rays_v.shape) # W, H, 3\n rays_v = rays_v / torch.linalg.norm(rays_v, ord=2, dim=-1, keepdim=True) # W, H, 3\n return rays_o.transpose(0, 1), rays_v.transpose(0, 1), rays_r.transpose(0, 1)\n\n def gen_random_rays_at(self, img_idx, batch_size):\n \"\"\"\n Generate random rays at world space from one camera.\n \"\"\"\n error = self.errors[img_idx].reshape(-1).numpy()\n max_error = np.max(error) + 1e-8\n error = error / max_error\n error[error < 0.1] = 0.1\n error = error / np.sum(error)\n index = np.arange(0, self.W*self.H // 64)\n select_index = np.random.choice(index, size=[batch_size], p=error)\n pixels_y = torch.LongTensor(select_index // (self.W // 8)) * 8\n pixels_y += torch.randint_like(pixels_y, 8)\n pixels_x = torch.LongTensor(select_index % (self.W // 8)) * 8\n pixels_x += torch.randint_like(pixels_x, 8)\n\n color = self.images[img_idx][(pixels_y, pixels_x)] # batch_size, 3\n mask = self.masks[img_idx][(pixels_y, pixels_x)] # batch_size, 3\n rays_r = self.radius[img_idx][(pixels_x, pixels_y)] # batch_size, 1\n p = torch.stack([pixels_x, pixels_y, torch.ones_like(pixels_y)], dim=-1).float().to(self.device) # batch_size, 3\n p = torch.matmul(self.intrinsics_all_inv[img_idx, None, :3, :3], p[:, :, None]).squeeze() # batch_size, 3\n rays_v = p / torch.linalg.norm(p, ord=2, dim=-1, keepdim=True) # batch_size, 3\n rays_v = torch.matmul(self.pose_all[img_idx, None, :3, :3], rays_v[:, :, None]).squeeze() # batch_size, 3\n rays_o = self.pose_all[img_idx, None, :3, 3].expand(rays_v.shape) # batch_size, 3\n return torch.cat([rays_o.cpu(), rays_v.cpu(), color.cpu(), mask[:, :1].cpu(), rays_r.cpu()], dim=-1).cuda(), pixels_y.cpu(), pixels_x.cpu() # batch_size, 10\n\n def gen_rays_between(self, idx_0, idx_1, ratio, resolution_level=1):\n \"\"\"\n Interpolate pose between two cameras.\n \"\"\"\n l = resolution_level\n tx = torch.linspace(0, self.W - 1, self.W // l, device=self.device)\n ty = torch.linspace(0, self.H - 1, self.H // l, device=self.device)\n pixels_x, pixels_y = torch.meshgrid(tx, ty)\n p = torch.stack([pixels_x, pixels_y, torch.ones_like(pixels_y)], dim=-1) # W, H, 3\n rays_v = torch.matmul(self.intrinsics_all_inv[0, None, None, :3, :3], p[:, :, :, None]).squeeze() # W, H, 3\n trans = self.pose_all[idx_0, :3, 3] * (1.0 - ratio) + self.pose_all[idx_1, :3, 3] * ratio\n pose_0 = self.pose_all[idx_0].detach().cpu().numpy()\n pose_1 = self.pose_all[idx_1].detach().cpu().numpy()\n pose_0 = np.linalg.inv(pose_0)\n pose_1 = np.linalg.inv(pose_1)\n rot_0 = pose_0[:3, :3]\n rot_1 = pose_1[:3, :3]\n rots = Rot.from_matrix(np.stack([rot_0, rot_1]))\n key_times = [0, 1]\n slerp = Slerp(key_times, rots)\n rot = slerp(ratio)\n pose = np.diag([1.0, 1.0, 1.0, 1.0])\n pose = pose.astype(np.float32)\n pose[:3, :3] = rot.as_matrix()\n pose[:3, 3] = ((1.0 - ratio) * pose_0 + ratio * pose_1)[:3, 3]\n pose = np.linalg.inv(pose)\n rot = torch.from_numpy(pose[:3, :3]).cuda()\n trans = torch.from_numpy(pose[:3, 3]).cuda()\n rays_v = torch.matmul(rot[None, None, :3, :3], rays_v[:, :, :, None]).squeeze() # W, H, 3\n dx = torch.sqrt(torch.sum((rays_v[:-1, :, :] - rays_v[1:, :, :]) ** 2, dim=-1))\n dx = torch.cat([dx, dx[-2:-1, :]], dim=0)\n rays_r = dx[..., None] * 2 / np.sqrt(12)\n rays_v = rays_v / torch.linalg.norm(rays_v, ord=2, dim=-1, keepdim=True) # W, H, 3\n rays_o = trans[None, None, :3].expand(rays_v.shape) # W, H, 3\n return rays_o.transpose(0, 1), rays_v.transpose(0, 1), rays_r.transpose(0, 1)\n\n def near_far_from_sphere(self, rays_o, rays_d):\n if self.near > 0:\n return self.near, self.far\n a = torch.sum(rays_d**2, dim=-1, keepdim=True)\n b = 2.0 * torch.sum(rays_o * rays_d, dim=-1, keepdim=True)\n mid = 0.5 * (-b) / a\n near = mid - 1.0\n far = mid + 1.0\n return near, far\n\n def image_at(self, idx, resolution_level):\n img = cv.imread(self.images_lis[idx])\n return (cv.resize(img, (self.W // resolution_level, self.H // resolution_level))).clip(0, 255)" }, { "identifier": "BlenderDataset", "path": "models/dataset.py", "snippet": "class BlenderDataset:\n def __init__(self, conf):\n super(BlenderDataset, self).__init__()\n print('Load data: Begin')\n self.device = torch.device('cuda')\n self.conf = conf\n\n self.near = conf.get_float('near', default=-1)\n self.far = conf.get_float('far', default=-1)\n self.n_frames = conf.get_int('n_frames', default=128)\n\n self.data_dir = conf.get_string('data_dir')\n splits = ['train']\n metas = {}\n for s in splits:\n with open(os.path.join(self.data_dir, 'transforms_{}.json'.format(s)), 'r') as fp:\n metas[s] = json.load(fp)\n self.images_lis = sorted(glob(os.path.join(self.data_dir, 'train/*.png')), key=lambda x: int(x.split('.')[0].split('_')[-1]))\n # if self.data_dir.split('/')[-2] == 'lego':\n # # self.images_lis = self.images_lis[1:]\n # self.images_lis.append('/data00/yzy/Git_Project/data/dynamic/D-NeRF/lego/val/r_0.png')\n all_imgs = []\n all_poses = []\n all_masks = []\n all_times = []\n counts = [0]\n for s in splits:\n meta = metas[s]\n\n imgs = []\n poses = []\n times = []\n\n for t, frame in enumerate(meta['frames']):\n fname = os.path.join(self.data_dir, frame['file_path'] + '.png')\n image = cv.imread(fname, cv.IMREAD_UNCHANGED)\n imgs.append(image)\n pose = np.array(frame['transform_matrix'])\n time = np.array([frame['time']])\n\n a = pose[:, 0:1]\n b = pose[:, 1:2]\n c = pose[:, 2:3]\n d = pose[:, 3:].copy()\n d[:3, :] *= 0.8\n\n pose = np.concatenate([a, -b, -c, d], 1)\n\n poses.append(pose)\n times.append(time)\n\n imgs = (np.array(imgs) / 255.).astype(np.float32) # keep all 4 channels (RGBA)\n poses = np.array(poses).astype(np.float32)\n times = np.array(times).astype(np.float32)\n masks = (imgs[..., 3:] > 0).astype(np.float32)\n imgs = imgs[..., :3]\n counts.append(counts[-1] + imgs.shape[0])\n all_imgs.append(imgs)\n all_poses.append(poses)\n all_masks.append(masks)\n all_times.append(times)\n\n self.images = torch.from_numpy(np.concatenate(all_imgs, 0)).cpu()\n self.masks = torch.from_numpy(np.concatenate(all_masks, 0)).cpu()\n self.radius = torch.zeros(self.masks.shape[0], self.masks.shape[2], self.masks.shape[1], 1) # no use\n self.errors = self.masks[:, :, :, :1].clone()\n self.errors = F.interpolate(self.errors.permute(0, 3, 1, 2),\n (self.images.shape[1] // 8, self.images.shape[2] // 8), mode='bilinear')\n self.errors = F.max_pool2d(self.errors, 7, stride=1, padding=3)\n self.errors = self.errors.permute(0, 2, 3, 1)\n self.n_images = self.images.shape[0]\n\n self.fid_list = [torch.LongTensor(np.array([idx])) for idx in range(self.n_images)]\n # if self.data_dir.split('/')[-2] == 'lego':\n # self.fid_list[-1] = torch.LongTensor(np.array([0]))\n self.pose_all = torch.from_numpy(np.concatenate(all_poses, 0)).to(self.device)\n self.fid_all = torch.stack(self.fid_list).to(self.device)\n self.time_emb_list = torch.from_numpy(np.concatenate(all_times, 0)).to(self.device)\n\n self.H, self.W = self.images[0].shape[:2]\n self.image_pixels = self.H * self.W\n\n camera_angle_x = float(meta['camera_angle_x'])\n self.focal = .5 * self.W / np.tan(.5 * camera_angle_x)\n intrinsics = torch.Tensor(\n [[self.focal, 0, 0.5 * self.W, 0],\n [0, self.focal, 0.5 * self.H, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]]).to(self.device)\n self.intrinsics_all = intrinsics.expand(self.n_images, -1, -1)\n self.intrinsics_all_inv = torch.inverse(self.intrinsics_all) # [n_images, 4, 4]\n self.object_bbox_min = np.array([-1.01, -1.01, -1.01]) # hard code bbox\n self.object_bbox_max = np.array([1.01, 1.01, 1.01])\n self.process_radius()\n\n print('Load data: End')\n\n def process_radius(self):\n for img_idx in tqdm(range(self.images.shape[0])):\n tx = torch.linspace(0, self.W - 1, self.W, device=self.device)\n ty = torch.linspace(0, self.H - 1, self.H, device=self.device)\n pixels_x, pixels_y = torch.meshgrid(tx, ty)\n p = torch.stack([pixels_x, pixels_y, torch.ones_like(pixels_y)], dim=-1) # W, H, 3\n rays_v = torch.matmul(self.intrinsics_all_inv[img_idx, None, None, :3, :3], p[:, :, :, None]).squeeze() # W, H, 3\n rays_v = torch.matmul(self.pose_all[img_idx, None, None, :3, :3], rays_v[:, :, :, None]).squeeze() # W, H, 3\n dx = torch.sqrt(torch.sum((rays_v[:-1, :, :] - rays_v[1:, :, :]) ** 2, dim=-1))\n dx = torch.cat([dx, dx[-2:-1, :]], dim=0)\n # Cut the distance in half, and then round it out so that it's\n # halfway between inscribed by / circumscribed about the pixel.\n radii = dx[..., None] * 2 / np.sqrt(12)\n self.radius[img_idx] = radii.detach().cpu() # W H 3\n\n def gen_rays_at(self, img_idx, resolution_level=1):\n \"\"\"\n Generate rays at world space from one camera.\n \"\"\"\n l = resolution_level\n tx = torch.linspace(0, self.W - 1, self.W // l, device=self.device)\n ty = torch.linspace(0, self.H - 1, self.H // l, device=self.device)\n pixels_x, pixels_y = torch.meshgrid(tx, ty)\n p = torch.stack([pixels_x, pixels_y, torch.ones_like(pixels_y)], dim=-1) # W, H, 3\n rays_v = torch.matmul(self.intrinsics_all_inv[img_idx, None, None, :3, :3],\n p[:, :, :, None]).squeeze() # W, H, 3\n rays_v = torch.matmul(self.pose_all[img_idx, None, None, :3, :3], rays_v[:, :, :, None]).squeeze() # W, H, 3\n dx = torch.sqrt(torch.sum((rays_v[:-1, :, :] - rays_v[1:, :, :]) ** 2, dim=-1))\n dx = torch.cat([dx, dx[-2:-1, :]], dim=0)\n rays_r = dx[..., None] * 2 / np.sqrt(12)\n rays_o = self.pose_all[img_idx, None, None, :3, 3].expand(rays_v.shape) # W, H, 3\n rays_v = rays_v / torch.linalg.norm(rays_v, ord=2, dim=-1, keepdim=True) # W, H, 3\n return rays_o.transpose(0, 1), rays_v.transpose(0, 1), rays_r.transpose(0, 1)\n\n def gen_random_rays_at(self, img_idx, batch_size):\n \"\"\"\n Generate random rays at world space from one camera.\n \"\"\"\n error = self.errors[img_idx].reshape(-1).numpy()\n max_error = np.max(error) + 1e-8\n error = error / max_error\n error[error < 0.1] = 0.1\n error = error / np.sum(error)\n index = np.arange(0, self.W * self.H // 64)\n select_index = np.random.choice(index, size=[batch_size], p=error)\n pixels_y = torch.LongTensor(select_index // (self.W // 8)) * 8\n pixels_y += torch.randint_like(pixels_y, 8)\n pixels_x = torch.LongTensor(select_index % (self.W // 8)) * 8\n pixels_x += torch.randint_like(pixels_x, 8)\n\n color = self.images[img_idx][(pixels_y, pixels_x)] # batch_size, 3\n mask = self.masks[img_idx][(pixels_y, pixels_x)] # batch_size, 3\n rays_r = self.radius[img_idx][(pixels_x, pixels_y)] # batch_size, 1\n p = torch.stack([pixels_x, pixels_y, torch.ones_like(pixels_y)], dim=-1).float().to(\n self.device) # batch_size, 3\n p = torch.matmul(self.intrinsics_all_inv[img_idx, None, :3, :3], p[:, :, None]).squeeze() # batch_size, 3\n rays_v = p / torch.linalg.norm(p, ord=2, dim=-1, keepdim=True) # batch_size, 3\n rays_v = torch.matmul(self.pose_all[img_idx, None, :3, :3], rays_v[:, :, None]).squeeze() # batch_size, 3\n rays_o = self.pose_all[img_idx, None, :3, 3].expand(rays_v.shape) # batch_size, 3\n return torch.cat([rays_o.cpu(), rays_v.cpu(), color.cpu(), mask[:, :1].cpu(), rays_r.cpu()],\n dim=-1).cuda(), pixels_y.cpu(), pixels_x.cpu() # batch_size, 10\n\n def gen_rays_between(self, idx_0, idx_1, ratio, resolution_level=1):\n \"\"\"\n Interpolate pose between two cameras.\n \"\"\"\n l = resolution_level\n tx = torch.linspace(0, self.W - 1, self.W // l, device=self.device)\n ty = torch.linspace(0, self.H - 1, self.H // l, device=self.device)\n pixels_x, pixels_y = torch.meshgrid(tx, ty)\n p = torch.stack([pixels_x, pixels_y, torch.ones_like(pixels_y)], dim=-1) # W, H, 3\n rays_v = torch.matmul(self.intrinsics_all_inv[0, None, None, :3, :3], p[:, :, :, None]).squeeze() # W, H, 3\n trans = self.pose_all[idx_0, :3, 3] * (1.0 - ratio) + self.pose_all[idx_1, :3, 3] * ratio\n pose_0 = self.pose_all[idx_0].detach().cpu().numpy()\n pose_1 = self.pose_all[idx_1].detach().cpu().numpy()\n pose_0 = np.linalg.inv(pose_0)\n pose_1 = np.linalg.inv(pose_1)\n rot_0 = pose_0[:3, :3]\n rot_1 = pose_1[:3, :3]\n rots = Rot.from_matrix(np.stack([rot_0, rot_1]))\n key_times = [0, 1]\n slerp = Slerp(key_times, rots)\n rot = slerp(ratio)\n pose = np.diag([1.0, 1.0, 1.0, 1.0])\n pose = pose.astype(np.float32)\n pose[:3, :3] = rot.as_matrix()\n pose[:3, 3] = ((1.0 - ratio) * pose_0 + ratio * pose_1)[:3, 3]\n pose = np.linalg.inv(pose)\n rot = torch.from_numpy(pose[:3, :3]).cuda()\n trans = torch.from_numpy(pose[:3, 3]).cuda()\n rays_v = torch.matmul(rot[None, None, :3, :3], rays_v[:, :, :, None]).squeeze() # W, H, 3\n dx = torch.sqrt(torch.sum((rays_v[:-1, :, :] - rays_v[1:, :, :]) ** 2, dim=-1))\n dx = torch.cat([dx, dx[-2:-1, :]], dim=0)\n rays_r = dx[..., None] * 2 / np.sqrt(12)\n rays_v = rays_v / torch.linalg.norm(rays_v, ord=2, dim=-1, keepdim=True) # W, H, 3\n rays_o = trans[None, None, :3].expand(rays_v.shape) # W, H, 3\n return rays_o.transpose(0, 1), rays_v.transpose(0, 1), rays_r.transpose(0, 1)\n\n def near_far_from_sphere(self, rays_o, rays_d):\n if self.near > 0:\n return self.near, self.far\n a = torch.sum(rays_d ** 2, dim=-1, keepdim=True)\n b = 2.0 * torch.sum(rays_o * rays_d, dim=-1, keepdim=True)\n mid = 0.5 * (-b) / a\n near = mid - 1.0\n far = mid + 1.0\n return near, far\n\n def image_at(self, idx, resolution_level):\n img = cv.imread(self.images_lis[idx])\n return (cv.resize(img, (self.W // resolution_level, self.H // resolution_level))).clip(0, 255)" }, { "identifier": "RenderingNetwork", "path": "models/fields.py", "snippet": "class RenderingNetwork(nn.Module):\n def __init__(self,\n d_feature,\n mode,\n d_in,\n d_out,\n d_hidden,\n n_layers,\n weight_norm=True,\n multires_view=0,\n squeeze_out=True):\n super().__init__()\n\n self.mode = mode\n self.squeeze_out = squeeze_out\n dims = [d_in + d_feature] + [d_hidden for _ in range(n_layers)] + [d_out]\n\n self.embedview_fn = None\n if multires_view > 0:\n embedview_fn, input_ch = get_embedder(multires_view)\n self.embedview_fn = embedview_fn\n dims[0] += (input_ch - 3)\n\n self.num_layers = len(dims)\n\n for l in range(0, self.num_layers - 1):\n out_dim = dims[l + 1]\n lin = nn.Linear(dims[l], out_dim)\n if weight_norm:\n lin = nn.utils.weight_norm(lin)\n\n setattr(self, \"lin\" + str(l), lin)\n\n self.relu = nn.ReLU()\n\n self.mask = -torch.ones((1, 1, 256, 256, 256)).float().cuda()\n \n\n def forward(self, points, normals, view_dirs, feature_vectors):\n if self.embedview_fn is not None:\n view_dirs = self.embedview_fn(view_dirs)\n\n rendering_input = NoOptionError\n\n if self.mode == 'idr':\n rendering_input = torch.cat([points, view_dirs, normals, feature_vectors], dim=-1)\n elif self.mode == 'no_view_dir':\n rendering_input = torch.cat([points, normals, feature_vectors], dim=-1)\n elif self.mode == 'no_normal':\n rendering_input = torch.cat([points, view_dirs, feature_vectors], dim=-1)\n\n x = rendering_input\n for l in range(0, self.num_layers - 1):\n lin = getattr(self, \"lin\" + str(l))\n\n x = lin(x)\n\n if l < self.num_layers - 2:\n x = self.relu(x)\n\n if self.squeeze_out:\n x = torch.sigmoid(x)\n return x" }, { "identifier": "FieldNetwork", "path": "models/fields.py", "snippet": "class FieldNetwork(nn.Module):\n def __init__(self,\n d_in,\n d_out,\n d_hidden,\n d_t4d,\n min_emb,\n max_emb,\n n_layers,\n t_emb=-1,\n skip_in=(4,),\n bias=0.5,\n geometric_init=True,\n weight_norm=True):\n super(FieldNetwork, self).__init__()\n\n dims = [d_in] + [d_hidden for _ in range(n_layers)] + [d_out]\n dims[0] = d_in + (max_emb - min_emb)*3*2\n\n self.num_layers = len(dims)\n self.skip_in = skip_in\n self.min_emb = min_emb\n self.max_emb = max_emb\n self.t_emb = t_emb\n\n if t_emb > 0:\n embed_fn, time_input_ch = get_embedder(t_emb, input_dims=1)\n self.embed_fn = embed_fn\n dims[0] += time_input_ch\n\n for l in range(0, self.num_layers - 1):\n if l in self.skip_in:\n in_dim = dims[l] + dims[0] + d_t4d\n else:\n in_dim = dims[l]\n out_dim = dims[l+1]\n\n lin = nn.Linear(in_dim, out_dim)\n \n if geometric_init:\n if l == self.num_layers - 2:\n torch.nn.init.normal_(lin.weight, mean=np.sqrt(np.pi) / np.sqrt(dims[l]), std=0.0001)\n torch.nn.init.constant_(lin.bias, -bias)\n elif l == 0:\n torch.nn.init.constant_(lin.bias, 0.0)\n torch.nn.init.constant_(lin.weight[:, 3:], 0.0)\n torch.nn.init.normal_(lin.weight[:, :3], 0.0, np.sqrt(2) / np.sqrt(out_dim))\n elif l in self.skip_in:\n torch.nn.init.constant_(lin.bias, 0.0)\n torch.nn.init.normal_(lin.weight, 0.0, np.sqrt(2) / np.sqrt(out_dim))\n torch.nn.init.constant_(lin.weight[:, -(dims[0] + d_t4d):], 0.0)\n else:\n torch.nn.init.constant_(lin.bias, 0.0)\n torch.nn.init.normal_(lin.weight, 0.0, np.sqrt(2) / np.sqrt(out_dim))\n\n if weight_norm:\n lin = nn.utils.weight_norm(lin)\n\n setattr(self, \"lin\" + str(l), lin)\n\n self.activation = nn.Softplus(beta=100)\n\n def set_tensor4d(self, tensor4d):\n self.tensor4d = tensor4d\n\n def forward(self, mean, cov, fid, time_emb, reg_l2=False):\n cones_embedding = integrated_pos_enc((mean[:, None, :], cov[:, None, :]), self.min_emb, self.max_emb, diagonal=True).reshape(mean.shape[0], -1)\n inputs = mean\n tri_feat = self.tensor4d(inputs, fid, torch.mean(time_emb))\n\n if reg_l2:\n d_vec = F.normalize(torch.randn_like(inputs), dim=-1) * 1e-3\n d_tri_feat = self.tensor4d(inputs + d_vec, fid, torch.mean(time_emb))\n pred_reg_l2 = (d_tri_feat - tri_feat)**2\n \n xyz = inputs\n if self.t_emb > 0:\n time_input = self.embed_fn(time_emb)\n x = torch.cat([xyz, cones_embedding, time_input], 1)\n else:\n x = torch.cat([xyz, cones_embedding], 1)\n\n for l in range(0, self.num_layers - 1):\n lin = getattr(self, \"lin\" + str(l))\n \n if l in self.skip_in:\n if self.t_emb > 0:\n x = torch.cat([x, tri_feat, xyz, cones_embedding, time_input], 1) / np.sqrt(2)\n else:\n x = torch.cat([x, tri_feat, xyz, cones_embedding], 1) / np.sqrt(2)\n x = lin(x)\n\n if l < self.num_layers - 2:\n x = self.activation(x)\n if reg_l2:\n return x, pred_reg_l2\n return x" }, { "identifier": "SingleVarianceNetwork", "path": "models/fields.py", "snippet": "class SingleVarianceNetwork(nn.Module):\n def __init__(self, init_val):\n super(SingleVarianceNetwork, self).__init__()\n init_tensor = torch.zeros(120)\n init_tensor[:] = init_val\n self.register_parameter('variance', nn.Parameter(init_tensor))\n\n def forward(self, x):\n return torch.ones([len(x), 1], device=x.device) * torch.exp(self.variance[0] * 10.0)" }, { "identifier": "Tensor4D", "path": "models/tensor4d.py", "snippet": "class Tensor4D(nn.Module):\n def __init__(self, feature_type, lr_resolution, hr_resolution, image_guide=False, image_guide_interval=2, image_guide_base=16) -> None:\n super(Tensor4D, self).__init__()\n \n self.data_dims = 0\n self.feature_type = feature_type\n if feature_type == '3d':\n self.feature_plane = SpacePlane(lr_resolution, hr_resolution)\n self.data_dims = self.feature_plane.dims\n elif feature_type == '4d':\n self.feature_plane = TimeSpacePlane(lr_resolution, hr_resolution)\n self.data_dims = self.feature_plane.dims\n\n self.img_dims = 0\n self.image_guide = image_guide\n if image_guide:\n self.conv_net = ConvNet(image_guide_base)\n self.img_dims = image_guide_base*8*2\n self.ig_interval = image_guide_interval\n\n if feature_type == '4d':\n self.compress_network = CompressNetwork(self.data_dims, self.data_dims // 3)\n self.compress_list = [self.compress_network.compress1, self.compress_network.compress2, self.compress_network.compress3]\n\n self.dims = self.data_dims + self.img_dims\n self.matMode = torch.BoolTensor([[0, 1, 1], [1, 0, 1], [1, 1, 0]]).cuda()\n self.vecMode = torch.BoolTensor([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).cuda()\n \n def get_data_parameters(self):\n return list(self.feature_plane.parameters())\n \n def get_network_parameters(self):\n params = []\n if self.feature_type == '4d':\n params += list(self.compress_network.parameters())\n if self.image_guide:\n params += list(self.conv_net.parameters())\n return params\n\n def set_images(self, image, proj):\n step = self.ig_interval\n select_proj = torch.cat([proj[i*step:i*step+1] for i in range(proj.shape[0] // step)], dim=0)\n self.proj = select_proj\n self.img_shape = image.shape\n select_image = torch.cat([image[i*step:i*step+1] for i in range(image.shape[0] // step)], dim=0)\n self.image_feature, self.image_feature_hr = self.conv_net(F.interpolate(select_image.permute(0, 3, 1, 2), size=(1024, 1024)))\n\n def forward(self, xyz_sampled_ori, fid, time_emb):\n sigma_feature_list = [] \n\n if self.image_guide:\n proj_pts = ((self.proj[:, :3, :3] @ xyz_sampled_ori.T.unsqueeze(0)) + self.proj[:, :3, 3:]).transpose(1, 2)\n proj_xy = proj_pts[:, :, :2] / (proj_pts[:, :, 2:] + 1e-6)\n B, H, W, C = self.img_shape\n proj_xy[:, :, 0] = (proj_xy[:, :, 0] - W / 2) / (W / 2)\n proj_xy[:, :, 1] = (proj_xy[:, :, 1] - H / 2) / (H / 2)\n N = self.image_feature.shape[0]\n img_feature = grid_sample(self.image_feature, proj_xy.reshape(N, -1, 1, 2)).reshape(N, -1, xyz_sampled_ori.shape[0])\n img_feature_cost = torch.sqrt(torch.sum((img_feature - torch.sum(img_feature, dim=0).unsqueeze(0) / N)**2, dim=0) / N + 1e-8)\n img_feature_max = torch.mean(img_feature, dim=0) + torch.max(img_feature, dim=0)[0]\n image_feature_hr = grid_sample(self.image_feature_hr, proj_xy.reshape(N, -1, 1, 2)).reshape(N, -1, xyz_sampled_ori.shape[0])\n image_feature_hr_cost = torch.sqrt(torch.sum((image_feature_hr - torch.sum(image_feature_hr, dim=0).unsqueeze(0) / N)**2, dim=0) / N + 1e-8)\n image_feature_hr_max = torch.mean(image_feature_hr, dim=0) + torch.max(image_feature_hr, dim=0)[0]\n sigma_feature_list = [img_feature_cost, img_feature_max, image_feature_hr_cost, image_feature_hr_max]\n \n xyz_sampled = xyz_sampled_ori\n scale = 1.0\n matMode = self.matMode\n coordinate_plane = torch.stack((xyz_sampled[..., matMode[0]] * scale, xyz_sampled[..., matMode[1]] * scale, xyz_sampled[..., matMode[2]] * scale)).view(3, -1, 1, 2)\n\n for idx_plane in range(3):\n sample_points = coordinate_plane[[idx_plane]]\n plane_coef_point = self.feature_plane.sample(sample_points, idx_plane, time_emb).view(-1, *xyz_sampled.shape[:1])\n if self.feature_type == '4d':\n plane_coef_point = self.compress_list[idx_plane](plane_coef_point.T).T\n sigma_feature_list.append(plane_coef_point)\n \n sigma_feature_list = torch.cat(sigma_feature_list, dim=0)\n # print(sigma_feature_list.shape)\n return sigma_feature_list.T" }, { "identifier": "NeuSRenderer", "path": "models/renderer.py", "snippet": "class NeuSRenderer:\n def __init__(self,\n sdf_network,\n deviation_network,\n color_network,\n mask3d,\n n_samples,\n n_importance,\n n_outside,\n up_sample_steps,\n perturb,\n reg_l2=False,\n mip_render=False,\n flow_network=None):\n \n self.sdf_network = sdf_network\n self.deviation_network = deviation_network\n self.color_network = color_network\n self.mask3d = mask3d\n self.n_samples = n_samples\n self.n_importance = n_importance\n self.n_outside = n_outside\n self.up_sample_steps = up_sample_steps\n self.perturb = perturb\n self.reg_l2 = reg_l2\n self.flow_network = flow_network\n self.mip_render = mip_render\n\n def mask_query_geometry(self, mean, cov, only_sdf=False):\n fid = self.fid\n time_emb = self.time_emb\n time_input = time_emb.expand(mean[:, :1].shape)\n space_time_input = torch.cat([mean, time_input], dim=-1)\n if not only_sdf:\n space_time_input.requires_grad_(True)\n inputs = space_time_input[:, :3]\n time_emb = space_time_input[:, 3:]\n N, _ = inputs.shape\n grads = torch.zeros((N, 4), device=inputs.device)\n sdf_nn = torch.zeros((N, 257), device=inputs.device)\n\n reg_l2 = torch.zeros((N, self.sdf_network.tensor4d.dims), device=inputs.device)\n grads[:, 0] = 1\n sdf_nn[:, 0] = -10\n\n mask = self.mask3d.valid_input(inputs, fid)\n if torch.sum(mask) == 0:\n results = {\n 'sdf_nn': sdf_nn,\n 'grads': grads[:, :3],\n 'time_grads': grads[:, 3:],\n 'pts_mask': mask,\n 'reg_l2': reg_l2\n }\n return results\n mask_mean = inputs[mask, :]\n mask_time_emb = time_emb[mask, :]\n mask_cov = cov[mask, :]\n \n if self.flow_network is not None:\n mask_cov = torch.zeros_like(mask_mean) # flow mode, disable mip_render\n if fid != 0:\n pred_flow = self.flow_network(mask_mean, mask_cov, fid, mask_time_emb, reg_l2=False)\n mask_mean = mask_mean + pred_flow\n elif not self.mip_render:\n mask_cov = torch.zeros_like(mask_mean)\n\n if (not only_sdf) and self.reg_l2:\n pred_sdf_nn, pred_reg_l2 = self.sdf_network(mask_mean, mask_cov, fid, mask_time_emb, reg_l2=True)\n reg_l2[mask] = pred_reg_l2\n else:\n pred_sdf_nn = self.sdf_network(mask_mean, mask_cov, fid, mask_time_emb, reg_l2=False)\n\n if not only_sdf:\n pred_sdf = pred_sdf_nn[:, :1]\n d_output = torch.ones_like(pred_sdf, requires_grad=False, device=pred_sdf.device)\n gradients = torch.autograd.grad(\n outputs=pred_sdf,\n inputs=space_time_input,\n grad_outputs=d_output,\n create_graph=True,\n retain_graph=True,\n only_inputs=True)[0]\n grads[mask] = gradients.reshape(-1, 4)[mask]\n \n sdf_nn[mask] = pred_sdf_nn\n results = {\n 'sdf_nn': sdf_nn,\n 'grads': grads[:, :3],\n 'time_grads': grads[:, 3:],\n 'pts_mask': mask,\n 'reg_l2': reg_l2\n }\n return results\n\n def mask_query_color(self, pts, mask, normals, view_dirs, features):\n N, _ = pts.shape\n out = torch.zeros((N, 3), device=pts.device)\n if torch.sum(mask) > 0:\n x = self.color_network(pts[mask], normals[mask], view_dirs[mask], features[mask])\n out[mask] = x\n return out\n else:\n return torch.zeros((N, 3), device=pts.device)\n\n def up_sample(self, rays_o, rays_d, z_vals, sdf, n_importance, inv_s, pts_mask):\n \"\"\"\n Up sampling give a fixed inv_s\n \"\"\"\n batch_size, n_samples = z_vals.shape\n pts = rays_o[:, None, :] + rays_d[:, None, :] * z_vals[..., :, None] # n_rays, n_samples, 3\n radius = torch.linalg.norm(pts, ord=2, dim=-1, keepdim=False)\n inside_sphere = (radius[:, :-1] < 1.0) | (radius[:, 1:] < 1.0)\n sdf = sdf.reshape(batch_size, n_samples)\n prev_sdf, next_sdf = sdf[:, :-1], sdf[:, 1:]\n prev_mask, next_mask = pts_mask[:, :-1], pts_mask[:, 1:]\n mid_mask = torch.logical_and(prev_mask, next_mask)\n prev_z_vals, next_z_vals = z_vals[:, :-1], z_vals[:, 1:]\n mid_sdf = (prev_sdf + next_sdf) * 0.5\n cos_val = (next_sdf - prev_sdf) / (next_z_vals - prev_z_vals + 1e-5)\n\n # ----------------------------------------------------------------------------------------------------------\n # Use min value of [ cos, prev_cos ]\n # Though it makes the sampling (not rendering) a little bit biased, this strategy can make the sampling more\n # robust when meeting situations like below:\n #\n # SDF\n # ^\n # |\\ -----x----...\n # | \\ /\n # | x x\n # |---\\----/-------------> 0 level\n # | \\ /\n # | \\/\n # |\n # ----------------------------------------------------------------------------------------------------------\n prev_cos_val = torch.cat([torch.zeros([batch_size, 1], device=sdf.device), cos_val[:, :-1]], dim=-1)\n cos_val = torch.stack([prev_cos_val, cos_val], dim=-1)\n cos_val, _ = torch.min(cos_val, dim=-1, keepdim=False)\n cos_val = cos_val.clip(-1e3, 0.0) * inside_sphere\n\n dist = (next_z_vals - prev_z_vals)\n prev_esti_sdf = mid_sdf - cos_val * dist * 0.5\n next_esti_sdf = mid_sdf + cos_val * dist * 0.5\n prev_cdf = torch.sigmoid(prev_esti_sdf * inv_s)\n next_cdf = torch.sigmoid(next_esti_sdf * inv_s)\n\n alpha = (prev_cdf - next_cdf + 1e-5) / (prev_cdf + 1e-5)\n alpha[~mid_mask] = 0\n alpha = alpha.clamp(0.0, 1.0)\n \n alpha = torch.cat([alpha, torch.zeros([batch_size, 1], device=alpha.device)], dim=-1)\n weights = alpha * torch.cumprod(\n torch.cat([torch.ones([batch_size, 1], device=alpha.device), 1. - alpha + 1e-7], -1), -1)[:, :-1]\n\n z_samples = sample_pdf(z_vals, weights, n_importance, det=True).detach()\n return z_samples\n\n def cat_z_vals(self, rays_o, rays_d, z_vals, new_z_vals, sdf, pts_mask, last=False):\n batch_size, n_samples = z_vals.shape\n _, n_importance = new_z_vals.shape\n pts = rays_o[:, None, :] + rays_d[:, None, :] * new_z_vals[..., :, None]\n z_vals = torch.cat([z_vals, new_z_vals], dim=-1)\n z_vals, index = torch.sort(z_vals, dim=-1)\n if not last:\n new_sdf, new_pts_mask = self.sdf_network.sdf(pts.reshape(-1, 3), rt_mask=True)\n new_sdf = new_sdf.reshape(batch_size, n_importance)\n new_pts_mask = new_pts_mask.reshape(batch_size, n_importance)\n sdf = torch.cat([sdf, new_sdf], dim=-1)\n pts_mask = torch.cat([pts_mask, new_pts_mask], dim=-1)\n xx = torch.arange(batch_size)[:, None].expand(batch_size, n_samples + n_importance).reshape(-1)\n index = index.reshape(-1)\n sdf = sdf[(xx, index)].reshape(batch_size, n_samples + n_importance)\n pts_mask = pts_mask[(xx, index)].reshape(batch_size, n_samples + n_importance)\n\n return z_vals, sdf, pts_mask\n\n def render_core(self,\n rays_o,\n rays_d,\n rays_r,\n z_vals,\n sample_dist,\n background_alpha=None,\n background_sampled_color=None,\n background_rgb=None,\n cos_anneal_ratio=0.0):\n batch_size, n_samples = z_vals[:, :-1].shape\n\n # Section length\n dists = z_vals[..., 1:] - z_vals[..., :-1]\n cat_dists = torch.cat([dists, torch.Tensor([sample_dist]).to(dists.device).expand(dists[..., :1].shape)], -1)\n mid_z_vals = z_vals + cat_dists * 0.5\n\n cones = cast_rays(z_vals, rays_o, rays_d, rays_r, 'cone', diagonal=True)\n dirs = rays_d[:, None, :].expand(cones[0].shape)\n dirs = dirs.reshape(-1, 3)\n\n results = self.mask_query_geometry(cones[0].reshape(-1, 3), cones[1].reshape(-1, 3))\n sdf_nn_output, gradients, t_grads, pts_mask = results['sdf_nn'], results['grads'], results['time_grads'], results['pts_mask']\n sdf = sdf_nn_output[:, :1]\n feature_vector = sdf_nn_output[:, 1:]\n\n gradients = gradients.squeeze()\n sampled_color = self.mask_query_color(cones[0].reshape(-1, 3), pts_mask, gradients, dirs, feature_vector).reshape(batch_size, n_samples, 3)\n \n inv_s = self.deviation_network(torch.zeros([1, 3], device=sdf.device))[:, :1].clip(1e-6, 1e6) # Single parameter\n inv_s = inv_s.expand(batch_size * n_samples, 1)\n\n true_cos = (dirs * gradients).sum(-1, keepdim=True)\n\n # \"cos_anneal_ratio\" grows from 0 to 1 in the beginning training iterations. The anneal strategy below makes\n # the cos value \"not dead\" at the beginning training iterations, for better convergence.\n iter_cos = -(F.relu(-true_cos * 0.5 + 0.5) * (1.0 - cos_anneal_ratio) +\n F.relu(-true_cos) * cos_anneal_ratio) # always non-positive\n\n # Estimate signed distances at section points\n estimated_next_sdf = sdf + iter_cos * dists.reshape(-1, 1) * 0.5\n estimated_prev_sdf = sdf - iter_cos * dists.reshape(-1, 1) * 0.5\n\n prev_cdf = torch.sigmoid(estimated_prev_sdf * inv_s)\n next_cdf = torch.sigmoid(estimated_next_sdf * inv_s)\n\n p = prev_cdf - next_cdf\n c = prev_cdf\n\n alpha = ((p + 1e-5) / (c + 1e-5))\n \n alpha[~pts_mask] = 0\n alpha = alpha.reshape(batch_size, n_samples).clip(0.0, 1.0)\n \n weights = alpha * torch.cumprod(torch.cat([torch.ones([batch_size, 1], device=alpha.device), 1. - alpha + 1e-7], -1), -1)[:, :-1]\n weights_sum = weights.sum(dim=-1, keepdim=True)\n \n color = (sampled_color * weights[:, :, None]).sum(dim=1)\n if background_rgb is not None: # Fixed background, usually black\n color = color + background_rgb * (1.0 - weights_sum)\n\n # Eikonal loss\n gradient_error = torch.mean((torch.linalg.norm(gradients.reshape(batch_size, n_samples, 3), ord=2,\n dim=-1) - 1.0) ** 2)\n time_grad_error = torch.mean(t_grads**2)\n return {\n 'color': color,\n 'sdf': sdf,\n 'pts_mask': pts_mask,\n 'dists': dists,\n 'gradients': gradients.reshape(batch_size, n_samples, 3),\n 's_val': 1.0 / inv_s,\n 'mid_z_vals': mid_z_vals,\n 'weights': weights,\n 'gradient_error': gradient_error,\n 'time_grad_error': time_grad_error,\n 'reg_l2': results['reg_l2'].reshape(batch_size, n_samples, -1),\n }\n\n def render(self, rays_o, rays_d, rays_r, near, far, fid, time_emb, perturb_overwrite=-1, background_rgb=None, cos_anneal_ratio=0.0):\n self.fid = fid\n self.time_emb = time_emb\n self.mask3d.set_fid(fid)\n\n batch_size = len(rays_o)\n sample_dist = 2.0 / self.n_samples # Assuming the region of interest is a unit sphere\n z_vals = torch.linspace(0.0, 1.0, self.n_samples, device=rays_o.device)\n z_vals = near + (far - near) * z_vals[None, :]\n\n z_vals_outside = None\n \n n_samples = self.n_samples\n perturb = self.perturb\n\n if perturb_overwrite >= 0:\n perturb = perturb_overwrite\n if perturb > 0:\n t_rand = (torch.rand([batch_size, 1], device=z_vals.device) - 0.5)\n z_vals = z_vals + t_rand * 2.0 / self.n_samples\n\n background_alpha = None\n background_sampled_color = None\n\n # Up sample\n if self.n_importance > 0:\n with torch.no_grad():\n cast_z_vals = torch.cat([z_vals, z_vals[:, -1:]], dim=1)\n cones = cast_rays(cast_z_vals, rays_o, rays_d, rays_r, 'cone', diagonal=True)\n results = self.mask_query_geometry(cones[0].reshape(-1, 3), cones[1].reshape(-1, 3), only_sdf=True)\n sdf, pts_mask = results['sdf_nn'][:, :1], results['pts_mask']\n # sdf, pts_mask = self.sdf_network.sdf(pts.reshape(-1, 3), rt_mask=True)\n sdf = sdf.reshape(batch_size, self.n_samples)\n pts_mask = pts_mask.reshape(batch_size, self.n_samples)\n for i in range(self.up_sample_steps):\n new_z_vals = self.up_sample(rays_o,\n rays_d,\n z_vals,\n sdf,\n self.n_importance // self.up_sample_steps + 1,\n 64 * 2**i, pts_mask)\n z_vals, sdf, pts_mask = self.cat_z_vals(rays_o,\n rays_d,\n z_vals,\n new_z_vals,\n sdf, pts_mask,\n last=(i + 1 == self.up_sample_steps))\n\n n_samples = self.n_samples + self.n_importance\n\n background_alpha = None\n background_sampled_color = None\n sample_dist = 1e-2\n\n # Render core\n ret_fine = self.render_core(rays_o,\n rays_d,\n rays_r,\n z_vals,\n sample_dist,\n background_rgb=background_rgb,\n background_alpha=background_alpha,\n background_sampled_color=background_sampled_color,\n cos_anneal_ratio=cos_anneal_ratio)\n\n\n return {\n 'color_fine': ret_fine['color'],\n 's_val': ret_fine['s_val'].reshape(batch_size, n_samples).mean(dim=-1, keepdim=True),\n 'mid_z_vals': ret_fine['mid_z_vals'],\n 'weights': ret_fine['weights'],\n 'weight_sum': ret_fine['weights'].sum(dim=-1, keepdim=True),\n 'weight_max': torch.max(ret_fine['weights'], dim=-1, keepdim=True)[0],\n 'gradients': ret_fine['gradients'],\n 'gradient_error': ret_fine['gradient_error'],\n 'time_grad_error': ret_fine['time_grad_error'],\n 'reg_l2': ret_fine['reg_l2']\n }" }, { "identifier": "Mask3D", "path": "models/mask.py", "snippet": "class Mask3D:\n def __init__(self, mask_type, num_frames=None, mask_reso=None, device=None):\n self.mask_type = mask_type # 'bounding or visualhull'\n if mask_type == 'visualhull':\n self.R = mask_reso\n self.mask = torch.ones([num_frames, self.R, self.R, self.R]).float()\n self.device = device\n self.current_fid = -1\n self.current_mask = None\n\n def set_fid(self, fid):\n if fid != self.current_fid:\n self.current_fid = fid\n if self.mask_type == 'visualhull':\n self.current_mask = self.mask[fid.cpu()].to(self.device)\n \n def valid_input(self, pts, fid):\n with torch.no_grad():\n pts = pts.reshape(1, -1, 1, 1, 3)\n pts_max = torch.max(pts, dim=-1)[0]\n pts_min = torch.min(pts, dim=-1)[0]\n mask_max = (pts_max > 1).reshape(-1)\n mask_min = (pts_min < -1).reshape(-1)\n if self.mask_type == 'visualhull':\n R = self.R\n sigma = F.grid_sample(self.current_mask.view(1, 1, R, R, R), pts, mode='bilinear', padding_mode='border').reshape(-1)\n calc_mask = sigma < 0.05\n else:\n calc_mask = torch.ones_like(mask_max)\n calc_mask[mask_max] = 0\n calc_mask[mask_min] = 0\n return calc_mask\n\n def visualhull(self, pts_ori, projs, masks, g_nums):\n cam_nums = projs.shape[0]\n interval = 1\n pts_mask = torch.zeros(pts_ori.shape[0], g_nums)\n out_mask = torch.zeros(pts_ori.shape[0])\n N, H, W, C = masks.shape\n for gp in range(cam_nums // (g_nums*interval)):\n for j in range(g_nums):\n i = j + gp*(g_nums*interval)\n mask = masks[i, :, :, :1].permute(2, 0, 1).unsqueeze(0).clone()\n mask = torch.max_pool2d(mask, 7, 1, 3, 1)\n pts = torch.cat([pts_ori, torch.ones_like(pts_ori[:, :1])], dim=-1)\n pts = projs[i] @ pts.T\n pts = pts[:2] / pts[2:]\n pts[0] = pts[0] / W * 2 - 1\n pts[1] = pts[1] / H * 2 - 1\n pts = pts.T.reshape(1, -1, 1, 2)\n \n sample_mask = torch.nn.functional.grid_sample(mask, pts, mode='bilinear', padding_mode='zeros').reshape(-1)\n pts_mask[:, j] = sample_mask\n pts_mask_sum = torch.min(pts_mask, dim=1)[0]\n valid = pts_mask_sum > 0.1\n out_mask[valid] = -1\n if gp == 0:\n out_mask[~valid] = 1\n return out_mask\n\n def compute_image_mask(self, projs, masks, g_nums):\n N = 64\n R = self.R\n X = torch.linspace(-1, 1, R).split(N)\n Y = torch.linspace(-1, 1, R).split(N)\n Z = torch.linspace(-1, 1, R).split(N)\n cam_nums = projs.shape[0]\n \n self.mask = self.mask.to(self.device)\n for gp in tqdm(range(cam_nums // g_nums)):\n # for gp in range(1):\n with torch.no_grad():\n for xi, xs in enumerate(X):\n for yi, ys in enumerate(Y):\n for zi, zs in enumerate(Z):\n xx, yy, zz = torch.meshgrid(xs, ys, zs)\n pts = torch.cat([zz.reshape(-1, 1), yy.reshape(-1, 1), xx.reshape(-1, 1)], dim=-1).to(self.device)\n val = self.visualhull(pts, projs[gp*g_nums:gp*g_nums+g_nums].to(self.device), masks[gp*g_nums:gp*g_nums+g_nums].to(self.device), g_nums).reshape(len(xs), len(ys), len(zs))\n self.mask[gp, xi * N: xi * N + len(xs),yi * N: yi * N + len(ys), zi * N: zi * N + len(zs)] = val\n self.mask = self.mask.unsqueeze(1)\n self.mask = -torch.max_pool3d(-self.mask, 7, 1, 3)\n self.mask[self.mask > -0.5] = 1\n self.mask = self.mask.detach().cpu()\n \n def compute_mask(self, fid, query_func, inv_s):\n N = 64\n R = 128\n X = torch.linspace(-1, 1, R).split(N)\n Y = torch.linspace(-1, 1, R).split(N)\n Z = torch.linspace(-1, 1, R).split(N)\n from .renderer import sigma_f\n mask = self.mask[fid].reshape(R, R, R).clone()\n self.triplane[0].flow(fid)\n with torch.no_grad():\n for xi, xs in enumerate(X):\n for yi, ys in enumerate(Y):\n for zi, zs in enumerate(Z):\n xx, yy, zz = torch.meshgrid(xs, ys, zs)\n pts = torch.cat([zz.reshape(-1, 1), yy.reshape(-1, 1), xx.reshape(-1, 1)], dim=-1)\n val = sigma_f(query_func(pts), inv_s).reshape(len(xs), len(ys), len(zs))\n mask[xi * N: xi * N + len(xs),yi * N: yi * N + len(ys), zi * N: zi * N + len(zs)] = val\n valid = mask > 0.02\n mask[valid] = 1\n mask[~valid] = -1\n mask = -torch.max_pool3d(mask.reshape(1, 1, 128, 128, 128), 7, 1, 3)\n self.mask[fid][mask[0] > -0.5] = 1" } ]
import os import time import logging import argparse import numpy as np import cv2 as cv import torch import torch.nn.functional as F from torch.utils.tensorboard import SummaryWriter from shutil import copyfile from tqdm import tqdm from pyhocon import ConfigFactory from models.dataset import Dataset, BlenderDataset from models.fields import RenderingNetwork, FieldNetwork, SingleVarianceNetwork from models.tensor4d import Tensor4D from models.renderer import NeuSRenderer from models.mask import Mask3D from metrics import *
16,173
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' class Runner: def __init__(self, conf_path, mode='train', case='CASE_NAME', is_continue=False): self.device = torch.device('cuda') # Configuration self.conf_path = conf_path f = open(self.conf_path) conf_text = f.read() conf_text = conf_text.replace('CASE_NAME', case) f.close() self.conf = ConfigFactory.parse_string(conf_text) self.conf['dataset.data_dir'] = self.conf['dataset.data_dir'].replace('CASE_NAME', case) self.base_exp_dir = self.conf['general.base_exp_dir'] os.makedirs(self.base_exp_dir, exist_ok=True) self.is_blender = self.conf['dataset'].get_bool('is_blender', default=False) self.dataset = BlenderDataset(self.conf['dataset']) if self.is_blender else Dataset(self.conf['dataset']) self.g_nums = self.conf['dataset']['g_nums'] self.iter_step = 0 self.flow = self.conf.get_bool('model.flow', default=False) # Training parameters self.end_iter = self.conf.get_int('train.end_iter') self.save_freq = self.conf.get_int('train.save_freq') self.report_freq = self.conf.get_int('train.report_freq') self.val_freq = self.conf.get_int('train.val_freq') self.batch_size = self.conf.get_int('train.batch_size') self.fine_level_iter = self.conf.get_int('train.fine_level_iter') self.downsample_iter = self.conf.get_int('train.downsample_iter') self.validate_resolution_level = self.conf.get_int('train.validate_resolution_level') self.learning_rate = self.conf.get_float('train.learning_rate') self.learning_rate_alpha = self.conf.get_float('train.learning_rate_alpha') self.use_white_bkgd = self.conf.get_bool('train.use_white_bkgd') self.warm_up_end = self.conf.get_float('train.warm_up_end', default=0.0) self.warm_up_imgs = self.conf.get_int('train.warm_up_imgs', default=50) self.anneal_end = self.conf.get_float('train.anneal_end', default=0.0) self.mask_color_loss = self.conf.get_bool('train.mask_color_loss') self.weighted_sample = self.conf.get_bool('train.weighted_sample') # Weights self.igr_weight = self.conf.get_float('train.igr_weight') self.tgr_weight = self.conf.get_float('train.tgr_weight') self.mask_weight = self.conf.get_float('train.mask_weight') self.tv_weight = self.conf.get_float('train.tv_weight') if self.tv_weight > 0: self.reg_l2 = True else: self.reg_l2 = False self.is_continue = is_continue self.mode = mode self.model_list = [] self.writer = None # Masks self.mask3d = Mask3D(**self.conf['model.mask3d'], num_frames=self.dataset.n_images // self.g_nums, device=self.device) # Networks
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' class Runner: def __init__(self, conf_path, mode='train', case='CASE_NAME', is_continue=False): self.device = torch.device('cuda') # Configuration self.conf_path = conf_path f = open(self.conf_path) conf_text = f.read() conf_text = conf_text.replace('CASE_NAME', case) f.close() self.conf = ConfigFactory.parse_string(conf_text) self.conf['dataset.data_dir'] = self.conf['dataset.data_dir'].replace('CASE_NAME', case) self.base_exp_dir = self.conf['general.base_exp_dir'] os.makedirs(self.base_exp_dir, exist_ok=True) self.is_blender = self.conf['dataset'].get_bool('is_blender', default=False) self.dataset = BlenderDataset(self.conf['dataset']) if self.is_blender else Dataset(self.conf['dataset']) self.g_nums = self.conf['dataset']['g_nums'] self.iter_step = 0 self.flow = self.conf.get_bool('model.flow', default=False) # Training parameters self.end_iter = self.conf.get_int('train.end_iter') self.save_freq = self.conf.get_int('train.save_freq') self.report_freq = self.conf.get_int('train.report_freq') self.val_freq = self.conf.get_int('train.val_freq') self.batch_size = self.conf.get_int('train.batch_size') self.fine_level_iter = self.conf.get_int('train.fine_level_iter') self.downsample_iter = self.conf.get_int('train.downsample_iter') self.validate_resolution_level = self.conf.get_int('train.validate_resolution_level') self.learning_rate = self.conf.get_float('train.learning_rate') self.learning_rate_alpha = self.conf.get_float('train.learning_rate_alpha') self.use_white_bkgd = self.conf.get_bool('train.use_white_bkgd') self.warm_up_end = self.conf.get_float('train.warm_up_end', default=0.0) self.warm_up_imgs = self.conf.get_int('train.warm_up_imgs', default=50) self.anneal_end = self.conf.get_float('train.anneal_end', default=0.0) self.mask_color_loss = self.conf.get_bool('train.mask_color_loss') self.weighted_sample = self.conf.get_bool('train.weighted_sample') # Weights self.igr_weight = self.conf.get_float('train.igr_weight') self.tgr_weight = self.conf.get_float('train.tgr_weight') self.mask_weight = self.conf.get_float('train.mask_weight') self.tv_weight = self.conf.get_float('train.tv_weight') if self.tv_weight > 0: self.reg_l2 = True else: self.reg_l2 = False self.is_continue = is_continue self.mode = mode self.model_list = [] self.writer = None # Masks self.mask3d = Mask3D(**self.conf['model.mask3d'], num_frames=self.dataset.n_images // self.g_nums, device=self.device) # Networks
self.tensor4d = Tensor4D(**self.conf['model.tensor4d']).to(self.device)
5
2023-11-07 10:16:33+00:00
24k
Kushalhk/AutoFilter
plugins/p_ttishow.py
[ { "identifier": "ADMINS", "path": "info.py", "snippet": "ADMINS = [int(admin) if id_pattern.search(admin) else admin for admin in environ.get('ADMINS', '').split()]" }, { "identifier": "LOG_CHANNEL", "path": "info.py", "snippet": "LOG_CHANNEL = int(environ.get('LOG_CHANNEL', ''))" }, { "identifier": "SUPPORT_CHAT", "path": "info.py", "snippet": "SUPPORT_CHAT = environ.get('SUPPORT_CHAT', '')" }, { "identifier": "MELCOW_NEW_USERS", "path": "info.py", "snippet": "MELCOW_NEW_USERS = is_enabled((environ.get('MELCOW_NEW_USERS', \"True\")), True)" }, { "identifier": "MELCOW_VID", "path": "info.py", "snippet": "MELCOW_VID = environ.get(\"MELCOW_VID\", \"https://te.legra.ph/file/6f55d902f9bf2d0afd4bb.mp4\")" }, { "identifier": "CHNL_LNK", "path": "info.py", "snippet": "CHNL_LNK = environ.get('CHNL_LNK', 'https://t.me/TG_LINKS_CHANNEL')" }, { "identifier": "GRP_LNK", "path": "info.py", "snippet": "GRP_LNK = environ.get('GRP_LNK', 'https://t.me/TG_SUPPORT_GROUP')" }, { "identifier": "db", "path": "database/users_chats_db.py", "snippet": "class Database:\n def __init__(self, uri, database_name):\n def new_user(self, id, name):\n def new_group(self, id, title):\n async def add_user(self, id, name):\n async def is_user_exist(self, id):\n async def total_users_count(self):\n async def remove_ban(self, id):\n async def ban_user(self, user_id, ban_reason=\"No Reason\"):\n async def get_ban_status(self, id):\n async def get_all_users(self):\n async def delete_user(self, user_id):\n async def get_banned(self):\n async def add_chat(self, chat, title):\n async def get_chat(self, chat):\n async def re_enable_chat(self, id):\n async def update_settings(self, id, settings):\n async def get_settings(self, id):\n async def disable_chat(self, chat, reason=\"No Reason\"):\n async def total_chat_count(self):\n async def get_all_chats(self):\n async def get_db_size(self):" }, { "identifier": "Media", "path": "database/ia_filterdb.py", "snippet": "class Media(Document):\n file_id = fields.StrField(attribute='_id')\n file_ref = fields.StrField(allow_none=True)\n file_name = fields.StrField(required=True)\n file_size = fields.IntField(required=True)\n file_type = fields.StrField(allow_none=True)\n mime_type = fields.StrField(allow_none=True)\n caption = fields.StrField(allow_none=True)\n\n class Meta:\n indexes = ('$file_name', )\n collection_name = COLLECTION_NAME" }, { "identifier": "get_size", "path": "utils.py", "snippet": "def get_size(size):\n \"\"\"Get size in readable format\"\"\"\n\n units = [\"Bytes\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\"]\n size = float(size)\n i = 0\n while size >= 1024.0 and i < len(units):\n i += 1\n size /= 1024.0\n return \"%.2f %s\" % (size, units[i])" }, { "identifier": "temp", "path": "utils.py", "snippet": "class temp(object):\n BANNED_USERS = []\n BANNED_CHATS = []\n ME = None\n CURRENT=int(os.environ.get(\"SKIP\", 2))\n CANCEL = False\n MELCOW = {}\n U_NAME = None\n B_NAME = None\n GETALL = {}\n SHORT = {}\n SETTINGS = {}" }, { "identifier": "get_settings", "path": "utils.py", "snippet": "async def get_settings(group_id):\n settings = temp.SETTINGS.get(group_id)\n if not settings:\n settings = await db.get_settings(group_id)\n temp.SETTINGS[group_id] = settings\n return settings" }, { "identifier": "script", "path": "Script.py", "snippet": "class script(object):\r\n START_TXT = \"\"\"<b>Hᴇʟʟᴏ 👋 {}</b>\r\n\r\n<b>Mʏ Nᴀᴍᴇ Is <a href=\"https://t.me/{}\">{}</a>, I Cᴀɴ Pʀᴏᴠɪᴅᴇ Mᴏᴠɪᴇs, Sᴇʀɪᴇs, Aɴɪᴍᴀᴛɪᴏɴ, Cᴀʀᴛᴏᴏɴ, Aɴɪᴍᴇ, K-Dʀᴀᴍᴀ & Mᴀɴʏ Mᴏʀᴇ ☺ Jᴜsᴛ Aᴅᴅ Mᴇ Tᴏ Yᴏᴜʀ Gʀᴏᴜᴘ As Aᴅᴍɪɴ EɴJᴏʏ 😍</b>\"\"\"\r\n\r\n HELP_TXT = \"\"\"<b>Hᴇʀᴇ Is Tʜᴇ Hᴇʟᴘ Fᴏʀ Mʏ Cᴏᴍᴍᴀɴᴅs.</b>\"\"\"\r\n \r\n ABOUT_TXT = \"\"\"\r\n<b>‣ ᴍʏ ɴᴀᴍᴇ : <a href=\"https://t.me/{}\">ʙᴏᴛ</a>\r\n‣ ᴄʀᴇᴀᴛᴏʀ : <a href=\"https://t.me/KUSHALHK\">𝐊𝐔𝐒𝐇𝐀𝐋</a>\r\n‣ ʟɪʙʀᴀʀʏ : <a href=\"https://pyrogram.org/\">ᴘʏʀᴏɢʀᴀᴍ</a>\r\n‣ ʟᴀɴɢᴜᴀɢᴇ : <a href=\"https://www.python.org/\">ᴘʏᴛʜᴏɴ</a>\r\n‣ ᴅᴀᴛᴀʙᴀꜱᴇ : <a href=\"https://www.mongodb.com/\">ᴍᴏɴɢᴏ ᴅʙ</a>\r\n‣ ʜᴏꜱᴛᴇᴅ ᴏɴ : <a href=\"https://render.com/\">Render</a>\r\n‣ ʙᴜɪʟᴅ ꜱᴛᴀᴛᴜꜱ : ᴠ.𝟹.𝟶 [ꜱᴛᴀʙʟᴇ]</b>\"\"\"\r\n \r\n DISCLAIMER_TXT = \"\"\"<b>ᴛʜɪꜱ ɪꜱ ᴀɴ ᴏᴘᴇɴ ꜱᴏᴜʀᴄᴇ ᴘʀᴏᴊᴇᴄᴛ.\r\n\r\nᴀʟʟ ᴛʜᴇ ꜰɪʟᴇꜱ ɪɴ ᴛʜɪꜱ ʙᴏᴛ ᴀʀᴇ ꜰʀᴇᴇʟʏ ᴀᴠᴀɪʟᴀʙʟᴇ ᴏɴ ᴛʜᴇ ɪɴᴛᴇʀɴᴇᴛ ᴏʀ ᴘᴏꜱᴛᴇᴅ ʙʏ ꜱᴏᴍᴇʙᴏᴅʏ ᴇʟꜱᴇ. ᴊᴜꜱᴛ ꜰᴏʀ ᴇᴀꜱʏ ꜱᴇᴀʀᴄʜɪɴɢ ᴛʜɪꜱ ʙᴏᴛ ɪꜱ ɪɴᴅᴇxɪɴɢ ꜰɪʟᴇꜱ ᴡʜɪᴄʜ ᴀʀᴇ ᴀʟʀᴇᴀᴅʏ ᴜᴘʟᴏᴀᴅᴇᴅ ᴏɴ ᴛᴇʟᴇɢʀᴀᴍ. ᴡᴇ ʀᴇꜱᴘᴇᴄᴛ ᴀʟʟ ᴛʜᴇ ᴄᴏᴘʏʀɪɢʜᴛ ʟᴀᴡꜱ ᴀɴᴅ ᴡᴏʀᴋꜱ ɪɴ ᴄᴏᴍᴘʟɪᴀɴᴄᴇ ᴡɪᴛʜ ᴅᴍᴄᴀ ᴀɴᴅ ᴇᴜᴄᴅ. ɪꜰ ᴀɴʏᴛʜɪɴɢ ɪꜱ ᴀɢᴀɪɴꜱᴛ ʟᴀᴡ ᴘʟᴇᴀꜱᴇ ᴄᴏɴᴛᴀᴄᴛ ᴍᴇ ꜱᴏ ᴛʜᴀᴛ ɪᴛ ᴄᴀɴ ʙᴇ ʀᴇᴍᴏᴠᴇᴅ ᴀꜱᴀᴘ. ɪᴛ ɪꜱ ꜰᴏʀʙɪᴅᴅᴇɴ ᴛᴏ ᴅᴏᴡɴʟᴏᴀᴅ, ꜱᴛʀᴇᴀᴍ, ʀᴇᴘʀᴏᴅᴜᴄᴇ, ꜱʜᴀʀᴇ ᴏʀ ᴄᴏɴꜱᴜᴍᴇ ᴄᴏɴᴛᴇɴᴛ ᴡɪᴛʜᴏᴜᴛ ᴇxᴘʟɪᴄɪᴛ ᴘᴇʀᴍɪꜱꜱɪᴏɴ ꜰʀᴏᴍ ᴛʜᴇ ᴄᴏɴᴛᴇɴᴛ ᴡɪᴛʜᴏᴜᴛ ᴇxᴘʟɪᴄɪᴛ ᴘᴇʀᴍɪꜱꜱɪᴏɴ ꜰʀᴏᴍ ᴛʜᴇ ᴄᴏɴᴛᴇɴᴛ ᴄʀᴇᴀᴛᴏʀ ᴏʀ ʟᴇɢᴀʟ ᴄᴏᴘʏʀɪɢʜᴛ ʜᴏʟᴅᴇʀ. ɪꜰ ʏᴏᴜ ʙᴇʟɪᴇᴠᴇ ᴛʜɪꜱ ʙᴏᴛ ɪꜱ ᴠɪᴏʟᴀᴛɪɴɢ ʏᴏᴜʀ ɪɴᴛᴇʟʟᴇᴄᴛᴜᴀʟ ᴘʀᴏᴘᴇʀᴛʏ, ᴄᴏɴᴛᴀᴄᴛ ᴛʜᴇ ʀᴇꜱᴘᴇᴄᴛɪᴠᴇ ᴄʜᴀɴɴᴇʟꜱ ꜰᴏʀ ʀᴇᴍᴏᴠᴀʟ. ᴛʜᴇ ʙᴏᴛ ᴅᴏᴇꜱ ɴᴏᴛ ᴏᴡɴ ᴀɴʏ ᴏꜰ ᴛʜᴇꜱᴇ ᴄᴏɴᴛᴇɴᴛꜱ, ɪᴛ ᴏɴʟʏ ɪɴᴅᴇx ᴛʜᴇ ꜰɪʟᴇꜱ ꜰʀᴏᴍ ᴛᴇʟᴇɢʀᴀᴍ.\r\n\r\nᴍᴀɪɴᴛᴀɪɴᴇᴅ ʙʏ : <a href=\"https://t.me/KUSHALHK\">𝐊𝐔𝐒𝐇𝐀𝐋</a></b>\"\"\"\r\n\r\n SOURCE_TXT = \"\"\"\r\n<b>Hᴇʏ, Tʜɪs ɪs ᴀ Oᴘᴇɴ Sᴏᴜʀᴄᴇ Pʀᴏᴊᴇᴄᴛ.\r\n\r\nTʜɪs Bᴏᴛ ʜᴀs Lᴀᴛᴇsᴛ ᴀɴᴅ Aᴅᴠᴀɴᴄᴇᴅ Fᴇᴀᴛᴜʀᴇs⚡️\r\n\r\nFork our repository and give star ⭐- <a href='https://github.com/Kushalhk/AutoFilter'>📥 ᴄʟɪᴄᴋ ʜᴇʀᴇ 📥</a></b>\r\n\"\"\"\r\n \r\n KUSHAL_TXT = \"\"\" \r\n<b>🔥 ᴘʀᴇᴍɪᴜᴍ ғᴇᴀᴛᴜʀᴇs 🔥\r\n\r\n➻ ɴᴏ ɴᴇᴇᴅ ᴛᴏ ᴠᴇʀɪғʏ\r\n➻ ᴅɪʀᴇᴄᴛ ғɪʟᴇs\r\n➻ ᴀᴅ-ғʀᴇᴇ ᴇxᴘᴇʀɪᴇɴᴄᴇ\r\n➻ ʜɪɢʜ-sᴘᴇᴇᴅ ᴅᴏᴡɴʟᴏᴀᴅ ʟɪɴᴋ\r\n➻ ᴜɴʟɪᴍɪᴛᴇᴅ ᴍᴏᴠɪᴇs ᴀɴᴅ sᴇʀɪᴇs\r\n➻ ғᴜʟʟ ᴀᴅᴍɪɴ sᴜᴘᴘᴏʀᴛ \r\n➻ ʀᴇǫᴜᴇsᴛ ᴡɪʟʟ ʙᴇ ᴄᴏᴍᴘʟᴇᴛᴇᴅ ɪɴ 𝟷ʜ ɪғ ᴀᴠᴀɪʟᴀʙʟᴇ\r\n\r\n‼️ ᴄʟɪᴄᴋ ᴏɴ ʙᴇʟᴏᴡ ʙᴜᴛᴛᴏɴ ᴛᴏ ᴄʜᴇᴄᴋ ᴀʟʟ ᴀᴠᴀɪʟᴀʙʟᴇ ᴘʀᴇᴍɪᴜᴍ ᴘʟᴀɴs ᴀɴᴅ ɪᴛ's ᴘʀɪᴄᴇs.</b>\"\"\"\r\n\r\n \r\n SETTINGS_TXT = \"\"\"\r\nHᴇʟᴘ : <b>Sᴇᴛᴛɪɴɢꜱ</b>\r\n \r\n◈ sᴇᴛᴛɪɴɢs ɪs ᴍᴏsᴛ ɪᴍᴘᴏʀᴛᴀɴᴛ ғᴇᴀᴛᴜʀᴇ ɪɴ ᴛʜɪs ʙᴏᴛ.\r\n◈ ʏᴏᴜ ᴄᴀɴ ᴇᴀsɪʟʏ ᴄᴜsᴛᴏᴍɪᴢᴇ ᴛʜɪs ʙᴏᴛ ғᴏʀ ʏᴏᴜʀ ɢʀᴏᴜᴘ.\r\n\r\n<b>Nᴏᴛᴇ :</b>\r\n1. ᴏɴʟʏ ɢʀᴏᴜᴘ ᴀᴅᴍɪɴ ᴄᴀɴ ᴜsᴇ ᴛʜɪs ᴄᴏᴍᴍᴀɴᴅ ᴀɴᴅ ᴄʜᴀɴɢᴇ sᴇᴛᴛɪɴɢs.\r\n2. ɪᴛ ᴡᴏʀᴋs ᴏɴʟʏ ᴡʜᴇɴ ʙᴏᴛ ᴀʟʀᴇᴀᴅʏ ᴄᴏɴɴᴇᴄᴛᴇᴅ ᴛᴏ ʏᴏᴜʀ ɢʀᴏᴜᴘ.\r\n\r\n<b>Cᴏᴍᴍᴀɴᴅs Aɴᴅ Usᴀɢᴇ :</b>\r\n• /connect - ᴄᴏɴɴᴇᴄᴛ ʏᴏᴜʀ ɢʀᴏᴜᴘ ᴛᴏ ʙᴏᴛ\r\n• /settings - ᴄʜᴀɴɢᴇ sᴇᴛᴛɪɴɢs ᴀs ʏᴏᴜʀ ᴡɪsʜ \"\"\"\r\n\r\n TELEGRAPH_TXT = \"\"\" Hᴇʟᴘ : <b>Tᴇʟᴇɢʀᴀᴘʜ</b>\r\n\r\n<b>Nᴏᴛᴇ</b>: ᴛʜɪꜱ ᴄᴏᴍᴍᴀɴᴅ ɪꜱ ᴀᴠᴀɪʟᴀʙʟᴇ ɪɴ ɢʀᴏᴜᴘꜱ ᴀɴᴅ ᴘᴍꜱ. ᴀʟꜱᴏ ᴄᴀɴ ʙᴇ ᴜꜱᴇ ʙʏ ᴇᴠᴇʀʏᴏɴᴇ.\r\n\r\n<b>Cᴏᴍᴍᴀɴᴅs & Usᴀɢᴇ :</b>\r\n• /telegraph - sᴇɴᴅ ᴍᴇ ᴘɪᴄᴛᴜʀᴇ ᴏʀ ᴠɪᴅᴇᴏ ᴜɴᴅᴇʀ 𝟻ᴍʙ\"\"\"\r\n\r\n FONT_TXT = \"\"\"Hᴇʟᴘ : <b>Fᴏɴᴛ</b>\r\n\r\n<b>Nᴏᴛᴇ</b>: ʏᴏᴜ ᴄᴀɴ ᴜꜱᴇ ᴛʜɪꜱ ᴍᴏᴅᴇ ᴛᴏ ᴄʜᴀɴɢᴇ ʏᴏᴜʀ ꜰᴏɴᴛꜱ ꜱᴛʏʟᴇ, ᴊᴜꜱᴛ ꜱᴇɴᴅ ᴍᴇ ʟɪᴋᴇ ᴛʜɪꜱ ꜰᴏʀᴍᴀᴛ. \r\n\r\n<code>/font TG_LINKS_CHANNEL</code>\"\"\"\r\n\r\n MANUELFILTER_TXT = \"\"\"Hᴇʟᴘ : <b>Fɪʟᴛᴇʀꜱ</b>\r\n \r\n◈ ꜰɪʟᴛᴇʀ ɪꜱ ᴀ ꜰᴇᴀᴛᴜʀᴇ ᴡᴇʀᴇ ᴜꜱᴇʀꜱ ᴄᴀɴ ꜱᴇᴛ ᴀᴜᴛᴏᴍᴀᴛᴇᴅ ʀᴇᴘʟɪᴇꜱ ꜰᴏʀ ᴀ ᴘᴀʀᴛɪᴄᴜʟᴀʀ ᴋᴇʏᴡᴏʀᴅ ᴀɴᴅ ɪ ᴡɪʟʟ ʀᴇꜱᴘᴏɴᴅ ᴡʜᴇɴᴇᴠᴇʀ ᴀ ᴋᴇʏᴡᴏʀᴅ ɪꜱ ꜰᴏᴜɴᴅ ɪɴ ᴛʜᴇ ᴍᴇꜱꜱᴀɢᴇ.\r\n\r\n<b>Nᴏᴛᴇ :</b>\r\n1. ᴛʜɪꜱ ʙᴏᴛ ꜱʜᴏᴜʟᴅ ʜᴀᴠᴇ ᴀᴅᴍɪɴ ᴘʀɪᴠɪʟᴇɢᴇ.\r\n2. ᴏɴʟʏ ᴀᴅᴍɪɴꜱ ᴄᴀɴ ᴀᴅᴅ ꜰɪʟᴛᴇʀꜱ ɪɴ ᴀ ᴄʜᴀᴛ.\r\n3. ᴀʟᴇʀᴛ ʙᴜᴛᴛᴏɴꜱ ʜᴀᴠᴇ ᴀ ʟɪᴍɪᴛ ᴏꜰ 64 ᴄʜᴀʀᴀᴄᴛᴇʀꜱ.\r\n\r\n<b>Cᴏᴍᴍᴀɴᴅs Aɴᴅ Usᴀɢᴇ :</b>\r\n• /filter - ᴀᴅᴅ ᴀ ꜰɪʟᴛᴇʀ ɪɴ ᴀ ᴄʜᴀᴛ\r\n• /filters - ʟɪꜱᴛ ᴀʟʟ ᴛʜᴇ ꜰɪʟᴛᴇʀꜱ ᴏꜰ ᴀ ᴄʜᴀᴛ\r\n• /del - ᴅᴇʟᴇᴛᴇ ᴀ ꜱᴘᴇᴄɪꜰɪᴄ ꜰɪʟᴛᴇʀ ɪɴ ᴀ ᴄʜᴀᴛ\r\n• /delall - ᴅᴇʟᴇᴛᴇ ᴛʜᴇ ᴡʜᴏʟᴇ ꜰɪʟᴛᴇʀꜱ ɪɴ ᴀ ᴄʜᴀᴛ (ᴄʜᴀᴛ ᴏᴡɴᴇʀ ᴏɴʟʏ)\"\"\"\r\n\r\n BUTTON_TXT = \"\"\"Hᴇʟᴘ : <b>Bᴜᴛᴛᴏɴꜱ</b>\r\n \r\n◈ ᴛʜɪꜱ ʙᴏᴛ ꜱᴜᴘᴘᴏʀᴛꜱ ʙᴏᴛʜ ᴜʀʟ ᴀɴᴅ ᴀʟᴇʀᴛ ɪɴʟɪɴᴇ ʙᴜᴛᴛᴏɴꜱ.\r\n\r\n<b>Nᴏᴛᴇ :</b>\r\n𝟷. ᴛᴇʟᴇɢʀᴀᴍ ᴡɪʟʟ ɴᴏᴛ ᴀʟʟᴏᴡꜱ ʏᴏᴜ ᴛᴏ ꜱᴇɴᴅ ʙᴜᴛᴛᴏɴꜱ ᴡɪᴛʜᴏᴜᴛ ᴀɴʏ ᴄᴏɴᴛᴇɴᴛ, ꜱᴏ ᴄᴏɴᴛᴇɴᴛ ɪꜱ ᴍᴀɴᴅᴀᴛᴏʀʏ.\r\n𝟸. ᴛʜɪꜱ ʙᴏᴛ ꜱᴜᴘᴘᴏʀᴛꜱ ʙᴜᴛᴛᴏɴꜱ ᴡɪᴛʜ ᴀɴʏ ᴛᴇʟᴇɢʀᴀᴍ ᴍᴇᴅɪᴀ ᴛʏᴘᴇ.\r\n𝟹. ʙᴜᴛᴛᴏɴꜱ ꜱʜᴏᴜʟᴅ ʙᴇ ᴘʀᴏᴘᴇʀʟʏ ᴘᴀʀꜱᴇᴅ ᴀꜱ ᴍᴀʀᴋᴅᴏᴡɴ ꜰᴏʀᴍᴀᴛ\r\n\r\nᴜʀʟ ʙᴜᴛᴛᴏɴꜱ :\r\n<code>[Button Text](buttonurl:https://t.me/TG_LINKS_CHANNEL)</code>\r\n\r\nᴀʟᴇʀᴛ ʙᴜᴛᴛᴏɴꜱ :\r\n<code>[Button Text](buttonalert:ᴛʜɪꜱ ɪꜱ ᴀɴ ᴀʟᴇʀᴛ ᴍᴇꜱꜱᴀɢᴇ)</code>\"\"\"\r\n\r\n AUTOFILTER_TXT = \"\"\"Hᴇʟᴘ : <b>Aᴜᴛᴏ Fɪʟᴛᴇʀ</b>\r\n    \r\n<b>Nᴏᴛᴇ :</b> Fɪʟᴇ Iɴᴅᴇx\r\n𝟷. ᴍᴀᴋᴇ ᴍᴇ ᴛʜᴇ ᴀᴅᴍɪɴ ᴏꜰ ʏᴏᴜʀ ᴄʜᴀɴɴᴇʟ ɪꜰ ɪᴛ'ꜱ ᴘʀɪᴠᴀᴛᴇ.\r\n𝟸. ᴍᴀᴋᴇ ꜱᴜʀᴇ ᴛʜᴀᴛ ʏᴏᴜʀ ᴄʜᴀɴɴᴇʟ ᴅᴏᴇꜱ ɴᴏᴛ ᴄᴏɴᴛᴀɪɴꜱ ᴄᴀᴍʀɪᴘꜱ, ᴘᴏʀɴ ᴀɴᴅ ꜰᴀᴋᴇ ꜰɪʟᴇꜱ.\r\n𝟹. ꜰᴏʀᴡᴀʀᴅ ᴛʜᴇ ʟᴀꜱᴛ ᴍᴇꜱꜱᴀɢᴇ ᴛᴏ ᴍᴇ ᴡɪᴛʜ ǫᴜᴏᴛᴇꜱ. ɪ'ʟʟ ᴀᴅᴅ ᴀʟʟ ᴛʜᴇ ꜰɪʟᴇꜱ ɪɴ ᴛʜᴀᴛ ᴄʜᴀɴɴᴇʟ ᴛᴏ ᴍʏ ᴅʙ.\r\n\r\n<b>Nᴏᴛᴇ :</b> Aᴜᴛᴏ Fɪʟᴛᴇʀ\r\n𝟷. Aᴅᴅ ᴛʜᴇ ʙᴏᴛ ᴀs ᴀᴅᴍɪɴ ᴏɴ ʏᴏᴜʀ ɢʀᴏᴜᴘ.\r\n𝟸. Usᴇ /connect ᴀɴᴅ ᴄᴏɴɴᴇᴄᴛ ʏᴏᴜʀ ɢʀᴏᴜᴘ ᴛᴏ ᴛʜᴇ ʙᴏᴛ.\r\n𝟹. Usᴇ /settings ᴏɴ ʙᴏᴛ's ᴘᴍ ᴀɴᴅ ᴛᴜʀɴ ᴏɴ AᴜᴛᴏFɪʟᴛᴇʀ ᴏɴ ᴛʜᴇ sᴇᴛᴛɪɴɢs ᴍᴇɴᴜ.\"\"\"\r\n\r\n \r\n RULE_TXT = \"\"\"♦ 𝗚𝗿𝗼𝘂𝗽 𝗥𝘂𝗹𝗲𝘀 ♦\r\n\r\n◈ <b>Sᴇᴀʀᴄʜ Mᴏᴠɪᴇ Wɪᴛʜ Cᴏʀʀᴇᴄᴛ Sᴘᴇʟʟɪɴɢ:</b>\r\n• ᴀᴠᴀᴛᴀʀ 𝟸𝟶𝟶𝟿 ✅\r\n• ᴀᴠᴀᴛᴀʀ ʜɪɴᴅɪ ✅\r\n• ᴀᴠᴀᴛᴀʀ ᴍᴏᴠɪᴇ ❌\r\n• ᴀᴠᴀᴛᴀʀ ʜɪɴᴅɪ ᴅᴜʙʙᴇᴅ..❌\r\n\r\n◈ <b>Sᴇᴀʀᴄʜ Wᴇʙ Sᴇʀɪᴇs Iɴ ᴛʜɪs Fᴏʀᴍᴀᴛ:</b>\r\n• ᴠɪᴋɪɴɢs S𝟶𝟷 ✅\r\n• ᴠɪᴋɪɴɢs S𝟶𝟷E𝟶𝟷 ✅\r\n• ᴠɪᴋɪɴɢs S𝟶𝟷 ʜɪɴᴅɪ ✅\r\n• ᴠɪᴋɪɴɢs S𝟶𝟷 ʜɪɴᴅɪ ᴅᴜʙʙ... ❌\r\n• ᴠɪᴋɪɴɢs sᴇᴀsᴏɴ 𝟷 ❌\r\n• ᴠɪᴋɪɴɢs ᴡᴇʙ sᴇʀɪᴇs ❌\r\n\r\n<b>➙ ᴅᴏɴ'ᴛ ᴅᴏ ᴀɴʏ ꜱᴇʟꜰ ᴘʀᴏᴍᴏᴛɪᴏɴ. \r\n➙ ᴅᴏɴ'ᴛ ꜱᴇɴᴅ ᴀɴʏ ᴋɪɴᴅ ᴏꜰ ᴘʜᴏᴛᴏ, ᴠɪᴅᴇᴏ, ᴅᴏᴄᴜᴍᴇɴᴛꜱ, ᴜʀʟ, ᴇᴛᴄ...\r\n➙ ᴅᴏɴ'ᴛ ʀᴇǫᴜᴇꜱᴛ ᴀɴʏ ᴛʜɪɴɢꜱ ᴏᴛʜᴇʀ ᴛʜᴀɴ ᴍᴏᴠɪᴇꜱ, ꜱᴇʀɪᴇꜱ, ᴀɴɪᴍᴀᴛɪᴏɴ, ᴄᴀʀᴛᴏᴏɴ, ᴀɴɪᴍᴇ, ᴋ-ᴅʀᴀᴍᴀ ᴍᴀɴʏ ᴍᴏʀᴇ.</b>\r\n\r\n🔰 <b>Nᴏᴛᴇ :</b> ᴀʟʟ ᴍᴇꜱꜱᴀɢᴇꜱ ᴡɪʟʟ ʙᴇ ᴀᴜᴛᴏ-ᴅᴇʟᴇᴛᴇᴅ ᴀꜰᴛᴇʀ 𝟷𝟶 ᴍɪɴᴜᴛᴇꜱ ᴛᴏ ᴀᴠᴏɪᴅ ᴄᴏᴘʏʀɪɢʜᴛ ɪꜱꜱᴜᴇꜱ.\"\"\"\r\n\r\n CONNECTION_TXT = \"\"\"Hᴇʟᴘ : <b>Cᴏɴɴᴇᴄᴛɪᴏɴꜱ</b>\r\n \r\n◈ ᴜꜱᴇᴅ ᴛᴏ ᴄᴏɴɴᴇᴄᴛ ʙᴏᴛ ᴛᴏ ᴘᴍ ꜰᴏʀ ᴍᴀɴᴀɢɪɴɢ ꜰɪʟᴛᴇʀꜱ \r\n◈ ɪᴛ ʜᴇʟᴘꜱ ᴛᴏ ᴀᴠᴏɪᴅ ꜱᴘᴀᴍᴍɪɴɢ ɪɴ ɢʀᴏᴜᴘꜱ.\r\n\r\n<b>Nᴏᴛᴇ :</b>\r\n1. ᴏɴʟʏ ᴀᴅᴍɪɴꜱ ᴄᴀɴ ᴀᴅᴅ ᴀ ᴄᴏɴɴᴇᴄᴛɪᴏɴ.\r\n2. ꜱᴇɴᴅ /ᴄᴏɴɴᴇᴄᴛ ꜰᴏʀ ᴄᴏɴɴᴇᴄᴛɪɴɢ ᴍᴇ ᴛᴏ ʏᴏᴜʀ ᴘᴍ\r\n\r\n<b>Cᴏᴍᴍᴀɴᴅs Aɴᴅ Usᴀɢᴇ :</b>\r\n• /connect - ᴄᴏɴɴᴇᴄᴛ ᴀ ᴘᴀʀᴛɪᴄᴜʟᴀʀ ᴄʜᴀᴛ ᴛᴏ ʏᴏᴜʀ ᴘᴍ\r\n• /disconnect - ᴅɪꜱᴄᴏɴɴᴇᴄᴛ ꜰʀᴏᴍ ᴀ ᴄʜᴀᴛ\r\n• /connections - ʟɪꜱᴛ ᴀʟʟ ʏᴏᴜʀ ᴄᴏɴɴᴇᴄᴛɪᴏɴꜱ\"\"\"\r\n\r\n EXTRAMOD_TXT = \"\"\"Hᴇʟᴘ : <b>Exᴛʀᴀ Mᴏᴅᴜʟᴇs</b>\r\n \r\n<b>Nᴏᴛᴇ :</b>\r\nᴛʜᴇꜱᴇ ᴀʀᴇ ᴛʜᴇ ᴇxᴛʀᴀ ꜰᴇᴀᴛᴜʀᴇꜱ ᴏꜰ ᴛʜɪꜱ ʙᴏᴛ\r\n\r\n<b>Cᴏᴍᴍᴀɴᴅs Aɴᴅ Usᴀɢᴇ :</b>\r\n• /id - ɢᴇᴛ ɪᴅ ᴏꜰ ᴀ ꜱᴘᴇᴄɪꜰɪᴇᴅ ᴜꜱᴇʀ.\r\n• /info - ɢᴇᴛ ɪɴꜰᴏʀᴍᴀᴛɪᴏɴ ᴀʙᴏᴜᴛ ᴀ ᴜꜱᴇʀ.\r\n• /imdb - ɢᴇᴛ ᴛʜᴇ ꜰɪʟᴍ ɪɴꜰᴏʀᴍᴀᴛɪᴏɴ ꜰʀᴏᴍ ɪᴍᴅʙ ꜱᴏᴜʀᴄᴇ.\r\n• /search - ɢᴇᴛ ᴛʜᴇ ꜰɪʟᴍ ɪɴꜰᴏʀᴍᴀᴛɪᴏɴ ꜰʀᴏᴍ ᴠᴀʀɪᴏᴜꜱ ꜱᴏᴜʀᴄᴇꜱ.\"\"\"\r\n\r\n ADMIN_TXT = \"\"\"<b>Nᴏᴛᴇ :</b> Tʜɪs Mᴏᴅᴜʟᴇ Oɴʟʏ Wᴏʀᴋs Fᴏʀ Mʏ Aᴅᴍɪɴs.\r\n\r\n<b>Cᴏᴍᴍᴀɴᴅs Aɴᴅ Usᴀɢᴇ :</b>\r\n• /logs - ᴛᴏ ɢᴇᴛ ᴛʜᴇ ʀᴇᴄᴇɴᴛ ᴇʀʀᴏʀꜱ\r\n• /stats - ᴛᴏ ɢᴇᴛ ꜱᴛᴀᴛᴜꜱ ᴏꜰ ꜰɪʟᴇꜱ ɪɴ ᴅʙ. <b>[Tʜɪs Cᴏᴍᴍᴀɴᴅ Cᴀɴ Bᴇ Usᴇᴅ Bʏ Aɴʏᴏɴᴇ]</b>\r\n• /delete - ᴛᴏ ᴅᴇʟᴇᴛᴇ ᴀ ꜱᴘᴇᴄɪꜰɪᴄ ꜰɪʟᴇ ꜰʀᴏᴍ ᴅʙ.\r\n• /users - ᴛᴏ ɢᴇᴛ ʟɪꜱᴛ ᴏꜰ ᴍʏ ᴜꜱᴇʀꜱ ᴀɴᴅ ɪᴅꜱ.\r\n• /chats - ᴛᴏ ɢᴇᴛ ʟɪꜱᴛ ᴏꜰ ᴍʏ ᴄʜᴀᴛꜱ ᴀɴᴅ ɪᴅꜱ\r\n• /leave - ᴛᴏ ʟᴇᴀᴠᴇ ꜰʀᴏᴍ ᴀ ᴄʜᴀᴛ.\r\n• /disable - ᴛᴏ ᴅɪꜱᴀʙʟᴇ ᴀ ᴄʜᴀᴛ.\r\n• /ban - ᴛᴏ ʙᴀɴ ᴀ ᴜꜱᴇʀ.\r\n• /unban - ᴛᴏ ᴜɴʙᴀɴ ᴀ ᴜꜱᴇʀ.\r\n• /channel - ᴛᴏ ɢᴇᴛ ʟɪꜱᴛ ᴏꜰ ᴛᴏᴛᴀʟ ᴄᴏɴɴᴇᴄᴛᴇᴅ ᴄʜᴀɴɴᴇʟꜱ. \r\n• /broadcast - ᴛᴏ ʙʀᴏᴀᴅᴄᴀꜱᴛ ᴀ ᴍᴇꜱꜱᴀɢᴇ ᴛᴏ ᴀʟʟ ᴜꜱᴇʀꜱ. \r\n• /grp_broadcast - Tᴏ ʙʀᴏᴀᴅᴄᴀsᴛ ᴀ ᴍᴇssᴀɢᴇ ᴛᴏ ᴀʟʟ ᴄᴏɴɴᴇᴄᴛᴇᴅ ɢʀᴏᴜᴘs.\r\n• /gfilter - ᴛᴏ ᴀᴅᴅ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀs. \r\n• /gfilters - ᴛᴏ ᴠɪᴇᴡ ʟɪsᴛ ᴏғ ᴀʟʟ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀs. \r\n• /delg - ᴛᴏ ᴅᴇʟᴇᴛᴇ ᴀ sᴘᴇᴄɪғɪᴄ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀ. \r\n• /request - ᴛᴏ sᴇɴᴅ ᴀ ᴍᴏᴠɪᴇ/sᴇʀɪᴇs ʀᴇᴏ̨ᴜᴇsᴛ ᴛᴏ ʙᴏᴛ ᴀᴅᴍɪɴs. ᴏɴʟʏ ᴡᴏʀᴋs ᴏɴ sᴜᴘᴘᴏʀᴛ ɢʀᴏᴜᴘ. <b>[Tʜɪs Cᴏᴍᴍᴀɴᴅ Cᴀɴ Bᴇ Usᴇᴅ Bʏ Aɴʏᴏɴᴇ]</b>\r\n• /delallg - ᴛᴏ ᴅᴇʟᴇᴛᴇ ᴀʟʟ ɢғɪʟᴛᴇʀs ғʀᴏᴍ ᴛʜᴇ ʙᴏᴛ's ᴅᴀᴛᴀʙᴀsᴇ.\r\n• /deletefiles - ᴛᴏ ᴅᴇʟᴇᴛᴇ ᴄᴀᴍʀɪᴘ ᴀɴᴅ ᴘʀᴇ-ᴅᴠᴅ ғɪʟᴇs ғʀᴏᴍ ᴛʜᴇ ʙᴏᴛ's ᴅᴀᴛᴀʙᴀsᴇ.\"\"\"\r\n\r\n STICKER_TXT = \"\"\"<b>yᴏᴜ ᴄᴀɴ ᴜꜱᴇ ᴛʜɪꜱ ᴍᴏᴅᴜʟᴇ ᴛᴏ ꜰɪɴᴅᴀɴy ꜱᴛɪᴄᴋᴇʀꜱ ɪᴅ.\r\n• ᴜꜱᴀɢᴇ :ᴛᴏ ɢᴇᴛ ꜱᴛɪᴄᴋᴇʀ\r\n \r\n⭕ ʜᴏᴡ ᴛᴏ ᴜꜱᴇ\r\n◉ Reply To Any Sticker [/stickerid]\r\n\r\n/𝐬𝐭𝐢𝐜𝐤𝐞𝐫𝐢𝐝 𝐬𝐭𝐢𝐜𝐤𝐞𝐫 𝐢𝐝\r\n\r\n</b>\"\"\"\r\n \r\n STATUS_TXT = \"\"\"<b>⍟─────[ <b>Bᴏᴛ Sᴛᴀᴛᴜs</b> ]─────⍟\r\n    \r\n★ ᴛᴏᴛᴀʟ ꜰɪʟᴇꜱ : <code>{}</code>\r\n★ ᴛᴏᴛᴀʟ ᴜꜱᴇʀꜱ : <code>{}</code>\r\n★ ᴛᴏᴛᴀʟ ɢʀᴏᴜᴘꜱ : <code>{}</code>\r\n★ ᴜꜱᴇᴅ ꜱᴛᴏʀᴀɢᴇ: <code>{}</code>\r\n★ ꜰʀᴇᴇ ꜱᴛᴏʀᴀɢᴇ : <code>{}</code>\r\n\r\n•❅──────✧❅✦❅✧──────❅•</b>\"\"\"\r\n\r\n\r\n LOG_TEXT_G = \"\"\"<b>#NewGroup\r\nGʀᴏᴜᴘ = {}(<code>{}</code>)\r\nTᴏᴛᴀʟ Mᴇᴍʙᴇʀs = <code>{}</code>\r\nAᴅᴅᴇᴅ Bʏ - {}</b>\"\"\"\r\n\r\n LOG_TEXT_P = \"\"\"<b>#NewUser\r\nID - <code>{}</code>\r\nNᴀᴍᴇ - {}</b>\"\"\"\r\n\r\n ALRT_TXT = \"\"\"<b>ʜᴇʟʟᴏ {},\r\nᴛʜɪꜱ ɪꜱ ɴᴏᴛ ʏᴏᴜʀ ᴍᴏᴠɪᴇ ʀᴇQᴜᴇꜱᴛ,\r\nʀᴇǫᴜᴇꜱᴛ ʏᴏᴜʀ'ꜱ...</b>\"\"\"\r\n\r\n OLD_ALRT_TXT = \"\"\"<b>ʜᴇʏ {},\r\nʏᴏᴜ ᴀʀᴇ ᴜꜱɪɴɢ ᴏɴᴇ ᴏꜰ ᴍʏ ᴏʟᴅ ᴍᴇꜱꜱᴀɢᴇꜱ, \r\nᴘʟᴇᴀꜱᴇ ꜱᴇɴᴅ ᴛʜᴇ ʀᴇǫᴜᴇꜱᴛ ᴀɢᴀɪɴ.</b>\"\"\"\r\n\r\n CUDNT_FND = \"\"\"<b>ɪ ᴄᴏᴜʟᴅɴ'ᴛ ꜰɪɴᴅ ᴀɴʏᴛʜɪɴɢ ʀᴇʟᴀᴛᴇᴅ ᴛᴏ {}\r\nᴅɪᴅ ʏᴏᴜ ᴍᴇᴀɴ ᴀɴʏ ᴏɴᴇ ᴏꜰ ᴛʜᴇꜱᴇ?</b>\"\"\"\r\n\r\n I_CUDNT = \"\"\"<b>sᴏʀʀʏ ɴᴏ ꜰɪʟᴇs ᴡᴇʀᴇ ꜰᴏᴜɴᴅ ꜰᴏʀ ʏᴏᴜʀ ʀᴇǫᴜᴇꜱᴛ {} 😕\r\n\r\nMᴏᴠɪᴇs Nᴏᴛ Aᴠᴀɪʟᴀʙʟᴇ Rᴇᴀsᴏɴ:\r\n𝟷. ᴏ.ᴛ.ᴛ ᴏʀ ᴅᴠᴅ ɴᴏᴛ ʀᴇʟᴇᴀsᴇᴅ\r\n𝟸. ᴛʏᴘᴇ ɴᴀᴍᴇ ᴡɪᴛʜ ʏᴇᴀʀ\r\n𝟹. ᴍᴏᴠɪᴇ ɪs ɴᴏᴛ ᴀᴠᴀɪʟᴀʙʟᴇ ɪɴ ᴛʜᴇ ᴅᴀᴛᴀʙᴀsᴇ ʀᴇᴘᴏʀᴛ ᴛᴏ ᴀᴅᴍɪɴs @TG_Bots_Supporter</b>\"\"\"\r\n\r\n I_CUD_NT = \"\"\"<b>ɪ ᴄᴏᴜʟᴅɴ'ᴛ ꜰɪɴᴅ ᴀɴʏ ᴍᴏᴠɪᴇ ʀᴇʟᴀᴛᴇᴅ ᴛᴏ {}.\r\nᴘʟᴇᴀꜱᴇ ᴄʜᴇᴄᴋ ᴛʜᴇ ꜱᴘᴇʟʟɪɴɢ ᴏɴ ɢᴏᴏɢʟᴇ ᴏʀ ɪᴍᴅʙ...</b>\"\"\"\r\n\r\n MVE_NT_FND = \"\"\"<b>ᴍᴏᴠɪᴇ ɴᴏᴛ ꜰᴏᴜɴᴅ ɪɴ ᴅᴀᴛᴀʙᴀꜱᴇ...</b>\"\"\"\r\n\r\n TOP_ALRT_MSG = \"\"\"<b>Cʜᴇᴄᴋɪɴɢ Fᴏʀ Mᴏᴠɪᴇ Iɴ Dᴀᴛᴀʙᴀsᴇ...</b>\"\"\"\r\n\r\n MELCOW_ENG = \"\"\"<b>Hᴇʟʟᴏ {} 😍, Aɴᴅ Wᴇʟᴄᴏᴍᴇ Tᴏ {} Gʀᴏᴜᴘ ❤️\r\n\r\n➻ ʜᴇʀᴇ ʏᴏᴜ ᴄᴀɴ ꜱᴇᴀʀᴄʜ ʏᴏᴜʀ ꜰᴀᴠᴏᴜʀɪᴛᴇ ᴍᴏᴠɪᴇꜱ ᴏʀ ꜱᴇʀɪᴇꜱ ʙʏ ᴊᴜꜱᴛ ᴛʏᴘɪɴɢ ɪᴛ'ꜱ ɴᴀᴍᴇ. \r\n\r\n⚠️ ɪꜰ ʏᴏᴜ ᴀʀᴇ ʜᴀᴠɪɴɢ ᴀɴʏ ᴘʀᴏʙʟᴇᴍ ʀᴇɢᴀʀᴅɪɴɢ ᴅᴏᴡɴʟᴏᴀᴅɪɴɢ ᴏʀ ꜱᴏᴍᴇᴛʜɪɴɢ ᴇʟꜱᴇ ᴛʜᴇɴ ᴍᴇꜱꜱᴀɢᴇ ʜᴇʀᴇ 👇</b>\"\"\"\r\n \r\n REQINFO = \"\"\"\r\n⚠ ɪɴꜰᴏʀᴍᴀᴛɪᴏɴ ⚠\r\n\r\nᴀꜰᴛᴇʀ 5 ᴍɪɴᴜᴛᴇꜱ ᴛʜɪꜱ ᴍᴇꜱꜱᴀɢᴇ ᴡɪʟʟ ʙᴇ ᴀᴜᴛᴏᴍᴀᴛɪᴄᴀʟʟʏ ᴅᴇʟᴇᴛᴇᴅ\r\n\r\nɪꜰ ʏᴏᴜ ᴅᴏ ɴᴏᴛ ꜱᴇᴇ ᴛʜᴇ ʀᴇǫᴜᴇsᴛᴇᴅ ᴍᴏᴠɪᴇ / sᴇʀɪᴇs ꜰɪʟᴇ, ʟᴏᴏᴋ ᴀᴛ ᴛʜᴇ ɴᴇxᴛ ᴘᴀɢᴇ\"\"\"\r\n\r\n \r\n\r\n SINFO = \"\"\"\r\n⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯\r\nꜱᴇʀɪᴇꜱ ʀᴇǫᴜᴇꜱᴛ ꜰᴏʀᴍᴀᴛ\r\n⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯\r\n\r\nɢᴏ ᴛᴏ ɢᴏᴏɢʟᴇ ➠ ᴛʏᴘᴇ ꜱᴇʀɪᴇꜱ ɴᴀᴍᴇ ➠ ᴄᴏᴘʏ ᴄᴏʀʀᴇᴄᴛ ɴᴀᴍᴇ ➠ ᴘᴀꜱᴛᴇ ᴛʜɪꜱ ɢʀᴏᴜᴘ\r\n\r\nᴇxᴀᴍᴘʟᴇ : Loki S01E01\r\n\r\n🚯 ᴅᴏɴᴛ ᴜꜱᴇ ➠ ':(!,./)\"\"\"\r\n\r\n NORSLTS = \"\"\"\r\n★ #𝗡𝗼𝗥𝗲𝘀𝘂𝗹𝘁𝘀 ★\r\n\r\n𝗜𝗗 <b>: {}</b>\r\n\r\n𝗡𝗮𝗺𝗲 <b>: {}</b>\r\n\r\n𝗠𝗲𝘀𝘀𝗮𝗴𝗲 <b>: {}</b>🥲\"\"\"\r\n\r\n CAPTION = \"\"\" \r\n🗂 𝗙𝗶𝗹𝗲: <b><font class=smcp>{file_name}</font></b>\r\n📀 𝗦𝗶𝘇𝗲: <b><font class=smcp>{file_size}</font></b>\r\n\r\n<b>🔰 Cʀᴇᴀᴛᴏʀ : <a href=\"https://t.me/KUSHALHK\">𝐊𝐔𝐒𝐇𝐀𝐋</a>\r\n🔰 Cʜᴀɴɴᴇʟ : <a href=\"https://t.me/TG_LINKS_CHANNEL\">𝐌𝐎𝐕𝐈𝐄𝐒 𝐂𝐇𝐀𝐍𝐍𝐄𝐋</a>\r\n🔰 Gʀᴏᴜᴘ : <a href=\"https://t.me/movies_hub_official1\">𝐌𝐎𝐕𝐈𝐄 𝐑𝐄𝐐𝐔𝐄𝐒𝐓 𝐆𝐑𝐎𝐔𝐏</a></b>\"\"\"\r\n \r\n IMDB_TEMPLATE_TXT = \"\"\"\r\n<b>Query: {query}\r\nIMDb Data:\r\n\r\n🧿 𝐓𝐈𝐓𝐋𝐄: <a href={url}>{title}</a>\r\n🎭 𝐆𝐄𝐍𝐑𝐄𝐒: {genres}\r\n📆 𝐘𝐄𝐀𝐑: <a href={url}/releaseinfo>{year}</a>\r\n🌟 𝐑𝐀𝐓𝐈𝐍𝐆: <a href={url}/ratings>{rating}</a> / 10 (Based on {votes} user ratings)</b>\r\n☀️ 𝐋𝐀𝐍𝐆𝐔𝐀𝐆𝐄 : <code>{languages}</code></a>\r\n📀 𝐑𝐔𝐍𝐓𝐈𝐌𝐄: {runtime} Minutes</a>\r\n\r\n<b>👨‍💼 Requested by : {message.from_user.mention}</b>\"\"\"\r\n\r\n \r\n ALL_FILTERS = \"\"\"\r\n<b>Hᴇʏ {}, Tʜᴇsᴇ ᴀʀᴇ ᴍʏ ᴛʜʀᴇᴇ ᴛʏᴘᴇs ᴏғ ғɪʟᴛᴇʀs.</b>\"\"\"\r\n \r\n GFILTER_TXT = \"\"\"Hᴇʟᴘ : <b>Gʟᴏʙᴀʟ Fɪʟᴛᴇʀs</b>\r\n \r\n◈ Gʟᴏʙᴀʟ Fɪʟᴛᴇʀs ᴀʀᴇ ᴛʜᴇ ғɪʟᴛᴇʀs sᴇᴛ ʙʏ ʙᴏᴛ ᴀᴅᴍɪɴs ᴡʜɪᴄʜ ᴡɪʟʟ ᴡᴏʀᴋ ᴏɴ ᴀʟʟ ɢʀᴏᴜᴘs.\r\n \r\n<b>Cᴏᴍᴍᴀɴᴅs Aɴᴅ Usᴀɢᴇ :</b>\r\n• /gfilter - Tᴏ ᴄʀᴇᴀᴛᴇ ᴀ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀ.\r\n• /gfilters - Tᴏ ᴠɪᴇᴡ ᴀʟʟ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀs.\r\n• /delg - Tᴏ ᴅᴇʟᴇᴛᴇ ᴀ ᴘᴀʀᴛɪᴄᴜʟᴀʀ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀ.\r\n• /delallg - ᴛᴏ ᴅᴇʟᴇᴛᴇ ᴀʟʟ ɢʟᴏʙᴀʟ ꜰɪʟᴛᴇʀꜱ.\"\"\"\r\n \r\n FILE_STORE_TXT = \"\"\"Hᴇʟᴘ : <b>Fɪʟᴇ Sᴛᴏʀᴇ</b>\r\n \r\n◈ Fɪʟᴇ sᴛᴏʀᴇ ɪs ᴛʜᴇ ғᴇᴀᴛᴜʀᴇ ᴡʜɪᴄʜ ᴡɪʟʟ ᴄʀᴇᴀᴛᴇ ᴀ sʜᴀʀᴇᴀʙʟᴇ ʟɪɴᴋ ᴏғ ᴀ sɪɴɢʟᴇ ᴏʀ ᴍᴜʟᴛɪᴘʟᴇ ғɪʟᴇs.\r\n\r\n<b>Cᴏᴍᴍᴀɴᴅs Aɴᴅ Usᴀɢᴇ :</b>\r\n• /batch - ᴛᴏ ᴄʀᴇᴀᴛᴇ ᴀ ʙᴀᴛᴄʜ ʟɪɴᴋ ᴏғ ᴍᴜʟᴛɪᴘʟᴇ ғɪʟᴇs.\r\n• /link - ᴛᴏ ᴄʀᴇᴀᴛᴇ ᴀ sɪɴɢʟᴇ ғɪʟᴇ sᴛᴏʀᴇ ʟɪɴᴋ.\r\n• /pbatch - ᴊᴜsᴛ ʟɪᴋᴇ <code>/batch</code>, ʙᴜᴛ ᴛʜᴇ ғɪʟᴇs ᴡɪʟʟ ʙᴇ sᴇɴᴅ ᴡɪᴛʜ ғᴏʀᴡᴀʀᴅ ʀᴇsᴛʀɪᴄᴛɪᴏɴs.\r\n• /plink - ᴊᴜsᴛ ʟɪᴋᴇ <code>/link</code>, ʙᴜᴛ ᴛʜᴇ ғɪʟᴇ ᴡɪʟʟ ʙᴇ sᴇɴᴅ ᴡɪᴛʜ ғᴏʀᴡᴀʀᴅ ʀᴇsᴛʀɪᴄᴛɪᴏɴ.\"\"\"\r\n\r\n CHECK_TXT = \"\"\"\r\n<b>🔥 ᴄʜᴏᴏsᴇ ʏᴏᴜʀ sᴜɪᴛᴀʙʟᴇ ᴘʟᴀɴ ᴀɴᴅ ᴘᴀʏ ʏᴏᴜʀ ᴘʀᴇᴍɪᴜᴍ ғᴇᴇs ᴜsɪɴɢ ᴀɴʏ ᴜᴘɪ ᴀᴘᴘ. \r\n\r\nᴘʟᴀɴ ᴀ : 𝟷 ᴡᴇᴇᴋ / ₹𝟷𝟻\r\nᴘʟᴀɴ ʙ : 𝟷 ᴍᴏɴᴛʜ / ₹𝟹𝟿\r\nᴘʟᴀɴ ᴄ : 𝟷 ʏᴇᴀʀ / ₹𝟹𝟼𝟶\r\n\r\n➻ ᴜᴘɪ ɪᴅ : harikushal234@paytm\r\n\r\n‼️ ᴍᴜsᴛ sᴇɴᴅ sᴄʀᴇᴇɴsʜᴏᴛ ᴀғᴛᴇʀ ᴘᴀʏᴍᴇɴᴛ ᴀɴᴅ ɢɪᴠᴇ ᴍᴇ sᴏᴍᴇ ᴛɪᴍᴇ ᴛᴏ ᴀᴅᴅ ʏᴏᴜ ɪɴ ᴛʜᴇ ᴘʀᴇᴍɪᴜᴍ ʟɪsᴛ.</b>\"\"\"\r\n\r\n PLAN1_TXT = \"\"\"\r\n<b>🔥 ᴘᴀʏ ʏᴏᴜʀ ᴘʀᴇᴍɪᴜᴍ ᴘʟᴀɴ ғᴇᴇs ₹𝟷𝟻 ғᴏʀ 𝟷 ᴡᴇᴇᴋ ᴘʀᴇᴍɪᴜᴍ ᴀᴄᴄᴇss ᴡɪᴛʜ ᴀᴅ-ғʀᴇᴇ ᴇxᴘᴇʀɪᴇɴᴄᴇ ᴀɴᴅ ᴍᴀɴʏ ᴍᴏʀᴇ. \r\n\r\n➻ ᴜᴘɪ ɪᴅ : harikushal234@paytm\r\n\r\n‼️ ᴍᴜsᴛ sᴇɴᴅ sᴄʀᴇᴇɴsʜᴏᴛ ᴀғᴛᴇʀ ᴘᴀʏᴍᴇɴᴛ ᴀɴᴅ ɢɪᴠᴇ ᴍᴇ sᴏᴍᴇ ᴛɪᴍᴇ ᴛᴏ ᴀᴅᴅ ʏᴏᴜ ɪɴ ᴛʜᴇ ᴘʀᴇᴍɪᴜᴍ ʟɪsᴛ.</b>\"\"\"\r\n\r\n PLAN2_TXT = \"\"\"\r\n<b>🔥 ᴘᴀʏ ʏᴏᴜʀ ᴘʀᴇᴍɪᴜᴍ ᴘʟᴀɴ ғᴇᴇs ₹𝟹𝟿 ғᴏʀ 𝟷 ᴍᴏɴᴛʜ ᴘʀᴇᴍɪᴜᴍ ᴀᴄᴄᴇss ᴡɪᴛʜ ᴀᴅ-ғʀᴇᴇ ᴇxᴘᴇʀɪᴇɴᴄᴇ ᴀɴᴅ ᴍᴀɴʏ ᴍᴏʀᴇ. \r\n\r\n➻ ᴜᴘɪ ɪᴅ : harikushal234@paytm\r\n\r\n‼️ ᴍᴜsᴛ sᴇɴᴅ sᴄʀᴇᴇɴsʜᴏᴛ ᴀғᴛᴇʀ ᴘᴀʏᴍᴇɴᴛ ᴀɴᴅ ɢɪᴠᴇ ᴍᴇ sᴏᴍᴇ ᴛɪᴍᴇ ᴛᴏ ᴀᴅᴅ ʏᴏᴜ ɪɴ ᴛʜᴇ ᴘʀᴇᴍɪᴜᴍ ʟɪsᴛ.</b>\"\"\"\r\n\r\n PLAN3_TXT = \"\"\"\r\n<b>🔥 ᴘᴀʏ ʏᴏᴜʀ ᴘʀᴇᴍɪᴜᴍ ᴘʟᴀɴ ғᴇᴇs ₹𝟹𝟼𝟶 ғᴏʀ 𝟷 ʏᴇᴀʀ ᴘʀᴇᴍɪᴜᴍ ᴀᴄᴄᴇss ᴡɪᴛʜ ᴀᴅ-ғʀᴇᴇ ᴇxᴘᴇʀɪᴇɴᴄᴇ ᴀɴᴅ ᴍᴀɴʏ ᴍᴏʀᴇ. \r\n\r\n➻ ᴜᴘɪ ɪᴅ : harikushal234@paytm\r\n\r\n‼️ ᴍᴜsᴛ sᴇɴᴅ sᴄʀᴇᴇɴsʜᴏᴛ ᴀғᴛᴇʀ ᴘᴀʏᴍᴇɴᴛ ᴀɴᴅ ɢɪᴠᴇ ᴍᴇ sᴏᴍᴇ ᴛɪᴍᴇ ᴛᴏ ᴀᴅᴅ ʏᴏᴜ ɪɴ ᴛʜᴇ ᴘʀᴇᴍɪᴜᴍ ʟɪsᴛ.</b>\"\"\"\r\n\r\n RESTART_TXT = \"\"\"\r\n<b>Bᴏᴛ Rᴇsᴛᴀʀᴛᴇᴅ !\r\n\r\n📅 Dᴀᴛᴇ : <code>{}</code>\r\n⏰ Tɪᴍᴇ : <code>{}</code>\r\n🌐 Tɪᴍᴇᴢᴏɴᴇ : <code>Asia/Kolkata</code>\r\n🛠️ Bᴜɪʟᴅ Sᴛᴀᴛᴜs: <code>ᴠ𝟹.𝟶 [ Sᴛᴀʙʟᴇ ]</code></b>\"\"\"\r\n\r\n LOGO = \"\"\"\r\n ____ ___ ____ __ ____ ____ \r\n(_ _)/ __) ( _ \\ / \\(_ _)(__ )\r\n )( ( (_ \\ ) _ (( O ) )( / _/ \r\n (__) \\___/ (____/ \\__/ (__) (____)\"\"\"\r" } ]
from pyrogram import Client, filters, enums from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery from pyrogram.errors.exceptions.bad_request_400 import MessageTooLong, PeerIdInvalid from info import ADMINS, LOG_CHANNEL, SUPPORT_CHAT, MELCOW_NEW_USERS, MELCOW_VID, CHNL_LNK, GRP_LNK from database.users_chats_db import db from database.ia_filterdb import Media from utils import get_size, temp, get_settings from Script import script from pyrogram.errors import ChatAdminRequired import asyncio
19,629
"""-----------------------------------------https://t.me/TG_LINKS_CHANNEL--------------------------------------""" @Client.on_message(filters.new_chat_members & filters.group) async def save_group(bot, message): r_j_check = [u.id for u in message.new_chat_members] if temp.ME in r_j_check: if not await db.get_chat(message.chat.id): total=await bot.get_chat_members_count(message.chat.id) r_j = message.from_user.mention if message.from_user else "Anonymous" await bot.send_message(LOG_CHANNEL, script.LOG_TEXT_G.format(message.chat.title, message.chat.id, total, r_j)) await db.add_chat(message.chat.id, message.chat.title) if message.chat.id in temp.BANNED_CHATS: # Inspired from a boat of a banana tree buttons = [[ InlineKeyboardButton('Support', url=f'https://t.me/{SUPPORT_CHAT}') ]] reply_markup=InlineKeyboardMarkup(buttons) k = await message.reply( text='<b>CHAT NOT ALLOWED 🐞\n\nMy admins has restricted me from working here ! If you want to know more about it contact support..</b>', reply_markup=reply_markup, ) try: await k.pin() except: pass await bot.leave_chat(message.chat.id) return buttons = [[ InlineKeyboardButton('🔸 ᴍᴇꜱꜱᴀɢᴇ ʜᴇʀᴇ 🔹', url="https://t.me/TG_Bots_Supporter") ],[ InlineKeyboardButton('ᴄʜᴀɴɴᴇʟ', url=CHNL_LNK),
"""-----------------------------------------https://t.me/TG_LINKS_CHANNEL--------------------------------------""" @Client.on_message(filters.new_chat_members & filters.group) async def save_group(bot, message): r_j_check = [u.id for u in message.new_chat_members] if temp.ME in r_j_check: if not await db.get_chat(message.chat.id): total=await bot.get_chat_members_count(message.chat.id) r_j = message.from_user.mention if message.from_user else "Anonymous" await bot.send_message(LOG_CHANNEL, script.LOG_TEXT_G.format(message.chat.title, message.chat.id, total, r_j)) await db.add_chat(message.chat.id, message.chat.title) if message.chat.id in temp.BANNED_CHATS: # Inspired from a boat of a banana tree buttons = [[ InlineKeyboardButton('Support', url=f'https://t.me/{SUPPORT_CHAT}') ]] reply_markup=InlineKeyboardMarkup(buttons) k = await message.reply( text='<b>CHAT NOT ALLOWED 🐞\n\nMy admins has restricted me from working here ! If you want to know more about it contact support..</b>', reply_markup=reply_markup, ) try: await k.pin() except: pass await bot.leave_chat(message.chat.id) return buttons = [[ InlineKeyboardButton('🔸 ᴍᴇꜱꜱᴀɢᴇ ʜᴇʀᴇ 🔹', url="https://t.me/TG_Bots_Supporter") ],[ InlineKeyboardButton('ᴄʜᴀɴɴᴇʟ', url=CHNL_LNK),
InlineKeyboardButton('ɢʀᴏᴜᴘ', url=GRP_LNK)
6
2023-11-03 12:21:26+00:00
24k
apple/ml-reed
reed/algorithms/pebble.py
[ { "identifier": "utils", "path": "BPref/utils.py", "snippet": "def make_env(cfg):\ndef ppo_make_env(env_id, seed):\ndef tie_weights(src, trg):\ndef make_metaworld_env(cfg):\ndef ppo_make_metaworld_env(env_id, seed):\n def __init__(self, *models):\n def __enter__(self):\n def __exit__(self, *args):\n def __init__(self, *models):\n def __enter__(self):\n def __exit__(self, *args):\ndef soft_update_params(net, target_net, tau):\ndef set_seed_everywhere(seed):\ndef make_dir(*path_parts):\ndef weight_init(m):\n def __init__(self,\n input_dim,\n hidden_dim,\n output_dim,\n hidden_depth,\n output_mod=None):\n def forward(self, x):\n def __init__(self, cache_size=1):\n def atanh(x):\n def __eq__(self, other):\n def _call(self, x):\n def _inverse(self, y):\n def log_abs_det_jacobian(self, x, y):\n def __init__(self, loc, scale):\n def mean(self):\n def __init__(self, epsilon=1e-4, shape=(), device=None):\n def update(self, x):\n def update_from_moments(self, batch_mean, batch_var, batch_count):\n def std(self):\ndef update_mean_var_count_from_moments(\n mean, var, count, batch_mean, batch_var, batch_count\n):\ndef mlp(input_dim, hidden_dim, output_dim, hidden_depth, output_mod=None):\ndef to_np(t):\nclass eval_mode(object):\nclass train_mode(object):\nclass MLP(nn.Module):\nclass TanhTransform(pyd.transforms.Transform):\nclass SquashedNormal(pyd.transformed_distribution.TransformedDistribution):\nclass TorchRunningMeanStd:\n M2 = m_a + m_b + torch.pow(delta, 2) * count * batch_count / tot_count" }, { "identifier": "Logger", "path": "BPref/logger.py", "snippet": "class Logger(object):\n def __init__(self,\n log_dir,\n save_tb=False,\n log_frequency=10000,\n agent='sac'):\n self._log_dir = log_dir\n self._log_frequency = log_frequency\n if save_tb:\n tb_dir = os.path.join(log_dir, 'tb')\n if os.path.exists(tb_dir):\n try:\n shutil.rmtree(tb_dir)\n except:\n print(\"logger.py warning: Unable to remove tb directory\")\n pass\n self._sw = SummaryWriter(tb_dir)\n else:\n self._sw = None\n # each agent has specific output format for training\n assert agent in AGENT_TRAIN_FORMAT\n train_format = COMMON_TRAIN_FORMAT + AGENT_TRAIN_FORMAT[agent]\n self._train_mg = MetersGroup(os.path.join(log_dir, 'train'),\n formating=train_format)\n self._eval_mg = MetersGroup(os.path.join(log_dir, 'eval'),\n formating=COMMON_EVAL_FORMAT)\n\n def _should_log(self, step, log_frequency):\n log_frequency = log_frequency or self._log_frequency\n return step % log_frequency == 0\n\n def _try_sw_log(self, key, value, step):\n if self._sw is not None:\n self._sw.add_scalar(key, value, step)\n\n def _try_sw_log_video(self, key, frames, step):\n if self._sw is not None:\n frames = torch.from_numpy(np.array(frames))\n frames = frames.unsqueeze(0)\n self._sw.add_video(key, frames, step, fps=30)\n\n def _try_sw_log_histogram(self, key, histogram, step):\n if self._sw is not None:\n self._sw.add_histogram(key, histogram, step)\n\n def log(self, key, value, step, n=1, log_frequency=1):\n if not self._should_log(step, log_frequency):\n return\n assert key.startswith('train') or key.startswith('eval')\n if type(value) == torch.Tensor:\n value = value.item()\n self._try_sw_log(key, value / n, step)\n mg = self._train_mg if key.startswith('train') else self._eval_mg\n mg.log(key, value, n)\n\n def log_param(self, key, param, step, log_frequency=None):\n if not self._should_log(step, log_frequency):\n return\n self.log_histogram(key + '_w', param.weight.data, step)\n if hasattr(param.weight, 'grad') and param.weight.grad is not None:\n self.log_histogram(key + '_w_g', param.weight.grad.data, step)\n if hasattr(param, 'bias') and hasattr(param.bias, 'data'):\n self.log_histogram(key + '_b', param.bias.data, step)\n if hasattr(param.bias, 'grad') and param.bias.grad is not None:\n self.log_histogram(key + '_b_g', param.bias.grad.data, step)\n\n def log_video(self, key, frames, step, log_frequency=None):\n if not self._should_log(step, log_frequency):\n return\n assert key.startswith('train') or key.startswith('eval')\n self._try_sw_log_video(key, frames, step)\n\n def log_histogram(self, key, histogram, step, log_frequency=None):\n if not self._should_log(step, log_frequency):\n return\n assert key.startswith('train') or key.startswith('eval')\n self._try_sw_log_histogram(key, histogram, step)\n\n def dump(self, step, save=True, ty=None):\n if ty is None:\n self._train_mg.dump(step, 'train', save)\n self._eval_mg.dump(step, 'eval', save)\n elif ty == 'eval':\n self._eval_mg.dump(step, 'eval', save)\n elif ty == 'train':\n self._train_mg.dump(step, 'train', save)\n else:\n raise f'invalid log type: {ty}'" }, { "identifier": "TrajectoryReplayBuffer", "path": "BPref/replay_buffer.py", "snippet": "class TrajectoryReplayBuffer:\n \"\"\"\n Buffer to store trajectories of environment transitions. Unlike ReplayBuffer, which stores all transitions in a\n flat manner, transitions are sorted by trajectory. Each trajectory corresponds to an episode.\n \"\"\"\n _RELABEL_BATCH_SIZE = 256\n\n def __init__(self, capacity: int, device: torch.device, window: int = 1, num_envs: t.Optional[int] = None,\n image_observations: t.Optional[t.Union[int, np.ndarray]] = None):\n \"\"\"\n Args:\n capacity: the number of trajectories to hold in memory\n device: the device sampled transitions should be put on\n window: no idea - part of the original code and is used in add_batch(...) which has not yet been refactored\n num_envs: the number of environment instances used to train the policy. Only needs to be specified when the\n number is >1. Some algorithms train on multiple instances of an environment at once, e.g. PPO.\n Not currently used, but not yet removed because we have not tested with an algorithm that needs\n multiple environment instances.\n image_observations: (default = false) whether to collect image observations in addition to state\n observations. This is helpful to use when the policy is trained on the state, but you\n want to visualize the trajectories or the reward model is trained on images.\n\n \"\"\"\n self.capacity = capacity\n self.device = device\n\n self.observations: t.Optional[np.ndarray] = None\n self.actions: t.Optional[np.ndarray] = None\n self.rewards: t.Optional[np.ndarray] = None\n self.not_dones: t.Optional[np.ndarray] = None\n self.not_dones_no_max: t.Optional[np.ndarray] = None\n self.trajectory_lengths: t.List = []\n self.window = window\n self.env_rewards: t.Optional[np.ndarray] = None\n self.image_observations: t.Optional[np.ndarray] = None\n # track whether to collect image observations - when not None, specifies the dimensions of the images\n self._collect_image_observations = image_observations\n\n # track the trajectories as a list of Trajectory\n self.trajectories: t.List[Trajectory] = []\n\n self.idx = 0\n self.last_save = 0\n self.full = False\n\n def __len__(self):\n return np.sum(self.trajectory_lengths) - len(self.trajectory_lengths)\n\n def __getitem__(self, flat_indx: t.Union[int, t.Tuple[int, int], t.List[int]]) -> TRANSITION:\n \"\"\"\n Get the transition at the given index\n\n Args:\n flat_indx: the index assuming transitions are stored flat instead of nested in trajectories\n - when an integer is specified, a single transition is retrieved\n - when a tuple of integers is given, a slice is retrieved as if the transitions are stored flat\n\n Returns:\n current observation\n action\n reward\n next observation\n whether the episode ended\n whether the episode ended without reaching max steps\n image version of current observation (optional)\n \"\"\"\n if isinstance(flat_indx, int) or isinstance(flat_indx, np.int64):\n traj_indx, trans_indx = self._flat_indx_to_trajectory_index(flat_indx)\n # check we are grabbing from a trajectory currently being accumulated\n # When the done signal is given, the current trajectory being accumulated is converted to a trajectory,\n # is added to the list of trajectories, and the values used to accumulate the next trajectory are set to\n # done. The next trajectory is not started until the call to add(...) after the done signal is received.\n # Therefore, we need to check whether the trajectory to pull from is actually the last completed trajectory\n # prior to starting a new trajectory. This is why we compare the length of the lists containing trajectory\n # lengths and the list containing the trajectories.\n if (traj_indx == len(self.trajectory_lengths) - 1\n and len(self.trajectory_lengths) > len(self.trajectories)):\n # we need to grab from the trajectory currently being populated\n return (self.observations[trans_indx].astype(np.float32), self.actions[trans_indx].astype(np.float32),\n self.rewards[trans_indx].astype(np.float32), self.observations[trans_indx + 1].astype(np.float32),\n self.not_dones[trans_indx].astype(np.float32),\n self.not_dones_no_max[trans_indx].astype(np.float32),\n (self.env_rewards[trans_indx].astype(np.float32)\n if self.env_rewards is not None\n else None),\n ((self.image_observations[trans_indx].astype(np.float32))\n if self.image_observations is not None\n else None),\n ((self.image_observations[trans_indx+1].astype(np.float32))\n if self.image_observations is not None\n else None))\n else:\n # grab from a previously completed trajectory\n transition: Transition = self.trajectories[traj_indx][trans_indx]\n return (transition.observation.astype(np.float32), transition.action.astype(np.float32),\n transition.reward.astype(np.float32), transition.next_observation.astype(np.float32),\n transition.not_done.astype(np.float32), transition.not_done_no_max.astype(np.float32),\n transition.env_reward.astype(np.float32),\n (transition.image_observation.astype(np.float32)\n if transition.image_observation is not None\n else None),\n (transition.next_image_observation.astype(np.float32)\n if transition.next_image_observation is not None\n else None))\n elif isinstance(flat_indx, t.List):\n observations = []\n actions = []\n rewards = []\n next_observations = []\n not_dones = []\n not_dones_no_max = []\n env_rewards = []\n image_observations = []\n next_image_observations = []\n for indx in flat_indx:\n observation, action, reward, next_observation, not_done, not_done_no_max, env_reward, image_observation, next_image_observation = self[indx]\n observations.append(observation)\n actions.append(action)\n rewards.append(reward)\n next_observations.append(next_observation)\n not_dones.append(not_done)\n not_dones_no_max.append(not_done_no_max)\n if env_reward is not None:\n env_rewards.append(env_reward)\n if image_observation is not None:\n image_observations.append(image_observation)\n if next_image_observation is not None:\n next_image_observations.append(next_image_observation)\n return (np.asarray(observations, dtype=np.float32), np.asarray(actions, dtype=np.float32),\n np.asarray(rewards, dtype=np.float32), np.asarray(next_observations, dtype=np.float32),\n np.asarray(not_dones, dtype=np.float32), np.asarray(not_dones_no_max, dtype=np.float32),\n (np.asarray(env_rewards, dtype=np.float32) if len(env_rewards) > 0 else None),\n (np.asarray(image_observations, dtype=np.float32) if self._collect_image_observations else None),\n (np.asarray(next_image_observations, dtype=np.float32) if self._collect_image_observations else None))\n else:\n # get the locations of the start and end transitions\n start_traj_indx, start_trans_indx = self._flat_indx_to_trajectory_index(flat_indx[0])\n end_traj_indx, end_trans_indx = self._flat_indx_to_trajectory_index(flat_indx[1])\n # check that we are not spanning trajectories\n if start_traj_indx == end_traj_indx:\n # grab the sub-trajectory\n sub_trajectory = self.trajectories[start_traj_indx][tuple((start_trans_indx, end_trans_indx))]\n else:\n # grab what remains of the trajectory\n end_trans_indx = len(self.trajectories[start_traj_indx]) - 1\n sub_trajectory = self.trajectories[start_traj_indx][tuple((start_trans_indx, end_trans_indx))]\n return (sub_trajectory.initial_observations,\n sub_trajectory.actions,\n sub_trajectory.rewards,\n sub_trajectory.next_observations,\n sub_trajectory.not_dones,\n sub_trajectory.not_dones_no_max,\n sub_trajectory.env_rewards,\n (sub_trajectory.initial_image_observations\n if sub_trajectory.initial_image_observations is not None\n else None),\n (sub_trajectory.next_image_observations\n if sub_trajectory.next_image_observations is not None\n else None))\n\n @property\n def trajectory_count(self) -> int:\n \"\"\"\n The number of trajectories in the buffer\n \"\"\"\n return len(self.trajectories)\n\n @property\n def all_not_dones(self) -> np.ndarray:\n \"\"\"\n Rewards from the state-action pairs from all trajectories and all transitions, where the action was taken in the state\n \"\"\"\n return np.concatenate([np.expand_dims(traj.not_dones, axis=0) for traj in self.trajectories], axis=0)\n\n @property\n def all_rewards(self) -> np.ndarray:\n \"\"\"\n Rewards from the state-action pairs from all trajectories and all transitions, where the action was taken in the state\n \"\"\"\n return np.concatenate([np.expand_dims(traj.rewards, axis=0) for traj in self.trajectories], axis=0)\n\n @property\n def all_environment_rewards(self) -> np.ndarray:\n \"\"\"\n Environment rewards from all trajectories and all transitions\n \"\"\"\n return np.concatenate([np.expand_dims(traj.rewards, axis=0) for traj in self.trajectories], axis=0)\n\n @property\n def all_initial_image_observations(self) -> np.ndarray:\n \"\"\"\n Image observations from the state-action pairs from all trajectories and all transitions, where the action was taken in the state\n \"\"\"\n return np.concatenate([np.expand_dims(traj.initial_image_observations, axis=0)\n for traj in self.trajectories],\n axis=0)\n\n @property\n def all_next_image_observations(self) -> np.ndarray:\n \"\"\"\n Image observations from the state-action pairs from all trajectories and all transitions,\n\n The result of a transition\n \"\"\"\n return np.concatenate([np.expand_dims(traj.next_image_observations, axis=0)\n for traj in self.trajectories],\n axis=0)\n\n @property\n def all_initial_observations(self) -> np.ndarray:\n \"\"\"\n observations from the state-action pairs from all trajectories and all transitions, where the action was taken in the state\n \"\"\"\n return np.concatenate([np.expand_dims(traj.initial_observations, axis=0) for traj in self.trajectories], axis=0)\n\n @property\n def all_next_observations(self) -> np.ndarray:\n \"\"\"\n Observations from the state-action pairs from all trajectories and all transitions\n\n The result of a transition\n \"\"\"\n return np.concatenate([np.expand_dims(traj.next_observations, axis=0) for traj in self.trajectories], axis=0)\n\n @property\n def all_actions(self) -> np.ndarray:\n \"\"\"\n Actions from the state-action pairs from all trajectories and all transitions\n \"\"\"\n return np.concatenate([np.expand_dims(traj.actions, axis=0) for traj in self.trajectories], axis=0)\n\n def _flat_indx_to_trajectory_index(self, flat_indx: int) -> t.Tuple[int, int]:\n \"\"\"\n Converts an index that assumes the transitions are flat to a trajectory and transition (w/in trajectory) index\n\n Args:\n flat_indx: the index assuming transitions are stored flat\n\n Returns:\n the index of the trajectory containing the transition\n the index of the transition within the trajectory\n \"\"\"\n # need to figure out which transition indices are stored in which trajectories\n transition_cumulative_sum = np.cumsum(self.trajectory_lengths)\n # the trajectory containing the transition is at the first index where the cumulative sum of transitions is\n # less than the transition index\n target_trajectory_indx = int(np.argmax(flat_indx < transition_cumulative_sum))\n # get the transition's index within the trajectory as the different between the flat index and the cumulative\n # sum at the previous trajectory - tells us how far into the target trajectory the transition is\n if target_trajectory_indx == 0:\n transition_trajectory_indx = flat_indx\n else:\n transition_trajectory_indx = flat_indx - transition_cumulative_sum[target_trajectory_indx - 1]\n return target_trajectory_indx, transition_trajectory_indx\n\n def _add_transition(self, observation: np.ndarray, action: np.ndarray, reward: float, done: t.Union[float, bool],\n done_no_max: t.Union[float, bool],\n env_reward: t.Optional[float] = None, image_observations: t.Optional[np.ndarray] = None):\n \"\"\"\n Track the transition and update the length of the trajectory currently being accumulated\n\n Args:\n observation: the current observation\n action: the action taken in the current state\n reward: the reward associated with the last state-action pait\n done: whether the last action completed an episode\n done_no_max: whether the last action completed an episode without reaching the maximum allowed steps\n env_reward: (optional) the reward given by the environment - stored and used to train the preference-learned\n reward model when learning from synthetic feedback\n image_observations: (optional) image-based observation -> should not be given is observations is also an image. This\n should be used when you want to accumulate images separately from policy training.\n \"\"\"\n self.observations = np.concatenate([self.observations, np.expand_dims(observation, axis=0)], axis=0)\n self.actions = np.concatenate([self.actions, np.expand_dims(action, axis=0)], axis=0)\n self.rewards = np.concatenate([self.rewards, np.asarray(reward).reshape(1, 1)], axis=0)\n if type(done) is float:\n self.not_dones = np.concatenate([self.not_dones,\n np.asarray(not done, dtype=np.float32).reshape(1, 1)], axis=0)\n self.not_dones_no_max = np.concatenate([self.not_dones_no_max,\n np.asarray(not done_no_max, dtype=np.float32).reshape(1, 1)],\n axis=0)\n else:\n self.not_dones = np.concatenate([self.not_dones,\n np.asarray(~done, dtype=np.float32).reshape(1, 1)], axis=0)\n self.not_dones_no_max = np.concatenate([self.not_dones_no_max,\n np.asarray(~done_no_max, dtype=np.float32).reshape(1, 1)],\n axis=0)\n\n self.trajectory_lengths[-1] += 1\n if env_reward is not None:\n self.env_rewards = np.concatenate([self.env_rewards,\n np.asarray(env_reward, dtype=np.float32).reshape(1, 1)], axis=0)\n\n if image_observations is not None and self._collect_image_observations:\n self.image_observations = np.concatenate([self.image_observations, np.expand_dims(image_observations, axis=0)], axis=0)\n\n def _start_trajectory(self, observation: np.ndarray,\n action: np.ndarray,\n reward: float,\n done: t.Union[float, bool],\n done_no_max: t.Union[float, bool],\n env_reward: t.Optional[float] = None,\n image_observations: t.Optional[np.ndarray] = None):\n \"\"\"\n Start a new trajectory and track the transition\n\n Args:\n observation: the current observation\n action: the action taken in the current state\n reward: the reward associated with the last state-action pait\n done: whether the last action completed an episode\n done_no_max: whether the last action completed an episode without reaching the maximum allowed steps\n env_reward: (optional) the reward given by the environment - stored and used to train the preference-learned\n reward model when learning from synthetic feedback\n image_observations: (optional) image-based observation -> should not be given is observations is also an image. This\n should be used when you want to accumulate images separately from policy training.\n \"\"\"\n self.observations = np.expand_dims(observation, axis=0).astype(dtype=np.float32)\n self.actions = np.expand_dims(action, axis=0).astype(dtype=np.float32)\n self.rewards = np.asarray(reward, dtype=np.float32).reshape(1, 1)\n if type(done) is float:\n self.not_dones = np.asarray(not done, dtype=np.float32).reshape(1, 1)\n self.not_dones_no_max = np.asarray(not done_no_max, dtype=np.float32).reshape(1, 1)\n else:\n self.not_dones = np.asarray(~done, dtype=np.float32).reshape(1, 1)\n self.not_dones_no_max = np.asarray(~done_no_max, dtype=np.float32).reshape(1, 1)\n\n self.trajectory_lengths.append(1)\n\n if env_reward is not None:\n self.env_rewards = np.asarray(env_reward, dtype=np.float32).reshape(1, 1)\n\n if image_observations is not None and self._collect_image_observations:\n self.image_observations = np.expand_dims(image_observations, axis=0).astype(dtype=np.float32)\n\n def add(self, observation, action, reward, next_observation, done, done_no_max,\n env_reward: t.Optional[float] = None, image_observation: t.Optional[np.ndarray] = None,\n image_next_observation: t.Optional[np.ndarray] = None):\n \"\"\"\n Args:\n observation: the current observation\n action: the action taken in the current state\n reward: the reward associated with the last state-action pait\n next_observation: only used when an episode is completed to ensure the last observation is captured\n done: whether the last action completed an episode\n done_no_max: whether the last action completed an episode without reaching the maximum allowed steps\n env_reward: (optional) the reward given by the environment - stored and used to train the preference-learned\n reward model when learning from synthetic feedback\n image_observation: (optional) image-based observation -> should not be given is observations is also an image. This\n should be used when you want to accumulate images separately from policy training.\n image_next_observation: (optional) the image-based next observation -> should not be given when next_observation is also\n and image. This should be used when you want to accumulate the images separately from the\n trained policy.\n \"\"\"\n if self.observations is None:\n self._start_trajectory(observation, action, reward, done, done_no_max, env_reward, image_observation)\n elif done:\n self._add_transition(observation, action, reward, done, done_no_max, env_reward, image_observation)\n # the episode has ended, so we need to track the next observation\n self.observations = np.concatenate([self.observations, np.expand_dims(next_observation, axis=0)], axis=0)\n if image_next_observation is not None:\n self.image_observations = np.concatenate([self.image_observations,\n np.expand_dims(image_next_observation, axis=0)], axis=0)\n # create the trajectory\n self.trajectories.append(Trajectory(self.observations.astype(dtype=np.float32),\n (self.image_observations.astype(dtype=np.float32)\n if self.image_observations is not None\n else None),\n actions=self.actions.astype(dtype=np.float32),\n rewards=self.rewards.astype(dtype=np.float32),\n not_dones=self.not_dones.astype(dtype=np.float32),\n not_dones_no_max=self.not_dones_no_max.astype(dtype=np.float32),\n env_rewards=self.env_rewards.astype(dtype=np.float32)))\n # check if the inclusion of the just completed trajectory puts the buffer at capacity\n # if it does, remove the first trajectory as this is a FIFO buffer\n if np.sum(self.trajectory_lengths) >= self.capacity:\n self.trajectories = self.trajectories[1:]\n self.trajectory_lengths = self.trajectory_lengths[1:]\n self.observations = None\n self.actions = None\n self.rewards = None\n self.not_dones = None\n self.not_dones_no_max = None\n self.env_rewards = None\n self.image_observations = None\n else:\n self._add_transition(observation, action, reward, done, done_no_max, env_reward, image_observation)\n\n self.idx = (self.idx + 1) % self.capacity\n self.full = self.full or self.idx == 0\n\n def relabel_with_predictor(self, predictor, state_action_formatter: PreProcessInference):\n \"\"\"\n Relabel the rewards stored in the replay buffer using the given predictor\n\n Args:\n predictor: network that will consume state-action pairs and assign a reward\n state_action_formatter: formats the states and actions for consumption by the reward model\n \"\"\"\n print(\"Relabelling the replay buffer with the updated reward model.\")\n for trajectory in self.trajectories:\n # the number of batches to run through the model\n total_iter = int(len(trajectory) / self._RELABEL_BATCH_SIZE)\n # handle the case where we have more transitions than is evenly divisible by the batch size\n if len(trajectory) > self._RELABEL_BATCH_SIZE * total_iter:\n total_iter += 1\n # collect and process each batch to be passed through predictor\n for index in range(total_iter):\n start_indx = index * self._RELABEL_BATCH_SIZE\n # make sure we don't have an end index that is after the end of the trajectory\n end_indx = min((index + 1) * self._RELABEL_BATCH_SIZE, len(trajectory))\n\n # pull out the actions from the transitions that will be relabelled\n actions = trajectory.actions[start_indx:end_indx]\n # we need to handle the case where the reward model operates off of images\n if predictor.image_observations:\n observations = trajectory.all_image_observations[start_indx:end_indx]\n else:\n observations = trajectory.all_observations[start_indx:end_indx]\n formatted_state_action = state_action_formatter.format_state_action(observations, actions, batch_sa=True)\n pred_reward = predictor.r_hat_batch(formatted_state_action)\n # update the rewards assigned to the transitions\n trajectory.rewards[start_indx:end_indx] = pred_reward\n\n def sample(self, batch_size: int):\n indxs = list(np.random.randint(0, np.sum(self.trajectory_lengths) - 1, size=batch_size))\n observations, actions, rewards, next_observations, not_dones, not_dones_no_max, env_rewards, image_observations, next_image_observations = self[indxs]\n observations = torch.as_tensor(observations, device=self.device).float()\n actions = torch.as_tensor(actions, device=self.device)\n rewards = torch.as_tensor(rewards, device=self.device)\n next_observations = torch.as_tensor(next_observations, device=self.device).float()\n not_dones = torch.as_tensor(not_dones, device=self.device)\n not_dones_no_max = torch.as_tensor(not_dones_no_max, device=self.device)\n env_rewards = torch.as_tensor(env_rewards, device=self.device)\n image_observations = (torch.as_tensor(image_observations, device=self.device).float() if self._collect_image_observations else None)\n next_image_observations = (torch.as_tensor(next_image_observations, device=self.device).float() if self._collect_image_observations else None)\n return observations, actions, rewards, next_observations, not_dones, not_dones_no_max, env_rewards, image_observations, next_image_observations\n\n def sample_state_ent(self, batch_size: int):\n observations, actions, rewards, next_observations, not_dones, not_dones_no_max, _, _, _ = self.sample(batch_size)\n full_observation = torch.as_tensor(np.concatenate([traj.all_observations for traj in self.trajectories], axis=0),\n device=self.device)\n return observations, full_observation, actions, rewards, next_observations, not_dones, not_dones_no_max\n\n def save(self, out_directory: Path, env_id: str, step: int):\n \"\"\"\n Save the replay buffer to disk as a npz archive\n Args:\n out_directory: location where replay buffer will be saved\n env_id: the environment within which the data was generated\n step: the number of policy training steps taken to produce this dataset\n \"\"\"\n # create the ZipFile object\n zip_obj = ZipFile(out_directory / f\"{env_id}_replay_buffer_{step}.zip\", \"w\")\n\n # write each trajectory file to disk and to the zip archive\n for traj_id, trajectory in enumerate(self.trajectories):\n trajectory.save(out_directory / f\"{traj_id}.npz\")\n zip_obj.write(out_directory / f\"{traj_id}.npz\")\n # close the Zip File\n zip_obj.close()\n\n @staticmethod\n def from_directory(directory_path: Path,\n device: torch.device = 'cuda') -> \"TrajectoryReplayBuffer\":\n \"\"\"\n Create a TrajectoryReplay buffer from a directory of npz archive trajectories\n\n Args:\n directory_path: the location of the npz_archive on disk\n device: the device sampled transitions should be pushed to\n Returns:\n populated trajectory replay buffer\n \"\"\"\n # accumulate the trajectories\n trajectories = []\n trajectory_lengths = []\n # determine how many transitions are in the replay buffer\n capacity = 0\n # load each trajectory from disk\n for traj_filename in directory_path.iterdir():\n # we only load data from npz archives, so we need to skip anything else\n if not traj_filename.suffix == \".npz\": continue\n # load the trajectory from disk\n traj = Trajectory.from_npz(traj_filename)\n # track the trajectory\n trajectories.append(traj)\n # track the trajectory's length\n trajectory_lengths.append(len(traj))\n # track the trajectory's length\n capacity += len(traj)\n # create the buffer\n _buffer = TrajectoryReplayBuffer(capacity=capacity, device=device)\n # add the trajectories to the buffer\n _buffer.trajectories = trajectories\n _buffer.trajectory_lengths = trajectory_lengths\n\n return _buffer" }, { "identifier": "StateActionRewardModel", "path": "reed/models/reward_model.py", "snippet": "class StateActionRewardModel:\n \"\"\"\n Reward model that operates over state action pairs\n \"\"\"\n def __init__(self,\n in_dim: t.Union[int, t.List[int]],\n ensemble_size: int = 3,\n hidden_dim: int = 256,\n hidden_layers: int = 3,\n final_activation: str = 'tanh',\n lr: float = 3e-4,\n optimizer: str = \"adam\",\n reward_train_batch: int = 128,\n size_segment: int = 1,\n device: torch.device = \"cuda\",\n multi_gpu: bool = False,\n image_observations: bool = False,\n image_encoder_architecture: str = \"pixl2r\",\n image_hidden_num_channels: int = 32,\n grayscale_images: bool = True):\n # the device the model will be put on\n self.device = device\n # whether data parallelism should be used during model training\n self.multi_gpu = multi_gpu\n # reward model configuration\n self.in_dim = in_dim\n self.hidden_dim = hidden_dim\n self.hidden_layers = hidden_layers\n self.ensemble_size = ensemble_size\n self.lr = lr\n self.optimizer_type = optimizer\n self.ensemble = []\n self.paramlst = []\n self.optimizer = None\n self.model = None\n self.final_activation = final_activation\n self.size_segment = size_segment\n\n self.image_observations = image_observations\n self.image_encoder_architecture = image_encoder_architecture\n self.image_hidden_num_channels = image_hidden_num_channels\n self.grayscale_images = grayscale_images\n\n # construct the reward ensemble\n self.construct_ensemble()\n\n # parameters used to train the reward model on the preference labelled trajectories\n self.train_batch_size = reward_train_batch\n self.CEloss = nn.CrossEntropyLoss()\n\n def eval(self):\n \"\"\"Set each reward model in the ensemble to evaluation mode\"\"\"\n self.ensemble = [net.eval() for net in self.ensemble]\n\n def train(self):\n \"\"\"Set each reward model in the ensemble to train mode\"\"\"\n self.ensemble = [net.train() for net in self.ensemble]\n\n def softXEnt_loss(self, predicted: torch.Tensor, target: torch.Tensor):\n logprobs = F.log_softmax(predicted, dim=1)\n return -(target * logprobs).sum() / predicted.shape[0]\n\n def construct_ensemble(self):\n for _ in range(self.ensemble_size):\n if self.image_observations:\n model = ImageStateActionNetwork(self.in_dim,\n out_size=1,\n hidden_dim=self.hidden_dim,\n hidden_depth=self.hidden_layers,\n final_activation=self.final_activation,\n image_encoder_architecture=self.image_encoder_architecture,\n image_hidden_num_channels=self.image_hidden_num_channels).float()\n else:\n model = StateActionNetwork(self.in_dim,\n out_size=1,\n hidden_dim=self.hidden_dim,\n hidden_depth=self.hidden_layers,\n final_activation=self.final_activation).float()\n print(model)\n # check if the model will be run with Data Parallelism\n if self.multi_gpu:\n print(f\"There are {torch.cuda.device_count()} GPU devices, so the reward ensemble WILL be trained \"\n f\"using nn.DataParallel\")\n self.ensemble.append(nn.DataParallel(model).to(self.device))\n else:\n print(f\"There are {torch.cuda.device_count()} GPU devices, so the reward ensemble will NOT be trained \"\n f\"using nn.DataParallel\")\n self.ensemble.append(model.to(self.device))\n # track all model parameters\n self.paramlst.extend(model.parameters())\n # create a single optimizer applied to all ensemble members\n if self.optimizer_type == \"adam\":\n self.optimizer = torch.optim.Adam(self.paramlst, lr=self.lr)\n elif self.optimizer_type == \"sgd\":\n self.optimizer = torch.optim.SGD(self.paramlst, lr=self.lr)\n else:\n raise NotImplementedError(f\"{self.optimizer_type} is not implemented as a reward optimizer and must be \"\n f\"one of 'adam' or 'sgd'.\")\n\n def format_state(self, obs: np.ndarray, batch_states: bool = False, by_trajectory: bool = False):\n \"\"\"\n Args:\n obs: the state observations\n batch_states: whether a batch of state is to be processed\n by_trajectory: whether the batch of states is structured by trajectory -> should only be\n True when batch_sa=True\n Returns:\n the state-action pairs as a single array\n \"\"\"\n if self.image_observations:\n # check if the images needs to be converted to grayscale\n if self.grayscale_images:\n obs = _to_grayscale(obs, batch_states=batch_states)\n if batch_states:\n # permute the input so that the channels are in the first dimension\n if by_trajectory:\n obs = np.transpose(obs, (0, 1, 4, 2, 3))\n else:\n print(obs.shape)\n obs = np.transpose(obs, (0, 3, 1, 2))\n return obs\n else:\n # permute the input so that the channels are in the first dimension\n obs = np.transpose(obs, (2, 0, 1))\n # add a dimension along the front for concatenation into the buffer\n return obs.reshape(1, *obs.shape)\n else:\n return obs.reshape(1, obs.shape[1:]) if batch_states else obs.reshape(1, obs.shape[0])\n\n def format_state_action(self, obs: np.ndarray, act: np.ndarray,\n batch_sa: bool = False, by_trajectory: bool = False) -> np.ndarray:\n \"\"\"\n Args:\n obs: the state observations\n act: the actions associated with each state observation\n batch_sa: whether a batch of state-action pairs is to be processed\n by_trajectory: whether the batch of state-action pairs is structured by trajectory -> should only be\n True when batch_sa=True\n Returns:\n the state-action pairs as a single array\n \"\"\"\n if self.image_observations:\n # check if the images needs to be converted to grayscale\n if self.grayscale_images:\n obs = _to_grayscale(obs, batch_states=batch_sa)\n if batch_sa:\n obs_dim = obs.shape[1:]\n # we concatenate the actions along channel dimension of the image\n if by_trajectory:\n repeated_actions = np.tile(act.reshape((act.shape[0], act.shape[1], 1, 1, act.shape[-1])),\n (1, 1, obs_dim[0], obs_dim[1], 1))\n else:\n repeated_actions = np.tile(act.reshape((act.shape[0], 1, 1, act.shape[-1])),\n (1, obs_dim[0], obs_dim[1], 1))\n # now concatenate the two\n sa_t = np.concatenate((obs, repeated_actions), axis=-1)\n # permute the input so that the channels are in the first dimension\n if by_trajectory:\n sa_t = np.transpose(sa_t, (0, 1, 4, 2, 3))\n else:\n sa_t = np.transpose(sa_t, (0, 3, 1, 2))\n return sa_t\n else:\n obs_dim = obs.shape\n # we concatenate the actions along channel dimension of the image\n repeated_actions = np.tile(act.reshape((1, 1, -1)), (obs_dim[0], obs_dim[1], 1))\n # now concatenate the two\n sa_t = np.concatenate((obs, repeated_actions), axis=-1)\n # permute the input so that the channels are in the first dimension\n sa_t = np.transpose(sa_t, (2, 0, 1))\n # add a dimension along the front for concatenation into the buffer\n return sa_t.reshape(1, *self.in_dim)\n else:\n sa_t = np.concatenate([obs, act], axis=-1)\n if batch_sa:\n return sa_t\n else:\n return sa_t.reshape(1, -1)\n\n def p_hat_member(self, x_1: np.ndarray, x_2: np.ndarray, member: int = -1):\n # softmaxing to get the probabilities according to eqn 1\n with torch.no_grad():\n # if we are using image observations, we need to collapse along the batch and time dimensions to push\n # a forward pass through the network\n # to compute the probabilities when then need to re-construct the batch and time dimensions\n if self.image_observations:\n # we need to compute the probabilities in batches to avoid out of memory issues\n # we use the train batch size as it should be an amount safe to put on the GPU's memory without causing\n # issues\n mb_size = self.train_batch_size\n start_indx = 0\n r_hat1 = None\n r_hat2 = None\n while start_indx < x_1.shape[0]:\n # check if there is a mb_size worth of trajectories to still be processed\n if start_indx + mb_size <= x_1.shape[0]:\n mb_x_1 = x_1[start_indx:start_indx + mb_size].reshape((-1, *x_1.shape[2:]))\n mb_x_2 = x_1[start_indx:start_indx + mb_size].reshape((-1, *x_1.shape[2:]))\n else:\n # process the leftover trajectories in a batch smaller than mb_size\n mb_x_1 = x_1[start_indx:].reshape((-1, *x_1.shape[2:]))\n mb_x_2 = x_2[start_indx:].reshape((-1, *x_2.shape[2:]))\n # process the leftover trajectories in a batch smaller than mb_size\n mb_rhat1 = self.r_hat_member(torch.from_numpy(mb_x_1).float().to(self.device),\n member=member).detach().cpu().reshape((mb_size, x_1.shape[1], 1))\n mb_rhat2 = self.r_hat_member(torch.from_numpy(mb_x_2).float().to(self.device),\n member=member).detach().cpu().reshape((mb_size, x_2.shape[1], 1))\n start_indx += mb_size\n\n # accumulate the rhats\n if r_hat1 is None:\n r_hat1 = mb_rhat1\n r_hat2 = mb_rhat2\n else:\n r_hat1 = torch.concat((r_hat1, mb_rhat1), dim=0)\n r_hat2 = torch.concat((r_hat2, mb_rhat2))\n\n else:\n r_hat1 = self.r_hat_member(x_1, member=member).cpu()\n r_hat2 = self.r_hat_member(x_2, member=member).cpu()\n r_hat1 = r_hat1.sum(axis=1)\n r_hat2 = r_hat2.sum(axis=1)\n r_hat = torch.cat([r_hat1, r_hat2], axis=-1)\n # taking 0 index for probability x_1 > x_2\n return F.softmax(r_hat, dim=-1)[:, 0]\n\n def p_hat_entropy(self, x_1: np.ndarray, x_2: np.ndarray, member: int = -1):\n # softmaxing to get the probabilities according to eqn 1\n with torch.no_grad():\n r_hat1 = self.r_hat_member(x_1, member=member)\n r_hat2 = self.r_hat_member(x_2, member=member)\n r_hat1 = r_hat1.sum(axis=1)\n r_hat2 = r_hat2.sum(axis=1)\n r_hat = torch.cat([r_hat1, r_hat2], axis=-1)\n\n ent = F.softmax(r_hat, dim=-1) * F.log_softmax(r_hat, dim=-1)\n ent = ent.sum(axis=-1).abs()\n return ent\n\n def r_hat_member(self, x: torch.Tensor, member: int = -1) -> torch.Tensor:\n # the network parameterizes r hat in eqn 1 from the paper\n # return self.ensemble[member](torch.from_numpy(x).float().to(device))\n return self.ensemble[member](x)\n\n def r_hat(self, x: np.ndarray):\n # they say they average the rewards from each member of the ensemble, but I think this only makes sense if the\n # rewards are already normalized and I don't understand how the normalization should be happening right now :(\n r_hats = []\n for member in range(self.ensemble_size):\n r_hats.append(self.r_hat_member(torch.from_numpy(x).float().to(self.device), member=member).detach().cpu().numpy())\n r_hats = np.array(r_hats)\n return np.mean(r_hats)\n\n def r_hat_batch(self, x: np.ndarray):\n # they say they average the rewards from each member of the ensemble, but I think this only makes sense if the rewards are already normalized\n # but I don't understand how the normalization should be happening right now :(\n r_hats = []\n for member in range(self.ensemble_size):\n r_hats.append(self.r_hat_member(torch.from_numpy(x).float().to(self.device), member=member).detach().cpu().numpy())\n r_hats = np.array(r_hats)\n return np.mean(r_hats, axis=0)\n\n def save(self, model_dir: str, env_id: str, step: int):\n \"\"\"\n Save the reward ensemble to disk\n\n Args:\n model_dir: path where the ensemble is to be saved\n env_id: the environment on which the ensemble has been trained\n step: the number of policy training steps\n \"\"\"\n for member in range(self.ensemble_size):\n torch.save(\n self.ensemble[member].state_dict(), f'{model_dir}/{env_id}_reward_model_{step}_{member}.pt'\n )\n\n def train_reward(self,\n preference_data_loader: PreferenceTripletEnsembleDataLoader,\n num_epoch: int):\n \"\"\"\n Train the reward model on the given preference dataset.\n\n Args:\n preference_data_loader: loads batches of preference triplets. Separated handles different preference\n dataset permutations for each member of the reward's ensemble.\n num_epoch: the number of training epochs to execute\n \"\"\"\n # track the accuracy and loss by ensemble member per epoch\n ensemble_accuracies = np.zeros((num_epoch, self.ensemble_size))\n ensemble_losses = np.zeros((num_epoch, self.ensemble_size))\n\n # train the reward model for the specified number of epochs\n for epoch in range(num_epoch):\n if epoch % 10 == 0:\n print(f\"Running preference training epoch {epoch} of {num_epoch}\")\n epoch_ensemble_losses = np.zeros(self.ensemble_size)\n epoch_ensemble_acc = np.zeros(self.ensemble_size)\n # train on each batch\n for batch_indx, batch in enumerate(preference_data_loader):\n # confirm there is either a single batch to be shared by all networks in the reward ensemble or\n # a batch per network in the ensemble\n assert len(batch) == 1 or len(batch) == self.ensemble_size\n # we need to zero out the gradients before we begin to process this batch\n self.optimizer.zero_grad()\n # we will need to accumulate the loss across the ensemble members\n batch_loss = 0.0\n for member_indx, preference_triplet_batch in enumerate(batch):\n # the predicted reward per transition in each trajectory\n # check if we need to collapse the batch and time dimensions into one and then reconstruct the two\n if self.image_observations:\n # get the rewards for each transition in the trajectories one\n traj_one_shape = preference_triplet_batch.trajectories_one.shape\n formatted_trajectories_one = preference_triplet_batch.trajectories_one.reshape(\n (-1, *traj_one_shape[2:]))\n r_hat1 = self.r_hat_member(formatted_trajectories_one,\n member=member_indx).reshape((traj_one_shape[0],\n traj_one_shape[1], 1))\n # get the rewards for each transition in the trajectories two\n traj_two_shape = preference_triplet_batch.trajectories_two.shape\n formatted_trajectories_two = preference_triplet_batch.trajectories_two.reshape(\n (-1, *traj_two_shape[2:]))\n r_hat2 = self.r_hat_member(formatted_trajectories_two,\n member=member_indx).reshape((traj_two_shape[0],\n traj_two_shape[1], 1))\n else:\n r_hat1 = self.r_hat_member(preference_triplet_batch.trajectories_one,\n member=member_indx)\n r_hat2 = self.r_hat_member(preference_triplet_batch.trajectories_two,\n member=member_indx)\n # compute the return per trajectory\n r_hat1 = r_hat1.sum(axis=1)\n r_hat2 = r_hat2.sum(axis=1)\n\n r_hat = torch.cat([r_hat1, r_hat2], dim=-1)\n\n # compute the ensemble member's loss\n curr_loss = self.CEloss(r_hat, preference_triplet_batch.preference_labels.squeeze())\n # add the loss from the ensemble member to the batch loss\n batch_loss += curr_loss\n # track the loss for this ensemble member\n epoch_ensemble_losses[member_indx] += curr_loss.item()\n\n # compute the accuracy of the ensemble member's predictions\n _, predicted = torch.max(r_hat.data, 1)\n correct = (predicted == preference_triplet_batch.preference_labels.squeeze()).sum().item()\n epoch_ensemble_acc[member_indx] += correct\n # compute the gradients\n batch_loss.backward()\n # apply the gradients to the model\n self.optimizer.step()\n # compute the ensemble accuracy for this epoch\n ensemble_accuracies[epoch] = epoch_ensemble_acc / preference_data_loader.dataset_length()\n # compute the mean ensemble loss for this epoch\n ensemble_losses[epoch] = epoch_ensemble_losses / preference_data_loader.dataset_length()\n\n if epoch % 10 == 0:\n print(f\"Epoch {epoch} mean accuracy = {np.mean(ensemble_accuracies[:epoch + 1]):.2f}\")\n\n # check the current mean accuracy, if it is greater than 0.97 then terminate training\n if np.mean(ensemble_accuracies[epoch]) >= 0.97:\n print(f\"Epoch accuracy {np.mean(ensemble_accuracies[epoch]):.2f} \"\n f\"after {epoch} epochs triggered early stopping.\")\n return ensemble_accuracies[:epoch + 1], ensemble_losses[:epoch + 1]\n\n print(f\"Epoch {num_epoch} mean accuracy = {np.mean(ensemble_accuracies):.2f}\")\n\n return ensemble_accuracies, ensemble_losses" }, { "identifier": "PreferenceDataset", "path": "reed/data/preference_dataset.py", "snippet": "class PreferenceDataset:\n def __init__(self, observation_dim: t.Union[t.Tuple, int], action_dim: t.Union[t.Tuple, int], capacity: int,\n size_segment: int, out_path: Path, image_observations: bool, grayscale_images: bool,\n collect_image_pref_dataset: bool, state_action_formatter: PreProcessInference,\n teacher_beta: float = -1, teacher_gamma: float = 1,\n teacher_eps_mistake: float = 0, teacher_eps_skip: float = 0, teacher_eps_equal: float = 0):\n \"\"\"\n Args:\n observation_dim: the dimensionality of the observations\n action_dim: the dimensionality of the actions\n capacity: the maximum number of trajectory pairs to include in the action_dimtaset\n size_segment: the length of the trajectory segments\n out_path: the location where the preference action_dimtaset will be written to disk during training\n image_observations: whether the observations given to the reward model are images\n grayscale_images: whether the image observations should be converted to grayscale instead of color\n collect_image_pref_dataset: whether to collect the image preference dataset separate from the observations.\n Should NOT be set to true if the observations are images.\n state_action_formatter: function that maps states and actions to a single input\n teacher_beta\n teacher_gamma: used to determine how much influence each reward has on the preference label based on\n order within the trajectory. Used to compute the return\n teacher_eps_mistake: the frequency with which the teacher assigns an incorrect label\n teacher_eps_skip: the frequency with which the teacher does not assign a label\n teacher_eps_equal: the maximum difference between trajectory returns for the two trajectories to be labelled\n as equally preferred\n \"\"\"\n self.observation_dim = observation_dim\n self.action_dim = action_dim\n self.capacity = capacity\n self.size_segment = size_segment\n self.out_path = out_path\n self.image_observations = image_observations\n self.grayscale_images = grayscale_images\n # whether to collect the preference dataset as images\n # only needs to be set to True if we are not learning the reward function from images\n # if we are learning the reward function from images then we have an image dataset\n self.collect_image_pref_dataset = collect_image_pref_dataset\n\n # formats the state-action pairs into a single input to the reward model\n self.state_action_formatter = state_action_formatter\n\n # track where each preference triplet is written to disk\n self._preference_triplet_tracker: t.List[Path] = []\n\n self.buffer_index = 0\n self.buffer_full = False\n\n # create the preference labeller\n self._preference_labeller = _PreferenceLabeller(teacher_beta=teacher_beta, teacher_gamma=teacher_gamma,\n teacher_eps_mistake=teacher_eps_mistake,\n teacher_eps_skip=teacher_eps_skip,\n teacher_eps_equal=teacher_eps_equal)\n\n # make sure the outpath where the trajectories will be written exist\n self.out_path.mkdir(parents=True, exist_ok=True)\n\n def __len__(self):\n return len(self._preference_triplet_tracker)\n\n def __getitem__(self, item: int) -> PREFERENCE_TRIPLET:\n \"\"\"\n Load and return the preference triplet at the specified index in the buffer\n\n Args:\n item: index of the triplet in the buffer\n Returns:\n trajectory one\n trajectory two\n preference label\n \"\"\"\n # get the location of the specified preference triplet and load it into memory\n npz_archive = np.load(self._preference_triplet_tracker[item].as_posix())\n\n # grab the trajectories and preference labels\n trajectory_one = npz_archive[\"trajectory_one\"]\n trajectory_two = npz_archive[\"trajectory_two\"]\n preference_label = npz_archive[\"preference_label\"]\n\n return trajectory_one, trajectory_two, preference_label\n\n def get_batch(self, indices: t.List[int]) -> PREFERENCE_TRIPLET_BATCH:\n \"\"\"\n Load and return the batch of preference triplets at the given indices in the buffer\n\n Args:\n indices: the buffer indices of the preference triplets to load into memory\n Returns:\n batch of trajectories one\n batch of trajectories two\n batch of preference labels\n \"\"\"\n # accumulate the trajectory pairs and preference labels\n trajectories_one = []\n trajectories_two = []\n preference_labels = []\n # grab each preference triplet\n for index in indices:\n trajectory_one, trajectory_two, preference_label = self[index]\n trajectories_one.append(np.expand_dims(trajectory_one, axis=0))\n trajectories_two.append(np.expand_dims(trajectory_two, axis=0))\n preference_labels.append(preference_label)\n\n return (np.concatenate(trajectories_one, axis=0), np.concatenate(trajectories_two, axis=0),\n np.concatenate(preference_labels, axis=0))\n\n def _sample_trajectory_segments_uniform(self,\n experience_buffer: TrajectoryReplayBuffer,\n trajectory_count: int,\n mini_batch_size: int) -> t.Tuple[np.ndarray, np.ndarray, t.Optional[np.ndarray]]:\n \"\"\"\n Uniformly sample trajectories and then uniformly sample a segment of the trajectory.\n\n Format and track the state-action pairs from each trajectory segment\n Format and track rewards from each trajectory segment\n\n Combine the formatted state-action pairs and the rewards across trajectory segments\n\n Args:\n experience_buffer: the replay buffer from which trajectory pairs will be drawn\n trajectory_count: the number of trajectories to be sampled from\n mini_batch_size: the number of trajectories to sample\n\n Returns:\n the formatted state-action pairs from random trajectory segments from trajectories\n the rewards from each random trajectory segment\n (optionally) the image observations from each random trajectory segment - only returned when the flag to\n collect image observations in the preference dataset is true and image observations are not\n used to train the reward model\n \"\"\"\n # select the trajectories to be included in this batch of trajectory segments\n trajectory_indices = np.random.choice(trajectory_count, size=mini_batch_size, replace=True)\n\n # accumulate the formatted state-action pairs and rewards from each trajectory segment\n state_action_pairs = []\n rewards = []\n # optionally accumulate image observations\n image_observations = ([] if self.collect_image_pref_dataset and not self.image_observations else None)\n # extract each trajectory and randomly sample a segment\n for traj_index in trajectory_indices:\n # grab the trajectory\n trajectory = experience_buffer.trajectories[traj_index]\n # select a random segment from the trajectory\n traj_segment = trajectory.random_segment(length=self.size_segment)\n # track the rewards associated with the random segment\n rewards.append(np.expand_dims(traj_segment.env_rewards, axis=0))\n # format the state and action based on whether image observations are being used\n if self.image_observations:\n formatted_pair = self.state_action_formatter.format_state_action(\n traj_segment.initial_image_observations,\n traj_segment.actions,\n batch_sa=True)\n else:\n formatted_pair = self.state_action_formatter.format_state_action(\n traj_segment.initial_observations,\n traj_segment.actions,\n batch_sa=True)\n if self.collect_image_pref_dataset:\n image_observations.append(np.expand_dims(traj_segment.initial_image_observations, axis=0))\n # add a dimension in the front so we can concatenate later and the track\n state_action_pairs.append(np.expand_dims(formatted_pair, axis=0))\n return (np.concatenate(state_action_pairs, axis=0),\n np.concatenate(rewards, axis=0),\n (np.concatenate(image_observations, axis=0) if image_observations is not None else None))\n\n @staticmethod\n def get_rank_probability(trajectories_one: np.ndarray, trajectories_two: np.ndarray,\n reward_model: torch.nn.Module):\n \"\"\"\n Compute the preference-prediction disagreement between the ensemble members for each trajectory pair\n\n Args:\n trajectories_one: the trajectories one to be evaluated for ensemble disagreement\n trajectories_two: the trajectories two to be evaluated for ensemble disagreement\n reward_model: the ensemble of networks that will be used to compute disagreement\n \"\"\"\n\n # get probability x_1 > x_2\n probs = []\n for member in range(len(reward_model.ensemble)):\n probs.append(reward_model.p_hat_member(trajectories_one,\n trajectories_two,\n member=member).cpu().numpy())\n probs = np.array(probs)\n\n return np.mean(probs, axis=0), np.std(probs, axis=0)\n\n def get_queries(self, experience_buffer: TrajectoryReplayBuffer, mb_size=20):\n len_traj, max_len = experience_buffer.trajectory_lengths[0], experience_buffer.trajectory_count\n\n # if len(self.experience_buffer.trajectory_lengths[0][-1]) < len_traj:\n # check that the last trajectory contains at least as many transitions as the target segment length\n # we check the last trajectory, because it may be incomplete\n # this is a carry over from the original code. The authors had an assumption that all \"completed\" trajectories\n # will be at least as long as the target segment length\n if experience_buffer.trajectory_lengths[-1] < self.size_segment:\n max_len = max_len - 1\n\n # grab each trajectory, select a random segment from each, format the state-action pairs, and concatenate\n # along the batch dimension\n state_action_pair_traj_one, r_t_1, images_traj_one = self._sample_trajectory_segments_uniform(\n experience_buffer=experience_buffer,\n trajectory_count=max_len,\n mini_batch_size=mb_size)\n state_action_pair_traj_two, r_t_2, images_traj_two = self._sample_trajectory_segments_uniform(\n experience_buffer=experience_buffer,\n trajectory_count=max_len,\n mini_batch_size=mb_size)\n # confirm the image-specific variables are only populated when they should be\n if not self.collect_image_pref_dataset and self.image_observations:\n assert images_traj_one is None and images_traj_two is None\n return state_action_pair_traj_one, state_action_pair_traj_two, r_t_1, r_t_2, images_traj_one, images_traj_two\n\n def put_queries(self, state_action_pair_traj_one: np.ndarray, state_action_pair_traj_two: np.ndarray,\n preference_labels: np.ndarray,\n images_traj_one: t.Optional[np.ndarray] = None, images_traj_two: t.Optional[np.ndarray] = None):\n \"\"\"\n Args:\n state_action_pair_traj_one: the state-action pairs that make up the trajectories one in the queries\n state_action_pair_traj_two: the state-action pairs that make up the trajectories two in the queries\n preference_labels: the preference labels for each pair of trajectories\n images_traj_one: the images for trajectories one\n images_traj_two: the images for trajectories two\n \"\"\"\n # get the number of triplets to be stored\n total_sample = state_action_pair_traj_one.shape[0]\n # write each preference_triplet to disk\n for batch_indx in range(total_sample):\n # get the index of the triplet in the \"buffer\"\n preference_triplet_index = self.buffer_index + batch_indx\n # check if we need to wrap the buffer\n if preference_triplet_index >= self.capacity:\n preference_triplet_index -= self.capacity\n elif not self.buffer_full:\n # this is a previously unseen preference triplet buffer index, so we need to track the triplet location\n self._preference_triplet_tracker.append(self.out_path / f\"preference_triplet_{preference_triplet_index}.npz\")\n # save the preference triplet\n np.savez((self.out_path / f\"preference_triplet_{preference_triplet_index}.npz\").as_posix(),\n trajectory_one=state_action_pair_traj_one[batch_indx],\n trajectory_two=state_action_pair_traj_two[batch_indx],\n preference_label=preference_labels[batch_indx],\n image_trajectory_one=(\n None if images_traj_one is None else images_traj_one[batch_indx]),\n image_trajectory_two=(\n None if images_traj_two is None else images_traj_two[batch_indx]))\n # set the new buffer index\n next_index = self.buffer_index + total_sample\n # check if the buffer has wrapped\n if next_index >= self.capacity:\n self.buffer_full = True\n # wrap the buffer index\n self.buffer_index = next_index - self.capacity\n else:\n self.buffer_index = next_index\n\n def uniform_sampling(self, experience_buffer: TrajectoryReplayBuffer, mb_size: int) -> int:\n \"\"\"\n Grow the preference dataset with preference triplets uniformly sampled from the experience buffer\n\n Args:\n experience_buffer: the replay buffer from which to sample trajectory pairs\n mb_size: target number of preference triplets to add to the preference dataset. Fewer than the target may\n be added depending on the whether labeller skips labelling some trajectories.\n Returns:\n number of preference triplets added to the dataset\n \"\"\"\n # get queries\n sa_t_1, sa_t_2, r_t_1, r_t_2, img_sa_t_1, img_sa_t_2 = self.get_queries(experience_buffer=experience_buffer,\n mb_size=mb_size)\n\n # get labels\n sa_t_1, sa_t_2, r_t_1, r_t_2, labels = self._preference_labeller.get_label(sa_t_1, sa_t_2, r_t_1, r_t_2)\n if len(labels) > 0:\n self.put_queries(sa_t_1, sa_t_2, labels, img_sa_t_1, img_sa_t_2)\n\n return len(labels)\n\n # TODO: refactor to break the circular import that would need to happen in order to specify that reward_model here\n # should be BPref.reward_model.RewardModel\n def disagreement_sampling(self, experience_buffer: TrajectoryReplayBuffer, mb_size: int, large_batch: int,\n reward_model: torch.nn.Module) -> int:\n \"\"\"\n Grow the preference dataset with preference triplets from the experience buffer that the reward ensemble\n disagrees about\n\n Args:\n experience_buffer: the replay buffer from which to sample trajectory pairs\n mb_size: target number of preference triplets to add to the preference dataset. Fewer than the target may\n be added depending on the whether labeller skips labelling some trajectories.\n large_batch: scales up the number of triplets to add to the preference dataset to uniformly select a large\n number of trajectory pairs, which are then pruned based on which ones the reward ensemble\n has the most disagreement over\n reward_model: the ensemble of reward networks that will be used to assess disagreement.\n Should be BPref.reward_model.RewardModel, but cannot import and reference from here right now\n as it would lead to circular imports\n Returns:\n number of preference triplets added to the dataset\n \"\"\"\n # get queries\n sa_t_1, sa_t_2, r_t_1, r_t_2, img_sa_t_1, img_sa_t_2 = self.get_queries(\n experience_buffer=experience_buffer, mb_size=mb_size * large_batch)\n\n # get final queries based on ensemble member disagreement\n _, disagree = self.get_rank_probability(sa_t_1, sa_t_2, reward_model=reward_model)\n top_k_index = (-disagree).argsort()[:mb_size]\n r_t_1, sa_t_1 = r_t_1[top_k_index], sa_t_1[top_k_index]\n r_t_2, sa_t_2 = r_t_2[top_k_index], sa_t_2[top_k_index]\n if img_sa_t_1 is not None:\n img_sa_t_1 = img_sa_t_1[top_k_index]\n img_sa_t_2 = img_sa_t_2[top_k_index]\n\n # get labels\n sa_t_1, sa_t_2, r_t_1, r_t_2, labels = self._preference_labeller.get_label(\n sa_t_1, sa_t_2, r_t_1, r_t_2)\n if len(labels) > 0:\n self.put_queries(sa_t_1, sa_t_2, labels, img_sa_t_1, img_sa_t_2)\n\n return len(labels)\n\n def set_teacher_thres_skip(self, new_margin):\n self._preference_labeller.teacher_thres_skip = new_margin * self._preference_labeller.teacher_eps_skip\n\n def set_teacher_thres_equal(self, new_margin):\n self._preference_labeller.teacher_eps_equal = new_margin * self._preference_labeller.teacher_eps_equal\n\n def save(self, dataset_dir: Path, env_id: str, step: int):\n \"\"\"\n Saves the preference dataset as a zip archive and the labeller configuration as a yaml to the specified location\n\n Args:\n dataset_dir: path where the dataset is to be saved\n env_id: the environment/task within which the data was generated\n step: the number of policy training steps taken to produce this dataset\n \"\"\"\n # create the ZipFile object\n zip_obj = ZipFile(dataset_dir / f\"{env_id}_preference_dataset_{step}.zip\", \"w\")\n # the configuration for the online preference dataset\n config = {\"teacher_params\": {\"teacher_beta\": self._preference_labeller.teacher_beta,\n \"teacher_gamma\": self._preference_labeller.teacher_gamma,\n \"teacher_eps_mistake\": self._preference_labeller.teacher_eps_mistake,\n \"teacher_eps_equal\": self._preference_labeller.teacher_eps_equal,\n \"teacher_eps_skip\": self._preference_labeller.teacher_eps_skip,\n \"teacher_thres_skip\": self._preference_labeller.teacher_thres_skip,\n \"teacher_thres_equal\": self._preference_labeller.teacher_thres_equal,\n \"label_margin\": self._preference_labeller.label_margin,\n \"label_target\": self._preference_labeller.label_target}}\n with open((dataset_dir / f\"preference_dataset_config.yaml\").as_posix(), \"w+\") as f:\n yaml.dump(config, f)\n # write the labeller config to the preference dataset's zip archive\n zip_obj.write(dataset_dir / f\"preference_dataset_config.yaml\")\n\n # add each preference triplet to the zip archive\n for pref_triplet_path in self._preference_triplet_tracker:\n zip_obj.write(pref_triplet_path)\n # move the file from it temp location to the artifact directory\n file_dest_path = dataset_dir / pref_triplet_path.name\n shutil.move(pref_triplet_path, file_dest_path)\n # close the Zip File\n zip_obj.close()" }, { "identifier": "PreferenceTripletEnsembleDataLoader", "path": "reed/data/preference_data_loader.py", "snippet": "class PreferenceTripletEnsembleDataLoader:\n \"\"\"\n Handles loading and generating batches of preference triplets.\n\n The special logic needed is to handle different batch orderings for different networks in the reward ensemble\n \"\"\"\n def __init__(self, dataset: PreferenceDataset, ensemble_size: int,\n batch_size: int = 64, num_workers: int = 0, shuffle: bool = True, device: torch.device = \"cuda\"):\n \"\"\"\n Args:\n\n \"\"\"\n # create a data loader per ensemble network\n self.loader_ensemble = [DataLoader(dataset=dataset,\n batch_size=batch_size,\n shuffle=shuffle,\n num_workers=num_workers)\n for _ in range(ensemble_size)]\n\n self.device = device\n\n def _format_batch(self, batch: UNFORMATTED_PREFERENCE_TRIPLET_BATCH) -> FORMATTED_PREFERENCE_TRIPLET_BATCH:\n \"\"\"\n Format the preference batch so that the tensors are longs and on the correct device\n \"\"\"\n return [PreferenceTripletBatch(trajectories_one=member[0].float().to(self.device),\n trajectories_two=member[1].float().to(self.device),\n preference_labels=member[2].long().to(self.device))\n for member in batch]\n\n def dataset_length(self) -> int:\n return len(self.loader_ensemble[0].dataset)\n\n def __iter__(self) -> FORMATTED_PREFERENCE_TRIPLET_BATCH:\n \"\"\"\n Iterate through the preference triplet data loaders and return the batch per ensemble member\n\n Returns:\n list of PreferenceTripletBatch\n \"\"\"\n # set up each loader as an iterator\n iter_loader_ensemble = [iter(loader) for loader in self.loader_ensemble]\n # for each data loader grab the next batch until there are no more batches to grab\n while True:\n # check if there is a next batch to return\n try:\n yield self._format_batch([next(dataloader_iterator) for dataloader_iterator in iter_loader_ensemble])\n except StopIteration:\n break" }, { "identifier": "PreProcessInference", "path": "reed/data/preprocess_images.py", "snippet": "class PreProcessInference:\n \"\"\"\n Preprocess the data for inference by the reward, SSC, and SFC models\n \"\"\"\n def __init__(self,\n image_observations: bool = False,\n grayscale_images: bool = True,\n normalize_images: bool = True,\n environment_id: str = \"dmc\"):\n \"\"\"\n Args:\n image_observations: whether the observations are images\n grayscale_images: whether images observations should be in grayscale\n normalize_images: whether the image observations should be normalized\n environment_id: the environment from which the data is coming\n \"\"\"\n self.image_observations = image_observations\n self.grayscale_images = grayscale_images\n self.normalize_images = normalize_images\n self.environment_id = environment_id\n\n @staticmethod\n def _channel_first_to_last(observation: np.ndarray,\n batch_states: bool = False,\n by_trajectory: bool = False) -> np.ndarray:\n \"\"\"\n Move the channel from the first dimension to the last dimension\n \"\"\"\n if batch_states and by_trajectory:\n return np.transpose(observation, (0, 1, 3, 4, 2))\n elif batch_states:\n return np.transpose(observation, (0, 2, 3, 1))\n else:\n return np.transpose(observation, (1, 2, 0))\n\n @staticmethod\n def _channel_last_to_first(observation: np.ndarray, batch_states: bool = False,\n by_trajectory: bool = False) -> np.ndarray:\n \"\"\"\n Move the channel from the last dimension to the first dimension\n Args:\n observation: the state observations\n batch_states: whether a batch of state is to be processed\n by_trajectory: whether the batch of states is structured by trajectory -> should only be\n True when batch_sa=True\n Returns:\n the image with the channel dimension moved from first to last\n \"\"\"\n # permute the input so that the channels are in the first dimension of the images\n if batch_states and by_trajectory:\n return np.transpose(observation, (0, 1, 4, 2, 3))\n elif batch_states:\n return np.transpose(observation, (0, 3, 1, 2))\n else:\n # permute the input so that the channels are in the first dimension\n obs = np.transpose(observation, (2, 0, 1))\n # add a dimension along the front for concatenation into the buffer\n return np.expand_dims(obs, axis=0)\n\n def format_state(self, obs: np.ndarray, batch_states: bool = False,\n by_trajectory: bool = False, channel_first: bool = False) -> np.ndarray:\n \"\"\"\n Args:\n obs: the state observations\n batch_states: whether a batch of state is to be processed\n by_trajectory: whether the batch of states is structured by trajectory -> should only be\n True when batch_sa=True\n channel_first: whether the channel dimension is first when the observations are images.\n Returns:\n the state-action pairs as a single array\n \"\"\"\n if self.image_observations:\n if channel_first:\n # move the channel dimension from first to last to avoid a bunch of logic in our formatting methods\n # that handles variable locations for the channel dimension\n obs = self._channel_first_to_last(observation=obs,\n batch_states=batch_states,\n by_trajectory=by_trajectory)\n if self.grayscale_images:\n obs = _to_grayscale(observation=obs)\n if self.normalize_images:\n # TODO: add normalization based on pixel mean and standard deviation instead of scaling 0 to 1\n obs = np.divide(obs, 255.)\n # move the channel dimension from first to last\n return self._channel_last_to_first(observation=obs, batch_states=batch_states, by_trajectory=by_trajectory)\n\n else:\n return obs.reshape(1, obs.shape[1:]) if batch_states else obs.reshape(1, obs.shape[0])\n\n def format_state_action(self, obs: np.ndarray, act: np.ndarray,\n batch_sa: bool = False, by_trajectory: bool = False,\n channel_first: bool = False) -> np.ndarray:\n \"\"\"\n Args:\n obs: the state observations\n act: the actions associated with each state observation\n batch_sa: whether a batch of state-action pairs is to be processed\n by_trajectory: whether the batch of state-action pairs is structured by trajectory -> should only be\n True when batch_sa=True\n channel_first: whether the channel dimension is first when the observations are images.\n Returns:\n the state-action pairs as a single array\n \"\"\"\n if self.image_observations:\n if channel_first:\n # move the channel dimension from first to last to avoid a bunch of logic in our formatting methods\n # that handles variable locations for the channel dimension\n obs = self._channel_first_to_last(observation=obs,\n batch_states=batch_sa,\n by_trajectory=by_trajectory)\n if self.grayscale_images:\n obs = _to_grayscale(observation=obs)\n if self.normalize_images:\n # TODO: add normalization based on pixel mean and standard deviation instead of scaling 0 to 1\n obs = np.divide(obs, 255.)\n\n # get the dimensions of the image\n obs_dim = obs.shape[-3:]\n assert len(obs_dim) == 3\n # add the actions to the image channels and permute the input so that the channels are in the first\n # dimension of the images\n if batch_sa and by_trajectory:\n repeated_actions = np.tile(act.reshape((act.shape[0], act.shape[1], 1, 1, act.shape[-1])),\n (1, 1, obs_dim[0], obs_dim[1], 1))\n elif batch_sa:\n repeated_actions = np.tile(act.reshape((act.shape[0], 1, 1, act.shape[-1])),\n (1, obs_dim[0], obs_dim[1], 1))\n else:\n repeated_actions = np.tile(act.reshape((1, 1, -1)), (obs_dim[0], obs_dim[1], 1))\n sa_t = np.concatenate((obs, repeated_actions), axis=-1)\n return self._channel_last_to_first(sa_t, batch_states=batch_sa, by_trajectory=by_trajectory)\n else:\n sa_t = np.concatenate([obs, act], axis=-1)\n if batch_sa:\n return sa_t\n else:\n return sa_t.reshape(1, -1)" } ]
import typing as t import time import numpy as np import torch import hydra from pathlib import Path from omegaconf import dictconfig, OmegaConf from BPref import utils from BPref.logger import Logger from BPref.replay_buffer import TrajectoryReplayBuffer from collections import deque from reed.models.reward_model import StateActionRewardModel from reed.data.preference_dataset import PreferenceDataset from reed.data.preference_data_loader import PreferenceTripletEnsembleDataLoader from reed.data.preprocess_images import PreProcessInference
18,851
# # For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. # class PEBBLE: """ Train a reward model in conjunction with policy training following the PEBBLE algorithm from (Lee et al. 2021) """ def __init__(self, experiment_config: dictconfig.DictConfig): """ Args: experiment_config: contains the configuration for the experiment to be run. Access like a dictionry """ # track the experimental configuration self.experiment_config = experiment_config # create the logger to track policy learning progress self.logger = Logger( self.experiment_config.out_dir, save_tb=self.experiment_config.log_save_tb, log_frequency=self.experiment_config.log_frequency, agent=self.experiment_config.agent.name) # used to track where we are in training # total amount of feedback the reward model has solicited self.total_feedback = 0 # total amount of feedback given to the reward model self.labeled_feedback = 0 # policy train step self.step = 0 # we need to set the random seed for replication purposes
# # For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. # class PEBBLE: """ Train a reward model in conjunction with policy training following the PEBBLE algorithm from (Lee et al. 2021) """ def __init__(self, experiment_config: dictconfig.DictConfig): """ Args: experiment_config: contains the configuration for the experiment to be run. Access like a dictionry """ # track the experimental configuration self.experiment_config = experiment_config # create the logger to track policy learning progress self.logger = Logger( self.experiment_config.out_dir, save_tb=self.experiment_config.log_save_tb, log_frequency=self.experiment_config.log_frequency, agent=self.experiment_config.agent.name) # used to track where we are in training # total amount of feedback the reward model has solicited self.total_feedback = 0 # total amount of feedback given to the reward model self.labeled_feedback = 0 # policy train step self.step = 0 # we need to set the random seed for replication purposes
utils.set_seed_everywhere(self.experiment_config.seed)
0
2023-11-06 23:14:20+00:00
24k
alibaba/animate-anything
train.py
[ { "identifier": "VideoJsonDataset", "path": "utils/dataset.py", "snippet": "class VideoJsonDataset(Dataset):\n def __init__(\n self,\n tokenizer=None,\n width: int = 256,\n height: int = 256,\n n_sample_frames: int = 16,\n fps: int = 8,\n video_dir: str = \"./data\",\n video_json: str = \"\",\n fallback_prompt: str = \"\",\n use_bucketing: bool = False,\n cache_latents = False,\n motion_threshold = 50,\n **kwargs\n ):\n self.tokenizer = tokenizer\n self.use_bucketing = use_bucketing\n\n self.fallback_prompt = fallback_prompt\n self.video_dir = video_dir\n self.video_files = json.load(open(video_json))\n\n self.width = width\n self.height = height\n\n self.n_sample_frames = n_sample_frames\n self.fps = fps\n self.cache_latents = cache_latents\n self.motion_threshold = motion_threshold\n self.transform = T.Compose([\n #T.RandomResizedCrop(size=(height, width), scale=(0.8, 1.0), ratio=(width/height, width/height), antialias=False),\n T.Resize(min(height, width), antialias=False),\n T.CenterCrop([height, width])\n ])\n\n\n def get_frame_buckets(self, vr):\n _, h, w = vr[0].shape \n width, height = sensible_buckets(self.width, self.height, h, w)\n resize = T.transforms.Resize((height, width), antialias=True)\n\n return resize\n\n \n @staticmethod\n def __getname__(): return 'video_json'\n\n def __len__(self):\n return len(self.video_files)\n\n def __getitem__(self, index):\n mask = None\n try:\n item = self.video_files[index]\n video_path = os.path.join(self.video_dir, item['video'])\n cache_path = os.path.splitext(video_path)[0] + '.pt'\n if self.cache_latents and os.path.exists(cache_path):\n return torch.load(cache_path, map_location='cpu')\n\n prompt = item['caption']\n if self.fallback_prompt == \"<no_text>\":\n prompt = \"\"\n vr = decord.VideoReader(video_path)\n video = get_frame_batch(self.n_sample_frames, self.fps, vr, self.transform)\n except Exception as err:\n print(\"read video error\", err, video_path)\n return self.__getitem__(index+1)\n prompt_ids = get_prompt_ids(prompt, self.tokenizer)\n\n example = {\n \"pixel_values\": normalize_input(video), \n \"prompt_ids\": prompt_ids, \n \"text_prompt\": prompt, \n 'cache_path': cache_path,\n 'dataset': self.__getname__()\n }\n mask = get_moved_area_mask(video.permute([0,2,3,1]).numpy())\n example['motion'] = calculate_motion_score(video.permute([0,2,3,1]).numpy())\n if example['motion'] < self.motion_threshold:\n return self.__getitem__(random.randint(0, len(self)-1))\n return example" }, { "identifier": "SingleVideoDataset", "path": "utils/dataset.py", "snippet": "class SingleVideoDataset(Dataset):\n def __init__(\n self,\n tokenizer = None,\n width: int = 256,\n height: int = 256,\n n_sample_frames: int = 4,\n frame_step: int = 1,\n single_video_path: str = \"\",\n single_video_prompt: str = \"\",\n use_caption: bool = False,\n use_bucketing: bool = False,\n **kwargs\n ):\n self.tokenizer = tokenizer\n self.use_bucketing = use_bucketing\n self.frames = []\n self.index = 1\n\n self.vid_types = (\".mp4\", \".avi\", \".mov\", \".webm\", \".flv\", \".mjpeg\")\n self.n_sample_frames = n_sample_frames\n self.frame_step = frame_step\n\n self.single_video_path = single_video_path\n self.single_video_prompt = single_video_prompt\n\n self.width = width\n self.height = height\n def create_video_chunks(self):\n # Create a list of frames separated by sample frames\n # [(1,2,3), (4,5,6), ...]\n vr = decord.VideoReader(self.single_video_path)\n vr_range = range(1, len(vr), self.frame_step)\n\n self.frames = list(self.chunk(vr_range, self.n_sample_frames))\n\n # Delete any list that contains an out of range index.\n for i, inner_frame_nums in enumerate(self.frames):\n for frame_num in inner_frame_nums:\n if frame_num > len(vr):\n print(f\"Removing out of range index list at position: {i}...\")\n del self.frames[i]\n\n return self.frames\n\n def chunk(self, it, size):\n it = iter(it)\n return iter(lambda: tuple(islice(it, size)), ())\n\n def get_frame_batch(self, vr, resize=None):\n index = self.index\n frames = vr.get_batch(self.frames[self.index])\n video = rearrange(frames, \"f h w c -> f c h w\")\n\n if resize is not None: video = resize(video)\n return video\n\n def get_frame_buckets(self, vr):\n _, h, w = vr[0].shape \n width, height = sensible_buckets(self.width, self.height, h, w)\n resize = T.transforms.Resize((height, width), antialias=True)\n\n return resize\n \n def process_video_wrapper(self, vid_path):\n video, vr = process_video(\n vid_path,\n self.use_bucketing,\n self.width, \n self.height, \n self.get_frame_buckets, \n self.get_frame_batch\n )\n \n return video, vr \n\n def single_video_batch(self, index):\n train_data = self.single_video_path\n self.index = index\n\n if train_data.endswith(self.vid_types):\n video, _ = self.process_video_wrapper(train_data)\n\n prompt = self.single_video_prompt\n prompt_ids = get_prompt_ids(prompt, self.tokenizer)\n\n return video, prompt, prompt_ids\n else:\n raise ValueError(f\"Single video is not a video type. Types: {self.vid_types}\")\n \n @staticmethod\n def __getname__(): return 'single_video'\n\n def __len__(self):\n \n return len(self.create_video_chunks())\n\n def __getitem__(self, index):\n\n video, prompt, prompt_ids = self.single_video_batch(index)\n\n example = {\n \"pixel_values\": normalize_input(video),\n \"prompt_ids\": prompt_ids,\n \"text_prompt\": prompt,\n 'dataset': self.__getname__()\n }\n\n return example" }, { "identifier": "ImageDataset", "path": "utils/dataset.py", "snippet": "class ImageDataset(Dataset):\n \n def __init__(\n self,\n tokenizer = None,\n width: int = 256,\n height: int = 256,\n base_width: int = 256,\n base_height: int = 256,\n use_caption: bool = False,\n image_dir: str = '',\n single_img_prompt: str = '',\n use_bucketing: bool = False,\n fallback_prompt: str = '',\n **kwargs\n ):\n self.tokenizer = tokenizer\n self.img_types = (\".png\", \".jpg\", \".jpeg\", '.bmp')\n self.use_bucketing = use_bucketing\n #self.image_dir = self.get_images_list(image_dir)\n self.image_dir_path = image_dir\n self.image_dir = json.load(open(kwargs['image_json']))\n self.fallback_prompt = fallback_prompt\n\n self.use_caption = use_caption\n self.single_img_prompt = single_img_prompt\n\n self.width = width\n self.height = height\n\n def get_images_list(self, image_dir):\n if os.path.exists(image_dir):\n imgs = [x for x in os.listdir(image_dir) if x.endswith(self.img_types)]\n full_img_dir = []\n\n for img in imgs: \n full_img_dir.append(f\"{image_dir}/{img}\")\n\n return sorted(full_img_dir)\n\n return ['']\n\n def image_batch(self, index):\n train_data = self.image_dir[index]\n img, prompt = train_data['image'], train_data['caption']\n img = os.path.join(self.image_dir_path, img)\n try:\n img = torchvision.io.read_image(img, mode=torchvision.io.ImageReadMode.RGB)\n except:\n img = T.transforms.PILToTensor()(Image.open(img).convert(\"RGB\"))\n\n width = self.width\n height = self.height\n\n if self.use_bucketing:\n _, h, w = img.shape\n width, height = sensible_buckets(width, height, w, h)\n \n resize = T.transforms.Resize((height, width), antialias=True)\n\n img = resize(img) \n img = repeat(img, 'c h w -> f c h w', f=1)\n prompt_ids = get_prompt_ids(prompt, self.tokenizer)\n\n return img, prompt, prompt_ids\n\n @staticmethod\n def __getname__(): return 'image'\n \n def __len__(self):\n # Image directory\n return len(self.image_dir)\n\n def __getitem__(self, index):\n img, prompt, prompt_ids = self.image_batch(index)\n example = {\n \"pixel_values\": normalize_input(img),\n \"frames\": img,\n \"prompt_ids\": prompt_ids,\n \"text_prompt\": prompt, \n 'dataset': self.__getname__()\n }\n\n return example" }, { "identifier": "VideoFolderDataset", "path": "utils/dataset.py", "snippet": "class VideoFolderDataset(Dataset):\n def __init__(\n self,\n tokenizer=None,\n width: int = 256,\n height: int = 256,\n n_sample_frames: int = 16,\n fps: int = 8,\n path: str = \"./data\",\n fallback_prompt: str = \"\",\n use_bucketing: bool = False,\n **kwargs\n ):\n self.tokenizer = tokenizer\n self.use_bucketing = use_bucketing\n\n self.fallback_prompt = fallback_prompt\n\n self.video_files = glob(f\"{path}/*.mp4\")\n\n self.width = width\n self.height = height\n\n self.n_sample_frames = n_sample_frames\n self.fps = fps\n\n def get_frame_buckets(self, vr):\n _, h, w = vr[0].shape \n width, height = sensible_buckets(self.width, self.height, h, w)\n resize = T.transforms.Resize((height, width), antialias=True)\n\n return resize\n\n def get_frame_batch(self, vr, resize=None):\n n_sample_frames = self.n_sample_frames\n native_fps = vr.get_avg_fps()\n \n every_nth_frame = max(1, round(native_fps / self.fps))\n every_nth_frame = min(len(vr), every_nth_frame)\n \n effective_length = len(vr) // every_nth_frame\n if effective_length < n_sample_frames:\n n_sample_frames = effective_length\n raise RuntimeError(\"not enough frames\")\n\n effective_idx = random.randint(0, (effective_length - n_sample_frames))\n idxs = every_nth_frame * np.arange(effective_idx, effective_idx + n_sample_frames)\n\n video = vr.get_batch(idxs)\n video = rearrange(video, \"f h w c -> f c h w\")\n\n if resize is not None: video = resize(video)\n return video, vr\n \n def process_video_wrapper(self, vid_path):\n video, vr = process_video(\n vid_path,\n self.use_bucketing,\n self.width, \n self.height, \n self.get_frame_buckets, \n self.get_frame_batch\n )\n return video, vr\n \n @staticmethod\n def __getname__(): return 'folder'\n\n def __len__(self):\n return len(self.video_files)\n\n def __getitem__(self, index):\n try:\n video, _ = self.process_video_wrapper(self.video_files[index])\n except Exception as err:\n print(\"read video error\", self.video_files[index])\n video, _ = self.process_video_wrapper(self.video_files[index+1])\n\n if os.path.exists(self.video_files[index].replace(\".mp4\", \".txt\")):\n with open(self.video_files[index].replace(\".mp4\", \".txt\"), \"r\") as f:\n lines = f.readlines()\n prompt = random.choice(lines)\n else:\n prompt = self.fallback_prompt\n\n prompt_ids = get_prompt_ids(prompt, self.tokenizer)\n\n return {\"pixel_values\": normalize_input(video[0]), \"frames\": video[0],\n \"prompt_ids\": prompt_ids, \"text_prompt\": prompt, 'dataset': self.__getname__()}" }, { "identifier": "CachedDataset", "path": "utils/dataset.py", "snippet": "class CachedDataset(Dataset):\n def __init__(self,cache_dir: str = ''):\n self.cache_dir = cache_dir\n self.cached_data_list = self.get_files_list()\n\n def get_files_list(self):\n tensors_list = [f\"{self.cache_dir}/{x}\" for x in os.listdir(self.cache_dir) if x.endswith('.pt')]\n return sorted(tensors_list)\n\n def __len__(self):\n return len(self.cached_data_list)\n\n def __getitem__(self, index):\n cached_latent = torch.load(self.cached_data_list[index], map_location='cuda:0')\n return cached_latent" }, { "identifier": "VideoBLIPDataset", "path": "utils/dataset.py", "snippet": "class VideoBLIPDataset(Dataset):\n def __init__(\n self,\n tokenizer = None,\n width: int = 256,\n height: int = 256,\n n_sample_frames: int = 4,\n sample_start_idx: int = 1,\n fps: int = 1,\n json_path: str =\"\",\n json_data = None,\n vid_data_key: str = \"video_path\",\n preprocessed: bool = False,\n use_bucketing: bool = False,\n cache_latents: bool = False,\n motion_threshold = 50,\n **kwargs\n ):\n self.vid_types = (\".mp4\", \".avi\", \".mov\", \".webm\", \".flv\", \".mjpeg\")\n self.use_bucketing = use_bucketing\n self.tokenizer = tokenizer\n self.preprocessed = preprocessed\n \n self.vid_data_key = vid_data_key\n self.train_data = self.load_from_json(json_path, json_data)\n self.cache_latents = cache_latents\n self.motion_threshold = motion_threshold\n self.width = width\n self.height = height\n\n self.n_sample_frames = n_sample_frames\n self.sample_start_idx = sample_start_idx\n self.fps = fps\n self.transform = T.Compose([\n #T.RandomResizedCrop(size=(height, width), scale=(0.8, 1.0), ratio=(width/height, width/height), antialias=False)\n T.Resize(min(height, width), antialias=False),\n T.CenterCrop([height, width])\n ])\n\n def build_json(self, json_data):\n extended_data = []\n for data in json_data['data']:\n for nested_data in data['data']:\n self.build_json_dict(\n data, \n nested_data, \n extended_data\n )\n json_data = extended_data\n return json_data\n\n def build_json_dict(self, data, nested_data, extended_data):\n clip_path = nested_data['clip_path'] if 'clip_path' in nested_data else None\n \n extended_data.append({\n self.vid_data_key: data[self.vid_data_key],\n 'frame_index': nested_data['frame_index'],\n 'prompt': nested_data['prompt'],\n 'clip_path': clip_path\n })\n \n def load_from_json(self, path, json_data):\n try:\n with open(path) as jpath:\n print(f\"Loading JSON from {path}\")\n json_data = json.load(jpath)\n\n return self.build_json(json_data)\n\n except:\n import traceback\n traceback.print_exc()\n self.train_data = []\n print(\"Non-existant JSON path. Skipping.\")\n \n def validate_json(self, base_path, path):\n return os.path.exists(f\"{base_path}/{path}\")\n\n def get_frame_buckets(self, vr):\n _, h, w = vr[0].shape \n width, height = sensible_buckets(self.width, self.height, h, w)\n resize = T.transforms.Resize((height, width), antialias=True)\n\n return resize\n\n def train_data_batch(self, index):\n vid_data = self.train_data[index]\n # Get video prompt\n prompt = vid_data['prompt']\n # If we are training on individual clips.\n if 'clip_path' in self.train_data[index] and \\\n self.train_data[index]['clip_path'] is not None:\n clip_path = vid_data['clip_path']\n else:\n clip_path = vid_data[self.vid_data_key]\n # Get the frame of the current index.\n self.sample_start_idx = vid_data['frame_index']\n cache_path = os.path.splitext(clip_path)[0] + '.pt'\n if self.cache_latents and os.path.exists(cache_path):\n return torch.load(cache_path, map_location='cpu')\n\n vr = decord.VideoReader(clip_path)\n video = get_frame_batch(self.n_sample_frames, self.fps, vr, self.transform)\n prompt_ids = get_prompt_ids(prompt, self.tokenizer)\n example = {\n \"pixel_values\": normalize_input(video),\n \"prompt_ids\": prompt_ids,\n \"text_prompt\": prompt,\n 'dataset': self.__getname__(),\n 'cache_path': cache_path,\n }\n mask = get_moved_area_mask(video.permute([0,2,3,1]).numpy())\n example['mask'] = mask\n example['motion'] = calculate_motion_score(video.permute([0,2,3,1]).numpy())\n return example\n \n\n @staticmethod\n def __getname__(): return 'video_blip'\n\n def __len__(self):\n if self.train_data is not None:\n return len(self.train_data)\n else: \n return 0\n\n def __getitem__(self, index):\n example = self.train_data_batch(index)\n if example['motion'] < self.motion_threshold:\n return self.__getitem__(random.randint(0, len(self)-1))\n return example" }, { "identifier": "UNet3DConditionModel", "path": "models/unet_3d_condition_mask.py", "snippet": "class UNet3DConditionModel(ModelMixin, ConfigMixin):\n r\"\"\"\n UNet3DConditionModel is a conditional 2D UNet model that takes in a noisy sample, conditional state, and a timestep\n and returns sample shaped output.\n\n This model inherits from [`ModelMixin`]. Check the superclass documentation for the generic methods the library\n implements for all the models (such as downloading or saving, etc.)\n\n Parameters:\n sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):\n Height and width of input/output sample.\n in_channels (`int`, *optional*, defaults to 4): The number of channels in the input sample.\n out_channels (`int`, *optional*, defaults to 4): The number of channels in the output.\n down_block_types (`Tuple[str]`, *optional*, defaults to `(\"CrossAttnDownBlock2D\", \"CrossAttnDownBlock2D\", \"CrossAttnDownBlock2D\", \"DownBlock2D\")`):\n The tuple of downsample blocks to use.\n up_block_types (`Tuple[str]`, *optional*, defaults to `(\"UpBlock2D\", \"CrossAttnUpBlock2D\", \"CrossAttnUpBlock2D\", \"CrossAttnUpBlock2D\",)`):\n The tuple of upsample blocks to use.\n block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):\n The tuple of output channels for each block.\n layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.\n downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.\n mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.\n act_fn (`str`, *optional*, defaults to `\"silu\"`): The activation function to use.\n norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.\n If `None`, it will skip the normalization and activation layers in post-processing\n norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.\n cross_attention_dim (`int`, *optional*, defaults to 1280): The dimension of the cross attention features.\n attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.\n \"\"\"\n\n _supports_gradient_checkpointing = True\n\n @register_to_config\n def __init__(\n self,\n sample_size: Optional[int] = None,\n in_channels: int = 4,\n out_channels: int = 4,\n down_block_types: Tuple[str] = (\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"DownBlock3D\",\n ),\n up_block_types: Tuple[str] = (\"UpBlock3D\", \"CrossAttnUpBlock3D\", \"CrossAttnUpBlock3D\", \"CrossAttnUpBlock3D\"),\n block_out_channels: Tuple[int] = (320, 640, 1280, 1280),\n layers_per_block: int = 2,\n downsample_padding: int = 1,\n mid_block_scale_factor: float = 1,\n act_fn: str = \"silu\",\n norm_num_groups: Optional[int] = 32,\n norm_eps: float = 1e-5,\n cross_attention_dim: int = 1024,\n attention_head_dim: Union[int, Tuple[int]] = 64,\n motion_mask = False,\n motion_strength = False,\n ):\n super().__init__()\n self.motion_mask = motion_mask\n self.motion_strength = motion_strength\n print(f\"motion mask {self.motion_mask}, motion_strength {self.motion_strength}\")\n self.sample_size = sample_size\n self.gradient_checkpointing = False\n # Check inputs\n if len(down_block_types) != len(up_block_types):\n raise ValueError(\n f\"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}.\"\n )\n\n if len(block_out_channels) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}.\"\n )\n\n if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}.\"\n )\n\n # input\n conv_in_kernel = 3\n conv_out_kernel = 3\n conv_in_padding = (conv_in_kernel - 1) // 2\n self.conv_in = nn.Conv2d(\n in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding\n )\n self.conv_in2 = nn.Conv2d(\n 5, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding\n )\n\n # time\n time_embed_dim = block_out_channels[0] * 4\n self.time_proj = Timesteps(block_out_channels[0], True, 0)\n timestep_input_dim = block_out_channels[0]\n\n self.time_embedding = TimestepEmbedding(\n timestep_input_dim,\n time_embed_dim,\n act_fn=act_fn,\n cond_proj_dim=block_out_channels[0],\n )\n\n self.motion_proj = Timesteps(block_out_channels[0], True, 0)\n self.motion_embedding = nn.Sequential(\n nn.Linear(timestep_input_dim, time_embed_dim), nn.SiLU(),\n nn.Linear(time_embed_dim, time_embed_dim))\n nn.init.zeros_(self.motion_embedding[-1].weight)\n nn.init.zeros_(self.motion_embedding[-1].bias)\n\n self.transformer_in = TransformerTemporalModel(\n num_attention_heads=8,\n attention_head_dim=attention_head_dim,\n in_channels=block_out_channels[0],\n num_layers=1,\n )\n\n # class embedding\n self.down_blocks = nn.ModuleList([])\n self.up_blocks = nn.ModuleList([])\n\n if isinstance(attention_head_dim, int):\n attention_head_dim = (attention_head_dim,) * len(down_block_types)\n\n # down\n output_channel = block_out_channels[0]\n for i, down_block_type in enumerate(down_block_types):\n input_channel = output_channel\n output_channel = block_out_channels[i]\n is_final_block = i == len(block_out_channels) - 1\n\n down_block = get_down_block(\n down_block_type,\n num_layers=layers_per_block,\n in_channels=input_channel,\n out_channels=output_channel,\n temb_channels=time_embed_dim,\n add_downsample=not is_final_block,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[i],\n downsample_padding=downsample_padding,\n dual_cross_attention=False,\n )\n self.down_blocks.append(down_block)\n\n # mid\n self.mid_block = UNetMidBlock3DCrossAttn(\n in_channels=block_out_channels[-1],\n temb_channels=time_embed_dim,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n output_scale_factor=mid_block_scale_factor,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[-1],\n resnet_groups=norm_num_groups,\n dual_cross_attention=False,\n )\n # count how many layers upsample the images\n self.num_upsamplers = 0\n\n # up\n reversed_block_out_channels = list(reversed(block_out_channels))\n reversed_attention_head_dim = list(reversed(attention_head_dim))\n\n output_channel = reversed_block_out_channels[0]\n for i, up_block_type in enumerate(up_block_types):\n is_final_block = i == len(block_out_channels) - 1\n\n prev_output_channel = output_channel\n output_channel = reversed_block_out_channels[i]\n input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]\n\n # add upsample block for all BUT final layer\n if not is_final_block:\n add_upsample = True\n self.num_upsamplers += 1\n else:\n add_upsample = False\n\n up_block = get_up_block(\n up_block_type,\n num_layers=layers_per_block + 1,\n in_channels=input_channel,\n out_channels=output_channel,\n prev_output_channel=prev_output_channel,\n temb_channels=time_embed_dim,\n add_upsample=add_upsample,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=reversed_attention_head_dim[i],\n dual_cross_attention=False,\n )\n self.up_blocks.append(up_block)\n prev_output_channel = output_channel\n\n # out\n if norm_num_groups is not None:\n self.conv_norm_out = nn.GroupNorm(\n num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps\n )\n self.conv_act = nn.SiLU()\n else:\n self.conv_norm_out = None\n self.conv_act = None\n\n conv_out_padding = (conv_out_kernel - 1) // 2\n self.conv_out = nn.Conv2d(\n block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding\n )\n\n def set_attention_slice(self, slice_size):\n r\"\"\"\n Enable sliced attention computation.\n\n When this option is enabled, the attention module will split the input tensor in slices, to compute attention\n in several steps. This is useful to save some memory in exchange for a small speed decrease.\n\n Args:\n slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `\"auto\"`):\n When `\"auto\"`, halves the input to the attention heads, so attention will be computed in two steps. If\n `\"max\"`, maxium amount of memory will be saved by running only one slice at a time. If a number is\n provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`\n must be a multiple of `slice_size`.\n \"\"\"\n sliceable_head_dims = []\n\n def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):\n if hasattr(module, \"set_attention_slice\"):\n sliceable_head_dims.append(module.sliceable_head_dim)\n\n for child in module.children():\n fn_recursive_retrieve_slicable_dims(child)\n\n # retrieve number of attention layers\n for module in self.children():\n fn_recursive_retrieve_slicable_dims(module)\n\n num_slicable_layers = len(sliceable_head_dims)\n\n if slice_size == \"auto\":\n # half the attention head size is usually a good trade-off between\n # speed and memory\n slice_size = [dim // 2 for dim in sliceable_head_dims]\n elif slice_size == \"max\":\n # make smallest slice possible\n slice_size = num_slicable_layers * [1]\n\n slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size\n\n if len(slice_size) != len(sliceable_head_dims):\n raise ValueError(\n f\"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different\"\n f\" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}.\"\n )\n\n for i in range(len(slice_size)):\n size = slice_size[i]\n dim = sliceable_head_dims[i]\n if size is not None and size > dim:\n raise ValueError(f\"size {size} has to be smaller or equal to {dim}.\")\n\n # Recursively walk through all the children.\n # Any children which exposes the set_attention_slice method\n # gets the message\n def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):\n if hasattr(module, \"set_attention_slice\"):\n module.set_attention_slice(slice_size.pop())\n\n for child in module.children():\n fn_recursive_set_attention_slice(child, slice_size)\n\n reversed_slice_size = list(reversed(slice_size))\n for module in self.children():\n fn_recursive_set_attention_slice(module, reversed_slice_size)\n\n def _set_gradient_checkpointing(self, value=False):\n self.gradient_checkpointing = value\n self.mid_block.gradient_checkpointing = value\n for module in self.down_blocks + self.up_blocks:\n if isinstance(module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D)):\n module.gradient_checkpointing = value \n \n def forward(\n self,\n sample: torch.FloatTensor,\n timestep: Union[torch.Tensor, float, int],\n encoder_hidden_states: torch.Tensor,\n condition_latent: torch.Tensor,\n mask: torch.Tensor,\n class_labels: Optional[torch.Tensor] = None,\n timestep_cond: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,\n mid_block_additional_residual: Optional[torch.Tensor] = None,\n motion = None,\n return_dict: bool = True,\n ) -> Union[UNet3DConditionOutput, Tuple]:\n r\"\"\"\n Args:\n sample (`torch.FloatTensor`): (batch, num_frames, channel, height, width) noisy inputs tensor\n timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps\n encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states\n return_dict (`bool`, *optional*, defaults to `True`):\n Whether or not to return a [`models.unet_2d_condition.UNet3DConditionOutput`] instead of a plain tuple.\n cross_attention_kwargs (`dict`, *optional*):\n A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under\n `self.processor` in\n [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).\n\n Returns:\n [`~models.unet_2d_condition.UNet3DConditionOutput`] or `tuple`:\n [`~models.unet_2d_condition.UNet3DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When\n returning a tuple, the first element is the sample tensor.\n \"\"\"\n # By default samples have to be AT least a multiple of the overall upsampling factor.\n # The overall upsampling factor is equal to 2 ** (# num of upsampling layears).\n # However, the upsampling interpolation output size can be forced to fit any upsampling size\n # on the fly if necessary.\n default_overall_up_factor = 2**self.num_upsamplers\n sample = torch.cat([condition_latent, sample], dim=2)\n # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`\n forward_upsample_size = False\n upsample_size = None\n\n if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):\n logger.info(\"Forward upsample size to force interpolation output size.\")\n forward_upsample_size = True\n\n # prepare attention_mask\n if attention_mask is not None:\n attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0\n attention_mask = attention_mask.unsqueeze(1)\n\n # 1. time\n timesteps = timestep\n if not torch.is_tensor(timesteps):\n # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can\n # This would be a good case for the `match` statement (Python 3.10+)\n is_mps = sample.device.type == \"mps\"\n if isinstance(timestep, float):\n dtype = torch.float32 if is_mps else torch.float64\n else:\n dtype = torch.int32 if is_mps else torch.int64\n timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)\n elif len(timesteps.shape) == 0:\n timesteps = timesteps[None].to(sample.device)\n\n # broadcast to batch dimension in a way that's compatible with ONNX/Core ML\n num_frames = sample.shape[2]\n timesteps = timesteps.expand(sample.shape[0])\n\n t_emb = self.time_proj(timesteps)\n\n # timesteps does not contain any weights and will always return f32 tensors\n # but time_embedding might actually be running in fp16. so we need to cast here.\n # there might be better ways to encapsulate this.\n t_emb = t_emb.to(dtype=self.dtype)\n if self.motion_strength and motion is not None:\n timestep_cond = self.motion_proj(motion).to(dtype=self.dtype)\n emb = self.time_embedding(t_emb, timestep_cond)\n #emb += self.motion_embedding(m_emb)\n else:\n emb = self.time_embedding(t_emb, timestep_cond)\n emb = emb.repeat_interleave(repeats=num_frames, dim=0)\n encoder_hidden_states = encoder_hidden_states.repeat_interleave(repeats=num_frames, dim=0)\n\n # 2. pre-process\n if self.motion_mask and mask is not None:\n mask = repeat(mask , 'b 1 1 h w -> (t b) 1 f h w', t=sample.shape[0]//mask.shape[0], f=sample.shape[2])\n sample = torch.cat([mask, sample], dim=1)\n sample = sample.permute(0, 2, 1, 3, 4).reshape((sample.shape[0] * num_frames, -1) + sample.shape[3:])\n sample = self.conv_in2(sample)\n else:\n sample = sample.permute(0, 2, 1, 3, 4).reshape((sample.shape[0] * num_frames, -1) + sample.shape[3:])\n sample = self.conv_in(sample)\n\n if num_frames > 1:\n if self.gradient_checkpointing:\n sample = transformer_g_c(self.transformer_in, sample, num_frames)\n else:\n sample = self.transformer_in(sample, num_frames=num_frames).sample\n\n # 3. down\n down_block_res_samples = (sample,)\n for i, downsample_block in enumerate(self.down_blocks):\n if hasattr(downsample_block, \"has_cross_attention\") and downsample_block.has_cross_attention:\n sample, res_samples = downsample_block(\n hidden_states=sample,\n temb=emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n num_frames=num_frames,\n cross_attention_kwargs=cross_attention_kwargs,\n )\n else:\n sample, res_samples = downsample_block(hidden_states=sample, temb=emb, num_frames=num_frames)\n \n down_block_res_samples += res_samples\n\n if down_block_additional_residuals is not None:\n new_down_block_res_samples = ()\n\n for down_block_res_sample, down_block_additional_residual in zip(\n down_block_res_samples, down_block_additional_residuals\n ):\n down_block_res_sample = down_block_res_sample + down_block_additional_residual\n new_down_block_res_samples += (down_block_res_sample,)\n\n down_block_res_samples = new_down_block_res_samples\n\n # 4. mid\n if self.mid_block is not None:\n sample = self.mid_block(\n sample,\n emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n num_frames=num_frames,\n cross_attention_kwargs=cross_attention_kwargs,\n )\n\n if mid_block_additional_residual is not None:\n sample = sample + mid_block_additional_residual\n\n # 5. up\n for i, upsample_block in enumerate(self.up_blocks):\n is_final_block = i == len(self.up_blocks) - 1\n\n res_samples = down_block_res_samples[-len(upsample_block.resnets) :]\n down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]\n\n # if we have not reached the final block and need to forward the\n # upsample size, we do it here\n if not is_final_block and forward_upsample_size:\n upsample_size = down_block_res_samples[-1].shape[2:]\n\n if hasattr(upsample_block, \"has_cross_attention\") and upsample_block.has_cross_attention:\n sample = upsample_block(\n hidden_states=sample,\n temb=emb,\n res_hidden_states_tuple=res_samples,\n encoder_hidden_states=encoder_hidden_states,\n upsample_size=upsample_size,\n attention_mask=attention_mask,\n num_frames=num_frames,\n cross_attention_kwargs=cross_attention_kwargs,\n )\n else:\n sample = upsample_block(\n hidden_states=sample,\n temb=emb,\n res_hidden_states_tuple=res_samples,\n upsample_size=upsample_size,\n num_frames=num_frames,\n )\n\n # 6. post-process\n if self.conv_norm_out:\n sample = self.conv_norm_out(sample)\n sample = self.conv_act(sample)\n\n sample = self.conv_out(sample)\n\n # reshape to (batch, channel, framerate, width, height)\n sample = sample[None, :].reshape((-1, num_frames) + sample.shape[1:]).permute(0, 2, 1, 3, 4)\n sample = sample[:,:,1:]\n if not return_dict:\n return (sample,)\n\n return UNet3DConditionOutput(sample=sample)" }, { "identifier": "LatentToVideoPipeline", "path": "models/pipeline.py", "snippet": "class LatentToVideoPipeline(TextToVideoSDPipeline):\n @torch.no_grad()\n def __call__(\n self,\n prompt = None,\n height= None,\n width= None,\n num_frames: int = 16,\n num_inference_steps: int = 50,\n guidance_scale= 9.0,\n negative_prompt= None,\n eta: float = 0.0,\n generator= None,\n latents= None,\n prompt_embeds= None,\n negative_prompt_embeds= None,\n output_type= \"np\",\n return_dict: bool = True,\n callback= None,\n callback_steps: int = 1,\n cross_attention_kwargs= None,\n condition_latent=None,\n mask=None,\n timesteps=None,\n motion=None,\n ):\n r\"\"\"\n Function invoked when calling the pipeline for generation.\n\n Args:\n prompt (`str` or `List[str]`, *optional*):\n The prompt or prompts to guide the video generation. If not defined, one has to pass `prompt_embeds`.\n instead.\n height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):\n The height in pixels of the generated video.\n width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):\n The width in pixels of the generated video.\n num_frames (`int`, *optional*, defaults to 16):\n The number of video frames that are generated. Defaults to 16 frames which at 8 frames per seconds\n amounts to 2 seconds of video.\n num_inference_steps (`int`, *optional*, defaults to 50):\n The number of denoising steps. More denoising steps usually lead to a higher quality videos at the\n expense of slower inference.\n guidance_scale (`float`, *optional*, defaults to 7.5):\n Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).\n `guidance_scale` is defined as `w` of equation 2. of [Imagen\n Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >\n 1`. Higher guidance scale encourages to generate videos that are closely linked to the text `prompt`,\n usually at the expense of lower video quality.\n negative_prompt (`str` or `List[str]`, *optional*):\n The prompt or prompts not to guide the video generation. If not defined, one has to pass\n `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is\n less than `1`).\n eta (`float`, *optional*, defaults to 0.0):\n Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to\n [`schedulers.DDIMScheduler`], will be ignored for others.\n generator (`torch.Generator` or `List[torch.Generator]`, *optional*):\n One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)\n to make generation deterministic.\n latents (`torch.FloatTensor`, *optional*):\n Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for video\n generation. Can be used to tweak the same generation with different prompts. If not provided, a latents\n tensor will ge generated by sampling using the supplied random `generator`. Latents should be of shape\n `(batch_size, num_channel, num_frames, height, width)`.\n prompt_embeds (`torch.FloatTensor`, *optional*):\n Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not\n provided, text embeddings will be generated from `prompt` input argument.\n negative_prompt_embeds (`torch.FloatTensor`, *optional*):\n Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt\n weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input\n argument.\n output_type (`str`, *optional*, defaults to `\"np\"`):\n The output format of the generate video. Choose between `torch.FloatTensor` or `np.array`.\n return_dict (`bool`, *optional*, defaults to `True`):\n Whether or not to return a [`~pipelines.stable_diffusion.TextToVideoSDPipelineOutput`] instead of a\n plain tuple.\n callback (`Callable`, *optional*):\n A function that will be called every `callback_steps` steps during inference. The function will be\n called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.\n callback_steps (`int`, *optional*, defaults to 1):\n The frequency at which the `callback` function will be called. If not specified, the callback will be\n called at every step.\n cross_attention_kwargs (`dict`, *optional*):\n A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under\n `self.processor` in\n [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).\n\n Examples:\n\n Returns:\n [`~pipelines.stable_diffusion.TextToVideoSDPipelineOutput`] or `tuple`:\n [`~pipelines.stable_diffusion.TextToVideoSDPipelineOutput`] if `return_dict` is True, otherwise a `tuple.\n When returning a tuple, the first element is a list with the generated frames.\n \"\"\"\n # 0. Default height and width to unet\n height = height or self.unet.config.sample_size * self.vae_scale_factor\n width = width or self.unet.config.sample_size * self.vae_scale_factor\n\n num_images_per_prompt = 1\n\n # 1. Check inputs. Raise error if not correct\n self.check_inputs(\n prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds\n )\n\n # 2. Define call parameters\n if prompt is not None and isinstance(prompt, str):\n batch_size = 1\n elif prompt is not None and isinstance(prompt, list):\n batch_size = len(prompt)\n else:\n batch_size = prompt_embeds.shape[0]\n\n #device = self._execution_device\n device = latents.device\n # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)\n # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`\n # corresponds to doing no classifier free guidance.\n do_classifier_free_guidance = guidance_scale > 1.0\n\n # 3. Encode input prompt\n text_encoder_lora_scale = (\n cross_attention_kwargs.get(\"scale\", None) if cross_attention_kwargs is not None else None\n )\n prompt_embeds = self._encode_prompt(\n prompt,\n device,\n num_images_per_prompt,\n do_classifier_free_guidance,\n negative_prompt,\n prompt_embeds=prompt_embeds,\n negative_prompt_embeds=negative_prompt_embeds,\n lora_scale=text_encoder_lora_scale,\n )\n\n # 4. Prepare timesteps\n self.scheduler.set_timesteps(num_inference_steps, device=device)\n if timesteps is None:\n timesteps = self.scheduler.timesteps\n else:\n num_inference_steps = len(timesteps)\n # 5. Prepare latent variables. do nothing\n\n # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline\n extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)\n\n # 7. Denoising loop\n num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order\n uncondition_latent = condition_latent\n condition_latent = torch.cat([uncondition_latent, condition_latent]) if do_classifier_free_guidance else condition_latent \n with self.progress_bar(total=num_inference_steps) as progress_bar:\n for i, t in enumerate(timesteps):\n # expand the latents if we are doing classifier free guidance\n latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents\n latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)\n if motion is not None:\n motion = torch.tensor(motion, device=device)\n noise_pred = self.unet(\n latent_model_input,\n t,\n encoder_hidden_states=prompt_embeds,\n cross_attention_kwargs=cross_attention_kwargs,\n condition_latent=condition_latent,\n mask=mask,\n motion=motion\n ).sample\n # perform guidance\n if do_classifier_free_guidance:\n noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)\n noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)\n\n # reshape latents\n bsz, channel, frames, width, height = latents.shape\n latents = latents.permute(0, 2, 1, 3, 4).reshape(bsz * frames, channel, width, height)\n noise_pred = noise_pred.permute(0, 2, 1, 3, 4).reshape(bsz * frames, channel, width, height)\n\n # compute the previous noisy sample x_t -> x_t-1\n latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample\n\n # reshape latents back\n latents = latents[None, :].reshape(bsz, frames, channel, width, height).permute(0, 2, 1, 3, 4)\n\n # call the callback, if provided\n if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):\n progress_bar.update()\n if callback is not None and i % callback_steps == 0:\n callback(i, t, latents)\n\n video_tensor = self.decode_latents(latents)\n\n if output_type == \"pt\":\n video = video_tensor\n else:\n video = tensor2vid(video_tensor)\n\n # Offload last model to CPU\n if hasattr(self, \"final_offload_hook\") and self.final_offload_hook is not None:\n self.final_offload_hook.offload()\n\n if not return_dict:\n return (video, latents)\n\n return TextToVideoSDPipelineOutput(frames=video)" }, { "identifier": "LoraHandler", "path": "utils/lora_handler.py", "snippet": "class LoraHandler(object):\n def __init__(\n self, \n version: LORA_VERSIONS = LoraVersions.cloneofsimo, \n use_unet_lora: bool = False,\n use_text_lora: bool = False,\n save_for_webui: bool = False,\n only_for_webui: bool = False,\n lora_bias: str = 'none',\n unet_replace_modules: list = ['UNet3DConditionModel'],\n text_encoder_replace_modules: list = ['CLIPEncoderLayer']\n ):\n self.version = version\n self.lora_loader = self.get_lora_func(func_type=LoraFuncTypes.loader)\n self.lora_injector = self.get_lora_func(func_type=LoraFuncTypes.injector)\n self.lora_bias = lora_bias\n self.use_unet_lora = use_unet_lora\n self.use_text_lora = use_text_lora\n self.save_for_webui = save_for_webui\n self.only_for_webui = only_for_webui\n self.unet_replace_modules = unet_replace_modules\n self.text_encoder_replace_modules = text_encoder_replace_modules\n self.use_lora = any([use_text_lora, use_unet_lora])\n\n if self.use_lora:\n print(f\"Using LoRA Version: {self.version}\")\n\n def is_cloneofsimo_lora(self):\n return self.version == LoraVersions.cloneofsimo\n\n def is_stable_lora(self):\n return self.version == LoraVersions.stable_lora\n\n def get_lora_func(self, func_type: LORA_FUNC_TYPES = LoraFuncTypes.loader):\n\n if self.is_cloneofsimo_lora():\n\n if func_type == LoraFuncTypes.loader:\n return monkeypatch_or_replace_lora_extended\n\n if func_type == LoraFuncTypes.injector:\n return inject_trainable_lora_extended\n\n if self.is_stable_lora():\n\n if func_type == LoraFuncTypes.loader:\n return load_lora\n\n if func_type == LoraFuncTypes.injector:\n return add_lora_to\n \n assert \"LoRA Version does not exist.\"\n\n def check_lora_ext(self, lora_file: str):\n return lora_file.endswith(tuple(LORA_FILE_TYPES))\n\n def get_lora_file_path(\n self, \n lora_path: str, \n model: Union[UNet3DConditionModel, CLIPTextModel]\n ):\n if os.path.exists(lora_path):\n lora_filenames = [fns for fns in os.listdir(lora_path)]\n is_lora = self.check_lora_ext(lora_path)\n\n is_unet = isinstance(model, UNet3DConditionModel)\n is_text = isinstance(model, CLIPTextModel)\n idx = 0 if is_unet else 1\n\n base_name = FILE_BASENAMES[idx]\n \n for lora_filename in lora_filenames:\n is_lora = self.check_lora_ext(lora_filename)\n if not is_lora:\n continue\n \n if base_name in lora_filename:\n return os.path.join(lora_path, lora_filename)\n\n return None\n\n def handle_lora_load(self, file_name:str, lora_loader_args: dict = None):\n self.lora_loader(**lora_loader_args)\n print(f\"Successfully loaded LoRA from: {file_name}\")\n \n def load_lora(self, model, lora_path: str = '', lora_loader_args: dict = None,):\n try:\n lora_file = self.get_lora_file_path(lora_path, model)\n\n if lora_file is not None:\n lora_loader_args.update({\"lora_path\": lora_file})\n self.handle_lora_load(lora_file, lora_loader_args)\n\n else:\n print(f\"Could not load LoRAs for {model.__class__.__name__}. Injecting new ones instead...\")\n\n except Exception as e:\n print(f\"An error occured while loading a LoRA file: {e}\")\n \n def get_lora_func_args(self, lora_path, use_lora, model, replace_modules, r, dropout, lora_bias):\n return_dict = lora_args.copy()\n \n if self.is_cloneofsimo_lora():\n return_dict = filter_dict(return_dict, keys=CLONE_OF_SIMO_KEYS)\n return_dict.update({\n \"model\": model,\n \"loras\": self.get_lora_file_path(lora_path, model),\n \"target_replace_module\": replace_modules,\n \"r\": r\n })\n\n if self.is_stable_lora():\n KEYS = ['model', 'lora_path']\n return_dict = filter_dict(return_dict, KEYS)\n \n return_dict.update({'model': model, 'lora_path': lora_path})\n\n return return_dict\n\n def do_lora_injection(\n self, \n model, \n replace_modules, \n bias='none',\n dropout=0,\n r=4,\n lora_loader_args=None,\n ): \n REPLACE_MODULES = replace_modules\n\n params = None\n negation = None\n is_injection_hybrid = False\n \n if self.is_cloneofsimo_lora():\n is_injection_hybrid = True\n injector_args = lora_loader_args\n\n params, negation = self.lora_injector(**injector_args) \n for _up, _down in extract_lora_ups_down(\n model, \n target_replace_module=REPLACE_MODULES):\n\n if all(x is not None for x in [_up, _down]):\n print(f\"Lora successfully injected into {model.__class__.__name__}.\")\n\n break\n\n return params, negation, is_injection_hybrid\n\n if self.is_stable_lora():\n injector_args = lora_args.copy()\n injector_args = filter_dict(injector_args, keys=STABLE_LORA_KEYS)\n\n SEARCH_CLASS = [torch.nn.Linear, torch.nn.Conv2d, torch.nn.Conv3d, torch.nn.Embedding]\n\n injector_args.update({\n \"model\": model,\n \"target_module\": REPLACE_MODULES,\n \"search_class\": SEARCH_CLASS,\n \"r\": r,\n \"dropout\": dropout,\n \"lora_bias\": self.lora_bias\n })\n\n activator = self.lora_injector(**injector_args)\n activator()\n\n return params, negation, is_injection_hybrid\n\n def add_lora_to_model(self, use_lora, model, replace_modules, dropout=0.0, lora_path='', r=16):\n\n params = None\n negation = None\n\n lora_loader_args = self.get_lora_func_args(\n lora_path,\n use_lora,\n model,\n replace_modules,\n r,\n dropout,\n self.lora_bias\n )\n if use_lora:\n params, negation, is_injection_hybrid = self.do_lora_injection(\n model, \n replace_modules, \n bias=self.lora_bias,\n lora_loader_args=lora_loader_args,\n dropout=dropout,\n r=r\n )\n\n if not is_injection_hybrid:\n self.load_lora(model, lora_path=lora_path, lora_loader_args=lora_loader_args)\n \n params = model if params is None else params\n return params, negation\n \n\n def deactivate_lora_train(self, models, deactivate=True):\n \"\"\"\n Usage: Use before and after sampling previews.\n Currently only available for Stable LoRA.\n \"\"\"\n if self.is_stable_lora():\n set_mode_group(models, not deactivate)\n\n def save_cloneofsimo_lora(self, model, save_path, step):\n \n def save_lora(model, name, condition, replace_modules, step, save_path): \n if condition and replace_modules is not None:\n save_path = f\"{save_path}/{step}_{name}.pt\"\n save_lora_weight(model, save_path, replace_modules)\n\n save_lora(\n model.unet, \n FILE_BASENAMES[0], \n self.use_unet_lora, \n self.unet_replace_modules, \n step,\n save_path, \n )\n save_lora(\n model.text_encoder, \n FILE_BASENAMES[1], \n self.use_text_lora, \n self.text_encoder_replace_modules, \n step, \n save_path\n )\n\n train_patch_pipe(model, self.use_unet_lora, self.use_text_lora)\n\n def save_stable_lora(\n self, \n model, \n step, \n name, \n save_path = '', \n save_for_webui=False,\n only_for_webui=False\n ):\n import uuid\n\n save_filename = f\"{step}_{name}\"\n lora_metadata = metadata = {\n \"stable_lora_text_to_video\": \"v1\", \n \"lora_name\": name + \"_\" + uuid.uuid4().hex.lower()[:5]\n }\n save_lora(\n unet=model.unet,\n text_encoder=model.text_encoder,\n save_text_weights=self.use_text_lora,\n output_dir=save_path,\n lora_filename=save_filename,\n lora_bias=self.lora_bias,\n save_for_webui=self.save_for_webui,\n only_webui=self.only_for_webui,\n metadata=lora_metadata,\n unet_dict_converter=convert_unet_state_dict,\n text_dict_converter=convert_text_enc_state_dict_v20\n )\n\n def save_lora_weights(self, model: None, save_path: str ='',step: str = ''):\n save_path = f\"{save_path}/lora\"\n os.makedirs(save_path, exist_ok=True)\n\n if self.is_cloneofsimo_lora():\n if any([self.save_for_webui, self.only_for_webui]):\n warnings.warn(\n \"\"\"\n You have 'save_for_webui' enabled, but are using cloneofsimo's LoRA implemention.\n Only 'stable_lora' is supported for saving to a compatible webui file.\n \"\"\"\n )\n self.save_cloneofsimo_lora(model, save_path, step)\n\n if self.is_stable_lora():\n name = 'lora_text_to_video'\n self.save_stable_lora(model, step, name, save_path)" }, { "identifier": "LORA_VERSIONS", "path": "utils/lora_handler.py", "snippet": "LORA_VERSIONS = [LoraVersions.stable_lora, LoraVersions.cloneofsimo]" }, { "identifier": "read_mask", "path": "utils/common.py", "snippet": "def read_mask(json_path, label=[\"mask\"]):\n j = json.load(open(json_path)) \n if type(label) != list:\n labels = [label]\n height = j['imageHeight']\n width = j['imageWidth']\n mask = np.zeros([height, width], dtype=np.uint8)\n for shape in j['shapes']:\n if shape['label'] in label:\n x1, y1 = shape['points'][0]\n x2, y2 = shape['points'][1]\n mask[int(y1):int(y2), int(x1):int(x2)] = 255\n return mask" }, { "identifier": "generate_random_mask", "path": "utils/common.py", "snippet": "def generate_random_mask(image):\n # Create a blank mask with the same size as the image\n b, c , h, w = image.shape\n mask = np.zeros([b, h, w], dtype=np.uint8)\n \n # Generate random coordinates for the mask\n num_points = np.random.randint(3, 10) # Randomly choose the number of points to generate\n points = np.random.randint(0, min(h, w), size=(num_points, 2)) # Randomly generate the points\n # Draw a filled polygon on the mask using the random points\n for i in range(b):\n width = random.randint(w//4, w)\n height = random.randint(h//4, h)\n x = random.randint(0, w-width)\n y = random.randint(0, h-height)\n points=np.array([[x, y], [x+width, y], [x+width, y+height], [x, y+height]])\n mask[i] = cv2.fillPoly(mask[i], [points], 255)\n \n # Apply the mask to the image\n #masked_image = cv2.bitwise_and(image, image, mask=mask)\n return mask " }, { "identifier": "slerp", "path": "utils/common.py", "snippet": "def slerp(z1, z2, alpha):\n theta = torch.acos(torch.sum(z1 * z2) / (torch.norm(z1) * torch.norm(z2)))\n return (\n torch.sin((1 - alpha) * theta) / torch.sin(theta) * z1\n + torch.sin(alpha * theta) / torch.sin(theta) * z2\n )" }, { "identifier": "calculate_motion_score", "path": "utils/common.py", "snippet": "def calculate_motion_score(frame_imgs, calculate_edges=False, color=\"RGB\") -> float:\n # Convert image into HSV colorspace.\n _last_frame = None\n\n _weights = [1.0, 1.0, 1.0, 0.0]\n score = 0\n for frame_img in frame_imgs:\n if color == \"RGB\":\n hue, sat, lum = cv2.split(cv2.cvtColor(frame_img, cv2.COLOR_RGB2HSV))\n else:\n hue, sat, lum = cv2.split(cv2.cvtColor(frame_img, cv2.COLOR_BGR2HSV))\n # Performance: Only calculate edges if we have to.\n edges = _detect_edges(lum) if calculate_edges else None\n if _last_frame == None:\n _last_frame = (hue, sat, lum, edges)\n continue\n\n score_components = [\n _mean_pixel_distance(hue, _last_frame[0]),\n _mean_pixel_distance(sat, _last_frame[1]),\n _mean_pixel_distance(lum, _last_frame[2]),\n 0.0 if edges is None else _mean_pixel_distance(edges, _last_frame[3]),\n ]\n\n frame_score: float = (\n sum(component * weight for (component, weight) in zip(score_components, _weights))\n / sum(abs(weight) for weight in _weights))\n score += frame_score\n _last_frame = (hue, sat, lum, edges)\n\n return round(score/(len(frame_imgs)-1) * 10)" }, { "identifier": "read_video", "path": "utils/common.py", "snippet": "def read_video(video_path, frame_number=-1):\n # Open the video file\n cap = cv2.VideoCapture(video_path)\n count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) \n if frame_number == -1:\n frame_number = count\n else:\n frame_number = min(frame_number, count)\n frames = []\n for i in range(frame_number):\n ret, ref_frame = cap.read()\n ref_frame = cv2.cvtColor(ref_frame, cv2.COLOR_BGR2RGB)\n if not ret:\n raise ValueError(\"Failed to read video file\")\n frames.append(ref_frame)\n return frames" }, { "identifier": "calculate_motion_precision", "path": "utils/common.py", "snippet": "def calculate_motion_precision(frames, mask):\n moved_mask = get_moved_area_mask(frames, move_th=20, th=0)\n moved = moved_mask == 255\n gt = mask == 255\n precision = np.sum(moved & gt) / np.sum(moved)\n return precision" }, { "identifier": "calculate_latent_motion_score", "path": "utils/common.py", "snippet": "def calculate_latent_motion_score(latents):\n #latents b, c f, h, w\n diff=torch.abs(latents[:,:,1:]-latents[:,:,:-1])\n motion_score = torch.sum(torch.mean(diff, dim=[2,3,4]), dim=1) * 10\n return motion_score" }, { "identifier": "DDPM_forward", "path": "utils/common.py", "snippet": "def DDPM_forward(x0, step, num_frames, scheduler):\n device = x0.device\n t = scheduler.timesteps[-1]\n xt = repeat(x0, 'b c 1 h w -> b c f h w', f = num_frames)\n\n eps = torch.randn_like(xt)\n alpha_vec = torch.prod(scheduler.alphas[t:])\n xt = torch.sqrt(alpha_vec) * xt + torch.sqrt(1-alpha_vec) * eps\n return xt, None" }, { "identifier": "DDPM_forward_timesteps", "path": "utils/common.py", "snippet": "def DDPM_forward_timesteps(x0, step, num_frames, scheduler):\n '''larger step -> smaller t -> smaller alphas[t:] -> smaller xt -> smaller x0'''\n\n device = x0.device\n # timesteps are reversed\n timesteps = scheduler.timesteps[len(scheduler.timesteps)-step:]\n t = timesteps[0]\n\n if x0.shape[2] == 1:\n xt = repeat(x0, 'b c 1 h w -> b c f h w', f = num_frames)\n else:\n xt = x0\n noise = torch.randn(xt.shape, dtype=xt.dtype, device=device)\n # t to tensor of batch size \n t = torch.tensor([t]*xt.shape[0], device=device)\n xt = scheduler.add_noise(xt, noise, t)\n return xt, timesteps" }, { "identifier": "DDPM_forward_mask", "path": "utils/common.py", "snippet": "def DDPM_forward_mask(x0, step, num_frames, scheduler, mask):\n '''larger step -> smaller t -> smaller alphas[t:] -> smaller xt -> smaller x0'''\n device = x0.device\n dtype = x0.dtype\n b, c, f, h, w = x0.shape\n\n move_xt, timesteps = DDPM_forward_timesteps(x0, step, num_frames, scheduler)\n mask = T.ToTensor()(mask).to(dtype).to(device)\n mask = T.Resize([h, w], antialias=False)(mask)\n mask = rearrange(mask, 'b h w -> b 1 1 h w')\n freeze_xt = repeat(x0, 'b c 1 h w -> b c f h w', f = num_frames)\n initial = freeze_xt * (1-mask) + move_xt * mask\n return initial, timesteps" }, { "identifier": "motion_mask_loss", "path": "utils/common.py", "snippet": "def motion_mask_loss(latents, mask):\n diff = torch.abs(latents[:,:,1:] - latents[:,:,:-1])\n loss = torch.sum(torch.mean(diff * (1-mask), dim=[2,3,4]), dim=1)\n return loss" }, { "identifier": "generate_center_mask", "path": "utils/common.py", "snippet": "def generate_center_mask(image):\n # Create a blank mask with the same size as the image\n b, c , h, w = image.shape\n mask = np.zeros([b, h, w], dtype=np.uint8)\n \n # Generate random coordinates for the mask\n for i in range(b):\n width = int(w/10)\n height = int(h/10)\n mask[i][height:-height,width:-width] = 255\n # Apply the mask to the image\n #masked_image = cv2.bitwise_and(image, image, mask=mask)\n return mask " }, { "identifier": "tensor_to_vae_latent", "path": "utils/common.py", "snippet": "def tensor_to_vae_latent(t, vae):\n video_length = t.shape[1]\n\n t = rearrange(t, \"b f c h w -> (b f) c h w\")\n latents = vae.encode(t).latent_dist.sample()\n latents = rearrange(latents, \"(b f) c h w -> b c f h w\", f=video_length)\n latents = latents * 0.18215\n\n return latents" } ]
import argparse import datetime import logging import inspect import math import os import json import gc import copy import random import cv2 import torch import torch.nn.functional as F import torch.utils.checkpoint import torchvision.transforms as T import diffusers import transformers import numpy as np import imageio import itertools import bitsandbytes as bnb from typing import Dict, Optional, Tuple from omegaconf import OmegaConf from tqdm.auto import tqdm from PIL import Image from accelerate import Accelerator from accelerate.logging import get_logger from accelerate.utils import set_seed from diffusers.models import AutoencoderKL from diffusers import DPMSolverMultistepScheduler, DDPMScheduler from diffusers.image_processor import VaeImageProcessor from diffusers.optimization import get_scheduler from diffusers.utils import check_min_version, export_to_video from diffusers.utils.import_utils import is_xformers_available from diffusers.models.attention_processor import AttnProcessor2_0, Attention from diffusers.models.attention import BasicTransformerBlock from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_synth import tensor2vid from transformers import CLIPTextModel, CLIPTokenizer from transformers.models.clip.modeling_clip import CLIPEncoder from utils.dataset import VideoJsonDataset, SingleVideoDataset, \ ImageDataset, VideoFolderDataset, CachedDataset, VideoBLIPDataset from einops import rearrange, repeat from models.unet_3d_condition_mask import UNet3DConditionModel from models.pipeline import LatentToVideoPipeline from utils.lora_handler import LoraHandler, LORA_VERSIONS from utils.common import read_mask, generate_random_mask, slerp, calculate_motion_score, \ read_video, calculate_motion_precision, calculate_latent_motion_score, \ DDPM_forward, DDPM_forward_timesteps, DDPM_forward_mask, motion_mask_loss, \ generate_center_mask, tensor_to_vae_latent from xformers.ops import MemoryEfficientAttentionFlashAttentionOp
19,759
} if extra_params is not None: for k, v in extra_params.items(): params[k] = v return params def negate_params(name, negation): # We have to do this if we are co-training with LoRA. # This ensures that parameter groups aren't duplicated. if negation is None: return False for n in negation: if n in name and 'temp' not in name: return True return False def create_optimizer_params(model_list, lr): optimizer_params = [] for optim in model_list: model, condition, extra_params, is_lora, negation = optim.values() # Check if we are doing LoRA training. if is_lora and condition and isinstance(model, list): params = create_optim_params( params=itertools.chain(*model), extra_params=extra_params ) optimizer_params.append(params) continue if is_lora and condition and not isinstance(model, list): for n, p in model.named_parameters(): if 'lora' in n: params = create_optim_params(n, p, lr, extra_params) optimizer_params.append(params) continue # If this is true, we can train it. if condition: for n, p in model.named_parameters(): should_negate = 'lora' in n and not is_lora if should_negate: continue params = create_optim_params(n, p, lr, extra_params) optimizer_params.append(params) return optimizer_params def get_optimizer(use_8bit_adam): if use_8bit_adam: try: except ImportError: raise ImportError( "Please install bitsandbytes to use 8-bit Adam. You can do so by running `pip install bitsandbytes`" ) return bnb.optim.AdamW8bit else: return torch.optim.AdamW def is_mixed_precision(accelerator): weight_dtype = torch.float32 if accelerator.mixed_precision == "fp16": weight_dtype = torch.float16 elif accelerator.mixed_precision == "bf16": weight_dtype = torch.bfloat16 return weight_dtype def cast_to_gpu_and_type(model_list, device, weight_dtype): for model in model_list: if model is not None: model.to(device, dtype=weight_dtype) def handle_cache_latents( should_cache, output_dir, train_dataloader, train_batch_size, vae, cached_latent_dir=None, shuffle=False ): # Cache latents by storing them in VRAM. # Speeds up training and saves memory by not encoding during the train loop. if not should_cache: return None vae.to('cuda', dtype=torch.float16) vae.enable_slicing() cached_latent_dir = ( os.path.abspath(cached_latent_dir) if cached_latent_dir is not None else None ) if cached_latent_dir is None: cache_save_dir = f"{output_dir}/cached_latents" os.makedirs(cache_save_dir, exist_ok=True) for i, batch in enumerate(tqdm(train_dataloader, desc="Caching Latents.")): save_name = f"cached_{i}" full_out_path = f"{cache_save_dir}/{save_name}.pt" pixel_values = batch['pixel_values'].to('cuda', dtype=torch.float16) batch['pixel_values'] = tensor_to_vae_latent(pixel_values, vae) for k, v in batch.items(): batch[k] = v[0] torch.save(batch, full_out_path) del pixel_values del batch # We do this to avoid fragmentation from casting latents between devices. torch.cuda.empty_cache() else: cache_save_dir = cached_latent_dir return torch.utils.data.DataLoader(
already_printed_trainables = False logger = get_logger(__name__, log_level="INFO") def create_logging(logging, logger, accelerator): logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO, ) logger.info(accelerator.state, main_process_only=False) def accelerate_set_verbose(accelerator): if accelerator.is_local_main_process: transformers.utils.logging.set_verbosity_warning() diffusers.utils.logging.set_verbosity_info() else: transformers.utils.logging.set_verbosity_error() diffusers.utils.logging.set_verbosity_error() def get_train_dataset(dataset_types, train_data, tokenizer): train_datasets = [] dataset_cls = [VideoJsonDataset, SingleVideoDataset, ImageDataset, VideoFolderDataset, VideoBLIPDataset] dataset_map = {d.__getname__(): d for d in dataset_cls} # Loop through all available datasets, get the name, then add to list of data to process. for dataset in dataset_types: if dataset in dataset_map: train_datasets.append(dataset_map[dataset](**train_data, tokenizer=tokenizer)) else: raise ValueError(f"Dataset type not found: {dataset} not in {dataset_map.keys()}") return train_datasets def extend_datasets(datasets, dataset_items, extend=False): biggest_data_len = max(x.__len__() for x in datasets) extended = [] for dataset in datasets: if dataset.__len__() == 0: del dataset continue if dataset.__len__() < biggest_data_len: for item in dataset_items: if extend and item not in extended and hasattr(dataset, item): print(f"Extending {item}") value = getattr(dataset, item) value *= biggest_data_len value = value[:biggest_data_len] setattr(dataset, item, value) print(f"New {item} dataset length: {dataset.__len__()}") extended.append(item) def export_to_video(video_frames, output_video_path, fps): fourcc = cv2.VideoWriter_fourcc(*"mp4v") h, w, _ = video_frames[0].shape video_writer = cv2.VideoWriter(output_video_path, fourcc, fps=fps, frameSize=(w, h)) for i in range(len(video_frames)): img = cv2.cvtColor(video_frames[i], cv2.COLOR_RGB2BGR) video_writer.write(img) def create_output_folders(output_dir, config): now = datetime.datetime.now().strftime("%Y-%m-%dT%H-%M-%S") out_dir = os.path.join(output_dir, f"train_{now}") os.makedirs(out_dir, exist_ok=True) os.makedirs(f"{out_dir}/samples", exist_ok=True) OmegaConf.save(config, os.path.join(out_dir, 'config.yaml')) return out_dir def load_primary_models(pretrained_model_path, motion_mask, motion_strength): noise_scheduler = DDPMScheduler.from_pretrained(pretrained_model_path, subfolder="scheduler") tokenizer = CLIPTokenizer.from_pretrained(pretrained_model_path, subfolder="tokenizer") text_encoder = CLIPTextModel.from_pretrained(pretrained_model_path, subfolder="text_encoder") vae = AutoencoderKL.from_pretrained(pretrained_model_path, subfolder="vae") unet = UNet3DConditionModel.from_pretrained(pretrained_model_path, subfolder="unet", low_cpu_mem_usage=False, device_map=None, motion_mask=motion_mask, motion_strength=motion_strength) if pretrained_model_path.endswith('zeroscope_v2_576w'): #first time init, modify unet conv in2 unet.conv_in2.bias.data = copy.deepcopy(unet.conv_in.bias) torch.nn.init.zeros_(unet.conv_in2.weight) unet.conv_in2.weight.data[:,1:]= copy.deepcopy(unet.conv_in.weight) return noise_scheduler, tokenizer, text_encoder, vae, unet def unet_and_text_g_c(unet, text_encoder, unet_enable, text_enable): unet._set_gradient_checkpointing(value=unet_enable) if text_enable: text_encoder.gradient_checkpointing_enable() else: text_encoder.gradient_checkpointing_disable() def freeze_models(models_to_freeze): for model in models_to_freeze: if model is not None: model.requires_grad_(False) def is_attn(name): return ('attn1' or 'attn2' == name.split('.')[-1]) def set_processors(attentions): for attn in attentions: attn.set_processor(AttnProcessor2_0()) def set_torch_2_attn(unet): optim_count = 0 for name, module in unet.named_modules(): if is_attn(name): if isinstance(module, torch.nn.ModuleList): for m in module: if isinstance(m, BasicTransformerBlock): set_processors([m.attn1, m.attn2]) optim_count += 1 if optim_count > 0: print(f"{optim_count} Attention layers using Scaled Dot Product Attention.") def handle_memory_attention(enable_xformers_memory_efficient_attention, enable_torch_2_attn, unet): try: is_torch_2 = hasattr(F, 'scaled_dot_product_attention') enable_torch_2 = is_torch_2 and enable_torch_2_attn if enable_xformers_memory_efficient_attention and not enable_torch_2: if is_xformers_available(): unet.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp) else: raise ValueError("xformers is not available. Make sure it is installed correctly") if enable_torch_2: set_torch_2_attn(unet) except: print("Could not enable memory efficient attention for xformers or Torch 2.0.") def param_optim(model, condition, extra_params=None, is_lora=False, negation=None): extra_params = extra_params if len(extra_params.keys()) > 0 else None return { "model": model, "condition": condition, 'extra_params': extra_params, 'is_lora': is_lora, "negation": negation } def create_optim_params(name='param', params=None, lr=5e-6, extra_params=None): params = { "name": name, "params": params, "lr": lr } if extra_params is not None: for k, v in extra_params.items(): params[k] = v return params def negate_params(name, negation): # We have to do this if we are co-training with LoRA. # This ensures that parameter groups aren't duplicated. if negation is None: return False for n in negation: if n in name and 'temp' not in name: return True return False def create_optimizer_params(model_list, lr): optimizer_params = [] for optim in model_list: model, condition, extra_params, is_lora, negation = optim.values() # Check if we are doing LoRA training. if is_lora and condition and isinstance(model, list): params = create_optim_params( params=itertools.chain(*model), extra_params=extra_params ) optimizer_params.append(params) continue if is_lora and condition and not isinstance(model, list): for n, p in model.named_parameters(): if 'lora' in n: params = create_optim_params(n, p, lr, extra_params) optimizer_params.append(params) continue # If this is true, we can train it. if condition: for n, p in model.named_parameters(): should_negate = 'lora' in n and not is_lora if should_negate: continue params = create_optim_params(n, p, lr, extra_params) optimizer_params.append(params) return optimizer_params def get_optimizer(use_8bit_adam): if use_8bit_adam: try: except ImportError: raise ImportError( "Please install bitsandbytes to use 8-bit Adam. You can do so by running `pip install bitsandbytes`" ) return bnb.optim.AdamW8bit else: return torch.optim.AdamW def is_mixed_precision(accelerator): weight_dtype = torch.float32 if accelerator.mixed_precision == "fp16": weight_dtype = torch.float16 elif accelerator.mixed_precision == "bf16": weight_dtype = torch.bfloat16 return weight_dtype def cast_to_gpu_and_type(model_list, device, weight_dtype): for model in model_list: if model is not None: model.to(device, dtype=weight_dtype) def handle_cache_latents( should_cache, output_dir, train_dataloader, train_batch_size, vae, cached_latent_dir=None, shuffle=False ): # Cache latents by storing them in VRAM. # Speeds up training and saves memory by not encoding during the train loop. if not should_cache: return None vae.to('cuda', dtype=torch.float16) vae.enable_slicing() cached_latent_dir = ( os.path.abspath(cached_latent_dir) if cached_latent_dir is not None else None ) if cached_latent_dir is None: cache_save_dir = f"{output_dir}/cached_latents" os.makedirs(cache_save_dir, exist_ok=True) for i, batch in enumerate(tqdm(train_dataloader, desc="Caching Latents.")): save_name = f"cached_{i}" full_out_path = f"{cache_save_dir}/{save_name}.pt" pixel_values = batch['pixel_values'].to('cuda', dtype=torch.float16) batch['pixel_values'] = tensor_to_vae_latent(pixel_values, vae) for k, v in batch.items(): batch[k] = v[0] torch.save(batch, full_out_path) del pixel_values del batch # We do this to avoid fragmentation from casting latents between devices. torch.cuda.empty_cache() else: cache_save_dir = cached_latent_dir return torch.utils.data.DataLoader(
CachedDataset(cache_dir=cache_save_dir),
4
2023-12-07 08:26:29+00:00
24k
rehg-lab/RAVE
annotator/oneformer/detectron2/modeling/meta_arch/retinanet.py
[ { "identifier": "configurable", "path": "annotator/oneformer/detectron2/config/config.py", "snippet": "def configurable(init_func=None, *, from_config=None):\r\n \"\"\"\r\n Decorate a function or a class's __init__ method so that it can be called\r\n with a :class:`CfgNode` object using a :func:`from_config` function that translates\r\n :class:`CfgNode` to arguments.\r\n\r\n Examples:\r\n ::\r\n # Usage 1: Decorator on __init__:\r\n class A:\r\n @configurable\r\n def __init__(self, a, b=2, c=3):\r\n pass\r\n\r\n @classmethod\r\n def from_config(cls, cfg): # 'cfg' must be the first argument\r\n # Returns kwargs to be passed to __init__\r\n return {\"a\": cfg.A, \"b\": cfg.B}\r\n\r\n a1 = A(a=1, b=2) # regular construction\r\n a2 = A(cfg) # construct with a cfg\r\n a3 = A(cfg, b=3, c=4) # construct with extra overwrite\r\n\r\n # Usage 2: Decorator on any function. Needs an extra from_config argument:\r\n @configurable(from_config=lambda cfg: {\"a: cfg.A, \"b\": cfg.B})\r\n def a_func(a, b=2, c=3):\r\n pass\r\n\r\n a1 = a_func(a=1, b=2) # regular call\r\n a2 = a_func(cfg) # call with a cfg\r\n a3 = a_func(cfg, b=3, c=4) # call with extra overwrite\r\n\r\n Args:\r\n init_func (callable): a class's ``__init__`` method in usage 1. The\r\n class must have a ``from_config`` classmethod which takes `cfg` as\r\n the first argument.\r\n from_config (callable): the from_config function in usage 2. It must take `cfg`\r\n as its first argument.\r\n \"\"\"\r\n\r\n if init_func is not None:\r\n assert (\r\n inspect.isfunction(init_func)\r\n and from_config is None\r\n and init_func.__name__ == \"__init__\"\r\n ), \"Incorrect use of @configurable. Check API documentation for examples.\"\r\n\r\n @functools.wraps(init_func)\r\n def wrapped(self, *args, **kwargs):\r\n try:\r\n from_config_func = type(self).from_config\r\n except AttributeError as e:\r\n raise AttributeError(\r\n \"Class with @configurable must have a 'from_config' classmethod.\"\r\n ) from e\r\n if not inspect.ismethod(from_config_func):\r\n raise TypeError(\"Class with @configurable must have a 'from_config' classmethod.\")\r\n\r\n if _called_with_cfg(*args, **kwargs):\r\n explicit_args = _get_args_from_config(from_config_func, *args, **kwargs)\r\n init_func(self, **explicit_args)\r\n else:\r\n init_func(self, *args, **kwargs)\r\n\r\n return wrapped\r\n\r\n else:\r\n if from_config is None:\r\n return configurable # @configurable() is made equivalent to @configurable\r\n assert inspect.isfunction(\r\n from_config\r\n ), \"from_config argument of configurable must be a function!\"\r\n\r\n def wrapper(orig_func):\r\n @functools.wraps(orig_func)\r\n def wrapped(*args, **kwargs):\r\n if _called_with_cfg(*args, **kwargs):\r\n explicit_args = _get_args_from_config(from_config, *args, **kwargs)\r\n return orig_func(**explicit_args)\r\n else:\r\n return orig_func(*args, **kwargs)\r\n\r\n wrapped.from_config = from_config\r\n return wrapped\r\n\r\n return wrapper\r" }, { "identifier": "get_norm", "path": "annotator/oneformer/detectron2/layers/batch_norm.py", "snippet": "def get_norm(norm, out_channels):\r\n \"\"\"\r\n Args:\r\n norm (str or callable): either one of BN, SyncBN, FrozenBN, GN;\r\n or a callable that takes a channel number and returns\r\n the normalization layer as a nn.Module.\r\n\r\n Returns:\r\n nn.Module or None: the normalization layer\r\n \"\"\"\r\n if norm is None:\r\n return None\r\n if isinstance(norm, str):\r\n if len(norm) == 0:\r\n return None\r\n norm = {\r\n \"BN\": BatchNorm2d,\r\n # Fixed in https://github.com/pytorch/pytorch/pull/36382\r\n \"SyncBN\": NaiveSyncBatchNorm if env.TORCH_VERSION <= (1, 5) else nn.SyncBatchNorm,\r\n \"FrozenBN\": FrozenBatchNorm2d,\r\n \"GN\": lambda channels: nn.GroupNorm(32, channels),\r\n # for debugging:\r\n \"nnSyncBN\": nn.SyncBatchNorm,\r\n \"naiveSyncBN\": NaiveSyncBatchNorm,\r\n # expose stats_mode N as an option to caller, required for zero-len inputs\r\n \"naiveSyncBN_N\": lambda channels: NaiveSyncBatchNorm(channels, stats_mode=\"N\"),\r\n \"LN\": lambda channels: LayerNorm(channels),\r\n }[norm]\r\n return norm(out_channels)\r" }, { "identifier": "CycleBatchNormList", "path": "annotator/oneformer/detectron2/layers/batch_norm.py", "snippet": "class CycleBatchNormList(nn.ModuleList):\r\n \"\"\"\r\n Implement domain-specific BatchNorm by cycling.\r\n\r\n When a BatchNorm layer is used for multiple input domains or input\r\n features, it might need to maintain a separate test-time statistics\r\n for each domain. See Sec 5.2 in :paper:`rethinking-batchnorm`.\r\n\r\n This module implements it by using N separate BN layers\r\n and it cycles through them every time a forward() is called.\r\n\r\n NOTE: The caller of this module MUST guarantee to always call\r\n this module by multiple of N times. Otherwise its test-time statistics\r\n will be incorrect.\r\n \"\"\"\r\n\r\n def __init__(self, length: int, bn_class=nn.BatchNorm2d, **kwargs):\r\n \"\"\"\r\n Args:\r\n length: number of BatchNorm layers to cycle.\r\n bn_class: the BatchNorm class to use\r\n kwargs: arguments of the BatchNorm class, such as num_features.\r\n \"\"\"\r\n self._affine = kwargs.pop(\"affine\", True)\r\n super().__init__([bn_class(**kwargs, affine=False) for k in range(length)])\r\n if self._affine:\r\n # shared affine, domain-specific BN\r\n channels = self[0].num_features\r\n self.weight = nn.Parameter(torch.ones(channels))\r\n self.bias = nn.Parameter(torch.zeros(channels))\r\n self._pos = 0\r\n\r\n def forward(self, x):\r\n ret = self[self._pos](x)\r\n self._pos = (self._pos + 1) % len(self)\r\n\r\n if self._affine:\r\n w = self.weight.reshape(1, -1, 1, 1)\r\n b = self.bias.reshape(1, -1, 1, 1)\r\n return ret * w + b\r\n else:\r\n return ret\r\n\r\n def extra_repr(self):\r\n return f\"affine={self._affine}\"\r" }, { "identifier": "batched_nms", "path": "annotator/oneformer/detectron2/layers/nms.py", "snippet": "def batched_nms(\r\n boxes: torch.Tensor, scores: torch.Tensor, idxs: torch.Tensor, iou_threshold: float\r\n):\r\n \"\"\"\r\n Same as torchvision.ops.boxes.batched_nms, but with float().\r\n \"\"\"\r\n assert boxes.shape[-1] == 4\r\n # Note: Torchvision already has a strategy (https://github.com/pytorch/vision/issues/1311)\r\n # to decide whether to use coordinate trick or for loop to implement batched_nms. So we\r\n # just call it directly.\r\n # Fp16 does not have enough range for batched NMS, so adding float().\r\n return box_ops.batched_nms(boxes.float(), scores, idxs, iou_threshold)\r" }, { "identifier": "ShapeSpec", "path": "annotator/oneformer/detectron2/layers/shape_spec.py", "snippet": "class ShapeSpec:\r\n \"\"\"\r\n A simple structure that contains basic shape specification about a tensor.\r\n It is often used as the auxiliary inputs/outputs of models,\r\n to complement the lack of shape inference ability among pytorch modules.\r\n \"\"\"\r\n\r\n channels: Optional[int] = None\r\n height: Optional[int] = None\r\n width: Optional[int] = None\r\n stride: Optional[int] = None\r" }, { "identifier": "cat", "path": "annotator/oneformer/detectron2/layers/wrappers.py", "snippet": "def cat(tensors: List[torch.Tensor], dim: int = 0):\r\n \"\"\"\r\n Efficient version of torch.cat that avoids a copy if there is only a single element in a list\r\n \"\"\"\r\n assert isinstance(tensors, (list, tuple))\r\n if len(tensors) == 1:\r\n return tensors[0]\r\n return torch.cat(tensors, dim)\r" }, { "identifier": "Boxes", "path": "annotator/oneformer/detectron2/structures/boxes.py", "snippet": "class Boxes:\r\n \"\"\"\r\n This structure stores a list of boxes as a Nx4 torch.Tensor.\r\n It supports some common methods about boxes\r\n (`area`, `clip`, `nonempty`, etc),\r\n and also behaves like a Tensor\r\n (support indexing, `to(device)`, `.device`, and iteration over all boxes)\r\n\r\n Attributes:\r\n tensor (torch.Tensor): float matrix of Nx4. Each row is (x1, y1, x2, y2).\r\n \"\"\"\r\n\r\n def __init__(self, tensor: torch.Tensor):\r\n \"\"\"\r\n Args:\r\n tensor (Tensor[float]): a Nx4 matrix. Each row is (x1, y1, x2, y2).\r\n \"\"\"\r\n if not isinstance(tensor, torch.Tensor):\r\n tensor = torch.as_tensor(tensor, dtype=torch.float32, device=torch.device(\"cpu\"))\r\n else:\r\n tensor = tensor.to(torch.float32)\r\n if tensor.numel() == 0:\r\n # Use reshape, so we don't end up creating a new tensor that does not depend on\r\n # the inputs (and consequently confuses jit)\r\n tensor = tensor.reshape((-1, 4)).to(dtype=torch.float32)\r\n assert tensor.dim() == 2 and tensor.size(-1) == 4, tensor.size()\r\n\r\n self.tensor = tensor\r\n\r\n def clone(self) -> \"Boxes\":\r\n \"\"\"\r\n Clone the Boxes.\r\n\r\n Returns:\r\n Boxes\r\n \"\"\"\r\n return Boxes(self.tensor.clone())\r\n\r\n def to(self, device: torch.device):\r\n # Boxes are assumed float32 and does not support to(dtype)\r\n return Boxes(self.tensor.to(device=device))\r\n\r\n def area(self) -> torch.Tensor:\r\n \"\"\"\r\n Computes the area of all the boxes.\r\n\r\n Returns:\r\n torch.Tensor: a vector with areas of each box.\r\n \"\"\"\r\n box = self.tensor\r\n area = (box[:, 2] - box[:, 0]) * (box[:, 3] - box[:, 1])\r\n return area\r\n\r\n def clip(self, box_size: Tuple[int, int]) -> None:\r\n \"\"\"\r\n Clip (in place) the boxes by limiting x coordinates to the range [0, width]\r\n and y coordinates to the range [0, height].\r\n\r\n Args:\r\n box_size (height, width): The clipping box's size.\r\n \"\"\"\r\n assert torch.isfinite(self.tensor).all(), \"Box tensor contains infinite or NaN!\"\r\n h, w = box_size\r\n x1 = self.tensor[:, 0].clamp(min=0, max=w)\r\n y1 = self.tensor[:, 1].clamp(min=0, max=h)\r\n x2 = self.tensor[:, 2].clamp(min=0, max=w)\r\n y2 = self.tensor[:, 3].clamp(min=0, max=h)\r\n self.tensor = torch.stack((x1, y1, x2, y2), dim=-1)\r\n\r\n def nonempty(self, threshold: float = 0.0) -> torch.Tensor:\r\n \"\"\"\r\n Find boxes that are non-empty.\r\n A box is considered empty, if either of its side is no larger than threshold.\r\n\r\n Returns:\r\n Tensor:\r\n a binary vector which represents whether each box is empty\r\n (False) or non-empty (True).\r\n \"\"\"\r\n box = self.tensor\r\n widths = box[:, 2] - box[:, 0]\r\n heights = box[:, 3] - box[:, 1]\r\n keep = (widths > threshold) & (heights > threshold)\r\n return keep\r\n\r\n def __getitem__(self, item) -> \"Boxes\":\r\n \"\"\"\r\n Args:\r\n item: int, slice, or a BoolTensor\r\n\r\n Returns:\r\n Boxes: Create a new :class:`Boxes` by indexing.\r\n\r\n The following usage are allowed:\r\n\r\n 1. `new_boxes = boxes[3]`: return a `Boxes` which contains only one box.\r\n 2. `new_boxes = boxes[2:10]`: return a slice of boxes.\r\n 3. `new_boxes = boxes[vector]`, where vector is a torch.BoolTensor\r\n with `length = len(boxes)`. Nonzero elements in the vector will be selected.\r\n\r\n Note that the returned Boxes might share storage with this Boxes,\r\n subject to Pytorch's indexing semantics.\r\n \"\"\"\r\n if isinstance(item, int):\r\n return Boxes(self.tensor[item].view(1, -1))\r\n b = self.tensor[item]\r\n assert b.dim() == 2, \"Indexing on Boxes with {} failed to return a matrix!\".format(item)\r\n return Boxes(b)\r\n\r\n def __len__(self) -> int:\r\n return self.tensor.shape[0]\r\n\r\n def __repr__(self) -> str:\r\n return \"Boxes(\" + str(self.tensor) + \")\"\r\n\r\n def inside_box(self, box_size: Tuple[int, int], boundary_threshold: int = 0) -> torch.Tensor:\r\n \"\"\"\r\n Args:\r\n box_size (height, width): Size of the reference box.\r\n boundary_threshold (int): Boxes that extend beyond the reference box\r\n boundary by more than boundary_threshold are considered \"outside\".\r\n\r\n Returns:\r\n a binary vector, indicating whether each box is inside the reference box.\r\n \"\"\"\r\n height, width = box_size\r\n inds_inside = (\r\n (self.tensor[..., 0] >= -boundary_threshold)\r\n & (self.tensor[..., 1] >= -boundary_threshold)\r\n & (self.tensor[..., 2] < width + boundary_threshold)\r\n & (self.tensor[..., 3] < height + boundary_threshold)\r\n )\r\n return inds_inside\r\n\r\n def get_centers(self) -> torch.Tensor:\r\n \"\"\"\r\n Returns:\r\n The box centers in a Nx2 array of (x, y).\r\n \"\"\"\r\n return (self.tensor[:, :2] + self.tensor[:, 2:]) / 2\r\n\r\n def scale(self, scale_x: float, scale_y: float) -> None:\r\n \"\"\"\r\n Scale the box with horizontal and vertical scaling factors\r\n \"\"\"\r\n self.tensor[:, 0::2] *= scale_x\r\n self.tensor[:, 1::2] *= scale_y\r\n\r\n @classmethod\r\n def cat(cls, boxes_list: List[\"Boxes\"]) -> \"Boxes\":\r\n \"\"\"\r\n Concatenates a list of Boxes into a single Boxes\r\n\r\n Arguments:\r\n boxes_list (list[Boxes])\r\n\r\n Returns:\r\n Boxes: the concatenated Boxes\r\n \"\"\"\r\n assert isinstance(boxes_list, (list, tuple))\r\n if len(boxes_list) == 0:\r\n return cls(torch.empty(0))\r\n assert all([isinstance(box, Boxes) for box in boxes_list])\r\n\r\n # use torch.cat (v.s. layers.cat) so the returned boxes never share storage with input\r\n cat_boxes = cls(torch.cat([b.tensor for b in boxes_list], dim=0))\r\n return cat_boxes\r\n\r\n @property\r\n def device(self) -> device:\r\n return self.tensor.device\r\n\r\n # type \"Iterator[torch.Tensor]\", yield, and iter() not supported by torchscript\r\n # https://github.com/pytorch/pytorch/issues/18627\r\n @torch.jit.unused\r\n def __iter__(self):\r\n \"\"\"\r\n Yield a box as a Tensor of shape (4,) at a time.\r\n \"\"\"\r\n yield from self.tensor\r" }, { "identifier": "pairwise_iou", "path": "annotator/oneformer/detectron2/structures/boxes.py", "snippet": "def pairwise_iou(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:\r\n \"\"\"\r\n Given two lists of boxes of size N and M, compute the IoU\r\n (intersection over union) between **all** N x M pairs of boxes.\r\n The box order must be (xmin, ymin, xmax, ymax).\r\n\r\n Args:\r\n boxes1,boxes2 (Boxes): two `Boxes`. Contains N & M boxes, respectively.\r\n\r\n Returns:\r\n Tensor: IoU, sized [N,M].\r\n \"\"\"\r\n area1 = boxes1.area() # [N]\r\n area2 = boxes2.area() # [M]\r\n inter = pairwise_intersection(boxes1, boxes2)\r\n\r\n # handle empty boxes\r\n iou = torch.where(\r\n inter > 0,\r\n inter / (area1[:, None] + area2 - inter),\r\n torch.zeros(1, dtype=inter.dtype, device=inter.device),\r\n )\r\n return iou\r" }, { "identifier": "ImageList", "path": "annotator/oneformer/detectron2/structures/image_list.py", "snippet": "class ImageList(object):\r\n \"\"\"\r\n Structure that holds a list of images (of possibly\r\n varying sizes) as a single tensor.\r\n This works by padding the images to the same size.\r\n The original sizes of each image is stored in `image_sizes`.\r\n\r\n Attributes:\r\n image_sizes (list[tuple[int, int]]): each tuple is (h, w).\r\n During tracing, it becomes list[Tensor] instead.\r\n \"\"\"\r\n\r\n def __init__(self, tensor: torch.Tensor, image_sizes: List[Tuple[int, int]]):\r\n \"\"\"\r\n Arguments:\r\n tensor (Tensor): of shape (N, H, W) or (N, C_1, ..., C_K, H, W) where K >= 1\r\n image_sizes (list[tuple[int, int]]): Each tuple is (h, w). It can\r\n be smaller than (H, W) due to padding.\r\n \"\"\"\r\n self.tensor = tensor\r\n self.image_sizes = image_sizes\r\n\r\n def __len__(self) -> int:\r\n return len(self.image_sizes)\r\n\r\n def __getitem__(self, idx) -> torch.Tensor:\r\n \"\"\"\r\n Access the individual image in its original size.\r\n\r\n Args:\r\n idx: int or slice\r\n\r\n Returns:\r\n Tensor: an image of shape (H, W) or (C_1, ..., C_K, H, W) where K >= 1\r\n \"\"\"\r\n size = self.image_sizes[idx]\r\n return self.tensor[idx, ..., : size[0], : size[1]]\r\n\r\n @torch.jit.unused\r\n def to(self, *args: Any, **kwargs: Any) -> \"ImageList\":\r\n cast_tensor = self.tensor.to(*args, **kwargs)\r\n return ImageList(cast_tensor, self.image_sizes)\r\n\r\n @property\r\n def device(self) -> device:\r\n return self.tensor.device\r\n\r\n @staticmethod\r\n def from_tensors(\r\n tensors: List[torch.Tensor],\r\n size_divisibility: int = 0,\r\n pad_value: float = 0.0,\r\n padding_constraints: Optional[Dict[str, int]] = None,\r\n ) -> \"ImageList\":\r\n \"\"\"\r\n Args:\r\n tensors: a tuple or list of `torch.Tensor`, each of shape (Hi, Wi) or\r\n (C_1, ..., C_K, Hi, Wi) where K >= 1. The Tensors will be padded\r\n to the same shape with `pad_value`.\r\n size_divisibility (int): If `size_divisibility > 0`, add padding to ensure\r\n the common height and width is divisible by `size_divisibility`.\r\n This depends on the model and many models need a divisibility of 32.\r\n pad_value (float): value to pad.\r\n padding_constraints (optional[Dict]): If given, it would follow the format as\r\n {\"size_divisibility\": int, \"square_size\": int}, where `size_divisibility` will\r\n overwrite the above one if presented and `square_size` indicates the\r\n square padding size if `square_size` > 0.\r\n Returns:\r\n an `ImageList`.\r\n \"\"\"\r\n assert len(tensors) > 0\r\n assert isinstance(tensors, (tuple, list))\r\n for t in tensors:\r\n assert isinstance(t, torch.Tensor), type(t)\r\n assert t.shape[:-2] == tensors[0].shape[:-2], t.shape\r\n\r\n image_sizes = [(im.shape[-2], im.shape[-1]) for im in tensors]\r\n image_sizes_tensor = [shapes_to_tensor(x) for x in image_sizes]\r\n max_size = torch.stack(image_sizes_tensor).max(0).values\r\n\r\n if padding_constraints is not None:\r\n square_size = padding_constraints.get(\"square_size\", 0)\r\n if square_size > 0:\r\n # pad to square.\r\n max_size[0] = max_size[1] = square_size\r\n if \"size_divisibility\" in padding_constraints:\r\n size_divisibility = padding_constraints[\"size_divisibility\"]\r\n if size_divisibility > 1:\r\n stride = size_divisibility\r\n # the last two dims are H,W, both subject to divisibility requirement\r\n max_size = (max_size + (stride - 1)).div(stride, rounding_mode=\"floor\") * stride\r\n\r\n # handle weirdness of scripting and tracing ...\r\n if torch.jit.is_scripting():\r\n max_size: List[int] = max_size.to(dtype=torch.long).tolist()\r\n else:\r\n if torch.jit.is_tracing():\r\n image_sizes = image_sizes_tensor\r\n\r\n if len(tensors) == 1:\r\n # This seems slightly (2%) faster.\r\n # TODO: check whether it's faster for multiple images as well\r\n image_size = image_sizes[0]\r\n padding_size = [0, max_size[-1] - image_size[1], 0, max_size[-2] - image_size[0]]\r\n batched_imgs = F.pad(tensors[0], padding_size, value=pad_value).unsqueeze_(0)\r\n else:\r\n # max_size can be a tensor in tracing mode, therefore convert to list\r\n batch_shape = [len(tensors)] + list(tensors[0].shape[:-2]) + list(max_size)\r\n device = (\r\n None if torch.jit.is_scripting() else (\"cpu\" if torch.jit.is_tracing() else None)\r\n )\r\n batched_imgs = tensors[0].new_full(batch_shape, pad_value, device=device)\r\n batched_imgs = move_device_like(batched_imgs, tensors[0])\r\n for i, img in enumerate(tensors):\r\n # Use `batched_imgs` directly instead of `img, pad_img = zip(tensors, batched_imgs)`\r\n # Tracing mode cannot capture `copy_()` of temporary locals\r\n batched_imgs[i, ..., : img.shape[-2], : img.shape[-1]].copy_(img)\r\n\r\n return ImageList(batched_imgs.contiguous(), image_sizes)\r" }, { "identifier": "Instances", "path": "annotator/oneformer/detectron2/structures/instances.py", "snippet": "class Instances:\r\n \"\"\"\r\n This class represents a list of instances in an image.\r\n It stores the attributes of instances (e.g., boxes, masks, labels, scores) as \"fields\".\r\n All fields must have the same ``__len__`` which is the number of instances.\r\n\r\n All other (non-field) attributes of this class are considered private:\r\n they must start with '_' and are not modifiable by a user.\r\n\r\n Some basic usage:\r\n\r\n 1. Set/get/check a field:\r\n\r\n .. code-block:: python\r\n\r\n instances.gt_boxes = Boxes(...)\r\n print(instances.pred_masks) # a tensor of shape (N, H, W)\r\n print('gt_masks' in instances)\r\n\r\n 2. ``len(instances)`` returns the number of instances\r\n 3. Indexing: ``instances[indices]`` will apply the indexing on all the fields\r\n and returns a new :class:`Instances`.\r\n Typically, ``indices`` is a integer vector of indices,\r\n or a binary mask of length ``num_instances``\r\n\r\n .. code-block:: python\r\n\r\n category_3_detections = instances[instances.pred_classes == 3]\r\n confident_detections = instances[instances.scores > 0.9]\r\n \"\"\"\r\n\r\n def __init__(self, image_size: Tuple[int, int], **kwargs: Any):\r\n \"\"\"\r\n Args:\r\n image_size (height, width): the spatial size of the image.\r\n kwargs: fields to add to this `Instances`.\r\n \"\"\"\r\n self._image_size = image_size\r\n self._fields: Dict[str, Any] = {}\r\n for k, v in kwargs.items():\r\n self.set(k, v)\r\n\r\n @property\r\n def image_size(self) -> Tuple[int, int]:\r\n \"\"\"\r\n Returns:\r\n tuple: height, width\r\n \"\"\"\r\n return self._image_size\r\n\r\n def __setattr__(self, name: str, val: Any) -> None:\r\n if name.startswith(\"_\"):\r\n super().__setattr__(name, val)\r\n else:\r\n self.set(name, val)\r\n\r\n def __getattr__(self, name: str) -> Any:\r\n if name == \"_fields\" or name not in self._fields:\r\n raise AttributeError(\"Cannot find field '{}' in the given Instances!\".format(name))\r\n return self._fields[name]\r\n\r\n def set(self, name: str, value: Any) -> None:\r\n \"\"\"\r\n Set the field named `name` to `value`.\r\n The length of `value` must be the number of instances,\r\n and must agree with other existing fields in this object.\r\n \"\"\"\r\n with warnings.catch_warnings(record=True):\r\n data_len = len(value)\r\n if len(self._fields):\r\n assert (\r\n len(self) == data_len\r\n ), \"Adding a field of length {} to a Instances of length {}\".format(data_len, len(self))\r\n self._fields[name] = value\r\n\r\n def has(self, name: str) -> bool:\r\n \"\"\"\r\n Returns:\r\n bool: whether the field called `name` exists.\r\n \"\"\"\r\n return name in self._fields\r\n\r\n def remove(self, name: str) -> None:\r\n \"\"\"\r\n Remove the field called `name`.\r\n \"\"\"\r\n del self._fields[name]\r\n\r\n def get(self, name: str) -> Any:\r\n \"\"\"\r\n Returns the field called `name`.\r\n \"\"\"\r\n return self._fields[name]\r\n\r\n def get_fields(self) -> Dict[str, Any]:\r\n \"\"\"\r\n Returns:\r\n dict: a dict which maps names (str) to data of the fields\r\n\r\n Modifying the returned dict will modify this instance.\r\n \"\"\"\r\n return self._fields\r\n\r\n # Tensor-like methods\r\n def to(self, *args: Any, **kwargs: Any) -> \"Instances\":\r\n \"\"\"\r\n Returns:\r\n Instances: all fields are called with a `to(device)`, if the field has this method.\r\n \"\"\"\r\n ret = Instances(self._image_size)\r\n for k, v in self._fields.items():\r\n if hasattr(v, \"to\"):\r\n v = v.to(*args, **kwargs)\r\n ret.set(k, v)\r\n return ret\r\n\r\n def __getitem__(self, item: Union[int, slice, torch.BoolTensor]) -> \"Instances\":\r\n \"\"\"\r\n Args:\r\n item: an index-like object and will be used to index all the fields.\r\n\r\n Returns:\r\n If `item` is a string, return the data in the corresponding field.\r\n Otherwise, returns an `Instances` where all fields are indexed by `item`.\r\n \"\"\"\r\n if type(item) == int:\r\n if item >= len(self) or item < -len(self):\r\n raise IndexError(\"Instances index out of range!\")\r\n else:\r\n item = slice(item, None, len(self))\r\n\r\n ret = Instances(self._image_size)\r\n for k, v in self._fields.items():\r\n ret.set(k, v[item])\r\n return ret\r\n\r\n def __len__(self) -> int:\r\n for v in self._fields.values():\r\n # use __len__ because len() has to be int and is not friendly to tracing\r\n return v.__len__()\r\n raise NotImplementedError(\"Empty Instances does not support __len__!\")\r\n\r\n def __iter__(self):\r\n raise NotImplementedError(\"`Instances` object is not iterable!\")\r\n\r\n @staticmethod\r\n def cat(instance_lists: List[\"Instances\"]) -> \"Instances\":\r\n \"\"\"\r\n Args:\r\n instance_lists (list[Instances])\r\n\r\n Returns:\r\n Instances\r\n \"\"\"\r\n assert all(isinstance(i, Instances) for i in instance_lists)\r\n assert len(instance_lists) > 0\r\n if len(instance_lists) == 1:\r\n return instance_lists[0]\r\n\r\n image_size = instance_lists[0].image_size\r\n if not isinstance(image_size, torch.Tensor): # could be a tensor in tracing\r\n for i in instance_lists[1:]:\r\n assert i.image_size == image_size\r\n ret = Instances(image_size)\r\n for k in instance_lists[0]._fields.keys():\r\n values = [i.get(k) for i in instance_lists]\r\n v0 = values[0]\r\n if isinstance(v0, torch.Tensor):\r\n values = torch.cat(values, dim=0)\r\n elif isinstance(v0, list):\r\n values = list(itertools.chain(*values))\r\n elif hasattr(type(v0), \"cat\"):\r\n values = type(v0).cat(values)\r\n else:\r\n raise ValueError(\"Unsupported type {} for concatenation\".format(type(v0)))\r\n ret.set(k, values)\r\n return ret\r\n\r\n def __str__(self) -> str:\r\n s = self.__class__.__name__ + \"(\"\r\n s += \"num_instances={}, \".format(len(self))\r\n s += \"image_height={}, \".format(self._image_size[0])\r\n s += \"image_width={}, \".format(self._image_size[1])\r\n s += \"fields=[{}])\".format(\", \".join((f\"{k}: {v}\" for k, v in self._fields.items())))\r\n return s\r\n\r\n __repr__ = __str__\r" }, { "identifier": "get_event_storage", "path": "annotator/oneformer/detectron2/utils/events.py", "snippet": "def get_event_storage():\r\n \"\"\"\r\n Returns:\r\n The :class:`EventStorage` object that's currently being used.\r\n Throws an error if no :class:`EventStorage` is currently enabled.\r\n \"\"\"\r\n assert len(\r\n _CURRENT_STORAGE_STACK\r\n ), \"get_event_storage() has to be called inside a 'with EventStorage(...)' context!\"\r\n return _CURRENT_STORAGE_STACK[-1]\r" }, { "identifier": "build_anchor_generator", "path": "annotator/oneformer/detectron2/modeling/anchor_generator.py", "snippet": "def build_anchor_generator(cfg, input_shape):\r\n \"\"\"\r\n Built an anchor generator from `cfg.MODEL.ANCHOR_GENERATOR.NAME`.\r\n \"\"\"\r\n anchor_generator = cfg.MODEL.ANCHOR_GENERATOR.NAME\r\n return ANCHOR_GENERATOR_REGISTRY.get(anchor_generator)(cfg, input_shape)\r" }, { "identifier": "build_backbone", "path": "annotator/oneformer/detectron2/modeling/backbone/build.py", "snippet": "def build_backbone(cfg, input_shape=None):\r\n \"\"\"\r\n Build a backbone from `cfg.MODEL.BACKBONE.NAME`.\r\n\r\n Returns:\r\n an instance of :class:`Backbone`\r\n \"\"\"\r\n if input_shape is None:\r\n input_shape = ShapeSpec(channels=len(cfg.MODEL.PIXEL_MEAN))\r\n\r\n backbone_name = cfg.MODEL.BACKBONE.NAME\r\n backbone = BACKBONE_REGISTRY.get(backbone_name)(cfg, input_shape)\r\n assert isinstance(backbone, Backbone)\r\n return backbone\r" }, { "identifier": "Backbone", "path": "annotator/oneformer/detectron2/modeling/backbone/backbone.py", "snippet": "class Backbone(nn.Module, metaclass=ABCMeta):\r\n \"\"\"\r\n Abstract base class for network backbones.\r\n \"\"\"\r\n\r\n def __init__(self):\r\n \"\"\"\r\n The `__init__` method of any subclass can specify its own set of arguments.\r\n \"\"\"\r\n super().__init__()\r\n\r\n @abstractmethod\r\n def forward(self):\r\n \"\"\"\r\n Subclasses must override this method, but adhere to the same return type.\r\n\r\n Returns:\r\n dict[str->Tensor]: mapping from feature name (e.g., \"res2\") to tensor\r\n \"\"\"\r\n pass\r\n\r\n @property\r\n def size_divisibility(self) -> int:\r\n \"\"\"\r\n Some backbones require the input height and width to be divisible by a\r\n specific integer. This is typically true for encoder / decoder type networks\r\n with lateral connection (e.g., FPN) for which feature maps need to match\r\n dimension in the \"bottom up\" and \"top down\" paths. Set to 0 if no specific\r\n input size divisibility is required.\r\n \"\"\"\r\n return 0\r\n\r\n @property\r\n def padding_constraints(self) -> Dict[str, int]:\r\n \"\"\"\r\n This property is a generalization of size_divisibility. Some backbones and training\r\n recipes require specific padding constraints, such as enforcing divisibility by a specific\r\n integer (e.g., FPN) or padding to a square (e.g., ViTDet with large-scale jitter\r\n in :paper:vitdet). `padding_constraints` contains these optional items like:\r\n {\r\n \"size_divisibility\": int,\r\n \"square_size\": int,\r\n # Future options are possible\r\n }\r\n `size_divisibility` will read from here if presented and `square_size` indicates the\r\n square padding size if `square_size` > 0.\r\n\r\n TODO: use type of Dict[str, int] to avoid torchscipt issues. The type of padding_constraints\r\n could be generalized as TypedDict (Python 3.8+) to support more types in the future.\r\n \"\"\"\r\n return {}\r\n\r\n def output_shape(self):\r\n \"\"\"\r\n Returns:\r\n dict[str->ShapeSpec]\r\n \"\"\"\r\n # this is a backward-compatible default\r\n return {\r\n name: ShapeSpec(\r\n channels=self._out_feature_channels[name], stride=self._out_feature_strides[name]\r\n )\r\n for name in self._out_features\r\n }\r" }, { "identifier": "Box2BoxTransform", "path": "annotator/oneformer/detectron2/modeling/box_regression.py", "snippet": "class Box2BoxTransform(object):\r\n \"\"\"\r\n The box-to-box transform defined in R-CNN. The transformation is parameterized\r\n by 4 deltas: (dx, dy, dw, dh). The transformation scales the box's width and height\r\n by exp(dw), exp(dh) and shifts a box's center by the offset (dx * width, dy * height).\r\n \"\"\"\r\n\r\n def __init__(\r\n self, weights: Tuple[float, float, float, float], scale_clamp: float = _DEFAULT_SCALE_CLAMP\r\n ):\r\n \"\"\"\r\n Args:\r\n weights (4-element tuple): Scaling factors that are applied to the\r\n (dx, dy, dw, dh) deltas. In Fast R-CNN, these were originally set\r\n such that the deltas have unit variance; now they are treated as\r\n hyperparameters of the system.\r\n scale_clamp (float): When predicting deltas, the predicted box scaling\r\n factors (dw and dh) are clamped such that they are <= scale_clamp.\r\n \"\"\"\r\n self.weights = weights\r\n self.scale_clamp = scale_clamp\r\n\r\n def get_deltas(self, src_boxes, target_boxes):\r\n \"\"\"\r\n Get box regression transformation deltas (dx, dy, dw, dh) that can be used\r\n to transform the `src_boxes` into the `target_boxes`. That is, the relation\r\n ``target_boxes == self.apply_deltas(deltas, src_boxes)`` is true (unless\r\n any delta is too large and is clamped).\r\n\r\n Args:\r\n src_boxes (Tensor): source boxes, e.g., object proposals\r\n target_boxes (Tensor): target of the transformation, e.g., ground-truth\r\n boxes.\r\n \"\"\"\r\n assert isinstance(src_boxes, torch.Tensor), type(src_boxes)\r\n assert isinstance(target_boxes, torch.Tensor), type(target_boxes)\r\n\r\n src_widths = src_boxes[:, 2] - src_boxes[:, 0]\r\n src_heights = src_boxes[:, 3] - src_boxes[:, 1]\r\n src_ctr_x = src_boxes[:, 0] + 0.5 * src_widths\r\n src_ctr_y = src_boxes[:, 1] + 0.5 * src_heights\r\n\r\n target_widths = target_boxes[:, 2] - target_boxes[:, 0]\r\n target_heights = target_boxes[:, 3] - target_boxes[:, 1]\r\n target_ctr_x = target_boxes[:, 0] + 0.5 * target_widths\r\n target_ctr_y = target_boxes[:, 1] + 0.5 * target_heights\r\n\r\n wx, wy, ww, wh = self.weights\r\n dx = wx * (target_ctr_x - src_ctr_x) / src_widths\r\n dy = wy * (target_ctr_y - src_ctr_y) / src_heights\r\n dw = ww * torch.log(target_widths / src_widths)\r\n dh = wh * torch.log(target_heights / src_heights)\r\n\r\n deltas = torch.stack((dx, dy, dw, dh), dim=1)\r\n assert (src_widths > 0).all().item(), \"Input boxes to Box2BoxTransform are not valid!\"\r\n return deltas\r\n\r\n def apply_deltas(self, deltas, boxes):\r\n \"\"\"\r\n Apply transformation `deltas` (dx, dy, dw, dh) to `boxes`.\r\n\r\n Args:\r\n deltas (Tensor): transformation deltas of shape (N, k*4), where k >= 1.\r\n deltas[i] represents k potentially different class-specific\r\n box transformations for the single box boxes[i].\r\n boxes (Tensor): boxes to transform, of shape (N, 4)\r\n \"\"\"\r\n deltas = deltas.float() # ensure fp32 for decoding precision\r\n boxes = boxes.to(deltas.dtype)\r\n\r\n widths = boxes[:, 2] - boxes[:, 0]\r\n heights = boxes[:, 3] - boxes[:, 1]\r\n ctr_x = boxes[:, 0] + 0.5 * widths\r\n ctr_y = boxes[:, 1] + 0.5 * heights\r\n\r\n wx, wy, ww, wh = self.weights\r\n dx = deltas[:, 0::4] / wx\r\n dy = deltas[:, 1::4] / wy\r\n dw = deltas[:, 2::4] / ww\r\n dh = deltas[:, 3::4] / wh\r\n\r\n # Prevent sending too large values into torch.exp()\r\n dw = torch.clamp(dw, max=self.scale_clamp)\r\n dh = torch.clamp(dh, max=self.scale_clamp)\r\n\r\n pred_ctr_x = dx * widths[:, None] + ctr_x[:, None]\r\n pred_ctr_y = dy * heights[:, None] + ctr_y[:, None]\r\n pred_w = torch.exp(dw) * widths[:, None]\r\n pred_h = torch.exp(dh) * heights[:, None]\r\n\r\n x1 = pred_ctr_x - 0.5 * pred_w\r\n y1 = pred_ctr_y - 0.5 * pred_h\r\n x2 = pred_ctr_x + 0.5 * pred_w\r\n y2 = pred_ctr_y + 0.5 * pred_h\r\n pred_boxes = torch.stack((x1, y1, x2, y2), dim=-1)\r\n return pred_boxes.reshape(deltas.shape)\r" }, { "identifier": "_dense_box_regression_loss", "path": "annotator/oneformer/detectron2/modeling/box_regression.py", "snippet": "def _dense_box_regression_loss(\r\n anchors: List[Union[Boxes, torch.Tensor]],\r\n box2box_transform: Box2BoxTransform,\r\n pred_anchor_deltas: List[torch.Tensor],\r\n gt_boxes: List[torch.Tensor],\r\n fg_mask: torch.Tensor,\r\n box_reg_loss_type=\"smooth_l1\",\r\n smooth_l1_beta=0.0,\r\n):\r\n \"\"\"\r\n Compute loss for dense multi-level box regression.\r\n Loss is accumulated over ``fg_mask``.\r\n\r\n Args:\r\n anchors: #lvl anchor boxes, each is (HixWixA, 4)\r\n pred_anchor_deltas: #lvl predictions, each is (N, HixWixA, 4)\r\n gt_boxes: N ground truth boxes, each has shape (R, 4) (R = sum(Hi * Wi * A))\r\n fg_mask: the foreground boolean mask of shape (N, R) to compute loss on\r\n box_reg_loss_type (str): Loss type to use. Supported losses: \"smooth_l1\", \"giou\",\r\n \"diou\", \"ciou\".\r\n smooth_l1_beta (float): beta parameter for the smooth L1 regression loss. Default to\r\n use L1 loss. Only used when `box_reg_loss_type` is \"smooth_l1\"\r\n \"\"\"\r\n if isinstance(anchors[0], Boxes):\r\n anchors = type(anchors[0]).cat(anchors).tensor # (R, 4)\r\n else:\r\n anchors = cat(anchors)\r\n if box_reg_loss_type == \"smooth_l1\":\r\n gt_anchor_deltas = [box2box_transform.get_deltas(anchors, k) for k in gt_boxes]\r\n gt_anchor_deltas = torch.stack(gt_anchor_deltas) # (N, R, 4)\r\n loss_box_reg = smooth_l1_loss(\r\n cat(pred_anchor_deltas, dim=1)[fg_mask],\r\n gt_anchor_deltas[fg_mask],\r\n beta=smooth_l1_beta,\r\n reduction=\"sum\",\r\n )\r\n elif box_reg_loss_type == \"giou\":\r\n pred_boxes = [\r\n box2box_transform.apply_deltas(k, anchors) for k in cat(pred_anchor_deltas, dim=1)\r\n ]\r\n loss_box_reg = giou_loss(\r\n torch.stack(pred_boxes)[fg_mask], torch.stack(gt_boxes)[fg_mask], reduction=\"sum\"\r\n )\r\n elif box_reg_loss_type == \"diou\":\r\n pred_boxes = [\r\n box2box_transform.apply_deltas(k, anchors) for k in cat(pred_anchor_deltas, dim=1)\r\n ]\r\n loss_box_reg = diou_loss(\r\n torch.stack(pred_boxes)[fg_mask], torch.stack(gt_boxes)[fg_mask], reduction=\"sum\"\r\n )\r\n elif box_reg_loss_type == \"ciou\":\r\n pred_boxes = [\r\n box2box_transform.apply_deltas(k, anchors) for k in cat(pred_anchor_deltas, dim=1)\r\n ]\r\n loss_box_reg = ciou_loss(\r\n torch.stack(pred_boxes)[fg_mask], torch.stack(gt_boxes)[fg_mask], reduction=\"sum\"\r\n )\r\n else:\r\n raise ValueError(f\"Invalid dense box regression loss type '{box_reg_loss_type}'\")\r\n return loss_box_reg\r" }, { "identifier": "Matcher", "path": "annotator/oneformer/detectron2/modeling/matcher.py", "snippet": "class Matcher(object):\r\n \"\"\"\r\n This class assigns to each predicted \"element\" (e.g., a box) a ground-truth\r\n element. Each predicted element will have exactly zero or one matches; each\r\n ground-truth element may be matched to zero or more predicted elements.\r\n\r\n The matching is determined by the MxN match_quality_matrix, that characterizes\r\n how well each (ground-truth, prediction)-pair match each other. For example,\r\n if the elements are boxes, this matrix may contain box intersection-over-union\r\n overlap values.\r\n\r\n The matcher returns (a) a vector of length N containing the index of the\r\n ground-truth element m in [0, M) that matches to prediction n in [0, N).\r\n (b) a vector of length N containing the labels for each prediction.\r\n \"\"\"\r\n\r\n def __init__(\r\n self, thresholds: List[float], labels: List[int], allow_low_quality_matches: bool = False\r\n ):\r\n \"\"\"\r\n Args:\r\n thresholds (list): a list of thresholds used to stratify predictions\r\n into levels.\r\n labels (list): a list of values to label predictions belonging at\r\n each level. A label can be one of {-1, 0, 1} signifying\r\n {ignore, negative class, positive class}, respectively.\r\n allow_low_quality_matches (bool): if True, produce additional matches\r\n for predictions with maximum match quality lower than high_threshold.\r\n See set_low_quality_matches_ for more details.\r\n\r\n For example,\r\n thresholds = [0.3, 0.5]\r\n labels = [0, -1, 1]\r\n All predictions with iou < 0.3 will be marked with 0 and\r\n thus will be considered as false positives while training.\r\n All predictions with 0.3 <= iou < 0.5 will be marked with -1 and\r\n thus will be ignored.\r\n All predictions with 0.5 <= iou will be marked with 1 and\r\n thus will be considered as true positives.\r\n \"\"\"\r\n # Add -inf and +inf to first and last position in thresholds\r\n thresholds = thresholds[:]\r\n assert thresholds[0] > 0\r\n thresholds.insert(0, -float(\"inf\"))\r\n thresholds.append(float(\"inf\"))\r\n # Currently torchscript does not support all + generator\r\n assert all([low <= high for (low, high) in zip(thresholds[:-1], thresholds[1:])])\r\n assert all([l in [-1, 0, 1] for l in labels])\r\n assert len(labels) == len(thresholds) - 1\r\n self.thresholds = thresholds\r\n self.labels = labels\r\n self.allow_low_quality_matches = allow_low_quality_matches\r\n\r\n def __call__(self, match_quality_matrix):\r\n \"\"\"\r\n Args:\r\n match_quality_matrix (Tensor[float]): an MxN tensor, containing the\r\n pairwise quality between M ground-truth elements and N predicted\r\n elements. All elements must be >= 0 (due to the us of `torch.nonzero`\r\n for selecting indices in :meth:`set_low_quality_matches_`).\r\n\r\n Returns:\r\n matches (Tensor[int64]): a vector of length N, where matches[i] is a matched\r\n ground-truth index in [0, M)\r\n match_labels (Tensor[int8]): a vector of length N, where pred_labels[i] indicates\r\n whether a prediction is a true or false positive or ignored\r\n \"\"\"\r\n assert match_quality_matrix.dim() == 2\r\n if match_quality_matrix.numel() == 0:\r\n default_matches = match_quality_matrix.new_full(\r\n (match_quality_matrix.size(1),), 0, dtype=torch.int64\r\n )\r\n # When no gt boxes exist, we define IOU = 0 and therefore set labels\r\n # to `self.labels[0]`, which usually defaults to background class 0\r\n # To choose to ignore instead, can make labels=[-1,0,-1,1] + set appropriate thresholds\r\n default_match_labels = match_quality_matrix.new_full(\r\n (match_quality_matrix.size(1),), self.labels[0], dtype=torch.int8\r\n )\r\n return default_matches, default_match_labels\r\n\r\n assert torch.all(match_quality_matrix >= 0)\r\n\r\n # match_quality_matrix is M (gt) x N (predicted)\r\n # Max over gt elements (dim 0) to find best gt candidate for each prediction\r\n matched_vals, matches = match_quality_matrix.max(dim=0)\r\n\r\n match_labels = matches.new_full(matches.size(), 1, dtype=torch.int8)\r\n\r\n for (l, low, high) in zip(self.labels, self.thresholds[:-1], self.thresholds[1:]):\r\n low_high = (matched_vals >= low) & (matched_vals < high)\r\n match_labels[low_high] = l\r\n\r\n if self.allow_low_quality_matches:\r\n self.set_low_quality_matches_(match_labels, match_quality_matrix)\r\n\r\n return matches, match_labels\r\n\r\n def set_low_quality_matches_(self, match_labels, match_quality_matrix):\r\n \"\"\"\r\n Produce additional matches for predictions that have only low-quality matches.\r\n Specifically, for each ground-truth G find the set of predictions that have\r\n maximum overlap with it (including ties); for each prediction in that set, if\r\n it is unmatched, then match it to the ground-truth G.\r\n\r\n This function implements the RPN assignment case (i) in Sec. 3.1.2 of\r\n :paper:`Faster R-CNN`.\r\n \"\"\"\r\n # For each gt, find the prediction with which it has highest quality\r\n highest_quality_foreach_gt, _ = match_quality_matrix.max(dim=1)\r\n # Find the highest quality match available, even if it is low, including ties.\r\n # Note that the matches qualities must be positive due to the use of\r\n # `torch.nonzero`.\r\n _, pred_inds_with_highest_quality = nonzero_tuple(\r\n match_quality_matrix == highest_quality_foreach_gt[:, None]\r\n )\r\n # If an anchor was labeled positive only due to a low-quality match\r\n # with gt_A, but it has larger overlap with gt_B, it's matched index will still be gt_B.\r\n # This follows the implementation in Detectron, and is found to have no significant impact.\r\n match_labels[pred_inds_with_highest_quality] = 1\r" }, { "identifier": "META_ARCH_REGISTRY", "path": "annotator/oneformer/detectron2/modeling/meta_arch/build.py", "snippet": "META_ARCH_REGISTRY = Registry(\"META_ARCH\") # noqa F401 isort:skip\r" }, { "identifier": "DenseDetector", "path": "annotator/oneformer/detectron2/modeling/meta_arch/dense_detector.py", "snippet": "class DenseDetector(nn.Module):\r\n \"\"\"\r\n Base class for dense detector. We define a dense detector as a fully-convolutional model that\r\n makes per-pixel (i.e. dense) predictions.\r\n \"\"\"\r\n\r\n def __init__(\r\n self,\r\n backbone: Backbone,\r\n head: nn.Module,\r\n head_in_features: Optional[List[str]] = None,\r\n *,\r\n pixel_mean,\r\n pixel_std,\r\n ):\r\n \"\"\"\r\n Args:\r\n backbone: backbone module\r\n head: head module\r\n head_in_features: backbone features to use in head. Default to all backbone features.\r\n pixel_mean (Tuple[float]):\r\n Values to be used for image normalization (BGR order).\r\n To train on images of different number of channels, set different mean & std.\r\n Default values are the mean pixel value from ImageNet: [103.53, 116.28, 123.675]\r\n pixel_std (Tuple[float]):\r\n When using pre-trained models in Detectron1 or any MSRA models,\r\n std has been absorbed into its conv1 weights, so the std needs to be set 1.\r\n Otherwise, you can use [57.375, 57.120, 58.395] (ImageNet std)\r\n \"\"\"\r\n super().__init__()\r\n\r\n self.backbone = backbone\r\n self.head = head\r\n if head_in_features is None:\r\n shapes = self.backbone.output_shape()\r\n self.head_in_features = sorted(shapes.keys(), key=lambda x: shapes[x].stride)\r\n else:\r\n self.head_in_features = head_in_features\r\n self.register_buffer(\"pixel_mean\", torch.tensor(pixel_mean).view(-1, 1, 1), False)\r\n self.register_buffer(\"pixel_std\", torch.tensor(pixel_std).view(-1, 1, 1), False)\r\n\r\n @property\r\n def device(self):\r\n return self.pixel_mean.device\r\n\r\n def _move_to_current_device(self, x):\r\n return move_device_like(x, self.pixel_mean)\r\n\r\n def forward(self, batched_inputs: List[Dict[str, Tensor]]):\r\n \"\"\"\r\n Args:\r\n batched_inputs: a list, batched outputs of :class:`DatasetMapper` .\r\n Each item in the list contains the inputs for one image.\r\n For now, each item in the list is a dict that contains:\r\n\r\n * image: Tensor, image in (C, H, W) format.\r\n * instances: Instances\r\n\r\n Other information that's included in the original dicts, such as:\r\n\r\n * \"height\", \"width\" (int): the output resolution of the model, used in inference.\r\n See :meth:`postprocess` for details.\r\n\r\n Returns:\r\n In training, dict[str, Tensor]: mapping from a named loss to a tensor storing the\r\n loss. Used during training only. In inference, the standard output format, described\r\n in :doc:`/tutorials/models`.\r\n \"\"\"\r\n images = self.preprocess_image(batched_inputs)\r\n features = self.backbone(images.tensor)\r\n features = [features[f] for f in self.head_in_features]\r\n predictions = self.head(features)\r\n\r\n if self.training:\r\n assert not torch.jit.is_scripting(), \"Not supported\"\r\n assert \"instances\" in batched_inputs[0], \"Instance annotations are missing in training!\"\r\n gt_instances = [x[\"instances\"].to(self.device) for x in batched_inputs]\r\n return self.forward_training(images, features, predictions, gt_instances)\r\n else:\r\n results = self.forward_inference(images, features, predictions)\r\n if torch.jit.is_scripting():\r\n return results\r\n\r\n processed_results = []\r\n for results_per_image, input_per_image, image_size in zip(\r\n results, batched_inputs, images.image_sizes\r\n ):\r\n height = input_per_image.get(\"height\", image_size[0])\r\n width = input_per_image.get(\"width\", image_size[1])\r\n r = detector_postprocess(results_per_image, height, width)\r\n processed_results.append({\"instances\": r})\r\n return processed_results\r\n\r\n def forward_training(self, images, features, predictions, gt_instances):\r\n raise NotImplementedError()\r\n\r\n def preprocess_image(self, batched_inputs: List[Dict[str, Tensor]]):\r\n \"\"\"\r\n Normalize, pad and batch the input images.\r\n \"\"\"\r\n images = [self._move_to_current_device(x[\"image\"]) for x in batched_inputs]\r\n images = [(x - self.pixel_mean) / self.pixel_std for x in images]\r\n images = ImageList.from_tensors(\r\n images,\r\n self.backbone.size_divisibility,\r\n padding_constraints=self.backbone.padding_constraints,\r\n )\r\n return images\r\n\r\n def _transpose_dense_predictions(\r\n self, predictions: List[List[Tensor]], dims_per_anchor: List[int]\r\n ) -> List[List[Tensor]]:\r\n \"\"\"\r\n Transpose the dense per-level predictions.\r\n\r\n Args:\r\n predictions: a list of outputs, each is a list of per-level\r\n predictions with shape (N, Ai x K, Hi, Wi), where N is the\r\n number of images, Ai is the number of anchors per location on\r\n level i, K is the dimension of predictions per anchor.\r\n dims_per_anchor: the value of K for each predictions. e.g. 4 for\r\n box prediction, #classes for classification prediction.\r\n\r\n Returns:\r\n List[List[Tensor]]: each prediction is transposed to (N, Hi x Wi x Ai, K).\r\n \"\"\"\r\n assert len(predictions) == len(dims_per_anchor)\r\n res: List[List[Tensor]] = []\r\n for pred, dim_per_anchor in zip(predictions, dims_per_anchor):\r\n pred = [permute_to_N_HWA_K(x, dim_per_anchor) for x in pred]\r\n res.append(pred)\r\n return res\r\n\r\n def _ema_update(self, name: str, value: float, initial_value: float, momentum: float = 0.9):\r\n \"\"\"\r\n Apply EMA update to `self.name` using `value`.\r\n\r\n This is mainly used for loss normalizer. In Detectron1, loss is normalized by number\r\n of foreground samples in the batch. When batch size is 1 per GPU, #foreground has a\r\n large variance and using it lead to lower performance. Therefore we maintain an EMA of\r\n #foreground to stabilize the normalizer.\r\n\r\n Args:\r\n name: name of the normalizer\r\n value: the new value to update\r\n initial_value: the initial value to start with\r\n momentum: momentum of EMA\r\n\r\n Returns:\r\n float: the updated EMA value\r\n \"\"\"\r\n if hasattr(self, name):\r\n old = getattr(self, name)\r\n else:\r\n old = initial_value\r\n new = old * momentum + value * (1 - momentum)\r\n setattr(self, name, new)\r\n return new\r\n\r\n def _decode_per_level_predictions(\r\n self,\r\n anchors: Boxes,\r\n pred_scores: Tensor,\r\n pred_deltas: Tensor,\r\n score_thresh: float,\r\n topk_candidates: int,\r\n image_size: Tuple[int, int],\r\n ) -> Instances:\r\n \"\"\"\r\n Decode boxes and classification predictions of one featuer level, by\r\n the following steps:\r\n 1. filter the predictions based on score threshold and top K scores.\r\n 2. transform the box regression outputs\r\n 3. return the predicted scores, classes and boxes\r\n\r\n Args:\r\n anchors: Boxes, anchor for this feature level\r\n pred_scores: HxWxA,K\r\n pred_deltas: HxWxA,4\r\n\r\n Returns:\r\n Instances: with field \"scores\", \"pred_boxes\", \"pred_classes\".\r\n \"\"\"\r\n # Apply two filtering to make NMS faster.\r\n # 1. Keep boxes with confidence score higher than threshold\r\n keep_idxs = pred_scores > score_thresh\r\n pred_scores = pred_scores[keep_idxs]\r\n topk_idxs = torch.nonzero(keep_idxs) # Kx2\r\n\r\n # 2. Keep top k top scoring boxes only\r\n topk_idxs_size = topk_idxs.shape[0]\r\n if isinstance(topk_idxs_size, Tensor):\r\n # It's a tensor in tracing\r\n num_topk = torch.clamp(topk_idxs_size, max=topk_candidates)\r\n else:\r\n num_topk = min(topk_idxs_size, topk_candidates)\r\n pred_scores, idxs = pred_scores.topk(num_topk)\r\n topk_idxs = topk_idxs[idxs]\r\n\r\n anchor_idxs, classes_idxs = topk_idxs.unbind(dim=1)\r\n\r\n pred_boxes = self.box2box_transform.apply_deltas(\r\n pred_deltas[anchor_idxs], anchors.tensor[anchor_idxs]\r\n )\r\n return Instances(\r\n image_size, pred_boxes=Boxes(pred_boxes), scores=pred_scores, pred_classes=classes_idxs\r\n )\r\n\r\n def _decode_multi_level_predictions(\r\n self,\r\n anchors: List[Boxes],\r\n pred_scores: List[Tensor],\r\n pred_deltas: List[Tensor],\r\n score_thresh: float,\r\n topk_candidates: int,\r\n image_size: Tuple[int, int],\r\n ) -> Instances:\r\n \"\"\"\r\n Run `_decode_per_level_predictions` for all feature levels and concat the results.\r\n \"\"\"\r\n predictions = [\r\n self._decode_per_level_predictions(\r\n anchors_i,\r\n box_cls_i,\r\n box_reg_i,\r\n self.test_score_thresh,\r\n self.test_topk_candidates,\r\n image_size,\r\n )\r\n # Iterate over every feature level\r\n for box_cls_i, box_reg_i, anchors_i in zip(pred_scores, pred_deltas, anchors)\r\n ]\r\n return predictions[0].cat(predictions) # 'Instances.cat' is not scriptale but this is\r\n\r\n def visualize_training(self, batched_inputs, results):\r\n \"\"\"\r\n A function used to visualize ground truth images and final network predictions.\r\n It shows ground truth bounding boxes on the original image and up to 20\r\n predicted object bounding boxes on the original image.\r\n\r\n Args:\r\n batched_inputs (list): a list that contains input to the model.\r\n results (List[Instances]): a list of #images elements returned by forward_inference().\r\n \"\"\"\r\n from annotator.oneformer.detectron2.utils.visualizer import Visualizer\r\n\r\n assert len(batched_inputs) == len(\r\n results\r\n ), \"Cannot visualize inputs and results of different sizes\"\r\n storage = get_event_storage()\r\n max_boxes = 20\r\n\r\n image_index = 0 # only visualize a single image\r\n img = batched_inputs[image_index][\"image\"]\r\n img = convert_image_to_rgb(img.permute(1, 2, 0), self.input_format)\r\n v_gt = Visualizer(img, None)\r\n v_gt = v_gt.overlay_instances(boxes=batched_inputs[image_index][\"instances\"].gt_boxes)\r\n anno_img = v_gt.get_image()\r\n processed_results = detector_postprocess(results[image_index], img.shape[0], img.shape[1])\r\n predicted_boxes = processed_results.pred_boxes.tensor.detach().cpu().numpy()\r\n\r\n v_pred = Visualizer(img, None)\r\n v_pred = v_pred.overlay_instances(boxes=predicted_boxes[0:max_boxes])\r\n prop_img = v_pred.get_image()\r\n vis_img = np.vstack((anno_img, prop_img))\r\n vis_img = vis_img.transpose(2, 0, 1)\r\n vis_name = f\"Top: GT bounding boxes; Bottom: {max_boxes} Highest Scoring Results\"\r\n storage.put_image(vis_name, vis_img)\r" }, { "identifier": "permute_to_N_HWA_K", "path": "annotator/oneformer/detectron2/modeling/meta_arch/dense_detector.py", "snippet": "def permute_to_N_HWA_K(tensor, K: int):\r\n \"\"\"\r\n Transpose/reshape a tensor from (N, (Ai x K), H, W) to (N, (HxWxAi), K)\r\n \"\"\"\r\n assert tensor.dim() == 4, tensor.shape\r\n N, _, H, W = tensor.shape\r\n tensor = tensor.view(N, -1, K, H, W)\r\n tensor = tensor.permute(0, 3, 4, 1, 2)\r\n tensor = tensor.reshape(N, -1, K) # Size=(N,HWA,K)\r\n return tensor\r" } ]
import logging import math import torch from typing import List, Tuple from fvcore.nn import sigmoid_focal_loss_jit from torch import Tensor, nn from torch.nn import functional as F from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import CycleBatchNormList, ShapeSpec, batched_nms, cat, get_norm from annotator.oneformer.detectron2.structures import Boxes, ImageList, Instances, pairwise_iou from annotator.oneformer.detectron2.utils.events import get_event_storage from ..anchor_generator import build_anchor_generator from ..backbone import Backbone, build_backbone from ..box_regression import Box2BoxTransform, _dense_box_regression_loss from ..matcher import Matcher from .build import META_ARCH_REGISTRY from .dense_detector import DenseDetector, permute_to_N_HWA_K # noqa
15,594
# Copyright (c) Facebook, Inc. and its affiliates. __all__ = ["RetinaNet"] logger = logging.getLogger(__name__) @META_ARCH_REGISTRY.register() class RetinaNet(DenseDetector): """ Implement RetinaNet in :paper:`RetinaNet`. """ @configurable def __init__( self, *, backbone: Backbone, head: nn.Module, head_in_features, anchor_generator, box2box_transform, anchor_matcher, num_classes, focal_loss_alpha=0.25, focal_loss_gamma=2.0, smooth_l1_beta=0.0, box_reg_loss_type="smooth_l1", test_score_thresh=0.05, test_topk_candidates=1000, test_nms_thresh=0.5, max_detections_per_image=100, pixel_mean, pixel_std, vis_period=0, input_format="BGR", ): """ NOTE: this interface is experimental. Args: backbone: a backbone module, must follow detectron2's backbone interface head (nn.Module): a module that predicts logits and regression deltas for each level from a list of per-level features head_in_features (Tuple[str]): Names of the input feature maps to be used in head anchor_generator (nn.Module): a module that creates anchors from a list of features. Usually an instance of :class:`AnchorGenerator` box2box_transform (Box2BoxTransform): defines the transform from anchors boxes to instance boxes anchor_matcher (Matcher): label the anchors by matching them with ground truth. num_classes (int): number of classes. Used to label background proposals. # Loss parameters: focal_loss_alpha (float): focal_loss_alpha focal_loss_gamma (float): focal_loss_gamma smooth_l1_beta (float): smooth_l1_beta box_reg_loss_type (str): Options are "smooth_l1", "giou", "diou", "ciou" # Inference parameters: test_score_thresh (float): Inference cls score threshold, only anchors with score > INFERENCE_TH are considered for inference (to improve speed) test_topk_candidates (int): Select topk candidates before NMS test_nms_thresh (float): Overlap threshold used for non-maximum suppression (suppress boxes with IoU >= this threshold) max_detections_per_image (int): Maximum number of detections to return per image during inference (100 is based on the limit established for the COCO dataset). pixel_mean, pixel_std: see :class:`DenseDetector`. """ super().__init__( backbone, head, head_in_features, pixel_mean=pixel_mean, pixel_std=pixel_std ) self.num_classes = num_classes # Anchors self.anchor_generator = anchor_generator self.box2box_transform = box2box_transform self.anchor_matcher = anchor_matcher # Loss parameters: self.focal_loss_alpha = focal_loss_alpha self.focal_loss_gamma = focal_loss_gamma self.smooth_l1_beta = smooth_l1_beta self.box_reg_loss_type = box_reg_loss_type # Inference parameters: self.test_score_thresh = test_score_thresh self.test_topk_candidates = test_topk_candidates self.test_nms_thresh = test_nms_thresh self.max_detections_per_image = max_detections_per_image # Vis parameters self.vis_period = vis_period self.input_format = input_format @classmethod def from_config(cls, cfg):
# Copyright (c) Facebook, Inc. and its affiliates. __all__ = ["RetinaNet"] logger = logging.getLogger(__name__) @META_ARCH_REGISTRY.register() class RetinaNet(DenseDetector): """ Implement RetinaNet in :paper:`RetinaNet`. """ @configurable def __init__( self, *, backbone: Backbone, head: nn.Module, head_in_features, anchor_generator, box2box_transform, anchor_matcher, num_classes, focal_loss_alpha=0.25, focal_loss_gamma=2.0, smooth_l1_beta=0.0, box_reg_loss_type="smooth_l1", test_score_thresh=0.05, test_topk_candidates=1000, test_nms_thresh=0.5, max_detections_per_image=100, pixel_mean, pixel_std, vis_period=0, input_format="BGR", ): """ NOTE: this interface is experimental. Args: backbone: a backbone module, must follow detectron2's backbone interface head (nn.Module): a module that predicts logits and regression deltas for each level from a list of per-level features head_in_features (Tuple[str]): Names of the input feature maps to be used in head anchor_generator (nn.Module): a module that creates anchors from a list of features. Usually an instance of :class:`AnchorGenerator` box2box_transform (Box2BoxTransform): defines the transform from anchors boxes to instance boxes anchor_matcher (Matcher): label the anchors by matching them with ground truth. num_classes (int): number of classes. Used to label background proposals. # Loss parameters: focal_loss_alpha (float): focal_loss_alpha focal_loss_gamma (float): focal_loss_gamma smooth_l1_beta (float): smooth_l1_beta box_reg_loss_type (str): Options are "smooth_l1", "giou", "diou", "ciou" # Inference parameters: test_score_thresh (float): Inference cls score threshold, only anchors with score > INFERENCE_TH are considered for inference (to improve speed) test_topk_candidates (int): Select topk candidates before NMS test_nms_thresh (float): Overlap threshold used for non-maximum suppression (suppress boxes with IoU >= this threshold) max_detections_per_image (int): Maximum number of detections to return per image during inference (100 is based on the limit established for the COCO dataset). pixel_mean, pixel_std: see :class:`DenseDetector`. """ super().__init__( backbone, head, head_in_features, pixel_mean=pixel_mean, pixel_std=pixel_std ) self.num_classes = num_classes # Anchors self.anchor_generator = anchor_generator self.box2box_transform = box2box_transform self.anchor_matcher = anchor_matcher # Loss parameters: self.focal_loss_alpha = focal_loss_alpha self.focal_loss_gamma = focal_loss_gamma self.smooth_l1_beta = smooth_l1_beta self.box_reg_loss_type = box_reg_loss_type # Inference parameters: self.test_score_thresh = test_score_thresh self.test_topk_candidates = test_topk_candidates self.test_nms_thresh = test_nms_thresh self.max_detections_per_image = max_detections_per_image # Vis parameters self.vis_period = vis_period self.input_format = input_format @classmethod def from_config(cls, cfg):
backbone = build_backbone(cfg)
12
2023-12-05 02:51:53+00:00
24k
DiffusionLight/DiffusionLight
relighting/inpainter.py
[ { "identifier": "CustomStableDiffusionControlNetInpaintPipeline", "path": "relighting/pipeline.py", "snippet": "class CustomStableDiffusionControlNetInpaintPipeline(StableDiffusionControlNetInpaintPipeline):\n @torch.no_grad()\n def __call__(\n self,\n prompt: Union[str, List[str]] = None,\n image: PipelineImageInput = None,\n mask_image: PipelineImageInput = None,\n control_image: PipelineImageInput = None,\n height: Optional[int] = None,\n width: Optional[int] = None,\n strength: float = 1.0,\n num_inference_steps: int = 50,\n guidance_scale: float = 7.5,\n negative_prompt: Optional[Union[str, List[str]]] = None,\n num_images_per_prompt: Optional[int] = 1,\n eta: float = 0.0,\n generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,\n latents: Optional[torch.FloatTensor] = None,\n prompt_embeds: Optional[torch.FloatTensor] = None,\n negative_prompt_embeds: Optional[torch.FloatTensor] = None,\n output_type: Optional[str] = \"pil\",\n return_dict: bool = True,\n callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,\n callback_steps: int = 1,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n controlnet_conditioning_scale: Union[float, List[float]] = 0.5,\n guess_mode: bool = False,\n control_guidance_start: Union[float, List[float]] = 0.0,\n control_guidance_end: Union[float, List[float]] = 1.0,\n newx: int = 0,\n newy: int = 0,\n newr: int = 256,\n current_seed=0,\n use_noise_moving=True,\n ):\n # OVERWRITE METHODS\n self.prepare_mask_latents = custom_prepare_mask_latents.__get__(self, CustomStableDiffusionControlNetInpaintPipeline)\n self.prepare_latents = custom_prepare_latents.__get__(self, CustomStableDiffusionControlNetInpaintPipeline)\n\n controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet\n\n # align format for control guidance\n if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):\n control_guidance_start = len(control_guidance_end) * [control_guidance_start]\n elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):\n control_guidance_end = len(control_guidance_start) * [control_guidance_end]\n elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):\n mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1\n control_guidance_start, control_guidance_end = mult * [control_guidance_start], mult * [\n control_guidance_end\n ]\n\n # 1. Check inputs. Raise error if not correct\n self.check_inputs(\n prompt,\n control_image,\n height,\n width,\n callback_steps,\n negative_prompt,\n prompt_embeds,\n negative_prompt_embeds,\n controlnet_conditioning_scale,\n control_guidance_start,\n control_guidance_end,\n )\n\n # 2. Define call parameters\n if prompt is not None and isinstance(prompt, str):\n batch_size = 1\n elif prompt is not None and isinstance(prompt, list):\n batch_size = len(prompt)\n else:\n batch_size = prompt_embeds.shape[0]\n\n device = self._execution_device\n # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)\n # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`\n # corresponds to doing no classifier free guidance.\n do_classifier_free_guidance = guidance_scale > 1.0\n\n if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):\n controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)\n\n global_pool_conditions = (\n controlnet.config.global_pool_conditions\n if isinstance(controlnet, ControlNetModel)\n else controlnet.nets[0].config.global_pool_conditions\n )\n guess_mode = guess_mode or global_pool_conditions\n\n # 3. Encode input prompt\n text_encoder_lora_scale = (\n cross_attention_kwargs.get(\"scale\", None) if cross_attention_kwargs is not None else None\n )\n prompt_embeds, negative_prompt_embeds = self.encode_prompt(\n prompt,\n device,\n num_images_per_prompt,\n do_classifier_free_guidance,\n negative_prompt,\n prompt_embeds=prompt_embeds,\n negative_prompt_embeds=negative_prompt_embeds,\n lora_scale=text_encoder_lora_scale,\n )\n # For classifier free guidance, we need to do two forward passes.\n # Here we concatenate the unconditional and text embeddings into a single batch\n # to avoid doing two forward passes\n if do_classifier_free_guidance:\n prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])\n\n # 4. Prepare image\n if isinstance(controlnet, ControlNetModel):\n control_image = self.prepare_control_image(\n image=control_image,\n width=width,\n height=height,\n batch_size=batch_size * num_images_per_prompt,\n num_images_per_prompt=num_images_per_prompt,\n device=device,\n dtype=controlnet.dtype,\n do_classifier_free_guidance=do_classifier_free_guidance,\n guess_mode=guess_mode,\n )\n elif isinstance(controlnet, MultiControlNetModel):\n control_images = []\n\n for control_image_ in control_image:\n control_image_ = self.prepare_control_image(\n image=control_image_,\n width=width,\n height=height,\n batch_size=batch_size * num_images_per_prompt,\n num_images_per_prompt=num_images_per_prompt,\n device=device,\n dtype=controlnet.dtype,\n do_classifier_free_guidance=do_classifier_free_guidance,\n guess_mode=guess_mode,\n )\n\n control_images.append(control_image_)\n\n control_image = control_images\n else:\n assert False\n\n # 4. Preprocess mask and image - resizes image and mask w.r.t height and width\n init_image = self.image_processor.preprocess(image, height=height, width=width)\n init_image = init_image.to(dtype=torch.float32)\n\n mask = self.mask_processor.preprocess(mask_image, height=height, width=width)\n\n masked_image = init_image * (mask < 0.5)\n _, _, height, width = init_image.shape\n\n # 5. Prepare timesteps\n self.scheduler.set_timesteps(num_inference_steps, device=device)\n timesteps, num_inference_steps = self.get_timesteps(\n num_inference_steps=num_inference_steps, strength=strength, device=device\n )\n # at which timestep to set the initial noise (n.b. 50% if strength is 0.5)\n latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)\n # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise\n is_strength_max = strength == 1.0\n\n # 6. Prepare latent variables\n num_channels_latents = self.vae.config.latent_channels\n num_channels_unet = self.unet.config.in_channels\n return_image_latents = num_channels_unet == 4\n\n # EDITED HERE\n latents_outputs = self.prepare_latents(\n batch_size * num_images_per_prompt,\n num_channels_latents,\n height,\n width,\n prompt_embeds.dtype,\n device,\n generator,\n latents,\n image=init_image,\n timestep=latent_timestep,\n is_strength_max=is_strength_max,\n return_noise=True,\n return_image_latents=return_image_latents,\n newx=newx,\n newy=newy,\n newr=newr,\n current_seed=current_seed,\n use_noise_moving=use_noise_moving,\n )\n\n if return_image_latents:\n latents, noise, image_latents = latents_outputs\n else:\n latents, noise = latents_outputs\n\n # 7. Prepare mask latent variables\n mask, masked_image_latents = self.prepare_mask_latents(\n mask,\n masked_image,\n batch_size * num_images_per_prompt,\n height,\n width,\n prompt_embeds.dtype,\n device,\n generator,\n do_classifier_free_guidance,\n )\n\n # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline\n extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)\n\n # 7.1 Create tensor stating which controlnets to keep\n controlnet_keep = []\n for i in range(len(timesteps)):\n keeps = [\n 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)\n for s, e in zip(control_guidance_start, control_guidance_end)\n ]\n controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)\n\n # 8. Denoising loop\n num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order\n with self.progress_bar(total=num_inference_steps) as progress_bar:\n for i, t in enumerate(timesteps):\n # expand the latents if we are doing classifier free guidance\n latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents\n latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)\n\n # controlnet(s) inference\n if guess_mode and do_classifier_free_guidance:\n # Infer ControlNet only for the conditional batch.\n control_model_input = latents\n control_model_input = self.scheduler.scale_model_input(control_model_input, t)\n controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]\n else:\n control_model_input = latent_model_input\n controlnet_prompt_embeds = prompt_embeds\n\n if isinstance(controlnet_keep[i], list):\n cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]\n else:\n controlnet_cond_scale = controlnet_conditioning_scale\n if isinstance(controlnet_cond_scale, list):\n controlnet_cond_scale = controlnet_cond_scale[0]\n cond_scale = controlnet_cond_scale * controlnet_keep[i]\n\n down_block_res_samples, mid_block_res_sample = self.controlnet(\n control_model_input,\n t,\n encoder_hidden_states=controlnet_prompt_embeds,\n controlnet_cond=control_image,\n conditioning_scale=cond_scale,\n guess_mode=guess_mode,\n return_dict=False,\n )\n\n if guess_mode and do_classifier_free_guidance:\n # Infered ControlNet only for the conditional batch.\n # To apply the output of ControlNet to both the unconditional and conditional batches,\n # add 0 to the unconditional batch to keep it unchanged.\n down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]\n mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])\n\n # predict the noise residual\n if num_channels_unet == 9:\n latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)\n\n noise_pred = self.unet(\n latent_model_input,\n t,\n encoder_hidden_states=prompt_embeds,\n cross_attention_kwargs=cross_attention_kwargs,\n down_block_additional_residuals=down_block_res_samples,\n mid_block_additional_residual=mid_block_res_sample,\n return_dict=False,\n )[0]\n\n # perform guidance\n if do_classifier_free_guidance:\n noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)\n noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)\n\n # compute the previous noisy sample x_t -> x_t-1\n latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]\n\n if num_channels_unet == 4:\n init_latents_proper = image_latents[:1]\n init_mask = mask[:1]\n\n if i < len(timesteps) - 1:\n noise_timestep = timesteps[i + 1]\n init_latents_proper = self.scheduler.add_noise(\n init_latents_proper, noise, torch.tensor([noise_timestep])\n )\n\n latents = (1 - init_mask) * init_latents_proper + init_mask * latents\n\n # call the callback, if provided\n if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):\n progress_bar.update()\n if callback is not None and i % callback_steps == 0:\n callback(i, t, latents)\n\n # If we do sequential model offloading, let's offload unet and controlnet\n # manually for max memory savings\n if hasattr(self, \"final_offload_hook\") and self.final_offload_hook is not None:\n self.unet.to(\"cpu\")\n self.controlnet.to(\"cpu\")\n torch.cuda.empty_cache()\n\n if not output_type == \"latent\":\n image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]\n image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)\n else:\n image = latents\n has_nsfw_concept = None\n\n if has_nsfw_concept is None:\n do_denormalize = [True] * image.shape[0]\n else:\n do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]\n\n image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)\n\n # Offload all models\n self.maybe_free_model_hooks()\n\n if not return_dict:\n return (image, has_nsfw_concept)\n\n return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)" }, { "identifier": "CustomStableDiffusionInpaintPipeline", "path": "relighting/pipeline_inpaintonly.py", "snippet": "class CustomStableDiffusionInpaintPipeline(StableDiffusionInpaintPipeline):\n @torch.no_grad()\n def __call__(\n self,\n prompt: Union[str, List[str]] = None,\n image: PipelineImageInput = None,\n mask_image: PipelineImageInput = None,\n masked_image_latents: torch.FloatTensor = None,\n height: Optional[int] = None,\n width: Optional[int] = None,\n strength: float = 1.0,\n num_inference_steps: int = 50,\n guidance_scale: float = 7.5,\n negative_prompt: Optional[Union[str, List[str]]] = None,\n num_images_per_prompt: Optional[int] = 1,\n eta: float = 0.0,\n generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,\n latents: Optional[torch.FloatTensor] = None,\n prompt_embeds: Optional[torch.FloatTensor] = None,\n negative_prompt_embeds: Optional[torch.FloatTensor] = None,\n output_type: Optional[str] = \"pil\",\n return_dict: bool = True,\n callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,\n callback_steps: int = 1,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n newx: int = 0,\n newy: int = 0,\n newr: int = 256,\n current_seed=0,\n use_noise_moving=True,\n ):\n # OVERWRITE METHODS\n self.prepare_mask_latents = custom_prepare_mask_latents.__get__(self, CustomStableDiffusionInpaintPipeline)\n self.prepare_latents = custom_prepare_latents.__get__(self, CustomStableDiffusionInpaintPipeline)\n\n # 0. Default height and width to unet\n height = height or self.unet.config.sample_size * self.vae_scale_factor\n width = width or self.unet.config.sample_size * self.vae_scale_factor\n\n # 1. Check inputs\n self.check_inputs(\n prompt,\n height,\n width,\n strength,\n callback_steps,\n negative_prompt,\n prompt_embeds,\n negative_prompt_embeds,\n )\n\n # 2. Define call parameters\n if prompt is not None and isinstance(prompt, str):\n batch_size = 1\n elif prompt is not None and isinstance(prompt, list):\n batch_size = len(prompt)\n else:\n batch_size = prompt_embeds.shape[0]\n\n device = self._execution_device\n # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)\n # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`\n # corresponds to doing no classifier free guidance.\n do_classifier_free_guidance = guidance_scale > 1.0\n\n # 3. Encode input prompt\n text_encoder_lora_scale = (\n cross_attention_kwargs.get(\"scale\", None) if cross_attention_kwargs is not None else None\n )\n prompt_embeds, negative_prompt_embeds = self.encode_prompt(\n prompt,\n device,\n num_images_per_prompt,\n do_classifier_free_guidance,\n negative_prompt,\n prompt_embeds=prompt_embeds,\n negative_prompt_embeds=negative_prompt_embeds,\n lora_scale=text_encoder_lora_scale,\n )\n # For classifier free guidance, we need to do two forward passes.\n # Here we concatenate the unconditional and text embeddings into a single batch\n # to avoid doing two forward passes\n if do_classifier_free_guidance:\n prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])\n\n # 4. set timesteps\n self.scheduler.set_timesteps(num_inference_steps, device=device)\n timesteps, num_inference_steps = self.get_timesteps(\n num_inference_steps=num_inference_steps, strength=strength, device=device\n )\n # check that number of inference steps is not < 1 - as this doesn't make sense\n if num_inference_steps < 1:\n raise ValueError(\n f\"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline\"\n f\"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline.\"\n )\n # at which timestep to set the initial noise (n.b. 50% if strength is 0.5)\n latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)\n # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise\n is_strength_max = strength == 1.0\n\n # 5. Preprocess mask and image\n\n init_image = self.image_processor.preprocess(image, height=height, width=width)\n init_image = init_image.to(dtype=torch.float32)\n\n # 6. Prepare latent variables\n num_channels_latents = self.vae.config.latent_channels\n num_channels_unet = self.unet.config.in_channels\n return_image_latents = num_channels_unet == 4\n\n latents_outputs = self.prepare_latents(\n batch_size * num_images_per_prompt,\n num_channels_latents,\n height,\n width,\n prompt_embeds.dtype,\n device,\n generator,\n latents,\n image=init_image,\n timestep=latent_timestep,\n is_strength_max=is_strength_max,\n return_noise=True,\n return_image_latents=return_image_latents,\n newx=newx,\n newy=newy,\n newr=newr,\n current_seed=current_seed,\n use_noise_moving=use_noise_moving,\n )\n\n if return_image_latents:\n latents, noise, image_latents = latents_outputs\n else:\n latents, noise = latents_outputs\n\n # 7. Prepare mask latent variables\n mask_condition = self.mask_processor.preprocess(mask_image, height=height, width=width)\n\n if masked_image_latents is None:\n masked_image = init_image * (mask_condition < 0.5)\n else:\n masked_image = masked_image_latents\n\n mask, masked_image_latents = self.prepare_mask_latents(\n mask_condition,\n masked_image,\n batch_size * num_images_per_prompt,\n height,\n width,\n prompt_embeds.dtype,\n device,\n generator,\n do_classifier_free_guidance,\n )\n\n # 8. Check that sizes of mask, masked image and latents match\n if num_channels_unet == 9:\n # default case for runwayml/stable-diffusion-inpainting\n num_channels_mask = mask.shape[1]\n num_channels_masked_image = masked_image_latents.shape[1]\n if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels:\n raise ValueError(\n f\"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects\"\n f\" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +\"\n f\" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}\"\n f\" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of\"\n \" `pipeline.unet` or your `mask_image` or `image` input.\"\n )\n elif num_channels_unet != 4:\n raise ValueError(\n f\"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}.\"\n )\n\n # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline\n extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)\n\n # 10. Denoising loop\n num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order\n with self.progress_bar(total=num_inference_steps) as progress_bar:\n for i, t in enumerate(timesteps):\n # expand the latents if we are doing classifier free guidance\n latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents\n\n # concat latents, mask, masked_image_latents in the channel dimension\n latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)\n\n if num_channels_unet == 9:\n latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)\n\n # predict the noise residual\n noise_pred = self.unet(\n latent_model_input,\n t,\n encoder_hidden_states=prompt_embeds,\n cross_attention_kwargs=cross_attention_kwargs,\n return_dict=False,\n )[0]\n\n # perform guidance\n if do_classifier_free_guidance:\n noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)\n noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)\n\n # compute the previous noisy sample x_t -> x_t-1\n latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]\n\n if num_channels_unet == 4:\n init_latents_proper = image_latents[:1]\n init_mask = mask[:1]\n\n if i < len(timesteps) - 1:\n noise_timestep = timesteps[i + 1]\n init_latents_proper = self.scheduler.add_noise(\n init_latents_proper, noise, torch.tensor([noise_timestep])\n )\n\n latents = (1 - init_mask) * init_latents_proper + init_mask * latents\n\n # call the callback, if provided\n if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):\n progress_bar.update()\n if callback is not None and i % callback_steps == 0:\n callback(i, t, latents)\n\n if not output_type == \"latent\":\n condition_kwargs = {}\n if isinstance(self.vae, AsymmetricAutoencoderKL):\n init_image = init_image.to(device=device, dtype=masked_image_latents.dtype)\n init_image_condition = init_image.clone()\n init_image = self._encode_vae_image(init_image, generator=generator)\n mask_condition = mask_condition.to(device=device, dtype=masked_image_latents.dtype)\n condition_kwargs = {\"image\": init_image_condition, \"mask\": mask_condition}\n image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, **condition_kwargs)[0]\n image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)\n else:\n image = latents\n has_nsfw_concept = None\n\n if has_nsfw_concept is None:\n do_denormalize = [True] * image.shape[0]\n else:\n do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]\n\n image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)\n\n # Offload all models\n self.maybe_free_model_hooks()\n\n if not return_dict:\n return (image, has_nsfw_concept)\n\n return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)" }, { "identifier": "CustomStableDiffusionXLInpaintPipeline", "path": "relighting/pipeline_inpaintonly.py", "snippet": "class CustomStableDiffusionXLInpaintPipeline(StableDiffusionXLInpaintPipeline):\n @torch.no_grad()\n def __call__(\n self,\n prompt: Union[str, List[str]] = None,\n prompt_2: Optional[Union[str, List[str]]] = None,\n image: PipelineImageInput = None,\n mask_image: PipelineImageInput = None,\n masked_image_latents: torch.FloatTensor = None,\n height: Optional[int] = None,\n width: Optional[int] = None,\n strength: float = 0.9999,\n num_inference_steps: int = 50,\n denoising_start: Optional[float] = None,\n denoising_end: Optional[float] = None,\n guidance_scale: float = 7.5,\n negative_prompt: Optional[Union[str, List[str]]] = None,\n negative_prompt_2: Optional[Union[str, List[str]]] = None,\n num_images_per_prompt: Optional[int] = 1,\n eta: float = 0.0,\n generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,\n latents: Optional[torch.FloatTensor] = None,\n prompt_embeds: Optional[torch.FloatTensor] = None,\n negative_prompt_embeds: Optional[torch.FloatTensor] = None,\n pooled_prompt_embeds: Optional[torch.FloatTensor] = None,\n negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,\n output_type: Optional[str] = \"pil\",\n return_dict: bool = True,\n callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,\n callback_steps: int = 1,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n guidance_rescale: float = 0.0,\n original_size: Tuple[int, int] = None,\n crops_coords_top_left: Tuple[int, int] = (0, 0),\n target_size: Tuple[int, int] = None,\n negative_original_size: Optional[Tuple[int, int]] = None,\n negative_crops_coords_top_left: Tuple[int, int] = (0, 0),\n negative_target_size: Optional[Tuple[int, int]] = None,\n aesthetic_score: float = 6.0,\n negative_aesthetic_score: float = 2.5,\n newx: int = 0,\n newy: int = 0,\n newr: int = 256,\n current_seed=0,\n use_noise_moving=True,\n ):\n # OVERWRITE METHODS\n self.prepare_mask_latents = custom_prepare_mask_latents.__get__(self, CustomStableDiffusionXLInpaintPipeline)\n self.prepare_latents = custom_prepare_latents.__get__(self, CustomStableDiffusionXLInpaintPipeline)\n\n # 0. Default height and width to unet\n height = height or self.unet.config.sample_size * self.vae_scale_factor\n width = width or self.unet.config.sample_size * self.vae_scale_factor\n\n # 1. Check inputs\n self.check_inputs(\n prompt,\n prompt_2,\n height,\n width,\n strength,\n callback_steps,\n negative_prompt,\n negative_prompt_2,\n prompt_embeds,\n negative_prompt_embeds,\n )\n\n # 2. Define call parameters\n if prompt is not None and isinstance(prompt, str):\n batch_size = 1\n elif prompt is not None and isinstance(prompt, list):\n batch_size = len(prompt)\n else:\n batch_size = prompt_embeds.shape[0]\n\n device = self._execution_device\n # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)\n # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`\n # corresponds to doing no classifier free guidance.\n do_classifier_free_guidance = guidance_scale > 1.0\n\n # 3. Encode input prompt\n text_encoder_lora_scale = (\n cross_attention_kwargs.get(\"scale\", None) if cross_attention_kwargs is not None else None\n )\n\n (\n prompt_embeds,\n negative_prompt_embeds,\n pooled_prompt_embeds,\n negative_pooled_prompt_embeds,\n ) = self.encode_prompt(\n prompt=prompt,\n prompt_2=prompt_2,\n device=device,\n num_images_per_prompt=num_images_per_prompt,\n do_classifier_free_guidance=do_classifier_free_guidance,\n negative_prompt=negative_prompt,\n negative_prompt_2=negative_prompt_2,\n prompt_embeds=prompt_embeds,\n negative_prompt_embeds=negative_prompt_embeds,\n pooled_prompt_embeds=pooled_prompt_embeds,\n negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,\n lora_scale=text_encoder_lora_scale,\n )\n\n # 4. set timesteps\n def denoising_value_valid(dnv):\n return isinstance(denoising_end, float) and 0 < dnv < 1\n\n self.scheduler.set_timesteps(num_inference_steps, device=device)\n timesteps, num_inference_steps = self.get_timesteps(\n num_inference_steps, strength, device, denoising_start=denoising_start if denoising_value_valid else None\n )\n # check that number of inference steps is not < 1 - as this doesn't make sense\n if num_inference_steps < 1:\n raise ValueError(\n f\"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline\"\n f\"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline.\"\n )\n # at which timestep to set the initial noise (n.b. 50% if strength is 0.5)\n latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)\n # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise\n is_strength_max = strength == 1.0\n\n # 5. Preprocess mask and image\n init_image = self.image_processor.preprocess(image, height=height, width=width)\n init_image = init_image.to(dtype=torch.float32)\n\n mask = self.mask_processor.preprocess(mask_image, height=height, width=width)\n\n if masked_image_latents is not None:\n masked_image = masked_image_latents\n elif init_image.shape[1] == 4:\n # if images are in latent space, we can't mask it\n masked_image = None\n else:\n masked_image = init_image * (mask < 0.5)\n\n # 6. Prepare latent variables\n num_channels_latents = self.vae.config.latent_channels\n num_channels_unet = self.unet.config.in_channels\n return_image_latents = num_channels_unet == 4\n\n # add_noise = True if denoising_start is None else False\n latents_outputs = self.prepare_latents(\n batch_size * num_images_per_prompt,\n num_channels_latents,\n height,\n width,\n prompt_embeds.dtype,\n device,\n generator,\n latents,\n image=init_image,\n timestep=latent_timestep,\n is_strength_max=is_strength_max,\n return_noise=True,\n return_image_latents=return_image_latents,\n newx=newx,\n newy=newy,\n newr=newr,\n current_seed=current_seed,\n use_noise_moving=use_noise_moving,\n )\n\n if return_image_latents:\n latents, noise, image_latents = latents_outputs\n else:\n latents, noise = latents_outputs\n\n # 7. Prepare mask latent variables\n mask, masked_image_latents = self.prepare_mask_latents(\n mask,\n masked_image,\n batch_size * num_images_per_prompt,\n height,\n width,\n prompt_embeds.dtype,\n device,\n generator,\n do_classifier_free_guidance,\n )\n\n # 8. Check that sizes of mask, masked image and latents match\n if num_channels_unet == 9:\n # default case for runwayml/stable-diffusion-inpainting\n num_channels_mask = mask.shape[1]\n num_channels_masked_image = masked_image_latents.shape[1]\n if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels:\n raise ValueError(\n f\"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects\"\n f\" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +\"\n f\" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}\"\n f\" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of\"\n \" `pipeline.unet` or your `mask_image` or `image` input.\"\n )\n elif num_channels_unet != 4:\n raise ValueError(\n f\"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}.\"\n )\n # 8.1 Prepare extra step kwargs.\n extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)\n\n # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline\n height, width = latents.shape[-2:]\n height = height * self.vae_scale_factor\n width = width * self.vae_scale_factor\n\n original_size = original_size or (height, width)\n target_size = target_size or (height, width)\n\n # 10. Prepare added time ids & embeddings\n if negative_original_size is None:\n negative_original_size = original_size\n if negative_target_size is None:\n negative_target_size = target_size\n\n add_text_embeds = pooled_prompt_embeds\n add_time_ids, add_neg_time_ids = self._get_add_time_ids(\n original_size,\n crops_coords_top_left,\n target_size,\n aesthetic_score,\n negative_aesthetic_score,\n negative_original_size,\n negative_crops_coords_top_left,\n negative_target_size,\n dtype=prompt_embeds.dtype,\n )\n add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)\n\n if do_classifier_free_guidance:\n prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)\n add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)\n add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)\n add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)\n\n prompt_embeds = prompt_embeds.to(device)\n add_text_embeds = add_text_embeds.to(device)\n add_time_ids = add_time_ids.to(device)\n\n # 11. Denoising loop\n num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)\n\n if (\n denoising_end is not None\n and denoising_start is not None\n and denoising_value_valid(denoising_end)\n and denoising_value_valid(denoising_start)\n and denoising_start >= denoising_end\n ):\n raise ValueError(\n f\"`denoising_start`: {denoising_start} cannot be larger than or equal to `denoising_end`: \"\n + f\" {denoising_end} when using type float.\"\n )\n elif denoising_end is not None and denoising_value_valid(denoising_end):\n discrete_timestep_cutoff = int(\n round(\n self.scheduler.config.num_train_timesteps\n - (denoising_end * self.scheduler.config.num_train_timesteps)\n )\n )\n num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))\n timesteps = timesteps[:num_inference_steps]\n\n with self.progress_bar(total=num_inference_steps) as progress_bar:\n for i, t in enumerate(timesteps):\n # expand the latents if we are doing classifier free guidance\n latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents\n\n # concat latents, mask, masked_image_latents in the channel dimension\n latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)\n\n if num_channels_unet == 9:\n latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)\n\n # predict the noise residual\n added_cond_kwargs = {\"text_embeds\": add_text_embeds, \"time_ids\": add_time_ids}\n noise_pred = self.unet(\n latent_model_input,\n t,\n encoder_hidden_states=prompt_embeds,\n cross_attention_kwargs=cross_attention_kwargs,\n added_cond_kwargs=added_cond_kwargs,\n return_dict=False,\n )[0]\n\n # perform guidance\n if do_classifier_free_guidance:\n noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)\n noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)\n\n if do_classifier_free_guidance and guidance_rescale > 0.0:\n # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf\n noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)\n\n # compute the previous noisy sample x_t -> x_t-1\n latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]\n\n if num_channels_unet == 4:\n init_latents_proper = image_latents[:1]\n init_mask = mask[:1]\n\n if i < len(timesteps) - 1:\n noise_timestep = timesteps[i + 1]\n init_latents_proper = self.scheduler.add_noise(\n init_latents_proper, noise, torch.tensor([noise_timestep])\n )\n\n latents = (1 - init_mask) * init_latents_proper + init_mask * latents\n\n # call the callback, if provided\n if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):\n progress_bar.update()\n if callback is not None and i % callback_steps == 0:\n callback(i, t, latents)\n\n if not output_type == \"latent\":\n # make sure the VAE is in float32 mode, as it overflows in float16\n needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast\n\n if needs_upcasting:\n self.upcast_vae()\n latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)\n\n image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]\n\n # cast back to fp16 if needed\n if needs_upcasting:\n self.vae.to(dtype=torch.float16)\n else:\n return StableDiffusionXLPipelineOutput(images=latents)\n\n # apply watermark if available\n if self.watermark is not None:\n image = self.watermark.apply_watermark(image)\n\n image = self.image_processor.postprocess(image, output_type=output_type)\n\n # Offload all models\n self.maybe_free_model_hooks()\n\n if not return_dict:\n return (image,)\n\n return StableDiffusionXLPipelineOutput(images=image)" }, { "identifier": "SAMPLERS", "path": "relighting/argument.py", "snippet": "SAMPLERS = {\n \"ddim\": DDIMScheduler,\n \"ddpm\": DDPMScheduler,\n \"unipc\": UniPCMultistepScheduler,\n}" }, { "identifier": "VAE_MODELS", "path": "relighting/argument.py", "snippet": "VAE_MODELS = {\n \"sdxl\": \"madebyollin/sdxl-vae-fp16-fix\",\n \"sdxl_fast\": \"madebyollin/sdxl-vae-fp16-fix\",\n}" }, { "identifier": "DEPTH_ESTIMATOR", "path": "relighting/argument.py", "snippet": "DEPTH_ESTIMATOR = \"Intel/dpt-hybrid-midas\"" }, { "identifier": "get_control_signal_type", "path": "relighting/argument.py", "snippet": "def get_control_signal_type(controlnet):\n if \"normal\" in controlnet:\n return \"normal\"\n elif \"depth\" in controlnet:\n return \"depth\"\n else:\n raise NotImplementedError" }, { "identifier": "estimate_scene_depth", "path": "relighting/image_processor.py", "snippet": "def estimate_scene_depth(image, depth_estimator):\n #image = feature_extractor(images=image, return_tensors=\"pt\").pixel_values.to(\"cuda\")\n #with torch.no_grad(), torch.autocast(\"cuda\"):\n # depth_map = depth_estimator(image).predicted_depth\n\n depth_map = depth_estimator(image)['predicted_depth']\n W, H = image.size\n depth_map = torch.nn.functional.interpolate(\n depth_map.unsqueeze(1),\n size=(H, W),\n mode=\"bicubic\",\n align_corners=False,\n )\n depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)\n depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)\n depth_map = (depth_map - depth_min) / (depth_max - depth_min)\n image = torch.cat([depth_map] * 3, dim=1)\n\n image = image.permute(0, 2, 3, 1).cpu().numpy()[0]\n image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))\n return image" }, { "identifier": "estimate_scene_normal", "path": "relighting/image_processor.py", "snippet": "def estimate_scene_normal(image, depth_estimator):\n # can be improve speed do not going back and float between numpy and torch\n normal_image = depth_estimator(image)['predicted_depth'][0]\n\n normal_image = normal_image.numpy()\n\n # upsizing image depth to match input\n hw = np.array(image).shape[:2]\n normal_image = skimage.transform.resize(normal_image, hw, preserve_range=True)\n\n image_depth = normal_image.copy()\n image_depth -= np.min(image_depth)\n image_depth /= np.max(image_depth)\n \n bg_threhold = 0.4\n\n x = cv2.Sobel(normal_image, cv2.CV_32F, 1, 0, ksize=3)\n x[image_depth < bg_threhold] = 0\n\n y = cv2.Sobel(normal_image, cv2.CV_32F, 0, 1, ksize=3)\n y[image_depth < bg_threhold] = 0\n\n z = np.ones_like(x) * np.pi * 2.0\n\n normal_image = np.stack([x, y, z], axis=2)\n normal_image /= np.sum(normal_image ** 2.0, axis=2, keepdims=True) ** 0.5\n\n # rescale back to image size\n return normal_image" }, { "identifier": "merge_normal_map", "path": "relighting/image_processor.py", "snippet": "def merge_normal_map(normal_map, normal_ball, mask_ball, x, y):\n \"\"\"\n Merge a ball to normal map using mask\n @params\n normal_amp (np.array) - normal map of the scene [height, width, 3]\n normal_ball (np.array) - normal map of the ball [ball_height, ball_width, 3]\n mask_ball (np.array) - mask of the ball [ball_height, ball_width]\n x (int) - x position of the ball (top-left)\n y (int) - y position of the ball (top-left)\n @return\n normal_mapthe merge normal map [height, width, 3] \n \"\"\"\n result = normal_map.copy()\n\n mask_ball = mask_ball[..., None]\n ball = (normal_ball * mask_ball) # alpha blending the ball\n unball = (normal_map[y:y+normal_ball.shape[0], x:x+normal_ball.shape[1]] * (1 - mask_ball)) # alpha blending the normal map\n result[y:y+normal_ball.shape[0], x:x+normal_ball.shape[1]] = ball+unball # add them together\n return result" }, { "identifier": "fill_depth_circular", "path": "relighting/image_processor.py", "snippet": "def fill_depth_circular(depth_image, x, y, r):\n depth_image = np.array(depth_image)\n\n for i in range(depth_image.shape[0]):\n for j in range(depth_image.shape[1]):\n xy = (i - x - r//2)**2 + (j - y - r//2)**2\n # if xy <= rr**2:\n # depth_image[j, i, :] = 255\n # depth_image[j, i, :] = int(minv + (maxv - minv) * z)\n if xy <= (r // 2)**2:\n depth_image[j, i, :] = 255\n \n depth_image = Image.fromarray(depth_image)\n return depth_image" }, { "identifier": "get_ideal_normal_ball", "path": "relighting/ball_processor.py", "snippet": "def get_ideal_normal_ball(size, flip_x=True):\n \"\"\"\n Generate normal ball for specific size \n Normal map is x \"left\", y up, z into the screen \n (we flip X to match sobel operator)\n @params\n - size (int) - single value of height and width\n @return:\n - normal_map (np.array) - normal map [size, size, 3]\n - mask (np.array) - mask that make a valid normal map [size,size]\n \"\"\"\n # we flip x to match sobel operator\n x = torch.linspace(1, -1, size)\n y = torch.linspace(1, -1, size)\n x = x.flip(dims=(-1,)) if not flip_x else x\n\n y, x = torch.meshgrid(y, x)\n z = (1 - x**2 - y**2)\n mask = z >= 0\n\n # clean up invalid value outsize the mask\n x = x * mask\n y = y * mask\n z = z * mask\n \n # get real z value\n z = torch.sqrt(z)\n \n # clean up normal map value outside mask \n normal_map = torch.cat([x[..., None], y[..., None], z[..., None]], dim=-1)\n normal_map = normal_map.numpy()\n mask = mask.numpy()\n return normal_map, mask" }, { "identifier": "crop_ball", "path": "relighting/ball_processor.py", "snippet": "def crop_ball(image, mask_ball, x, y, size, apply_mask=True, bg_color = (0, 0, 0)):\n if isinstance(image, Image.Image):\n result = np.array(image)\n else:\n result = image.copy()\n \n result = result[y:y+size, x:x+size]\n if apply_mask:\n result[~mask_ball] = bg_color\n return result" }, { "identifier": "CustomStableDiffusionXLControlNetInpaintPipeline", "path": "relighting/pipeline_xl.py", "snippet": "class CustomStableDiffusionXLControlNetInpaintPipeline(StableDiffusionXLControlNetInpaintPipeline):\n @torch.no_grad()\n def __call__(\n self,\n prompt: Union[str, List[str]] = None,\n prompt_2: Optional[Union[str, List[str]]] = None,\n image: PipelineImageInput = None,\n mask_image: PipelineImageInput = None,\n control_image: Union[\n PipelineImageInput,\n List[PipelineImageInput],\n ] = None,\n height: Optional[int] = None,\n width: Optional[int] = None,\n strength: float = 0.9999,\n num_inference_steps: int = 50,\n denoising_start: Optional[float] = None,\n denoising_end: Optional[float] = None,\n guidance_scale: float = 5.0,\n negative_prompt: Optional[Union[str, List[str]]] = None,\n negative_prompt_2: Optional[Union[str, List[str]]] = None,\n num_images_per_prompt: Optional[int] = 1,\n eta: float = 0.0,\n generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,\n latents: Optional[torch.FloatTensor] = None,\n prompt_embeds: Optional[torch.FloatTensor] = None,\n negative_prompt_embeds: Optional[torch.FloatTensor] = None,\n pooled_prompt_embeds: Optional[torch.FloatTensor] = None,\n negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,\n output_type: Optional[str] = \"pil\",\n return_dict: bool = True,\n callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,\n callback_steps: int = 1,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n controlnet_conditioning_scale: Union[float, List[float]] = 1.0,\n guess_mode: bool = False,\n control_guidance_start: Union[float, List[float]] = 0.0,\n control_guidance_end: Union[float, List[float]] = 1.0,\n guidance_rescale: float = 0.0,\n original_size: Tuple[int, int] = None,\n crops_coords_top_left: Tuple[int, int] = (0, 0),\n target_size: Tuple[int, int] = None,\n aesthetic_score: float = 6.0,\n negative_aesthetic_score: float = 2.5,\n newx: int = 0,\n newy: int = 0,\n newr: int = 256,\n current_seed=0,\n use_noise_moving=True,\n ):\n # OVERWRITE METHODS\n self.prepare_mask_latents = custom_prepare_mask_latents.__get__(self, CustomStableDiffusionXLControlNetInpaintPipeline)\n self.prepare_latents = custom_prepare_latents.__get__(self, CustomStableDiffusionXLControlNetInpaintPipeline)\n\n controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet\n\n # align format for control guidance\n if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):\n control_guidance_start = len(control_guidance_end) * [control_guidance_start]\n elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):\n control_guidance_end = len(control_guidance_start) * [control_guidance_end]\n elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):\n mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1\n control_guidance_start, control_guidance_end = mult * [control_guidance_start], mult * [\n control_guidance_end\n ]\n\n # # 0.0 Default height and width to unet\n # height = height or self.unet.config.sample_size * self.vae_scale_factor\n # width = width or self.unet.config.sample_size * self.vae_scale_factor\n\n # 0.1 align format for control guidance\n if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):\n control_guidance_start = len(control_guidance_end) * [control_guidance_start]\n elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):\n control_guidance_end = len(control_guidance_start) * [control_guidance_end]\n elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):\n mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1\n control_guidance_start, control_guidance_end = mult * [control_guidance_start], mult * [\n control_guidance_end\n ]\n\n # 1. Check inputs\n self.check_inputs(\n prompt,\n prompt_2,\n control_image,\n strength,\n num_inference_steps,\n callback_steps,\n negative_prompt,\n negative_prompt_2,\n prompt_embeds,\n negative_prompt_embeds,\n pooled_prompt_embeds,\n negative_pooled_prompt_embeds,\n controlnet_conditioning_scale,\n control_guidance_start,\n control_guidance_end,\n )\n\n # 2. Define call parameters\n if prompt is not None and isinstance(prompt, str):\n batch_size = 1\n elif prompt is not None and isinstance(prompt, list):\n batch_size = len(prompt)\n else:\n batch_size = prompt_embeds.shape[0]\n\n device = self._execution_device\n # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)\n # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`\n # corresponds to doing no classifier free guidance.\n do_classifier_free_guidance = guidance_scale > 1.0\n\n if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):\n controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)\n\n # 3. Encode input prompt\n text_encoder_lora_scale = (\n cross_attention_kwargs.get(\"scale\", None) if cross_attention_kwargs is not None else None\n )\n\n (\n prompt_embeds,\n negative_prompt_embeds,\n pooled_prompt_embeds,\n negative_pooled_prompt_embeds,\n ) = self.encode_prompt(\n prompt=prompt,\n prompt_2=prompt_2,\n device=device,\n num_images_per_prompt=num_images_per_prompt,\n do_classifier_free_guidance=do_classifier_free_guidance,\n negative_prompt=negative_prompt,\n negative_prompt_2=negative_prompt_2,\n prompt_embeds=prompt_embeds,\n negative_prompt_embeds=negative_prompt_embeds,\n pooled_prompt_embeds=pooled_prompt_embeds,\n negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,\n lora_scale=text_encoder_lora_scale,\n )\n\n # 4. set timesteps\n def denoising_value_valid(dnv):\n return isinstance(denoising_end, float) and 0 < dnv < 1\n\n self.scheduler.set_timesteps(num_inference_steps, device=device)\n timesteps, num_inference_steps = self.get_timesteps(\n num_inference_steps, strength, device, denoising_start=denoising_start if denoising_value_valid else None\n )\n # check that number of inference steps is not < 1 - as this doesn't make sense\n if num_inference_steps < 1:\n raise ValueError(\n f\"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline\"\n f\"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline.\"\n )\n # at which timestep to set the initial noise (n.b. 50% if strength is 0.5)\n latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)\n # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise\n is_strength_max = strength == 1.0\n\n # 5. Preprocess mask and image - resizes image and mask w.r.t height and width\n # 5.1 Prepare init image\n init_image = self.image_processor.preprocess(image, height=height, width=width)\n init_image = init_image.to(dtype=torch.float32)\n\n # 5.2 Prepare control images\n if isinstance(controlnet, ControlNetModel):\n control_image = self.prepare_control_image(\n image=control_image,\n width=width,\n height=height,\n batch_size=batch_size * num_images_per_prompt,\n num_images_per_prompt=num_images_per_prompt,\n device=device,\n dtype=controlnet.dtype,\n do_classifier_free_guidance=do_classifier_free_guidance,\n guess_mode=guess_mode,\n )\n elif isinstance(controlnet, MultiControlNetModel):\n control_images = []\n\n for control_image_ in control_image:\n control_image_ = self.prepare_control_image(\n image=control_image_,\n width=width,\n height=height,\n batch_size=batch_size * num_images_per_prompt,\n num_images_per_prompt=num_images_per_prompt,\n device=device,\n dtype=controlnet.dtype,\n do_classifier_free_guidance=do_classifier_free_guidance,\n guess_mode=guess_mode,\n )\n\n control_images.append(control_image_)\n\n control_image = control_images\n else:\n raise ValueError(f\"{controlnet.__class__} is not supported.\")\n\n # 5.3 Prepare mask\n mask = self.mask_processor.preprocess(mask_image, height=height, width=width)\n\n masked_image = init_image * (mask < 0.5)\n _, _, height, width = init_image.shape\n\n # 6. Prepare latent variables\n num_channels_latents = self.vae.config.latent_channels\n num_channels_unet = self.unet.config.in_channels\n return_image_latents = num_channels_unet == 4\n\n add_noise = True if denoising_start is None else False\n latents_outputs = self.prepare_latents(\n batch_size * num_images_per_prompt,\n num_channels_latents,\n height,\n width,\n prompt_embeds.dtype,\n device,\n generator,\n latents,\n image=init_image,\n timestep=latent_timestep,\n is_strength_max=is_strength_max,\n return_noise=True,\n return_image_latents=return_image_latents,\n newx=newx,\n newy=newy,\n newr=newr,\n current_seed=current_seed,\n use_noise_moving=use_noise_moving,\n )\n\n if return_image_latents:\n latents, noise, image_latents = latents_outputs\n else:\n latents, noise = latents_outputs\n\n # 7. Prepare mask latent variables\n mask, masked_image_latents = self.prepare_mask_latents(\n mask,\n masked_image,\n batch_size * num_images_per_prompt,\n height,\n width,\n prompt_embeds.dtype,\n device,\n generator,\n do_classifier_free_guidance,\n )\n\n # 8. Check that sizes of mask, masked image and latents match\n if num_channels_unet == 9:\n # default case for runwayml/stable-diffusion-inpainting\n num_channels_mask = mask.shape[1]\n num_channels_masked_image = masked_image_latents.shape[1]\n if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels:\n raise ValueError(\n f\"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects\"\n f\" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +\"\n f\" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}\"\n f\" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of\"\n \" `pipeline.unet` or your `mask_image` or `image` input.\"\n )\n elif num_channels_unet != 4:\n raise ValueError(\n f\"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}.\"\n )\n # 8.1 Prepare extra step kwargs.\n extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)\n\n # 8.2 Create tensor stating which controlnets to keep\n controlnet_keep = []\n for i in range(len(timesteps)):\n keeps = [\n 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)\n for s, e in zip(control_guidance_start, control_guidance_end)\n ]\n if isinstance(self.controlnet, MultiControlNetModel):\n controlnet_keep.append(keeps)\n else:\n controlnet_keep.append(keeps[0])\n\n # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline\n height, width = latents.shape[-2:]\n height = height * self.vae_scale_factor\n width = width * self.vae_scale_factor\n\n original_size = original_size or (height, width)\n target_size = target_size or (height, width)\n\n # 10. Prepare added time ids & embeddings\n add_text_embeds = pooled_prompt_embeds\n add_time_ids, add_neg_time_ids = self._get_add_time_ids(\n original_size,\n crops_coords_top_left,\n target_size,\n aesthetic_score,\n negative_aesthetic_score,\n dtype=prompt_embeds.dtype,\n )\n add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)\n\n if do_classifier_free_guidance:\n prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)\n add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)\n add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)\n add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)\n\n prompt_embeds = prompt_embeds.to(device)\n add_text_embeds = add_text_embeds.to(device)\n add_time_ids = add_time_ids.to(device)\n\n # 11. Denoising loop\n num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)\n\n if (\n denoising_end is not None\n and denoising_start is not None\n and denoising_value_valid(denoising_end)\n and denoising_value_valid(denoising_start)\n and denoising_start >= denoising_end\n ):\n raise ValueError(\n f\"`denoising_start`: {denoising_start} cannot be larger than or equal to `denoising_end`: \"\n + f\" {denoising_end} when using type float.\"\n )\n elif denoising_end is not None and denoising_value_valid(denoising_end):\n discrete_timestep_cutoff = int(\n round(\n self.scheduler.config.num_train_timesteps\n - (denoising_end * self.scheduler.config.num_train_timesteps)\n )\n )\n num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))\n timesteps = timesteps[:num_inference_steps]\n\n with self.progress_bar(total=num_inference_steps) as progress_bar:\n for i, t in enumerate(timesteps):\n # expand the latents if we are doing classifier free guidance\n latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents\n\n # concat latents, mask, masked_image_latents in the channel dimension\n latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)\n\n added_cond_kwargs = {\"text_embeds\": add_text_embeds, \"time_ids\": add_time_ids}\n\n # controlnet(s) inference\n if guess_mode and do_classifier_free_guidance:\n # Infer ControlNet only for the conditional batch.\n control_model_input = latents\n control_model_input = self.scheduler.scale_model_input(control_model_input, t)\n controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]\n controlnet_added_cond_kwargs = {\n \"text_embeds\": add_text_embeds.chunk(2)[1],\n \"time_ids\": add_time_ids.chunk(2)[1],\n }\n else:\n control_model_input = latent_model_input\n controlnet_prompt_embeds = prompt_embeds\n controlnet_added_cond_kwargs = added_cond_kwargs\n\n if isinstance(controlnet_keep[i], list):\n cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]\n else:\n controlnet_cond_scale = controlnet_conditioning_scale\n if isinstance(controlnet_cond_scale, list):\n controlnet_cond_scale = controlnet_cond_scale[0]\n cond_scale = controlnet_cond_scale * controlnet_keep[i]\n\n # # Resize control_image to match the size of the input to the controlnet\n # if control_image.shape[-2:] != control_model_input.shape[-2:]:\n # control_image = F.interpolate(control_image, size=control_model_input.shape[-2:], mode=\"bilinear\", align_corners=False)\n\n down_block_res_samples, mid_block_res_sample = self.controlnet(\n control_model_input,\n t,\n encoder_hidden_states=controlnet_prompt_embeds,\n controlnet_cond=control_image,\n conditioning_scale=cond_scale,\n guess_mode=guess_mode,\n added_cond_kwargs=controlnet_added_cond_kwargs,\n return_dict=False,\n )\n\n if guess_mode and do_classifier_free_guidance:\n # Infered ControlNet only for the conditional batch.\n # To apply the output of ControlNet to both the unconditional and conditional batches,\n # add 0 to the unconditional batch to keep it unchanged.\n down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]\n mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])\n\n if num_channels_unet == 9:\n latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)\n\n # predict the noise residual\n noise_pred = self.unet(\n latent_model_input,\n t,\n encoder_hidden_states=prompt_embeds,\n cross_attention_kwargs=cross_attention_kwargs,\n down_block_additional_residuals=down_block_res_samples,\n mid_block_additional_residual=mid_block_res_sample,\n added_cond_kwargs=added_cond_kwargs,\n return_dict=False,\n )[0]\n\n # perform guidance\n if do_classifier_free_guidance:\n noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)\n noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)\n\n if do_classifier_free_guidance and guidance_rescale > 0.0:\n print(\"rescale: \", guidance_rescale)\n # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf\n noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)\n\n # compute the previous noisy sample x_t -> x_t-1\n latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]\n\n if num_channels_unet == 4:\n init_latents_proper = image_latents[:1]\n init_mask = mask[:1]\n\n if i < len(timesteps) - 1:\n noise_timestep = timesteps[i + 1]\n init_latents_proper = self.scheduler.add_noise(\n init_latents_proper, noise, torch.tensor([noise_timestep])\n )\n\n latents = (1 - init_mask) * init_latents_proper + init_mask * latents\n\n # call the callback, if provided\n if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):\n progress_bar.update()\n if callback is not None and i % callback_steps == 0:\n callback(i, t, latents)\n\n # make sure the VAE is in float32 mode, as it overflows in float16\n if self.vae.dtype == torch.float16 and self.vae.config.force_upcast:\n self.upcast_vae()\n latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)\n\n # If we do sequential model offloading, let's offload unet and controlnet\n # manually for max memory savings\n if hasattr(self, \"final_offload_hook\") and self.final_offload_hook is not None:\n self.unet.to(\"cpu\")\n self.controlnet.to(\"cpu\")\n torch.cuda.empty_cache()\n\n if not output_type == \"latent\":\n image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]\n else:\n return StableDiffusionXLPipelineOutput(images=latents)\n\n # apply watermark if available\n if self.watermark is not None:\n image = self.watermark.apply_watermark(image)\n\n image = self.image_processor.postprocess(image, output_type=output_type)\n\n # Offload last model to CPU\n if hasattr(self, \"final_offload_hook\") and self.final_offload_hook is not None:\n self.final_offload_hook.offload()\n\n if not return_dict:\n return (image,)\n\n return StableDiffusionXLPipelineOutput(images=image)" } ]
import torch import numpy as np import os import pickle from diffusers import ControlNetModel, AutoencoderKL from PIL import Image from tqdm.auto import tqdm from transformers import pipeline as transformers_pipeline from relighting.pipeline import CustomStableDiffusionControlNetInpaintPipeline from relighting.pipeline_inpaintonly import CustomStableDiffusionInpaintPipeline, CustomStableDiffusionXLInpaintPipeline from relighting.argument import SAMPLERS, VAE_MODELS, DEPTH_ESTIMATOR, get_control_signal_type from relighting.image_processor import ( estimate_scene_depth, estimate_scene_normal, merge_normal_map, fill_depth_circular ) from relighting.ball_processor import get_ideal_normal_ball, crop_ball from relighting.pipeline_xl import CustomStableDiffusionXLControlNetInpaintPipeline
18,097
class NoWaterMark: def apply_watermark(self, *args, **kwargs): return args[0] class ControlSignalGenerator(): def __init__(self, sd_arch, control_signal_type, device): self.sd_arch = sd_arch self.control_signal_type = control_signal_type self.device = device def process_sd_depth(self, input_image, normal_ball=None, mask_ball=None, x=None, y=None, r=None): if getattr(self, 'depth_estimator', None) is None: self.depth_estimator = transformers_pipeline("depth-estimation", device=self.device.index) control_image = self.depth_estimator(input_image)['depth'] control_image = np.array(control_image) control_image = control_image[:, :, None] control_image = np.concatenate([control_image, control_image, control_image], axis=2) control_image = Image.fromarray(control_image) control_image = fill_depth_circular(control_image, x, y, r) return control_image def process_sdxl_depth(self, input_image, normal_ball=None, mask_ball=None, x=None, y=None, r=None): if getattr(self, 'depth_estimator', None) is None: self.depth_estimator = transformers_pipeline("depth-estimation", model=DEPTH_ESTIMATOR, device=self.device.index) control_image = estimate_scene_depth(input_image, depth_estimator=self.depth_estimator) xs = [x] if not isinstance(x, list) else x ys = [y] if not isinstance(y, list) else y rs = [r] if not isinstance(r, list) else r for x, y, r in zip(xs, ys, rs): #print(f"depth at {x}, {y}, {r}") control_image = fill_depth_circular(control_image, x, y, r) return control_image def process_sd_normal(self, input_image, normal_ball, mask_ball, x, y, r=None, normal_ball_path=None): if getattr(self, 'depth_estimator', None) is None: self.depth_estimator = transformers_pipeline("depth-estimation", model=DEPTH_ESTIMATOR, device=self.device.index) normal_scene = estimate_scene_normal(input_image, depth_estimator=self.depth_estimator) normal_image = merge_normal_map(normal_scene, normal_ball, mask_ball, x, y) normal_image = (normal_image * 127.5 + 127.5).clip(0, 255).astype(np.uint8) control_image = Image.fromarray(normal_image) return control_image def __call__(self, *args, **kwargs): process_fn = getattr(self, f"process_{self.sd_arch}_{self.control_signal_type}", None) if process_fn is None: raise ValueError else: return process_fn(*args, **kwargs) class BallInpainter(): def __init__(self, pipeline, sd_arch, control_generator, disable_water_mask=True): self.pipeline = pipeline self.sd_arch = sd_arch self.control_generator = control_generator self.median = {} if disable_water_mask: self._disable_water_mask() def _disable_water_mask(self): if hasattr(self.pipeline, "watermark"): self.pipeline.watermark = NoWaterMark() print("Disabled watermasking") @classmethod def from_sd(cls, model, controlnet=None, device=0, sampler="unipc", torch_dtype=torch.float16, disable_water_mask=True, offload=False ): if controlnet is not None: control_signal_type = get_control_signal_type(controlnet) controlnet = ControlNetModel.from_pretrained(controlnet, torch_dtype=torch.float16)
class NoWaterMark: def apply_watermark(self, *args, **kwargs): return args[0] class ControlSignalGenerator(): def __init__(self, sd_arch, control_signal_type, device): self.sd_arch = sd_arch self.control_signal_type = control_signal_type self.device = device def process_sd_depth(self, input_image, normal_ball=None, mask_ball=None, x=None, y=None, r=None): if getattr(self, 'depth_estimator', None) is None: self.depth_estimator = transformers_pipeline("depth-estimation", device=self.device.index) control_image = self.depth_estimator(input_image)['depth'] control_image = np.array(control_image) control_image = control_image[:, :, None] control_image = np.concatenate([control_image, control_image, control_image], axis=2) control_image = Image.fromarray(control_image) control_image = fill_depth_circular(control_image, x, y, r) return control_image def process_sdxl_depth(self, input_image, normal_ball=None, mask_ball=None, x=None, y=None, r=None): if getattr(self, 'depth_estimator', None) is None: self.depth_estimator = transformers_pipeline("depth-estimation", model=DEPTH_ESTIMATOR, device=self.device.index) control_image = estimate_scene_depth(input_image, depth_estimator=self.depth_estimator) xs = [x] if not isinstance(x, list) else x ys = [y] if not isinstance(y, list) else y rs = [r] if not isinstance(r, list) else r for x, y, r in zip(xs, ys, rs): #print(f"depth at {x}, {y}, {r}") control_image = fill_depth_circular(control_image, x, y, r) return control_image def process_sd_normal(self, input_image, normal_ball, mask_ball, x, y, r=None, normal_ball_path=None): if getattr(self, 'depth_estimator', None) is None: self.depth_estimator = transformers_pipeline("depth-estimation", model=DEPTH_ESTIMATOR, device=self.device.index) normal_scene = estimate_scene_normal(input_image, depth_estimator=self.depth_estimator) normal_image = merge_normal_map(normal_scene, normal_ball, mask_ball, x, y) normal_image = (normal_image * 127.5 + 127.5).clip(0, 255).astype(np.uint8) control_image = Image.fromarray(normal_image) return control_image def __call__(self, *args, **kwargs): process_fn = getattr(self, f"process_{self.sd_arch}_{self.control_signal_type}", None) if process_fn is None: raise ValueError else: return process_fn(*args, **kwargs) class BallInpainter(): def __init__(self, pipeline, sd_arch, control_generator, disable_water_mask=True): self.pipeline = pipeline self.sd_arch = sd_arch self.control_generator = control_generator self.median = {} if disable_water_mask: self._disable_water_mask() def _disable_water_mask(self): if hasattr(self.pipeline, "watermark"): self.pipeline.watermark = NoWaterMark() print("Disabled watermasking") @classmethod def from_sd(cls, model, controlnet=None, device=0, sampler="unipc", torch_dtype=torch.float16, disable_water_mask=True, offload=False ): if controlnet is not None: control_signal_type = get_control_signal_type(controlnet) controlnet = ControlNetModel.from_pretrained(controlnet, torch_dtype=torch.float16)
pipe = CustomStableDiffusionControlNetInpaintPipeline.from_pretrained(
0
2023-12-07 14:03:31+00:00
24k
modelscope/normal-depth-diffusion
ldm/models/diffusion/ddpm.py
[ { "identifier": "AutoencoderKL", "path": "ldm/models/autoencoder.py", "snippet": "class AutoencoderKL(pl.LightningModule):\n\n def __init__(self,\n ddconfig,\n lossconfig,\n embed_dim,\n ckpt_path=None,\n ignore_keys=[],\n image_key='image',\n colorize_nlabels=None,\n monitor=None,\n prior_model=None,\n prior_normal=None,\n using_rgb=True):\n super().__init__()\n self.image_key = image_key\n self.encoder = Encoder(**ddconfig)\n self.decoder = Decoder(**ddconfig)\n self.loss = instantiate_from_config(lossconfig)\n self.prior_model = prior_model\n self.using_rgb = using_rgb\n\n assert ddconfig['double_z']\n self.quant_conv = torch.nn.Conv2d(2 * ddconfig['z_channels'],\n 2 * embed_dim, 1)\n self.post_quant_conv = torch.nn.Conv2d(embed_dim,\n ddconfig['z_channels'], 1)\n self.embed_dim = embed_dim\n if colorize_nlabels is not None:\n assert type(colorize_nlabels) == int\n self.register_buffer('colorize',\n torch.randn(3, colorize_nlabels, 1, 1))\n if monitor is not None:\n self.monitor = monitor\n\n if prior_model is not None:\n self.prior_model = instantiate_from_config(prior_model)\n if prior_normal is not None:\n self.prior_normal = instantiate_from_config(prior_normal)\n\n if ckpt_path is not None:\n self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)\n\n def init_from_ckpt(self, path, ignore_keys=list()):\n try:\n sd = torch.load(path, map_location='cpu')['state_dict']\n except:\n sd = torch.load(path, map_location='cpu')\n\n keys = list(sd.keys())\n for k in keys:\n for ik in ignore_keys:\n if k.startswith(ik):\n print('Deleting key {} from state_dict.'.format(k))\n del sd[k]\n m, u = self.load_state_dict(sd, strict=False)\n if len(m) > 0:\n print('missing keys:')\n print(m)\n if len(u) > 0:\n print('unexpected keys:')\n print(u)\n\n print(f'Restored from {path}')\n\n def encode(self, x):\n h = self.encoder(x)\n moments = self.quant_conv(h)\n posterior = DiagonalGaussianDistribution(moments)\n return posterior\n\n def decode(self, z):\n z = self.post_quant_conv(z)\n dec = self.decoder(z)\n return dec\n\n def prior_to_eval(self):\n\n if self.prior_model is not None:\n self.prior_model.eval()\n\n if self.prior_normal is not None:\n self.prior_normal.eval()\n\n @torch.no_grad()\n def prior_inference(self, inputs, prior_inputs):\n # depth prior model\n # midas or zoe is 384 model\n prior_results = {}\n\n self.prior_to_eval()\n\n model_prior_results = self.prior_model(prior_inputs)\n prior_results.update(model_prior_results)\n\n # using normal map\n if not self.using_rgb:\n normal_prior = self.prior_normal(prior_inputs)\n prior_results.update(normal_prior)\n\n resize_prior_results = {}\n _, __, h, w = inputs.shape\n\n for key in prior_results.keys():\n resize_prior_results[key] = F.interpolate(\n prior_results[key], (w, h), mode='bilinear')\n\n if self.using_rgb:\n return torch.cat([inputs, resize_prior_results['depth']], dim=1)\n else:\n return torch.cat([\n resize_prior_results['normal'], resize_prior_results['depth']\n ],\n dim=1)\n\n def forward(self, input, sample_posterior=True):\n\n posterior = self.encode(input)\n if sample_posterior:\n z = posterior.sample()\n else:\n z = posterior.mode()\n dec = self.decode(z)\n return dec, posterior\n\n def get_input(self, batch, k):\n x = batch[k]\n if len(x.shape) == 3:\n x = x[..., None]\n x = x.permute(0, 3, 1,\n 2).to(memory_format=torch.contiguous_format).float()\n return x\n\n def training_step(self, batch, batch_idx, optimizer_idx):\n\n inputs = self.get_input(batch, self.image_key)\n if self.prior_model is not None:\n inputs = self.prior_inference(inputs, batch['prior'])\n\n reconstructions, posterior = self(inputs)\n\n if optimizer_idx == 0:\n # train encoder+decoder+logvar\n aeloss, log_dict_ae = self.loss(\n inputs,\n reconstructions,\n posterior,\n optimizer_idx,\n self.global_step,\n last_layer=self.get_last_layer(),\n split='train')\n\n self.log(\n 'rec_loss',\n log_dict_ae['train/rec_loss'],\n prog_bar=True,\n logger=True,\n on_step=True,\n on_epoch=True)\n self.log(\n 'aeloss',\n aeloss,\n prog_bar=True,\n logger=True,\n on_step=True,\n on_epoch=True)\n self.log_dict(\n log_dict_ae,\n prog_bar=False,\n logger=True,\n on_step=True,\n on_epoch=False)\n return aeloss\n\n if optimizer_idx == 1:\n # train the discriminator\n discloss, log_dict_disc = self.loss(\n inputs,\n reconstructions,\n posterior,\n optimizer_idx,\n self.global_step,\n last_layer=self.get_last_layer(),\n split='train')\n\n self.log(\n 'discloss',\n discloss,\n prog_bar=True,\n logger=True,\n on_step=True,\n on_epoch=True)\n self.log_dict(\n log_dict_disc,\n prog_bar=False,\n logger=True,\n on_step=True,\n on_epoch=False)\n return discloss\n\n def validation_step(self, batch, batch_idx):\n inputs = self.get_input(batch, self.image_key)\n reconstructions, posterior = self(inputs)\n aeloss, log_dict_ae = self.loss(\n inputs,\n reconstructions,\n posterior,\n 0,\n self.global_step,\n last_layer=self.get_last_layer(),\n split='val')\n\n discloss, log_dict_disc = self.loss(\n inputs,\n reconstructions,\n posterior,\n 1,\n self.global_step,\n last_layer=self.get_last_layer(),\n split='val')\n\n self.log('val/rec_loss', log_dict_ae['val/rec_loss'])\n self.log_dict(log_dict_ae)\n self.log_dict(log_dict_disc)\n return self.log_dict\n\n @torch.no_grad()\n def test_step(self, batch, batch_idx):\n pass\n\n @torch.no_grad()\n def sample_imgs(self, batch):\n '''using to test for sampling image\n\n '''\n inputs = self.get_input(batch, self.image_key)\n reconstructions, posterior = self(inputs)\n\n return {'samples': reconstructions}\n\n def configure_optimizers(self):\n lr = self.learning_rate\n opt_ae = torch.optim.Adam(\n list(self.encoder.parameters()) + list(self.decoder.parameters())\n + list(self.quant_conv.parameters())\n + list(self.post_quant_conv.parameters()),\n lr=lr,\n betas=(0.5, 0.9))\n opt_disc = torch.optim.Adam(\n self.loss.discriminator.parameters(), lr=lr, betas=(0.5, 0.9))\n\n return [opt_ae, opt_disc], []\n\n def get_last_layer(self):\n return self.decoder.conv_out.weight\n\n @torch.no_grad()\n def log_images(self, batch, only_inputs=False, **kwargs):\n log = dict()\n x = self.get_input(batch, self.image_key)\n x = x.to(self.device)\n if not only_inputs:\n xrec, posterior = self(x)\n xrec = repeat(xrec[:, 0, ...], 'b h w -> b c h w', c=3)\n\n if x.shape[1] > 3:\n # colorize with random projection\n assert xrec.shape[1] > 3\n x = self.to_rgb(x)\n xrec = self.to_rgb(xrec)\n samples = self.decode(torch.randn_like(posterior.sample()))\n samples = repeat(samples[:, 0, ...], 'b h w -> b c h w', c=3)\n log['samples'] = samples\n\n log['reconstructions'] = xrec\n log['inputs'] = x\n return log\n\n @torch.no_grad()\n def log_rgbd(self, batch, only_inputs=False, **kwargs):\n log = dict()\n x = self.get_input(batch, self.image_key)\n\n if x.shape[1] == 3:\n if self.prior_model is not None:\n x = self.prior_inference(x, batch['prior'])\n\n x = x.to(self.device)\n if not only_inputs:\n xrec, posterior = self(x)\n samples = self.decode(torch.randn_like(posterior.sample()))\n log['samples'] = samples\n log['reconstructions'] = xrec\n log['inputs'] = x\n return log\n\n def to_rgb(self, x):\n assert self.image_key == 'segmentation'\n if not hasattr(self, 'colorize'):\n self.register_buffer('colorize',\n torch.randn(3, x.shape[1], 1, 1).to(x))\n x = F.conv2d(x, weight=self.colorize)\n x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.\n return x" }, { "identifier": "IdentityFirstStage", "path": "ldm/models/autoencoder.py", "snippet": "class IdentityFirstStage(torch.nn.Module):\n\n def __init__(self, *args, vq_interface=False, **kwargs):\n self.vq_interface = vq_interface # TODO: Should be true by default but check to not break older stuff\n super().__init__()\n\n def encode(self, x, *args, **kwargs):\n return x\n\n def decode(self, x, *args, **kwargs):\n return x\n\n def quantize(self, x, *args, **kwargs):\n if self.vq_interface:\n return x, None, [None, None, None]\n return x\n\n def forward(self, x, *args, **kwargs):\n return x" }, { "identifier": "VQModelInterface", "path": "ldm/models/autoencoder.py", "snippet": "class VQModelInterface(VQModel):\n\n def __init__(self, embed_dim, *args, **kwargs):\n super().__init__(embed_dim=embed_dim, *args, **kwargs)\n self.embed_dim = embed_dim\n\n def encode(self, x):\n h = self.encoder(x)\n h = self.quant_conv(h)\n return h\n\n def decode(self, h, force_not_quantize=False):\n # also go through quantization layer\n if not force_not_quantize:\n quant, emb_loss, info = self.quantize(h)\n else:\n quant = h\n quant = self.post_quant_conv(quant)\n dec = self.decoder(quant)\n return dec" }, { "identifier": "DDIMSampler", "path": "ldm/models/diffusion/ddim.py", "snippet": "class DDIMSampler(object):\n\n def __init__(self, model, schedule='linear', **kwargs):\n super().__init__()\n self.model = model\n self.ddpm_num_timesteps = model.num_timesteps\n self.schedule = schedule\n\n def register_buffer(self, name, attr):\n if type(attr) == torch.Tensor:\n if attr.device != torch.device('cuda'):\n attr = attr.to(torch.device('cuda'))\n setattr(self, name, attr)\n\n def make_schedule(self,\n ddim_num_steps,\n ddim_discretize='uniform',\n ddim_eta=0.,\n verbose=True):\n self.ddim_timesteps = make_ddim_timesteps(\n ddim_discr_method=ddim_discretize,\n num_ddim_timesteps=ddim_num_steps,\n num_ddpm_timesteps=self.ddpm_num_timesteps,\n verbose=verbose)\n alphas_cumprod = self.model.alphas_cumprod\n assert alphas_cumprod.shape[\n 0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'\n to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model\n .device)\n\n self.register_buffer('betas', to_torch(self.model.betas))\n self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))\n self.register_buffer('alphas_cumprod_prev',\n to_torch(self.model.alphas_cumprod_prev))\n\n # calculations for diffusion q(x_t | x_{t-1}) and others\n self.register_buffer('sqrt_alphas_cumprod',\n to_torch(np.sqrt(alphas_cumprod.cpu())))\n self.register_buffer('sqrt_one_minus_alphas_cumprod',\n to_torch(np.sqrt(1. - alphas_cumprod.cpu())))\n self.register_buffer('log_one_minus_alphas_cumprod',\n to_torch(np.log(1. - alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recip_alphas_cumprod',\n to_torch(np.sqrt(1. / alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recipm1_alphas_cumprod',\n to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))\n\n # ddim sampling parameters\n ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(\n alphacums=alphas_cumprod.cpu(),\n ddim_timesteps=self.ddim_timesteps,\n eta=ddim_eta,\n verbose=verbose)\n self.register_buffer('ddim_sigmas', ddim_sigmas)\n self.register_buffer('ddim_alphas', ddim_alphas)\n self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)\n self.register_buffer('ddim_sqrt_one_minus_alphas',\n np.sqrt(1. - ddim_alphas))\n sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(\n (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) *\n (1 - self.alphas_cumprod / self.alphas_cumprod_prev))\n self.register_buffer('ddim_sigmas_for_original_num_steps',\n sigmas_for_original_sampling_steps)\n\n @torch.no_grad()\n def sample(\n self,\n S,\n batch_size,\n shape,\n conditioning=None,\n callback=None,\n normals_sequence=None,\n img_callback=None,\n quantize_x0=False,\n eta=0.,\n mask=None,\n x0=None,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n verbose=True,\n x_T=None,\n log_every_t=100,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None,\n # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...\n **kwargs):\n if conditioning is not None:\n if isinstance(conditioning, dict):\n cbs = conditioning[list(conditioning.keys())[0]].shape[0]\n if cbs != batch_size:\n print(\n f'Warning: Got {cbs} conditionings but batch-size is {batch_size}'\n )\n else:\n if conditioning.shape[0] != batch_size:\n print(\n f'Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}'\n )\n\n self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)\n # sampling\n C, H, W = shape\n size = (batch_size, C, H, W)\n\n samples, intermediates = self.ddim_sampling(\n conditioning,\n size,\n callback=callback,\n img_callback=img_callback,\n quantize_denoised=quantize_x0,\n mask=mask,\n x0=x0,\n ddim_use_original_steps=False,\n noise_dropout=noise_dropout,\n temperature=temperature,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n x_T=x_T,\n log_every_t=log_every_t,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n **kwargs)\n return samples, intermediates\n\n @torch.no_grad()\n def ddim_sampling(self,\n cond,\n shape,\n x_T=None,\n ddim_use_original_steps=False,\n callback=None,\n timesteps=None,\n quantize_denoised=False,\n mask=None,\n x0=None,\n img_callback=None,\n log_every_t=100,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None,\n **kwargs):\n device = self.model.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n if timesteps is None:\n timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps\n elif timesteps is not None and not ddim_use_original_steps:\n subset_end = int(\n min(timesteps / self.ddim_timesteps.shape[0], 1)\n * self.ddim_timesteps.shape[0]) - 1\n timesteps = self.ddim_timesteps[:subset_end]\n\n intermediates = {'x_inter': [img], 'pred_x0': [img]}\n time_range = reversed(range(\n 0, timesteps)) if ddim_use_original_steps else np.flip(timesteps)\n total_steps = timesteps if ddim_use_original_steps else timesteps.shape[\n 0]\n\n iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)\n\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((b, ), step, device=device, dtype=torch.long)\n\n if mask is not None:\n assert x0 is not None\n img_orig = self.model.q_sample(\n x0, ts) # TODO: deterministic forward pass?\n img = img_orig * mask + (1. - mask) * img\n\n outs = self.p_sample_ddim(\n img,\n cond,\n ts,\n index=index,\n use_original_steps=ddim_use_original_steps,\n quantize_denoised=quantize_denoised,\n temperature=temperature,\n noise_dropout=noise_dropout,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n **kwargs)\n img, pred_x0 = outs\n if callback: callback(i)\n if img_callback: img_callback(pred_x0, i)\n\n if index % log_every_t == 0 or index == total_steps - 1:\n intermediates['x_inter'].append(img)\n intermediates['pred_x0'].append(pred_x0)\n\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_ddim(self,\n x,\n c,\n t,\n index,\n repeat_noise=False,\n use_original_steps=False,\n quantize_denoised=False,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None,\n dynamic_threshold=None,\n **kwargs):\n b, *_, device = *x.shape, x.device\n\n if unconditional_conditioning is None or unconditional_guidance_scale == 1.:\n model_output = self.model.apply_model(x, t, c)\n else:\n x_in = torch.cat([x] * 2)\n t_in = torch.cat([t] * 2)\n if isinstance(c, dict):\n assert isinstance(unconditional_conditioning, dict)\n c_in = dict()\n for k in c:\n if isinstance(c[k], list):\n c_in[k] = [\n torch.cat(\n [unconditional_conditioning[k][i], c[k][i]])\n for i in range(len(c[k]))\n ]\n elif isinstance(c[k], torch.Tensor):\n c_in[k] = torch.cat(\n [unconditional_conditioning[k], c[k]])\n else:\n assert c[k] == unconditional_conditioning[k]\n c_in[k] = c[k]\n elif isinstance(c, list):\n c_in = list()\n assert isinstance(unconditional_conditioning, list)\n for i in range(len(c)):\n c_in.append(\n torch.cat([unconditional_conditioning[i], c[i]]))\n else:\n c_in = torch.cat([unconditional_conditioning, c])\n model_uncond, model_t = self.model.apply_model(x_in, t_in,\n c_in).chunk(2)\n # model_t = self.model.apply_model(x, t, c, **kwargs)\n # model_uncond = self.model.apply_model(x, t, unconditional_conditioning, **kwargs)\n model_output = model_uncond + unconditional_guidance_scale * (\n model_t - model_uncond)\n\n if self.model.parameterization == 'v':\n print('using v!')\n e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)\n else:\n e_t = model_output\n\n if score_corrector is not None:\n assert self.model.parameterization == 'eps', 'not implemented'\n e_t = score_corrector.modify_score(self.model, e_t, x, t, c,\n **corrector_kwargs)\n\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n # select parameters corresponding to the currently considered timestep\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)\n sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n sqrt_one_minus_at = torch.full((b, 1, 1, 1),\n sqrt_one_minus_alphas[index],\n device=device)\n\n # current prediction for x_0\n if self.model.parameterization != 'v':\n pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n else:\n pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)\n\n if quantize_denoised:\n pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n\n if dynamic_threshold is not None:\n raise NotImplementedError()\n\n # direction pointing to x_t\n dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t\n noise = sigma_t * noise_like(x.shape, device,\n repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n return x_prev, pred_x0\n\n @torch.no_grad()\n def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):\n # fast, but does not allow for exact reconstruction\n # t serves as an index to gather the correct alphas\n if use_original_steps:\n sqrt_alphas_cumprod = self.sqrt_alphas_cumprod\n sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod\n else:\n sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)\n sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas\n\n if noise is None:\n noise = torch.randn_like(x0)\n return (\n extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0\n + extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape)\n * noise)\n\n @torch.no_grad()\n def decode(self,\n x_latent,\n cond,\n t_start,\n unconditional_guidance_scale=1.0,\n unconditional_conditioning=None,\n use_original_steps=False,\n **kwargs):\n\n timesteps = np.arange(self.ddpm_num_timesteps\n ) if use_original_steps else self.ddim_timesteps\n timesteps = timesteps[:t_start]\n\n time_range = np.flip(timesteps)\n total_steps = timesteps.shape[0]\n\n iterator = tqdm(time_range, desc='Decoding image', total=total_steps)\n x_dec = x_latent\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((x_latent.shape[0], ),\n step,\n device=x_latent.device,\n dtype=torch.long)\n x_dec, _ = self.p_sample_ddim(\n x_dec,\n cond,\n ts,\n index=index,\n use_original_steps=use_original_steps,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n **kwargs)\n return x_dec" }, { "identifier": "DPMSolverSampler", "path": "ldm/models/diffusion/dpm_solver/sampler.py", "snippet": "class DPMSolverSampler(object):\n\n def __init__(self, model, **kwargs):\n super().__init__()\n self.model = model\n to_torch = lambda x: x.clone().detach().to(torch.float32).to(model.\n device)\n self.register_buffer('alphas_cumprod', to_torch(model.alphas_cumprod))\n\n def register_buffer(self, name, attr):\n if type(attr) == torch.Tensor:\n if attr.device != torch.device('cuda'):\n attr = attr.to(torch.device('cuda'))\n setattr(self, name, attr)\n\n @torch.no_grad()\n def sample(\n self,\n S,\n batch_size,\n shape,\n conditioning=None,\n callback=None,\n normals_sequence=None,\n img_callback=None,\n quantize_x0=False,\n eta=0.,\n mask=None,\n x0=None,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n verbose=True,\n x_T=None,\n log_every_t=100,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None,\n # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...\n **kwargs):\n if conditioning is not None:\n if isinstance(conditioning, dict):\n cbs = conditioning[list(conditioning.keys())[0]].shape[0]\n if cbs != batch_size:\n print(\n f'Warning: Got {cbs} conditionings but batch-size is {batch_size}'\n )\n else:\n if conditioning.shape[0] != batch_size:\n print(\n f'Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}'\n )\n\n # sampling\n C, H, W = shape\n size = (batch_size, C, H, W)\n\n # print(f'Data shape for DPM-Solver sampling is {size}, sampling steps {S}')\n\n device = self.model.betas.device\n if x_T is None:\n img = torch.randn(size, device=device)\n else:\n img = x_T\n\n ns = NoiseScheduleVP('discrete', alphas_cumprod=self.alphas_cumprod)\n\n model_fn = model_wrapper(\n lambda x, t, c: self.model.apply_model(x, t, c),\n ns,\n model_type='noise',\n guidance_type='classifier-free',\n condition=conditioning,\n unconditional_condition=unconditional_conditioning,\n guidance_scale=unconditional_guidance_scale,\n )\n\n dpm_solver = DPM_Solver(\n model_fn, ns, predict_x0=True, thresholding=False)\n x = dpm_solver.sample(\n img,\n steps=S,\n skip_type='time_uniform',\n method='multistep',\n order=2,\n lower_order_final=True)\n\n return x.to(device), None" }, { "identifier": "PLMSSampler", "path": "ldm/models/diffusion/plms.py", "snippet": "class PLMSSampler(object):\n\n def __init__(self, model, schedule='linear', **kwargs):\n super().__init__()\n self.model = model\n self.ddpm_num_timesteps = model.num_timesteps\n self.schedule = schedule\n\n def register_buffer(self, name, attr):\n if type(attr) == torch.Tensor:\n if attr.device != torch.device('cuda'):\n attr = attr.to(torch.device('cuda'))\n setattr(self, name, attr)\n\n def make_schedule(self,\n ddim_num_steps,\n ddim_discretize='uniform',\n ddim_eta=0.,\n verbose=True):\n if ddim_eta != 0:\n raise ValueError('ddim_eta must be 0 for PLMS')\n self.ddim_timesteps = make_ddim_timesteps(\n ddim_discr_method=ddim_discretize,\n num_ddim_timesteps=ddim_num_steps,\n num_ddpm_timesteps=self.ddpm_num_timesteps,\n verbose=verbose)\n alphas_cumprod = self.model.alphas_cumprod\n assert alphas_cumprod.shape[\n 0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'\n to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model\n .device)\n\n self.register_buffer('betas', to_torch(self.model.betas))\n self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))\n self.register_buffer('alphas_cumprod_prev',\n to_torch(self.model.alphas_cumprod_prev))\n\n # calculations for diffusion q(x_t | x_{t-1}) and others\n self.register_buffer('sqrt_alphas_cumprod',\n to_torch(np.sqrt(alphas_cumprod.cpu())))\n self.register_buffer('sqrt_one_minus_alphas_cumprod',\n to_torch(np.sqrt(1. - alphas_cumprod.cpu())))\n self.register_buffer('log_one_minus_alphas_cumprod',\n to_torch(np.log(1. - alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recip_alphas_cumprod',\n to_torch(np.sqrt(1. / alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recipm1_alphas_cumprod',\n to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))\n\n # ddim sampling parameters\n ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(\n alphacums=alphas_cumprod.cpu(),\n ddim_timesteps=self.ddim_timesteps,\n eta=ddim_eta,\n verbose=verbose)\n self.register_buffer('ddim_sigmas', ddim_sigmas)\n self.register_buffer('ddim_alphas', ddim_alphas)\n self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)\n self.register_buffer('ddim_sqrt_one_minus_alphas',\n np.sqrt(1. - ddim_alphas))\n sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(\n (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) *\n (1 - self.alphas_cumprod / self.alphas_cumprod_prev))\n self.register_buffer('ddim_sigmas_for_original_num_steps',\n sigmas_for_original_sampling_steps)\n\n @torch.no_grad()\n def sample(\n self,\n S,\n batch_size,\n shape,\n conditioning=None,\n callback=None,\n normals_sequence=None,\n img_callback=None,\n quantize_x0=False,\n eta=0.,\n mask=None,\n x0=None,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n verbose=True,\n x_T=None,\n log_every_t=100,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None,\n # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...\n **kwargs):\n if conditioning is not None:\n if isinstance(conditioning, dict):\n cbs = conditioning[list(conditioning.keys())[0]].shape[0]\n if cbs != batch_size:\n print(\n f'Warning: Got {cbs} conditionings but batch-size is {batch_size}'\n )\n else:\n if conditioning.shape[0] != batch_size:\n print(\n f'Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}'\n )\n\n self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)\n # sampling\n C, H, W = shape\n size = (batch_size, C, H, W)\n print(f'Data shape for PLMS sampling is {size}')\n\n samples, intermediates = self.plms_sampling(\n conditioning,\n size,\n callback=callback,\n img_callback=img_callback,\n quantize_denoised=quantize_x0,\n mask=mask,\n x0=x0,\n ddim_use_original_steps=False,\n noise_dropout=noise_dropout,\n temperature=temperature,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n x_T=x_T,\n log_every_t=log_every_t,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n )\n return samples, intermediates\n\n @torch.no_grad()\n def plms_sampling(\n self,\n cond,\n shape,\n x_T=None,\n ddim_use_original_steps=False,\n callback=None,\n timesteps=None,\n quantize_denoised=False,\n mask=None,\n x0=None,\n img_callback=None,\n log_every_t=100,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None,\n ):\n device = self.model.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n if timesteps is None:\n timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps\n elif timesteps is not None and not ddim_use_original_steps:\n subset_end = int(\n min(timesteps / self.ddim_timesteps.shape[0], 1)\n * self.ddim_timesteps.shape[0]) - 1\n timesteps = self.ddim_timesteps[:subset_end]\n\n intermediates = {'x_inter': [img], 'pred_x0': [img]}\n time_range = list(reversed(range(\n 0, timesteps))) if ddim_use_original_steps else np.flip(timesteps)\n total_steps = timesteps if ddim_use_original_steps else timesteps.shape[\n 0]\n print(f'Running PLMS Sampling with {total_steps} timesteps')\n\n iterator = tqdm(time_range, desc='PLMS Sampler', total=total_steps)\n old_eps = []\n\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((b, ), step, device=device, dtype=torch.long)\n ts_next = torch.full((b, ),\n time_range[min(i + 1,\n len(time_range) - 1)],\n device=device,\n dtype=torch.long)\n\n if mask is not None:\n assert x0 is not None\n img_orig = self.model.q_sample(\n x0, ts) # TODO: deterministic forward pass?\n img = img_orig * mask + (1. - mask) * img\n\n outs = self.p_sample_plms(\n img,\n cond,\n ts,\n index=index,\n use_original_steps=ddim_use_original_steps,\n quantize_denoised=quantize_denoised,\n temperature=temperature,\n noise_dropout=noise_dropout,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n old_eps=old_eps,\n t_next=ts_next)\n img, pred_x0, e_t = outs\n old_eps.append(e_t)\n if len(old_eps) >= 4:\n old_eps.pop(0)\n if callback: callback(i)\n if img_callback: img_callback(pred_x0, i)\n\n if index % log_every_t == 0 or index == total_steps - 1:\n intermediates['x_inter'].append(img)\n intermediates['pred_x0'].append(pred_x0)\n\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_plms(self,\n x,\n c,\n t,\n index,\n repeat_noise=False,\n use_original_steps=False,\n quantize_denoised=False,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None,\n old_eps=None,\n t_next=None):\n b, *_, device = *x.shape, x.device\n\n def get_model_output(x, t):\n if unconditional_conditioning is None or unconditional_guidance_scale == 1.:\n e_t = self.model.apply_model(x, t, c)\n else:\n x_in = torch.cat([x] * 2)\n t_in = torch.cat([t] * 2)\n c_in = torch.cat([unconditional_conditioning, c])\n e_t_uncond, e_t = self.model.apply_model(x_in, t_in,\n c_in).chunk(2)\n e_t = e_t_uncond + unconditional_guidance_scale * (\n e_t - e_t_uncond)\n\n if score_corrector is not None:\n assert self.model.parameterization == 'eps'\n e_t = score_corrector.modify_score(self.model, e_t, x, t, c,\n **corrector_kwargs)\n\n return e_t\n\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n\n def get_x_prev_and_pred_x0(e_t, index):\n # select parameters corresponding to the currently considered timestep\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n a_prev = torch.full((b, 1, 1, 1),\n alphas_prev[index],\n device=device)\n sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n sqrt_one_minus_at = torch.full((b, 1, 1, 1),\n sqrt_one_minus_alphas[index],\n device=device)\n\n # current prediction for x_0\n pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n if quantize_denoised:\n pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n # direction pointing to x_t\n dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t\n noise = sigma_t * noise_like(x.shape, device,\n repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n return x_prev, pred_x0\n\n e_t = get_model_output(x, t)\n if len(old_eps) == 0:\n # Pseudo Improved Euler (2nd order)\n x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t, index)\n e_t_next = get_model_output(x_prev, t_next)\n e_t_prime = (e_t + e_t_next) / 2\n elif len(old_eps) == 1:\n # 2nd order Pseudo Linear Multistep (Adams-Bashforth)\n e_t_prime = (3 * e_t - old_eps[-1]) / 2\n elif len(old_eps) == 2:\n # 3nd order Pseudo Linear Multistep (Adams-Bashforth)\n e_t_prime = (23 * e_t - 16 * old_eps[-1] + 5 * old_eps[-2]) / 12\n elif len(old_eps) >= 3:\n # 4nd order Pseudo Linear Multistep (Adams-Bashforth)\n e_t_prime = (55 * e_t - 59 * old_eps[-1] + 37 * old_eps[-2]\n - 9 * old_eps[-3]) / 24\n\n x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t_prime, index)\n\n return x_prev, pred_x0, e_t" }, { "identifier": "CrossAttention", "path": "ldm/modules/attention.py", "snippet": "class CrossAttention(nn.Module):\n\n def __init__(self,\n query_dim,\n context_dim=None,\n heads=8,\n dim_head=64,\n dropout=0.):\n super().__init__()\n inner_dim = dim_head * heads\n context_dim = default(context_dim, query_dim)\n\n self.scale = dim_head**-0.5\n self.heads = heads\n\n self.to_q = nn.Linear(query_dim, inner_dim, bias=False)\n self.to_k = nn.Linear(context_dim, inner_dim, bias=False)\n self.to_v = nn.Linear(context_dim, inner_dim, bias=False)\n\n self.to_out = nn.Sequential(\n nn.Linear(inner_dim, query_dim), nn.Dropout(dropout))\n\n def forward(self, x, context=None, mask=None):\n h = self.heads\n\n q = self.to_q(x)\n context = default(context, x)\n k = self.to_k(context)\n v = self.to_v(context)\n\n q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h),\n (q, k, v))\n\n sim = einsum('b i d, b j d -> b i j', q, k) * self.scale\n\n if exists(mask):\n mask = rearrange(mask, 'b ... -> b (...)')\n max_neg_value = -torch.finfo(sim.dtype).max\n mask = repeat(mask, 'b j -> (b h) () j', h=h)\n sim.masked_fill_(~mask, max_neg_value)\n\n # attention, what we cannot get enough of\n attn = sim.softmax(dim=-1)\n\n out = einsum('b i j, b j d -> b i d', attn, v)\n out = rearrange(out, '(b h) n d -> b n (h d)', h=h)\n return self.to_out(out)" }, { "identifier": "extract_into_tensor", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def extract_into_tensor(a, t, x_shape):\n b, *_ = t.shape\n out = a.gather(-1, t)\n return out.reshape(b, *((1, ) * (len(x_shape) - 1)))" }, { "identifier": "make_beta_schedule", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def make_beta_schedule(schedule,\n n_timestep,\n linear_start=1e-4,\n linear_end=2e-2,\n cosine_s=8e-3):\n if schedule == 'linear':\n betas = (\n torch.linspace(\n linear_start**0.5,\n linear_end**0.5,\n n_timestep,\n dtype=torch.float64)**2)\n\n elif schedule == 'cosine':\n timesteps = (\n torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep\n + cosine_s)\n alphas = timesteps / (1 + cosine_s) * np.pi / 2\n alphas = torch.cos(alphas).pow(2)\n alphas = alphas / alphas[0]\n betas = 1 - alphas[1:] / alphas[:-1]\n betas = np.clip(betas, a_min=0, a_max=0.999)\n\n elif schedule == 'sqrt_linear':\n betas = torch.linspace(\n linear_start, linear_end, n_timestep, dtype=torch.float64)\n elif schedule == 'sqrt':\n betas = torch.linspace(\n linear_start, linear_end, n_timestep, dtype=torch.float64)**0.5\n else:\n raise ValueError(f\"schedule '{schedule}' unknown.\")\n return betas.numpy()" }, { "identifier": "noise_like", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def noise_like(shape, device, repeat=False):\n repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(\n shape[0], *((1, ) * (len(shape) - 1)))\n noise = lambda: torch.randn(shape, device=device)\n return repeat_noise() if repeat else noise()" }, { "identifier": "DiagonalGaussianDistribution", "path": "ldm/modules/distributions/distributions.py", "snippet": "class DiagonalGaussianDistribution(object):\n\n def __init__(self, parameters, deterministic=False):\n self.parameters = parameters\n self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)\n self.logvar = torch.clamp(self.logvar, -30.0, 20.0)\n self.deterministic = deterministic\n self.std = torch.exp(0.5 * self.logvar)\n self.var = torch.exp(self.logvar)\n if self.deterministic:\n self.var = self.std = torch.zeros_like(\n self.mean).to(device=self.parameters.device)\n\n def sample(self):\n x = self.mean + self.std * torch.randn(\n self.mean.shape).to(device=self.parameters.device)\n return x\n\n def kl(self, other=None):\n if self.deterministic:\n return torch.Tensor([0.])\n else:\n if other is None:\n return 0.5 * torch.sum(\n torch.pow(self.mean, 2) + self.var - 1.0 - self.logvar,\n dim=[1, 2, 3])\n else:\n return 0.5 * torch.sum(\n torch.pow(self.mean - other.mean, 2) / other.var\n + self.var / other.var - 1.0 - self.logvar + other.logvar,\n dim=[1, 2, 3])\n\n def nll(self, sample, dims=[1, 2, 3]):\n if self.deterministic:\n return torch.Tensor([0.])\n logtwopi = np.log(2.0 * np.pi)\n return 0.5 * torch.sum(\n logtwopi + self.logvar\n + torch.pow(sample - self.mean, 2) / self.var,\n dim=dims)\n\n def mode(self):\n return self.mean" }, { "identifier": "normal_kl", "path": "ldm/modules/distributions/distributions.py", "snippet": "def normal_kl(mean1, logvar1, mean2, logvar2):\n \"\"\"\n source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12\n Compute the KL divergence between two gaussians.\n Shapes are automatically broadcasted, so batches can be compared to\n scalars, among other use cases.\n \"\"\"\n tensor = None\n for obj in (mean1, logvar1, mean2, logvar2):\n if isinstance(obj, torch.Tensor):\n tensor = obj\n break\n assert tensor is not None, 'at least one argument must be a Tensor'\n\n # Force variances to be Tensors. Broadcasting helps convert scalars to\n # Tensors, but it does not work for torch.exp().\n logvar1, logvar2 = [\n x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor)\n for x in (logvar1, logvar2)\n ]\n\n return 0.5 * (-1.0 + logvar2 - logvar1 + torch.exp(logvar1 - logvar2) +\n ((mean1 - mean2)**2) * torch.exp(-logvar2))" }, { "identifier": "LitEma", "path": "ldm/modules/ema.py", "snippet": "class LitEma(nn.Module):\n\n def __init__(self, model, decay=0.9999, use_num_upates=True):\n super().__init__()\n if decay < 0.0 or decay > 1.0:\n raise ValueError('Decay must be between 0 and 1')\n\n self.m_name2s_name = {}\n self.register_buffer('decay', torch.tensor(decay, dtype=torch.float32))\n self.register_buffer(\n 'num_updates',\n torch.tensor(0, dtype=torch.int)\n if use_num_upates else torch.tensor(-1, dtype=torch.int))\n\n for name, p in model.named_parameters():\n if p.requires_grad:\n #remove as '.'-character is not allowed in buffers\n s_name = name.replace('.', '')\n self.m_name2s_name.update({name: s_name})\n self.register_buffer(s_name, p.clone().detach().data)\n\n self.collected_params = []\n\n def forward(self, model):\n decay = self.decay\n\n if self.num_updates >= 0:\n self.num_updates += 1\n decay = min(self.decay, (1 + self.num_updates) /\n (10 + self.num_updates))\n\n one_minus_decay = 1.0 - decay\n\n with torch.no_grad():\n m_param = dict(model.named_parameters())\n shadow_params = dict(self.named_buffers())\n\n for key in m_param:\n if m_param[key].requires_grad:\n sname = self.m_name2s_name[key]\n shadow_params[sname] = shadow_params[sname].type_as(\n m_param[key])\n shadow_params[sname].sub_(\n one_minus_decay *\n (shadow_params[sname] - m_param[key]))\n else:\n assert not key in self.m_name2s_name\n\n def copy_to(self, model):\n m_param = dict(model.named_parameters())\n shadow_params = dict(self.named_buffers())\n for key in m_param:\n if m_param[key].requires_grad:\n m_param[key].data.copy_(\n shadow_params[self.m_name2s_name[key]].data)\n else:\n assert not key in self.m_name2s_name\n\n def store(self, parameters):\n \"\"\"\n Save the current parameters for restoring later.\n Args:\n parameters: Iterable of `torch.nn.Parameter`; the parameters to be\n temporarily stored.\n \"\"\"\n self.collected_params = [param.clone() for param in parameters]\n\n def restore(self, parameters):\n \"\"\"\n Restore the parameters stored with the `store` method.\n Useful to validate the model with EMA parameters without affecting the\n original optimization process. Store the parameters before the\n `copy_to` method. After validation (or model saving), use this to\n restore the former parameters.\n Args:\n parameters: Iterable of `torch.nn.Parameter`; the parameters to be\n updated with the stored parameters.\n \"\"\"\n for c_param, param in zip(self.collected_params, parameters):\n param.data.copy_(c_param.data)" }, { "identifier": "count_params", "path": "ldm/util.py", "snippet": "def count_params(model, verbose=False):\n total_params = sum(p.numel() for p in model.parameters())\n if verbose:\n print(\n f'{model.__class__.__name__} has {total_params * 1.e-6:.2f} M params.'\n )\n return total_params" }, { "identifier": "default", "path": "ldm/util.py", "snippet": "def default(val, d):\n if exists(val):\n return val\n return d() if isfunction(d) else d" }, { "identifier": "exists", "path": "ldm/util.py", "snippet": "def exists(x):\n return x is not None" }, { "identifier": "filter_nan_loss", "path": "ldm/util.py", "snippet": "def filter_nan_loss(loss):\n fake_loss = torch.isnan(loss)\n loss = loss[torch.logical_not(fake_loss)]\n\n if loss.shape[0] == 0:\n return loss.sum()\n else:\n return loss" }, { "identifier": "instantiate_from_config", "path": "ldm/util.py", "snippet": "def instantiate_from_config(config):\n if not 'target' in config:\n\n print(config)\n if config == '__is_first_stage__':\n return None\n elif config == '__is_unconditional__':\n return None\n raise KeyError('Expected key `target` to instantiate.')\n return get_obj_from_str(config['target'])(**config.get('params', dict()))" }, { "identifier": "isimage", "path": "ldm/util.py", "snippet": "def isimage(x):\n if not isinstance(x, torch.Tensor):\n return False\n return (len(x.shape) == 4) and (x.shape[1] == 3 or x.shape[1] == 1)" }, { "identifier": "ismap", "path": "ldm/util.py", "snippet": "def ismap(x):\n if not isinstance(x, torch.Tensor):\n return False\n return (len(x.shape) == 4) and (x.shape[1] > 3)" }, { "identifier": "log_txt_as_img", "path": "ldm/util.py", "snippet": "def log_txt_as_img(wh, xc, size=20):\n # wh a tuple of (width, height)\n # xc a list of captions to plot\n b = len(xc)\n txts = list()\n for bi in range(b):\n txt = Image.new('RGB', wh, color='white')\n draw = ImageDraw.Draw(txt)\n font = ImageFont.truetype('data/DejaVuSans.ttf', size=size)\n nc = int(10 * (wh[0] / 256))\n lines = '\\n'.join(xc[bi][start:start + nc]\n for start in range(0, len(xc[bi]), nc))\n\n try:\n draw.text((0, 0), lines, fill='black', font=font)\n except UnicodeEncodeError:\n print('Cant encode string for logging. Skipping.')\n\n txt = np.array(txt).transpose(2, 0, 1) / 127.5 - 1.0\n txts.append(txt)\n txts = np.stack(txts)\n txts = torch.tensor(txts)\n return txts" }, { "identifier": "mean_flat", "path": "ldm/util.py", "snippet": "def mean_flat(tensor):\n \"\"\"\n https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86\n Take the mean over all non-batch dimensions.\n \"\"\"\n return tensor.mean(dim=list(range(1, len(tensor.shape))))" } ]
import pdb import numpy as np import pytorch_lightning as pl import torch import torch.nn as nn import torch.nn.functional as F from contextlib import contextmanager from functools import partial from einops import rearrange, repeat from ldm.models.autoencoder import (AutoencoderKL, IdentityFirstStage, VQModelInterface) from ldm.models.diffusion.ddim import DDIMSampler from ldm.models.diffusion.dpm_solver import DPMSolverSampler from ldm.models.diffusion.plms import PLMSSampler from ldm.modules.attention import CrossAttention from ldm.modules.diffusionmodules.util import (extract_into_tensor, make_beta_schedule, noise_like) from ldm.modules.distributions.distributions import ( DiagonalGaussianDistribution, normal_kl) from ldm.modules.ema import LitEma from ldm.util import (count_params, default, exists, filter_nan_loss, instantiate_from_config, isimage, ismap, log_txt_as_img, mean_flat) from torch.optim.lr_scheduler import LambdaLR from torchvision.utils import make_grid from tqdm import tqdm from pytorch_lightning.utilities.distributed import rank_zero_only from pytorch_lightning.utilities.rank_zero import rank_zero_only
16,562
else: c = None xc = None if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) c = {'pos_x': pos_x, 'pos_y': pos_y} out = [z, c] if return_first_stage_outputs: xrec = self.decode_first_stage(z) out.extend([x, xrec]) if return_original_cond: out.append(xc) return out ''' @torch.no_grad() def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False, cond_key=None, return_original_cond=False, bs=None, uncond=0.1): ''' we add uncondition prompts to improve classifer-free guidance results ''' x = super().get_input(batch, k) if bs is not None: x = x[:bs] x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() if self.model.conditioning_key is not None: if cond_key is None: cond_key = self.cond_stage_key if cond_key != self.first_stage_key: if cond_key in ['caption', 'coordinates_bbox']: xc = batch[cond_key] elif cond_key == 'class_label': xc = batch else: xc = super().get_input(batch, cond_key).to(self.device) else: xc = x if not self.cond_stage_trainable or force_c_encode: if isinstance(xc, dict) or isinstance(xc, list): # import pudb; pudb.set_trace() c = self.get_learned_conditioning(xc) else: c = self.get_learned_conditioning(xc.to(self.device)) else: c = xc if bs is not None: c = c[:bs] if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) ckey = __conditioning_keys__[self.model.conditioning_key] c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y} else: c = None xc = None if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) c = {'pos_x': pos_x, 'pos_y': pos_y} # To support classifier-free guidance, randomly drop out only text conditioning 10% like sd-v1.5 random = torch.rand(x.size(0), device=x.device) prompt_mask = rearrange(random < uncond, 'n -> n 1 1') null_prompts = self.get_learned_conditioning(['']).to(c.device) cc = torch.where(prompt_mask, null_prompts, c) out = [z, cc] if return_first_stage_outputs: xrec = self.decode_first_stage(z) out.extend([x, xrec]) if return_original_cond: out.append(xc) return out @torch.no_grad() def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False): if predict_cids: if z.dim() == 4: z = torch.argmax(z.exp(), dim=1).long() z = self.first_stage_model.quantize.get_codebook_entry( z, shape=None) z = rearrange(z, 'b h w c -> b c h w').contiguous() z = 1. / self.scale_factor * z if hasattr(self, 'split_input_params'): if self.split_input_params['patch_distributed_vq']: ks = self.split_input_params['ks'] # eg. (128, 128) stride = self.split_input_params['stride'] # eg. (64, 64) uf = self.split_input_params['vqf'] bs, nc, h, w = z.shape if ks[0] > h or ks[1] > w: ks = (min(ks[0], h), min(ks[1], w)) print('reducing Kernel') if stride[0] > h or stride[1] > w: stride = (min(stride[0], h), min(stride[1], w)) print('reducing stride') fold, unfold, normalization, weighting = self.get_fold_unfold( z, ks, stride, uf=uf) z = unfold(z) # (bn, nc * prod(**ks), L) # 1. Reshape to img shape z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L ) # 2. apply model loop over last dim
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ try: except: __conditioning_keys__ = { 'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y' } def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class anneal_identity(): def __call__(self, x, global_step): return x def upper_bound(arr, key): left = 0 right = len(arr) while left < right: mid = (left + right) >> 1 if arr[mid] < key: left = mid + 1 else: right = mid return left class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__( self, unet_config, timesteps=1000, beta_schedule='linear', loss_type='l2', ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor='val/loss', use_ema=True, first_stage_key='image', image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0., v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1., conditioning_key=None, parameterization='eps', # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0., anneal_t=False, # we find at the begining, smaller t, larger denoise mse loss. anneal_global_step=[], anneal_ratio=0.9, prior_model=None, prior_normal=None, input_keys=['rgb'], ): super().__init__() assert parameterization in [ 'eps', 'x0' ], 'currently only supporting "eps" and "x0"' self.parameterization = parameterization print( f'{self.__class__.__name__}: Running in {self.parameterization}-prediction mode' ) self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f'Keeping EMAs of {len(list(self.model_ema.buffers()))}.') self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight self.input_keys = input_keys if monitor is not None: self.monitor = monitor if ckpt_path is not None: self.init_from_ckpt( ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet) self.register_schedule( given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) self.loss_type = loss_type self.learn_logvar = learn_logvar self.logvar = torch.full( fill_value=logvar_init, size=(self.num_timesteps, )) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) ### anneal t function if not anneal_t: self.anneal_func = anneal_identity() else: self.anneal_func = anneal_warmup(anneal_ratio, anneal_global_step, self.num_timesteps) if prior_model is not None: self.prior_model = instantiate_from_config(prior_model) else: self.prior_model = None if prior_normal is not None: self.prior_normal = instantiate_from_config(prior_normal) else: self.prior_normal = None def register_schedule(self, given_betas=None, beta_schedule='linear', timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): if exists(given_betas): betas = given_betas else: betas = make_beta_schedule( beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) alphas = 1. - betas alphas_cumprod = np.cumprod(alphas, axis=0) alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1]) timesteps, = betas.shape self.num_timesteps = int(timesteps) self.linear_start = linear_start self.linear_end = linear_end assert alphas_cumprod.shape[ 0] == self.num_timesteps, 'alphas have to be defined for each timestep' to_torch = partial(torch.tensor, dtype=torch.float32) self.register_buffer('betas', to_torch(betas)) self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev)) # calculations for diffusion q(x_t | x_{t-1}) and others self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod))) self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod))) self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1))) # calculations for posterior q(x_{t-1} | x_t, x_0) posterior_variance = (1 - self.v_posterior) * betas * ( 1. - alphas_cumprod_prev) / ( 1. - alphas_cumprod) + self.v_posterior * betas # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) self.register_buffer('posterior_variance', to_torch(posterior_variance)) # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain self.register_buffer( 'posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20)))) self.register_buffer( 'posterior_mean_coef1', to_torch(betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))) self.register_buffer( 'posterior_mean_coef2', to_torch((1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod))) if self.parameterization == 'eps': lvlb_weights = self.betas**2 / (2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)) elif self.parameterization == 'x0': lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / ( 2. * 1 - torch.Tensor(alphas_cumprod)) else: raise NotImplementedError('mu not supported') # TODO how to choose this term lvlb_weights[0] = lvlb_weights[1] self.register_buffer('lvlb_weights', lvlb_weights, persistent=False) assert not torch.isnan(self.lvlb_weights).all() @contextmanager def ema_scope(self, context=None): if self.use_ema: self.model_ema.store(self.model.parameters()) self.model_ema.copy_to(self.model) if context is not None: print(f'{context}: Switched to EMA weights') try: yield None finally: if self.use_ema: self.model_ema.restore(self.model.parameters()) if context is not None: print(f'{context}: Restored training weights') def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): sd = torch.load(path, map_location='cpu') if 'state_dict' in list(sd.keys()): sd = sd['state_dict'] keys = list(sd.keys()) for k in keys: for ik in ignore_keys: if k.startswith(ik): print('Deleting key {} from state_dict.'.format(k)) del sd[k] missing, unexpected = self.load_state_dict( sd, strict=False) if not only_model else self.model.load_state_dict( sd, strict=False) print( f'Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys' ) if len(missing) > 0: print(f'Missing Keys: {missing}') if len(unexpected) > 0: print(f'Unexpected Keys: {unexpected}') if self.use_ema: if len(missing) > 0: model_ema_str = sorted(missing)[-1] # missing model_ema if 'model_ema' in model_ema_str: print(f'Reinitialize model_ema') self.model_ema = LitEma(self.model) print( f'Keeping EMAs of {len(list(self.model_ema.buffers()))}.' ) else: if self.ema_copy == True: print(f'Reinitialize model_ema') self.model_ema = LitEma(self.model) print( f'Keeping EMAs of {len(list(self.model_ema.buffers()))}.' ) 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 predict_start_from_noise(self, x_t, t, noise): 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) * noise) def q_posterior(self, x_start, x_t, t): 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) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance(self, x, t, clip_denoised: bool): model_out = self.model(x, t) if self.parameterization == 'eps': x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == 'x0': x_recon = model_out if clip_denoised: x_recon.clamp_(-1., 1.) model_mean, posterior_variance, posterior_log_variance = self.q_posterior( x_start=x_recon, x_t=x, t=t) return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): b, *_, device = *x.shape, x.device model_mean, _, model_log_variance = self.p_mean_variance( x=x, t=t, clip_denoised=clip_denoised) noise = noise_like(x.shape, device, repeat_noise) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape( b, *((1, ) * (len(x.shape) - 1))) return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def p_sample_loop(self, shape, return_intermediates=False): device = self.betas.device b = shape[0] img = torch.randn(shape, device=device) intermediates = [img] for i in tqdm( reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps): img = self.p_sample( img, torch.full((b, ), i, device=device, dtype=torch.long), clip_denoised=self.clip_denoised) if i % self.log_every_t == 0 or i == self.num_timesteps - 1: intermediates.append(img) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, batch_size=16, return_intermediates=False): image_size = self.image_size channels = self.channels return self.p_sample_loop( (batch_size, channels, image_size, image_size), return_intermediates=return_intermediates) def q_sample(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) 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 get_loss(self, pred, target, mean=True): if self.loss_type == 'l1': loss = (target - pred).abs() if mean: loss = loss.mean() elif self.loss_type == 'l2': if mean: loss = torch.nn.functional.mse_loss(target, pred) else: loss = torch.nn.functional.mse_loss( target, pred, reduction='none') else: raise NotImplementedError("unknown loss type '{loss_type}'") return loss def p_losses(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) model_out = self.model(x_noisy, t) loss_dict = {} if self.parameterization == 'eps': target = noise elif self.parameterization == 'x0': target = x_start else: raise NotImplementedError( f'Paramterization {self.parameterization} not yet supported') loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3]) log_prefix = 'train' if self.training else 'val' loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()}) loss_simple = loss.mean() * self.l_simple_weight loss_vlb = (self.lvlb_weights[t] * loss).mean() loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb}) loss = loss_simple + self.original_elbo_weight * loss_vlb loss_dict.update({f'{log_prefix}/loss': loss}) return loss, loss_dict def forward(self, x, *args, **kwargs): # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size # assert h == img_size and w == img_size, f'height and width of image must be {img_size}' t = torch.randint( 0, self.num_timesteps, (x.shape[0], ), device=self.device).long() return self.p_losses(x, t, *args, **kwargs) def get_input(self, batch, k): x = batch[k] if len(x.shape) == 3: x = x[..., None] x = rearrange(x, 'b h w c -> b c h w') x = x.to(memory_format=torch.contiguous_format).float() return x def shared_step(self, batch): x = self.get_input(batch, self.first_stage_key) loss, loss_dict = self(x) return loss, loss_dict # property of model for (to, cuda, cpu, float, half, ...) def to(self, *args, **kwargs): # type: ignore[valid-type] """See :meth:`torch.nn.Module.to`.""" # this converts `str` device to `torch.device` if self.prior_model is not None: self.prior_model.to(*args, **kwargs) if self.prior_normal is not None: self.prior_normal.to(*args, **kwargs) return super().to(*args, **kwargs) def cuda(self, device=None): # type: ignore[valid-type] """Moves all model parameters and buffers to the GPU. This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized. Arguments: device: If specified, all parameters will be copied to that device. If `None`, the current CUDA device index will be used. Returns: Module: self """ if device is None: device = torch.device('cuda', torch.cuda.current_device()) elif isinstance(device, int): device = torch.device('cuda', index=device) if self.prior_model is not None: self.prior_model.cuda(device) if self.prior_normal is not None: self.prior_normal.cuda(device) return super().cuda(device=device) def cpu(self): # type: ignore[valid-type] """See :meth:`torch.nn.Module.cpu`.""" if self.prior_model is not None: self.prior_model.cpu() if self.prior_normal is not None: self.prior_normal.cpu() return super().cpu() def float(self): # type: ignore[valid-type] """See :meth:`torch.nn.Module.float`.""" if self.prior_model is not None: self.prior_model.float() if self.prior_normal is not None: self.prior_normal.float() return super().float() def double(self): # type: ignore[valid-type] """See :meth:`torch.nn.Module.double`.""" if self.prior_model is not None: self.prior_model.double() if self.prior_normal is not None: self.prior_normal.double() return super().double() def half(self): # type: ignore[valid-type] """See :meth:`torch.nn.Module.half`.""" if self.prior_model is not None: self.prior_model.half() if self.prior_normal is not None: self.prior_normal.half() return super().half() def prior_to_eval(self): if self.prior_model is not None: self.prior_model.eval() if self.prior_normal is not None: self.prior_normal.eval() @torch.no_grad() def prior_inference(self, inputs, prior_inputs): # depth prior model # midas or zoe is 384 model inputs = inputs.permute(0, 3, 1, 2) prior_results = {} self.prior_to_eval() # using depth prior if self.prior_model is not None: model_prior_results = self.prior_model(prior_inputs) prior_results.update(model_prior_results) # using normal map if self.prior_normal is not None: normal_prior_results = self.prior_normal(prior_inputs) prior_results.update(normal_prior_results) resize_prior_results = {} _, __, h, w = inputs.shape for key in prior_results.keys(): resize_prior_results[key] = F.interpolate( prior_results[key], (w, h), mode='bilinear') # add a rgb input resize_prior_results.update({'rgb': inputs}) input_container = [] for key in self.input_keys: input_container.append(resize_prior_results[key]) return torch.cat(input_container, dim=1).permute(0, 2, 3, 1) @torch.no_grad() def collect_inputs(self, batch): input_container = [] for key in self.input_keys: # [B H W C] input_container.append(batch[key]) return torch.cat(input_container, dim=-1) def training_step(self, batch, batch_idx): if self.prior_model is not None: batch['image'] = self.prior_inference(batch['image'], batch['prior']) # image_condition batch['ic'] = batch['image'][..., :3] else: batch['image'] = self.collect_inputs(batch) # image_condition batch['ic'] = batch['image'][..., :3] loss, loss_dict = self.shared_step(batch) self.log_dict( loss_dict, prog_bar=True, logger=True, on_step=True, on_epoch=True) self.log( 'global_step', self.global_step, prog_bar=True, logger=True, on_step=True, on_epoch=False) if self.use_scheduler: lr = self.optimizers().param_groups[0]['lr'] self.log( 'lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False) return loss @torch.no_grad() def validation_step(self, batch, batch_idx): if self.prior_model is not None: batch['image'] = self.prior_inference(batch['image'], batch['prior']) # image_condition batch['ic'] = batch['image'][..., :3] else: batch['image'] = self.collect_inputs(batch) # image_condition batch['ic'] = batch['image'][..., :3] _, loss_dict_no_ema = self.shared_step(batch) with self.ema_scope(): _, loss_dict_ema = self.shared_step(batch) loss_dict_ema = { key + '_ema': loss_dict_ema[key] for key in loss_dict_ema } self.log_dict( loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) self.log_dict( loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) @torch.no_grad() def test_step(self, batch, batch_idx): if self.prior_model is not None: batch['image'] = self.prior_inference(batch['image'], batch['prior']) # image_condition batch['ic'] = batch['image'][..., :3] else: batch['image'] = self.collect_inputs(batch) # image_condition batch['ic'] = batch['image'][..., :3] with self.ema_scope(): _, loss_dict_ema = self.shared_step(batch) loss_dict_ema = { key + '_ema': loss_dict_ema[key] for key in loss_dict_ema } self.log_dict( loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) def on_train_batch_end(self, *args, **kwargs): # args: outputs, batch, batch_idx if self.use_ema: self.model_ema(self.model) def _get_rows_from_list(self, samples): n_imgs_per_row = len(samples) denoise_grid = rearrange(samples, 'n b c h w -> b n c h w') denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w') denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid @torch.no_grad() def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs): log = dict() x = self.get_input(batch, self.first_stage_key) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) x = x.to(self.device)[:N] log['inputs'] = x # get diffusion row diffusion_row = list() x_start = x[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), '1 -> b', b=n_row) t = t.to(self.device).long() noise = torch.randn_like(x_start) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) diffusion_row.append(x_noisy) log['diffusion_row'] = self._get_rows_from_list(diffusion_row) if sample: # get denoise row with self.ema_scope('Plotting'): samples, denoise_row = self.sample( batch_size=N, return_intermediates=True) log['samples'] = samples log['denoise_row'] = self._get_rows_from_list(denoise_row) if return_keys: if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0: return log else: return {key: log[key] for key in return_keys} return log def configure_optimizers(self): lr = self.learning_rate params = list(self.model.parameters()) if self.learn_logvar: params = params + [self.logvar] opt = torch.optim.AdamW(params, lr=lr) return opt class LatentDiffusion(DDPM): """main class""" def __init__(self, first_stage_config, cond_stage_config, num_timesteps_cond=None, cond_stage_key='image', cond_stage_trainable=False, concat_mode=True, cond_stage_forward=None, conditioning_key=None, scale_factor=1.0, scale_by_std=False, first_stage_ckpts=None, without_crossattn=False, ema_copy=False, *args, **kwargs): self.num_timesteps_cond = default(num_timesteps_cond, 1) self.scale_by_std = scale_by_std assert self.num_timesteps_cond <= kwargs['timesteps'] # for backwards compatibility after implementation of DiffusionWrapper if conditioning_key is None: conditioning_key = 'concat' if concat_mode else 'crossattn' if cond_stage_config == '__is_unconditional__': conditioning_key = None ckpt_path = kwargs.pop('ckpt_path', None) ignore_keys = kwargs.pop('ignore_keys', []) super().__init__(conditioning_key=conditioning_key, *args, **kwargs) self.concat_mode = concat_mode self.cond_stage_trainable = cond_stage_trainable self.cond_stage_key = cond_stage_key try: self.num_downs = len( first_stage_config.params.ddconfig.ch_mult) - 1 except: self.num_downs = 0 if not scale_by_std: self.scale_factor = scale_factor else: self.register_buffer('scale_factor', torch.tensor(scale_factor)) self.first_stage_ckpts = first_stage_ckpts # VAE Load self.instantiate_first_stage(first_stage_config) # CLIP load self.instantiate_cond_stage(cond_stage_config) self.cond_stage_forward = cond_stage_forward self.clip_denoised = False self.bbox_tokenizer = None self.restarted_from_ckpt = False self.ema_copy = ema_copy if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys) self.restarted_from_ckpt = True if self.first_stage_ckpts is not None: first_stage_ckpts = torch.load( self.first_stage_ckpts, map_location='cpu') no_match = self.first_stage_model.load_state_dict( first_stage_ckpts['state_dict'], strict=False) print('encode-decode, no match keys:\n {}'.format(no_match)) for param in self.first_stage_model.parameters(): param.requires_grad = False # lambda-stage-1 without crossattn if without_crossattn: for m in self.modules(): if isinstance(m, CrossAttention): for para in m.parameters(): para.requires_grad = False # RuntimeError: One of the differentiated Tensors does not require grad def make_cond_schedule(self, ): self.cond_ids = torch.full( size=(self.num_timesteps, ), fill_value=self.num_timesteps - 1, dtype=torch.long) ids = torch.round( torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long() self.cond_ids[:self.num_timesteps_cond] = ids @rank_zero_only @torch.no_grad() def on_train_batch_start(self, batch, batch_idx): # only for very first batch if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt: assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously' # set rescale weight to 1./std of encodings print('### USING STD-RESCALING ###') x = super().get_input(batch, self.first_stage_key) x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() del self.scale_factor self.register_buffer('scale_factor', 1. / z.flatten().std()) print(f'setting self.scale_factor to {self.scale_factor}') print('### USING STD-RESCALING ###') def register_schedule(self, given_betas=None, beta_schedule='linear', timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s) self.shorten_cond_schedule = self.num_timesteps_cond > 1 if self.shorten_cond_schedule: self.make_cond_schedule() def instantiate_first_stage(self, config): model = instantiate_from_config(config) self.first_stage_model = model.eval() self.first_stage_model.train = disabled_train for param in self.first_stage_model.parameters(): param.requires_grad = False def instantiate_cond_stage(self, config): if not self.cond_stage_trainable: if config == '__is_first_stage__': print('Using first stage also as cond stage.') self.cond_stage_model = self.first_stage_model elif config == '__is_unconditional__': print( f'Training {self.__class__.__name__} as an unconditional model.' ) self.cond_stage_model = None # self.be_unconditional = True else: model = instantiate_from_config(config) self.cond_stage_model = model.eval() self.cond_stage_model.train = disabled_train for param in self.cond_stage_model.parameters(): param.requires_grad = False else: assert config != '__is_first_stage__' assert config != '__is_unconditional__' model = instantiate_from_config(config) self.cond_stage_model = model def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False): denoise_row = [] for zd in tqdm(samples, desc=desc): denoise_row.append( self.decode_first_stage( zd.to(self.device), force_not_quantize=force_no_decoder_quantization)) n_imgs_per_row = len(denoise_row) denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w') denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w') denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid def get_first_stage_encoding(self, encoder_posterior): if isinstance(encoder_posterior, DiagonalGaussianDistribution): z = encoder_posterior.sample() elif isinstance(encoder_posterior, torch.Tensor): z = encoder_posterior else: raise NotImplementedError( f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented" ) return self.scale_factor * z def get_learned_conditioning(self, c): ''' # CLIP embedding ''' if self.cond_stage_forward is None: if hasattr(self.cond_stage_model, 'encode') and callable( self.cond_stage_model.encode): c = self.cond_stage_model.encode(c) if isinstance(c, DiagonalGaussianDistribution): c = c.mode() else: c = self.cond_stage_model(c) else: assert hasattr(self.cond_stage_model, self.cond_stage_forward) c = getattr(self.cond_stage_model, self.cond_stage_forward)(c) return c def meshgrid(self, h, w): y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1) x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1) arr = torch.cat([y, x], dim=-1) return arr def delta_border(self, h, w): """ :param h: height :param w: width :return: normalized distance to image border, wtith min distance = 0 at border and max dist = 0.5 at image center """ lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2) arr = self.meshgrid(h, w) / lower_right_corner dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0] dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0] edge_dist = torch.min( torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0] return edge_dist def get_weighting(self, h, w, Ly, Lx, device): weighting = self.delta_border(h, w) weighting = torch.clip( weighting, self.split_input_params['clip_min_weight'], self.split_input_params['clip_max_weight'], ) weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device) if self.split_input_params['tie_braker']: L_weighting = self.delta_border(Ly, Lx) L_weighting = torch.clip( L_weighting, self.split_input_params['clip_min_tie_weight'], self.split_input_params['clip_max_tie_weight']) L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device) weighting = weighting * L_weighting return weighting def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code """ :param x: img of size (bs, c, h, w) :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1]) """ bs, nc, h, w = x.shape # number of crops in image Ly = (h - kernel_size[0]) // stride[0] + 1 Lx = (w - kernel_size[1]) // stride[1] + 1 if uf == 1 and df == 1: fold_params = dict( kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params) weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap weighting = weighting.view( (1, 1, kernel_size[0], kernel_size[1], Ly * Lx)) elif uf > 1 and df == 1: fold_params = dict( kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict( kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf), dilation=1, padding=0, stride=(stride[0] * uf, stride[1] * uf)) fold = torch.nn.Fold( output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2) weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view( 1, 1, h * uf, w * uf) # normalizes the overlap weighting = weighting.view( (1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx)) elif df > 1 and uf == 1: fold_params = dict( kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict( kernel_size=(kernel_size[0] // df, kernel_size[0] // df), dilation=1, padding=0, stride=(stride[0] // df, stride[1] // df)) fold = torch.nn.Fold( output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2) weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view( 1, 1, h // df, w // df) # normalizes the overlap weighting = weighting.view( (1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx)) else: raise NotImplementedError return fold, unfold, normalization, weighting ''' @torch.no_grad() def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False, cond_key=None, return_original_cond=False, bs=None): x = super().get_input(batch, k) if bs is not None: x = x[:bs] x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() if self.model.conditioning_key is not None: if cond_key is None: cond_key = self.cond_stage_key if cond_key != self.first_stage_key: if cond_key in ['caption', 'coordinates_bbox']: xc = batch[cond_key] elif cond_key == 'class_label': xc = batch else: xc = super().get_input(batch, cond_key).to(self.device) else: xc = x if not self.cond_stage_trainable or force_c_encode: if isinstance(xc, dict) or isinstance(xc, list): # import pudb; pudb.set_trace() c = self.get_learned_conditioning(xc) else: c = self.get_learned_conditioning(xc.to(self.device)) else: c = xc if bs is not None: c = c[:bs] if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) ckey = __conditioning_keys__[self.model.conditioning_key] c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y} else: c = None xc = None if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) c = {'pos_x': pos_x, 'pos_y': pos_y} out = [z, c] if return_first_stage_outputs: xrec = self.decode_first_stage(z) out.extend([x, xrec]) if return_original_cond: out.append(xc) return out ''' @torch.no_grad() def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False, cond_key=None, return_original_cond=False, bs=None, uncond=0.1): ''' we add uncondition prompts to improve classifer-free guidance results ''' x = super().get_input(batch, k) if bs is not None: x = x[:bs] x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() if self.model.conditioning_key is not None: if cond_key is None: cond_key = self.cond_stage_key if cond_key != self.first_stage_key: if cond_key in ['caption', 'coordinates_bbox']: xc = batch[cond_key] elif cond_key == 'class_label': xc = batch else: xc = super().get_input(batch, cond_key).to(self.device) else: xc = x if not self.cond_stage_trainable or force_c_encode: if isinstance(xc, dict) or isinstance(xc, list): # import pudb; pudb.set_trace() c = self.get_learned_conditioning(xc) else: c = self.get_learned_conditioning(xc.to(self.device)) else: c = xc if bs is not None: c = c[:bs] if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) ckey = __conditioning_keys__[self.model.conditioning_key] c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y} else: c = None xc = None if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) c = {'pos_x': pos_x, 'pos_y': pos_y} # To support classifier-free guidance, randomly drop out only text conditioning 10% like sd-v1.5 random = torch.rand(x.size(0), device=x.device) prompt_mask = rearrange(random < uncond, 'n -> n 1 1') null_prompts = self.get_learned_conditioning(['']).to(c.device) cc = torch.where(prompt_mask, null_prompts, c) out = [z, cc] if return_first_stage_outputs: xrec = self.decode_first_stage(z) out.extend([x, xrec]) if return_original_cond: out.append(xc) return out @torch.no_grad() def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False): if predict_cids: if z.dim() == 4: z = torch.argmax(z.exp(), dim=1).long() z = self.first_stage_model.quantize.get_codebook_entry( z, shape=None) z = rearrange(z, 'b h w c -> b c h w').contiguous() z = 1. / self.scale_factor * z if hasattr(self, 'split_input_params'): if self.split_input_params['patch_distributed_vq']: ks = self.split_input_params['ks'] # eg. (128, 128) stride = self.split_input_params['stride'] # eg. (64, 64) uf = self.split_input_params['vqf'] bs, nc, h, w = z.shape if ks[0] > h or ks[1] > w: ks = (min(ks[0], h), min(ks[1], w)) print('reducing Kernel') if stride[0] > h or stride[1] > w: stride = (min(stride[0], h), min(stride[1], w)) print('reducing stride') fold, unfold, normalization, weighting = self.get_fold_unfold( z, ks, stride, uf=uf) z = unfold(z) # (bn, nc * prod(**ks), L) # 1. Reshape to img shape z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L ) # 2. apply model loop over last dim
if isinstance(self.first_stage_model, VQModelInterface):
2
2023-12-06 07:29:34+00:00
24k
RobertCsordas/moe_attention
tasks/simple/language_model/transformer_lm_mixin.py
[ { "identifier": "TransformerLanguageModel", "path": "models/transformer_language_model.py", "snippet": "class TransformerLanguageModel(LoggingLayer, torch.nn.Module):\n def __init__(self, voc_size: int, embedding_size: Optional[int], state_size: int, dropout: float,\n tied_embedding: bool, layers: List[torch.nn.Module], n_prev_states: int,\n n_prev_states_test: Optional[int] = None, adaptive_cutoffs: List[int] = [],\n same_length_eval: bool = True, norm_before_output: bool = False,\n p_drop_layer: float = 0.0, use_last_state: bool = False, same_length: bool = False):\n\n super().__init__()\n\n self.embedding = torch.nn.Embedding(voc_size, embedding_size or state_size)\n torch.nn.init.kaiming_normal_(self.embedding.weight, mode=\"fan_in\", nonlinearity=\"linear\")\n\n self.shared_layers = all([la is layers[0] for la in layers])\n\n if embedding_size is None:\n self.embedding_adapter = lambda x: x\n else:\n self.embedding_adapter = torch.nn.Linear(embedding_size, state_size)\n\n self.dropout = torch.nn.Dropout(dropout)\n self.layers = layers\n self.unique_layers = torch.nn.ModuleList(unique_obejcts(layers))\n self.output_adapter = lambda x: x\n self.n_prev_states = n_prev_states\n self.n_prev_states_test = n_prev_states_test or n_prev_states\n self.same_length_eval = same_length_eval\n self.embedding_scale = math.sqrt(state_size)\n self.p_drop_layer = p_drop_layer\n self.use_last_state = use_last_state\n self.same_length = same_length\n self.iter = 0\n\n self.adaptive = bool(adaptive_cutoffs)\n\n out_proj_size = (embedding_size or state_size) if tied_embedding else state_size\n if self.adaptive:\n self.output = framework.layers.CustomAdaptiveLogSoftmaxWithLoss(\n out_proj_size, voc_size, adaptive_cutoffs, div_value=1,\n tied_to=self.embedding if tied_embedding else None)\n else:\n self.output = torch.nn.Linear(out_proj_size, voc_size)\n\n if norm_before_output:\n self.out_norm = torch.nn.LayerNorm(state_size)\n else:\n self.out_norm = lambda x: x\n\n if tied_embedding:\n if not self.adaptive:\n self.output.weight = self.embedding.weight\n if embedding_size is not None:\n self.output_adapter = torch.nn.Linear(state_size, embedding_size)\n\n @staticmethod\n def generate_history_mask(sz: int, device: torch.device) -> torch.Tensor:\n return torch.tril(torch.ones(sz, sz, dtype=torch.bool, device=device), diagonal=-1)\n\n def gen_output(self, x: torch.Tensor, target: Optional[torch.Tensor]) -> torch.Tensor:\n net = self.out_norm(x)\n net = self.output_adapter(net)\n net = self.dropout(net)\n\n if self.adaptive:\n net = self.output(net.transpose(0, 1), target)\n else:\n net = self.output(net.transpose(0, 1))\n\n return net\n\n def forward(self, x: torch.Tensor, target: Optional[torch.Tensor], state) -> Tuple[torch.Tensor, Any]:\n causality_mask = Transformer.generate_square_subsequent_mask(x.shape[0], x.device)\n\n net = self.dropout(self.embedding(x.T.long()))\n net = self.embedding_adapter(net)\n net = net * self.embedding_scale\n\n new_state = []\n features = [net]\n\n n_prev_states = self.n_prev_states if self.training else self.n_prev_states_test\n\n same_length = self.same_length or ((not self.training) and self.same_length_eval)\n if same_length and state is not None:\n causality_mask = [self.generate_history_mask(x.shape[0], x.device)] + \\\n [torch.zeros_like(causality_mask)] * (len(state[0]) - 1) + [causality_mask]\n causality_mask = torch.cat(causality_mask, -1)\n\n\n plot_cossim = (self.iter % 100 == 0 and self.training)\n for li, l in enumerate(self.layers):\n if n_prev_states > 0:\n if li == 0:\n # Pos offset should be constant for all layers\n pos_offset = sum(s.shape[1] for s in state[0]) if state is not None else 0\n\n # Concatenate the new state with the previous states\n li_r = -1 if self.use_last_state else li\n s = (state[li_r] + [net]) if state is not None else [net]\n attend_to = torch.cat(s, 1)\n\n if not self.use_last_state:\n s[-1] = s[-1].detach()\n new_state.append(s[-n_prev_states:])\n else:\n pos_offset = None\n attend_to = None\n\n net_o = l(net, mask=AttentionMask(None, causality_mask), attend_to=attend_to,\n pos_offset=pos_offset)\n\n if plot_cossim:\n features.append(net_o)\n\n with torch.no_grad():\n ndiff = torch.norm(net_o - net, p=2, dim=-1)\n n_in = torch.norm(net, p=2, dim=-1)\n self.log(f\"activation_norm/abs_update_layer_{li}\", ndiff.mean())\n self.log(f\"activation_norm/in_layer_{li}\", n_in.mean())\n self.log(f\"activation_norm/rel_update_layer_{li}\", (ndiff/n_in.clamp(min=torch.finfo(n_in.dtype).eps)).mean())\n\n if self.training and self.p_drop_layer > 0.0:\n net = torch.where(torch.rand_like(net_o[..., 0:1]) < self.p_drop_layer, net, net_o)\n else:\n net = net_o\n\n if self.use_last_state and n_prev_states > 0:\n # If we carry over the last state, save it here\n new_state = [((state[0] if state is not None else []) + [net.detach()])[-n_prev_states:]]\n\n if plot_cossim:\n with torch.no_grad():\n f_sample = [f.view(-1, f.shape[-1])[:1024] for f in features]\n f_sample_all = torch.stack(f_sample, -2)\n scores = framework.utils.cossim(f_sample_all, f_sample_all).mean(0)\n self.log(\"feature_cossim\", framework.visualize.plot.Heatmap(scores, range=(0, 1), textval=False))\n\n outs = F.softmax(self.gen_output(f_sample_all, target).transpose(0, 1), -1)\n scores = framework.utils.cossim(outs, outs).mean(0)\n self.log(\"out_dist_cossim\", framework.visualize.plot.Heatmap(scores, range=(0, 1), textval=False))\n\n real_out = outs[:, -1]\n for i in range(outs.shape[-2] - 1):\n self.log(f\"out_diff_{i}\", (outs[:, i] - real_out).norm(dim=-1, p=1).mean())\n\n del outs\n\n\n del features\n\n net = self.gen_output(net, target)\n self.iter += 1\n\n return net, new_state" }, { "identifier": "task", "path": "tasks/task_db.py", "snippet": "def task(name: Optional[str] = None):\n def wrapper(cls):\n n = TASK_PREFIX + (name or camel_to_snake(cls.__name__))\n assert n not in TASKS, f\"Task {n} already exists\"\n TASKS[n] = cls\n return cls\n return wrapper" }, { "identifier": "args", "path": "tasks/task_db.py", "snippet": "def args(fn):\n global ARGS_REGISTERS\n ARGS_REGISTERS.append(fn)\n return fn" }, { "identifier": "RelativeTransformerEncoderLayer", "path": "layers/transformer/relative_transformer.py", "snippet": "class RelativeTransformerEncoderLayer(torch.nn.Module):\n def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation: ActivationFunction = F.relu,\n attention_dropout=0, test_pos_clamp: Optional[int] = None, drop_expand: bool = True,\n head_projection_size: Optional[int] = None, ln_after_attention: bool = True):\n super().__init__()\n self.ln_after_attention = ln_after_attention\n self.self_attn = FixedRelativeMultiheadAttention(\n d_model, nhead, dropout=attention_dropout, test_pos_clamp=test_pos_clamp,\n projection_size=head_projection_size)\n self.linear1 = torch.nn.Linear(d_model, dim_feedforward)\n self.dropout = torch.nn.Dropout(dropout) if drop_expand else lambda x: x\n self.linear2 = torch.nn.Linear(dim_feedforward, d_model)\n\n if ln_after_attention:\n self.norm1 = torch.nn.LayerNorm(d_model)\n self.norm2 = torch.nn.LayerNorm(d_model)\n self.dropout1 = torch.nn.Dropout(dropout)\n self.dropout2 = torch.nn.Dropout(dropout)\n\n self.activation = activation\n self.reset_parameters()\n\n def forward(self, src: torch.Tensor, mask: Optional[AttentionMask] = None, attend_to: Optional[torch.Tensor] = None,\n pos_offset: Optional[int] = None) -> torch.Tensor:\n src2 = self.self_attn(src, attend_to if attend_to is not None else src, mask, pos_offset=pos_offset)\n src = src + self.dropout1(src2)\n src = self.norm1(src) if self.ln_after_attention else src\n src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))\n src = src + self.dropout2(src2)\n src = self.norm2(src)\n return src\n\n def reset_parameters(self):\n torch.nn.init.xavier_normal_(self.linear1.weight, gain=torch.nn.init.calculate_gain('relu')\n if self.activation is F.relu else 1.0)\n torch.nn.init.xavier_uniform_(self.linear2.weight)" }, { "identifier": "PrelnRelativeTransformerEncoderLayer", "path": "layers/transformer/relative_preln_transformer.py", "snippet": "class PrelnRelativeTransformerEncoderLayer(RelativeTransformerEncoderLayer):\n is_preln = True\n\n def __init__(self, d_model, nhead, n_layers: int, dim_feedforward=2048, dropout=0.1,\n activation: ActivationFunction = F.relu, attention_dropout=0, test_pos_clamp: Optional[int] = None,\n drop_expand: bool = True, head_projection_size: Optional[int] = None):\n super().__init__(\n d_model=d_model, nhead=nhead, dim_feedforward=dim_feedforward, dropout=dropout,\n activation=activation, attention_dropout=attention_dropout, test_pos_clamp=test_pos_clamp,\n drop_expand=drop_expand, head_projection_size=head_projection_size)\n\n reset_prenorm_params(self, n_layers)\n\n def forward(self, src: torch.Tensor, mask: Optional[AttentionMask] = None, attend_to: Optional[torch.Tensor] = None,\n pos_offset: Optional[int] = None) -> torch.Tensor:\n src2 = self.norm1(src)\n src2 = self.self_attn(src2, self.norm1(attend_to) if attend_to is not None else src2, mask,\n pos_offset=pos_offset)\n src = src + self.dropout1(src2)\n src2 = self.norm2(src)\n src2 = self.linear2(self.dropout(self.activation(self.linear1(src2))))\n src = src + self.dropout2(src2)\n return src" }, { "identifier": "RelativeMoeTransformerEncoderLayer", "path": "layers/transformer/relative_moe_transformer.py", "snippet": "class RelativeMoeTransformerEncoderLayer(LoggingLayer, torch.nn.Module):\n def __init__(self, d_model, nhead, n_experts: int, expert_size: int, n_layers: int,\n dropout=0.1, activation: ActivationFunction = F.relu, attention_dropout=0,\n test_pos_clamp: Optional[int] = None,\n dropout_mode: str = \"none\", selection_mode: str = \"add\",\n perplexity_reg: float = 0.0,\n n_heads: int = 1, norm_keys: bool = False, perplexity_reg_mode: str=\"step\",\n n_random: int = 0, reg_type: str = \"normal\",\n topk_mode: str = \"full\", head_projection_size: Optional[int] = None,\n activation_after_topk: bool = False,\n drop_parallel: bool = True,\n normalize_expert_sel_init: bool = False, norm_key_init: bool = False, norm_value_init: bool = False,\n identical_init: bool = False,\n sel_norm: str = \"none\",\n preln: bool = True, ln_affine: bool = True,\n moe_dropout_factor: float = 1.0,\n drop_expert: float = 0.0, sync_distributed: bool = True,\n modulation_amplitude: float = 0.5, moe_init_scale: float = 1.0,\n moe_att_n_experts: int = 4, moe_att_expert_dropout: Optional[float] = None,\n moe_att_selection_mode: str = \"sigmoid\",\n moe_att_k: Optional[int] = None, moe_att_ppl_reg: Optional[float] = None,\n q_expert: bool = True, k_expert: bool = True, v_expert: bool = True,\n o_expert: bool = True,\n v_projection_size: Optional[int] = None,\n qside_n_experts: Optional[int] = None,\n moe_attention: bool = False, moe_att_variant: str = \"full\",\n moe_att_shared_experts: bool = False,\n moe_att_kq_n_experts: Optional[int] = None, moe_att_separate_kq_sel: bool = False,\n moe_att_norm_init: bool = False, moe_att_same_sel: bool = False, moe_att_norm_retrieval: bool = False,\n rotate_fraction: float = 0.5, rope_base: float = 10000):\n super().__init__()\n self.preln = preln\n self.i = 0\n\n if moe_attention:\n if moe_att_variant == \"full\":\n self.self_attn = FullMoeRelativeAttention(\n d_model, nhead, dropout=attention_dropout,\n projection_size=head_projection_size, init_std_scale=math.sqrt(2 / n_layers) if preln else 1.0,\n n_experts=moe_att_n_experts,\n perplexity_reg=perplexity_reg if moe_att_ppl_reg is None else moe_att_ppl_reg,\n expert_dropout=drop_expert if moe_att_expert_dropout is None else moe_att_expert_dropout,\n selection_mode=moe_att_selection_mode, q_expert=q_expert, k_expert=k_expert, v_expert=v_expert,\n moe_k=n_heads if moe_att_k is None else moe_att_k, o_expert=o_expert, qside_n_experts=qside_n_experts,\n v_projection_size=v_projection_size, shared_experts=moe_att_shared_experts,\n kq_n_experts=moe_att_kq_n_experts, separate_kq_sel=moe_att_separate_kq_sel,\n normalize_init=moe_att_norm_init,\n same_sel=moe_att_same_sel, normalize_retrieval=moe_att_norm_retrieval,\n )\n elif moe_att_variant == \"full_rope\":\n self.self_attn = FullMoeRopeAttention(\n d_model, nhead, dropout=attention_dropout,\n projection_size=head_projection_size, init_std_scale=math.sqrt(2 / n_layers) if preln else 1.0,\n n_experts=moe_att_n_experts,\n perplexity_reg=perplexity_reg if moe_att_ppl_reg is None else moe_att_ppl_reg,\n expert_dropout=drop_expert if moe_att_expert_dropout is None else moe_att_expert_dropout,\n selection_mode=moe_att_selection_mode, q_expert=q_expert, k_expert=k_expert, v_expert=v_expert,\n moe_k=n_heads if moe_att_k is None else moe_att_k, o_expert=o_expert, qside_n_experts=qside_n_experts,\n v_projection_size=v_projection_size, shared_experts=moe_att_shared_experts,\n kq_n_experts=moe_att_kq_n_experts, separate_kq_sel=moe_att_separate_kq_sel,\n normalize_init=moe_att_norm_init, normalize_retrieval=moe_att_norm_retrieval,\n rotate_fraction=rotate_fraction, rope_base=rope_base,\n )\n else:\n raise ValueError(f\"Unknown attention variant {moe_att_variant}\")\n else:\n self.self_attn = FixedRelativeMultiheadAttention(\n d_model, nhead, dropout=attention_dropout, test_pos_clamp=test_pos_clamp,\n projection_size=head_projection_size)\n\n std_scale = math.sqrt(2.0 / n_layers) if preln else 1.0\n std_scale *= math.sqrt(moe_init_scale)\n\n self.pkm = MoE(\n d_model, n_experts, expert_size, dropout=dropout * moe_dropout_factor, dropout_mode=dropout_mode,\n weight_scale=std_scale, selection_mode=selection_mode,\n perplexity_reg=perplexity_reg, n_heads=n_heads,\n norm_keys=norm_keys, perplexity_reg_mode=perplexity_reg_mode, n_random=n_random,\n reg_type=reg_type, topk_mode=topk_mode,\n activation_after_topk=activation_after_topk,\n activation=activation,\n normalize_expert_sel_init=normalize_expert_sel_init, norm_key_init=norm_key_init,\n norm_value_init=norm_value_init, identical_init=identical_init,\n sel_norm=sel_norm,\n expert_dropout=drop_expert,\n sync_distributed=sync_distributed,\n modulation_amplitude=modulation_amplitude)\n\n self.norm1 = torch.nn.LayerNorm(d_model, elementwise_affine=ln_affine)\n self.norm2 = torch.nn.LayerNorm(d_model, elementwise_affine=ln_affine)\n self.dropout = torch.nn.Dropout(dropout)\n\n self.activation = activation\n self.drop_parallel = drop_parallel\n\n if preln:\n reset_prenorm_params(self, n_layers)\n\n def forward(self, src: torch.Tensor, mask: Optional[AttentionMask] = None, attend_to: Optional[torch.Tensor] = None,\n pos_offset: Optional[int] = None) -> torch.Tensor:\n\n src2 = self.norm1(src) if self.preln else src\n src2 = self.self_attn(src2, self.norm1(attend_to) if attend_to is not None else src2, mask,\n pos_offset=pos_offset)\n src = src + self.dropout(src2)\n\n if self.preln:\n src2 = self.norm2(src)\n else:\n src = src2 = self.norm1(src)\n\n src3 = self.pkm(src2)\n\n src = src + self.dropout(src3)\n if not self.preln:\n src = self.norm2(src)\n return src" }, { "identifier": "FastRopeTransformerEncoderLayer", "path": "layers/transformer/fast_rope_transformer.py", "snippet": "class FastRopeTransformerEncoderLayer(torch.nn.Module):\n def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation: ActivationFunction = F.relu,\n attention_dropout=0, drop_expand: bool = True,\n head_projection_size: Optional[int] = None, preln: bool = False, n_layers: Optional[int] = None,\n rotate_fraction: float = 0.5, rope_base: float = 10000):\n super().__init__()\n self.preln = preln\n self.self_attn = FastRopeAttention(\n d_model, nhead, dropout=attention_dropout,\n projection_size=head_projection_size, rotate_fraction=rotate_fraction,\n rope_base=rope_base)\n self.linear1 = torch.nn.Linear(d_model, dim_feedforward)\n self.dropout = torch.nn.Dropout(dropout) if drop_expand else lambda x: x\n self.linear2 = torch.nn.Linear(dim_feedforward, d_model)\n\n self.norm1 = torch.nn.LayerNorm(d_model)\n self.norm2 = torch.nn.LayerNorm(d_model)\n self.dropout1 = torch.nn.Dropout(dropout)\n self.dropout2 = torch.nn.Dropout(dropout)\n\n self.activation = activation\n\n if preln:\n if n_layers is None:\n raise ValueError(\"n_layers must be specified when using preln\")\n reset_prenorm_params(self, n_layers)\n else:\n self.reset_parameters()\n\n def forward(self, src: torch.Tensor, mask: Optional[AttentionMask] = None, attend_to: Optional[torch.Tensor] = None,\n pos_offset: Optional[int] = None) -> torch.Tensor:\n src2 = self.norm1(src) if self.preln else src\n src2 = self.self_attn(src2, self.norm1(attend_to) if attend_to is not None else src2, mask, pos_offset=pos_offset)\n src = src + self.dropout1(src2)\n\n if self.preln:\n src2 = self.norm2(src)\n else:\n src2 = src = self.norm1(src)\n\n src2 = self.linear2(self.dropout(self.activation(self.linear1(src2))))\n src = src + self.dropout2(src2)\n\n if not self.preln:\n src = self.norm2(src)\n return src\n\n def reset_parameters(self):\n torch.nn.init.xavier_normal_(self.linear1.weight, gain=torch.nn.init.calculate_gain('relu')\n if self.activation is F.relu else 1.0)\n torch.nn.init.xavier_uniform_(self.linear2.weight)" }, { "identifier": "MoeAttentionRelativeTransformerEncoderLayer", "path": "layers/transformer/moe_attention_relative_transformer.py", "snippet": "class MoeAttentionRelativeTransformerEncoderLayer(torch.nn.Module):\n def __init__(self, d_model, nhead, moe_att_n_experts, dim_feedforward=2048, dropout=0.1, activation: ActivationFunction = F.relu,\n attention_dropout=0, drop_expand: bool = True,\n head_projection_size: Optional[int] = None, preln: bool = False, n_layers: Optional[int] = None,\n att_perplexity_reg: float = 0.0, expert_dropout: float = 0.0, att_selection_mode=\"sigmoid\",\n attention_variant=\"moa\", q_expert: bool = True, k_expert: bool = True, v_expert: bool = True,\n o_expert: bool = True, moe_k: int = 2,\n norm_qk_score: bool = False, v_projection_size: Optional[int] = None, same_sel: bool = False,\n qside_n_experts: Optional[int] = None, shared_experts: bool = False,\n kq_n_experts: Optional[int] = None, separate_kq_sel: bool = False,\n cvloss: float = 0.0, switchloss: float = 0.0, zloss: float = 0.0,\n moa_mode: str = \"my\", rotate_fraction: float = 0.5, rope_base: float = 10000,\n moeatt_norm_init: bool = False):\n super().__init__()\n self.is_preln = preln\n if attention_variant not in {\"full\", \"full_rope\"} and (not q_expert):\n raise ValueError(\"q_expert can be disabled only when using qside attention\")\n\n if attention_variant == \"moa\":\n self.self_attn = MoA(\n d_model, nhead, dropout=attention_dropout,\n projection_size=head_projection_size, init_std_scale=math.sqrt(2 / n_layers) if preln else 1.0,\n n_experts=moe_att_n_experts, perplexity_reg=att_perplexity_reg, expert_dropout=expert_dropout,\n selection_mode=att_selection_mode, mode=moa_mode, cvloss=cvloss, switchloss=switchloss, zloss=zloss\n )\n elif attention_variant == \"full\":\n self.self_attn = FullMoeRelativeAttention(\n d_model, nhead, dropout=attention_dropout,\n projection_size=head_projection_size, init_std_scale=math.sqrt(2 / n_layers) if preln else 1.0,\n n_experts=moe_att_n_experts, perplexity_reg=att_perplexity_reg, expert_dropout=expert_dropout,\n selection_mode=att_selection_mode, q_expert=q_expert, k_expert=k_expert, v_expert=v_expert,\n norm_qk_score=norm_qk_score, v_projection_size=v_projection_size, same_sel=same_sel,\n o_expert=o_expert, moe_k=moe_k, qside_n_experts=qside_n_experts,\n shared_experts=shared_experts, kq_n_experts=kq_n_experts, separate_kq_sel=separate_kq_sel,\n normalize_init=moeatt_norm_init\n )\n elif attention_variant == \"full_rope\":\n self.self_attn = FullMoeRopeAttention(\n d_model, nhead, dropout=attention_dropout,\n projection_size=head_projection_size, init_std_scale=math.sqrt(2 / n_layers) if preln else 1.0,\n n_experts=moe_att_n_experts, perplexity_reg=att_perplexity_reg, expert_dropout=expert_dropout,\n selection_mode=att_selection_mode, q_expert=q_expert, k_expert=k_expert, v_expert=v_expert,\n norm_qk_score=norm_qk_score, v_projection_size=v_projection_size, same_sel=same_sel,\n o_expert=o_expert, moe_k=moe_k, qside_n_experts=qside_n_experts,\n shared_experts=shared_experts, kq_n_experts=kq_n_experts, separate_kq_sel=separate_kq_sel,\n rotate_fraction=rotate_fraction, rope_base=rope_base,\n normalize_init=moeatt_norm_init\n )\n else:\n raise ValueError(f\"Unknown attention variant: {attention_variant}\")\n\n self.linear1 = torch.nn.Linear(d_model, dim_feedforward)\n self.dropout = torch.nn.Dropout(dropout) if drop_expand else lambda x: x\n self.linear2 = torch.nn.Linear(dim_feedforward, d_model)\n\n self.norm1 = torch.nn.LayerNorm(d_model)\n self.norm2 = torch.nn.LayerNorm(d_model)\n self.dropout1 = torch.nn.Dropout(dropout)\n self.dropout2 = torch.nn.Dropout(dropout)\n\n self.activation = activation\n\n if preln:\n if n_layers is None:\n raise ValueError(\"n_layers must be specified when using preln\")\n reset_prenorm_params(self, n_layers)\n else:\n self.reset_parameters()\n\n def forward(self, src: torch.Tensor, mask: Optional[AttentionMask] = None, attend_to: Optional[torch.Tensor] = None,\n pos_offset: Optional[int] = None) -> torch.Tensor:\n src2 = self.norm1(src) if self.is_preln else src\n src2 = self.self_attn(src2, self.norm1(attend_to) if attend_to is not None else src2, mask, pos_offset=pos_offset)\n src = src + self.dropout1(src2)\n\n if self.is_preln:\n src2 = self.norm2(src)\n else:\n src2 = src = self.norm1(src)\n\n src2 = self.linear2(self.dropout(self.activation(self.linear1(src2))))\n src = src + self.dropout2(src2)\n\n if not self.is_preln:\n src = self.norm2(src)\n return src\n\n def reset_parameters(self):\n torch.nn.init.xavier_normal_(self.linear1.weight, gain=torch.nn.init.calculate_gain('relu')\n if self.activation is F.relu else 1.0)\n torch.nn.init.xavier_uniform_(self.linear2.weight)" }, { "identifier": "MoE", "path": "layers/moe_layer.py", "snippet": "class MoE(LoggingLayer, RegularizedLayer, OncePerIterLayer, torch.nn.Module):\n def __init__(self, dmodel: int, n_experts: int, expert_size: int, n_heads: int,\n dropout: float = 0, weight_scale: float = 1.0,\n dropout_mode: str = \"none\", selection_mode: str = \"sigmoid\", perplexity_reg: float = 0.0,\n norm_keys: bool = False,\n perplexity_reg_mode: str=\"step\", n_random: int = 0, reg_type: str = \"entropy\",\n topk_mode: str = \"full\", activation_after_topk: bool = False,\n activation = lambda x: F.relu(x, inplace=True),\n normalize_expert_sel_init: bool = False, norm_key_init: bool = False, norm_value_init: bool = False,\n identical_init: bool = False,\n rescale_normed: bool = False, sel_norm: str = \"none\",\n v_dim: Optional[int] = None,\n expert_dropout: float = 0.0,\n sync_distributed: bool = False,\n modulation_amplitude: float = 0.5,\n ppl_past_blocks: int = 0):\n\n super().__init__()\n self.k_dim = dmodel\n self.v_dim = v_dim if v_dim is not None else dmodel\n self.n_experts = n_experts\n self.expert_size = expert_size\n self.size = self.n_experts * self.expert_size\n self.dropout = dropout\n self.dropout_mode = dropout_mode\n self.selection_mode = selection_mode\n self.perplexity_reg = perplexity_reg\n self.k_vec_dim = self.k_dim\n self.n_heads = n_heads\n self.norm_keys = norm_keys\n self.perplexity_reg_mode = perplexity_reg_mode\n self.n_random = n_random\n self.reg_type = reg_type\n self.topk_mode = topk_mode\n self.activation_after_topk = activation_after_topk\n self.activation = activation\n self.weight_scale = weight_scale\n self.normalize_expert_sel_init = normalize_expert_sel_init\n self.norm_key_init = norm_key_init\n self.norm_value_init = norm_value_init\n self.identical_init = identical_init\n self.layer = 0\n self.initalized = False\n self.rescale_normed = rescale_normed\n self.sel_norm = sel_norm\n self.was_training = True\n self.expert_dropout = expert_dropout\n self.reg_counts = 0\n self.sync_distributed = sync_distributed and torch.distributed.is_initialized()\n self.modulation_amplitude = modulation_amplitude\n self.record_all_expert_sel_counts = False\n self.ppl_past_blocks = ppl_past_blocks\n self.blocks_for_ppl = []\n self.recorded_inputs = []\n\n self.coocurence = None\n\n assert self.selection_mode in {\"gate\", \"sigmoid\", \"sinkhorn\", \"sinkhorn2\", \"sinkmoid\", \"sinkmax\", \"sinkhorn_local\", \"mul\", \"sinkmoid2\", \"sinkmax2\"}\n assert self.perplexity_reg_mode in {\"step\", \"global\", \"time\", \"global_time\"}\n assert self.dropout_mode in {\"none\", \"score\"}\n assert self.reg_type in {\"perplexity\", \"variance\", \"entropy\", \"l2\", \"switch\"}\n assert self.topk_mode in {\"full\", \"l1_approx\", \"approx\"}\n assert self.sel_norm in {\"none\", \"cos\", \"input\", \"weights\"}\n\n self.register_buffer(\"iter\", torch.tensor(0, dtype=torch.int64), persistent=False)\n\n if selection_mode in {\"mul\"} and activation_after_topk:\n raise ValueError(\"Activation after topk is not supported with mul selection\")\n\n self.keys = torch.nn.Parameter(torch.empty(self.n_experts, self.k_vec_dim, self.expert_size))\n\n self.values = torch.nn.Parameter(torch.empty(self.n_experts, self.expert_size, self.v_dim))\n\n self.expert_sel = torch.nn.Parameter(torch.empty(self.n_experts, self.k_vec_dim))\n self.sel = lambda x: F.linear(x, self.expert_sel)\n\n torch.nn.init.normal_(self.expert_sel, std=self.k_vec_dim ** -0.5 * weight_scale)\n torch.nn.init.normal_(self.keys, std=dmodel ** -0.5 * weight_scale)\n torch.nn.init.normal_(self.values, std=self.size ** -0.5 * weight_scale)\n self.sel_hist = []\n self.index_sel_counts = 0\n self.index_sel_norm = 0\n\n self.index_sel_counts_100 = 0\n self.index_sel_norm_100 = 0\n\n self.sel_count_log = None\n\n self.all_expert_sel_counts = []\n self.all_expert_sel_soft = []\n\n self.register_buffer(\"kv_sel_counts\", torch.zeros(self.n_experts, self.expert_size), persistent=False)\n self.register_buffer(\"kv_sel_counts_100\", torch.zeros_like(self.kv_sel_counts))\n\n if self.rescale_normed and self.sel_norm != \"none\":\n self.sel_scale = torch.nn.Parameter(torch.ones([1]))\n else:\n self.sel_scale = 1.0\n\n self.register_buffer(\"seq\", torch.arange(max(self.n_heads, self.n_experts, self.k_dim, self.v_dim), dtype=torch.long), persistent=False)\n self.regroup_weights()\n\n if self.ppl_past_blocks > 0 and self.reg_type not in {\"perplexity\", \"entropy\"}:\n print(f\"Warning: ppl_past_blocks>0 (currently {self.ppl_past_blocks}) is only supported with perplexity and entropy regularization\")\n\n def keys_to_logical_order(self, keys: torch.Tensor) -> torch.Tensor:\n k = keys.view(self.n_experts, self.k_vec_dim, self.expert_size)\n return k.permute(0, 2, 1).contiguous().view(-1, self.k_vec_dim)\n\n def keys_from_logical_order(self, keys: torch.Tensor) -> torch.Tensor:\n return keys.view(self.n_experts, self.expert_size, self.k_vec_dim).permute(0, 2, 1).contiguous().view(self.n_experts * self.k_vec_dim, self.expert_size)\n\n def renorm_keep_std(self, weight: torch.Tensor, dim: int = 0):\n with torch.no_grad():\n std = weight.std()\n weight.div_(weight.norm(dim=dim, keepdim=True))\n weight.mul_(std / weight.std())\n\n def regroup_weights(self) -> Optional[torch.Tensor]:\n with torch.no_grad():\n if self.norm_key_init:\n self.renorm_keep_std(self.keys.view(self.n_experts, self.k_vec_dim, self.expert_size), dim=1)\n\n if self.norm_value_init:\n self.renorm_keep_std(self.values, dim=1)\n\n if self.identical_init:\n k = self.keys.view(self.n_experts, self.k_vec_dim, self.expert_size)\n self.keys.set_(k[:1].expand_as(k).reshape_as(self.keys))\n\n v = self.values.view(self.n_experts, self.expert_size, self.v_dim)\n self.values.set_(v[:1].expand_as(v).reshape_as(self.values))\n\n if self.normalize_expert_sel_init:\n self.renorm_keep_std(self.expert_sel, dim=1)\n\n def ani(self, x: torch.Tensor) -> torch.Tensor:\n assert x.ndim == 2\n chunk_size = 32\n\n xnorm = F.normalize(x, 2, dim=-1)\n\n accu = 0\n for i in range(0, x.shape[0], chunk_size):\n a = xnorm[i: i + chunk_size]\n sims = xnorm @ a.T\n sims[i : i + chunk_size].fill_diagonal_(0)\n accu += sims.sum()\n\n return accu / (x.shape[0] * (x.shape[0] - 1))\n\n def log_expert_sel_usage(self, prefix: str, channel_sel_counts: torch.Tensor):\n sel_nonzero = (channel_sel_counts != 0).type(torch.float).sum(axis=-1) / self.expert_size\n self.log(f\"{prefix}/mean\", sel_nonzero.mean())\n self.log(f\"{prefix}/min\", sel_nonzero.min())\n self.log(f\"{prefix}/max\", sel_nonzero.max())\n\n\n def pre_train_forward(self):\n if self.norm_keys:\n with torch.no_grad():\n self.keys.div_(self.keys.norm(dim=-1, keepdim=True))\n\n if self.training and not self.was_training:\n sorted_counts = self.index_sel_counts.sort(descending=True).values\n self.log(\"test_exert_channel_usage\", framework.visualize.plot.Barplot(sorted_counts, xlabel=\"expert\", ylabel=\"usage count\"), drop_old=True)\n\n self.layer = 0\n if self.sel_hist:\n self.sel_hist = []\n self.index_sel_counts = 0\n self.index_sel_norm = 0\n self.reg_counts = 0\n\n def before_loss(self):\n if self.sel_hist:\n # Concatenate against time dimension. Important for the within-batch regularization\n sel = torch.cat(self.sel_hist, -2)\n self.add_perplexity_reg(sel)\n\n self.sel_hist = []\n\n if self.index_sel_norm > 0:\n if self.training:\n with torch.no_grad():\n self.log(\"usag_rel_perplexity_all_layers\", utils.relative_perplexity(self.index_sel_counts / self.index_sel_norm))\n self.log(\"dead_expert_proportion_all_layers\", (self.index_sel_counts == 0).float().sum() / self.n_experts)\n\n self.log_expert_sel_usage(\"exert_channel_usage\", self.kv_sel_counts)\n\n self.kv_sel_counts_100.add_(self.kv_sel_counts)\n self.kv_sel_counts.zero_()\n\n self.index_sel_counts_100 = self.index_sel_counts_100 + self.index_sel_counts\n self.index_sel_norm_100 = self.index_sel_norm_100 + self.index_sel_norm\n\n if self.training and self.iter % 100 == 0:\n norm_cnt = self.index_sel_counts_100 / self.index_sel_norm_100\n self.log(\"usag_rel_perplexity_100\", utils.relative_perplexity(norm_cnt))\n self.log(\"dead_expert_proportion_100\", (self.index_sel_counts_100 == 0).float().sum() / self.n_experts)\n\n sorted_counts = self.index_sel_counts_100.sort(descending=True).values\n self.log(\"usage_counts_100\", framework.visualize.plot.Barplot(sorted_counts, xlabel=\"expert\", ylabel=\"usage count\"), drop_old=True)\n\n\n self.log_expert_sel_usage(\"exert_channel_usage_100\", self.kv_sel_counts_100)\n self.kv_sel_counts_100.zero_()\n\n self.index_sel_counts_100 = 0\n self.index_sel_norm_100 = 0\n\n self.log(\"ani/keys\", self.ani(self.keys_to_logical_order(self.keys)))\n self.log(\"ani/values\", self.ani(self.values.flatten(0, -2)))\n self.log(\"ani/expert_sel\", self.ani(self.expert_sel.T))\n\n if self.training:\n self.iter += 1\n\n def topk(self, x: torch.Tensor, k: int, approx: bool) -> Tuple[torch.Tensor, torch.Tensor]:\n if approx:\n x = x.view(*x.shape[:-1], k, -1)\n scores, ind = x.max(-1)\n return scores, self.seq[:k] * x.shape[-1] + ind\n else:\n return x.topk(k, dim=-1, sorted=False)\n\n def rolling_logsumexp(self, x: torch.Tensor) -> torch.Tensor:\n # Simulate calculating logsumexp over a bigger batch than the current one. Will have stale values, but that\n # should not matter much later in training.\n if self.ppl_past_blocks == 0 or not self.training:\n return F.log_softmax(x, dim=-1)\n else:\n if len(self.blocks_for_ppl) == self.ppl_past_blocks:\n self.blocks_for_ppl.pop(0)\n\n self.blocks_for_ppl.append(x)\n res = F.log_softmax(torch.cat(self.blocks_for_ppl, dim=0), dim=-1)\n self.blocks_for_ppl[-1] = self.blocks_for_ppl[-1].detach()\n return res\n\n def add_perplexity_reg(self, sel: torch.Tensor):\n sync_distributed = self.sync_distributed and (self.perplexity_reg_mode not in {\"time\", \"global_time\"})\n\n if self.perplexity_reg_mode in {\"time\", \"global_time\"}:\n sel = sel.flatten(0, -3)\n else:\n sel = sel.flatten(0, -2)\n\n # Note: sel are raw logits, no matter what activation is used\n if self.perplexity_reg > 0:\n if self.reg_type == \"perplexity\":\n sel_d = self.rolling_logsumexp(sel)\n sel_d = framework.utils.distributed_ops.log_mean(sel_d, -2, self.sync_distributed)\n loss = lambda: self.perplexity_reg * ( - utils.relative_perplexity_l(sel_d).mean())\n elif self.reg_type == \"entropy\":\n sel_d = self.rolling_logsumexp(sel)\n sel_d = framework.utils.distributed_ops.log_mean(sel_d, -2, self.sync_distributed)\n loss = lambda: self.perplexity_reg * ( - utils.entropy_l(sel_d).mean())\n elif self.reg_type == \"variance\":\n if sync_distributed:\n raise NotImplementedError(\"Variance regularization is not supported in distributed mode\")\n avg_sel = sel.mean(-2)\n loss = lambda: self.perplexity_reg * avg_sel.var(-1).mean()\n elif self.reg_type == \"l2\":\n loss = lambda: self.perplexity_reg * sel.pow(2).mean()\n elif self.reg_type == \"switch\":\n if sync_distributed:\n torch.distributed.all_reduce(self.reg_counts, op=torch.distributed.ReduceOp.SUM)\n\n p_sel_real = self.reg_counts / self.reg_counts.sum(-1, keepdims=True)\n if self.perplexity_reg_mode in {\"time\", \"global_time\"}:\n p_sel_real = p_sel_real.unsqueeze(-2)\n\n loss = lambda: self.perplexity_reg * (F.softmax(sel, dim=-1) * p_sel_real).mean()\n self.reg_counts = 0\n else:\n assert False\n\n self.add_reg(loss, \"moe\")\n\n def compute_scores(self, input: torch.Tensor, index: CVMMSel, expert_scores: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n scores = cvmm(input, index, self.keys)\n\n if self.selection_mode in {\"mul\"}:\n scores = scores * expert_scores[..., None]\n elif self.selection_mode in {\"gate\", \"sigmoid\", \"sinkhorn\", \"sinkhorn2\", \"sinkmoid\", \"sinkmax\", \"sinkmoid2\"}:\n # Handle it later\n pass\n\n scores = self.activation(scores)\n\n plot_training = self.train and self.iter % 10 == 0\n if plot_training:\n with torch.no_grad():\n gt0 = (scores > 0).float()\n gt0_s = gt0.sum()\n\n if plot_training:\n self.log(\"relu_pass_rate\", gt0_s / scores.numel())\n\n self.kv_sel_counts.index_add_(0, index.raw_sel.flatten(), gt0.flatten(end_dim=-2))\n\n if self.dropout > 0 and self.dropout_mode != \"none\":\n scores = F.dropout(scores, self.dropout, training=self.training)\n\n return scores\n\n def sel_activation(self, sel: torch.Tensor, seq_len: int) -> Tuple[torch.Tensor, torch.Tensor]:\n reg_sel = sel\n if self.selection_mode in {\"sigmoid\"}:\n sel = torch.sigmoid(sel)\n elif self.selection_mode in {\"mul\"}:\n sel = sel.abs()\n reg_sel = sel\n elif self.selection_mode in {\"gate\"}:\n sel = F.softmax(sel, dim=-1)\n with torch.no_grad():\n self.log(\"expert_rel_perplexity_per_selection\", utils.relative_perplexity(sel).mean())\n else:\n assert False\n\n return sel, reg_sel\n\n def forward(self, input: torch.Tensor) -> torch.Tensor:\n out = 0\n\n in1 = in2 = input\n\n sel = self.sel(in1)\n # sel=sel.float()\n\n if self.sel_norm == \"cos\":\n sel = sel / (in1.norm(dim=-1, keepdim=True) * self.expert_sel.norm(dim=-1)[None]) * self.sel_scale\n elif self.sel_norm == \"weights\":\n sel = sel * (self.sel_scale / self.expert_sel.norm(dim=-1)[None])\n elif self.sel_norm == \"input\":\n sel = sel * (self.sel_scale / in1.norm(dim=-1, keepdim=True))\n\n sel_raw = reg_sel = sel\n\n inv_val = float(\"-inf\")\n\n if not self.activation_after_topk:\n # Sinkhorn should be always applied before top-k\n sel, reg_sel = self.sel_activation(sel, input.shape[-2])\n inv_val = 0\n\n if self.training and self.expert_dropout > 0:\n if self.selection_mode not in {\"sigmoid\", \"gate\"}:\n raise ValueError(\"Expert dropout not supported in this mode\")\n\n mask = torch.rand_like(sel) < self.expert_dropout\n sel2 = sel.masked_fill(mask, inv_val)\n else:\n sel2 = sel\n\n sel_val, sel_index = self.topk(sel2, self.n_heads, self.topk_mode in {\"l1_approx\", \"approx\"})\n\n if self.activation_after_topk or (self.selection_mode in {\"mul\"}):\n sel_val = torch.gather(sel_raw, -1, sel_index)\n sel_val, reg_sel = self.sel_activation(sel_val, input.shape[-2])\n\n\n record_counts_now = (self.training and self.iter % 10 == 0) or (not self.training) or (self.record_all_expert_sel_counts)\n\n if not self.training:\n sel_index_flat = sel_index.flatten(end_dim=-2)\n if self.coocurence is None:\n self.coocurence = torch.zeros([self.n_experts, self.n_experts], device=sel_index_flat.device, dtype=torch.long)\n\n for h1 in range(self.n_heads):\n for h2 in range(self.n_heads):\n ind_flat = sel_index_flat[..., h1] * self.n_experts + sel_index_flat[..., h2]\n values = torch.tensor([1], device=self.coocurence.device, dtype=self.coocurence.dtype).expand_as(ind_flat)\n # values = sel_val[..., h2].flatten()\n self.coocurence.flatten().put_(ind_flat, values, accumulate=True)\n # self.coocurence[sel_index_flat[..., h1], sel_index_flat[..., h2]] += 1\n\n if record_counts_now or self.reg_type == \"switch\":\n reg_counts = F.one_hot(sel_index, self.n_experts).type_as(input)\n\n if self.reg_type == \"switch\":\n reg_counts2 = reg_counts.view(*input.shape[:-2], input.shape[-2] * self.n_heads, self.n_experts)\n if self.perplexity_reg_mode == \"time\":\n reg_counts2 = reg_counts2.sum(-2)\n else:\n reg_counts2 = reg_counts2.flatten(end_dim=-2).sum(0)\n\n self.reg_counts = self.reg_counts + reg_counts2\n\n if record_counts_now:\n with torch.no_grad():\n sel_counts = reg_counts.flatten(end_dim=-2).sum(0)\n cnt = sel_index.nelement()\n\n p_expert_sel = sel_counts / cnt\n\n self.index_sel_counts = self.index_sel_counts + sel_counts\n self.index_sel_norm = self.index_sel_norm + cnt\n\n if self.record_all_expert_sel_counts:\n softcnt = torch.zeros_like(sel_counts, dtype=sel_val.dtype)\n softcnt.index_add_(0, sel_index.flatten(), sel_val.flatten())\n\n self.all_expert_sel_soft.append(softcnt)\n self.all_expert_sel_counts.append(sel_counts)\n\n if self.training:\n self.log(\"min_sel_score\", sel_val.min(dim=-1).values.mean())\n self.log(\"max_sel_score\", sel_val.max(dim=-1).values.mean())\n\n sel_oh = F.one_hot(sel_index, self.n_experts).sum(-2).bool()\n if self.layer >= 1 and self.training:\n self.log(f\"layer_sel_overlap_{self.layer}\", ((self.prev_sel_oh & sel_oh).sum(-1).float() / self.n_heads).mean())\n\n self.prev_sel_oh = sel_oh\n\n ppl = utils.relative_perplexity(p_expert_sel)\n self.log(\"usage_rel_perplexity\", ppl)\n self.log(\"dead_expert_proportion\", (p_expert_sel == 0).float().sum() / self.n_experts)\n\n if self.perplexity_reg_mode in {\"step\", \"time\"}:\n self.add_perplexity_reg(reg_sel)\n elif self.perplexity_reg > 0 and self.training:\n self.sel_hist.append(reg_sel)\n\n sel_indices = cvmm_prepare_sel2(sel_index.int())\n\n scores = self.compute_scores(in2, sel_indices, sel_val)\n\n sel_indices = sel_indices.clone()\n sel_indices.reduction_weight = sel_val\n sel_indices.sel_index = sel_indices.out_index\n sel_indices.out_index = None\n\n if self.selection_mode not in {\"gate\", \"sigmoid\"}:\n sel_indices.reduction_weight = torch.ones_like(sel_indices.reduction_weight)\n\n out = cvmm(scores, sel_indices, self.values)\n\n self.layer += 1\n\n self.was_training = self.training\n res = out.view(*input.shape[:-1], self.v_dim)\n return res\n\n def dump_logs(self, save_dir: str):\n if self.coocurence is not None:\n os.makedirs(save_dir, exist_ok=True)\n torch.save(self.coocurence, os.path.join(save_dir, \"coocurence.pt\"))\n\n def get_logs(self) -> Dict[str, Any]:\n res = super().get_logs()\n\n if self.coocurence is not None:\n coo = self.coocurence / self.coocurence.diagonal().clamp(min=1)[:, None]\n res[\"expert_coocurence\"] = framework.visualize.plot.Heatmap(coo, xlabel=\"expert\", ylabel=\"expert\", textval=False)\n self.coocurence = None\n return res" }, { "identifier": "Result", "path": "interfaces/result.py", "snippet": "class Result:\n outputs: torch.Tensor\n loss: torch.Tensor\n\n batch_dim = 0\n\n def plot(self) -> Dict[str, Any]:\n return {}\n\n @property\n def batch_size(self) -> int:\n return self.outputs.shape[self.batch_dim]\n\n @staticmethod\n def merge(l: List, batch_weights: Optional[List[float]] = None):\n if len(l) == 1:\n return l[0]\n batch_weights = batch_weights if batch_weights is not None else [1] * len(l)\n loss = sum([r.loss * w for r, w in zip(l, batch_weights)]) / sum(batch_weights)\n out = torch.cat([r.outputs for r in l], l[0].batch_dim)\n return l[0].__class__(out, loss)" }, { "identifier": "LayerVisualizer", "path": "layers/layer_with_visualization.py", "snippet": "class LayerVisualizer:\n def __init__(self, module: torch.nn.Module, options: Dict[str, Any] = {}):\n self.modules = []\n self.options = options\n self.curr_options = None\n for n, m in module.named_modules():\n if isinstance(m, LayerWithVisualization):\n self.modules.append((n, m))\n\n def plot(self) -> Dict[str, Any]:\n res = {}\n for n, m in self.modules:\n res.update({f\"{n}/{k}\": v for k, v in m.plot(self.curr_options).items()})\n m.visualization_enabled = False\n\n self.curr_options = None\n return res\n\n def prepare(self, options: Dict[str, Any] = {}):\n self.curr_options = self.options.copy()\n self.curr_options.update(options)\n\n for _, m in self.modules:\n m.prepare()\n m.visualization_enabled = True" }, { "identifier": "FullMoeRelativeAttentionCore", "path": "layers/transformer/full_moe_relative_attention.py", "snippet": "class FullMoeRelativeAttentionCore(LayerWithVisualization, LoggingLayer, RegularizedLayer, OncePerIterLayer, torch.nn.Module):\n def __init__(self, state_size: int, n_heads: int, n_experts: int, dropout: float = 0.0, input_size: Optional[int] = None,\n projection_size: Optional[int] = None, output_size: Optional[int] = None, init_std_scale: float = 1.0,\n perplexity_reg: float = 0, share_pk: bool = True, expert_dropout: float = 0.0,\n selection_mode: str = \"sigmoid\", moe_k: int = 2, q_expert: bool = True,\n k_expert: bool = True, v_expert: bool = True, o_expert: bool = True, norm_qk_score: bool = False,\n v_projection_size: Optional[int] = None, same_sel: bool = False,\n qside_n_experts: Optional[int] = None, shared_experts: bool = False,\n kq_n_experts: Optional[int] = None, separate_kq_sel: bool = False,\n normalize_init: bool = False, normalize_retrieval: bool = False):\n\n super().__init__()\n\n self.input_size = input_size or state_size\n self.output_size = output_size or state_size\n self.pe_size = self.input_size\n self.perplexity_reg = perplexity_reg\n self.share_pk = share_pk\n self.expert_dropout = expert_dropout\n self.selection_mode = selection_mode\n self.iter = 0\n self.moe_k = moe_k\n self.norm_qk_score = norm_qk_score\n self.same_sel = same_sel\n self.shared_experts = shared_experts\n self.init_std_scale = init_std_scale\n self.normalize_init = normalize_init\n self.attention_to_visualize = []\n self.selections_to_visualize = {}\n\n self.is_expert = {\n \"k\": k_expert,\n \"q\": q_expert,\n \"v\": v_expert,\n \"o\": o_expert\n }\n self.n_experts = {\n \"k\": kq_n_experts or n_experts,\n \"q\": kq_n_experts or qside_n_experts or n_experts,\n \"v\": n_experts,\n \"o\": qside_n_experts or n_experts\n }\n\n self.separate_k_sel = separate_kq_sel or (self.n_experts[\"k\"] != self.n_experts[\"v\"])\n self.separate_q_sel = separate_kq_sel or (self.n_experts[\"q\"] != self.n_experts[\"o\"])\n\n self.sel_hist = {}\n self.sel_counts_100 = {}\n\n self.n_heads = n_heads\n self.dropout = torch.nn.Dropout(dropout) if dropout > 0 else lambda x: x\n self.projection_size = projection_size or (state_size // n_heads)\n self.v_projection_size = v_projection_size or self.projection_size\n\n self.std_in = init_std_scale * math.sqrt(1 / self.input_size)\n std_out = init_std_scale * math.sqrt(1 / (n_heads * self.v_projection_size))\n\n self.create_selection_logic()\n\n self.src_side_maps = {\"k\", \"v\"}\n\n self.projections = torch.nn.ParameterDict({\n \"q\": self.create_param_block(\"q\", self.input_size, self.projection_size, self.std_in),\n \"k\": self.create_param_block(\"k\", self.input_size, self.projection_size, self.std_in),\n \"v\": self.create_param_block(\"v\", self.input_size, self.v_projection_size, self.std_in),\n \"o\": self.create_param_block(\"o\", self.v_projection_size, self.output_size, std_out),\n })\n\n if normalize_retrieval:\n self.norm_ret = torch.nn.LayerNorm(self.projection_size)\n else:\n self.norm_ret = lambda x: x\n\n self.sel_correlation = 0\n\n self.register_buffer(\"scale\", torch.full([1], 1.0 / math.sqrt(self.projection_size)), persistent=False)\n\n def renorm_keep_std(self, weight: torch.Tensor, dim: int = 0):\n with torch.no_grad():\n std = weight.std()\n weight.div_(weight.norm(dim=dim, keepdim=True))\n weight.mul_(std / weight.std())\n\n def get_n_copies(self, name: str):\n return self.n_heads\n\n def create_param_block(self, name: str, in_size: int, out_size: int, std: float):\n n_copies = self.get_n_copies(name)\n\n if self.is_expert[name]:\n exp_mul = 1 if self.shared_experts else n_copies\n p = torch.nn.Parameter(torch.randn(exp_mul * self.n_experts[name], in_size, out_size) * std)\n if self.normalize_init:\n self.renorm_keep_std(p, dim=0)\n return p\n else:\n if name == \"o\":\n in_size = n_copies * in_size\n else:\n out_size = n_copies * out_size\n return torch.nn.Parameter(torch.randn(out_size, in_size) * std)\n\n def create_selection_logic(self):\n sels_params = {}\n self.sel_map = {}\n\n def register_remap(dest: str, src: str) -> bool:\n if not (src in sels_params or src in self.sel_map):\n # src is not defined\n return False\n\n assert self.n_experts[src] == self.n_experts[dest]\n self.sel_map[dest] = self.sel_map.get(src, src)\n return True\n\n if self.is_expert[\"o\"]:\n sels_params[\"o\"] = self.init_sel(\"o\", self.std_in)\n\n if self.is_expert[\"q\"] and (self.separate_q_sel or not register_remap(\"q\", \"o\")):\n sels_params[\"q\"] = self.init_sel(\"q\", self.std_in)\n\n if self.is_expert[\"v\"] and ((not self.same_sel) or not register_remap(\"v\", \"o\")):\n sels_params[\"v\"] = self.init_sel(\"v\", self.std_in)\n\n if self.is_expert[\"k\"]:\n if (not (self.same_sel and self.separate_k_sel and register_remap(\"k\", \"q\"))) and (self.separate_k_sel or not register_remap(\"k\", \"v\")):\n sels_params[\"k\"] = self.init_sel(\"k\", self.std_in)\n\n self.selections = torch.nn.ParameterDict(sels_params)\n\n def init_sel(self, name: str, std: float) -> torch.nn.Parameter:\n n_copies = self.get_n_copies(name)\n n_experts = self.n_experts[name]\n sel = torch.nn.Parameter(torch.randn(n_experts*n_copies, self.input_size) * std)\n self.renorm_rows(sel)\n return sel\n\n def renorm_rows(self, x: torch.Tensor):\n with torch.no_grad():\n std_t = x.std(dim=-1, keepdim=True)\n x.div_(x.norm(dim=-1, keepdim=True))\n x.mul_(std_t / x.std())\n\n\n def project_to_torch_order(self, x: torch.Tensor):\n return x.view(*x.shape[:-1], self.get_n_copies(\"k\"), -1).transpose(-2, -3)\n\n def get_mask_tensor(self, src_len: int, mask: Optional[AttentionMask]) -> Optional[torch.Tensor]:\n if mask is None or (mask.position_mask is None and mask.src_length_mask is None):\n return None\n\n # mask.position_mask: [..., N_out, N_in]\n # mask.src_length_mask: [B, ...., N_in]\n # True where it has to be masked\n\n if mask.position_mask is not None:\n n_pad = src_len - mask.position_mask.shape[-1]\n if n_pad > 0:\n pm = F.pad(mask.position_mask, (n_pad, 0), 'constant', value=False)\n else:\n pm = mask.position_mask\n\n if mask.position_mask is None:\n m = mask.src_length_mask.unsqueeze(-2).unsqueeze(-2)\n elif mask.src_length_mask is None:\n m = pm\n else:\n m = mask.src_length_mask.unsqueeze(-2).unsqueeze(-2) | pm\n\n return m\n\n def train(self, mode: bool = True):\n self.sel_hist = {}\n return super().train(mode)\n\n def get_lost_on_hist(self, l: List[torch.Tensor]) -> torch.Tensor:\n assert l[0].ndim == 4\n l = [t.flatten(1,2) for t in l]\n sel = torch.cat(l, -2)\n sel_d = F.log_softmax(sel, dim=-1)\n sel_d = framework.utils.distributed_ops.log_mean(sel_d, -2, sync_distributed=False)\n return self.perplexity_reg * ( - utils.entropy_l(sel_d).mean())\n\n def get_reg_loss(self) -> Dict[str, torch.Tensor]:\n l = super().get_reg_loss()\n for k, v in self.sel_hist.items():\n l[f\"moe_att_entropy/{k}\"] = self.get_lost_on_hist(v)\n\n self.sel_hist = {}\n return l\n\n def get_sel(self, t: torch.Tensor, w: torch.Tensor, name: str) -> Selection:\n n_experts = self.n_experts[name]\n n_copies = self.get_n_copies(name)\n\n sel = F.linear(t, w).float()\n sel = sel.view(*sel.shape[:-1], n_copies, -1)\n with torch.no_grad():\n if self.expert_dropout > 0 and self.training:\n mask = torch.rand_like(sel) < self.expert_dropout\n sel2 = sel.masked_fill(mask, float('-inf'))\n else:\n sel2 = sel\n _, sel_index = sel2.topk(self.moe_k, dim=-1, sorted=False)\n sel_val = torch.gather(sel, -1, sel_index)\n\n if self.selection_mode == \"softmax\":\n sel_val = sel_val.softmax(-1)\n elif self.selection_mode == \"sigmoid\":\n sel_val = sel_val.sigmoid()\n else:\n raise ValueError(\"Unknown selection mode: \" + self.selection_mode)\n\n exp_shift = 0 if self.shared_experts else n_experts\n\n sel_index_shifted = (torch.arange(n_copies, device=sel_index.device, dtype=sel_index.dtype) * exp_shift).unsqueeze(-1) + sel_index\n sel_index_pp = cvmm_prepare_sel2(sel_index_shifted.flatten(-2,-1), sel_val)\n\n return Selection(sel, sel_val, sel_index, sel_index_pp)\n\n def before_loss(self):\n self.iter += 1\n if self.iter % 100 == 0:\n for k, v in self.sel_counts_100.items():\n sorted_counts = v.sort(descending=True).values\n self.log(f\"sel_counts/{k}\", framework.visualize.plot.Barplot(sorted_counts, xlabel=\"expert\", ylabel=\"usage count\"), drop_old=True)\n\n self.sel_counts_100 = {}\n\n def exp_proj(self, x: torch.Tensor, w: torch.Tensor, sel: Selection) -> torch.Tensor:\n return cvmm(x, sel.sel_index, w)\n\n def compute_sel(self, curr_state: torch.Tensor, attend_to: torch.Tensor) -> Dict[str, Selection]:\n self.selection_mode\n outs = {}\n done = {}\n cross_atten = curr_state is not attend_to\n\n for name in (set(self.selections.keys()) | set(self.sel_map.keys())):\n name_actual = self.sel_map.get(name, name)\n\n # There coukd be 2 versions of everything: source side and destination side. Check if they are different,\n # and if not, use the cached version, my_id is the unique identifier for this transformation\n is_src_side = (name in self.src_side_maps) or not cross_atten\n my_id = (name_actual, is_src_side)\n\n cached = done.get(my_id)\n if cached is not None:\n outs[name] = cached\n continue\n\n # No cache, actually compute\n inp = attend_to if is_src_side else curr_state\n v = self.selections[name_actual]\n outs[name] = self.get_sel(inp, v, name)\n\n # Save history for regularization\n if self.perplexity_reg > 0 and self.training:\n if name not in self.sel_hist:\n self.sel_hist[name] = []\n self.sel_hist[name].append(outs[name].raw_sel)\n\n # Visualize statistics\n if self.training and self.iter % 10 == 0:\n self.sel_counts_100[name] = self.sel_counts_100.get(name, 0) + \\\n F.one_hot(outs[name].raw_sel_index.flatten(), self.n_experts[name]).sum(0)\n\n done[my_id] = outs[name]\n\n return outs\n\n def project(self, name: str, src: torch.Tensor, sel: Dict[str, Selection]) -> torch.Tensor:\n if name in sel:\n sv = sel[name]\n if self.norm_qk_score and name in {\"q\", \"k\"}:\n sv.sel_index.reduction_weight = F.normalize(sv.sel_index.reduction_weight, p=1, dim=-1)\n return self.exp_proj(src, self.projections[name], sv)\n else:\n return F.linear(src, self.projections[name])\n\n def attend(self, curr_state: torch.Tensor, attend_to: torch.Tensor, pos_offset: int, v: torch.Tensor,\n k: torch.Tensor, q: torch.Tensor, mask: Optional[torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:\n raise NotImplementedError()\n\n def attention_proj(self, att: torch.Tensor, v: torch.Tensor,\n mask: Optional[torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:\n if mask is not None:\n att.masked_fill_(mask, float('-inf'))\n\n att = F.softmax(att, dim=-1)\n\n res = att @ v\n return res, att\n\n def forward(self, curr_state: torch.Tensor, attend_to: torch.Tensor, mask: Optional[AttentionMask],\n pos_offset: Optional[int] = None, need_weights: bool = False):\n # curr_state: [batch_size, out_len, c]\n # attend_to: [batch_size, in_len, c]\n\n if pos_offset is None:\n assert curr_state.shape[1] == attend_to.shape[1], \"If attend_to has different shape than curr_state, pos_offset should be provided\"\n pos_offset = 0\n\n sel = self.compute_sel(curr_state, attend_to)\n\n # scale q and k with sqrt(scale) before the attention. This should save memory, be faster, and\n # keep the range of k and v better. It should make attention NaNs better with float16.\n scale = self.scale.sqrt()\n\n q = self.project(\"q\", curr_state, sel)\n q = q * scale.type_as(q)\n k = self.project(\"k\", attend_to, sel)\n k = k * scale.type_as(k)\n v = self.project(\"v\", attend_to, sel)\n\n q = self.project_to_torch_order(q) if \"q\" not in sel else q.transpose(-2,-3)\n k = self.project_to_torch_order(k) if \"k\" not in sel else k.transpose(-2,-3)\n v = self.project_to_torch_order(v) if \"v\" not in sel else v.transpose(-2,-3)\n\n k = self.dropout(k)\n\n res, att = self.attend(curr_state, attend_to, pos_offset, v, k, q, self.get_mask_tensor(attend_to.shape[-2], mask))\n res = self.norm_ret(res)\n\n if self.visualization_enabled:\n self.attention_to_visualize.append(att[0].detach())\n for k, s in sel.items():\n if k not in self.selections_to_visualize:\n self.selections_to_visualize[k] = []\n\n with torch.no_grad():\n m = torch.zeros([*s.sel_val[0].shape[:-1], self.n_experts[k]], device=s.sel_val.device, dtype=s.sel_val.dtype)\n m.scatter_(-1, s.raw_sel_index[0], s.sel_val[0])\n\n self.selections_to_visualize[k].append(m)\n\n if self.get_n_copies(\"k\") != self.get_n_copies(\"v\"):\n res = res.view(\n *res.shape[:-1], self.get_n_copies(\"v\") // self.get_n_copies(\"k\"), -1).transpose(2,3).flatten(1,2).contiguous()\n\n if self.is_expert[\"o\"]:\n res = res.transpose(-2, -3)\n # The output selection indices are calculated from the current state and are also used for projecting \"q\".\n # But that projection needs to create multiple copies for the different heads. Here we already have the\n # heads, but we have to create copies for the top-k elements. We can calculate that from the reduction\n # weight. We also want to compute not only the weighted average between the top-k elements, but also\n # of the different heads. So reshape the reduction weight accordingly.\n o_sel = sel[\"o\"].sel_index.clone()\n o_sel.sel_index = o_sel.out_index // o_sel.reduction_weight.shape[-1]\n o_sel.reduction_weight = o_sel.reduction_weight.flatten(-2)\n out = cvmm(res, o_sel, self.projections[\"o\"])\n else:\n res = res.transpose(-2, -3)\n out = F.linear(res.contiguous().view(*curr_state.shape[:-1], -1), self.projections[\"o\"])\n\n return out\n\n def plot(self, options: Dict[str, Any]) -> Dict[str, Any]:\n r = {}\n marks = options.get(\"steplabel\")\n n_steps = options.get(\"n_steps\") or 9999999\n y_marks = options.get(\"target_labels\", marks)\n\n ns1 = (self.attention_to_visualize[0].shape[-2] + n_steps) if n_steps < 0 else 0\n ns1_e = self.attention_to_visualize[0].shape[-2] if n_steps < 0 else n_steps\n ns2 = (self.attention_to_visualize[0].shape[-1] + n_steps) if n_steps < 0 else 0\n ns2_e = self.attention_to_visualize[0].shape[-1] if n_steps < 0 else n_steps\n\n if marks is not None:\n assert len(marks) == self.attention_to_visualize[0].shape[-1]\n marks = marks[ns2:ns2_e]\n\n if y_marks is not None:\n assert len(y_marks) == self.attention_to_visualize[0].shape[-2]\n y_marks = y_marks[ns1:ns1_e]\n\n if options.get(\"mha.plot_head_details\") and self.attention_to_visualize[0].shape[0] > 1:\n for head in range(self.attention_to_visualize[0].shape[0]):\n sel_map = {k: [e[:, head][ns1:ns1_e] if k in {'q', 'o'} else e[:, head][ns2:ns2_e] for e in v] for k, v in self.selections_to_visualize.items()}\n selections = {k: torch.stack(v, 0).cpu() for k, v in sel_map.items()}\n\n x_selections = {k: v for k, v in selections.items() if k in {'k', 'v'}}\n y_selections = {k: v for k, v in selections.items() if k in {'q', 'o'}}\n\n r[f\"head_{head}\"] = MoEAttentionPlot(\n torch.stack([layer[head][ns1:ns1_e, ns2:ns2_e] for _, layer in enumerate(self.attention_to_visualize)], 0),\n x_selections, y_selections,\n ylabel=\"dest\", xlabel=\"src\", x_marks=marks, y_marks=y_marks)\n\n r[\"attention_max\"] = framework.visualize.plot.AnimatedHeatmap(\n torch.stack([layer.max(0)[0][ns1:ns1_e, ns2:ns2_e] for _, layer in enumerate(self.attention_to_visualize)], 0),\n ylabel=\"dest\", xlabel=\"src\", textval=False, x_marks=marks, y_marks=y_marks, ignore_wrong_marks=True)\n\n self.attention_to_visualize = []\n self.selections_to_visualize = {}\n return r\n\n def dump_logs(self, save_dir: str):\n if torch.is_tensor(self.sel_correlation):\n os.makedirs(save_dir, exist_ok=True)\n torch.save(self.sel_correlation, os.path.join(save_dir, \"sel_correlation.pt\"))\n\n def get_logs(self) -> Dict[str, Any]:\n res = super().get_logs()\n\n if torch.is_tensor(self.sel_correlation):\n coo = self.sel_correlation / self.sel_correlation.flatten(1).sum(-1).clamp(min=1)[:, None, None]\n for h in range(self.n_heads):\n res[f\"expert_coocurence_{h}\"] = framework.visualize.plot.Heatmap(coo[h], xlabel=\"o expert\", ylabel=\"v expert\", textval=False)\n self.sel_correlation = 0\n return res" } ]
import framework import torch import torch.nn import torch.nn.functional as F import torch.utils.data import math from typing import List, Tuple, Dict, Any from models import TransformerLanguageModel from ... import task, args from layers.transformer import RelativeTransformerEncoderLayer, PrelnRelativeTransformerEncoderLayer from layers.transformer.relative_moe_transformer import RelativeMoeTransformerEncoderLayer from layers.transformer.fast_rope_transformer import FastRopeTransformerEncoderLayer from layers.transformer.moe_attention_relative_transformer import MoeAttentionRelativeTransformerEncoderLayer from layers.moe_layer import MoE from interfaces import Result from layers import LayerVisualizer from layers.transformer.full_moe_relative_attention import FullMoeRelativeAttentionCore
19,506
@args def a(parser: framework.helpers.ArgumentParser): parser.add_argument("-lm.trafo.context_blocks", default=1) parser.add_argument("-lm.trafo.test_context_blocks", default="none", parser=parser.int_or_none_parser) parser.add_argument("-lm.trafo.test_pos_clamp", default="none", parser=parser.int_or_none_parser) parser.add_argument("-lm.trafo.same_length_eval", default=False) parser.add_argument("-lm.trafo.same_length", default=False) parser.add_argument("-lm.trafo.last_layer_context", default=False) parser.add_argument("-lm.trafo.xl_init", default=False) parser.add_argument("-lm.trafo.embedding_mode_init", default="default", choice=["default", "scale_to_sqrt_dmodel", "init_to_sqrt_dmodel", "one_and_scale_to_sqrt_dmodel", "like_preln"]) parser.add_argument("-pkm.n_heads", default=1) parser.add_argument("-moe.n_experts", default=128) parser.add_argument("-moe.expert_size", default=128) parser.add_argument("-moe.selection_mode", default="sigmoid", choice=["gate", "sigmoid", "mul"]) parser.add_argument("-moe.perplexity_reg", default=0.0) parser.add_argument("-moe.perplexity_reg_mode", default="step", choice=["step", "global", "time", "global_time"]) parser.add_argument("-moe.reg_type", default="entropy", choice=["perplexity", "variance", "entropy", "l2", "switch", "normal"]) parser.add_argument("-moe.norm_keys", default=False) parser.add_argument("-moe.n_random", default=0) parser.add_argument("-moe.topk_mode", default="full", choice=["full", "l1_approx", "approx"]) parser.add_argument("-moe.activation_after_topk", default=False) parser.add_argument("-moe.drop_parallel", default=True) parser.add_argument("-moe.norm_key_init", default=False) parser.add_argument("-moe.norm_value_init", default=False) parser.add_argument("-moe.identical_init", default=False) parser.add_argument("-moe.sel_lr_multipler", default=1.0) parser.add_argument("-moe.expert_lr_multipler", default=1.0) parser.add_argument("-moe.sel_norm", default="none", choice=["none", "cos", "input", "weights"]) parser.add_argument("-moe.dropout_factor", default=1.0) parser.add_argument("-moe.drop_expert", default=0.0) parser.add_argument("-moe.sync_distributed", default=True) parser.add_argument("-moe.modulation_amplitude", default=0.5) parser.add_argument("-moe.init_scale", default=1.0) parser.add_argument("-moe.norm_expert_sel_init", default=False) parser.add_argument("-kvmem.dropout", default="none", choice=["none", "early", "late", "weight", "score"]) parser.add_argument("-kvmem.norm_values", default=False) parser.add_argument("-transformer.topk_value", default=32) parser.add_argument("-transformer.activation", default="relu", choice=["relu", "topk", "gelu", "identity", "sigmoid", "softmax"]) parser.add_argument("-transformer.p_drop_layer", default=0.0) parser.add_argument("-transformer.head_projection_size", default="none", parser=parser.int_or_none_parser) parser.add_argument("-transformer.ln_affine", default=True) parser.add_argument("-transformer.ln_after_attention", default=True) parser.add_argument("-moe.att.n_experts", default=4) parser.add_argument("-moe.att.variant", default="moa", choice=["moa", "simple", "qside", "full", "full_rope", "seq", "target"]) parser.add_argument("-moe.att.enable", default=False) parser.add_argument("-moe.att.q_expert", default=True) parser.add_argument("-moe.att.k_expert", default=True) parser.add_argument("-moe.att.v_expert", default=True) parser.add_argument("-moe.att.o_expert", default=True) parser.add_argument("-moe.att.k", default=2) parser.add_argument("-moe.att.norm_qk", default=False) parser.add_argument("-moe.att.v_size", default="none", parser=parser.int_or_none_parser) parser.add_argument("-moe.att.same_sel", default=False) parser.add_argument("-moe.att.expert_dropout", default="none", parser=parser.float_or_none_parser) parser.add_argument("-moe.att.selection_mode", default="sigmoid", choice=["sigmoid", "softmax"]) parser.add_argument("-moe.att.perplexity_reg", default="none", parser=parser.float_or_none_parser) parser.add_argument("-moe.att.qside_n_experts", default="none", parser=parser.int_or_none_parser) parser.add_argument("-moe.att.k", default=2) parser.add_argument("-moe.att.norm_ret", default=False) parser.add_argument("-moe.att.shared_experts", default=False) parser.add_argument("-moe.att.drop_expert", default="none", parser=parser.float_or_none_parser) parser.add_argument("-moe.att.kq_n_experts", default="none", parser=parser.int_or_none_parser) parser.add_argument("-moe.att.separate_kq_sel", default=False) parser.add_argument("-moe.att.norm_init", default=False) parser.add_argument("-rope.rotate_fraction", default=0.5) parser.add_argument("-rope.base", default=10000.0) parser.add_argument("-moa.mode", default="my", choice=["my", "moa"]) parser.add_argument("-moa.cvloss", default=0.0) parser.add_argument("-moa.switchloss", default=0.0) parser.add_argument("-moa.zloss", default=0.0) parser.add_argument("-debug_plot_interval", default="none", parser=parser.int_or_none_parser) parser.add_argument("-transformer.plot_head_details", default=False) parser.add_argument("-plot.n_steps", default=-128) @task() class TransformerLMMixin: helper: framework.helpers.TrainingHelper def is_preln(self) -> bool: return "preln" in self.helper.args.transformer.variant def topk_activation(self, x: torch.Tensor) -> torch.Tensor: nx = -x return torch.masked_fill(x, nx <= nx.kthvalue(self.helper.args.transformer.topk_value, keepdim=True)[0], 0) def get_layers(self) -> List[torch.nn.Module]: # pyright: reportOptionalMemberAccess=false if self.helper.args.transformer.activation == "relu": activation = F.relu elif self.helper.args.transformer.activation == "topk": activation = self.topk_activation elif self.helper.args.transformer.activation == "identity": activation = lambda x: x elif self.helper.args.transformer.activation == "sigmoid": activation = torch.sigmoid elif self.helper.args.transformer.activation == "gelu": activation = F.gelu elif self.helper.args.transformer.activation == "softmax": activation = lambda x: F.softmax(x, dim=-1) else: raise ValueError(f"Invalid activation: {self.helper.args.transformer.activation}") base_args = dict( d_model=self.helper.args.state_size, nhead=self.helper.args.transformer.n_heads, dropout=self.helper.args.dropout, activation=activation ) if self.helper.args.transformer.variant not in {"preln_moe", "moe"}: base_args["dim_feedforward"]=int(self.helper.args.state_size * self.helper.args.transformer.ff_multiplier) extra_args = {} if not self.helper.args.transformer.variant.endswith("_gelu") else { "activation": F.gelu, "drop_expand": False } if self.helper.args.transformer.variant in {"preln_relative"}:
@args def a(parser: framework.helpers.ArgumentParser): parser.add_argument("-lm.trafo.context_blocks", default=1) parser.add_argument("-lm.trafo.test_context_blocks", default="none", parser=parser.int_or_none_parser) parser.add_argument("-lm.trafo.test_pos_clamp", default="none", parser=parser.int_or_none_parser) parser.add_argument("-lm.trafo.same_length_eval", default=False) parser.add_argument("-lm.trafo.same_length", default=False) parser.add_argument("-lm.trafo.last_layer_context", default=False) parser.add_argument("-lm.trafo.xl_init", default=False) parser.add_argument("-lm.trafo.embedding_mode_init", default="default", choice=["default", "scale_to_sqrt_dmodel", "init_to_sqrt_dmodel", "one_and_scale_to_sqrt_dmodel", "like_preln"]) parser.add_argument("-pkm.n_heads", default=1) parser.add_argument("-moe.n_experts", default=128) parser.add_argument("-moe.expert_size", default=128) parser.add_argument("-moe.selection_mode", default="sigmoid", choice=["gate", "sigmoid", "mul"]) parser.add_argument("-moe.perplexity_reg", default=0.0) parser.add_argument("-moe.perplexity_reg_mode", default="step", choice=["step", "global", "time", "global_time"]) parser.add_argument("-moe.reg_type", default="entropy", choice=["perplexity", "variance", "entropy", "l2", "switch", "normal"]) parser.add_argument("-moe.norm_keys", default=False) parser.add_argument("-moe.n_random", default=0) parser.add_argument("-moe.topk_mode", default="full", choice=["full", "l1_approx", "approx"]) parser.add_argument("-moe.activation_after_topk", default=False) parser.add_argument("-moe.drop_parallel", default=True) parser.add_argument("-moe.norm_key_init", default=False) parser.add_argument("-moe.norm_value_init", default=False) parser.add_argument("-moe.identical_init", default=False) parser.add_argument("-moe.sel_lr_multipler", default=1.0) parser.add_argument("-moe.expert_lr_multipler", default=1.0) parser.add_argument("-moe.sel_norm", default="none", choice=["none", "cos", "input", "weights"]) parser.add_argument("-moe.dropout_factor", default=1.0) parser.add_argument("-moe.drop_expert", default=0.0) parser.add_argument("-moe.sync_distributed", default=True) parser.add_argument("-moe.modulation_amplitude", default=0.5) parser.add_argument("-moe.init_scale", default=1.0) parser.add_argument("-moe.norm_expert_sel_init", default=False) parser.add_argument("-kvmem.dropout", default="none", choice=["none", "early", "late", "weight", "score"]) parser.add_argument("-kvmem.norm_values", default=False) parser.add_argument("-transformer.topk_value", default=32) parser.add_argument("-transformer.activation", default="relu", choice=["relu", "topk", "gelu", "identity", "sigmoid", "softmax"]) parser.add_argument("-transformer.p_drop_layer", default=0.0) parser.add_argument("-transformer.head_projection_size", default="none", parser=parser.int_or_none_parser) parser.add_argument("-transformer.ln_affine", default=True) parser.add_argument("-transformer.ln_after_attention", default=True) parser.add_argument("-moe.att.n_experts", default=4) parser.add_argument("-moe.att.variant", default="moa", choice=["moa", "simple", "qside", "full", "full_rope", "seq", "target"]) parser.add_argument("-moe.att.enable", default=False) parser.add_argument("-moe.att.q_expert", default=True) parser.add_argument("-moe.att.k_expert", default=True) parser.add_argument("-moe.att.v_expert", default=True) parser.add_argument("-moe.att.o_expert", default=True) parser.add_argument("-moe.att.k", default=2) parser.add_argument("-moe.att.norm_qk", default=False) parser.add_argument("-moe.att.v_size", default="none", parser=parser.int_or_none_parser) parser.add_argument("-moe.att.same_sel", default=False) parser.add_argument("-moe.att.expert_dropout", default="none", parser=parser.float_or_none_parser) parser.add_argument("-moe.att.selection_mode", default="sigmoid", choice=["sigmoid", "softmax"]) parser.add_argument("-moe.att.perplexity_reg", default="none", parser=parser.float_or_none_parser) parser.add_argument("-moe.att.qside_n_experts", default="none", parser=parser.int_or_none_parser) parser.add_argument("-moe.att.k", default=2) parser.add_argument("-moe.att.norm_ret", default=False) parser.add_argument("-moe.att.shared_experts", default=False) parser.add_argument("-moe.att.drop_expert", default="none", parser=parser.float_or_none_parser) parser.add_argument("-moe.att.kq_n_experts", default="none", parser=parser.int_or_none_parser) parser.add_argument("-moe.att.separate_kq_sel", default=False) parser.add_argument("-moe.att.norm_init", default=False) parser.add_argument("-rope.rotate_fraction", default=0.5) parser.add_argument("-rope.base", default=10000.0) parser.add_argument("-moa.mode", default="my", choice=["my", "moa"]) parser.add_argument("-moa.cvloss", default=0.0) parser.add_argument("-moa.switchloss", default=0.0) parser.add_argument("-moa.zloss", default=0.0) parser.add_argument("-debug_plot_interval", default="none", parser=parser.int_or_none_parser) parser.add_argument("-transformer.plot_head_details", default=False) parser.add_argument("-plot.n_steps", default=-128) @task() class TransformerLMMixin: helper: framework.helpers.TrainingHelper def is_preln(self) -> bool: return "preln" in self.helper.args.transformer.variant def topk_activation(self, x: torch.Tensor) -> torch.Tensor: nx = -x return torch.masked_fill(x, nx <= nx.kthvalue(self.helper.args.transformer.topk_value, keepdim=True)[0], 0) def get_layers(self) -> List[torch.nn.Module]: # pyright: reportOptionalMemberAccess=false if self.helper.args.transformer.activation == "relu": activation = F.relu elif self.helper.args.transformer.activation == "topk": activation = self.topk_activation elif self.helper.args.transformer.activation == "identity": activation = lambda x: x elif self.helper.args.transformer.activation == "sigmoid": activation = torch.sigmoid elif self.helper.args.transformer.activation == "gelu": activation = F.gelu elif self.helper.args.transformer.activation == "softmax": activation = lambda x: F.softmax(x, dim=-1) else: raise ValueError(f"Invalid activation: {self.helper.args.transformer.activation}") base_args = dict( d_model=self.helper.args.state_size, nhead=self.helper.args.transformer.n_heads, dropout=self.helper.args.dropout, activation=activation ) if self.helper.args.transformer.variant not in {"preln_moe", "moe"}: base_args["dim_feedforward"]=int(self.helper.args.state_size * self.helper.args.transformer.ff_multiplier) extra_args = {} if not self.helper.args.transformer.variant.endswith("_gelu") else { "activation": F.gelu, "drop_expand": False } if self.helper.args.transformer.variant in {"preln_relative"}:
mklayer = lambda: PrelnRelativeTransformerEncoderLayer(
4
2023-12-13 08:45:02+00:00
24k
AIFSH/NativeDancer
nativedancer/third_part/detectron2/modeling/meta_arch/retinanet.py
[ { "identifier": "configurable", "path": "nativedancer/third_part/detectron2/config/config.py", "snippet": "def configurable(init_func=None, *, from_config=None):\n \"\"\"\n Decorate a function or a class's __init__ method so that it can be called\n with a :class:`CfgNode` object using a :func:`from_config` function that translates\n :class:`CfgNode` to arguments.\n\n Examples:\n ::\n # Usage 1: Decorator on __init__:\n class A:\n @configurable\n def __init__(self, a, b=2, c=3):\n pass\n\n @classmethod\n def from_config(cls, cfg): # 'cfg' must be the first argument\n # Returns kwargs to be passed to __init__\n return {\"a\": cfg.A, \"b\": cfg.B}\n\n a1 = A(a=1, b=2) # regular construction\n a2 = A(cfg) # construct with a cfg\n a3 = A(cfg, b=3, c=4) # construct with extra overwrite\n\n # Usage 2: Decorator on any function. Needs an extra from_config argument:\n @configurable(from_config=lambda cfg: {\"a: cfg.A, \"b\": cfg.B})\n def a_func(a, b=2, c=3):\n pass\n\n a1 = a_func(a=1, b=2) # regular call\n a2 = a_func(cfg) # call with a cfg\n a3 = a_func(cfg, b=3, c=4) # call with extra overwrite\n\n Args:\n init_func (callable): a class's ``__init__`` method in usage 1. The\n class must have a ``from_config`` classmethod which takes `cfg` as\n the first argument.\n from_config (callable): the from_config function in usage 2. It must take `cfg`\n as its first argument.\n \"\"\"\n\n if init_func is not None:\n assert (\n inspect.isfunction(init_func)\n and from_config is None\n and init_func.__name__ == \"__init__\"\n ), \"Incorrect use of @configurable. Check API documentation for examples.\"\n\n @functools.wraps(init_func)\n def wrapped(self, *args, **kwargs):\n try:\n from_config_func = type(self).from_config\n except AttributeError as e:\n raise AttributeError(\n \"Class with @configurable must have a 'from_config' classmethod.\"\n ) from e\n if not inspect.ismethod(from_config_func):\n raise TypeError(\"Class with @configurable must have a 'from_config' classmethod.\")\n\n if _called_with_cfg(*args, **kwargs):\n explicit_args = _get_args_from_config(from_config_func, *args, **kwargs)\n init_func(self, **explicit_args)\n else:\n init_func(self, *args, **kwargs)\n\n return wrapped\n\n else:\n if from_config is None:\n return configurable # @configurable() is made equivalent to @configurable\n assert inspect.isfunction(\n from_config\n ), \"from_config argument of configurable must be a function!\"\n\n def wrapper(orig_func):\n @functools.wraps(orig_func)\n def wrapped(*args, **kwargs):\n if _called_with_cfg(*args, **kwargs):\n explicit_args = _get_args_from_config(from_config, *args, **kwargs)\n return orig_func(**explicit_args)\n else:\n return orig_func(*args, **kwargs)\n\n wrapped.from_config = from_config\n return wrapped\n\n return wrapper" }, { "identifier": "get_norm", "path": "nativedancer/third_part/detectron2/layers/batch_norm.py", "snippet": "def get_norm(norm, out_channels):\n \"\"\"\n Args:\n norm (str or callable): either one of BN, SyncBN, FrozenBN, GN;\n or a callable that takes a channel number and returns\n the normalization layer as a nn.Module.\n\n Returns:\n nn.Module or None: the normalization layer\n \"\"\"\n if norm is None:\n return None\n if isinstance(norm, str):\n if len(norm) == 0:\n return None\n norm = {\n \"BN\": BatchNorm2d,\n # Fixed in https://github.com/pytorch/pytorch/pull/36382\n \"SyncBN\": NaiveSyncBatchNorm if env.TORCH_VERSION <= (1, 5) else nn.SyncBatchNorm,\n \"FrozenBN\": FrozenBatchNorm2d,\n \"GN\": lambda channels: nn.GroupNorm(32, channels),\n # for debugging:\n \"nnSyncBN\": nn.SyncBatchNorm,\n \"naiveSyncBN\": NaiveSyncBatchNorm,\n # expose stats_mode N as an option to caller, required for zero-len inputs\n \"naiveSyncBN_N\": lambda channels: NaiveSyncBatchNorm(channels, stats_mode=\"N\"),\n \"LN\": lambda channels: LayerNorm(channels),\n }[norm]\n return norm(out_channels)" }, { "identifier": "CycleBatchNormList", "path": "nativedancer/third_part/detectron2/layers/batch_norm.py", "snippet": "class CycleBatchNormList(nn.ModuleList):\n \"\"\"\n Implement domain-specific BatchNorm by cycling.\n\n When a BatchNorm layer is used for multiple input domains or input\n features, it might need to maintain a separate test-time statistics\n for each domain. See Sec 5.2 in :paper:`rethinking-batchnorm`.\n\n This module implements it by using N separate BN layers\n and it cycles through them every time a forward() is called.\n\n NOTE: The caller of this module MUST guarantee to always call\n this module by multiple of N times. Otherwise its test-time statistics\n will be incorrect.\n \"\"\"\n\n def __init__(self, length: int, bn_class=nn.BatchNorm2d, **kwargs):\n \"\"\"\n Args:\n length: number of BatchNorm layers to cycle.\n bn_class: the BatchNorm class to use\n kwargs: arguments of the BatchNorm class, such as num_features.\n \"\"\"\n self._affine = kwargs.pop(\"affine\", True)\n super().__init__([bn_class(**kwargs, affine=False) for k in range(length)])\n if self._affine:\n # shared affine, domain-specific BN\n channels = self[0].num_features\n self.weight = nn.Parameter(torch.ones(channels))\n self.bias = nn.Parameter(torch.zeros(channels))\n self._pos = 0\n\n def forward(self, x):\n ret = self[self._pos](x)\n self._pos = (self._pos + 1) % len(self)\n\n if self._affine:\n w = self.weight.reshape(1, -1, 1, 1)\n b = self.bias.reshape(1, -1, 1, 1)\n return ret * w + b\n else:\n return ret\n\n def extra_repr(self):\n return f\"affine={self._affine}\"" }, { "identifier": "batched_nms", "path": "nativedancer/third_part/detectron2/layers/nms.py", "snippet": "def batched_nms(\n boxes: torch.Tensor, scores: torch.Tensor, idxs: torch.Tensor, iou_threshold: float\n):\n \"\"\"\n Same as torchvision.ops.boxes.batched_nms, but with float().\n \"\"\"\n assert boxes.shape[-1] == 4\n # Note: Torchvision already has a strategy (https://github.com/pytorch/vision/issues/1311)\n # to decide whether to use coordinate trick or for loop to implement batched_nms. So we\n # just call it directly.\n # Fp16 does not have enough range for batched NMS, so adding float().\n return box_ops.batched_nms(boxes.float(), scores, idxs, iou_threshold)" }, { "identifier": "ShapeSpec", "path": "nativedancer/third_part/detectron2/layers/shape_spec.py", "snippet": "class ShapeSpec:\n \"\"\"\n A simple structure that contains basic shape specification about a tensor.\n It is often used as the auxiliary inputs/outputs of models,\n to complement the lack of shape inference ability among pytorch modules.\n \"\"\"\n\n channels: Optional[int] = None\n height: Optional[int] = None\n width: Optional[int] = None\n stride: Optional[int] = None" }, { "identifier": "cat", "path": "nativedancer/third_part/detectron2/layers/wrappers.py", "snippet": "def cat(tensors: List[torch.Tensor], dim: int = 0):\n \"\"\"\n Efficient version of torch.cat that avoids a copy if there is only a single element in a list\n \"\"\"\n assert isinstance(tensors, (list, tuple))\n if len(tensors) == 1:\n return tensors[0]\n return torch.cat(tensors, dim)" }, { "identifier": "Boxes", "path": "nativedancer/third_part/detectron2/structures/boxes.py", "snippet": "class Boxes:\n \"\"\"\n This structure stores a list of boxes as a Nx4 torch.Tensor.\n It supports some common methods about boxes\n (`area`, `clip`, `nonempty`, etc),\n and also behaves like a Tensor\n (support indexing, `to(device)`, `.device`, and iteration over all boxes)\n\n Attributes:\n tensor (torch.Tensor): float matrix of Nx4. Each row is (x1, y1, x2, y2).\n \"\"\"\n\n def __init__(self, tensor: torch.Tensor):\n \"\"\"\n Args:\n tensor (Tensor[float]): a Nx4 matrix. Each row is (x1, y1, x2, y2).\n \"\"\"\n if not isinstance(tensor, torch.Tensor):\n tensor = torch.as_tensor(tensor, dtype=torch.float32, device=torch.device(\"cpu\"))\n else:\n tensor = tensor.to(torch.float32)\n if tensor.numel() == 0:\n # Use reshape, so we don't end up creating a new tensor that does not depend on\n # the inputs (and consequently confuses jit)\n tensor = tensor.reshape((-1, 4)).to(dtype=torch.float32)\n assert tensor.dim() == 2 and tensor.size(-1) == 4, tensor.size()\n\n self.tensor = tensor\n\n def clone(self) -> \"Boxes\":\n \"\"\"\n Clone the Boxes.\n\n Returns:\n Boxes\n \"\"\"\n return Boxes(self.tensor.clone())\n\n def to(self, device: torch.device):\n # Boxes are assumed float32 and does not support to(dtype)\n return Boxes(self.tensor.to(device=device))\n\n def area(self) -> torch.Tensor:\n \"\"\"\n Computes the area of all the boxes.\n\n Returns:\n torch.Tensor: a vector with areas of each box.\n \"\"\"\n box = self.tensor\n area = (box[:, 2] - box[:, 0]) * (box[:, 3] - box[:, 1])\n return area\n\n def clip(self, box_size: Tuple[int, int]) -> None:\n \"\"\"\n Clip (in place) the boxes by limiting x coordinates to the range [0, width]\n and y coordinates to the range [0, height].\n\n Args:\n box_size (height, width): The clipping box's size.\n \"\"\"\n assert torch.isfinite(self.tensor).all(), \"Box tensor contains infinite or NaN!\"\n h, w = box_size\n x1 = self.tensor[:, 0].clamp(min=0, max=w)\n y1 = self.tensor[:, 1].clamp(min=0, max=h)\n x2 = self.tensor[:, 2].clamp(min=0, max=w)\n y2 = self.tensor[:, 3].clamp(min=0, max=h)\n self.tensor = torch.stack((x1, y1, x2, y2), dim=-1)\n\n def nonempty(self, threshold: float = 0.0) -> torch.Tensor:\n \"\"\"\n Find boxes that are non-empty.\n A box is considered empty, if either of its side is no larger than threshold.\n\n Returns:\n Tensor:\n a binary vector which represents whether each box is empty\n (False) or non-empty (True).\n \"\"\"\n box = self.tensor\n widths = box[:, 2] - box[:, 0]\n heights = box[:, 3] - box[:, 1]\n keep = (widths > threshold) & (heights > threshold)\n return keep\n\n def __getitem__(self, item) -> \"Boxes\":\n \"\"\"\n Args:\n item: int, slice, or a BoolTensor\n\n Returns:\n Boxes: Create a new :class:`Boxes` by indexing.\n\n The following usage are allowed:\n\n 1. `new_boxes = boxes[3]`: return a `Boxes` which contains only one box.\n 2. `new_boxes = boxes[2:10]`: return a slice of boxes.\n 3. `new_boxes = boxes[vector]`, where vector is a torch.BoolTensor\n with `length = len(boxes)`. Nonzero elements in the vector will be selected.\n\n Note that the returned Boxes might share storage with this Boxes,\n subject to Pytorch's indexing semantics.\n \"\"\"\n if isinstance(item, int):\n return Boxes(self.tensor[item].view(1, -1))\n b = self.tensor[item]\n assert b.dim() == 2, \"Indexing on Boxes with {} failed to return a matrix!\".format(item)\n return Boxes(b)\n\n def __len__(self) -> int:\n return self.tensor.shape[0]\n\n def __repr__(self) -> str:\n return \"Boxes(\" + str(self.tensor) + \")\"\n\n def inside_box(self, box_size: Tuple[int, int], boundary_threshold: int = 0) -> torch.Tensor:\n \"\"\"\n Args:\n box_size (height, width): Size of the reference box.\n boundary_threshold (int): Boxes that extend beyond the reference box\n boundary by more than boundary_threshold are considered \"outside\".\n\n Returns:\n a binary vector, indicating whether each box is inside the reference box.\n \"\"\"\n height, width = box_size\n inds_inside = (\n (self.tensor[..., 0] >= -boundary_threshold)\n & (self.tensor[..., 1] >= -boundary_threshold)\n & (self.tensor[..., 2] < width + boundary_threshold)\n & (self.tensor[..., 3] < height + boundary_threshold)\n )\n return inds_inside\n\n def get_centers(self) -> torch.Tensor:\n \"\"\"\n Returns:\n The box centers in a Nx2 array of (x, y).\n \"\"\"\n return (self.tensor[:, :2] + self.tensor[:, 2:]) / 2\n\n def scale(self, scale_x: float, scale_y: float) -> None:\n \"\"\"\n Scale the box with horizontal and vertical scaling factors\n \"\"\"\n self.tensor[:, 0::2] *= scale_x\n self.tensor[:, 1::2] *= scale_y\n\n @classmethod\n def cat(cls, boxes_list: List[\"Boxes\"]) -> \"Boxes\":\n \"\"\"\n Concatenates a list of Boxes into a single Boxes\n\n Arguments:\n boxes_list (list[Boxes])\n\n Returns:\n Boxes: the concatenated Boxes\n \"\"\"\n assert isinstance(boxes_list, (list, tuple))\n if len(boxes_list) == 0:\n return cls(torch.empty(0))\n assert all([isinstance(box, Boxes) for box in boxes_list])\n\n # use torch.cat (v.s. layers.cat) so the returned boxes never share storage with input\n cat_boxes = cls(torch.cat([b.tensor for b in boxes_list], dim=0))\n return cat_boxes\n\n @property\n def device(self) -> device:\n return self.tensor.device\n\n # type \"Iterator[torch.Tensor]\", yield, and iter() not supported by torchscript\n # https://github.com/pytorch/pytorch/issues/18627\n @torch.jit.unused\n def __iter__(self):\n \"\"\"\n Yield a box as a Tensor of shape (4,) at a time.\n \"\"\"\n yield from self.tensor" }, { "identifier": "pairwise_iou", "path": "nativedancer/third_part/detectron2/structures/boxes.py", "snippet": "def pairwise_iou(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:\n \"\"\"\n Given two lists of boxes of size N and M, compute the IoU\n (intersection over union) between **all** N x M pairs of boxes.\n The box order must be (xmin, ymin, xmax, ymax).\n\n Args:\n boxes1,boxes2 (Boxes): two `Boxes`. Contains N & M boxes, respectively.\n\n Returns:\n Tensor: IoU, sized [N,M].\n \"\"\"\n area1 = boxes1.area() # [N]\n area2 = boxes2.area() # [M]\n inter = pairwise_intersection(boxes1, boxes2)\n\n # handle empty boxes\n iou = torch.where(\n inter > 0,\n inter / (area1[:, None] + area2 - inter),\n torch.zeros(1, dtype=inter.dtype, device=inter.device),\n )\n return iou" }, { "identifier": "ImageList", "path": "nativedancer/third_part/detectron2/structures/image_list.py", "snippet": "class ImageList:\n \"\"\"\n Structure that holds a list of images (of possibly\n varying sizes) as a single tensor.\n This works by padding the images to the same size.\n The original sizes of each image is stored in `image_sizes`.\n\n Attributes:\n image_sizes (list[tuple[int, int]]): each tuple is (h, w).\n During tracing, it becomes list[Tensor] instead.\n \"\"\"\n\n def __init__(self, tensor: torch.Tensor, image_sizes: List[Tuple[int, int]]):\n \"\"\"\n Arguments:\n tensor (Tensor): of shape (N, H, W) or (N, C_1, ..., C_K, H, W) where K >= 1\n image_sizes (list[tuple[int, int]]): Each tuple is (h, w). It can\n be smaller than (H, W) due to padding.\n \"\"\"\n self.tensor = tensor\n self.image_sizes = image_sizes\n\n def __len__(self) -> int:\n return len(self.image_sizes)\n\n def __getitem__(self, idx) -> torch.Tensor:\n \"\"\"\n Access the individual image in its original size.\n\n Args:\n idx: int or slice\n\n Returns:\n Tensor: an image of shape (H, W) or (C_1, ..., C_K, H, W) where K >= 1\n \"\"\"\n size = self.image_sizes[idx]\n return self.tensor[idx, ..., : size[0], : size[1]]\n\n @torch.jit.unused\n def to(self, *args: Any, **kwargs: Any) -> \"ImageList\":\n cast_tensor = self.tensor.to(*args, **kwargs)\n return ImageList(cast_tensor, self.image_sizes)\n\n @property\n def device(self) -> device:\n return self.tensor.device\n\n @staticmethod\n def from_tensors(\n tensors: List[torch.Tensor],\n size_divisibility: int = 0,\n pad_value: float = 0.0,\n padding_constraints: Optional[Dict[str, int]] = None,\n ) -> \"ImageList\":\n \"\"\"\n Args:\n tensors: a tuple or list of `torch.Tensor`, each of shape (Hi, Wi) or\n (C_1, ..., C_K, Hi, Wi) where K >= 1. The Tensors will be padded\n to the same shape with `pad_value`.\n size_divisibility (int): If `size_divisibility > 0`, add padding to ensure\n the common height and width is divisible by `size_divisibility`.\n This depends on the model and many models need a divisibility of 32.\n pad_value (float): value to pad.\n padding_constraints (optional[Dict]): If given, it would follow the format as\n {\"size_divisibility\": int, \"square_size\": int}, where `size_divisibility` will\n overwrite the above one if presented and `square_size` indicates the\n square padding size if `square_size` > 0.\n Returns:\n an `ImageList`.\n \"\"\"\n assert len(tensors) > 0\n assert isinstance(tensors, (tuple, list))\n for t in tensors:\n assert isinstance(t, torch.Tensor), type(t)\n assert t.shape[:-2] == tensors[0].shape[:-2], t.shape\n\n image_sizes = [(im.shape[-2], im.shape[-1]) for im in tensors]\n image_sizes_tensor = [shapes_to_tensor(x) for x in image_sizes]\n max_size = torch.stack(image_sizes_tensor).max(0).values\n\n if padding_constraints is not None:\n square_size = padding_constraints.get(\"square_size\", 0)\n if square_size > 0:\n # pad to square.\n max_size[0] = max_size[1] = square_size\n if \"size_divisibility\" in padding_constraints:\n size_divisibility = padding_constraints[\"size_divisibility\"]\n if size_divisibility > 1:\n stride = size_divisibility\n # the last two dims are H,W, both subject to divisibility requirement\n max_size = (max_size + (stride - 1)).div(stride, rounding_mode=\"floor\") * stride\n\n # handle weirdness of scripting and tracing ...\n if torch.jit.is_scripting():\n max_size: List[int] = max_size.to(dtype=torch.long).tolist()\n else:\n if torch.jit.is_tracing():\n image_sizes = image_sizes_tensor\n\n if len(tensors) == 1:\n # This seems slightly (2%) faster.\n # TODO: check whether it's faster for multiple images as well\n image_size = image_sizes[0]\n padding_size = [0, max_size[-1] - image_size[1], 0, max_size[-2] - image_size[0]]\n batched_imgs = F.pad(tensors[0], padding_size, value=pad_value).unsqueeze_(0)\n else:\n # max_size can be a tensor in tracing mode, therefore convert to list\n batch_shape = [len(tensors)] + list(tensors[0].shape[:-2]) + list(max_size)\n device = (\n None if torch.jit.is_scripting() else (\"cpu\" if torch.jit.is_tracing() else None)\n )\n batched_imgs = tensors[0].new_full(batch_shape, pad_value, device=device)\n batched_imgs = move_device_like(batched_imgs, tensors[0])\n for i, img in enumerate(tensors):\n # Use `batched_imgs` directly instead of `img, pad_img = zip(tensors, batched_imgs)`\n # Tracing mode cannot capture `copy_()` of temporary locals\n batched_imgs[i, ..., : img.shape[-2], : img.shape[-1]].copy_(img)\n\n return ImageList(batched_imgs.contiguous(), image_sizes)" }, { "identifier": "Instances", "path": "nativedancer/third_part/detectron2/structures/instances.py", "snippet": "class Instances:\n \"\"\"\n This class represents a list of instances in an image.\n It stores the attributes of instances (e.g., boxes, masks, labels, scores) as \"fields\".\n All fields must have the same ``__len__`` which is the number of instances.\n\n All other (non-field) attributes of this class are considered private:\n they must start with '_' and are not modifiable by a user.\n\n Some basic usage:\n\n 1. Set/get/check a field:\n\n .. code-block:: python\n\n instances.gt_boxes = Boxes(...)\n print(instances.pred_masks) # a tensor of shape (N, H, W)\n print('gt_masks' in instances)\n\n 2. ``len(instances)`` returns the number of instances\n 3. Indexing: ``instances[indices]`` will apply the indexing on all the fields\n and returns a new :class:`Instances`.\n Typically, ``indices`` is a integer vector of indices,\n or a binary mask of length ``num_instances``\n\n .. code-block:: python\n\n category_3_detections = instances[instances.pred_classes == 3]\n confident_detections = instances[instances.scores > 0.9]\n \"\"\"\n\n def __init__(self, image_size: Tuple[int, int], **kwargs: Any):\n \"\"\"\n Args:\n image_size (height, width): the spatial size of the image.\n kwargs: fields to add to this `Instances`.\n \"\"\"\n self._image_size = image_size\n self._fields: Dict[str, Any] = {}\n for k, v in kwargs.items():\n self.set(k, v)\n\n @property\n def image_size(self) -> Tuple[int, int]:\n \"\"\"\n Returns:\n tuple: height, width\n \"\"\"\n return self._image_size\n\n def __setattr__(self, name: str, val: Any) -> None:\n if name.startswith(\"_\"):\n super().__setattr__(name, val)\n else:\n self.set(name, val)\n\n def __getattr__(self, name: str) -> Any:\n if name == \"_fields\" or name not in self._fields:\n raise AttributeError(\"Cannot find field '{}' in the given Instances!\".format(name))\n return self._fields[name]\n\n def set(self, name: str, value: Any) -> None:\n \"\"\"\n Set the field named `name` to `value`.\n The length of `value` must be the number of instances,\n and must agree with other existing fields in this object.\n \"\"\"\n with warnings.catch_warnings(record=True):\n data_len = len(value)\n if len(self._fields):\n assert (\n len(self) == data_len\n ), \"Adding a field of length {} to a Instances of length {}\".format(data_len, len(self))\n self._fields[name] = value\n\n def has(self, name: str) -> bool:\n \"\"\"\n Returns:\n bool: whether the field called `name` exists.\n \"\"\"\n return name in self._fields\n\n def remove(self, name: str) -> None:\n \"\"\"\n Remove the field called `name`.\n \"\"\"\n del self._fields[name]\n\n def get(self, name: str) -> Any:\n \"\"\"\n Returns the field called `name`.\n \"\"\"\n return self._fields[name]\n\n def get_fields(self) -> Dict[str, Any]:\n \"\"\"\n Returns:\n dict: a dict which maps names (str) to data of the fields\n\n Modifying the returned dict will modify this instance.\n \"\"\"\n return self._fields\n\n # Tensor-like methods\n def to(self, *args: Any, **kwargs: Any) -> \"Instances\":\n \"\"\"\n Returns:\n Instances: all fields are called with a `to(device)`, if the field has this method.\n \"\"\"\n ret = Instances(self._image_size)\n for k, v in self._fields.items():\n if hasattr(v, \"to\"):\n v = v.to(*args, **kwargs)\n ret.set(k, v)\n return ret\n\n def __getitem__(self, item: Union[int, slice, torch.BoolTensor]) -> \"Instances\":\n \"\"\"\n Args:\n item: an index-like object and will be used to index all the fields.\n\n Returns:\n If `item` is a string, return the data in the corresponding field.\n Otherwise, returns an `Instances` where all fields are indexed by `item`.\n \"\"\"\n if type(item) == int:\n if item >= len(self) or item < -len(self):\n raise IndexError(\"Instances index out of range!\")\n else:\n item = slice(item, None, len(self))\n\n ret = Instances(self._image_size)\n for k, v in self._fields.items():\n ret.set(k, v[item])\n return ret\n\n def __len__(self) -> int:\n for v in self._fields.values():\n # use __len__ because len() has to be int and is not friendly to tracing\n return v.__len__()\n raise NotImplementedError(\"Empty Instances does not support __len__!\")\n\n def __iter__(self):\n raise NotImplementedError(\"`Instances` object is not iterable!\")\n\n @staticmethod\n def cat(instance_lists: List[\"Instances\"]) -> \"Instances\":\n \"\"\"\n Args:\n instance_lists (list[Instances])\n\n Returns:\n Instances\n \"\"\"\n assert all(isinstance(i, Instances) for i in instance_lists)\n assert len(instance_lists) > 0\n if len(instance_lists) == 1:\n return instance_lists[0]\n\n image_size = instance_lists[0].image_size\n if not isinstance(image_size, torch.Tensor): # could be a tensor in tracing\n for i in instance_lists[1:]:\n assert i.image_size == image_size\n ret = Instances(image_size)\n for k in instance_lists[0]._fields.keys():\n values = [i.get(k) for i in instance_lists]\n v0 = values[0]\n if isinstance(v0, torch.Tensor):\n values = torch.cat(values, dim=0)\n elif isinstance(v0, list):\n values = list(itertools.chain(*values))\n elif hasattr(type(v0), \"cat\"):\n values = type(v0).cat(values)\n else:\n raise ValueError(\"Unsupported type {} for concatenation\".format(type(v0)))\n ret.set(k, values)\n return ret\n\n def __str__(self) -> str:\n s = self.__class__.__name__ + \"(\"\n s += \"num_instances={}, \".format(len(self))\n s += \"image_height={}, \".format(self._image_size[0])\n s += \"image_width={}, \".format(self._image_size[1])\n s += \"fields=[{}])\".format(\", \".join((f\"{k}: {v}\" for k, v in self._fields.items())))\n return s\n\n __repr__ = __str__" }, { "identifier": "get_event_storage", "path": "nativedancer/third_part/detectron2/utils/events.py", "snippet": "def get_event_storage():\n \"\"\"\n Returns:\n The :class:`EventStorage` object that's currently being used.\n Throws an error if no :class:`EventStorage` is currently enabled.\n \"\"\"\n assert len(\n _CURRENT_STORAGE_STACK\n ), \"get_event_storage() has to be called inside a 'with EventStorage(...)' context!\"\n return _CURRENT_STORAGE_STACK[-1]" }, { "identifier": "build_anchor_generator", "path": "nativedancer/third_part/detectron2/modeling/anchor_generator.py", "snippet": "def build_anchor_generator(cfg, input_shape):\n \"\"\"\n Built an anchor generator from `cfg.MODEL.ANCHOR_GENERATOR.NAME`.\n \"\"\"\n anchor_generator = cfg.MODEL.ANCHOR_GENERATOR.NAME\n return ANCHOR_GENERATOR_REGISTRY.get(anchor_generator)(cfg, input_shape)" }, { "identifier": "build_backbone", "path": "nativedancer/third_part/detectron2/modeling/backbone/build.py", "snippet": "def build_backbone(cfg, input_shape=None):\n \"\"\"\n Build a backbone from `cfg.MODEL.BACKBONE.NAME`.\n\n Returns:\n an instance of :class:`Backbone`\n \"\"\"\n if input_shape is None:\n input_shape = ShapeSpec(channels=len(cfg.MODEL.PIXEL_MEAN))\n\n backbone_name = cfg.MODEL.BACKBONE.NAME\n backbone = BACKBONE_REGISTRY.get(backbone_name)(cfg, input_shape)\n assert isinstance(backbone, Backbone)\n return backbone" }, { "identifier": "Backbone", "path": "nativedancer/third_part/detectron2/modeling/backbone/backbone.py", "snippet": "class Backbone(nn.Module, metaclass=ABCMeta):\n \"\"\"\n Abstract base class for network backbones.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n The `__init__` method of any subclass can specify its own set of arguments.\n \"\"\"\n super().__init__()\n\n @abstractmethod\n def forward(self):\n \"\"\"\n Subclasses must override this method, but adhere to the same return type.\n\n Returns:\n dict[str->Tensor]: mapping from feature name (e.g., \"res2\") to tensor\n \"\"\"\n pass\n\n @property\n def size_divisibility(self) -> int:\n \"\"\"\n Some backbones require the input height and width to be divisible by a\n specific integer. This is typically true for encoder / decoder type networks\n with lateral connection (e.g., FPN) for which feature maps need to match\n dimension in the \"bottom up\" and \"top down\" paths. Set to 0 if no specific\n input size divisibility is required.\n \"\"\"\n return 0\n\n @property\n def padding_constraints(self) -> Dict[str, int]:\n \"\"\"\n This property is a generalization of size_divisibility. Some backbones and training\n recipes require specific padding constraints, such as enforcing divisibility by a specific\n integer (e.g., FPN) or padding to a square (e.g., ViTDet with large-scale jitter\n in :paper:vitdet). `padding_constraints` contains these optional items like:\n {\n \"size_divisibility\": int,\n \"square_size\": int,\n # Future options are possible\n }\n `size_divisibility` will read from here if presented and `square_size` indicates the\n square padding size if `square_size` > 0.\n\n TODO: use type of Dict[str, int] to avoid torchscipt issues. The type of padding_constraints\n could be generalized as TypedDict (Python 3.8+) to support more types in the future.\n \"\"\"\n return {}\n\n def output_shape(self):\n \"\"\"\n Returns:\n dict[str->ShapeSpec]\n \"\"\"\n # this is a backward-compatible default\n return {\n name: ShapeSpec(\n channels=self._out_feature_channels[name], stride=self._out_feature_strides[name]\n )\n for name in self._out_features\n }" }, { "identifier": "Box2BoxTransform", "path": "nativedancer/third_part/detectron2/modeling/box_regression.py", "snippet": "class Box2BoxTransform:\n \"\"\"\n The box-to-box transform defined in R-CNN. The transformation is parameterized\n by 4 deltas: (dx, dy, dw, dh). The transformation scales the box's width and height\n by exp(dw), exp(dh) and shifts a box's center by the offset (dx * width, dy * height).\n \"\"\"\n\n def __init__(\n self, weights: Tuple[float, float, float, float], scale_clamp: float = _DEFAULT_SCALE_CLAMP\n ):\n \"\"\"\n Args:\n weights (4-element tuple): Scaling factors that are applied to the\n (dx, dy, dw, dh) deltas. In Fast R-CNN, these were originally set\n such that the deltas have unit variance; now they are treated as\n hyperparameters of the system.\n scale_clamp (float): When predicting deltas, the predicted box scaling\n factors (dw and dh) are clamped such that they are <= scale_clamp.\n \"\"\"\n self.weights = weights\n self.scale_clamp = scale_clamp\n\n def get_deltas(self, src_boxes, target_boxes):\n \"\"\"\n Get box regression transformation deltas (dx, dy, dw, dh) that can be used\n to transform the `src_boxes` into the `target_boxes`. That is, the relation\n ``target_boxes == self.apply_deltas(deltas, src_boxes)`` is true (unless\n any delta is too large and is clamped).\n\n Args:\n src_boxes (Tensor): source boxes, e.g., object proposals\n target_boxes (Tensor): target of the transformation, e.g., ground-truth\n boxes.\n \"\"\"\n assert isinstance(src_boxes, torch.Tensor), type(src_boxes)\n assert isinstance(target_boxes, torch.Tensor), type(target_boxes)\n\n src_widths = src_boxes[:, 2] - src_boxes[:, 0]\n src_heights = src_boxes[:, 3] - src_boxes[:, 1]\n src_ctr_x = src_boxes[:, 0] + 0.5 * src_widths\n src_ctr_y = src_boxes[:, 1] + 0.5 * src_heights\n\n target_widths = target_boxes[:, 2] - target_boxes[:, 0]\n target_heights = target_boxes[:, 3] - target_boxes[:, 1]\n target_ctr_x = target_boxes[:, 0] + 0.5 * target_widths\n target_ctr_y = target_boxes[:, 1] + 0.5 * target_heights\n\n wx, wy, ww, wh = self.weights\n dx = wx * (target_ctr_x - src_ctr_x) / src_widths\n dy = wy * (target_ctr_y - src_ctr_y) / src_heights\n dw = ww * torch.log(target_widths / src_widths)\n dh = wh * torch.log(target_heights / src_heights)\n\n deltas = torch.stack((dx, dy, dw, dh), dim=1)\n assert (src_widths > 0).all().item(), \"Input boxes to Box2BoxTransform are not valid!\"\n return deltas\n\n def apply_deltas(self, deltas, boxes):\n \"\"\"\n Apply transformation `deltas` (dx, dy, dw, dh) to `boxes`.\n\n Args:\n deltas (Tensor): transformation deltas of shape (N, k*4), where k >= 1.\n deltas[i] represents k potentially different class-specific\n box transformations for the single box boxes[i].\n boxes (Tensor): boxes to transform, of shape (N, 4)\n \"\"\"\n deltas = deltas.float() # ensure fp32 for decoding precision\n boxes = boxes.to(deltas.dtype)\n\n widths = boxes[:, 2] - boxes[:, 0]\n heights = boxes[:, 3] - boxes[:, 1]\n ctr_x = boxes[:, 0] + 0.5 * widths\n ctr_y = boxes[:, 1] + 0.5 * heights\n\n wx, wy, ww, wh = self.weights\n dx = deltas[:, 0::4] / wx\n dy = deltas[:, 1::4] / wy\n dw = deltas[:, 2::4] / ww\n dh = deltas[:, 3::4] / wh\n\n # Prevent sending too large values into torch.exp()\n dw = torch.clamp(dw, max=self.scale_clamp)\n dh = torch.clamp(dh, max=self.scale_clamp)\n\n pred_ctr_x = dx * widths[:, None] + ctr_x[:, None]\n pred_ctr_y = dy * heights[:, None] + ctr_y[:, None]\n pred_w = torch.exp(dw) * widths[:, None]\n pred_h = torch.exp(dh) * heights[:, None]\n\n x1 = pred_ctr_x - 0.5 * pred_w\n y1 = pred_ctr_y - 0.5 * pred_h\n x2 = pred_ctr_x + 0.5 * pred_w\n y2 = pred_ctr_y + 0.5 * pred_h\n pred_boxes = torch.stack((x1, y1, x2, y2), dim=-1)\n return pred_boxes.reshape(deltas.shape)" }, { "identifier": "_dense_box_regression_loss", "path": "nativedancer/third_part/detectron2/modeling/box_regression.py", "snippet": "def _dense_box_regression_loss(\n anchors: List[Union[Boxes, torch.Tensor]],\n box2box_transform: Box2BoxTransform,\n pred_anchor_deltas: List[torch.Tensor],\n gt_boxes: List[torch.Tensor],\n fg_mask: torch.Tensor,\n box_reg_loss_type=\"smooth_l1\",\n smooth_l1_beta=0.0,\n):\n \"\"\"\n Compute loss for dense multi-level box regression.\n Loss is accumulated over ``fg_mask``.\n\n Args:\n anchors: #lvl anchor boxes, each is (HixWixA, 4)\n pred_anchor_deltas: #lvl predictions, each is (N, HixWixA, 4)\n gt_boxes: N ground truth boxes, each has shape (R, 4) (R = sum(Hi * Wi * A))\n fg_mask: the foreground boolean mask of shape (N, R) to compute loss on\n box_reg_loss_type (str): Loss type to use. Supported losses: \"smooth_l1\", \"giou\",\n \"diou\", \"ciou\".\n smooth_l1_beta (float): beta parameter for the smooth L1 regression loss. Default to\n use L1 loss. Only used when `box_reg_loss_type` is \"smooth_l1\"\n \"\"\"\n if isinstance(anchors[0], Boxes):\n anchors = type(anchors[0]).cat(anchors).tensor # (R, 4)\n else:\n anchors = cat(anchors)\n if box_reg_loss_type == \"smooth_l1\":\n gt_anchor_deltas = [box2box_transform.get_deltas(anchors, k) for k in gt_boxes]\n gt_anchor_deltas = torch.stack(gt_anchor_deltas) # (N, R, 4)\n loss_box_reg = smooth_l1_loss(\n cat(pred_anchor_deltas, dim=1)[fg_mask],\n gt_anchor_deltas[fg_mask],\n beta=smooth_l1_beta,\n reduction=\"sum\",\n )\n elif box_reg_loss_type == \"giou\":\n pred_boxes = [\n box2box_transform.apply_deltas(k, anchors) for k in cat(pred_anchor_deltas, dim=1)\n ]\n loss_box_reg = giou_loss(\n torch.stack(pred_boxes)[fg_mask], torch.stack(gt_boxes)[fg_mask], reduction=\"sum\"\n )\n elif box_reg_loss_type == \"diou\":\n pred_boxes = [\n box2box_transform.apply_deltas(k, anchors) for k in cat(pred_anchor_deltas, dim=1)\n ]\n loss_box_reg = diou_loss(\n torch.stack(pred_boxes)[fg_mask], torch.stack(gt_boxes)[fg_mask], reduction=\"sum\"\n )\n elif box_reg_loss_type == \"ciou\":\n pred_boxes = [\n box2box_transform.apply_deltas(k, anchors) for k in cat(pred_anchor_deltas, dim=1)\n ]\n loss_box_reg = ciou_loss(\n torch.stack(pred_boxes)[fg_mask], torch.stack(gt_boxes)[fg_mask], reduction=\"sum\"\n )\n else:\n raise ValueError(f\"Invalid dense box regression loss type '{box_reg_loss_type}'\")\n return loss_box_reg" }, { "identifier": "Matcher", "path": "nativedancer/third_part/detectron2/modeling/matcher.py", "snippet": "class Matcher:\n \"\"\"\n This class assigns to each predicted \"element\" (e.g., a box) a ground-truth\n element. Each predicted element will have exactly zero or one matches; each\n ground-truth element may be matched to zero or more predicted elements.\n\n The matching is determined by the MxN match_quality_matrix, that characterizes\n how well each (ground-truth, prediction)-pair match each other. For example,\n if the elements are boxes, this matrix may contain box intersection-over-union\n overlap values.\n\n The matcher returns (a) a vector of length N containing the index of the\n ground-truth element m in [0, M) that matches to prediction n in [0, N).\n (b) a vector of length N containing the labels for each prediction.\n \"\"\"\n\n def __init__(\n self, thresholds: List[float], labels: List[int], allow_low_quality_matches: bool = False\n ):\n \"\"\"\n Args:\n thresholds (list): a list of thresholds used to stratify predictions\n into levels.\n labels (list): a list of values to label predictions belonging at\n each level. A label can be one of {-1, 0, 1} signifying\n {ignore, negative class, positive class}, respectively.\n allow_low_quality_matches (bool): if True, produce additional matches\n for predictions with maximum match quality lower than high_threshold.\n See set_low_quality_matches_ for more details.\n\n For example,\n thresholds = [0.3, 0.5]\n labels = [0, -1, 1]\n All predictions with iou < 0.3 will be marked with 0 and\n thus will be considered as false positives while training.\n All predictions with 0.3 <= iou < 0.5 will be marked with -1 and\n thus will be ignored.\n All predictions with 0.5 <= iou will be marked with 1 and\n thus will be considered as true positives.\n \"\"\"\n # Add -inf and +inf to first and last position in thresholds\n thresholds = thresholds[:]\n assert thresholds[0] > 0\n thresholds.insert(0, -float(\"inf\"))\n thresholds.append(float(\"inf\"))\n # Currently torchscript does not support all + generator\n assert all([low <= high for (low, high) in zip(thresholds[:-1], thresholds[1:])])\n assert all([l in [-1, 0, 1] for l in labels])\n assert len(labels) == len(thresholds) - 1\n self.thresholds = thresholds\n self.labels = labels\n self.allow_low_quality_matches = allow_low_quality_matches\n\n def __call__(self, match_quality_matrix):\n \"\"\"\n Args:\n match_quality_matrix (Tensor[float]): an MxN tensor, containing the\n pairwise quality between M ground-truth elements and N predicted\n elements. All elements must be >= 0 (due to the us of `torch.nonzero`\n for selecting indices in :meth:`set_low_quality_matches_`).\n\n Returns:\n matches (Tensor[int64]): a vector of length N, where matches[i] is a matched\n ground-truth index in [0, M)\n match_labels (Tensor[int8]): a vector of length N, where pred_labels[i] indicates\n whether a prediction is a true or false positive or ignored\n \"\"\"\n assert match_quality_matrix.dim() == 2\n if match_quality_matrix.numel() == 0:\n default_matches = match_quality_matrix.new_full(\n (match_quality_matrix.size(1),), 0, dtype=torch.int64\n )\n # When no gt boxes exist, we define IOU = 0 and therefore set labels\n # to `self.labels[0]`, which usually defaults to background class 0\n # To choose to ignore instead, can make labels=[-1,0,-1,1] + set appropriate thresholds\n default_match_labels = match_quality_matrix.new_full(\n (match_quality_matrix.size(1),), self.labels[0], dtype=torch.int8\n )\n return default_matches, default_match_labels\n\n assert torch.all(match_quality_matrix >= 0)\n\n # match_quality_matrix is M (gt) x N (predicted)\n # Max over gt elements (dim 0) to find best gt candidate for each prediction\n matched_vals, matches = match_quality_matrix.max(dim=0)\n\n match_labels = matches.new_full(matches.size(), 1, dtype=torch.int8)\n\n for (l, low, high) in zip(self.labels, self.thresholds[:-1], self.thresholds[1:]):\n low_high = (matched_vals >= low) & (matched_vals < high)\n match_labels[low_high] = l\n\n if self.allow_low_quality_matches:\n self.set_low_quality_matches_(match_labels, match_quality_matrix)\n\n return matches, match_labels\n\n def set_low_quality_matches_(self, match_labels, match_quality_matrix):\n \"\"\"\n Produce additional matches for predictions that have only low-quality matches.\n Specifically, for each ground-truth G find the set of predictions that have\n maximum overlap with it (including ties); for each prediction in that set, if\n it is unmatched, then match it to the ground-truth G.\n\n This function implements the RPN assignment case (i) in Sec. 3.1.2 of\n :paper:`Faster R-CNN`.\n \"\"\"\n # For each gt, find the prediction with which it has highest quality\n highest_quality_foreach_gt, _ = match_quality_matrix.max(dim=1)\n # Find the highest quality match available, even if it is low, including ties.\n # Note that the matches qualities must be positive due to the use of\n # `torch.nonzero`.\n _, pred_inds_with_highest_quality = nonzero_tuple(\n match_quality_matrix == highest_quality_foreach_gt[:, None]\n )\n # If an anchor was labeled positive only due to a low-quality match\n # with gt_A, but it has larger overlap with gt_B, it's matched index will still be gt_B.\n # This follows the implementation in Detectron, and is found to have no significant impact.\n match_labels[pred_inds_with_highest_quality] = 1" }, { "identifier": "META_ARCH_REGISTRY", "path": "nativedancer/third_part/detectron2/modeling/meta_arch/build.py", "snippet": "META_ARCH_REGISTRY = Registry(\"META_ARCH\") # noqa F401 isort:skip" }, { "identifier": "DenseDetector", "path": "nativedancer/third_part/detectron2/modeling/meta_arch/dense_detector.py", "snippet": "class DenseDetector(nn.Module):\n \"\"\"\n Base class for dense detector. We define a dense detector as a fully-convolutional model that\n makes per-pixel (i.e. dense) predictions.\n \"\"\"\n\n def __init__(\n self,\n backbone: Backbone,\n head: nn.Module,\n head_in_features: Optional[List[str]] = None,\n *,\n pixel_mean,\n pixel_std,\n ):\n \"\"\"\n Args:\n backbone: backbone module\n head: head module\n head_in_features: backbone features to use in head. Default to all backbone features.\n pixel_mean (Tuple[float]):\n Values to be used for image normalization (BGR order).\n To train on images of different number of channels, set different mean & std.\n Default values are the mean pixel value from ImageNet: [103.53, 116.28, 123.675]\n pixel_std (Tuple[float]):\n When using pre-trained models in Detectron1 or any MSRA models,\n std has been absorbed into its conv1 weights, so the std needs to be set 1.\n Otherwise, you can use [57.375, 57.120, 58.395] (ImageNet std)\n \"\"\"\n super().__init__()\n\n self.backbone = backbone\n self.head = head\n if head_in_features is None:\n shapes = self.backbone.output_shape()\n self.head_in_features = sorted(shapes.keys(), key=lambda x: shapes[x].stride)\n else:\n self.head_in_features = head_in_features\n self.register_buffer(\"pixel_mean\", torch.tensor(pixel_mean).view(-1, 1, 1), False)\n self.register_buffer(\"pixel_std\", torch.tensor(pixel_std).view(-1, 1, 1), False)\n\n @property\n def device(self):\n return self.pixel_mean.device\n\n def _move_to_current_device(self, x):\n return move_device_like(x, self.pixel_mean)\n\n def forward(self, batched_inputs: List[Dict[str, Tensor]]):\n \"\"\"\n Args:\n batched_inputs: a list, batched outputs of :class:`DatasetMapper` .\n Each item in the list contains the inputs for one image.\n For now, each item in the list is a dict that contains:\n\n * image: Tensor, image in (C, H, W) format.\n * instances: Instances\n\n Other information that's included in the original dicts, such as:\n\n * \"height\", \"width\" (int): the output resolution of the model, used in inference.\n See :meth:`postprocess` for details.\n\n Returns:\n In training, dict[str, Tensor]: mapping from a named loss to a tensor storing the\n loss. Used during training only. In inference, the standard output format, described\n in :doc:`/tutorials/models`.\n \"\"\"\n images = self.preprocess_image(batched_inputs)\n features = self.backbone(images.tensor)\n features = [features[f] for f in self.head_in_features]\n predictions = self.head(features)\n\n if self.training:\n assert not torch.jit.is_scripting(), \"Not supported\"\n assert \"instances\" in batched_inputs[0], \"Instance annotations are missing in training!\"\n gt_instances = [x[\"instances\"].to(self.device) for x in batched_inputs]\n return self.forward_training(images, features, predictions, gt_instances)\n else:\n results = self.forward_inference(images, features, predictions)\n if torch.jit.is_scripting():\n return results\n\n processed_results = []\n for results_per_image, input_per_image, image_size in zip(\n results, batched_inputs, images.image_sizes\n ):\n height = input_per_image.get(\"height\", image_size[0])\n width = input_per_image.get(\"width\", image_size[1])\n r = detector_postprocess(results_per_image, height, width)\n processed_results.append({\"instances\": r})\n return processed_results\n\n def forward_training(self, images, features, predictions, gt_instances):\n raise NotImplementedError()\n\n def preprocess_image(self, batched_inputs: List[Dict[str, Tensor]]):\n \"\"\"\n Normalize, pad and batch the input images.\n \"\"\"\n images = [self._move_to_current_device(x[\"image\"]) for x in batched_inputs]\n images = [(x - self.pixel_mean) / self.pixel_std for x in images]\n images = ImageList.from_tensors(\n images,\n self.backbone.size_divisibility,\n padding_constraints=self.backbone.padding_constraints,\n )\n return images\n\n def _transpose_dense_predictions(\n self, predictions: List[List[Tensor]], dims_per_anchor: List[int]\n ) -> List[List[Tensor]]:\n \"\"\"\n Transpose the dense per-level predictions.\n\n Args:\n predictions: a list of outputs, each is a list of per-level\n predictions with shape (N, Ai x K, Hi, Wi), where N is the\n number of images, Ai is the number of anchors per location on\n level i, K is the dimension of predictions per anchor.\n dims_per_anchor: the value of K for each predictions. e.g. 4 for\n box prediction, #classes for classification prediction.\n\n Returns:\n List[List[Tensor]]: each prediction is transposed to (N, Hi x Wi x Ai, K).\n \"\"\"\n assert len(predictions) == len(dims_per_anchor)\n res: List[List[Tensor]] = []\n for pred, dim_per_anchor in zip(predictions, dims_per_anchor):\n pred = [permute_to_N_HWA_K(x, dim_per_anchor) for x in pred]\n res.append(pred)\n return res\n\n def _ema_update(self, name: str, value: float, initial_value: float, momentum: float = 0.9):\n \"\"\"\n Apply EMA update to `self.name` using `value`.\n\n This is mainly used for loss normalizer. In Detectron1, loss is normalized by number\n of foreground samples in the batch. When batch size is 1 per GPU, #foreground has a\n large variance and using it lead to lower performance. Therefore we maintain an EMA of\n #foreground to stabilize the normalizer.\n\n Args:\n name: name of the normalizer\n value: the new value to update\n initial_value: the initial value to start with\n momentum: momentum of EMA\n\n Returns:\n float: the updated EMA value\n \"\"\"\n if hasattr(self, name):\n old = getattr(self, name)\n else:\n old = initial_value\n new = old * momentum + value * (1 - momentum)\n setattr(self, name, new)\n return new\n\n def _decode_per_level_predictions(\n self,\n anchors: Boxes,\n pred_scores: Tensor,\n pred_deltas: Tensor,\n score_thresh: float,\n topk_candidates: int,\n image_size: Tuple[int, int],\n ) -> Instances:\n \"\"\"\n Decode boxes and classification predictions of one featuer level, by\n the following steps:\n 1. filter the predictions based on score threshold and top K scores.\n 2. transform the box regression outputs\n 3. return the predicted scores, classes and boxes\n\n Args:\n anchors: Boxes, anchor for this feature level\n pred_scores: HxWxA,K\n pred_deltas: HxWxA,4\n\n Returns:\n Instances: with field \"scores\", \"pred_boxes\", \"pred_classes\".\n \"\"\"\n # Apply two filtering to make NMS faster.\n # 1. Keep boxes with confidence score higher than threshold\n keep_idxs = pred_scores > score_thresh\n pred_scores = pred_scores[keep_idxs]\n topk_idxs = torch.nonzero(keep_idxs) # Kx2\n\n # 2. Keep top k top scoring boxes only\n topk_idxs_size = topk_idxs.shape[0]\n if isinstance(topk_idxs_size, Tensor):\n # It's a tensor in tracing\n num_topk = torch.clamp(topk_idxs_size, max=topk_candidates)\n else:\n num_topk = min(topk_idxs_size, topk_candidates)\n pred_scores, idxs = pred_scores.topk(num_topk)\n topk_idxs = topk_idxs[idxs]\n\n anchor_idxs, classes_idxs = topk_idxs.unbind(dim=1)\n\n pred_boxes = self.box2box_transform.apply_deltas(\n pred_deltas[anchor_idxs], anchors.tensor[anchor_idxs]\n )\n return Instances(\n image_size, pred_boxes=Boxes(pred_boxes), scores=pred_scores, pred_classes=classes_idxs\n )\n\n def _decode_multi_level_predictions(\n self,\n anchors: List[Boxes],\n pred_scores: List[Tensor],\n pred_deltas: List[Tensor],\n score_thresh: float,\n topk_candidates: int,\n image_size: Tuple[int, int],\n ) -> Instances:\n \"\"\"\n Run `_decode_per_level_predictions` for all feature levels and concat the results.\n \"\"\"\n predictions = [\n self._decode_per_level_predictions(\n anchors_i,\n box_cls_i,\n box_reg_i,\n score_thresh,\n topk_candidates,\n image_size,\n )\n # Iterate over every feature level\n for box_cls_i, box_reg_i, anchors_i in zip(pred_scores, pred_deltas, anchors)\n ]\n return predictions[0].cat(predictions) # 'Instances.cat' is not scriptale but this is\n\n def visualize_training(self, batched_inputs, results):\n \"\"\"\n A function used to visualize ground truth images and final network predictions.\n It shows ground truth bounding boxes on the original image and up to 20\n predicted object bounding boxes on the original image.\n\n Args:\n batched_inputs (list): a list that contains input to the model.\n results (List[Instances]): a list of #images elements returned by forward_inference().\n \"\"\"\n from detectron2.utils.visualizer import Visualizer\n\n assert len(batched_inputs) == len(\n results\n ), \"Cannot visualize inputs and results of different sizes\"\n storage = get_event_storage()\n max_boxes = 20\n\n image_index = 0 # only visualize a single image\n img = batched_inputs[image_index][\"image\"]\n img = convert_image_to_rgb(img.permute(1, 2, 0), self.input_format)\n v_gt = Visualizer(img, None)\n v_gt = v_gt.overlay_instances(boxes=batched_inputs[image_index][\"instances\"].gt_boxes)\n anno_img = v_gt.get_image()\n processed_results = detector_postprocess(results[image_index], img.shape[0], img.shape[1])\n predicted_boxes = processed_results.pred_boxes.tensor.detach().cpu().numpy()\n\n v_pred = Visualizer(img, None)\n v_pred = v_pred.overlay_instances(boxes=predicted_boxes[0:max_boxes])\n prop_img = v_pred.get_image()\n vis_img = np.vstack((anno_img, prop_img))\n vis_img = vis_img.transpose(2, 0, 1)\n vis_name = f\"Top: GT bounding boxes; Bottom: {max_boxes} Highest Scoring Results\"\n storage.put_image(vis_name, vis_img)" }, { "identifier": "permute_to_N_HWA_K", "path": "nativedancer/third_part/detectron2/modeling/meta_arch/dense_detector.py", "snippet": "def permute_to_N_HWA_K(tensor, K: int):\n \"\"\"\n Transpose/reshape a tensor from (N, (Ai x K), H, W) to (N, (HxWxAi), K)\n \"\"\"\n assert tensor.dim() == 4, tensor.shape\n N, _, H, W = tensor.shape\n tensor = tensor.view(N, -1, K, H, W)\n tensor = tensor.permute(0, 3, 4, 1, 2)\n tensor = tensor.reshape(N, -1, K) # Size=(N,HWA,K)\n return tensor" } ]
import logging import math import torch from typing import List, Tuple from fvcore.nn import sigmoid_focal_loss_jit from torch import Tensor, nn from torch.nn import functional as F from ...config import configurable from ...layers import CycleBatchNormList, ShapeSpec, batched_nms, cat, get_norm from ...structures import Boxes, ImageList, Instances, pairwise_iou from ...utils.events import get_event_storage from ..anchor_generator import build_anchor_generator from ..backbone import Backbone, build_backbone from ..box_regression import Box2BoxTransform, _dense_box_regression_loss from ..matcher import Matcher from .build import META_ARCH_REGISTRY from .dense_detector import DenseDetector, permute_to_N_HWA_K # noqa
17,569
match_quality_matrix = pairwise_iou(gt_per_image.gt_boxes, anchors) matched_idxs, anchor_labels = self.anchor_matcher(match_quality_matrix) del match_quality_matrix if len(gt_per_image) > 0: matched_gt_boxes_i = gt_per_image.gt_boxes.tensor[matched_idxs] gt_labels_i = gt_per_image.gt_classes[matched_idxs] # Anchors with label 0 are treated as background. gt_labels_i[anchor_labels == 0] = self.num_classes # Anchors with label -1 are ignored. gt_labels_i[anchor_labels == -1] = -1 else: matched_gt_boxes_i = torch.zeros_like(anchors.tensor) gt_labels_i = torch.zeros_like(matched_idxs) + self.num_classes gt_labels.append(gt_labels_i) matched_gt_boxes.append(matched_gt_boxes_i) return gt_labels, matched_gt_boxes def forward_inference( self, images: ImageList, features: List[Tensor], predictions: List[List[Tensor]] ): pred_logits, pred_anchor_deltas = self._transpose_dense_predictions( predictions, [self.num_classes, 4] ) anchors = self.anchor_generator(features) results: List[Instances] = [] for img_idx, image_size in enumerate(images.image_sizes): scores_per_image = [x[img_idx].sigmoid_() for x in pred_logits] deltas_per_image = [x[img_idx] for x in pred_anchor_deltas] results_per_image = self.inference_single_image( anchors, scores_per_image, deltas_per_image, image_size ) results.append(results_per_image) return results def inference_single_image( self, anchors: List[Boxes], box_cls: List[Tensor], box_delta: List[Tensor], image_size: Tuple[int, int], ): """ Single-image inference. Return bounding-box detection results by thresholding on scores and applying non-maximum suppression (NMS). Arguments: anchors (list[Boxes]): list of #feature levels. Each entry contains a Boxes object, which contains all the anchors in that feature level. box_cls (list[Tensor]): list of #feature levels. Each entry contains tensor of size (H x W x A, K) box_delta (list[Tensor]): Same shape as 'box_cls' except that K becomes 4. image_size (tuple(H, W)): a tuple of the image height and width. Returns: Same as `inference`, but for only one image. """ pred = self._decode_multi_level_predictions( anchors, box_cls, box_delta, self.test_score_thresh, self.test_topk_candidates, image_size, ) keep = batched_nms( # per-class NMS pred.pred_boxes.tensor, pred.scores, pred.pred_classes, self.test_nms_thresh ) return pred[keep[: self.max_detections_per_image]] class RetinaNetHead(nn.Module): """ The head used in RetinaNet for object classification and box regression. It has two subnets for the two tasks, with a common structure but separate parameters. """ @configurable def __init__( self, *, input_shape: List[ShapeSpec], num_classes, num_anchors, conv_dims: List[int], norm="", prior_prob=0.01, ): """ NOTE: this interface is experimental. Args: input_shape (List[ShapeSpec]): input shape num_classes (int): number of classes. Used to label background proposals. num_anchors (int): number of generated anchors conv_dims (List[int]): dimensions for each convolution layer norm (str or callable): Normalization for conv layers except for the two output layers. See :func:`detectron2.layers.get_norm` for supported types. prior_prob (float): Prior weight for computing bias """ super().__init__() self._num_features = len(input_shape) if norm == "BN" or norm == "SyncBN": logger.info( f"Using domain-specific {norm} in RetinaNetHead with len={self._num_features}." ) bn_class = nn.BatchNorm2d if norm == "BN" else nn.SyncBatchNorm def norm(c): return CycleBatchNormList( length=self._num_features, bn_class=bn_class, num_features=c ) else:
# Copyright (c) Facebook, Inc. and its affiliates. __all__ = ["RetinaNet"] logger = logging.getLogger(__name__) @META_ARCH_REGISTRY.register() class RetinaNet(DenseDetector): """ Implement RetinaNet in :paper:`RetinaNet`. """ @configurable def __init__( self, *, backbone: Backbone, head: nn.Module, head_in_features, anchor_generator, box2box_transform, anchor_matcher, num_classes, focal_loss_alpha=0.25, focal_loss_gamma=2.0, smooth_l1_beta=0.0, box_reg_loss_type="smooth_l1", test_score_thresh=0.05, test_topk_candidates=1000, test_nms_thresh=0.5, max_detections_per_image=100, pixel_mean, pixel_std, vis_period=0, input_format="BGR", ): """ NOTE: this interface is experimental. Args: backbone: a backbone module, must follow detectron2's backbone interface head (nn.Module): a module that predicts logits and regression deltas for each level from a list of per-level features head_in_features (Tuple[str]): Names of the input feature maps to be used in head anchor_generator (nn.Module): a module that creates anchors from a list of features. Usually an instance of :class:`AnchorGenerator` box2box_transform (Box2BoxTransform): defines the transform from anchors boxes to instance boxes anchor_matcher (Matcher): label the anchors by matching them with ground truth. num_classes (int): number of classes. Used to label background proposals. # Loss parameters: focal_loss_alpha (float): focal_loss_alpha focal_loss_gamma (float): focal_loss_gamma smooth_l1_beta (float): smooth_l1_beta box_reg_loss_type (str): Options are "smooth_l1", "giou", "diou", "ciou" # Inference parameters: test_score_thresh (float): Inference cls score threshold, only anchors with score > INFERENCE_TH are considered for inference (to improve speed) test_topk_candidates (int): Select topk candidates before NMS test_nms_thresh (float): Overlap threshold used for non-maximum suppression (suppress boxes with IoU >= this threshold) max_detections_per_image (int): Maximum number of detections to return per image during inference (100 is based on the limit established for the COCO dataset). pixel_mean, pixel_std: see :class:`DenseDetector`. """ super().__init__( backbone, head, head_in_features, pixel_mean=pixel_mean, pixel_std=pixel_std ) self.num_classes = num_classes # Anchors self.anchor_generator = anchor_generator self.box2box_transform = box2box_transform self.anchor_matcher = anchor_matcher # Loss parameters: self.focal_loss_alpha = focal_loss_alpha self.focal_loss_gamma = focal_loss_gamma self.smooth_l1_beta = smooth_l1_beta self.box_reg_loss_type = box_reg_loss_type # Inference parameters: self.test_score_thresh = test_score_thresh self.test_topk_candidates = test_topk_candidates self.test_nms_thresh = test_nms_thresh self.max_detections_per_image = max_detections_per_image # Vis parameters self.vis_period = vis_period self.input_format = input_format @classmethod def from_config(cls, cfg): backbone = build_backbone(cfg) backbone_shape = backbone.output_shape() feature_shapes = [backbone_shape[f] for f in cfg.MODEL.RETINANET.IN_FEATURES] head = RetinaNetHead(cfg, feature_shapes) anchor_generator = build_anchor_generator(cfg, feature_shapes) return { "backbone": backbone, "head": head, "anchor_generator": anchor_generator, "box2box_transform": Box2BoxTransform(weights=cfg.MODEL.RETINANET.BBOX_REG_WEIGHTS), "anchor_matcher": Matcher( cfg.MODEL.RETINANET.IOU_THRESHOLDS, cfg.MODEL.RETINANET.IOU_LABELS, allow_low_quality_matches=True, ), "pixel_mean": cfg.MODEL.PIXEL_MEAN, "pixel_std": cfg.MODEL.PIXEL_STD, "num_classes": cfg.MODEL.RETINANET.NUM_CLASSES, "head_in_features": cfg.MODEL.RETINANET.IN_FEATURES, # Loss parameters: "focal_loss_alpha": cfg.MODEL.RETINANET.FOCAL_LOSS_ALPHA, "focal_loss_gamma": cfg.MODEL.RETINANET.FOCAL_LOSS_GAMMA, "smooth_l1_beta": cfg.MODEL.RETINANET.SMOOTH_L1_LOSS_BETA, "box_reg_loss_type": cfg.MODEL.RETINANET.BBOX_REG_LOSS_TYPE, # Inference parameters: "test_score_thresh": cfg.MODEL.RETINANET.SCORE_THRESH_TEST, "test_topk_candidates": cfg.MODEL.RETINANET.TOPK_CANDIDATES_TEST, "test_nms_thresh": cfg.MODEL.RETINANET.NMS_THRESH_TEST, "max_detections_per_image": cfg.TEST.DETECTIONS_PER_IMAGE, # Vis parameters "vis_period": cfg.VIS_PERIOD, "input_format": cfg.INPUT.FORMAT, } def forward_training(self, images, features, predictions, gt_instances): # Transpose the Hi*Wi*A dimension to the middle: pred_logits, pred_anchor_deltas = self._transpose_dense_predictions( predictions, [self.num_classes, 4] ) anchors = self.anchor_generator(features) gt_labels, gt_boxes = self.label_anchors(anchors, gt_instances) return self.losses(anchors, pred_logits, gt_labels, pred_anchor_deltas, gt_boxes) def losses(self, anchors, pred_logits, gt_labels, pred_anchor_deltas, gt_boxes): """ Args: anchors (list[Boxes]): a list of #feature level Boxes gt_labels, gt_boxes: see output of :meth:`RetinaNet.label_anchors`. Their shapes are (N, R) and (N, R, 4), respectively, where R is the total number of anchors across levels, i.e. sum(Hi x Wi x Ai) pred_logits, pred_anchor_deltas: both are list[Tensor]. Each element in the list corresponds to one level and has shape (N, Hi * Wi * Ai, K or 4). Where K is the number of classes used in `pred_logits`. Returns: dict[str, Tensor]: mapping from a named loss to a scalar tensor storing the loss. Used during training only. The dict keys are: "loss_cls" and "loss_box_reg" """ num_images = len(gt_labels) gt_labels = torch.stack(gt_labels) # (N, R) valid_mask = gt_labels >= 0 pos_mask = (gt_labels >= 0) & (gt_labels != self.num_classes) num_pos_anchors = pos_mask.sum().item() get_event_storage().put_scalar("num_pos_anchors", num_pos_anchors / num_images) normalizer = self._ema_update("loss_normalizer", max(num_pos_anchors, 1), 100) # classification and regression loss gt_labels_target = F.one_hot(gt_labels[valid_mask], num_classes=self.num_classes + 1)[ :, :-1 ] # no loss for the last (background) class loss_cls = sigmoid_focal_loss_jit( cat(pred_logits, dim=1)[valid_mask], gt_labels_target.to(pred_logits[0].dtype), alpha=self.focal_loss_alpha, gamma=self.focal_loss_gamma, reduction="sum", ) loss_box_reg = _dense_box_regression_loss( anchors, self.box2box_transform, pred_anchor_deltas, gt_boxes, pos_mask, box_reg_loss_type=self.box_reg_loss_type, smooth_l1_beta=self.smooth_l1_beta, ) return { "loss_cls": loss_cls / normalizer, "loss_box_reg": loss_box_reg / normalizer, } @torch.no_grad() def label_anchors(self, anchors, gt_instances): """ Args: anchors (list[Boxes]): A list of #feature level Boxes. The Boxes contains anchors of this image on the specific feature level. gt_instances (list[Instances]): a list of N `Instances`s. The i-th `Instances` contains the ground-truth per-instance annotations for the i-th input image. Returns: list[Tensor]: List of #img tensors. i-th element is a vector of labels whose length is the total number of anchors across all feature maps (sum(Hi * Wi * A)). Label values are in {-1, 0, ..., K}, with -1 means ignore, and K means background. list[Tensor]: i-th element is a Rx4 tensor, where R is the total number of anchors across feature maps. The values are the matched gt boxes for each anchor. Values are undefined for those anchors not labeled as foreground. """ anchors = Boxes.cat(anchors) # Rx4 gt_labels = [] matched_gt_boxes = [] for gt_per_image in gt_instances: match_quality_matrix = pairwise_iou(gt_per_image.gt_boxes, anchors) matched_idxs, anchor_labels = self.anchor_matcher(match_quality_matrix) del match_quality_matrix if len(gt_per_image) > 0: matched_gt_boxes_i = gt_per_image.gt_boxes.tensor[matched_idxs] gt_labels_i = gt_per_image.gt_classes[matched_idxs] # Anchors with label 0 are treated as background. gt_labels_i[anchor_labels == 0] = self.num_classes # Anchors with label -1 are ignored. gt_labels_i[anchor_labels == -1] = -1 else: matched_gt_boxes_i = torch.zeros_like(anchors.tensor) gt_labels_i = torch.zeros_like(matched_idxs) + self.num_classes gt_labels.append(gt_labels_i) matched_gt_boxes.append(matched_gt_boxes_i) return gt_labels, matched_gt_boxes def forward_inference( self, images: ImageList, features: List[Tensor], predictions: List[List[Tensor]] ): pred_logits, pred_anchor_deltas = self._transpose_dense_predictions( predictions, [self.num_classes, 4] ) anchors = self.anchor_generator(features) results: List[Instances] = [] for img_idx, image_size in enumerate(images.image_sizes): scores_per_image = [x[img_idx].sigmoid_() for x in pred_logits] deltas_per_image = [x[img_idx] for x in pred_anchor_deltas] results_per_image = self.inference_single_image( anchors, scores_per_image, deltas_per_image, image_size ) results.append(results_per_image) return results def inference_single_image( self, anchors: List[Boxes], box_cls: List[Tensor], box_delta: List[Tensor], image_size: Tuple[int, int], ): """ Single-image inference. Return bounding-box detection results by thresholding on scores and applying non-maximum suppression (NMS). Arguments: anchors (list[Boxes]): list of #feature levels. Each entry contains a Boxes object, which contains all the anchors in that feature level. box_cls (list[Tensor]): list of #feature levels. Each entry contains tensor of size (H x W x A, K) box_delta (list[Tensor]): Same shape as 'box_cls' except that K becomes 4. image_size (tuple(H, W)): a tuple of the image height and width. Returns: Same as `inference`, but for only one image. """ pred = self._decode_multi_level_predictions( anchors, box_cls, box_delta, self.test_score_thresh, self.test_topk_candidates, image_size, ) keep = batched_nms( # per-class NMS pred.pred_boxes.tensor, pred.scores, pred.pred_classes, self.test_nms_thresh ) return pred[keep[: self.max_detections_per_image]] class RetinaNetHead(nn.Module): """ The head used in RetinaNet for object classification and box regression. It has two subnets for the two tasks, with a common structure but separate parameters. """ @configurable def __init__( self, *, input_shape: List[ShapeSpec], num_classes, num_anchors, conv_dims: List[int], norm="", prior_prob=0.01, ): """ NOTE: this interface is experimental. Args: input_shape (List[ShapeSpec]): input shape num_classes (int): number of classes. Used to label background proposals. num_anchors (int): number of generated anchors conv_dims (List[int]): dimensions for each convolution layer norm (str or callable): Normalization for conv layers except for the two output layers. See :func:`detectron2.layers.get_norm` for supported types. prior_prob (float): Prior weight for computing bias """ super().__init__() self._num_features = len(input_shape) if norm == "BN" or norm == "SyncBN": logger.info( f"Using domain-specific {norm} in RetinaNetHead with len={self._num_features}." ) bn_class = nn.BatchNorm2d if norm == "BN" else nn.SyncBatchNorm def norm(c): return CycleBatchNormList( length=self._num_features, bn_class=bn_class, num_features=c ) else:
norm_name = str(type(get_norm(norm, 32)))
1
2023-12-10 20:14:00+00:00
24k
mkang315/ASF-YOLO
segment/val.py
[ { "identifier": "DetectMultiBackend", "path": "models/common.py", "snippet": "class DetectMultiBackend(nn.Module):\n # YOLOv5 MultiBackend class for python inference on various backends\n def __init__(self, weights='yolov5s.pt', device=torch.device('cpu'), dnn=False, data=None, fp16=False, fuse=True):\n # Usage:\n # PyTorch: weights = *.pt\n # TorchScript: *.torchscript\n # ONNX Runtime: *.onnx\n # ONNX OpenCV DNN: *.onnx --dnn\n # OpenVINO: *_openvino_model\n # CoreML: *.mlmodel\n # TensorRT: *.engine\n # TensorFlow SavedModel: *_saved_model\n # TensorFlow GraphDef: *.pb\n # TensorFlow Lite: *.tflite\n # TensorFlow Edge TPU: *_edgetpu.tflite\n # PaddlePaddle: *_paddle_model\n from models.experimental import attempt_download, attempt_load # scoped to avoid circular import\n\n super().__init__()\n w = str(weights[0] if isinstance(weights, list) else weights)\n pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle, triton = self._model_type(w)\n fp16 &= pt or jit or onnx or engine # FP16\n nhwc = coreml or saved_model or pb or tflite or edgetpu # BHWC formats (vs torch BCWH)\n stride = 32 # default stride\n cuda = torch.cuda.is_available() and device.type != 'cpu' # use CUDA\n if not (pt or triton):\n w = attempt_download(w) # download if not local\n\n if pt: # PyTorch\n model = attempt_load(weights if isinstance(weights, list) else w, device=device, inplace=True, fuse=fuse)\n stride = max(int(model.stride.max()), 32) # model stride\n names = model.module.names if hasattr(model, 'module') else model.names # get class names\n model.half() if fp16 else model.float()\n self.model = model # explicitly assign for to(), cpu(), cuda(), half()\n elif jit: # TorchScript\n LOGGER.info(f'Loading {w} for TorchScript inference...')\n extra_files = {'config.txt': ''} # model metadata\n model = torch.jit.load(w, _extra_files=extra_files, map_location=device)\n model.half() if fp16 else model.float()\n if extra_files['config.txt']: # load metadata dict\n d = json.loads(extra_files['config.txt'],\n object_hook=lambda d: {int(k) if k.isdigit() else k: v\n for k, v in d.items()})\n stride, names = int(d['stride']), d['names']\n elif dnn: # ONNX OpenCV DNN\n LOGGER.info(f'Loading {w} for ONNX OpenCV DNN inference...')\n check_requirements('opencv-python>=4.5.4')\n net = cv2.dnn.readNetFromONNX(w)\n elif onnx: # ONNX Runtime\n LOGGER.info(f'Loading {w} for ONNX Runtime inference...')\n check_requirements(('onnx', 'onnxruntime-gpu' if cuda else 'onnxruntime'))\n import onnxruntime\n providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if cuda else ['CPUExecutionProvider']\n session = onnxruntime.InferenceSession(w, providers=providers)\n output_names = [x.name for x in session.get_outputs()]\n meta = session.get_modelmeta().custom_metadata_map # metadata\n if 'stride' in meta:\n stride, names = int(meta['stride']), eval(meta['names'])\n elif xml: # OpenVINO\n LOGGER.info(f'Loading {w} for OpenVINO inference...')\n check_requirements('openvino') # requires openvino-dev: https://pypi.org/project/openvino-dev/\n from openvino.runtime import Core, Layout, get_batch\n ie = Core()\n if not Path(w).is_file(): # if not *.xml\n w = next(Path(w).glob('*.xml')) # get *.xml file from *_openvino_model dir\n network = ie.read_model(model=w, weights=Path(w).with_suffix('.bin'))\n if network.get_parameters()[0].get_layout().empty:\n network.get_parameters()[0].set_layout(Layout(\"NCHW\"))\n batch_dim = get_batch(network)\n if batch_dim.is_static:\n batch_size = batch_dim.get_length()\n executable_network = ie.compile_model(network, device_name=\"CPU\") # device_name=\"MYRIAD\" for Intel NCS2\n stride, names = self._load_metadata(Path(w).with_suffix('.yaml')) # load metadata\n elif engine: # TensorRT\n LOGGER.info(f'Loading {w} for TensorRT inference...')\n import tensorrt as trt # https://developer.nvidia.com/nvidia-tensorrt-download\n check_version(trt.__version__, '7.0.0', hard=True) # require tensorrt>=7.0.0\n if device.type == 'cpu':\n device = torch.device('cuda:0')\n Binding = namedtuple('Binding', ('name', 'dtype', 'shape', 'data', 'ptr'))\n logger = trt.Logger(trt.Logger.INFO)\n with open(w, 'rb') as f, trt.Runtime(logger) as runtime:\n model = runtime.deserialize_cuda_engine(f.read())\n context = model.create_execution_context()\n bindings = OrderedDict()\n output_names = []\n fp16 = False # default updated below\n dynamic = False\n for i in range(model.num_bindings):\n name = model.get_binding_name(i)\n dtype = trt.nptype(model.get_binding_dtype(i))\n if model.binding_is_input(i):\n if -1 in tuple(model.get_binding_shape(i)): # dynamic\n dynamic = True\n context.set_binding_shape(i, tuple(model.get_profile_shape(0, i)[2]))\n if dtype == np.float16:\n fp16 = True\n else: # output\n output_names.append(name)\n shape = tuple(context.get_binding_shape(i))\n im = torch.from_numpy(np.empty(shape, dtype=dtype)).to(device)\n bindings[name] = Binding(name, dtype, shape, im, int(im.data_ptr()))\n binding_addrs = OrderedDict((n, d.ptr) for n, d in bindings.items())\n batch_size = bindings['images'].shape[0] # if dynamic, this is instead max batch size\n elif coreml: # CoreML\n LOGGER.info(f'Loading {w} for CoreML inference...')\n import coremltools as ct\n model = ct.models.MLModel(w)\n elif saved_model: # TF SavedModel\n LOGGER.info(f'Loading {w} for TensorFlow SavedModel inference...')\n import tensorflow as tf\n keras = False # assume TF1 saved_model\n model = tf.keras.models.load_model(w) if keras else tf.saved_model.load(w)\n elif pb: # GraphDef https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt\n LOGGER.info(f'Loading {w} for TensorFlow GraphDef inference...')\n import tensorflow as tf\n\n def wrap_frozen_graph(gd, inputs, outputs):\n x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=\"\"), []) # wrapped\n ge = x.graph.as_graph_element\n return x.prune(tf.nest.map_structure(ge, inputs), tf.nest.map_structure(ge, outputs))\n\n def gd_outputs(gd):\n name_list, input_list = [], []\n for node in gd.node: # tensorflow.core.framework.node_def_pb2.NodeDef\n name_list.append(node.name)\n input_list.extend(node.input)\n return sorted(f'{x}:0' for x in list(set(name_list) - set(input_list)) if not x.startswith('NoOp'))\n\n gd = tf.Graph().as_graph_def() # TF GraphDef\n with open(w, 'rb') as f:\n gd.ParseFromString(f.read())\n frozen_func = wrap_frozen_graph(gd, inputs=\"x:0\", outputs=gd_outputs(gd))\n elif tflite or edgetpu: # https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python\n try: # https://coral.ai/docs/edgetpu/tflite-python/#update-existing-tf-lite-code-for-the-edge-tpu\n from tflite_runtime.interpreter import Interpreter, load_delegate\n except ImportError:\n import tensorflow as tf\n Interpreter, load_delegate = tf.lite.Interpreter, tf.lite.experimental.load_delegate,\n if edgetpu: # TF Edge TPU https://coral.ai/software/#edgetpu-runtime\n LOGGER.info(f'Loading {w} for TensorFlow Lite Edge TPU inference...')\n delegate = {\n 'Linux': 'libedgetpu.so.1',\n 'Darwin': 'libedgetpu.1.dylib',\n 'Windows': 'edgetpu.dll'}[platform.system()]\n interpreter = Interpreter(model_path=w, experimental_delegates=[load_delegate(delegate)])\n else: # TFLite\n LOGGER.info(f'Loading {w} for TensorFlow Lite inference...')\n interpreter = Interpreter(model_path=w) # load TFLite model\n interpreter.allocate_tensors() # allocate\n input_details = interpreter.get_input_details() # inputs\n output_details = interpreter.get_output_details() # outputs\n # load metadata\n with contextlib.suppress(zipfile.BadZipFile):\n with zipfile.ZipFile(w, \"r\") as model:\n meta_file = model.namelist()[0]\n meta = ast.literal_eval(model.read(meta_file).decode(\"utf-8\"))\n stride, names = int(meta['stride']), meta['names']\n elif tfjs: # TF.js\n raise NotImplementedError('ERROR: YOLOv5 TF.js inference is not supported')\n elif paddle: # PaddlePaddle\n LOGGER.info(f'Loading {w} for PaddlePaddle inference...')\n check_requirements('paddlepaddle-gpu' if cuda else 'paddlepaddle')\n import paddle.inference as pdi\n if not Path(w).is_file(): # if not *.pdmodel\n w = next(Path(w).rglob('*.pdmodel')) # get *.pdmodel file from *_paddle_model dir\n weights = Path(w).with_suffix('.pdiparams')\n config = pdi.Config(str(w), str(weights))\n if cuda:\n config.enable_use_gpu(memory_pool_init_size_mb=2048, device_id=0)\n predictor = pdi.create_predictor(config)\n input_handle = predictor.get_input_handle(predictor.get_input_names()[0])\n output_names = predictor.get_output_names()\n elif triton: # NVIDIA Triton Inference Server\n LOGGER.info(f'Using {w} as Triton Inference Server...')\n check_requirements('tritonclient[all]')\n from utils.triton import TritonRemoteModel\n model = TritonRemoteModel(url=w)\n nhwc = model.runtime.startswith(\"tensorflow\")\n else:\n raise NotImplementedError(f'ERROR: {w} is not a supported format')\n\n # class names\n if 'names' not in locals():\n names = yaml_load(data)['names'] if data else {i: f'class{i}' for i in range(999)}\n if names[0] == 'n01440764' and len(names) == 1000: # ImageNet\n names = yaml_load(ROOT / 'data/ImageNet.yaml')['names'] # human-readable names\n\n self.__dict__.update(locals()) # assign all variables to self\n\n def forward(self, im, augment=False, visualize=False):\n # YOLOv5 MultiBackend inference\n b, ch, h, w = im.shape # batch, channel, height, width\n if self.fp16 and im.dtype != torch.float16:\n im = im.half() # to FP16\n if self.nhwc:\n im = im.permute(0, 2, 3, 1) # torch BCHW to numpy BHWC shape(1,320,192,3)\n\n if self.pt: # PyTorch\n y = self.model(im, augment=augment, visualize=visualize) if augment or visualize else self.model(im)\n elif self.jit: # TorchScript\n y = self.model(im)\n elif self.dnn: # ONNX OpenCV DNN\n im = im.cpu().numpy() # torch to numpy\n self.net.setInput(im)\n y = self.net.forward()\n elif self.onnx: # ONNX Runtime\n im = im.cpu().numpy() # torch to numpy\n y = self.session.run(self.output_names, {self.session.get_inputs()[0].name: im})\n elif self.xml: # OpenVINO\n im = im.cpu().numpy() # FP32\n y = list(self.executable_network([im]).values())\n elif self.engine: # TensorRT\n if self.dynamic and im.shape != self.bindings['images'].shape:\n i = self.model.get_binding_index('images')\n self.context.set_binding_shape(i, im.shape) # reshape if dynamic\n self.bindings['images'] = self.bindings['images']._replace(shape=im.shape)\n for name in self.output_names:\n i = self.model.get_binding_index(name)\n self.bindings[name].data.resize_(tuple(self.context.get_binding_shape(i)))\n s = self.bindings['images'].shape\n assert im.shape == s, f\"input size {im.shape} {'>' if self.dynamic else 'not equal to'} max model size {s}\"\n self.binding_addrs['images'] = int(im.data_ptr())\n self.context.execute_v2(list(self.binding_addrs.values()))\n y = [self.bindings[x].data for x in sorted(self.output_names)]\n elif self.coreml: # CoreML\n im = im.cpu().numpy()\n im = Image.fromarray((im[0] * 255).astype('uint8'))\n # im = im.resize((192, 320), Image.ANTIALIAS)\n y = self.model.predict({'image': im}) # coordinates are xywh normalized\n if 'confidence' in y:\n box = xywh2xyxy(y['coordinates'] * [[w, h, w, h]]) # xyxy pixels\n conf, cls = y['confidence'].max(1), y['confidence'].argmax(1).astype(np.float)\n y = np.concatenate((box, conf.reshape(-1, 1), cls.reshape(-1, 1)), 1)\n else:\n y = list(reversed(y.values())) # reversed for segmentation models (pred, proto)\n elif self.paddle: # PaddlePaddle\n im = im.cpu().numpy().astype(np.float32)\n self.input_handle.copy_from_cpu(im)\n self.predictor.run()\n y = [self.predictor.get_output_handle(x).copy_to_cpu() for x in self.output_names]\n elif self.triton: # NVIDIA Triton Inference Server\n y = self.model(im)\n else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU)\n im = im.cpu().numpy()\n if self.saved_model: # SavedModel\n y = self.model(im, training=False) if self.keras else self.model(im)\n elif self.pb: # GraphDef\n y = self.frozen_func(x=self.tf.constant(im))\n else: # Lite or Edge TPU\n input = self.input_details[0]\n int8 = input['dtype'] == np.uint8 # is TFLite quantized uint8 model\n if int8:\n scale, zero_point = input['quantization']\n im = (im / scale + zero_point).astype(np.uint8) # de-scale\n self.interpreter.set_tensor(input['index'], im)\n self.interpreter.invoke()\n y = []\n for output in self.output_details:\n x = self.interpreter.get_tensor(output['index'])\n if int8:\n scale, zero_point = output['quantization']\n x = (x.astype(np.float32) - zero_point) * scale # re-scale\n y.append(x)\n y = [x if isinstance(x, np.ndarray) else x.numpy() for x in y]\n y[0][..., :4] *= [w, h, w, h] # xywh normalized to pixels\n\n if isinstance(y, (list, tuple)):\n return self.from_numpy(y[0]) if len(y) == 1 else [self.from_numpy(x) for x in y]\n else:\n return self.from_numpy(y)\n\n def from_numpy(self, x):\n return torch.from_numpy(x).to(self.device) if isinstance(x, np.ndarray) else x\n\n def warmup(self, imgsz=(1, 3, 640, 640)):\n # Warmup model by running inference once\n warmup_types = self.pt, self.jit, self.onnx, self.engine, self.saved_model, self.pb, self.triton\n if any(warmup_types) and (self.device.type != 'cpu' or self.triton):\n im = torch.empty(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device) # input\n for _ in range(2 if self.jit else 1): #\n self.forward(im) # warmup\n\n @staticmethod\n def _model_type(p='path/to/model.pt'):\n # Return model type from model path, i.e. path='path/to/model.onnx' -> type=onnx\n # types = [pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle]\n from export import export_formats\n from utils.downloads import is_url\n sf = list(export_formats().Suffix) # export suffixes\n if not is_url(p, check=False):\n check_suffix(p, sf) # checks\n url = urlparse(p) # if url may be Triton inference server\n types = [s in Path(p).name for s in sf]\n types[8] &= not types[9] # tflite &= not edgetpu\n triton = not any(types) and all([any(s in url.scheme for s in [\"http\", \"grpc\"]), url.netloc])\n return types + [triton]\n\n @staticmethod\n def _load_metadata(f=Path('path/to/meta.yaml')):\n # Load metadata from meta.yaml if it exists\n if f.exists():\n d = yaml_load(f)\n return d['stride'], d['names'] # assign stride, names\n return None, None" }, { "identifier": "SegmentationModel", "path": "models/yolo.py", "snippet": "class SegmentationModel(DetectionModel):\n # YOLOv5 segmentation model\n def __init__(self, cfg='yolov5s-seg.yaml', ch=3, nc=None, anchors=None):\n super().__init__(cfg, ch, nc, anchors)" }, { "identifier": "Callbacks", "path": "utils/callbacks.py", "snippet": "class Callbacks:\n \"\"\"\"\n Handles all registered callbacks for YOLOv5 Hooks\n \"\"\"\n\n def __init__(self):\n # Define the available callbacks\n self._callbacks = {\n 'on_pretrain_routine_start': [],\n 'on_pretrain_routine_end': [],\n 'on_train_start': [],\n 'on_train_epoch_start': [],\n 'on_train_batch_start': [],\n 'optimizer_step': [],\n 'on_before_zero_grad': [],\n 'on_train_batch_end': [],\n 'on_train_epoch_end': [],\n 'on_val_start': [],\n 'on_val_batch_start': [],\n 'on_val_image_end': [],\n 'on_val_batch_end': [],\n 'on_val_end': [],\n 'on_fit_epoch_end': [], # fit = train + val\n 'on_model_save': [],\n 'on_train_end': [],\n 'on_params_update': [],\n 'teardown': [],}\n self.stop_training = False # set True to interrupt training\n\n def register_action(self, hook, name='', callback=None):\n \"\"\"\n Register a new action to a callback hook\n\n Args:\n hook: The callback hook name to register the action to\n name: The name of the action for later reference\n callback: The callback to fire\n \"\"\"\n assert hook in self._callbacks, f\"hook '{hook}' not found in callbacks {self._callbacks}\"\n assert callable(callback), f\"callback '{callback}' is not callable\"\n self._callbacks[hook].append({'name': name, 'callback': callback})\n\n def get_registered_actions(self, hook=None):\n \"\"\"\"\n Returns all the registered actions by callback hook\n\n Args:\n hook: The name of the hook to check, defaults to all\n \"\"\"\n return self._callbacks[hook] if hook else self._callbacks\n\n def run(self, hook, *args, thread=False, **kwargs):\n \"\"\"\n Loop through the registered actions and fire all callbacks on main thread\n\n Args:\n hook: The name of the hook to check, defaults to all\n args: Arguments to receive from YOLOv5\n thread: (boolean) Run callbacks in daemon thread\n kwargs: Keyword Arguments to receive from YOLOv5\n \"\"\"\n\n assert hook in self._callbacks, f\"hook '{hook}' not found in callbacks {self._callbacks}\"\n for logger in self._callbacks[hook]:\n if thread:\n threading.Thread(target=logger['callback'], args=args, kwargs=kwargs, daemon=True).start()\n else:\n logger['callback'](*args, **kwargs)" }, { "identifier": "LOGGER", "path": "utils/general.py", "snippet": "LOGGER = logging.getLogger(LOGGING_NAME) # define globally (used in train.py, val.py, detect.py, etc.)" }, { "identifier": "NUM_THREADS", "path": "utils/general.py", "snippet": "NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLOv5 multiprocessing threads" }, { "identifier": "TQDM_BAR_FORMAT", "path": "utils/general.py", "snippet": "TQDM_BAR_FORMAT = '{l_bar}{bar:10}| {n_fmt}/{total_fmt} {elapsed}' # tqdm bar format" }, { "identifier": "Profile", "path": "utils/general.py", "snippet": "class Profile(contextlib.ContextDecorator):\n # YOLOv5 Profile class. Usage: @Profile() decorator or 'with Profile():' context manager\n def __init__(self, t=0.0):\n self.t = t\n self.cuda = torch.cuda.is_available()\n\n def __enter__(self):\n self.start = self.time()\n return self\n\n def __exit__(self, type, value, traceback):\n self.dt = self.time() - self.start # delta-time\n self.t += self.dt # accumulate dt\n\n def time(self):\n if self.cuda:\n torch.cuda.synchronize()\n return time.time()" }, { "identifier": "check_dataset", "path": "utils/general.py", "snippet": "def check_dataset(data, autodownload=True):\n # Download, check and/or unzip dataset if not found locally\n\n # Download (optional)\n extract_dir = ''\n if isinstance(data, (str, Path)) and (is_zipfile(data) or is_tarfile(data)):\n download(data, dir=f'{DATASETS_DIR}/{Path(data).stem}', unzip=True, delete=False, curl=False, threads=1)\n data = next((DATASETS_DIR / Path(data).stem).rglob('*.yaml'))\n extract_dir, autodownload = data.parent, False\n\n # Read yaml (optional)\n if isinstance(data, (str, Path)):\n data = yaml_load(data) # dictionary\n\n # Checks\n for k in 'train', 'val', 'names':\n assert k in data, emojis(f\"data.yaml '{k}:' field missing ❌\")\n if isinstance(data['names'], (list, tuple)): # old array format\n data['names'] = dict(enumerate(data['names'])) # convert to dict\n assert all(isinstance(k, int) for k in data['names'].keys()), 'data.yaml names keys must be integers, i.e. 2: car'\n data['nc'] = len(data['names'])\n\n # Resolve paths\n path = Path(extract_dir or data.get('path') or '') # optional 'path' default to '.'\n if not path.is_absolute():\n path = (ROOT / path).resolve()\n data['path'] = path # download scripts\n for k in 'train', 'val', 'test':\n if data.get(k): # prepend path\n if isinstance(data[k], str):\n x = (path / data[k]).resolve()\n if not x.exists() and data[k].startswith('../'):\n x = (path / data[k][3:]).resolve()\n data[k] = str(x)\n else:\n data[k] = [str((path / x).resolve()) for x in data[k]]\n\n # Parse yaml\n train, val, test, s = (data.get(x) for x in ('train', 'val', 'test', 'download'))\n if val:\n val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path\n if not all(x.exists() for x in val):\n LOGGER.info('\\nDataset not found ⚠️, missing paths %s' % [str(x) for x in val if not x.exists()])\n if not s or not autodownload:\n raise Exception('Dataset not found ❌')\n t = time.time()\n if s.startswith('http') and s.endswith('.zip'): # URL\n f = Path(s).name # filename\n LOGGER.info(f'Downloading {s} to {f}...')\n torch.hub.download_url_to_file(s, f)\n Path(DATASETS_DIR).mkdir(parents=True, exist_ok=True) # create root\n unzip_file(f, path=DATASETS_DIR) # unzip\n Path(f).unlink() # remove zip\n r = None # success\n elif s.startswith('bash '): # bash script\n LOGGER.info(f'Running {s} ...')\n r = os.system(s)\n else: # python script\n r = exec(s, {'yaml': data}) # return None\n dt = f'({round(time.time() - t, 1)}s)'\n s = f\"success ✅ {dt}, saved to {colorstr('bold', DATASETS_DIR)}\" if r in (0, None) else f\"failure {dt} ❌\"\n LOGGER.info(f\"Dataset download {s}\")\n check_font('Arial.ttf' if is_ascii(data['names']) else 'Arial.Unicode.ttf', progress=True) # download fonts\n return data # dictionary" }, { "identifier": "check_img_size", "path": "utils/general.py", "snippet": "def check_img_size(imgsz, s=32, floor=0):\n # Verify image size is a multiple of stride s in each dimension\n if isinstance(imgsz, int): # integer i.e. img_size=640\n new_size = max(make_divisible(imgsz, int(s)), floor)\n else: # list i.e. img_size=[640, 480]\n imgsz = list(imgsz) # convert to list if tuple\n new_size = [max(make_divisible(x, int(s)), floor) for x in imgsz]\n if new_size != imgsz:\n LOGGER.warning(f'WARNING ⚠️ --img-size {imgsz} must be multiple of max stride {s}, updating to {new_size}')\n return new_size" }, { "identifier": "check_requirements", "path": "utils/general.py", "snippet": "@TryExcept()\ndef check_requirements(requirements=ROOT / 'requirements.txt', exclude=(), install=True, cmds=''):\n # Check installed dependencies meet YOLOv5 requirements (pass *.txt file or list of packages or single package str)\n prefix = colorstr('red', 'bold', 'requirements:')\n check_python() # check python version\n if isinstance(requirements, Path): # requirements.txt file\n file = requirements.resolve()\n assert file.exists(), f\"{prefix} {file} not found, check failed.\"\n with file.open() as f:\n requirements = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements(f) if x.name not in exclude]\n elif isinstance(requirements, str):\n requirements = [requirements]\n\n s = ''\n n = 0\n for r in requirements:\n try:\n pkg.require(r)\n except (pkg.VersionConflict, pkg.DistributionNotFound): # exception if requirements not met\n s += f'\"{r}\" '\n n += 1\n\n if s and install and AUTOINSTALL: # check environment variable\n LOGGER.info(f\"{prefix} YOLOv5 requirement{'s' * (n > 1)} {s}not found, attempting AutoUpdate...\")\n try:\n # assert check_online(), \"AutoUpdate skipped (offline)\"\n LOGGER.info(check_output(f'pip install {s} {cmds}', shell=True).decode())\n source = file if 'file' in locals() else requirements\n s = f\"{prefix} {n} package{'s' * (n > 1)} updated per {source}\\n\" \\\n f\"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\\n\"\n LOGGER.info(s)\n except Exception as e:\n LOGGER.warning(f'{prefix} ❌ {e}')" }, { "identifier": "check_yaml", "path": "utils/general.py", "snippet": "def check_yaml(file, suffix=('.yaml', '.yml')):\n # Search/download YAML file (if necessary) and return path, checking suffix\n return check_file(file, suffix)" }, { "identifier": "coco80_to_coco91_class", "path": "utils/general.py", "snippet": "def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)\n # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/\n # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\\n')\n # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\\n')\n # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco\n # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet\n return [\n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,\n 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,\n 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]" }, { "identifier": "colorstr", "path": "utils/general.py", "snippet": "def colorstr(*input):\n # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world')\n *args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string\n colors = {\n 'black': '\\033[30m', # basic colors\n 'red': '\\033[31m',\n 'green': '\\033[32m',\n 'yellow': '\\033[33m',\n 'blue': '\\033[34m',\n 'magenta': '\\033[35m',\n 'cyan': '\\033[36m',\n 'white': '\\033[37m',\n 'bright_black': '\\033[90m', # bright colors\n 'bright_red': '\\033[91m',\n 'bright_green': '\\033[92m',\n 'bright_yellow': '\\033[93m',\n 'bright_blue': '\\033[94m',\n 'bright_magenta': '\\033[95m',\n 'bright_cyan': '\\033[96m',\n 'bright_white': '\\033[97m',\n 'end': '\\033[0m', # misc\n 'bold': '\\033[1m',\n 'underline': '\\033[4m'}\n return ''.join(colors[x] for x in args) + f'{string}' + colors['end']" }, { "identifier": "increment_path", "path": "utils/general.py", "snippet": "def increment_path(path, exist_ok=False, sep='', mkdir=False):\n # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.\n path = Path(path) # os-agnostic\n if path.exists() and not exist_ok:\n path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '')\n\n # Method 1\n for n in range(2, 9999):\n p = f'{path}{sep}{n}{suffix}' # increment path\n if not os.path.exists(p): #\n break\n path = Path(p)\n\n # Method 2 (deprecated)\n # dirs = glob.glob(f\"{path}{sep}*\") # similar paths\n # matches = [re.search(rf\"{path.stem}{sep}(\\d+)\", d) for d in dirs]\n # i = [int(m.groups()[0]) for m in matches if m] # indices\n # n = max(i) + 1 if i else 2 # increment number\n # path = Path(f\"{path}{sep}{n}{suffix}\") # increment path\n\n if mkdir:\n path.mkdir(parents=True, exist_ok=True) # make directory\n\n return path" }, { "identifier": "non_max_suppression", "path": "utils/general.py", "snippet": "def non_max_suppression(\n prediction,\n conf_thres=0.25,\n iou_thres=0.45,\n classes=None,\n agnostic=False,\n multi_label=False,\n labels=(),\n max_det=300,\n nm=0, # number of masks\n):\n \"\"\"Non-Maximum Suppression (NMS) on inference results to reject overlapping detections\n\n Returns:\n list of detections, on (n,6) tensor per image [xyxy, conf, cls]\n \"\"\"\n\n if isinstance(prediction, (list, tuple)): # YOLOv5 model in validation model, output = (inference_out, loss_out)\n prediction = prediction[0] # select only inference output\n\n device = prediction.device\n mps = 'mps' in device.type # Apple MPS\n if mps: # MPS not fully supported yet, convert tensors to CPU before NMS\n prediction = prediction.cpu()\n bs = prediction.shape[0] # batch size\n nc = prediction.shape[2] - nm - 5 # number of classes\n xc = prediction[..., 4] > conf_thres # candidates\n\n # Checks\n assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'\n assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'\n\n # Settings\n # min_wh = 2 # (pixels) minimum box width and height\n max_wh = 7680 # (pixels) maximum box width and height\n max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()\n time_limit = 0.5 + 0.05 * bs # seconds to quit after\n redundant = True # require redundant detections\n multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)\n merge = False # use merge-NMS\n\n t = time.time()\n mi = 5 + nc # mask start index\n output = [torch.zeros((0, 6 + nm), device=prediction.device)] * bs\n for xi, x in enumerate(prediction): # image index, image inference\n # Apply constraints\n # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height\n x = x[xc[xi]] # confidence\n\n # Cat apriori labels if autolabelling\n if labels and len(labels[xi]):\n lb = labels[xi]\n v = torch.zeros((len(lb), nc + nm + 5), device=x.device)\n v[:, :4] = lb[:, 1:5] # box\n v[:, 4] = 1.0 # conf\n v[range(len(lb)), lb[:, 0].long() + 5] = 1.0 # cls\n x = torch.cat((x, v), 0)\n\n # If none remain process next image\n if not x.shape[0]:\n continue\n\n # Compute conf\n x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf\n\n # Box/Mask\n box = xywh2xyxy(x[:, :4]) # center_x, center_y, width, height) to (x1, y1, x2, y2)\n mask = x[:, mi:] # zero columns if no masks\n\n # Detections matrix nx6 (xyxy, conf, cls)\n if multi_label:\n i, j = (x[:, 5:mi] > conf_thres).nonzero(as_tuple=False).T\n x = torch.cat((box[i], x[i, 5 + j, None], j[:, None].float(), mask[i]), 1)\n else: # best class only\n conf, j = x[:, 5:mi].max(1, keepdim=True)\n x = torch.cat((box, conf, j.float(), mask), 1)[conf.view(-1) > conf_thres]\n\n # Filter by class\n if classes is not None:\n x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]\n\n # Apply finite constraint\n # if not torch.isfinite(x).all():\n # x = x[torch.isfinite(x).all(1)]\n\n # Check shape\n n = x.shape[0] # number of boxes\n if not n: # no boxes\n continue\n elif n > max_nms: # excess boxes\n x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence\n else:\n x = x[x[:, 4].argsort(descending=True)] # sort by confidence\n\n # Batched NMS\n c = x[:, 5:6] * (0 if agnostic else max_wh) # classes\n boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores\n i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS\n #i = my_soft_nms(boxes, scores, iou_thres) \n if i.shape[0] > max_det: # limit detections\n i = i[:max_det]\n if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)\n # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)\n iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix\n weights = iou * scores[None] # box weights\n x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes\n if redundant:\n i = i[iou.sum(1) > 1] # require redundancy\n\n output[xi] = x[i]\n if mps:\n output[xi] = output[xi].to(device)\n if (time.time() - t) > time_limit:\n LOGGER.warning(f'WARNING ⚠️ NMS time limit {time_limit:.3f}s exceeded')\n break # time limit exceeded\n\n return output" }, { "identifier": "print_args", "path": "utils/general.py", "snippet": "def print_args(args: Optional[dict] = None, show_file=True, show_func=False):\n # Print function arguments (optional args dict)\n x = inspect.currentframe().f_back # previous frame\n file, _, func, _, _ = inspect.getframeinfo(x)\n if args is None: # get args automatically\n args, _, _, frm = inspect.getargvalues(x)\n args = {k: v for k, v in frm.items() if k in args}\n try:\n file = Path(file).resolve().relative_to(ROOT).with_suffix('')\n except ValueError:\n file = Path(file).stem\n s = (f'{file}: ' if show_file else '') + (f'{func}: ' if show_func else '')\n LOGGER.info(colorstr(s) + ', '.join(f'{k}={v}' for k, v in args.items()))" }, { "identifier": "scale_boxes", "path": "utils/general.py", "snippet": "def scale_boxes(img1_shape, boxes, img0_shape, ratio_pad=None):\n # Rescale boxes (xyxy) from img1_shape to img0_shape\n if ratio_pad is None: # calculate from img0_shape\n gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new\n pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding\n else:\n gain = ratio_pad[0][0]\n pad = ratio_pad[1]\n\n boxes[:, [0, 2]] -= pad[0] # x padding\n boxes[:, [1, 3]] -= pad[1] # y padding\n boxes[:, :4] /= gain\n clip_boxes(boxes, img0_shape)\n return boxes" }, { "identifier": "xywh2xyxy", "path": "utils/general.py", "snippet": "def xywh2xyxy(x):\n # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x\n y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y\n y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x\n y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y\n return y" }, { "identifier": "xyxy2xywh", "path": "utils/general.py", "snippet": "def xyxy2xywh(x):\n # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right\n y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center\n y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center\n y[:, 2] = x[:, 2] - x[:, 0] # width\n y[:, 3] = x[:, 3] - x[:, 1] # height\n return y" }, { "identifier": "ConfusionMatrix", "path": "utils/metrics.py", "snippet": "class ConfusionMatrix:\n # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix\n def __init__(self, nc, conf=0.25, iou_thres=0.45):\n self.matrix = np.zeros((nc + 1, nc + 1))\n self.nc = nc # number of classes\n self.conf = conf\n self.iou_thres = iou_thres\n\n def process_batch(self, detections, labels):\n \"\"\"\n Return intersection-over-union (Jaccard index) of boxes.\n Both sets of boxes are expected to be in (x1, y1, x2, y2) format.\n Arguments:\n detections (Array[N, 6]), x1, y1, x2, y2, conf, class\n labels (Array[M, 5]), class, x1, y1, x2, y2\n Returns:\n None, updates confusion matrix accordingly\n \"\"\"\n if detections is None:\n gt_classes = labels.int()\n for gc in gt_classes:\n self.matrix[self.nc, gc] += 1 # background FN\n return\n\n detections = detections[detections[:, 4] > self.conf]\n gt_classes = labels[:, 0].int()\n detection_classes = detections[:, 5].int()\n iou = box_iou(labels[:, 1:], detections[:, :4])\n\n x = torch.where(iou > self.iou_thres)\n if x[0].shape[0]:\n matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()\n if x[0].shape[0] > 1:\n matches = matches[matches[:, 2].argsort()[::-1]]\n matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n matches = matches[matches[:, 2].argsort()[::-1]]\n matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n else:\n matches = np.zeros((0, 3))\n\n n = matches.shape[0] > 0\n m0, m1, _ = matches.transpose().astype(int)\n for i, gc in enumerate(gt_classes):\n j = m0 == i\n if n and sum(j) == 1:\n self.matrix[detection_classes[m1[j]], gc] += 1 # correct\n else:\n self.matrix[self.nc, gc] += 1 # true background\n\n if n:\n for i, dc in enumerate(detection_classes):\n if not any(m1 == i):\n self.matrix[dc, self.nc] += 1 # predicted background\n\n def tp_fp(self):\n tp = self.matrix.diagonal() # true positives\n fp = self.matrix.sum(1) - tp # false positives\n # fn = self.matrix.sum(0) - tp # false negatives (missed detections)\n return tp[:-1], fp[:-1] # remove background class\n\n @TryExcept('WARNING ⚠️ ConfusionMatrix plot failure')\n def plot(self, normalize=True, save_dir='', names=()):\n import seaborn as sn\n\n array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-9) if normalize else 1) # normalize columns\n array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)\n\n fig, ax = plt.subplots(1, 1, figsize=(12, 9), tight_layout=True)\n nc, nn = self.nc, len(names) # number of classes, names\n sn.set(font_scale=1.0 if nc < 50 else 0.8) # for label size\n labels = (0 < nn < 99) and (nn == nc) # apply names to ticklabels\n ticklabels = (names + ['background']) if labels else \"auto\"\n with warnings.catch_warnings():\n warnings.simplefilter('ignore') # suppress empty matrix RuntimeWarning: All-NaN slice encountered\n sn.heatmap(array,\n ax=ax,\n annot=nc < 30,\n annot_kws={\n \"size\": 8},\n cmap='Blues',\n fmt='.2f',\n square=True,\n vmin=0.0,\n xticklabels=ticklabels,\n yticklabels=ticklabels).set_facecolor((1, 1, 1))\n ax.set_ylabel('True')\n ax.set_ylabel('Predicted')\n ax.set_title('Confusion Matrix')\n fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)\n plt.close(fig)\n\n def print(self):\n for i in range(self.nc + 1):\n print(' '.join(map(str, self.matrix[i])))" }, { "identifier": "box_iou", "path": "utils/metrics.py", "snippet": "def box_iou(box1, box2, eps=1e-7):\n # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py\n \"\"\"\n Return intersection-over-union (Jaccard index) of boxes.\n Both sets of boxes are expected to be in (x1, y1, x2, y2) format.\n Arguments:\n box1 (Tensor[N, 4])\n box2 (Tensor[M, 4])\n Returns:\n iou (Tensor[N, M]): the NxM matrix containing the pairwise\n IoU values for every element in boxes1 and boxes2\n \"\"\"\n\n # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)\n (a1, a2), (b1, b2) = box1.unsqueeze(1).chunk(2, 2), box2.unsqueeze(0).chunk(2, 2)\n inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(0).prod(2)\n\n # IoU = inter / (area1 + area2 - inter)\n return inter / ((a2 - a1).prod(2) + (b2 - b1).prod(2) - inter + eps)" }, { "identifier": "output_to_target", "path": "utils/plots.py", "snippet": "def output_to_target(output, max_det=300):\n # Convert model output to target format [batch_id, class_id, x, y, w, h, conf] for plotting\n targets = []\n for i, o in enumerate(output):\n box, conf, cls = o[:max_det, :6].cpu().split((4, 1, 1), 1)\n j = torch.full((conf.shape[0], 1), i)\n targets.append(torch.cat((j, cls, xyxy2xywh(box), conf), 1))\n return torch.cat(targets, 0).numpy()" }, { "identifier": "plot_val_study", "path": "utils/plots.py", "snippet": "def plot_val_study(file='', dir='', x=None): # from utils.plots import *; plot_val_study()\n # Plot file=study.txt generated by val.py (or plot all study*.txt in dir)\n save_dir = Path(file).parent if file else Path(dir)\n plot2 = False # plot additional results\n if plot2:\n ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)[1].ravel()\n\n fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)\n # for f in [save_dir / f'study_coco_{x}.txt' for x in ['yolov5n6', 'yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]:\n for f in sorted(save_dir.glob('study*.txt')):\n y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T\n x = np.arange(y.shape[1]) if x is None else np.array(x)\n if plot2:\n s = ['P', 'R', '[email protected]', '[email protected]:.95', 't_preprocess (ms/img)', 't_inference (ms/img)', 't_NMS (ms/img)']\n for i in range(7):\n ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)\n ax[i].set_title(s[i])\n\n j = y[3].argmax() + 1\n ax2.plot(y[5, 1:j],\n y[3, 1:j] * 1E2,\n '.-',\n linewidth=2,\n markersize=8,\n label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))\n\n ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],\n 'k.-',\n linewidth=2,\n markersize=8,\n alpha=.25,\n label='EfficientDet')\n\n ax2.grid(alpha=0.2)\n ax2.set_yticks(np.arange(20, 60, 5))\n ax2.set_xlim(0, 57)\n ax2.set_ylim(25, 55)\n ax2.set_xlabel('GPU Speed (ms/img)')\n ax2.set_ylabel('COCO AP val')\n ax2.legend(loc='lower right')\n f = save_dir / 'study.png'\n print(f'Saving {f}...')\n plt.savefig(f, dpi=300)" }, { "identifier": "create_dataloader", "path": "utils/segment/dataloaders.py", "snippet": "def create_dataloader(path,\n imgsz,\n batch_size,\n stride,\n single_cls=False,\n hyp=None,\n augment=False,\n cache=False,\n pad=0.0,\n rect=False,\n rank=-1,\n workers=8,\n image_weights=False,\n quad=False,\n prefix='',\n shuffle=False,\n mask_downsample_ratio=1,\n overlap_mask=False):\n if rect and shuffle:\n LOGGER.warning('WARNING ⚠️ --rect is incompatible with DataLoader shuffle, setting shuffle=False')\n shuffle = False\n with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP\n dataset = LoadImagesAndLabelsAndMasks(\n path,\n imgsz,\n batch_size,\n augment=augment, # augmentation\n hyp=hyp, # hyperparameters\n rect=rect, # rectangular batches\n cache_images=cache,\n single_cls=single_cls,\n stride=int(stride),\n pad=pad,\n image_weights=image_weights,\n prefix=prefix,\n downsample_ratio=mask_downsample_ratio,\n overlap=overlap_mask)\n\n batch_size = min(batch_size, len(dataset))\n nd = torch.cuda.device_count() # number of CUDA devices\n nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers]) # number of workers\n sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)\n loader = DataLoader if image_weights else InfiniteDataLoader # only DataLoader allows for attribute updates\n generator = torch.Generator()\n generator.manual_seed(6148914691236517205 + RANK)\n return loader(\n dataset,\n batch_size=batch_size,\n shuffle=shuffle and sampler is None,\n num_workers=nw,\n sampler=sampler,\n pin_memory=True,\n collate_fn=LoadImagesAndLabelsAndMasks.collate_fn4 if quad else LoadImagesAndLabelsAndMasks.collate_fn,\n worker_init_fn=seed_worker,\n generator=generator,\n ), dataset" }, { "identifier": "mask_iou", "path": "utils/segment/general.py", "snippet": "def mask_iou(mask1, mask2, eps=1e-7):\n \"\"\"\n mask1: [N, n] m1 means number of predicted objects\n mask2: [M, n] m2 means number of gt objects\n Note: n means image_w x image_h\n\n return: masks iou, [N, M]\n \"\"\"\n intersection = torch.matmul(mask1, mask2.t()).clamp(0)\n union = (mask1.sum(1)[:, None] + mask2.sum(1)[None]) - intersection # (area1 + area2) - intersection\n return intersection / (union + eps)" }, { "identifier": "process_mask", "path": "utils/segment/general.py", "snippet": "def process_mask(protos, masks_in, bboxes, shape, upsample=False):\n \"\"\"\n Crop before upsample.\n proto_out: [mask_dim, mask_h, mask_w]\n out_masks: [n, mask_dim], n is number of masks after nms\n bboxes: [n, 4], n is number of masks after nms\n shape:input_image_size, (h, w)\n\n return: h, w, n\n \"\"\"\n\n c, mh, mw = protos.shape # CHW\n ih, iw = shape\n masks = (masks_in @ protos.float().view(c, -1)).sigmoid().view(-1, mh, mw) # CHW\n\n downsampled_bboxes = bboxes.clone()\n downsampled_bboxes[:, 0] *= mw / iw\n downsampled_bboxes[:, 2] *= mw / iw\n downsampled_bboxes[:, 3] *= mh / ih\n downsampled_bboxes[:, 1] *= mh / ih\n\n masks = crop_mask(masks, downsampled_bboxes) # CHW\n if upsample:\n masks = F.interpolate(masks[None], shape, mode='bilinear', align_corners=False)[0] # CHW\n return masks.gt_(0.5)" }, { "identifier": "process_mask_upsample", "path": "utils/segment/general.py", "snippet": "def process_mask_upsample(protos, masks_in, bboxes, shape):\n \"\"\"\n Crop after upsample.\n proto_out: [mask_dim, mask_h, mask_w]\n out_masks: [n, mask_dim], n is number of masks after nms\n bboxes: [n, 4], n is number of masks after nms\n shape:input_image_size, (h, w)\n\n return: h, w, n\n \"\"\"\n\n c, mh, mw = protos.shape # CHW\n masks = (masks_in @ protos.float().view(c, -1)).sigmoid().view(-1, mh, mw)\n masks = F.interpolate(masks[None], shape, mode='bilinear', align_corners=False)[0] # CHW\n masks = crop_mask(masks, bboxes) # CHW\n return masks.gt_(0.5)" }, { "identifier": "scale_image", "path": "utils/segment/general.py", "snippet": "def scale_image(im1_shape, masks, im0_shape, ratio_pad=None):\n \"\"\"\n img1_shape: model input shape, [h, w]\n img0_shape: origin pic shape, [h, w, 3]\n masks: [h, w, num]\n \"\"\"\n # Rescale coordinates (xyxy) from im1_shape to im0_shape\n if ratio_pad is None: # calculate from im0_shape\n gain = min(im1_shape[0] / im0_shape[0], im1_shape[1] / im0_shape[1]) # gain = old / new\n pad = (im1_shape[1] - im0_shape[1] * gain) / 2, (im1_shape[0] - im0_shape[0] * gain) / 2 # wh padding\n else:\n pad = ratio_pad[1]\n top, left = int(pad[1]), int(pad[0]) # y, x\n bottom, right = int(im1_shape[0] - pad[1]), int(im1_shape[1] - pad[0])\n\n if len(masks.shape) < 2:\n raise ValueError(f'\"len of masks shape\" should be 2 or 3, but got {len(masks.shape)}')\n masks = masks[top:bottom, left:right]\n # masks = masks.permute(2, 0, 1).contiguous()\n # masks = F.interpolate(masks[None], im0_shape[:2], mode='bilinear', align_corners=False)[0]\n # masks = masks.permute(1, 2, 0).contiguous()\n masks = cv2.resize(masks, (im0_shape[1], im0_shape[0]))\n\n if len(masks.shape) == 2:\n masks = masks[:, :, None]\n return masks" }, { "identifier": "Metrics", "path": "utils/segment/metrics.py", "snippet": "class Metrics:\n \"\"\"Metric for boxes and masks.\"\"\"\n\n def __init__(self) -> None:\n self.metric_box = Metric()\n self.metric_mask = Metric()\n\n def update(self, results):\n \"\"\"\n Args:\n results: Dict{'boxes': Dict{}, 'masks': Dict{}}\n \"\"\"\n self.metric_box.update(list(results[\"boxes\"].values()))\n self.metric_mask.update(list(results[\"masks\"].values()))\n\n def mean_results(self):\n return self.metric_box.mean_results() + self.metric_mask.mean_results()\n\n def class_result(self, i):\n return self.metric_box.class_result(i) + self.metric_mask.class_result(i)\n\n def get_maps(self, nc):\n return self.metric_box.get_maps(nc) + self.metric_mask.get_maps(nc)\n\n @property\n def ap_class_index(self):\n # boxes and masks have the same ap_class_index\n return self.metric_box.ap_class_index" }, { "identifier": "ap_per_class_box_and_mask", "path": "utils/segment/metrics.py", "snippet": "def ap_per_class_box_and_mask(\n tp_m,\n tp_b,\n conf,\n pred_cls,\n target_cls,\n plot=False,\n save_dir=\".\",\n names=(),\n):\n \"\"\"\n Args:\n tp_b: tp of boxes.\n tp_m: tp of masks.\n other arguments see `func: ap_per_class`.\n \"\"\"\n results_boxes = ap_per_class(tp_b,\n conf,\n pred_cls,\n target_cls,\n plot=plot,\n save_dir=save_dir,\n names=names,\n prefix=\"Box\")[2:]\n results_masks = ap_per_class(tp_m,\n conf,\n pred_cls,\n target_cls,\n plot=plot,\n save_dir=save_dir,\n names=names,\n prefix=\"Mask\")[2:]\n\n results = {\n \"boxes\": {\n \"p\": results_boxes[0],\n \"r\": results_boxes[1],\n \"ap\": results_boxes[3],\n \"f1\": results_boxes[2],\n \"ap_class\": results_boxes[4]},\n \"masks\": {\n \"p\": results_masks[0],\n \"r\": results_masks[1],\n \"ap\": results_masks[3],\n \"f1\": results_masks[2],\n \"ap_class\": results_masks[4]}}\n return results" }, { "identifier": "plot_images_and_masks", "path": "utils/segment/plots.py", "snippet": "@threaded\ndef plot_images_and_masks(images, targets, masks, paths=None, fname='images.jpg', names=None):\n # Plot image grid with labels\n if isinstance(images, torch.Tensor):\n images = images.cpu().float().numpy()\n if isinstance(targets, torch.Tensor):\n targets = targets.cpu().numpy()\n if isinstance(masks, torch.Tensor):\n masks = masks.cpu().numpy().astype(int)\n\n max_size = 1920 # max image size\n max_subplots = 16 # max image subplots, i.e. 4x4\n bs, _, h, w = images.shape # batch size, _, height, width\n bs = min(bs, max_subplots) # limit plot images\n ns = np.ceil(bs ** 0.5) # number of subplots (square)\n if np.max(images[0]) <= 1:\n images *= 255 # de-normalise (optional)\n\n # Build Image\n mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init\n for i, im in enumerate(images):\n if i == max_subplots: # if last batch has fewer images than we expect\n break\n x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin\n im = im.transpose(1, 2, 0)\n mosaic[y:y + h, x:x + w, :] = im\n\n # Resize (optional)\n scale = max_size / ns / max(h, w)\n if scale < 1:\n h = math.ceil(scale * h)\n w = math.ceil(scale * w)\n mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))\n\n # Annotate\n fs = int((h + w) * ns * 0.01) # font size\n annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=names)\n for i in range(i + 1):\n x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin\n annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2) # borders\n if paths:\n annotator.text((x + 5, y + 5 + h), text=Path(paths[i]).name[:40], txt_color=(220, 220, 220)) # filenames\n if len(targets) > 0:\n idx = targets[:, 0] == i\n ti = targets[idx] # image targets\n\n boxes = xywh2xyxy(ti[:, 2:6]).T\n classes = ti[:, 1].astype('int')\n labels = ti.shape[1] == 6 # labels if no conf column\n conf = None if labels else ti[:, 6] # check for confidence presence (label vs pred)\n\n if boxes.shape[1]:\n if boxes.max() <= 1.01: # if normalized with tolerance 0.01\n boxes[[0, 2]] *= w # scale to pixels\n boxes[[1, 3]] *= h\n elif scale < 1: # absolute coords need scale if image scales\n boxes *= scale\n boxes[[0, 2]] += x\n boxes[[1, 3]] += y\n for j, box in enumerate(boxes.T.tolist()):\n cls = classes[j]\n color = colors(cls)\n cls = names[cls] if names else cls\n if labels or conf[j] > 0.25: # 0.25 conf thresh\n label = f'{cls}' if labels else f'{cls} {conf[j]:.1f}'\n annotator.box_label(box, label, color=color)\n\n # Plot masks\n if len(masks):\n if masks.max() > 1.0: # mean that masks are overlap\n image_masks = masks[[i]] # (1, 640, 640)\n nl = len(ti)\n index = np.arange(nl).reshape(nl, 1, 1) + 1\n image_masks = np.repeat(image_masks, nl, axis=0)\n image_masks = np.where(image_masks == index, 1.0, 0.0)\n else:\n image_masks = masks[idx]\n\n im = np.asarray(annotator.im).copy()\n for j, box in enumerate(boxes.T.tolist()):\n if labels or conf[j] > 0.25: # 0.25 conf thresh\n color = colors(classes[j])\n mh, mw = image_masks[j].shape\n if mh != h or mw != w:\n mask = image_masks[j].astype(np.uint8)\n mask = cv2.resize(mask, (w, h))\n mask = mask.astype(bool)\n else:\n mask = image_masks[j].astype(bool)\n with contextlib.suppress(Exception):\n im[y:y + h, x:x + w, :][mask] = im[y:y + h, x:x + w, :][mask] * 0.4 + np.array(color) * 0.6\n annotator.fromarray(im)\n annotator.im.save(fname) # save" }, { "identifier": "de_parallel", "path": "utils/torch_utils.py", "snippet": "def de_parallel(model):\n # De-parallelize a model: returns single-GPU model if model is of type DP or DDP\n return model.module if is_parallel(model) else model" }, { "identifier": "select_device", "path": "utils/torch_utils.py", "snippet": "def select_device(device='', batch_size=0, newline=True):\n # device = None or 'cpu' or 0 or '0' or '0,1,2,3'\n s = f'YOLOv5 🚀 {git_describe() or file_date()} Python-{platform.python_version()} torch-{torch.__version__} '\n device = str(device).strip().lower().replace('cuda:', '').replace('none', '') # to string, 'cuda:0' to '0'\n cpu = device == 'cpu'\n mps = device == 'mps' # Apple Metal Performance Shaders (MPS)\n if cpu or mps:\n os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False\n elif device: # non-cpu device requested\n os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable - must be before assert is_available()\n assert torch.cuda.is_available() and torch.cuda.device_count() >= len(device.replace(',', '')), \\\n f\"Invalid CUDA '--device {device}' requested, use '--device cpu' or pass valid CUDA device(s)\"\n\n if not cpu and not mps and torch.cuda.is_available(): # prefer GPU if available\n devices = device.split(',') if device else '0' # range(torch.cuda.device_count()) # i.e. 0,1,6,7\n n = len(devices) # device count\n if n > 1 and batch_size > 0: # check batch_size is divisible by device_count\n assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'\n space = ' ' * (len(s) + 1)\n for i, d in enumerate(devices):\n p = torch.cuda.get_device_properties(i)\n s += f\"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / (1 << 20):.0f}MiB)\\n\" # bytes to MB\n arg = 'cuda:0'\n elif mps and getattr(torch, 'has_mps', False) and torch.backends.mps.is_available(): # prefer MPS if available\n s += 'MPS\\n'\n arg = 'mps'\n else: # revert to CPU\n s += 'CPU\\n'\n arg = 'cpu'\n\n if not newline:\n s = s.rstrip()\n LOGGER.info(s)\n return torch.device(arg)" }, { "identifier": "smart_inference_mode", "path": "utils/torch_utils.py", "snippet": "def smart_inference_mode(torch_1_9=check_version(torch.__version__, '1.9.0')):\n # Applies torch.inference_mode() decorator if torch>=1.9.0 else torch.no_grad() decorator\n def decorate(fn):\n return (torch.inference_mode if torch_1_9 else torch.no_grad)()(fn)\n\n return decorate" } ]
import argparse import json import os import sys import numpy as np import torch import torch.nn.functional as F import time from multiprocessing.pool import ThreadPool from pathlib import Path from tqdm import tqdm from models.common import DetectMultiBackend from models.yolo import SegmentationModel from utils.callbacks import Callbacks from utils.general import (LOGGER, NUM_THREADS, TQDM_BAR_FORMAT, Profile, check_dataset, check_img_size, check_requirements, check_yaml, coco80_to_coco91_class, colorstr, increment_path, non_max_suppression, print_args, scale_boxes, xywh2xyxy, xyxy2xywh) from utils.metrics import ConfusionMatrix, box_iou from utils.plots import output_to_target, plot_val_study from utils.segment.dataloaders import create_dataloader from utils.segment.general import mask_iou, process_mask, process_mask_upsample, scale_image from utils.segment.metrics import Metrics, ap_per_class_box_and_mask from utils.segment.plots import plot_images_and_masks from utils.torch_utils import de_parallel, select_device, smart_inference_mode from pycocotools.mask import encode from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval
19,918
detections (array[N, 6]), x1, y1, x2, y2, conf, class labels (array[M, 5]), class, x1, y1, x2, y2 Returns: correct (array[N, 10]), for 10 IoU levels """ if masks: if overlap: nl = len(labels) index = torch.arange(nl, device=gt_masks.device).view(nl, 1, 1) + 1 gt_masks = gt_masks.repeat(nl, 1, 1) # shape(1,640,640) -> (n,640,640) gt_masks = torch.where(gt_masks == index, 1.0, 0.0) if gt_masks.shape[1:] != pred_masks.shape[1:]: gt_masks = F.interpolate(gt_masks[None], pred_masks.shape[1:], mode="bilinear", align_corners=False)[0] gt_masks = gt_masks.gt_(0.5) iou = mask_iou(gt_masks.view(gt_masks.shape[0], -1), pred_masks.view(pred_masks.shape[0], -1)) else: # boxes iou = box_iou(labels[:, 1:], detections[:, :4]) correct = np.zeros((detections.shape[0], iouv.shape[0])).astype(bool) correct_class = labels[:, 0:1] == detections[:, 5] for i in range(len(iouv)): x = torch.where((iou >= iouv[i]) & correct_class) # IoU > threshold and classes match if x[0].shape[0]: matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() # [label, detect, iou] if x[0].shape[0] > 1: matches = matches[matches[:, 2].argsort()[::-1]] matches = matches[np.unique(matches[:, 1], return_index=True)[1]] # matches = matches[matches[:, 2].argsort()[::-1]] matches = matches[np.unique(matches[:, 0], return_index=True)[1]] correct[matches[:, 1].astype(int), i] = True return torch.tensor(correct, dtype=torch.bool, device=iouv.device) @smart_inference_mode() def run( data, weights=None, # model.pt path(s) batch_size=32, # batch size imgsz=640, # inference size (pixels) conf_thres=0.001, # confidence threshold iou_thres=0.6, # NMS IoU threshold max_det=300, # maximum detections per image task='val', # train, val, test, speed or study device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu workers=8, # max dataloader workers (per RANK in DDP mode) single_cls=False, # treat as single-class dataset augment=False, # augmented inference verbose=False, # verbose output save_txt=False, # save results to *.txt save_hybrid=False, # save label+prediction hybrid results to *.txt save_conf=False, # save confidences in --save-txt labels save_json=False, # save a COCO-JSON results file project=ROOT / 'runs/val-seg', # save to project/name name='exp', # save to project/name exist_ok=False, # existing project/name ok, do not increment half=True, # use FP16 half-precision inference dnn=False, # use OpenCV DNN for ONNX inference model=None, dataloader=None, save_dir=Path(''), plots=True, overlap=False, mask_downsample_ratio=1, compute_loss=None, callbacks=Callbacks(), ): if save_json: check_requirements(['pycocotools']) process = process_mask_upsample # more accurate else: process = process_mask # faster # Initialize/load model and set device training = model is not None if training: # called by train.py device, pt, jit, engine = next(model.parameters()).device, True, False, False # get model device, PyTorch model half &= device.type != 'cpu' # half precision only supported on CUDA model.half() if half else model.float() nm = de_parallel(model).model[-1].nm # number of masks else: # called directly device = select_device(device, batch_size=batch_size) # Directories save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir # Load model model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half) stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine imgsz = check_img_size(imgsz, s=stride) # check image size half = model.fp16 # FP16 supported on limited backends with CUDA nm = de_parallel(model).model.model[-1].nm if isinstance(model, SegmentationModel) else 32 # number of masks if engine: batch_size = model.batch_size else: device = model.device if not (pt or jit): batch_size = 1 # export.py models default to batch-size 1 LOGGER.info(f'Forcing --batch-size 1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models') # Data data = check_dataset(data) # check # Configure model.eval() cuda = device.type != 'cpu' is_coco = isinstance(data.get('val'), str) and data['val'].endswith(f'coco{os.sep}val2017.txt') # COCO dataset nc = 1 if single_cls else int(data['nc']) # number of classes iouv = torch.linspace(0.5, 0.95, 10, device=device) # iou vector for [email protected]:0.95 niou = iouv.numel() # Dataloader if not training: if pt and not single_cls: # check --weights are trained on --data ncm = model.model.nc assert ncm == nc, f'{weights} ({ncm} classes) trained on different --data than what you passed ({nc} ' \ f'classes). Pass correct combination of --weights and --data that are trained together.' model.warmup(imgsz=(1 if pt else batch_size, 3, imgsz, imgsz)) # warmup pad, rect = (0.0, False) if task == 'speed' else (0.5, pt) # square inference for benchmarks task = task if task in ('train', 'val', 'test') else 'val' # path to train/val/test images
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ Validate a trained YOLOv5 segment model on a segment dataset Usage: $ bash data/scripts/get_coco.sh --val --segments # download COCO-segments val split (1G, 5000 images) $ python segment/val.py --weights yolov5s-seg.pt --data coco.yaml --img 640 # validate COCO-segments Usage - formats: $ python segment/val.py --weights yolov5s-seg.pt # PyTorch yolov5s-seg.torchscript # TorchScript yolov5s-seg.onnx # ONNX Runtime or OpenCV DNN with --dnn yolov5s-seg_openvino_label # OpenVINO yolov5s-seg.engine # TensorRT yolov5s-seg.mlmodel # CoreML (macOS-only) yolov5s-seg_saved_model # TensorFlow SavedModel yolov5s-seg.pb # TensorFlow GraphDef yolov5s-seg.tflite # TensorFlow Lite yolov5s-seg_edgetpu.tflite # TensorFlow Edge TPU yolov5s-seg_paddle_model # PaddlePaddle """ FILE = Path(__file__).resolve() ROOT = FILE.parents[1] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) # add ROOT to PATH ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative def save_one_txt(predn, save_conf, shape, file): # Save one txt result gn = torch.tensor(shape)[[1, 0, 1, 0]] # normalization gain whwh for *xyxy, conf, cls in predn.tolist(): xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format with open(file, 'a') as f: f.write(('%g ' * len(line)).rstrip() % line + '\n') def save_one_json(predn, jdict, path, class_map, pred_masks): # Save one JSON result {"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236} def single_encode(x): rle = encode(np.asarray(x[:, :, None], order="F", dtype="uint8"))[0] rle["counts"] = rle["counts"].decode("utf-8") return rle image_id = int(path.stem) if path.stem.isnumeric() else path.stem box = xyxy2xywh(predn[:, :4]) # xywh box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner pred_masks = np.transpose(pred_masks, (2, 0, 1)) with ThreadPool(NUM_THREADS) as pool: rles = pool.map(single_encode, pred_masks) for i, (p, b) in enumerate(zip(predn.tolist(), box.tolist())): jdict.append({ 'image_id': image_id, 'category_id': class_map[int(p[5])], 'bbox': [round(x, 3) for x in b], 'score': round(p[4], 5), 'segmentation': rles[i]}) def process_batch(detections, labels, iouv, pred_masks=None, gt_masks=None, overlap=False, masks=False): """ Return correct prediction matrix Arguments: detections (array[N, 6]), x1, y1, x2, y2, conf, class labels (array[M, 5]), class, x1, y1, x2, y2 Returns: correct (array[N, 10]), for 10 IoU levels """ if masks: if overlap: nl = len(labels) index = torch.arange(nl, device=gt_masks.device).view(nl, 1, 1) + 1 gt_masks = gt_masks.repeat(nl, 1, 1) # shape(1,640,640) -> (n,640,640) gt_masks = torch.where(gt_masks == index, 1.0, 0.0) if gt_masks.shape[1:] != pred_masks.shape[1:]: gt_masks = F.interpolate(gt_masks[None], pred_masks.shape[1:], mode="bilinear", align_corners=False)[0] gt_masks = gt_masks.gt_(0.5) iou = mask_iou(gt_masks.view(gt_masks.shape[0], -1), pred_masks.view(pred_masks.shape[0], -1)) else: # boxes iou = box_iou(labels[:, 1:], detections[:, :4]) correct = np.zeros((detections.shape[0], iouv.shape[0])).astype(bool) correct_class = labels[:, 0:1] == detections[:, 5] for i in range(len(iouv)): x = torch.where((iou >= iouv[i]) & correct_class) # IoU > threshold and classes match if x[0].shape[0]: matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() # [label, detect, iou] if x[0].shape[0] > 1: matches = matches[matches[:, 2].argsort()[::-1]] matches = matches[np.unique(matches[:, 1], return_index=True)[1]] # matches = matches[matches[:, 2].argsort()[::-1]] matches = matches[np.unique(matches[:, 0], return_index=True)[1]] correct[matches[:, 1].astype(int), i] = True return torch.tensor(correct, dtype=torch.bool, device=iouv.device) @smart_inference_mode() def run( data, weights=None, # model.pt path(s) batch_size=32, # batch size imgsz=640, # inference size (pixels) conf_thres=0.001, # confidence threshold iou_thres=0.6, # NMS IoU threshold max_det=300, # maximum detections per image task='val', # train, val, test, speed or study device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu workers=8, # max dataloader workers (per RANK in DDP mode) single_cls=False, # treat as single-class dataset augment=False, # augmented inference verbose=False, # verbose output save_txt=False, # save results to *.txt save_hybrid=False, # save label+prediction hybrid results to *.txt save_conf=False, # save confidences in --save-txt labels save_json=False, # save a COCO-JSON results file project=ROOT / 'runs/val-seg', # save to project/name name='exp', # save to project/name exist_ok=False, # existing project/name ok, do not increment half=True, # use FP16 half-precision inference dnn=False, # use OpenCV DNN for ONNX inference model=None, dataloader=None, save_dir=Path(''), plots=True, overlap=False, mask_downsample_ratio=1, compute_loss=None, callbacks=Callbacks(), ): if save_json: check_requirements(['pycocotools']) process = process_mask_upsample # more accurate else: process = process_mask # faster # Initialize/load model and set device training = model is not None if training: # called by train.py device, pt, jit, engine = next(model.parameters()).device, True, False, False # get model device, PyTorch model half &= device.type != 'cpu' # half precision only supported on CUDA model.half() if half else model.float() nm = de_parallel(model).model[-1].nm # number of masks else: # called directly device = select_device(device, batch_size=batch_size) # Directories save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir # Load model model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half) stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine imgsz = check_img_size(imgsz, s=stride) # check image size half = model.fp16 # FP16 supported on limited backends with CUDA nm = de_parallel(model).model.model[-1].nm if isinstance(model, SegmentationModel) else 32 # number of masks if engine: batch_size = model.batch_size else: device = model.device if not (pt or jit): batch_size = 1 # export.py models default to batch-size 1 LOGGER.info(f'Forcing --batch-size 1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models') # Data data = check_dataset(data) # check # Configure model.eval() cuda = device.type != 'cpu' is_coco = isinstance(data.get('val'), str) and data['val'].endswith(f'coco{os.sep}val2017.txt') # COCO dataset nc = 1 if single_cls else int(data['nc']) # number of classes iouv = torch.linspace(0.5, 0.95, 10, device=device) # iou vector for [email protected]:0.95 niou = iouv.numel() # Dataloader if not training: if pt and not single_cls: # check --weights are trained on --data ncm = model.model.nc assert ncm == nc, f'{weights} ({ncm} classes) trained on different --data than what you passed ({nc} ' \ f'classes). Pass correct combination of --weights and --data that are trained together.' model.warmup(imgsz=(1 if pt else batch_size, 3, imgsz, imgsz)) # warmup pad, rect = (0.0, False) if task == 'speed' else (0.5, pt) # square inference for benchmarks task = task if task in ('train', 'val', 'test') else 'val' # path to train/val/test images
dataloader = create_dataloader(data[task],
23
2023-12-10 14:18:29+00:00
24k
youngskkim/CRN
exps/base_exp.py
[ { "identifier": "NuscDatasetRadarDet", "path": "datasets/nusc_det_dataset.py", "snippet": "class NuscDatasetRadarDet(Dataset):\n def __init__(self,\n ida_aug_conf,\n bda_aug_conf,\n rda_aug_conf,\n classes,\n data_root,\n info_paths,\n is_train,\n load_interval=1,\n num_sweeps=1,\n img_conf=dict(img_mean=[123.675, 116.28, 103.53],\n img_std=[58.395, 57.12, 57.375],\n to_rgb=True),\n img_backbone_conf=dict(\n x_bound=[-51.2, 51.2, 0.8],\n y_bound=[-51.2, 51.2, 0.8],\n z_bound=[-5, 3, 8],\n d_bound=[2.0, 58.0, 0.5]\n ),\n drop_aug_conf=None,\n return_image=True,\n return_depth=False,\n return_radar_pv=False,\n depth_path='depth_gt',\n radar_pv_path='radar_pv_filter',\n remove_z_axis=False,\n use_cbgs=False,\n gt_for_radar_only=False,\n sweep_idxes=list(),\n key_idxes=list()):\n \"\"\"Dataset used for bevdetection task.\n Args:\n ida_aug_conf (dict): Config for ida augmentation.\n bda_aug_conf (dict): Config for bda augmentation.\n classes (list): Class names.\n use_cbgs (bool): Whether to use cbgs strategy,\n Default: False.\n num_sweeps (int): Number of sweeps to be used for each sample.\n default: 1.\n img_conf (dict): Config for image.\n return_depth (bool): Whether to use depth gt.\n default: False.\n sweep_idxes (list): List of sweep idxes to be used.\n default: list().\n key_idxes (list): List of key idxes to be used.\n default: list().\n \"\"\"\n super().__init__()\n if isinstance(info_paths, list):\n self.infos = list()\n for info_path in info_paths:\n self.infos.extend(mmcv.load(info_path))\n else:\n self.infos = mmcv.load(info_paths)\n self.is_train = is_train\n self.ida_aug_conf = ida_aug_conf\n self.bda_aug_conf = bda_aug_conf\n self.rda_aug_conf = rda_aug_conf\n self.drop_aug_conf = drop_aug_conf\n self.data_root = data_root\n self.classes = classes\n self.use_cbgs = use_cbgs\n if self.use_cbgs:\n self.cat2id = {name: i for i, name in enumerate(self.classes)}\n self.sample_indices = self._get_sample_indices()\n self.num_sweeps = num_sweeps\n self.img_mean = np.array(img_conf['img_mean'], np.float32)\n self.img_std = np.array(img_conf['img_std'], np.float32)\n self.to_rgb = img_conf['to_rgb']\n self.img_backbone_conf = img_backbone_conf\n\n self.return_image = return_image\n self.return_depth = return_depth\n self.return_radar_pv = return_radar_pv\n\n self.remove_z_axis = remove_z_axis\n self.gt_for_radar_only = gt_for_radar_only\n\n assert sum([sweep_idx >= 0 for sweep_idx in sweep_idxes]) \\\n == len(sweep_idxes), 'All `sweep_idxes` must greater \\\n than or equal to 0.'\n\n self.sweeps_idx = sweep_idxes\n assert sum([key_idx < 0 for key_idx in key_idxes]) == len(key_idxes),\\\n 'All `key_idxes` must less than 0.'\n self.key_idxes = [0] + key_idxes\n if load_interval > 1:\n self.infos = self.infos[::load_interval]\n self.depth_path = depth_path\n self.radar_pv_path = radar_pv_path\n\n self.max_radar_points_pv = 1536\n self.max_distance_pv = self.img_backbone_conf['d_bound'][1]\n\n def _get_sample_indices(self):\n \"\"\"Load annotations from ann_file.\n\n Args:\n ann_file (str): Path of the annotation file.\n\n Returns:\n list[dict]: List of annotations after class sampling.\n \"\"\"\n class_sample_idxs = {cat_id: [] for cat_id in self.cat2id.values()}\n for idx, info in enumerate(self.infos):\n gt_names = set(\n [ann_info['category_name'] for ann_info in info['ann_infos']])\n for gt_name in gt_names:\n gt_name = map_name_from_general_to_detection[gt_name]\n if gt_name not in self.classes:\n continue\n class_sample_idxs[self.cat2id[gt_name]].append(idx)\n duplicated_samples = sum(\n [len(v) for _, v in class_sample_idxs.items()])\n class_distribution = {\n k: len(v) / duplicated_samples\n for k, v in class_sample_idxs.items()\n }\n\n sample_indices = []\n\n frac = 1.0 / len(self.classes)\n ratios = [frac / v for v in class_distribution.values()]\n for cls_inds, ratio in zip(list(class_sample_idxs.values()), ratios):\n sample_indices += np.random.choice(cls_inds,\n int(len(cls_inds) *\n ratio)).tolist()\n return sample_indices\n\n def sample_ida_augmentation(self):\n \"\"\"Generate ida augmentation values based on ida_config.\"\"\"\n H, W = self.ida_aug_conf['H'], self.ida_aug_conf['W']\n fH, fW = self.ida_aug_conf['final_dim']\n if self.is_train:\n resize = np.random.uniform(*self.ida_aug_conf['resize_lim'])\n resize_dims = (int(W * resize), int(H * resize))\n newW, newH = resize_dims\n crop_h = int(\n (1 - np.random.uniform(*self.ida_aug_conf['bot_pct_lim'])) *\n newH) - fH\n crop_w = int(np.random.uniform(0, max(0, newW - fW)))\n crop = (crop_w, crop_h, crop_w + fW, crop_h + fH)\n flip = False\n if self.ida_aug_conf['rand_flip'] and np.random.choice([0, 1]):\n flip = True\n rotate_ida = np.random.uniform(*self.ida_aug_conf['rot_lim'])\n else:\n resize = max(fH / H, fW / W)\n resize_dims = (int(W * resize), int(H * resize))\n newW, newH = resize_dims\n crop_h = int(\n (1 - np.mean(self.ida_aug_conf['bot_pct_lim'])) * newH) - fH\n crop_w = int(max(0, newW - fW) / 2)\n crop = (crop_w, crop_h, crop_w + fW, crop_h + fH)\n flip = False\n rotate_ida = 0\n return resize, resize_dims, crop, flip, rotate_ida\n\n def sample_bda_augmentation(self):\n \"\"\"Generate bda augmentation values based on bda_config.\"\"\"\n if self.is_train:\n if np.random.uniform() < self.bda_aug_conf['rot_ratio']:\n rotate_bda = np.random.uniform(*self.bda_aug_conf['rot_lim'])\n else:\n rotate_bda = 0\n scale_bda = np.random.uniform(*self.bda_aug_conf['scale_lim'])\n flip_dx = np.random.uniform() < self.bda_aug_conf['flip_dx_ratio']\n flip_dy = np.random.uniform() < self.bda_aug_conf['flip_dy_ratio']\n else:\n rotate_bda = 0\n scale_bda = 1.0\n flip_dx = False\n flip_dy = False\n return rotate_bda, scale_bda, flip_dx, flip_dy\n\n def sample_radar_augmentation(self):\n \"\"\"Generate bda augmentation values based on bda_config.\"\"\"\n if self.is_train:\n radar_idx = np.random.choice(self.rda_aug_conf['N_sweeps'],\n self.rda_aug_conf['N_use'],\n replace=False)\n else:\n radar_idx = np.arange(self.rda_aug_conf['N_sweeps'])\n return radar_idx\n\n def transform_radar_pv(self, points, resize, resize_dims, crop, flip, rotate, radar_idx):\n points = points[points[:, 2] < self.max_distance_pv, :]\n\n H, W = resize_dims\n points[:, :2] = points[:, :2] * resize\n points[:, 0] -= crop[0]\n points[:, 1] -= crop[1]\n if flip:\n points[:, 0] = resize_dims[1] - points[:, 0]\n\n points[:, 0] -= W / 2.0\n points[:, 1] -= H / 2.0\n\n h = rotate / 180 * np.pi\n rot_matrix = [\n [np.cos(h), np.sin(h)],\n [-np.sin(h), np.cos(h)],\n ]\n points[:, :2] = np.matmul(rot_matrix, points[:, :2].T).T\n\n points[:, 0] += W / 2.0\n points[:, 1] += H / 2.0\n\n depth_coords = points[:, :2].astype(np.int16)\n\n valid_mask = ((depth_coords[:, 1] < resize_dims[0])\n & (depth_coords[:, 0] < resize_dims[1])\n & (depth_coords[:, 1] >= 0)\n & (depth_coords[:, 0] >= 0))\n\n points = torch.Tensor(points[valid_mask])\n\n if self.remove_z_axis:\n points[:, 1] = 1. # dummy height value\n\n points_save = []\n for i in radar_idx:\n points_save.append(points[points[:, 6] == i])\n points = torch.cat(points_save, dim=0)\n\n # mean, std of rcs and speed are from train set\n points[:, 3] = (points[:, 3] - 4.783) / 7.576\n points[:, 4] = (torch.norm(points[:, 4:6], dim=1) - 0.677) / 1.976\n\n if self.is_train:\n drop_idx = np.random.uniform(size=points.shape[0]) # randomly drop points\n points = points[drop_idx > self.rda_aug_conf['drop_ratio']]\n\n num_points, num_feat = points.shape\n if num_points > self.max_radar_points_pv:\n choices = np.random.choice(num_points, self.max_radar_points_pv, replace=False)\n points = points[choices]\n else:\n num_append = self.max_radar_points_pv - num_points\n points = torch.cat([points, -999*torch.ones(num_append, num_feat)], dim=0)\n\n if num_points == 0:\n points[0, :] = points.new_tensor([0.1, 0.1, self.max_distance_pv-1, 0, 0, 0, 0])\n\n points[..., [0, 1, 2]] = points[..., [0, 2, 1]] # convert [w, h, d] to [w, d, h]\n\n return points[..., :5]\n\n def depth_transform(self, cam_depth, resize, resize_dims, crop, flip, rotate):\n \"\"\"Transform depth based on ida augmentation configuration.\n\n Args:\n cam_depth (np array): Nx3, 3: x,y,d.\n resize (float): Resize factor.\n resize_dims (tuple): Final dimension.\n crop (tuple): x1, y1, x2, y2\n flip (bool): Whether to flip.\n rotate (float): Rotation value.\n\n Returns:\n np array: [h/down_ratio, w/down_ratio, d]\n \"\"\"\n valid_depth = cam_depth[:, 2] < self.img_backbone_conf['d_bound'][1]\n cam_depth = cam_depth[valid_depth, :]\n\n H, W = resize_dims\n cam_depth[:, :2] = cam_depth[:, :2] * resize\n cam_depth[:, 0] -= crop[0]\n cam_depth[:, 1] -= crop[1]\n if flip:\n cam_depth[:, 0] = resize_dims[1] - cam_depth[:, 0]\n\n cam_depth[:, 0] -= W / 2.0\n cam_depth[:, 1] -= H / 2.0\n\n h = rotate / 180 * np.pi\n rot_matrix = [\n [np.cos(h), np.sin(h)],\n [-np.sin(h), np.cos(h)],\n ]\n cam_depth[:, :2] = np.matmul(rot_matrix, cam_depth[:, :2].T).T\n\n cam_depth[:, 0] += W / 2.0\n cam_depth[:, 1] += H / 2.0\n\n depth_coords = cam_depth[:, :2].astype(np.int16)\n\n depth_map = np.zeros(resize_dims)\n valid_mask = ((depth_coords[:, 1] < resize_dims[0])\n & (depth_coords[:, 0] < resize_dims[1])\n & (depth_coords[:, 1] >= 0)\n & (depth_coords[:, 0] >= 0))\n depth_map[depth_coords[valid_mask, 1],\n depth_coords[valid_mask, 0]] = cam_depth[valid_mask, 2]\n\n return torch.Tensor(depth_map)\n\n def get_image(self, cam_infos, cams):\n \"\"\"Given data and cam_names, return image data needed.\n\n Args:\n sweeps_data (list): Raw data used to generate the data we needed.\n cams (list): Camera names.\n\n Returns:\n Tensor: Image data after processing.\n Tensor: Transformation matrix from camera to ego.\n Tensor: Intrinsic matrix.\n Tensor: Transformation matrix for ida.\n Tensor: Transformation matrix from key\n frame camera to sweep frame camera.\n Tensor: timestamps.\n dict: meta infos needed for evaluation.\n \"\"\"\n assert len(cam_infos) > 0\n sweep_imgs = list()\n sweep_sensor2ego_mats = list()\n sweep_intrin_mats = list()\n sweep_ida_mats = list()\n sweep_sensor2sensor_mats = list()\n sweep_timestamps = list()\n sweep_gt_depths = list()\n sweep_radar_points = list()\n for cam in cams:\n imgs = list()\n sensor2ego_mats = list()\n intrin_mats = list()\n ida_mats = list()\n sensor2sensor_mats = list()\n timestamps = list()\n gt_depths = list()\n radar_points = list()\n key_info = cam_infos[0]\n resize, resize_dims, crop, flip, \\\n rotate_ida = self.sample_ida_augmentation()\n radar_idx = self.sample_radar_augmentation()\n\n for sweep_idx, cam_info in enumerate(cam_infos):\n img = Image.open(\n os.path.join(self.data_root, cam_info[cam]['filename']))\n\n w, x, y, z = cam_info[cam]['calibrated_sensor']['rotation']\n # sweep sensor to sweep ego\n sweepsensor2sweepego_rot = torch.Tensor(\n Quaternion(w, x, y, z).rotation_matrix)\n sweepsensor2sweepego_tran = torch.Tensor(\n cam_info[cam]['calibrated_sensor']['translation'])\n sweepsensor2sweepego = sweepsensor2sweepego_rot.new_zeros(\n (4, 4))\n sweepsensor2sweepego[3, 3] = 1\n sweepsensor2sweepego[:3, :3] = sweepsensor2sweepego_rot\n sweepsensor2sweepego[:3, -1] = sweepsensor2sweepego_tran\n # sweep ego to global\n w, x, y, z = cam_info[cam]['ego_pose']['rotation']\n sweepego2global_rot = torch.Tensor(\n Quaternion(w, x, y, z).rotation_matrix)\n sweepego2global_tran = torch.Tensor(\n cam_info[cam]['ego_pose']['translation'])\n sweepego2global = sweepego2global_rot.new_zeros((4, 4))\n sweepego2global[3, 3] = 1\n sweepego2global[:3, :3] = sweepego2global_rot\n sweepego2global[:3, -1] = sweepego2global_tran\n\n # global sensor to cur ego\n w, x, y, z = key_info[cam]['ego_pose']['rotation']\n keyego2global_rot = torch.Tensor(\n Quaternion(w, x, y, z).rotation_matrix)\n keyego2global_tran = torch.Tensor(\n key_info[cam]['ego_pose']['translation'])\n keyego2global = keyego2global_rot.new_zeros((4, 4))\n keyego2global[3, 3] = 1\n keyego2global[:3, :3] = keyego2global_rot\n keyego2global[:3, -1] = keyego2global_tran\n global2keyego = keyego2global.inverse()\n\n # cur ego to sensor\n w, x, y, z = key_info[cam]['calibrated_sensor']['rotation']\n keysensor2keyego_rot = torch.Tensor(\n Quaternion(w, x, y, z).rotation_matrix)\n keysensor2keyego_tran = torch.Tensor(\n key_info[cam]['calibrated_sensor']['translation'])\n keysensor2keyego = keysensor2keyego_rot.new_zeros((4, 4))\n keysensor2keyego[3, 3] = 1\n keysensor2keyego[:3, :3] = keysensor2keyego_rot\n keysensor2keyego[:3, -1] = keysensor2keyego_tran\n keyego2keysensor = keysensor2keyego.inverse()\n keysensor2sweepsensor = (\n keyego2keysensor @ global2keyego @ sweepego2global\n @ sweepsensor2sweepego).inverse()\n sweepsensor2keyego = global2keyego @ sweepego2global @\\\n sweepsensor2sweepego\n sensor2ego_mats.append(sweepsensor2keyego)\n sensor2sensor_mats.append(keysensor2sweepsensor)\n intrin_mat = torch.zeros((4, 4))\n intrin_mat[3, 3] = 1\n intrin_mat[:3, :3] = torch.Tensor(\n cam_info[cam]['calibrated_sensor']['camera_intrinsic'])\n\n file_name = os.path.split(cam_info[cam]['filename'])[-1]\n if self.return_depth:\n point_depth = np.fromfile(os.path.join(\n self.data_root, self.depth_path, f'{file_name}.bin'),\n dtype=np.float32,\n count=-1)\n point_depth = point_depth.reshape(-1, 3)\n point_depth_augmented = self.depth_transform(\n point_depth, resize, self.ida_aug_conf['final_dim'],\n crop, flip, rotate_ida)\n gt_depths.append(point_depth_augmented)\n\n if self.return_radar_pv:\n radar_point = np.fromfile(os.path.join(\n self.data_root, self.radar_pv_path, f'{file_name}.bin'),\n dtype=np.float32,\n count=-1).reshape(-1, 7)\n radar_point_augmented = self.transform_radar_pv(\n radar_point, resize, self.ida_aug_conf['final_dim'],\n crop, flip, rotate_ida, radar_idx)\n radar_points.append(radar_point_augmented)\n\n img, ida_mat = img_transform(\n img,\n resize=resize,\n resize_dims=resize_dims,\n crop=crop,\n flip=flip,\n rotate=rotate_ida,\n )\n ida_mats.append(ida_mat)\n img = mmcv.imnormalize(np.array(img), self.img_mean,\n self.img_std, self.to_rgb)\n img = torch.from_numpy(img).permute(2, 0, 1)\n imgs.append(img)\n intrin_mats.append(intrin_mat)\n timestamps.append(cam_info[cam]['timestamp'])\n sweep_imgs.append(torch.stack(imgs))\n sweep_sensor2ego_mats.append(torch.stack(sensor2ego_mats))\n sweep_intrin_mats.append(torch.stack(intrin_mats))\n sweep_ida_mats.append(torch.stack(ida_mats))\n sweep_sensor2sensor_mats.append(torch.stack(sensor2sensor_mats))\n sweep_timestamps.append(torch.tensor(timestamps))\n if self.return_depth:\n sweep_gt_depths.append(torch.stack(gt_depths))\n if self.return_radar_pv:\n sweep_radar_points.append(torch.stack(radar_points))\n\n ret_list = [\n torch.stack(sweep_imgs).permute(1, 0, 2, 3, 4),\n torch.stack(sweep_sensor2ego_mats).permute(1, 0, 2, 3),\n torch.stack(sweep_intrin_mats).permute(1, 0, 2, 3),\n torch.stack(sweep_ida_mats).permute(1, 0, 2, 3),\n torch.stack(sweep_sensor2sensor_mats).permute(1, 0, 2, 3),\n torch.stack(sweep_timestamps).permute(1, 0),\n ]\n if self.return_depth:\n ret_list.append(torch.stack(sweep_gt_depths).permute(1, 0, 2, 3),)\n else:\n ret_list.append(None)\n if self.return_radar_pv:\n ret_list.append(torch.stack(sweep_radar_points).permute(1, 0, 2, 3),)\n else:\n ret_list.append(None)\n return ret_list\n\n def get_image_meta(self, cam_infos, cams):\n key_info = cam_infos[0]\n\n # Get mean pose of all cams.\n ego2global_rotation = np.mean(\n [key_info[cam]['ego_pose']['rotation'] for cam in cams], 0)\n ego2global_translation = np.mean(\n [key_info[cam]['ego_pose']['translation'] for cam in cams], 0)\n img_metas = dict(\n box_type_3d=LiDARInstance3DBoxes,\n ego2global_translation=ego2global_translation,\n ego2global_rotation=ego2global_rotation,\n )\n return img_metas\n\n def get_image_sensor2ego_mats(self, cam_infos, cams):\n sweep_sensor2ego_mats = list()\n for cam in cams:\n sensor2ego_mats = list()\n key_info = cam_infos[0]\n for sweep_idx, cam_info in enumerate(cam_infos):\n w, x, y, z = cam_info[cam]['calibrated_sensor']['rotation']\n # sweep sensor to sweep ego\n sweepsensor2sweepego_rot = torch.Tensor(\n Quaternion(w, x, y, z).rotation_matrix)\n sweepsensor2sweepego_tran = torch.Tensor(\n cam_info[cam]['calibrated_sensor']['translation'])\n sweepsensor2sweepego = sweepsensor2sweepego_rot.new_zeros(\n (4, 4))\n sweepsensor2sweepego[3, 3] = 1\n sweepsensor2sweepego[:3, :3] = sweepsensor2sweepego_rot\n sweepsensor2sweepego[:3, -1] = sweepsensor2sweepego_tran\n # sweep ego to global\n w, x, y, z = cam_info[cam]['ego_pose']['rotation']\n sweepego2global_rot = torch.Tensor(\n Quaternion(w, x, y, z).rotation_matrix)\n sweepego2global_tran = torch.Tensor(\n cam_info[cam]['ego_pose']['translation'])\n sweepego2global = sweepego2global_rot.new_zeros((4, 4))\n sweepego2global[3, 3] = 1\n sweepego2global[:3, :3] = sweepego2global_rot\n sweepego2global[:3, -1] = sweepego2global_tran\n\n # global sensor to cur ego\n w, x, y, z = key_info[cam]['ego_pose']['rotation']\n keyego2global_rot = torch.Tensor(\n Quaternion(w, x, y, z).rotation_matrix)\n keyego2global_tran = torch.Tensor(\n key_info[cam]['ego_pose']['translation'])\n keyego2global = keyego2global_rot.new_zeros((4, 4))\n keyego2global[3, 3] = 1\n keyego2global[:3, :3] = keyego2global_rot\n keyego2global[:3, -1] = keyego2global_tran\n global2keyego = keyego2global.inverse()\n\n # cur ego to sensor\n w, x, y, z = key_info[cam]['calibrated_sensor']['rotation']\n keysensor2keyego_rot = torch.Tensor(\n Quaternion(w, x, y, z).rotation_matrix)\n keysensor2keyego_tran = torch.Tensor(\n key_info[cam]['calibrated_sensor']['translation'])\n keysensor2keyego = keysensor2keyego_rot.new_zeros((4, 4))\n keysensor2keyego[3, 3] = 1\n keysensor2keyego[:3, :3] = keysensor2keyego_rot\n keysensor2keyego[:3, -1] = keysensor2keyego_tran\n sweepsensor2keyego = global2keyego @ sweepego2global @\\\n sweepsensor2sweepego\n sensor2ego_mats.append(sweepsensor2keyego)\n sweep_sensor2ego_mats.append(torch.stack(sensor2ego_mats))\n return torch.stack(sweep_sensor2ego_mats).permute(1, 0, 2, 3)\n\n def get_gt(self, info, cams, return_corners=False):\n \"\"\"Generate gt labels from info.\n\n Args:\n info(dict): Infos needed to generate gt labels.\n cams(list): Camera names.\n\n Returns:\n Tensor: GT bboxes.\n Tensor: GT labels.\n \"\"\"\n ego2global_rotation = np.mean(\n [info['cam_infos'][cam]['ego_pose']['rotation'] for cam in cams],\n 0)\n ego2global_translation = np.mean([\n info['cam_infos'][cam]['ego_pose']['translation'] for cam in cams\n ], 0)\n trans = -np.array(ego2global_translation)\n rot = Quaternion(ego2global_rotation).inverse\n gt_boxes = list()\n gt_labels = list()\n if return_corners: # for debugging and visualization\n gt_corners = list()\n else:\n gt_corners = None\n for ann_info in info['ann_infos']:\n # Use ego coordinate.\n if self.gt_for_radar_only:\n if ann_info['num_radar_pts'] == 0:\n continue\n if map_name_from_general_to_detection[ann_info['category_name']] not in self.classes:\n continue\n if ann_info['num_lidar_pts'] + ann_info['num_radar_pts'] == 0:\n continue\n\n box = Box(\n ann_info['translation'],\n ann_info['size'],\n Quaternion(ann_info['rotation']),\n velocity=ann_info['velocity'],\n )\n box.translate(trans)\n box.rotate(rot)\n box_xyz = np.array(box.center)\n box_dxdydz = np.array(box.wlh)[[1, 0, 2]]\n box_yaw = np.array([box.orientation.yaw_pitch_roll[0]])\n box_velo = np.array(box.velocity[:2])\n gt_box = np.concatenate([box_xyz, box_dxdydz, box_yaw, box_velo])\n gt_boxes.append(gt_box)\n gt_labels.append(\n self.classes.index(map_name_from_general_to_detection[\n ann_info['category_name']]))\n if return_corners: # for debugging and visualization\n gt_corners.append(box.corners())\n\n return torch.Tensor(gt_boxes), torch.tensor(gt_labels), gt_corners\n\n def choose_cams(self):\n \"\"\"Choose cameras randomly.\n\n Returns:\n list: Cameras to be used.\n \"\"\"\n if self.is_train and self.ida_aug_conf['Ncams'] < len(\n self.ida_aug_conf['cams']):\n cams = np.random.choice(self.ida_aug_conf['cams'],\n self.ida_aug_conf['Ncams'],\n replace=False)\n else:\n cams = self.ida_aug_conf['cams']\n return cams\n\n def __getitem__(self, idx):\n if self.use_cbgs:\n idx = self.sample_indices[idx]\n cam_infos = list()\n pts_infos = list()\n cams = self.choose_cams()\n for key_idx in self.key_idxes:\n cur_idx = key_idx + idx\n # Handle scenarios when current idx doesn't have previous key\n # frame or previous key frame is from another scene.\n while self.infos[cur_idx]['scene_token'] != self.infos[idx]['scene_token']:\n cur_idx += 1\n info = self.infos[cur_idx]\n cam_infos.append(info['cam_infos'])\n pts_infos.append([info['lidar_infos']] + info['lidar_sweeps'])\n for sweep_idx in self.sweeps_idx:\n if len(info['cam_sweeps']) == 0:\n cam_infos.append(info['cam_infos'])\n else:\n # Handle scenarios when current sweep doesn't have all cam keys.\n for i in range(min(len(info['cam_sweeps']) - 1, sweep_idx), -1,\n -1):\n if sum([cam in info['cam_sweeps'][i]\n for cam in cams]) == len(cams):\n cam_infos.append(info['cam_sweeps'][i])\n break\n\n if self.return_image or self.return_depth or self.return_radar_pv:\n image_data_list = self.get_image(cam_infos, cams)\n (\n sweep_imgs,\n sweep_sensor2ego_mats,\n sweep_intrins,\n sweep_ida_mats,\n sweep_sensor2sensor_mats,\n sweep_timestamps,\n ) = image_data_list[:6]\n else:\n (\n sweep_imgs,\n sweep_intrins,\n sweep_ida_mats,\n sweep_sensor2sensor_mats,\n sweep_timestamps,\n ) = None, None, None, None, None\n sweep_sensor2ego_mats = self.get_image_sensor2ego_mats(cam_infos, cams)\n\n img_metas = self.get_image_meta(cam_infos, cams)\n img_metas['token'] = self.infos[idx]['sample_token']\n gt_boxes_3d, gt_labels_3d, gt_corners = self.get_gt(self.infos[idx], cams, return_corners=False)\n\n rotate_bda, scale_bda, flip_dx, flip_dy = self.sample_bda_augmentation()\n gt_boxes_3d, bda_rot = bev_det_transform(gt_boxes_3d, rotate_bda, scale_bda, flip_dx, flip_dy)\n\n bda_mat = torch.zeros(4, 4, dtype=torch.float32)\n bda_mat[:3, :3] = bda_rot\n bda_mat[3, 3] = 1\n\n ret_list = [\n sweep_imgs,\n sweep_sensor2ego_mats,\n sweep_intrins,\n sweep_ida_mats,\n sweep_sensor2sensor_mats,\n bda_mat,\n sweep_timestamps,\n img_metas,\n gt_boxes_3d,\n gt_labels_3d,\n ]\n\n if self.return_depth:\n ret_list.append(image_data_list[6])\n else:\n ret_list.append(None)\n if self.return_radar_pv:\n ret_list.append(image_data_list[7])\n else:\n ret_list.append(None)\n\n return ret_list\n\n def __str__(self):\n return f\"\"\"NuscData: {len(self)} samples. Split: \\\n {\"train\" if self.is_train else \"val\"}.\n Augmentation Conf: {self.ida_aug_conf}\"\"\"\n\n def __len__(self):\n if self.use_cbgs:\n return len(self.sample_indices)\n else:\n return len(self.infos)" }, { "identifier": "collate_fn", "path": "datasets/nusc_det_dataset.py", "snippet": "def collate_fn(data,\n is_return_image=True,\n is_return_depth=False,\n is_return_radar_pv=False):\n assert (is_return_image or is_return_depth or is_return_radar_pv) is True\n imgs_batch = list()\n sensor2ego_mats_batch = list()\n intrin_mats_batch = list()\n ida_mats_batch = list()\n sensor2sensor_mats_batch = list()\n bda_mat_batch = list()\n gt_boxes_3d_batch = list()\n gt_labels_3d_batch = list()\n img_metas_batch = list()\n depth_labels_batch = list()\n radar_pv_batch = list()\n\n for iter_data in data:\n (\n sweep_imgs,\n sweep_sensor2ego_mats,\n sweep_intrins,\n sweep_ida_mats,\n sweep_sensor2sensor_mats,\n bda_mat,\n sweep_timestamps,\n img_metas,\n gt_boxes,\n gt_labels,\n ) = iter_data[:10]\n if is_return_depth:\n gt_depth = iter_data[10]\n depth_labels_batch.append(gt_depth)\n if is_return_radar_pv:\n radar_pv = iter_data[11]\n radar_pv_batch.append(radar_pv)\n\n imgs_batch.append(sweep_imgs)\n sensor2ego_mats_batch.append(sweep_sensor2ego_mats)\n intrin_mats_batch.append(sweep_intrins)\n ida_mats_batch.append(sweep_ida_mats)\n sensor2sensor_mats_batch.append(sweep_sensor2sensor_mats)\n bda_mat_batch.append(bda_mat)\n img_metas_batch.append(img_metas)\n gt_boxes_3d_batch.append(gt_boxes)\n gt_labels_3d_batch.append(gt_labels)\n\n if is_return_image:\n mats_dict = dict()\n mats_dict['sensor2ego_mats'] = torch.stack(sensor2ego_mats_batch)\n mats_dict['intrin_mats'] = torch.stack(intrin_mats_batch)\n mats_dict['ida_mats'] = torch.stack(ida_mats_batch)\n mats_dict['sensor2sensor_mats'] = torch.stack(sensor2sensor_mats_batch)\n mats_dict['bda_mat'] = torch.stack(bda_mat_batch)\n ret_list = [\n torch.stack(imgs_batch),\n mats_dict,\n img_metas_batch,\n gt_boxes_3d_batch,\n gt_labels_3d_batch,\n None, # reserve for segmentation\n ]\n else:\n ret_list = [\n None,\n None,\n img_metas_batch,\n gt_boxes_3d_batch,\n gt_labels_3d_batch,\n None,\n ]\n if is_return_depth:\n ret_list.append(torch.stack(depth_labels_batch))\n else:\n ret_list.append(None)\n if is_return_radar_pv:\n ret_list.append(torch.stack(radar_pv_batch))\n else:\n ret_list.append(None)\n\n return ret_list" }, { "identifier": "DetNuscEvaluator", "path": "evaluators/det_evaluators.py", "snippet": "class DetNuscEvaluator():\n ErrNameMapping = {\n 'trans_err': 'mATE',\n 'scale_err': 'mASE',\n 'orient_err': 'mAOE',\n 'vel_err': 'mAVE',\n 'attr_err': 'mAAE',\n }\n\n DefaultAttribute = {\n 'car': 'vehicle.parked',\n 'pedestrian': 'pedestrian.moving',\n 'trailer': 'vehicle.parked',\n 'truck': 'vehicle.parked',\n 'bus': 'vehicle.moving',\n 'motorcycle': 'cycle.without_rider',\n 'construction_vehicle': 'vehicle.parked',\n 'bicycle': 'cycle.without_rider',\n 'barrier': '',\n 'traffic_cone': '',\n }\n\n def __init__(\n self,\n class_names,\n eval_version='detection_cvpr_2019',\n data_root='./data/nuScenes',\n version='v1.0-trainval',\n modality=dict(use_lidar=False,\n use_camera=True,\n use_radar=True,\n use_map=False,\n use_external=False),\n output_dir=None,\n ) -> None:\n self.eval_version = eval_version\n self.data_root = data_root\n\n # Load config file and deserialize it.\n this_dir = osp.dirname(osp.abspath(__file__))\n with open(osp.join(this_dir, 'configs', '%s.json' % eval_version), 'r') as f:\n data = json.load(f)\n self.eval_detection_configs = DetectionConfig.deserialize(data)\n\n self.version = version\n self.class_names = class_names\n self.modality = modality\n self.output_dir = output_dir\n\n def _evaluate_single(self,\n result_path,\n logger=None,\n metric='bbox',\n result_name='pts_bbox'):\n \"\"\"Evaluation for a single model in nuScenes protocol.\n\n Args:\n result_path (str): Path of the result file.\n logger (logging.Logger | str | None): Logger used for printing\n related information during evaluation. Default: None.\n metric (str): Metric name used for evaluation. Default: 'bbox'.\n result_name (str): Result name in the metric prefix.\n Default: 'pts_bbox'.\n\n Returns:\n dict: Dictionary of evaluation details.\n \"\"\"\n from nuscenes import NuScenes\n from nuscenes.eval.detection.evaluate import NuScenesEval\n\n output_dir = osp.join(*osp.split(result_path)[:-1])\n nusc = NuScenes(version=self.version,\n dataroot=self.data_root,\n verbose=False)\n eval_set_map = {\n 'v1.0-mini': 'mini_val',\n 'v1.0-trainval': 'val',\n }\n nusc_eval = NuScenesEval(nusc,\n config=self.eval_detection_configs,\n result_path=result_path,\n eval_set=eval_set_map[self.version],\n output_dir=output_dir,\n verbose=False)\n nusc_eval.main(render_curves=False)\n # nusc_eval.main(render_curves=True, plot_examples=40)\n\n # record metrics\n metrics = mmcv.load(osp.join(output_dir, 'metrics_summary.json'))\n detail = dict()\n metric_prefix = f'{result_name}_NuScenes'\n for class_name in self.class_names:\n for k, v in metrics['label_aps'][class_name].items():\n val = float('{:.4f}'.format(v))\n detail['{}/{}_AP_dist_{}'.format(metric_prefix, class_name,\n k)] = val\n for k, v in metrics['label_tp_errors'][class_name].items():\n val = float('{:.4f}'.format(v))\n detail['{}/{}_{}'.format(metric_prefix, class_name, k)] = val\n for k, v in metrics['tp_errors'].items():\n val = float('{:.4f}'.format(v))\n detail['{}/{}'.format(metric_prefix,\n self.ErrNameMapping[k])] = val\n\n detail['{}/NDS'.format(metric_prefix)] = metrics['nd_score']\n detail['{}/mAP'.format(metric_prefix)] = metrics['mean_ap']\n return detail\n\n def format_results(self,\n results,\n img_metas,\n result_names=['img_bbox'],\n jsonfile_prefix=None,\n **kwargs):\n \"\"\"Format the results to json (standard format for COCO evaluation).\n\n Args:\n results (list[tuple | numpy.ndarray]): Testing results of the\n dataset.\n jsonfile_prefix (str | None): The prefix of json files. It includes\n the file path and the prefix of filename, e.g., \"a/b/prefix\".\n If not specified, a temp file will be created. Default: None.\n\n Returns:\n tuple: (result_files, tmp_dir), result_files is a dict containing \\\n the json filepaths, tmp_dir is the temporal directory created \\\n for saving json files when jsonfile_prefix is not specified.\n \"\"\"\n assert isinstance(results, list), 'results must be a list'\n\n if jsonfile_prefix is None:\n tmp_dir = tempfile.TemporaryDirectory()\n jsonfile_prefix = osp.join(tmp_dir.name, 'results')\n else:\n tmp_dir = None\n\n # currently the output prediction results could be in two formats\n # 1. list of dict('boxes_3d': ..., 'scores_3d': ..., 'labels_3d': ...)\n # 2. list of dict('pts_bbox' or 'img_bbox':\n # dict('boxes_3d': ..., 'scores_3d': ..., 'labels_3d': ...))\n # this is a workaround to enable evaluation of both formats on nuScenes\n # refer to https://github.com/open-mmlab/mmdetection3d/issues/449\n # should take the inner dict out of 'pts_bbox' or 'img_bbox' dict\n result_files = dict()\n # refactor this.\n for rasult_name in result_names:\n # not evaluate 2D predictions on nuScenes\n if '2d' in rasult_name:\n continue\n print(f'\\nFormating bboxes of {rasult_name}')\n tmp_file_ = osp.join(jsonfile_prefix, rasult_name)\n if self.output_dir:\n result_files.update({\n rasult_name:\n self._format_bbox(results, img_metas, self.output_dir)\n })\n else:\n result_files.update({\n rasult_name:\n self._format_bbox(results, img_metas, tmp_file_)\n })\n return result_files, tmp_dir\n\n def evaluate(\n self,\n results,\n img_metas,\n metric='bbox',\n logger=None,\n jsonfile_prefix=None,\n result_names=['img_bbox'],\n show=False,\n out_dir=None,\n pipeline=None,\n ):\n \"\"\"Evaluation in nuScenes protocol.\n\n Args:\n results (list[dict]): Testing results of the dataset.\n metric (str | list[str]): Metrics to be evaluated.\n logger (logging.Logger | str | None): Logger used for printing\n related information during evaluation. Default: None.\n jsonfile_prefix (str | None): The prefix of json files. It includes\n the file path and the prefix of filename, e.g., \"a/b/prefix\".\n If not specified, a temp file will be created. Default: None.\n show (bool): Whether to visualize.\n Default: False.\n out_dir (str): Path to save the visualization results.\n Default: None.\n pipeline (list[dict], optional): raw data loading for showing.\n Default: None.\n\n Returns:\n dict[str, float]: Results of each evaluation metric.\n \"\"\"\n result_files, tmp_dir = self.format_results(results, img_metas,\n result_names,\n jsonfile_prefix)\n if isinstance(result_files, dict):\n for name in result_names:\n print('Evaluating bboxes of {}'.format(name))\n print()\n self._evaluate_single(result_files[name])\n elif isinstance(result_files, str):\n self._evaluate_single(result_files)\n\n if tmp_dir is not None:\n tmp_dir.cleanup()\n\n def _format_bbox(self, results, img_metas, jsonfile_prefix=None):\n \"\"\"Convert the results to the standard format.\n\n Args:\n results (list[dict]): Testing results of the dataset.\n jsonfile_prefix (str): The prefix of the output jsonfile.\n You can specify the output directory/filename by\n modifying the jsonfile_prefix. Default: None.\n\n Returns:\n str: Path of the output json file.\n \"\"\"\n nusc_annos = {}\n mapped_class_names = self.class_names\n\n print('Start to convert detection format...')\n\n for sample_id, det in enumerate(mmcv.track_iter_progress(results)):\n boxes, scores, labels = det\n\n order = np.argsort(scores)[::-1]\n order = order[:500]\n\n boxes = boxes[order]\n scores = scores[order]\n labels = labels[order]\n\n sample_token = img_metas[sample_id]['token']\n trans = np.array(img_metas[sample_id]['ego2global_translation'])\n rot = Quaternion(img_metas[sample_id]['ego2global_rotation'])\n annos = list()\n for i, box in enumerate(boxes):\n name = mapped_class_names[labels[i]]\n center = box[:3]\n wlh = box[[4, 3, 5]]\n box_yaw = box[6]\n box_vel = box[7:].tolist()\n box_vel.append(0)\n quat = pyquaternion.Quaternion(axis=[0, 0, 1], radians=box_yaw)\n nusc_box = Box(center, wlh, quat, velocity=box_vel)\n nusc_box.rotate(rot)\n nusc_box.translate(trans)\n if np.sqrt(nusc_box.velocity[0]**2 +\n nusc_box.velocity[1]**2) > 0.2:\n if name in [\n 'car',\n 'construction_vehicle',\n 'bus',\n 'truck',\n 'trailer',\n ]:\n attr = 'vehicle.moving'\n elif name in ['bicycle', 'motorcycle']:\n attr = 'cycle.with_rider'\n else:\n attr = self.DefaultAttribute[name]\n else:\n if name in ['pedestrian']:\n attr = 'pedestrian.standing'\n elif name in ['bus']:\n attr = 'vehicle.stopped'\n else:\n attr = self.DefaultAttribute[name]\n nusc_anno = dict(\n sample_token=sample_token,\n translation=nusc_box.center.tolist(),\n size=nusc_box.wlh.tolist(),\n rotation=nusc_box.orientation.elements.tolist(),\n velocity=nusc_box.velocity[:2],\n detection_name=name,\n detection_score=float(scores[i]),\n attribute_name=attr,\n )\n annos.append(nusc_anno)\n # other views results of the same frame should be concatenated\n if sample_token in nusc_annos:\n nusc_annos[sample_token].extend(annos)\n else:\n nusc_annos[sample_token] = annos\n nusc_submissions = {\n 'meta': self.modality,\n 'results': nusc_annos,\n }\n mmcv.mkdir_or_exist(jsonfile_prefix)\n res_path = osp.join(jsonfile_prefix, 'results_nusc.json')\n print('Results writes to', res_path)\n mmcv.dump(nusc_submissions, res_path)\n return res_path" }, { "identifier": "BaseBEVDepth", "path": "models/base_bev_depth.py", "snippet": "class BaseBEVDepth(nn.Module):\n \"\"\"Source code of `BEVDepth`, `https://arxiv.org/abs/2112.11790`.\n\n Args:\n backbone_conf (dict): Config of backbone.\n head_conf (dict): Config of head.\n \"\"\"\n\n def __init__(self, backbone_conf, head_conf):\n super(BaseBEVDepth, self).__init__()\n self.backbone_img = BaseLSSFPN(**backbone_conf)\n self.head = BEVDepthHead(**head_conf)\n\n # for inference time measurement\n self.idx = 0\n self.times_dict = {\n 'img': [],\n 'img_backbone': [],\n 'img_dep': [],\n 'img_transform': [],\n 'img_pool': [],\n\n 'head': [],\n 'head_backbone': [],\n 'head_head': [],\n }\n\n def forward(self,\n sweep_imgs,\n mats_dict,\n is_train=False\n ):\n \"\"\"Forward function for BEVDepth\n\n Args:\n sweep_imgs (Tensor): Input images.\n mats_dict(dict):\n sensor2ego_mats(Tensor): Transformation matrix from\n camera to ego with shape of (B, num_sweeps,\n num_cameras, 4, 4).\n intrin_mats(Tensor): Intrinsic matrix with shape\n of (B, num_sweeps, num_cameras, 4, 4).\n ida_mats(Tensor): Transformation matrix for ida with\n shape of (B, num_sweeps, num_cameras, 4, 4).\n sensor2sensor_mats(Tensor): Transformation matrix\n from key frame camera to sweep frame camera with\n shape of (B, num_sweeps, num_cameras, 4, 4).\n bda_mat(Tensor): Rotation matrix for bda with shape\n of (B, 4, 4).\n\n Returns:\n tuple(list[dict]): Output results for tasks.\n \"\"\"\n if is_train:\n self.time = None\n\n x, depth, _ = self.backbone_img(sweep_imgs, mats_dict,\n is_return_depth=True)\n preds, _ = self.head(x)\n return preds, depth\n else:\n if self.idx < 100: # skip few iterations for warmup\n self.times = None\n elif self.idx == 100:\n self.times = self.times_dict\n\n x, self.times = self.backbone_img(sweep_imgs, mats_dict,\n times=self.times)\n preds, self.times = self.head(x, times=self.times)\n\n if self.idx == 1000:\n time_mean = {}\n for k, v in self.times.items():\n time_mean[k] = sum(v) / len(v)\n print('img: %.2f' % time_mean['img'])\n print(' img_backbone: %.2f' % time_mean['img_backbone'])\n print(' img_dep: %.2f' % time_mean['img_dep'])\n print(' img_transform: %.2f' % time_mean['img_transform'])\n print(' img_pool: %.2f' % time_mean['img_pool'])\n print('head: %.2f' % time_mean['head'])\n print(' head_backbone: %.2f' % time_mean['head_backbone'])\n print(' head_head: %.2f' % time_mean['head_head'])\n total = time_mean['img'] + time_mean['head']\n print('total: %.2f' % total)\n print(' ')\n print('FPS: %.2f' % (1000/total))\n\n self.idx += 1\n return preds\n\n def get_targets(self, gt_boxes, gt_labels):\n \"\"\"Generate training targets for a single sample.\n\n Args:\n gt_bboxes_3d (:obj:`LiDARInstance3DBoxes`): Ground truth gt boxes.\n gt_labels_3d (torch.Tensor): Labels of boxes.\n\n Returns:\n tuple[list[torch.Tensor]]: Tuple of target including \\\n the following results in order.\n\n - list[torch.Tensor]: Heatmap scores.\n - list[torch.Tensor]: Ground truth boxes.\n - list[torch.Tensor]: Indexes indicating the position \\\n of the valid boxes.\n - list[torch.Tensor]: Masks indicating which boxes \\\n are valid.\n \"\"\"\n return self.head.get_targets(gt_boxes, gt_labels)\n\n def loss(self, targets, preds_dicts):\n \"\"\"Loss function for BEVDepth.\n\n Args:\n gt_bboxes_3d (list[:obj:`LiDARInstance3DBoxes`]): Ground\n truth gt boxes.\n gt_labels_3d (list[torch.Tensor]): Labels of boxes.\n preds_dicts (dict): Output of forward function.\n\n Returns:\n dict[str:torch.Tensor]: Loss of heatmap and bbox of each task.\n \"\"\"\n return self.head.loss(targets, preds_dicts)\n\n def get_bboxes(self, preds_dicts, img_metas=None, img=None, rescale=False):\n \"\"\"Generate bboxes from bbox head predictions.\n\n Args:\n preds_dicts (tuple[list[dict]]): Prediction results.\n img_metas (list[dict]): Point cloud and image's meta info.\n\n Returns:\n list[dict]: Decoded bbox, scores and labels after nms.\n \"\"\"\n return self.head.get_bboxes(preds_dicts, img_metas, img, rescale)" }, { "identifier": "all_gather_object", "path": "utils/torch_dist.py", "snippet": "def all_gather_object(obj):\n world_size = get_world_size()\n if world_size < 2:\n return [obj]\n output = [None for _ in range(world_size)]\n dist.all_gather_object(output, obj)\n return output" }, { "identifier": "synchronize", "path": "utils/torch_dist.py", "snippet": "def synchronize():\n \"\"\"Helper function to synchronize (barrier)\n among all processes when using distributed training\"\"\"\n if not dist.is_available():\n return\n if not dist.is_initialized():\n return\n current_world_size = dist.get_world_size()\n if current_world_size == 1:\n return\n dist.barrier()" } ]
from functools import partial from pytorch_lightning.core import LightningModule from torch.cuda.amp.autocast_mode import autocast from torch.optim.lr_scheduler import MultiStepLR from mmcv.runner import build_optimizer from datasets.nusc_det_dataset import NuscDatasetRadarDet, collate_fn from evaluators.det_evaluators import DetNuscEvaluator from models.base_bev_depth import BaseBEVDepth from utils.torch_dist import all_gather_object, synchronize import mmcv import torch import torch.nn.functional as F import torch.nn.parallel import torch.utils.data import torch.utils.data.distributed import torchvision.models as models
16,087
def forward(self, sweep_imgs, mats, is_train=False, **inputs): return self.model(sweep_imgs, mats, is_train=is_train) def training_step(self, batch): if self.global_rank == 0: for pg in self.trainer.optimizers[0].param_groups: self.log('learning_rate', pg["lr"]) (sweep_imgs, mats, _, gt_boxes_3d, gt_labels_3d, _, depth_labels, pts_pv) = batch if torch.cuda.is_available(): if self.return_image: sweep_imgs = sweep_imgs.cuda() for key, value in mats.items(): mats[key] = value.cuda() if self.return_radar_pv: pts_pv = pts_pv.cuda() gt_boxes_3d = [gt_box.cuda() for gt_box in gt_boxes_3d] gt_labels_3d = [gt_label.cuda() for gt_label in gt_labels_3d] preds, depth_preds = self(sweep_imgs, mats, pts_pv=pts_pv, is_train=True) targets = self.model.get_targets(gt_boxes_3d, gt_labels_3d) loss_detection, loss_heatmap, loss_bbox = self.model.loss(targets, preds) if len(depth_labels.shape) == 5: # only key-frame will calculate depth loss depth_labels = depth_labels[:, 0, ...].contiguous() loss_depth = self.get_depth_loss(depth_labels.cuda(), depth_preds) self.log('train/detection', loss_detection) self.log('train/heatmap', loss_heatmap) self.log('train/bbox', loss_bbox) self.log('train/depth', loss_depth) return loss_detection + loss_depth def get_depth_loss(self, depth_labels, depth_preds, weight=3.): depth_labels = self.get_downsampled_gt_depth(depth_labels) depth_preds = depth_preds.permute(0, 2, 3, 1).contiguous().view( -1, self.depth_channels) fg_mask = torch.max(depth_labels, dim=1).values > 0.0 with autocast(enabled=False): loss_depth = (F.binary_cross_entropy( depth_preds[fg_mask], depth_labels[fg_mask], reduction='none', ).sum() / max(1.0, fg_mask.sum())) return weight * loss_depth def get_downsampled_gt_depth(self, gt_depths): """ Input: gt_depths: [B, N, H, W] Output: gt_depths: [B*N*h*w, d] """ B, N, H, W = gt_depths.shape gt_depths = gt_depths.view( B * N, H // self.downsample_factor, self.downsample_factor, W // self.downsample_factor, self.downsample_factor, 1, ) gt_depths = gt_depths.permute(0, 1, 3, 5, 2, 4).contiguous() gt_depths = gt_depths.view( -1, self.downsample_factor * self.downsample_factor) gt_depths_tmp = torch.where(gt_depths == 0.0, 1e5 * torch.ones_like(gt_depths), gt_depths) gt_depths = torch.min(gt_depths_tmp, dim=-1).values gt_depths = gt_depths.view(B * N, H // self.downsample_factor, W // self.downsample_factor) gt_depths = (gt_depths - (self.dbound[0] - self.dbound[2])) / self.dbound[2] gt_depths = torch.where( (gt_depths < self.depth_channels + 1) & (gt_depths > 0.), gt_depths, torch.zeros_like(gt_depths)) gt_depths = F.one_hot(gt_depths.long(), num_classes=self.depth_channels + 1).view( -1, self.depth_channels + 1)[:, 1:] return gt_depths.float() def eval_step(self, batch, batch_idx, prefix: str): (sweep_imgs, mats, img_metas, _, _, _, _, pts_pv) = batch if torch.cuda.is_available(): if self.return_image: sweep_imgs = sweep_imgs.cuda() for key, value in mats.items(): mats[key] = value.cuda() if self.return_radar_pv: pts_pv = pts_pv.cuda() preds = self(sweep_imgs, mats, pts_pv=pts_pv, is_train=False) if isinstance(self.model, torch.nn.parallel.DistributedDataParallel): results = self.model.module.get_bboxes(preds, img_metas) else: results = self.model.get_bboxes(preds, img_metas) for i in range(len(results)): results[i][0] = results[i][0].tensor.detach().cpu().numpy() results[i][1] = results[i][1].detach().cpu().numpy() results[i][2] = results[i][2].detach().cpu().numpy() results[i].append(img_metas[i]) return results def validation_epoch_end(self, validation_step_outputs): detection_losses = list() heatmap_losses = list() bbox_losses = list() depth_losses = list() for validation_step_output in validation_step_outputs: detection_losses.append(validation_step_output[0]) heatmap_losses.append(validation_step_output[1]) bbox_losses.append(validation_step_output[2]) depth_losses.append(validation_step_output[3])
# Copyright (c) Megvii Inc. All rights reserved. pretrain_config = dict( img_model_path=None, img_load_key=[], img_freeze_key=None, pts_model_path=None, pts_load_key=[]) optimizer_config = dict( type='AdamW', lr=2e-4, weight_decay=1e-2) H = 900 W = 1600 final_dim = (256, 704) img_conf = dict(img_mean=[123.675, 116.28, 103.53], img_std=[58.395, 57.12, 57.375], to_rgb=True) ida_aug_conf = { 'resize_lim': (0.386, 0.55), 'final_dim': final_dim, 'rot_lim': (-5.4, 5.4), 'H': 900, 'W': 1600, 'rand_flip': True, 'bot_pct_lim': (0.0, 0.0), 'cams': ['CAM_FRONT_LEFT', 'CAM_FRONT', 'CAM_FRONT_RIGHT', 'CAM_BACK_LEFT', 'CAM_BACK', 'CAM_BACK_RIGHT'], 'Ncams': 6, } bda_aug_conf = { 'rot_ratio': 1.0, 'rot_lim': (-22.5, 22.5), 'scale_lim': (0.95, 1.05), 'flip_dx_ratio': 0.5, 'flip_dy_ratio': 0.5 } rda_aug_conf = { 'N_sweeps': 6, 'N_use': 5, 'drop_ratio': 0.1, } backbone_img_conf = { 'x_bound': [-51.2, 51.2, 0.8], 'y_bound': [-51.2, 51.2, 0.8], 'z_bound': [-5, 3, 8], 'd_bound': [2.0, 58.0, 0.8], 'final_dim': final_dim, 'output_channels': 80, 'downsample_factor': 16, 'img_backbone_conf': dict( type='ResNet', depth=50, frozen_stages=0, out_indices=[0, 1, 2, 3], norm_eval=False, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'), ), 'img_neck_conf': dict( type='SECONDFPN', in_channels=[256, 512, 1024, 2048], upsample_strides=[0.25, 0.5, 1, 2], out_channels=[128, 128, 128, 128], ), 'depth_net_conf': dict(in_channels=512, mid_channels=512), 'camera_aware': True } CLASSES = [ 'car', 'truck', 'construction_vehicle', 'bus', 'trailer', 'barrier', 'motorcycle', 'bicycle', 'pedestrian', 'traffic_cone', ] head_conf = { 'bev_backbone_conf': dict( type='ResNet', in_channels=80, depth=18, num_stages=3, strides=(1, 2, 2), dilations=(1, 1, 1), out_indices=[0, 1, 2], norm_eval=False, base_channels=160), 'bev_neck_conf': dict( type='SECONDFPN', in_channels=[80, 160, 320, 640], upsample_strides=[1, 2, 4, 8], out_channels=[64, 64, 64, 64]), 'tasks': [ dict(num_class=1, class_names=['car']), dict(num_class=2, class_names=['truck', 'construction_vehicle']), dict(num_class=2, class_names=['bus', 'trailer']), dict(num_class=1, class_names=['barrier']), dict(num_class=2, class_names=['motorcycle', 'bicycle']), dict(num_class=2, class_names=['pedestrian', 'traffic_cone']),], 'common_heads': dict( reg=(2, 2), height=(1, 2), dim=(3, 2), rot=(2, 2), vel=(2, 2)), 'bbox_coder': dict( type='CenterPointBBoxCoder', post_center_range=[-61.2, -61.2, -10.0, 61.2, 61.2, 10.0], max_num=500, score_threshold=0.1, out_size_factor=4, voxel_size=[0.2, 0.2, 8], pc_range=[-51.2, -51.2, -5, 51.2, 51.2, 3], code_size=9), 'train_cfg': dict( point_cloud_range=[-51.2, -51.2, -5, 51.2, 51.2, 3], grid_size=[512, 512, 1], voxel_size=[0.2, 0.2, 8], out_size_factor=4, dense_reg=1, gaussian_overlap=0.1, max_objs=500, min_radius=2, code_weights=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.5, 0.5]), 'test_cfg': dict( post_center_limit_range=[-61.2, -61.2, -10.0, 61.2, 61.2, 10.0], max_per_img=500, max_pool_nms=False, min_radius=[4, 12, 10, 1, 0.85, 0.175], score_threshold=0.1, out_size_factor=4, voxel_size=[0.2, 0.2, 8], nms_type='circle', pre_max_size=1000, post_max_size=83, nms_thr=0.2), 'in_channels': 256, # Equal to bev_neck output_channels. 'loss_cls': dict(type='GaussianFocalLoss', reduction='mean'), 'loss_bbox': dict(type='L1Loss', reduction='mean', loss_weight=0.25), 'gaussian_overlap': 0.1, 'min_radius': 2, } class BEVDepthLightningModel(LightningModule): MODEL_NAMES = sorted(name for name in models.__dict__ if name.islower() and not name.startswith('__') and callable(models.__dict__[name])) def __init__(self, gpus: int = 1, data_root='data/nuScenes', eval_interval=1, batch_size_per_device=8, class_names=CLASSES, backbone_img_conf=backbone_img_conf, head_conf=head_conf, ida_aug_conf=ida_aug_conf, bda_aug_conf=bda_aug_conf, rda_aug_conf=rda_aug_conf, default_root_dir='./outputs/', **kwargs): super().__init__() self.save_hyperparameters() self.gpus = gpus self.optimizer_config = optimizer_config self.pretrain_config = pretrain_config self.eval_interval = eval_interval self.batch_size_per_device = batch_size_per_device self.data_root = data_root self.class_names = class_names self.backbone_img_conf = backbone_img_conf self.head_conf = head_conf self.ida_aug_conf = ida_aug_conf self.bda_aug_conf = bda_aug_conf self.rda_aug_conf = rda_aug_conf mmcv.mkdir_or_exist(default_root_dir) self.default_root_dir = default_root_dir self.evaluator = DetNuscEvaluator(class_names=self.class_names, output_dir=self.default_root_dir) self.model = BaseBEVDepth(self.backbone_img_conf, self.head_conf) self.mode = 'valid' self.img_conf = img_conf self.data_use_cbgs = False self.load_interval = 1 self.num_sweeps = 1 self.sweep_idxes = list() self.key_idxes = list() self.data_return_depth = True self.downsample_factor = self.backbone_img_conf['downsample_factor'] self.dbound = self.backbone_img_conf['d_bound'] self.depth_channels = int( (self.dbound[1] - self.dbound[0]) / self.dbound[2]) self.use_fusion = False self.train_info_paths = 'data/nuScenes/nuscenes_infos_train.pkl' self.val_info_paths = 'data/nuScenes/nuscenes_infos_val.pkl' self.predict_info_paths = 'data/nuScenes/nuscenes_infos_test.pkl' self.return_image = True self.return_depth = True self.return_radar_pv = False self.remove_z_axis = True def forward(self, sweep_imgs, mats, is_train=False, **inputs): return self.model(sweep_imgs, mats, is_train=is_train) def training_step(self, batch): if self.global_rank == 0: for pg in self.trainer.optimizers[0].param_groups: self.log('learning_rate', pg["lr"]) (sweep_imgs, mats, _, gt_boxes_3d, gt_labels_3d, _, depth_labels, pts_pv) = batch if torch.cuda.is_available(): if self.return_image: sweep_imgs = sweep_imgs.cuda() for key, value in mats.items(): mats[key] = value.cuda() if self.return_radar_pv: pts_pv = pts_pv.cuda() gt_boxes_3d = [gt_box.cuda() for gt_box in gt_boxes_3d] gt_labels_3d = [gt_label.cuda() for gt_label in gt_labels_3d] preds, depth_preds = self(sweep_imgs, mats, pts_pv=pts_pv, is_train=True) targets = self.model.get_targets(gt_boxes_3d, gt_labels_3d) loss_detection, loss_heatmap, loss_bbox = self.model.loss(targets, preds) if len(depth_labels.shape) == 5: # only key-frame will calculate depth loss depth_labels = depth_labels[:, 0, ...].contiguous() loss_depth = self.get_depth_loss(depth_labels.cuda(), depth_preds) self.log('train/detection', loss_detection) self.log('train/heatmap', loss_heatmap) self.log('train/bbox', loss_bbox) self.log('train/depth', loss_depth) return loss_detection + loss_depth def get_depth_loss(self, depth_labels, depth_preds, weight=3.): depth_labels = self.get_downsampled_gt_depth(depth_labels) depth_preds = depth_preds.permute(0, 2, 3, 1).contiguous().view( -1, self.depth_channels) fg_mask = torch.max(depth_labels, dim=1).values > 0.0 with autocast(enabled=False): loss_depth = (F.binary_cross_entropy( depth_preds[fg_mask], depth_labels[fg_mask], reduction='none', ).sum() / max(1.0, fg_mask.sum())) return weight * loss_depth def get_downsampled_gt_depth(self, gt_depths): """ Input: gt_depths: [B, N, H, W] Output: gt_depths: [B*N*h*w, d] """ B, N, H, W = gt_depths.shape gt_depths = gt_depths.view( B * N, H // self.downsample_factor, self.downsample_factor, W // self.downsample_factor, self.downsample_factor, 1, ) gt_depths = gt_depths.permute(0, 1, 3, 5, 2, 4).contiguous() gt_depths = gt_depths.view( -1, self.downsample_factor * self.downsample_factor) gt_depths_tmp = torch.where(gt_depths == 0.0, 1e5 * torch.ones_like(gt_depths), gt_depths) gt_depths = torch.min(gt_depths_tmp, dim=-1).values gt_depths = gt_depths.view(B * N, H // self.downsample_factor, W // self.downsample_factor) gt_depths = (gt_depths - (self.dbound[0] - self.dbound[2])) / self.dbound[2] gt_depths = torch.where( (gt_depths < self.depth_channels + 1) & (gt_depths > 0.), gt_depths, torch.zeros_like(gt_depths)) gt_depths = F.one_hot(gt_depths.long(), num_classes=self.depth_channels + 1).view( -1, self.depth_channels + 1)[:, 1:] return gt_depths.float() def eval_step(self, batch, batch_idx, prefix: str): (sweep_imgs, mats, img_metas, _, _, _, _, pts_pv) = batch if torch.cuda.is_available(): if self.return_image: sweep_imgs = sweep_imgs.cuda() for key, value in mats.items(): mats[key] = value.cuda() if self.return_radar_pv: pts_pv = pts_pv.cuda() preds = self(sweep_imgs, mats, pts_pv=pts_pv, is_train=False) if isinstance(self.model, torch.nn.parallel.DistributedDataParallel): results = self.model.module.get_bboxes(preds, img_metas) else: results = self.model.get_bboxes(preds, img_metas) for i in range(len(results)): results[i][0] = results[i][0].tensor.detach().cpu().numpy() results[i][1] = results[i][1].detach().cpu().numpy() results[i][2] = results[i][2].detach().cpu().numpy() results[i].append(img_metas[i]) return results def validation_epoch_end(self, validation_step_outputs): detection_losses = list() heatmap_losses = list() bbox_losses = list() depth_losses = list() for validation_step_output in validation_step_outputs: detection_losses.append(validation_step_output[0]) heatmap_losses.append(validation_step_output[1]) bbox_losses.append(validation_step_output[2]) depth_losses.append(validation_step_output[3])
synchronize()
5
2023-12-06 14:57:49+00:00
24k
jinxixiang/magic_animate_unofficial
animatediff/magic_animate/pipeline.py
[ { "identifier": "UNet3DConditionModel", "path": "animatediff/magic_animate/unet_controlnet.py", "snippet": "class UNet3DConditionModel(ModelMixin, ConfigMixin):\n _supports_gradient_checkpointing = True\n\n @register_to_config\n def __init__(\n self,\n sample_size: Optional[int] = None,\n in_channels: int = 4,\n out_channels: int = 4,\n center_input_sample: bool = False,\n flip_sin_to_cos: bool = True,\n freq_shift: int = 0,\n down_block_types: Tuple[str] = (\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"DownBlock3D\",\n ),\n mid_block_type: str = \"UNetMidBlock3DCrossAttn\",\n up_block_types: Tuple[str] = (\n \"UpBlock3D\",\n \"CrossAttnUpBlock3D\",\n \"CrossAttnUpBlock3D\",\n \"CrossAttnUpBlock3D\"\n ),\n only_cross_attention: Union[bool, Tuple[bool]] = False,\n block_out_channels: Tuple[int] = (320, 640, 1280, 1280),\n layers_per_block: int = 2,\n downsample_padding: int = 1,\n mid_block_scale_factor: float = 1,\n act_fn: str = \"silu\",\n norm_num_groups: int = 32,\n norm_eps: float = 1e-5,\n cross_attention_dim: int = 1280,\n attention_head_dim: Union[int, Tuple[int]] = 8,\n dual_cross_attention: bool = False,\n use_linear_projection: bool = False,\n class_embed_type: Optional[str] = None,\n num_class_embeds: Optional[int] = None,\n upcast_attention: bool = False,\n resnet_time_scale_shift: str = \"default\",\n\n # Additional\n use_motion_module=False,\n motion_module_resolutions=(1, 2, 4, 8),\n motion_module_mid_block=False,\n motion_module_decoder_only=False,\n motion_module_type=None,\n motion_module_kwargs={},\n unet_use_cross_frame_attention=None,\n unet_use_temporal_attention=None,\n\n # Addition for image embeddings\n use_image_condition=False,\n # Additional for dwpose adapter\n use_dwpose_adapter=False,\n ):\n super().__init__()\n\n self.sample_size = sample_size\n time_embed_dim = block_out_channels[0] * 4\n\n # input\n self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1))\n\n # time\n self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)\n timestep_input_dim = block_out_channels[0]\n\n self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n\n # class embedding\n if class_embed_type is None and num_class_embeds is not None:\n self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)\n elif class_embed_type == \"timestep\":\n self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n elif class_embed_type == \"identity\":\n self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)\n else:\n self.class_embedding = None\n\n # dwpose condition\n if use_dwpose_adapter:\n self.dwpose_adapter = ControlNetConditioningEmbedding(conditioning_embedding_channels=4) # pose guider net\n else:\n self.dwpose_adapter = None\n\n self.use_image_condition = False\n if use_image_condition:\n self.use_image_condition = True\n self.image_proj_model = Resampler(\n dim=cross_attention_dim,\n depth=4,\n dim_head=64,\n heads=12,\n num_queries=16,\n embedding_dim=1024,\n output_dim=cross_attention_dim,\n ff_mult=4,\n )\n\n self.down_blocks = nn.ModuleList([])\n self.mid_block = None\n self.up_blocks = nn.ModuleList([])\n\n if isinstance(only_cross_attention, bool):\n only_cross_attention = [only_cross_attention] * len(down_block_types)\n\n if isinstance(attention_head_dim, int):\n attention_head_dim = (attention_head_dim,) * len(down_block_types)\n\n # down\n output_channel = block_out_channels[0]\n for i, down_block_type in enumerate(down_block_types):\n res = 2 ** i\n input_channel = output_channel\n output_channel = block_out_channels[i]\n is_final_block = i == len(block_out_channels) - 1\n\n down_block = get_down_block(\n down_block_type,\n num_layers=layers_per_block,\n in_channels=input_channel,\n out_channels=output_channel,\n temb_channels=time_embed_dim,\n add_downsample=not is_final_block,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[i],\n downsample_padding=downsample_padding,\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n\n unet_use_cross_frame_attention=unet_use_cross_frame_attention,\n unet_use_temporal_attention=unet_use_temporal_attention,\n\n use_motion_module=use_motion_module and (res in motion_module_resolutions) and (\n not motion_module_decoder_only),\n motion_module_type=motion_module_type,\n motion_module_kwargs=motion_module_kwargs,\n )\n self.down_blocks.append(down_block)\n\n # mid\n if mid_block_type == \"UNetMidBlock3DCrossAttn\":\n self.mid_block = UNetMidBlock3DCrossAttn(\n in_channels=block_out_channels[-1],\n temb_channels=time_embed_dim,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n output_scale_factor=mid_block_scale_factor,\n resnet_time_scale_shift=resnet_time_scale_shift,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[-1],\n resnet_groups=norm_num_groups,\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n upcast_attention=upcast_attention,\n\n unet_use_cross_frame_attention=unet_use_cross_frame_attention,\n unet_use_temporal_attention=unet_use_temporal_attention,\n\n use_motion_module=use_motion_module and motion_module_mid_block,\n motion_module_type=motion_module_type,\n motion_module_kwargs=motion_module_kwargs,\n )\n else:\n raise ValueError(f\"unknown mid_block_type : {mid_block_type}\")\n\n # count how many layers upsample the videos\n self.num_upsamplers = 0\n\n # up\n reversed_block_out_channels = list(reversed(block_out_channels))\n reversed_attention_head_dim = list(reversed(attention_head_dim))\n only_cross_attention = list(reversed(only_cross_attention))\n output_channel = reversed_block_out_channels[0]\n for i, up_block_type in enumerate(up_block_types):\n res = 2 ** (3 - i)\n is_final_block = i == len(block_out_channels) - 1\n\n prev_output_channel = output_channel\n output_channel = reversed_block_out_channels[i]\n input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]\n\n # add upsample block for all BUT final layer\n if not is_final_block:\n add_upsample = True\n self.num_upsamplers += 1\n else:\n add_upsample = False\n\n up_block = get_up_block(\n up_block_type,\n num_layers=layers_per_block + 1,\n in_channels=input_channel,\n out_channels=output_channel,\n prev_output_channel=prev_output_channel,\n temb_channels=time_embed_dim,\n add_upsample=add_upsample,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=reversed_attention_head_dim[i],\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n\n unet_use_cross_frame_attention=unet_use_cross_frame_attention,\n unet_use_temporal_attention=unet_use_temporal_attention,\n\n use_motion_module=use_motion_module and (res in motion_module_resolutions),\n motion_module_type=motion_module_type,\n motion_module_kwargs=motion_module_kwargs,\n )\n self.up_blocks.append(up_block)\n prev_output_channel = output_channel\n\n # out\n self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps)\n self.conv_act = nn.SiLU()\n self.conv_out = InflatedConv3d(block_out_channels[0], out_channels, kernel_size=3, padding=1)\n\n def set_attention_slice(self, slice_size):\n r\"\"\"\n Enable sliced attention computation.\n\n When this option is enabled, the attention module will split the input tensor in slices, to compute attention\n in several steps. This is useful to save some memory in exchange for a small speed decrease.\n\n Args:\n slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `\"auto\"`):\n When `\"auto\"`, halves the input to the attention heads, so attention will be computed in two steps. If\n `\"max\"`, maxium amount of memory will be saved by running only one slice at a time. If a number is\n provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`\n must be a multiple of `slice_size`.\n \"\"\"\n sliceable_head_dims = []\n\n def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):\n if hasattr(module, \"set_attention_slice\"):\n sliceable_head_dims.append(module.sliceable_head_dim)\n\n for child in module.children():\n fn_recursive_retrieve_slicable_dims(child)\n\n # retrieve number of attention layers\n for module in self.children():\n fn_recursive_retrieve_slicable_dims(module)\n\n num_slicable_layers = len(sliceable_head_dims)\n\n if slice_size == \"auto\":\n # half the attention head size is usually a good trade-off between\n # speed and memory\n slice_size = [dim // 2 for dim in sliceable_head_dims]\n elif slice_size == \"max\":\n # make smallest slice possible\n slice_size = num_slicable_layers * [1]\n\n slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size\n\n if len(slice_size) != len(sliceable_head_dims):\n raise ValueError(\n f\"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different\"\n f\" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}.\"\n )\n\n for i in range(len(slice_size)):\n size = slice_size[i]\n dim = sliceable_head_dims[i]\n if size is not None and size > dim:\n raise ValueError(f\"size {size} has to be smaller or equal to {dim}.\")\n\n # Recursively walk through all the children.\n # Any children which exposes the set_attention_slice method\n # gets the message\n def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):\n if hasattr(module, \"set_attention_slice\"):\n module.set_attention_slice(slice_size.pop())\n\n for child in module.children():\n fn_recursive_set_attention_slice(child, slice_size)\n\n reversed_slice_size = list(reversed(slice_size))\n for module in self.children():\n fn_recursive_set_attention_slice(module, reversed_slice_size)\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D)):\n module.gradient_checkpointing = value\n\n def forward(\n self,\n sample: torch.FloatTensor,\n timestep: Union[torch.Tensor, float, int],\n encoder_hidden_states: torch.Tensor,\n class_labels: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n # for controlnet\n down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,\n mid_block_additional_residual: Optional[torch.Tensor] = None,\n # for pose_guider\n dwpose_conditions: Optional[torch.Tensor] = None,\n return_dict: bool = True,\n ) -> Union[UNet3DConditionOutput, Tuple]:\n r\"\"\"\n Args:\n sample (`torch.FloatTensor`): (batch, channel, height, width) noisy inputs tensor\n timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps\n encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states\n return_dict (`bool`, *optional*, defaults to `True`):\n Whether or not to return a [`models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain tuple.\n\n Returns:\n [`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:\n [`~models.unet_2d_condition.UNet2DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When\n returning a tuple, the first element is the sample tensor.\n \"\"\"\n # By default samples have to be AT least a multiple of the overall upsampling factor.\n # The overall upsampling factor is equal to 2 ** (# num of upsampling layears).\n # However, the upsampling interpolation output size can be forced to fit any upsampling size\n # on the fly if necessary.\n default_overall_up_factor = 2 ** self.num_upsamplers\n\n # if self.use_image_condition:\n # # project global image to 16 tokens for cross-attention\n # encoder_hidden_states = self.image_proj(encoder_hidden_states)\n # encoder_hidden_states = encoder_hidden_states.reshape(-1, 16, 768)\n # encoder_hidden_states = self.image_norm(encoder_hidden_states)\n\n # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`\n forward_upsample_size = False\n upsample_size = None\n\n if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):\n logger.info(\"Forward upsample size to force interpolation output size.\")\n forward_upsample_size = True\n\n # prepare attention_mask\n if attention_mask is not None:\n attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0\n attention_mask = attention_mask.unsqueeze(1)\n\n # center input if necessary\n if self.config.center_input_sample:\n sample = 2 * sample - 1.0\n\n # time\n timesteps = timestep\n if not torch.is_tensor(timesteps):\n # This would be a good case for the `match` statement (Python 3.10+)\n is_mps = sample.device.type == \"mps\"\n if isinstance(timestep, float):\n dtype = torch.float32 if is_mps else torch.float64\n else:\n dtype = torch.int32 if is_mps else torch.int64\n timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)\n elif len(timesteps.shape) == 0:\n timesteps = timesteps[None].to(sample.device)\n\n # broadcast to batch dimension in a way that's compatible with ONNX/Core ML\n timesteps = timesteps.expand(sample.shape[0])\n\n t_emb = self.time_proj(timesteps)\n\n # timesteps does not contain any weights and will always return f32 tensors\n # but time_embedding might actually be running in fp16. so we need to cast here.\n # there might be better ways to encapsulate this.\n t_emb = t_emb.to(dtype=self.dtype)\n emb = self.time_embedding(t_emb)\n\n if self.class_embedding is not None:\n if class_labels is None:\n raise ValueError(\"class_labels should be provided when num_class_embeds > 0\")\n\n if self.config.class_embed_type == \"timestep\":\n class_labels = self.time_proj(class_labels)\n\n class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)\n emb = emb + class_emb\n\n # add pose conditions\n if dwpose_conditions is not None:\n conditions = self.dwpose_adapter(dwpose_conditions)\n sample += conditions\n\n # pre-process\n sample = self.conv_in(sample)\n\n # down\n is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None\n\n down_block_res_samples = (sample,)\n for downsample_block in self.down_blocks:\n if hasattr(downsample_block, \"has_cross_attention\") and downsample_block.has_cross_attention:\n sample, res_samples = downsample_block(\n hidden_states=sample,\n temb=emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n )\n else:\n sample, res_samples = downsample_block(hidden_states=sample, temb=emb,\n encoder_hidden_states=encoder_hidden_states)\n\n down_block_res_samples += res_samples\n\n if is_controlnet:\n new_down_block_res_samples = ()\n\n for down_block_res_sample, down_block_additional_residual in zip(\n down_block_res_samples, down_block_additional_residuals\n ):\n down_block_res_sample = down_block_res_sample + down_block_additional_residual\n new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)\n\n down_block_res_samples = new_down_block_res_samples\n\n # mid\n sample = self.mid_block(\n sample, emb, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask\n )\n\n if is_controlnet:\n sample = sample + mid_block_additional_residual\n\n # up\n for i, upsample_block in enumerate(self.up_blocks):\n is_final_block = i == len(self.up_blocks) - 1\n\n res_samples = down_block_res_samples[-len(upsample_block.resnets):]\n down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]\n\n # if we have not reached the final block and need to forward the\n # upsample size, we do it here\n if not is_final_block and forward_upsample_size:\n upsample_size = down_block_res_samples[-1].shape[2:]\n\n if hasattr(upsample_block, \"has_cross_attention\") and upsample_block.has_cross_attention:\n sample = upsample_block(\n hidden_states=sample,\n temb=emb,\n res_hidden_states_tuple=res_samples,\n encoder_hidden_states=encoder_hidden_states,\n upsample_size=upsample_size,\n attention_mask=attention_mask,\n )\n else:\n sample = upsample_block(\n hidden_states=sample, temb=emb, res_hidden_states_tuple=res_samples, upsample_size=upsample_size,\n encoder_hidden_states=encoder_hidden_states,\n )\n\n # post-process\n sample = self.conv_norm_out(sample)\n sample = self.conv_act(sample)\n sample = self.conv_out(sample)\n\n if not return_dict:\n return (sample,)\n\n return UNet3DConditionOutput(sample=sample)\n\n @classmethod\n def from_pretrained_2d(cls, pretrained_model_path, subfolder=None, unet_additional_kwargs=None):\n if subfolder is not None:\n pretrained_model_path = os.path.join(pretrained_model_path, subfolder)\n print(f\"loaded temporal unet's pretrained weights from {pretrained_model_path} ...\")\n\n config_file = os.path.join(pretrained_model_path, 'config.json')\n if not os.path.isfile(config_file):\n raise RuntimeError(f\"{config_file} does not exist\")\n with open(config_file, \"r\") as f:\n config = json.load(f)\n config[\"_class_name\"] = cls.__name__\n config[\"down_block_types\"] = [\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"DownBlock3D\"\n ]\n config[\"up_block_types\"] = [\n \"UpBlock3D\",\n \"CrossAttnUpBlock3D\",\n \"CrossAttnUpBlock3D\",\n \"CrossAttnUpBlock3D\"\n ]\n # config[\"mid_block_type\"] = \"UNetMidBlock3DCrossAttn\"\n\n from diffusers.utils import WEIGHTS_NAME\n model = cls.from_config(config, **unet_additional_kwargs)\n model_file = os.path.join(pretrained_model_path, WEIGHTS_NAME)\n if not os.path.isfile(model_file):\n raise RuntimeError(f\"{model_file} does not exist\")\n state_dict = torch.load(model_file, map_location=\"cpu\")\n\n m, u = model.load_state_dict(state_dict, strict=False)\n print(f\"### missing keys: {len(m)}; \\n### unexpected keys: {len(u)};\")\n # print(f\"### missing keys:\\n{m}\\n### unexpected keys:\\n{u}\\n\")\n\n params = [p.numel() if \"temporal\" in n else 0 for n, p in model.named_parameters()]\n print(f\"### Temporal Module Parameters: {sum(params) / 1e6} M\")\n\n return model" }, { "identifier": "ControlNetModel", "path": "animatediff/magic_animate/controlnet.py", "snippet": "class ControlNetModel(ModelMixin, ConfigMixin):\n _supports_gradient_checkpointing = True\n\n @register_to_config\n def __init__(\n self,\n in_channels: int = 4,\n flip_sin_to_cos: bool = True,\n freq_shift: int = 0,\n down_block_types: Tuple[str] = (\n \"CrossAttnDownBlock2D\",\n \"CrossAttnDownBlock2D\",\n \"CrossAttnDownBlock2D\",\n \"DownBlock2D\",\n ),\n only_cross_attention: Union[bool, Tuple[bool]] = False,\n block_out_channels: Tuple[int] = (320, 640, 1280, 1280),\n layers_per_block: int = 2,\n downsample_padding: int = 1,\n mid_block_scale_factor: float = 1,\n act_fn: str = \"silu\",\n norm_num_groups: Optional[int] = 32,\n norm_eps: float = 1e-5,\n cross_attention_dim: int = 1280,\n attention_head_dim: Union[int, Tuple[int]] = 8,\n use_linear_projection: bool = False,\n class_embed_type: Optional[str] = None,\n num_class_embeds: Optional[int] = None,\n upcast_attention: bool = False,\n resnet_time_scale_shift: str = \"default\",\n projection_class_embeddings_input_dim: Optional[int] = None,\n controlnet_conditioning_channel_order: str = \"rgb\",\n conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),\n ):\n super().__init__()\n\n # Check inputs\n if len(block_out_channels) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}.\"\n )\n\n if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}.\"\n )\n\n if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}.\"\n )\n\n # input\n conv_in_kernel = 3\n conv_in_padding = (conv_in_kernel - 1) // 2\n self.conv_in = nn.Conv2d(\n in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding\n )\n\n # time\n time_embed_dim = block_out_channels[0] * 4\n\n self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)\n timestep_input_dim = block_out_channels[0]\n\n self.time_embedding = TimestepEmbedding(\n timestep_input_dim,\n time_embed_dim,\n act_fn=act_fn,\n )\n\n # class embedding\n if class_embed_type is None and num_class_embeds is not None:\n self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)\n elif class_embed_type == \"timestep\":\n self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n elif class_embed_type == \"identity\":\n self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)\n elif class_embed_type == \"projection\":\n if projection_class_embeddings_input_dim is None:\n raise ValueError(\n \"`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set\"\n )\n # The projection `class_embed_type` is the same as the timestep `class_embed_type` except\n # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings\n # 2. it projects from an arbitrary input dimension.\n #\n # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.\n # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.\n # As a result, `TimestepEmbedding` can be passed arbitrary vectors.\n self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)\n else:\n self.class_embedding = None\n\n # control net conditioning embedding\n self.controlnet_cond_embedding = ControlNetConditioningEmbedding(\n conditioning_embedding_channels=block_out_channels[0],\n block_out_channels=conditioning_embedding_out_channels,\n )\n\n self.down_blocks = nn.ModuleList([])\n self.controlnet_down_blocks = nn.ModuleList([])\n\n if isinstance(only_cross_attention, bool):\n only_cross_attention = [only_cross_attention] * len(down_block_types)\n\n if isinstance(attention_head_dim, int):\n attention_head_dim = (attention_head_dim,) * len(down_block_types)\n\n # down\n output_channel = block_out_channels[0]\n\n controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n for i, down_block_type in enumerate(down_block_types):\n input_channel = output_channel\n output_channel = block_out_channels[i]\n is_final_block = i == len(block_out_channels) - 1\n\n down_block = get_down_block(\n down_block_type,\n num_layers=layers_per_block,\n in_channels=input_channel,\n out_channels=output_channel,\n temb_channels=time_embed_dim,\n add_downsample=not is_final_block,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n num_attention_heads=attention_head_dim[i],\n downsample_padding=downsample_padding,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n )\n self.down_blocks.append(down_block)\n\n for _ in range(layers_per_block):\n controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n if not is_final_block:\n controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n # mid\n mid_block_channel = block_out_channels[-1]\n\n controlnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_mid_block = controlnet_block\n\n self.mid_block = UNetMidBlock2DCrossAttn(\n in_channels=mid_block_channel,\n temb_channels=time_embed_dim,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n output_scale_factor=mid_block_scale_factor,\n resnet_time_scale_shift=resnet_time_scale_shift,\n cross_attention_dim=cross_attention_dim,\n num_attention_heads=attention_head_dim[-1],\n resnet_groups=norm_num_groups,\n use_linear_projection=use_linear_projection,\n upcast_attention=upcast_attention,\n )\n\n @classmethod\n def from_unet(\n cls,\n unet: UNet2DConditionModel,\n controlnet_conditioning_channel_order: str = \"rgb\",\n conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),\n load_weights_from_unet: bool = True,\n ):\n r\"\"\"\n Instantiate Controlnet class from UNet2DConditionModel.\n\n Parameters:\n unet (`UNet2DConditionModel`):\n UNet model which weights are copied to the ControlNet. Note that all configuration options are also\n copied where applicable.\n \"\"\"\n controlnet = cls(\n in_channels=unet.config.in_channels,\n flip_sin_to_cos=unet.config.flip_sin_to_cos,\n freq_shift=unet.config.freq_shift,\n down_block_types=unet.config.down_block_types,\n only_cross_attention=unet.config.only_cross_attention,\n block_out_channels=unet.config.block_out_channels,\n layers_per_block=unet.config.layers_per_block,\n downsample_padding=unet.config.downsample_padding,\n mid_block_scale_factor=unet.config.mid_block_scale_factor,\n act_fn=unet.config.act_fn,\n norm_num_groups=unet.config.norm_num_groups,\n norm_eps=unet.config.norm_eps,\n cross_attention_dim=unet.config.cross_attention_dim,\n attention_head_dim=unet.config.attention_head_dim,\n use_linear_projection=unet.config.use_linear_projection,\n class_embed_type=unet.config.class_embed_type,\n num_class_embeds=unet.config.num_class_embeds,\n upcast_attention=unet.config.upcast_attention,\n resnet_time_scale_shift=unet.config.resnet_time_scale_shift,\n projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,\n controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,\n conditioning_embedding_out_channels=conditioning_embedding_out_channels,\n )\n\n if load_weights_from_unet:\n controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())\n controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())\n controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())\n\n if controlnet.class_embedding:\n controlnet.class_embedding.load_state_dict(unet.class_embedding.state_dict())\n\n controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict())\n controlnet.mid_block.load_state_dict(unet.mid_block.state_dict())\n\n return controlnet\n\n # @property\n # # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors\n # def attn_processors(self) -> Dict[str, AttentionProcessor]:\n # r\"\"\"\n # Returns:\n # `dict` of attention processors: A dictionary containing all attention processors used in the model with\n # indexed by its weight name.\n # \"\"\"\n # # set recursively\n # processors = {}\n\n # def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):\n # if hasattr(module, \"set_processor\"):\n # processors[f\"{name}.processor\"] = module.processor\n\n # for sub_name, child in module.named_children():\n # fn_recursive_add_processors(f\"{name}.{sub_name}\", child, processors)\n\n # return processors\n\n # for name, module in self.named_children():\n # fn_recursive_add_processors(name, module, processors)\n\n # return processors\n\n # # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor\n # def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):\n # r\"\"\"\n # Parameters:\n # `processor (`dict` of `AttentionProcessor` or `AttentionProcessor`):\n # The instantiated processor class or a dictionary of processor classes that will be set as the processor\n # of **all** `Attention` layers.\n # In case `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainable attention processors.:\n\n # \"\"\"\n # count = len(self.attn_processors.keys())\n\n # if isinstance(processor, dict) and len(processor) != count:\n # raise ValueError(\n # f\"A dict of processors was passed, but the number of processors {len(processor)} does not match the\"\n # f\" number of attention layers: {count}. Please make sure to pass {count} processor classes.\"\n # )\n\n # def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):\n # if hasattr(module, \"set_processor\"):\n # if not isinstance(processor, dict):\n # module.set_processor(processor)\n # else:\n # module.set_processor(processor.pop(f\"{name}.processor\"))\n\n # for sub_name, child in module.named_children():\n # fn_recursive_attn_processor(f\"{name}.{sub_name}\", child, processor)\n\n # for name, module in self.named_children():\n # fn_recursive_attn_processor(name, module, processor)\n\n # # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor\n # def set_default_attn_processor(self):\n # \"\"\"\n # Disables custom attention processors and sets the default attention implementation.\n # \"\"\"\n # self.set_attn_processor(AttnProcessor())\n\n # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attention_slice\n def set_attention_slice(self, slice_size):\n r\"\"\"\n Enable sliced attention computation.\n\n When this option is enabled, the attention module will split the input tensor in slices, to compute attention\n in several steps. This is useful to save some memory in exchange for a small speed decrease.\n\n Args:\n slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `\"auto\"`):\n When `\"auto\"`, halves the input to the attention heads, so attention will be computed in two steps. If\n `\"max\"`, maximum amount of memory will be saved by running only one slice at a time. If a number is\n provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`\n must be a multiple of `slice_size`.\n \"\"\"\n sliceable_head_dims = []\n\n def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):\n if hasattr(module, \"set_attention_slice\"):\n sliceable_head_dims.append(module.sliceable_head_dim)\n\n for child in module.children():\n fn_recursive_retrieve_sliceable_dims(child)\n\n # retrieve number of attention layers\n for module in self.children():\n fn_recursive_retrieve_sliceable_dims(module)\n\n num_sliceable_layers = len(sliceable_head_dims)\n\n if slice_size == \"auto\":\n # half the attention head size is usually a good trade-off between\n # speed and memory\n slice_size = [dim // 2 for dim in sliceable_head_dims]\n elif slice_size == \"max\":\n # make smallest slice possible\n slice_size = num_sliceable_layers * [1]\n\n slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size\n\n if len(slice_size) != len(sliceable_head_dims):\n raise ValueError(\n f\"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different\"\n f\" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}.\"\n )\n\n for i in range(len(slice_size)):\n size = slice_size[i]\n dim = sliceable_head_dims[i]\n if size is not None and size > dim:\n raise ValueError(f\"size {size} has to be smaller or equal to {dim}.\")\n\n # Recursively walk through all the children.\n # Any children which exposes the set_attention_slice method\n # gets the message\n def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):\n if hasattr(module, \"set_attention_slice\"):\n module.set_attention_slice(slice_size.pop())\n\n for child in module.children():\n fn_recursive_set_attention_slice(child, slice_size)\n\n reversed_slice_size = list(reversed(slice_size))\n for module in self.children():\n fn_recursive_set_attention_slice(module, reversed_slice_size)\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):\n module.gradient_checkpointing = value\n\n def forward(\n self,\n sample: torch.FloatTensor,\n timestep: Union[torch.Tensor, float, int],\n encoder_hidden_states: torch.Tensor,\n controlnet_cond: torch.FloatTensor,\n conditioning_scale: float = 1.0,\n class_labels: Optional[torch.Tensor] = None,\n timestep_cond: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n return_dict: bool = True,\n ) -> Union[ControlNetOutput, Tuple]:\n # check channel order\n channel_order = self.config.controlnet_conditioning_channel_order\n\n if channel_order == \"rgb\":\n # in rgb order by default\n ...\n elif channel_order == \"bgr\":\n controlnet_cond = torch.flip(controlnet_cond, dims=[1])\n else:\n raise ValueError(f\"unknown `controlnet_conditioning_channel_order`: {channel_order}\")\n\n # prepare attention_mask\n if attention_mask is not None:\n attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0\n attention_mask = attention_mask.unsqueeze(1)\n\n # 1. time\n timesteps = timestep\n if not torch.is_tensor(timesteps):\n # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can\n # This would be a good case for the `match` statement (Python 3.10+)\n is_mps = sample.device.type == \"mps\"\n if isinstance(timestep, float):\n dtype = torch.float32 if is_mps else torch.float64\n else:\n dtype = torch.int32 if is_mps else torch.int64\n timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)\n elif len(timesteps.shape) == 0:\n timesteps = timesteps[None].to(sample.device)\n\n # broadcast to batch dimension in a way that's compatible with ONNX/Core ML\n timesteps = timesteps.expand(sample.shape[0])\n\n t_emb = self.time_proj(timesteps)\n\n # timesteps does not contain any weights and will always return f32 tensors\n # but time_embedding might actually be running in fp16. so we need to cast here.\n # there might be better ways to encapsulate this.\n t_emb = t_emb.to(dtype=self.dtype)\n\n emb = self.time_embedding(t_emb, timestep_cond)\n\n if self.class_embedding is not None:\n if class_labels is None:\n raise ValueError(\"class_labels should be provided when num_class_embeds > 0\")\n\n if self.config.class_embed_type == \"timestep\":\n class_labels = self.time_proj(class_labels)\n\n class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)\n emb = emb + class_emb\n\n # 2. pre-process\n sample = self.conv_in(sample)\n\n controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)\n\n sample += controlnet_cond\n\n # 3. down\n down_block_res_samples = (sample,)\n for downsample_block in self.down_blocks:\n if hasattr(downsample_block, \"has_cross_attention\") and downsample_block.has_cross_attention:\n sample, res_samples = downsample_block(\n hidden_states=sample,\n temb=emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n # cross_attention_kwargs=cross_attention_kwargs,\n )\n else:\n sample, res_samples = downsample_block(hidden_states=sample, temb=emb)\n\n down_block_res_samples += res_samples\n\n # 4. mid\n if self.mid_block is not None:\n sample = self.mid_block(\n sample,\n emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n # cross_attention_kwargs=cross_attention_kwargs,\n )\n\n # 5. Control net blocks\n\n controlnet_down_block_res_samples = ()\n\n for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):\n down_block_res_sample = controlnet_block(down_block_res_sample)\n controlnet_down_block_res_samples += (down_block_res_sample,)\n\n down_block_res_samples = controlnet_down_block_res_samples\n\n mid_block_res_sample = self.controlnet_mid_block(sample)\n\n # 6. scaling\n down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]\n mid_block_res_sample *= conditioning_scale\n\n if not return_dict:\n return (down_block_res_samples, mid_block_res_sample)\n\n return ControlNetOutput(\n down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample\n )" }, { "identifier": "ReferenceAttentionControl", "path": "animatediff/magic_animate/mutual_self_attention.py", "snippet": "class ReferenceAttentionControl():\n \n def __init__(self, \n unet,\n mode=\"write\",\n do_classifier_free_guidance=False,\n attention_auto_machine_weight = float('inf'),\n gn_auto_machine_weight = 1.0,\n style_fidelity = 1.0,\n reference_attn=True,\n reference_adain=False,\n fusion_blocks=\"midup\",\n batch_size=1,\n clip_length=8,\n is_image=False,\n ) -> None:\n # 10. Modify self attention and group norm\n self.unet = unet\n assert mode in [\"read\", \"write\"]\n assert fusion_blocks in [\"midup\", \"full\"]\n self.reference_attn = reference_attn\n self.reference_adain = reference_adain\n self.fusion_blocks = fusion_blocks\n self.register_reference_hooks(\n mode, \n do_classifier_free_guidance,\n clip_length,\n attention_auto_machine_weight,\n gn_auto_machine_weight,\n style_fidelity,\n reference_attn,\n reference_adain,\n fusion_blocks=fusion_blocks,\n batch_size=batch_size,\n is_image=is_image,\n )\n\n def register_reference_hooks(\n self, \n mode, \n do_classifier_free_guidance,\n clip_length,\n attention_auto_machine_weight,\n gn_auto_machine_weight,\n style_fidelity,\n reference_attn,\n reference_adain,\n dtype=torch.float16,\n batch_size=1, \n num_images_per_prompt=1, \n device=torch.device(\"cpu\"), \n fusion_blocks='midup',\n is_image=False,\n ):\n MODE = mode\n do_classifier_free_guidance = do_classifier_free_guidance\n attention_auto_machine_weight = attention_auto_machine_weight\n gn_auto_machine_weight = gn_auto_machine_weight\n style_fidelity = style_fidelity\n reference_attn = reference_attn\n reference_adain = reference_adain\n fusion_blocks = fusion_blocks\n num_images_per_prompt = num_images_per_prompt\n dtype=dtype\n if do_classifier_free_guidance:\n # uc_mask = (\n # torch.Tensor([1] * batch_size * num_images_per_prompt * 16 + [0] * batch_size * num_images_per_prompt * 16)\n # .to(device)\n # .bool()\n # )\n\n uc_mask = (\n torch.Tensor(\n [1] * batch_size * num_images_per_prompt * clip_length + [0] * batch_size * num_images_per_prompt * clip_length)\n .to(device)\n .bool()\n )\n\n else:\n uc_mask = (\n torch.Tensor([0] * batch_size * num_images_per_prompt * 2)\n .to(device)\n .bool()\n )\n \n def hacked_basic_transformer_inner_forward(\n self,\n hidden_states: torch.FloatTensor,\n attention_mask: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n timestep: Optional[torch.LongTensor] = None,\n cross_attention_kwargs: Dict[str, Any] = None,\n class_labels: Optional[torch.LongTensor] = None,\n video_length=None,\n ):\n if self.use_ada_layer_norm:\n norm_hidden_states = self.norm1(hidden_states, timestep)\n elif self.use_ada_layer_norm_zero:\n norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(\n hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype\n )\n else:\n norm_hidden_states = self.norm1(hidden_states)\n\n # 1. Self-Attention\n cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}\n if self.only_cross_attention:\n attn_output = self.attn1(\n norm_hidden_states,\n encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,\n attention_mask=attention_mask,\n **cross_attention_kwargs,\n )\n else:\n if MODE == \"write\":\n self.bank.append(norm_hidden_states.clone())\n attn_output = self.attn1(\n norm_hidden_states,\n encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,\n attention_mask=attention_mask,\n **cross_attention_kwargs,\n )\n if MODE == \"read\":\n if not is_image:\n self.bank = [rearrange(d.unsqueeze(1).repeat(1, video_length, 1, 1), \"b t l c -> (b t) l c\")[:hidden_states.shape[0]] for d in self.bank]\n\n hidden_states_uc = self.attn1(norm_hidden_states,\n encoder_hidden_states=torch.cat([norm_hidden_states] + self.bank, dim=1),\n attention_mask=attention_mask) + hidden_states\n hidden_states_c = hidden_states_uc.clone()\n _uc_mask = uc_mask.clone()\n if do_classifier_free_guidance:\n if hidden_states.shape[0] != _uc_mask.shape[0]:\n _uc_mask = (\n torch.Tensor([1] * (hidden_states.shape[0]//2) + [0] * (hidden_states.shape[0]//2))\n .to(device)\n .bool()\n )\n hidden_states_c[_uc_mask] = self.attn1(\n norm_hidden_states[_uc_mask],\n encoder_hidden_states=norm_hidden_states[_uc_mask],\n attention_mask=attention_mask,\n ) + hidden_states[_uc_mask]\n hidden_states = hidden_states_c.clone()\n \n self.bank.clear()\n if self.attn2 is not None:\n # Cross-Attention\n norm_hidden_states = (\n self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)\n )\n hidden_states = (\n self.attn2(\n norm_hidden_states, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask\n )\n + hidden_states\n )\n\n # Feed-forward\n hidden_states = self.ff(self.norm3(hidden_states)) + hidden_states\n\n # Temporal-Attention\n if not is_image:\n if self.unet_use_temporal_attention:\n d = hidden_states.shape[1]\n hidden_states = rearrange(hidden_states, \"(b f) d c -> (b d) f c\", f=video_length)\n norm_hidden_states = (\n self.norm_temp(hidden_states, timestep) if self.use_ada_layer_norm else self.norm_temp(hidden_states)\n )\n hidden_states = self.attn_temp(norm_hidden_states) + hidden_states\n hidden_states = rearrange(hidden_states, \"(b d) f c -> (b f) d c\", d=d)\n\n return hidden_states\n \n if self.use_ada_layer_norm_zero:\n attn_output = gate_msa.unsqueeze(1) * attn_output\n hidden_states = attn_output + hidden_states\n\n if self.attn2 is not None:\n norm_hidden_states = (\n self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)\n )\n\n # 2. Cross-Attention\n attn_output = self.attn2(\n norm_hidden_states,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=encoder_attention_mask,\n **cross_attention_kwargs,\n )\n hidden_states = attn_output + hidden_states\n\n # 3. Feed-forward\n norm_hidden_states = self.norm3(hidden_states)\n\n if self.use_ada_layer_norm_zero:\n norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]\n\n ff_output = self.ff(norm_hidden_states)\n\n if self.use_ada_layer_norm_zero:\n ff_output = gate_mlp.unsqueeze(1) * ff_output\n\n hidden_states = ff_output + hidden_states\n\n return hidden_states\n\n def hacked_mid_forward(self, *args, **kwargs):\n eps = 1e-6\n x = self.original_forward(*args, **kwargs)\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append(mean)\n self.var_bank.append(var)\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank) / float(len(self.mean_bank))\n var_acc = sum(self.var_bank) / float(len(self.var_bank))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n x_uc = (((x - mean) / std) * std_acc) + mean_acc\n x_c = x_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n x_c[uc_mask] = x[uc_mask]\n x = style_fidelity * x_c + (1.0 - style_fidelity) * x_uc\n self.mean_bank = []\n self.var_bank = []\n return x\n\n def hack_CrossAttnDownBlock2D_forward(\n self,\n hidden_states: torch.FloatTensor,\n temb: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n ):\n eps = 1e-6\n\n # TODO(Patrick, William) - attention mask is not used\n output_states = ()\n\n for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)):\n hidden_states = resnet(hidden_states, temb)\n hidden_states = attn(\n hidden_states,\n encoder_hidden_states=encoder_hidden_states,\n cross_attention_kwargs=cross_attention_kwargs,\n attention_mask=attention_mask,\n encoder_attention_mask=encoder_attention_mask,\n return_dict=False,\n )[0]\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append([mean])\n self.var_bank.append([var])\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))\n var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc\n hidden_states_c = hidden_states_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n hidden_states_c[uc_mask] = hidden_states[uc_mask].to(hidden_states_c.dtype)\n hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc\n\n output_states = output_states + (hidden_states,)\n\n if MODE == \"read\":\n self.mean_bank = []\n self.var_bank = []\n\n if self.downsamplers is not None:\n for downsampler in self.downsamplers:\n hidden_states = downsampler(hidden_states)\n\n output_states = output_states + (hidden_states,)\n\n return hidden_states, output_states\n\n def hacked_DownBlock2D_forward(self, hidden_states, temb=None):\n eps = 1e-6\n\n output_states = ()\n\n for i, resnet in enumerate(self.resnets):\n hidden_states = resnet(hidden_states, temb)\n\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append([mean])\n self.var_bank.append([var])\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))\n var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc\n hidden_states_c = hidden_states_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n hidden_states_c[uc_mask] = hidden_states[uc_mask].to(hidden_states_c.dtype)\n hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc\n\n output_states = output_states + (hidden_states,)\n\n if MODE == \"read\":\n self.mean_bank = []\n self.var_bank = []\n\n if self.downsamplers is not None:\n for downsampler in self.downsamplers:\n hidden_states = downsampler(hidden_states)\n\n output_states = output_states + (hidden_states,)\n\n return hidden_states, output_states\n\n def hacked_CrossAttnUpBlock2D_forward(\n self,\n hidden_states: torch.FloatTensor,\n res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],\n temb: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n upsample_size: Optional[int] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n ):\n eps = 1e-6\n # TODO(Patrick, William) - attention mask is not used\n for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)):\n # pop res hidden states\n res_hidden_states = res_hidden_states_tuple[-1]\n res_hidden_states_tuple = res_hidden_states_tuple[:-1]\n hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)\n hidden_states = resnet(hidden_states, temb)\n hidden_states = attn(\n hidden_states,\n encoder_hidden_states=encoder_hidden_states,\n cross_attention_kwargs=cross_attention_kwargs,\n attention_mask=attention_mask,\n encoder_attention_mask=encoder_attention_mask,\n return_dict=False,\n )[0]\n\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append([mean])\n self.var_bank.append([var])\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))\n var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc\n hidden_states_c = hidden_states_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n hidden_states_c[uc_mask] = hidden_states[uc_mask].to(hidden_states_c.dtype)\n hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc\n\n if MODE == \"read\":\n self.mean_bank = []\n self.var_bank = []\n\n if self.upsamplers is not None:\n for upsampler in self.upsamplers:\n hidden_states = upsampler(hidden_states, upsample_size)\n\n return hidden_states\n\n def hacked_UpBlock2D_forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None):\n eps = 1e-6\n for i, resnet in enumerate(self.resnets):\n # pop res hidden states\n res_hidden_states = res_hidden_states_tuple[-1]\n res_hidden_states_tuple = res_hidden_states_tuple[:-1]\n hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)\n hidden_states = resnet(hidden_states, temb)\n\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append([mean])\n self.var_bank.append([var])\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))\n var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc\n hidden_states_c = hidden_states_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n hidden_states_c[uc_mask] = hidden_states[uc_mask].to(hidden_states_c.dtype)\n hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc\n\n if MODE == \"read\":\n self.mean_bank = []\n self.var_bank = []\n\n if self.upsamplers is not None:\n for upsampler in self.upsamplers:\n hidden_states = upsampler(hidden_states, upsample_size)\n\n return hidden_states\n\n if self.reference_attn:\n if self.fusion_blocks == \"midup\":\n attn_modules = [module for module in (torch_dfs(self.unet.mid_block)+torch_dfs(self.unet.up_blocks)) if isinstance(module, BasicTransformerBlock) or isinstance(module, _BasicTransformerBlock)]\n elif self.fusion_blocks == \"full\":\n attn_modules = [module for module in torch_dfs(self.unet) if isinstance(module, BasicTransformerBlock) or isinstance(module, _BasicTransformerBlock)] \n attn_modules = sorted(attn_modules, key=lambda x: -x.norm1.normalized_shape[0])\n\n for i, module in enumerate(attn_modules):\n module._original_inner_forward = module.forward\n module.forward = hacked_basic_transformer_inner_forward.__get__(module, BasicTransformerBlock)\n module.bank = []\n module.attn_weight = float(i) / float(len(attn_modules))\n\n if self.reference_adain:\n gn_modules = [self.unet.mid_block]\n self.unet.mid_block.gn_weight = 0\n\n down_blocks = self.unet.down_blocks\n for w, module in enumerate(down_blocks):\n module.gn_weight = 1.0 - float(w) / float(len(down_blocks))\n gn_modules.append(module)\n\n up_blocks = self.unet.up_blocks\n for w, module in enumerate(up_blocks):\n module.gn_weight = float(w) / float(len(up_blocks))\n gn_modules.append(module)\n\n for i, module in enumerate(gn_modules):\n if getattr(module, \"original_forward\", None) is None:\n module.original_forward = module.forward\n if i == 0:\n # mid_block\n module.forward = hacked_mid_forward.__get__(module, torch.nn.Module)\n elif isinstance(module, CrossAttnDownBlock2D):\n module.forward = hack_CrossAttnDownBlock2D_forward.__get__(module, CrossAttnDownBlock2D)\n elif isinstance(module, DownBlock2D):\n module.forward = hacked_DownBlock2D_forward.__get__(module, DownBlock2D)\n elif isinstance(module, CrossAttnUpBlock2D):\n module.forward = hacked_CrossAttnUpBlock2D_forward.__get__(module, CrossAttnUpBlock2D)\n elif isinstance(module, UpBlock2D):\n module.forward = hacked_UpBlock2D_forward.__get__(module, UpBlock2D)\n module.mean_bank = []\n module.var_bank = []\n module.gn_weight *= 2\n \n def update(self, writer, dtype=torch.float16):\n if self.reference_attn:\n if self.fusion_blocks == \"midup\":\n reader_attn_modules = [module for module in (torch_dfs(self.unet.mid_block)+torch_dfs(self.unet.up_blocks)) if isinstance(module, _BasicTransformerBlock)]\n writer_attn_modules = [module for module in (torch_dfs(writer.unet.mid_block)+torch_dfs(writer.unet.up_blocks)) if isinstance(module, BasicTransformerBlock)]\n elif self.fusion_blocks == \"full\":\n reader_attn_modules = [module for module in torch_dfs(self.unet) if isinstance(module, _BasicTransformerBlock)]\n writer_attn_modules = [module for module in torch_dfs(writer.unet) if isinstance(module, BasicTransformerBlock)]\n reader_attn_modules = sorted(reader_attn_modules, key=lambda x: -x.norm1.normalized_shape[0]) \n writer_attn_modules = sorted(writer_attn_modules, key=lambda x: -x.norm1.normalized_shape[0])\n for r, w in zip(reader_attn_modules, writer_attn_modules):\n r.bank = [v.clone().to(dtype) for v in w.bank]\n # w.bank.clear()\n if self.reference_adain:\n reader_gn_modules = [self.unet.mid_block]\n \n down_blocks = self.unet.down_blocks\n for w, module in enumerate(down_blocks):\n reader_gn_modules.append(module)\n\n up_blocks = self.unet.up_blocks\n for w, module in enumerate(up_blocks):\n reader_gn_modules.append(module)\n \n writer_gn_modules = [writer.unet.mid_block]\n \n down_blocks = writer.unet.down_blocks\n for w, module in enumerate(down_blocks):\n writer_gn_modules.append(module)\n\n up_blocks = writer.unet.up_blocks\n for w, module in enumerate(up_blocks):\n writer_gn_modules.append(module)\n \n for r, w in zip(reader_gn_modules, writer_gn_modules):\n if len(w.mean_bank) > 0 and isinstance(w.mean_bank[0], list):\n r.mean_bank = [[v.clone().to(dtype) for v in vl] for vl in w.mean_bank]\n r.var_bank = [[v.clone().to(dtype) for v in vl] for vl in w.var_bank]\n else:\n r.mean_bank = [v.clone().to(dtype) for v in w.mean_bank]\n r.var_bank = [v.clone().to(dtype) for v in w.var_bank]\n \n def clear(self):\n if self.reference_attn:\n if self.fusion_blocks == \"midup\":\n reader_attn_modules = [module for module in (torch_dfs(self.unet.mid_block)+torch_dfs(self.unet.up_blocks)) if isinstance(module, BasicTransformerBlock) or isinstance(module, _BasicTransformerBlock)]\n elif self.fusion_blocks == \"full\":\n reader_attn_modules = [module for module in torch_dfs(self.unet) if isinstance(module, BasicTransformerBlock) or isinstance(module, _BasicTransformerBlock)]\n reader_attn_modules = sorted(reader_attn_modules, key=lambda x: -x.norm1.normalized_shape[0])\n for r in reader_attn_modules:\n r.bank.clear()\n if self.reference_adain:\n reader_gn_modules = [self.unet.mid_block]\n \n down_blocks = self.unet.down_blocks\n for w, module in enumerate(down_blocks):\n reader_gn_modules.append(module)\n\n up_blocks = self.unet.up_blocks\n for w, module in enumerate(up_blocks):\n reader_gn_modules.append(module)\n \n for r in reader_gn_modules:\n r.mean_bank.clear()\n r.var_bank.clear()" }, { "identifier": "get_context_scheduler", "path": "animatediff/magic_animate/context.py", "snippet": "def get_context_scheduler(name: str) -> Callable:\n if name == \"uniform\":\n return uniform\n else:\n raise ValueError(f\"Unknown context_overlap policy {name}\")" }, { "identifier": "get_total_steps", "path": "animatediff/magic_animate/context.py", "snippet": "def get_total_steps(\n scheduler,\n timesteps: List[int],\n num_steps: Optional[int] = None,\n num_frames: int = ...,\n context_size: Optional[int] = None,\n context_stride: int = 3,\n context_overlap: int = 4,\n closed_loop: bool = True,\n):\n return sum(\n len(\n list(\n scheduler(\n i,\n num_steps,\n num_frames,\n context_size,\n context_stride,\n context_overlap,\n )\n )\n )\n for i in range(len(timesteps))\n )" }, { "identifier": "get_tensor_interpolation_method", "path": "animatediff/utils/util.py", "snippet": "def get_tensor_interpolation_method():\n return tensor_interpolation" } ]
import inspect, math import numpy as np import torch import torch.distributed as dist import einops from typing import Callable, List, Optional, Union from dataclasses import dataclass from PIL import Image from tqdm import tqdm from diffusers.utils import is_accelerate_available from packaging import version from transformers import CLIPTextModel, CLIPTokenizer from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL from diffusers.pipeline_utils import DiffusionPipeline from diffusers.schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from diffusers.utils import deprecate, logging, BaseOutput from einops import rearrange from animatediff.magic_animate.unet_controlnet import UNet3DConditionModel from animatediff.magic_animate.controlnet import ControlNetModel from animatediff.magic_animate.mutual_self_attention import ReferenceAttentionControl from animatediff.magic_animate.context import ( get_context_scheduler, get_total_steps ) from animatediff.utils.util import get_tensor_interpolation_method from accelerate import cpu_offload
19,748
decoder_consistency=None, **kwargs, ): """ New args: - controlnet_condition : condition map (e.g., depth, canny, keypoints) for controlnet - controlnet_conditioning_scale : conditioning scale for controlnet - init_latents : initial latents to begin with (used along with invert()) - num_actual_inference_steps : number of actual inference steps (while total steps is num_inference_steps) """ controlnet = self.controlnet # Default height and width to unet height = height or self.unet.config.sample_size * self.vae_scale_factor width = width or self.unet.config.sample_size * self.vae_scale_factor # Check inputs. Raise error if not correct self.check_inputs(prompt, height, width, callback_steps) # Define call parameters # batch_size = 1 if isinstance(prompt, str) else len(prompt) batch_size = 1 if latents is not None: batch_size = latents.shape[0] if isinstance(prompt, list): batch_size = len(prompt) device = self._execution_device # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. do_classifier_free_guidance = guidance_scale > 1.0 # Encode input prompt if prompt_embeddings is None: prompt = prompt if isinstance(prompt, list) else [prompt] * batch_size if negative_prompt is not None: negative_prompt = negative_prompt if isinstance(negative_prompt, list) else [negative_prompt] * batch_size text_embeddings = self._encode_prompt( prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt ) text_embeddings = torch.cat([text_embeddings] * context_batch_size) else: text_embeddings = torch.cat([prompt_embeddings] * context_batch_size) reference_control_writer = ReferenceAttentionControl(appearance_encoder, do_classifier_free_guidance=do_classifier_free_guidance, mode='write', batch_size=context_batch_size, clip_length=context_frames) reference_control_reader = ReferenceAttentionControl(unet, do_classifier_free_guidance=do_classifier_free_guidance, mode='read', batch_size=context_batch_size, clip_length=context_frames) is_dist_initialized = kwargs.get("dist", False) rank = kwargs.get("rank", 0) world_size = kwargs.get("world_size", 1) # Prepare video assert num_videos_per_prompt == 1 # FIXME: verify if num_videos_per_prompt > 1 works assert batch_size == 1 # FIXME: verify if batch_size > 1 works control = self.prepare_condition( condition=controlnet_condition, device=device, dtype=controlnet.dtype, num_videos_per_prompt=num_videos_per_prompt, do_classifier_free_guidance=do_classifier_free_guidance, ) if do_classifier_free_guidance: controlnet_uncond_images, controlnet_cond_images = control.chunk(2) else: controlnet_cond_images = control # Prepare timesteps self.scheduler.set_timesteps(num_inference_steps, device=device) timesteps = self.scheduler.timesteps # Prepare latent variables if init_latents is not None: latents = rearrange(init_latents, "(b f) c h w -> b c f h w", f=video_length) else: num_channels_latents = self.unet.in_channels latents = self.prepare_latents( batch_size * num_videos_per_prompt, num_channels_latents, video_length, height, width, text_embeddings.dtype, device, generator, latents, clip_length=context_frames ) latents_dtype = latents.dtype # Prepare extra step kwargs. extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) # Prepare text embeddings for controlnet controlnet_text_embeddings = text_embeddings.repeat_interleave(video_length, 0) if do_classifier_free_guidance: _, controlnet_text_embeddings_c = controlnet_text_embeddings.chunk(2) else: controlnet_text_embeddings_c = controlnet_text_embeddings controlnet_res_samples_cache_dict = {i: None for i in range(video_length)} # For img2img setting if num_actual_inference_steps is None: num_actual_inference_steps = num_inference_steps if isinstance(source_image, str): ref_image_latents = self.images2latents(np.array(Image.open(source_image).resize((width, height)))[None, :], latents_dtype).to(device) elif isinstance(source_image, np.ndarray): ref_image_latents = self.images2latents(source_image[None, :], latents_dtype).to(device)
# ************************************************************************* # This file may have been modified by Bytedance Inc. (“Bytedance Inc.'s Mo- # difications”). All Bytedance Inc.'s Modifications are Copyright (2023) B- # ytedance Inc.. # ************************************************************************* # Adapted from https://github.com/showlab/Tune-A-Video/blob/main/tuneavideo/pipelines/pipeline_tuneavideo.py # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ TODO: 1. support multi-controlnet 2. [DONE] support DDIM inversion 3. support Prompt-to-prompt """ logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class AnimationPipelineOutput(BaseOutput): videos: Union[torch.Tensor, np.ndarray] class AnimationPipeline(DiffusionPipeline): _optional_components = [] def __init__( self, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet3DConditionModel, controlnet: ControlNetModel, scheduler: Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ], ): super().__init__() if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1: deprecation_message = ( f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`" f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False) new_config = dict(scheduler.config) new_config["steps_offset"] = 1 scheduler._internal_dict = FrozenDict(new_config) if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True: deprecation_message = ( f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`." " `clip_sample` should be set to False in the configuration file. Please make sure to update the" " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in" " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very" " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file" ) deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False) new_config = dict(scheduler.config) new_config["clip_sample"] = False scheduler._internal_dict = FrozenDict(new_config) is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse( version.parse(unet.config._diffusers_version).base_version ) < version.parse("0.9.0.dev0") is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64 if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64: deprecation_message = ( "The configuration file of the unet has set the default `sample_size` to smaller than" " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the" " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-" " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5" " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the" " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`" " in the config might lead to incorrect results in future versions. If you have downloaded this" " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for" " the `unet/config.json` file" ) deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False) new_config = dict(unet.config) new_config["sample_size"] = 64 unet._internal_dict = FrozenDict(new_config) self.register_modules( vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet, controlnet=controlnet, scheduler=scheduler, ) self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) def enable_vae_slicing(self): self.vae.enable_slicing() def disable_vae_slicing(self): self.vae.disable_slicing() def enable_sequential_cpu_offload(self, gpu_id=0): if is_accelerate_available(): else: raise ImportError("Please install accelerate via `pip install accelerate`") device = torch.device(f"cuda:{gpu_id}") for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]: if cpu_offloaded_model is not None: cpu_offload(cpu_offloaded_model, device) @property def _execution_device(self): if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"): return self.device for module in self.unet.modules(): if ( hasattr(module, "_hf_hook") and hasattr(module._hf_hook, "execution_device") and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device) return self.device def _encode_prompt(self, prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt): batch_size = len(prompt) if isinstance(prompt, list) else 1 text_inputs = self.tokenizer( prompt, padding="max_length", max_length=self.tokenizer.model_max_length, truncation=True, return_tensors="pt", ) text_input_ids = text_inputs.input_ids untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids): removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1: -1]) logger.warning( "The following part of your input was truncated because CLIP can only handle sequences up to" f" {self.tokenizer.model_max_length} tokens: {removed_text}" ) if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: attention_mask = text_inputs.attention_mask.to(device) else: attention_mask = None text_embeddings = self.text_encoder( text_input_ids.to(device), attention_mask=attention_mask, ) text_embeddings = text_embeddings[0] # duplicate text embeddings for each generation per prompt, using mps friendly method bs_embed, seq_len, _ = text_embeddings.shape text_embeddings = text_embeddings.repeat(1, num_videos_per_prompt, 1) text_embeddings = text_embeddings.view(bs_embed * num_videos_per_prompt, seq_len, -1) # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: uncond_tokens: List[str] if negative_prompt is None: uncond_tokens = [""] * batch_size elif type(prompt) is not type(negative_prompt): raise TypeError( f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" f" {type(prompt)}." ) elif isinstance(negative_prompt, str): uncond_tokens = [negative_prompt] elif batch_size != len(negative_prompt): raise ValueError( f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" " the batch size of `prompt`." ) else: uncond_tokens = negative_prompt max_length = text_input_ids.shape[-1] uncond_input = self.tokenizer( uncond_tokens, padding="max_length", max_length=max_length, truncation=True, return_tensors="pt", ) if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: attention_mask = uncond_input.attention_mask.to(device) else: attention_mask = None uncond_embeddings = self.text_encoder( uncond_input.input_ids.to(device), attention_mask=attention_mask, ) uncond_embeddings = uncond_embeddings[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method seq_len = uncond_embeddings.shape[1] uncond_embeddings = uncond_embeddings.repeat(1, num_videos_per_prompt, 1) uncond_embeddings = uncond_embeddings.view(batch_size * num_videos_per_prompt, seq_len, -1) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes text_embeddings = torch.cat([uncond_embeddings, text_embeddings]) return text_embeddings def decode_latents(self, latents, rank, decoder_consistency=None): video_length = latents.shape[2] latents = 1 / 0.18215 * latents latents = rearrange(latents, "b c f h w -> (b f) c h w") # video = self.vae.decode(latents).sample video = [] for frame_idx in tqdm(range(latents.shape[0]), disable=(rank != 0)): if decoder_consistency is not None: video.append(decoder_consistency(latents[frame_idx:frame_idx + 1])) else: video.append(self.vae.decode(latents[frame_idx:frame_idx + 1]).sample) video = torch.cat(video) video = rearrange(video, "(b f) c h w -> b c f h w", f=video_length) video = (video / 2 + 0.5).clamp(0, 1) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16 video = video.cpu().float().numpy() return video def prepare_extra_step_kwargs(self, generator, eta): # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) extra_step_kwargs = {} if accepts_eta: extra_step_kwargs["eta"] = eta # check if the scheduler accepts generator accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) if accepts_generator: extra_step_kwargs["generator"] = generator return extra_step_kwargs def check_inputs(self, prompt, height, width, callback_steps): if not isinstance(prompt, str) and not isinstance(prompt, list): raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") if height % 8 != 0 or width % 8 != 0: raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") if (callback_steps is None) or ( callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0) ): raise ValueError( f"`callback_steps` has to be a positive integer but is {callback_steps} of type" f" {type(callback_steps)}." ) def prepare_latents(self, batch_size, num_channels_latents, video_length, height, width, dtype, device, generator, latents=None, clip_length=16): shape = ( batch_size, num_channels_latents, clip_length, height // self.vae_scale_factor, width // self.vae_scale_factor) if isinstance(generator, list) and len(generator) != batch_size: raise ValueError( f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" f" size of {batch_size}. Make sure the batch size matches the length of the generators." ) if latents is None: rand_device = "cpu" if device.type == "mps" else device if isinstance(generator, list): latents = [ torch.randn(shape, generator=generator[i], device=rand_device, dtype=dtype) for i in range(batch_size) ] latents = torch.cat(latents, dim=0).to(device) else: latents = torch.randn(shape, generator=generator, device=rand_device, dtype=dtype).to(device) latents = latents.repeat(1, 1, video_length // clip_length, 1, 1) else: if latents.shape != shape: raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}") latents = latents.to(device) # scale the initial noise by the standard deviation required by the scheduler latents = latents * self.scheduler.init_noise_sigma return latents def prepare_condition(self, condition, num_videos_per_prompt, device, dtype, do_classifier_free_guidance): # prepare conditions for controlnet # condition = torch.from_numpy(condition.copy()).to(device=device, dtype=dtype) / 255.0 condition = condition.to(device=device, dtype=dtype) # condition = torch.stack([condition for _ in range(num_videos_per_prompt)], dim=0) condition = einops.repeat(condition, 'b f c h w -> (b r) f c h w', r=num_videos_per_prompt) condition = rearrange(condition, 'b f c h w -> (b f) c h w').clone() # condition = rearrange(condition, 'b f h w c -> (b f) c h w').clone() if do_classifier_free_guidance: condition = torch.cat([condition] * 2) return condition def next_step( self, model_output: torch.FloatTensor, timestep: int, x: torch.FloatTensor, eta=0., verbose=False ): """ Inverse sampling for DDIM Inversion """ if verbose: print("timestep: ", timestep) next_step = timestep timestep = min(timestep - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps, 999) alpha_prod_t = self.scheduler.alphas_cumprod[timestep] if timestep >= 0 else self.scheduler.final_alpha_cumprod alpha_prod_t_next = self.scheduler.alphas_cumprod[next_step] beta_prod_t = 1 - alpha_prod_t pred_x0 = (x - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 pred_dir = (1 - alpha_prod_t_next) ** 0.5 * model_output x_next = alpha_prod_t_next ** 0.5 * pred_x0 + pred_dir return x_next, pred_x0 @torch.no_grad() def images2latents(self, images, dtype): """ Convert RGB image to VAE latents """ device = self._execution_device images = torch.from_numpy(images).float().to(dtype) / 127.5 - 1 images = rearrange(images, "f h w c -> f c h w").to(device) latents = [] for frame_idx in range(images.shape[0]): latents.append(self.vae.encode(images[frame_idx:frame_idx + 1])['latent_dist'].mean * 0.18215) latents = torch.cat(latents) return latents @torch.no_grad() def invert( self, image: torch.Tensor, prompt, num_inference_steps=20, num_actual_inference_steps=10, eta=0.0, return_intermediates=False, **kwargs): """ Adapted from: https://github.com/Yujun-Shi/DragDiffusion/blob/main/drag_pipeline.py#L440 invert a real image into noise map with determinisc DDIM inversion """ device = self._execution_device batch_size = image.shape[0] if isinstance(prompt, list): if batch_size == 1: image = image.expand(len(prompt), -1, -1, -1) elif isinstance(prompt, str): if batch_size > 1: prompt = [prompt] * batch_size # text embeddings text_input = self.tokenizer( prompt, padding="max_length", max_length=77, return_tensors="pt" ) text_embeddings = self.text_encoder(text_input.input_ids.to(device))[0] print("input text embeddings :", text_embeddings.shape) # define initial latents latents = self.images2latents(image) print("latents shape: ", latents.shape) # interative sampling self.scheduler.set_timesteps(num_inference_steps) print("Valid timesteps: ", reversed(self.scheduler.timesteps)) latents_list = [latents] pred_x0_list = [latents] for i, t in enumerate(tqdm(reversed(self.scheduler.timesteps), desc="DDIM Inversion")): if num_actual_inference_steps is not None and i >= num_actual_inference_steps: continue model_inputs = latents # predict the noise # NOTE: the u-net here is UNet3D, therefore the model_inputs need to be of shape (b c f h w) model_inputs = rearrange(model_inputs, "f c h w -> 1 c f h w") noise_pred = self.unet(model_inputs, t, encoder_hidden_states=text_embeddings).sample noise_pred = rearrange(noise_pred, "b c f h w -> (b f) c h w") # compute the previous noise sample x_t-1 -> x_t latents, pred_x0 = self.next_step(noise_pred, t, latents) latents_list.append(latents) pred_x0_list.append(pred_x0) if return_intermediates: # return the intermediate laters during inversion return latents, latents_list return latents def interpolate_latents(self, latents: torch.Tensor, interpolation_factor: int, device): if interpolation_factor < 2: return latents new_latents = torch.zeros( (latents.shape[0], latents.shape[1], ((latents.shape[2] - 1) * interpolation_factor) + 1, latents.shape[3], latents.shape[4]), device=latents.device, dtype=latents.dtype, ) org_video_length = latents.shape[2] rate = [i / interpolation_factor for i in range(interpolation_factor)][1:] new_index = 0 v0 = None v1 = None for i0, i1 in zip(range(org_video_length), range(org_video_length)[1:]): v0 = latents[:, :, i0, :, :] v1 = latents[:, :, i1, :, :] new_latents[:, :, new_index, :, :] = v0 new_index += 1 for f in rate: v = get_tensor_interpolation_method()(v0.to(device=device), v1.to(device=device), f) new_latents[:, :, new_index, :, :] = v.to(latents.device) new_index += 1 new_latents[:, :, new_index, :, :] = v1 new_index += 1 return new_latents def select_controlnet_res_samples(self, controlnet_res_samples_cache_dict, context, do_classifier_free_guidance, b, f): _down_block_res_samples = [] _mid_block_res_sample = [] for i in np.concatenate(np.array(context)): _down_block_res_samples.append(controlnet_res_samples_cache_dict[i][0]) _mid_block_res_sample.append(controlnet_res_samples_cache_dict[i][1]) down_block_res_samples = [[] for _ in range(len(controlnet_res_samples_cache_dict[i][0]))] for res_t in _down_block_res_samples: for i, res in enumerate(res_t): down_block_res_samples[i].append(res) down_block_res_samples = [torch.cat(res) for res in down_block_res_samples] mid_block_res_sample = torch.cat(_mid_block_res_sample) # reshape controlnet output to match the unet3d inputs b = b // 2 if do_classifier_free_guidance else b _down_block_res_samples = [] for sample in down_block_res_samples: sample = rearrange(sample, '(b f) c h w -> b c f h w', b=b, f=f) if do_classifier_free_guidance: sample = sample.repeat(2, 1, 1, 1, 1) _down_block_res_samples.append(sample) down_block_res_samples = _down_block_res_samples mid_block_res_sample = rearrange(mid_block_res_sample, '(b f) c h w -> b c f h w', b=b, f=f) if do_classifier_free_guidance: mid_block_res_sample = mid_block_res_sample.repeat(2, 1, 1, 1, 1) return down_block_res_samples, mid_block_res_sample @torch.no_grad() def __call__( self, prompt: Union[str, List[str]], prompt_embeddings: Optional[torch.FloatTensor] = None, video_length: Optional[int] = 8, height: Optional[int] = None, width: Optional[int] = None, num_inference_steps: int = 50, guidance_scale: float = 7.5, negative_prompt: Optional[Union[str, List[str]]] = None, num_videos_per_prompt: Optional[int] = 1, eta: float = 0.0, generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, latents: Optional[torch.FloatTensor] = None, output_type: Optional[str] = "tensor", return_dict: bool = True, callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, callback_steps: Optional[int] = 1, controlnet_condition: list = None, controlnet_conditioning_scale: float = 1.0, context_frames: int = 16, context_stride: int = 1, context_overlap: int = 4, context_batch_size: int = 1, context_schedule: str = "uniform", init_latents: Optional[torch.FloatTensor] = None, num_actual_inference_steps: Optional[int] = None, appearance_encoder=None, unet=None, source_image: str = None, decoder_consistency=None, **kwargs, ): """ New args: - controlnet_condition : condition map (e.g., depth, canny, keypoints) for controlnet - controlnet_conditioning_scale : conditioning scale for controlnet - init_latents : initial latents to begin with (used along with invert()) - num_actual_inference_steps : number of actual inference steps (while total steps is num_inference_steps) """ controlnet = self.controlnet # Default height and width to unet height = height or self.unet.config.sample_size * self.vae_scale_factor width = width or self.unet.config.sample_size * self.vae_scale_factor # Check inputs. Raise error if not correct self.check_inputs(prompt, height, width, callback_steps) # Define call parameters # batch_size = 1 if isinstance(prompt, str) else len(prompt) batch_size = 1 if latents is not None: batch_size = latents.shape[0] if isinstance(prompt, list): batch_size = len(prompt) device = self._execution_device # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. do_classifier_free_guidance = guidance_scale > 1.0 # Encode input prompt if prompt_embeddings is None: prompt = prompt if isinstance(prompt, list) else [prompt] * batch_size if negative_prompt is not None: negative_prompt = negative_prompt if isinstance(negative_prompt, list) else [negative_prompt] * batch_size text_embeddings = self._encode_prompt( prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt ) text_embeddings = torch.cat([text_embeddings] * context_batch_size) else: text_embeddings = torch.cat([prompt_embeddings] * context_batch_size) reference_control_writer = ReferenceAttentionControl(appearance_encoder, do_classifier_free_guidance=do_classifier_free_guidance, mode='write', batch_size=context_batch_size, clip_length=context_frames) reference_control_reader = ReferenceAttentionControl(unet, do_classifier_free_guidance=do_classifier_free_guidance, mode='read', batch_size=context_batch_size, clip_length=context_frames) is_dist_initialized = kwargs.get("dist", False) rank = kwargs.get("rank", 0) world_size = kwargs.get("world_size", 1) # Prepare video assert num_videos_per_prompt == 1 # FIXME: verify if num_videos_per_prompt > 1 works assert batch_size == 1 # FIXME: verify if batch_size > 1 works control = self.prepare_condition( condition=controlnet_condition, device=device, dtype=controlnet.dtype, num_videos_per_prompt=num_videos_per_prompt, do_classifier_free_guidance=do_classifier_free_guidance, ) if do_classifier_free_guidance: controlnet_uncond_images, controlnet_cond_images = control.chunk(2) else: controlnet_cond_images = control # Prepare timesteps self.scheduler.set_timesteps(num_inference_steps, device=device) timesteps = self.scheduler.timesteps # Prepare latent variables if init_latents is not None: latents = rearrange(init_latents, "(b f) c h w -> b c f h w", f=video_length) else: num_channels_latents = self.unet.in_channels latents = self.prepare_latents( batch_size * num_videos_per_prompt, num_channels_latents, video_length, height, width, text_embeddings.dtype, device, generator, latents, clip_length=context_frames ) latents_dtype = latents.dtype # Prepare extra step kwargs. extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) # Prepare text embeddings for controlnet controlnet_text_embeddings = text_embeddings.repeat_interleave(video_length, 0) if do_classifier_free_guidance: _, controlnet_text_embeddings_c = controlnet_text_embeddings.chunk(2) else: controlnet_text_embeddings_c = controlnet_text_embeddings controlnet_res_samples_cache_dict = {i: None for i in range(video_length)} # For img2img setting if num_actual_inference_steps is None: num_actual_inference_steps = num_inference_steps if isinstance(source_image, str): ref_image_latents = self.images2latents(np.array(Image.open(source_image).resize((width, height)))[None, :], latents_dtype).to(device) elif isinstance(source_image, np.ndarray): ref_image_latents = self.images2latents(source_image[None, :], latents_dtype).to(device)
context_scheduler = get_context_scheduler(context_schedule)
3
2023-12-12 00:16:39+00:00
24k
qitan/devops-backend-lite
common/ext_fun.py
[ { "identifier": "generate_docu", "path": "common/utils/ElasticSearchAPI.py", "snippet": "def generate_docu(table, index_version=None):\n index_name = f\"{table.name}-{index_version}\" if index_version else table.name\n _tbindex = Index(index_name)\n _tbindex.analyzer(my_normalizer)\n _tbindex.settings(number_of_shards=3, number_of_replicas=1)\n _fields = Mapping().generate_data_mapping(table)\n docu = type(index_name, (CustomDocument,), _fields)\n return _tbindex.document(docu)" }, { "identifier": "Search", "path": "common/utils/ElasticSearchAPI.py", "snippet": "class Search(BaseSearch):\n def __init__(self, prefix=False, **kwargs):\n if kwargs.get('index', None) and prefix:\n if isinstance(kwargs['index'], string_types):\n kwargs['index'] = f\"{ELASTICSEARCH_PREFIX}{kwargs['index']}\"\n elif isinstance(kwargs['index'], list):\n kwargs['index'] = [\n f\"{ELASTICSEARCH_PREFIX}{i}\" for i in kwargs['index']]\n elif isinstance(kwargs['index'], tuple):\n kwargs['index'] = tuple(\n f\"{ELASTICSEARCH_PREFIX}{i}\" for i in kwargs['index'])\n else:\n raise Exception('索引名称格式错误!')\n super(Search, self).__init__(**kwargs)" }, { "identifier": "GitLabAPI", "path": "common/utils/GitLabAPI.py", "snippet": "class GitLabAPI(object):\n def __init__(self, url, user=None, password=None, token=None, oauth=False):\n self.__url = url\n if token:\n self.__token = token\n if oauth:\n params = {'oauth_token': self.__token}\n else:\n params = {'private_token': self.__token}\n self.__gl = gitlab.Gitlab(self.__url, **params)\n else:\n self.__gl = gitlab.Gitlab(\n self.__url, http_username=user, http_password=password)\n self.__gl.auth()\n\n def get_gl(self):\n return self.__gl\n\n def list_projects(self, get_all=False, key=None, per_page=20, page=1):\n params = {'per_page': per_page, 'page': page}\n if get_all:\n params = {'get_all': True, 'per_page': per_page}\n if key:\n params['search'] = key\n projects = self.__gl.projects.list(**params)\n return projects\n\n def get_project(self, project_id=None, project_name_with_namespace=None):\n if any([project_id, project_name_with_namespace]) is False:\n raise Exception('缺少参数,project_id或project_name_with_namespace必选其一.')\n condition = project_id or project_name_with_namespace\n try:\n project = self.__gl.projects.get(condition)\n return project\n except BaseException as e:\n logger.info(e)\n return None\n\n def create_project(self, name, namespace_id=None, initialize_with_readme=False):\n payload = {'name': name, 'path': name,\n 'initialize_with_readme': initialize_with_readme}\n if namespace_id:\n payload['namespace_id'] = namespace_id\n try:\n ret = self.__gl.projects.create(payload)\n return True, ret\n except BaseException as e:\n logger.exception(f'创建分支请求异常,原因:{e.__dict__}')\n return False, e\n\n def get_commit(self, commit_id, project_id=None, project_name_with_namespace=None):\n try:\n commit = self.get_project(\n project_id, project_name_with_namespace).get(commit_id)\n return commit\n except BaseException as e:\n logger.info(e)\n return None\n\n def list_groups(self, get_all=False, key=None, per_page=20, page=1):\n params = {'per_page': per_page, 'page': page}\n if get_all:\n params = {'get_all': True, 'all': True, 'per_page': per_page}\n if key:\n params['search'] = key\n groups = self.__gl.groups.list(**params)\n return [{'id': i.id, 'name': i.name, 'description': i.description} for i in groups if not i.parent_id]\n\n def create_group(self, name, path=None, desc=None, parent=None):\n \"\"\"\n 创建组\n \"\"\"\n payload = {'name': name, 'path': path or name,\n 'description': desc or ''}\n if parent:\n payload['parent_id'] = parent\n try:\n group = self.__gl.groups.create(payload)\n return True, group\n except BaseException as e:\n logger.info(e)\n return False, e\n\n def create_branch(self, project, src_branch, target_branch):\n payload = {'branch': target_branch,\n 'ref': src_branch}\n if isinstance(project, (int,)):\n project = self.get_project(project)\n try:\n ret = project.branches.create(payload)\n return True, ret\n except BaseException as e:\n logger.exception(f'创建分支请求异常,原因:{e.__dict__}')\n return False, e\n\n def list_branches(self, project_id=None, project_name_with_namespace=None, get_all=False, key=None, per_page=20,\n page=1, protected='0', *args, **kwargs):\n params = {'per_page': per_page, 'page': page}\n if not protected:\n protected = '0'\n if get_all:\n params = {'get_all': True, 'per_page': per_page}\n if key:\n params['search'] = key\n params.update(kwargs)\n branches = self.get_project(project_id=project_id,\n project_name_with_namespace=project_name_with_namespace).branches.list(**params)\n branches = [{'uid': f\"{G_COMMIT[0][0]}:{i.name}\", 'name': i.name, 'commit': i.commit, 'label': G_COMMIT[0][0], 'protected': i.protected}\n for i in branches]\n if protected != '0':\n # 过滤受保护分支\n _map = {'1': True, '2': False}\n branches = [i for i in branches if i['protected']\n == _map[protected]]\n return branches\n\n def list_protected_branches(self, project_id=None, project_name_with_namespace=None, get_all=False, key=None, per_page=20,\n page=1, *args, **kwargs):\n params = {'per_page': per_page, 'page': page}\n if get_all:\n params = {'get_all': True, 'per_page': per_page}\n if key:\n params['search'] = key\n params.update(kwargs)\n branches = self.get_project(project_id=project_id,\n project_name_with_namespace=project_name_with_namespace).protectedbranches.list(**params)\n branches = [{'uid': f\"{G_COMMIT[0][0]}:{i.name}\", 'name': i.name, 'commit': i.commit, 'label': G_COMMIT[0][0], 'protected': i.protected}\n for i in branches]\n return branches\n\n def list_tags(self, project_id=None, project_name_with_namespace=None, get_all=False, key=None, per_page=20,\n page=1):\n params = {'per_page': per_page, 'page': page}\n if get_all:\n params = {'get_all': True, 'per_page': per_page}\n if key:\n params['search'] = key\n tags = self.get_project(\n project_id, project_name_with_namespace).tags.list(**params)\n tags = [{'uid': f\"{G_COMMIT[1][0]}:{i.name}\", 'name': i.name, 'message': i.message, 'commit': i.commit,\n 'label': G_COMMIT[1][0]} for i in tags]\n return tags\n\n def list_commits(self, project_id=None, project_name_with_namespace=None, get_all=False, key=None, per_page=20,\n page=1, ref_name=None, since=None):\n params = {'per_page': per_page, 'page': page}\n if get_all:\n params = {'get_all': True, 'per_page': per_page}\n if key:\n params['search'] = key\n if ref_name:\n params['ref_name'] = ref_name\n if since:\n params['since'] = since\n commits = self.get_project(\n project_id, project_name_with_namespace).commits.list(**params)\n commits = [\n {'title': i.title, 'short_id': i.short_id, 'author_name': i.author_name, 'committer_name': i.committer_name,\n 'committed_date': i.committed_date, 'message': i.message, 'web_url': i.web_url} for i in commits]\n return commits\n\n def repo_checkout(self, repo):\n import subprocess\n git_url = repo.split('//')\n subprocess.call(\n ['git', 'clone', f\"{git_url[0]}//oauth2:{self.__token}@{git_url[1]}\"])\n\n def get_user_id(self, username):\n user_list = self.__gl.users.list(username=username)\n if user_list:\n return user_list[0].id\n else:\n return None\n\n def get_project_from_name(self, project_name):\n projects = self.__gl.projects.list(search=project_name)\n for p in projects:\n if p.name == project_name:\n return p\n return None\n\n def add_project_member(self, project, user_id, access_level):\n try:\n project.members.create(\n {'user_id': user_id, 'access_level': access_level})\n return True, '成功'\n except Exception as error:\n return False, error\n\n def del_project_member(self, project, user_id):\n try:\n project.members.delete(user_id)\n return True, '成功'\n except Exception as error:\n return False, error" }, { "identifier": "HarborAPI", "path": "common/utils/HarborAPI.py", "snippet": "class HarborAPI(object):\n def __init__(self, url, username, password):\n self.__url = url.rstrip('/')\n self.__user = username\n self.__password = password\n self.__token = base64.b64encode(\n bytes('%s:%s' % (self.__user, self.__password), encoding='utf-8'))\n self.__headers = dict()\n self.__headers[\"Accept\"] = \"application/json\"\n self.__headers['authorization'] = 'Basic %s' % str(\n self.__token, encoding='utf-8')\n\n def request(self, method, obj=None, prefix='/'):\n try:\n if method == 'get':\n req = requests.request(method, '%s%s' % (self.__url, prefix), params=obj, headers=self.__headers,\n verify=False)\n if req.status_code > 399:\n return {'ecode': req.status_code, 'message': f'{req.content}\\n{req.reason}'}\n res = {'ecode': req.status_code, 'data': req.json(), 'count': req.headers.get('X-Total-Count', None),\n 'next': req.headers.get('Link', None)}\n if method == 'delete':\n req = requests.request(method, '%s%s' % (\n self.__url, prefix), headers=self.__headers, verify=False)\n if req.status_code > 399:\n return {'ecode': req.status_code, 'message': f'{req.content}\\n{req.reason}'}\n res = {'ecode': req.status_code, 'data': req.content}\n if method in ['put', 'post']:\n req = requests.request(method, '%s%s' % (self.__url, prefix), json=obj, headers=self.__headers,\n verify=False)\n if req.status_code > 399:\n return {'ecode': req.status_code, 'message': f'{req.content}\\n{req.reason}'}\n res = {'ecode': req.status_code, 'data': req.content}\n if method == 'head':\n req = requests.request(method, '%s%s' % (\n self.__url, prefix), headers=self.__headers, verify=False)\n if req.status_code > 399:\n return {'ecode': req.status_code, 'message': f'{req.content}\\n{req.reason}'}\n res = {'ecode': req.status_code, 'data': req.content}\n except BaseException as e:\n raise e\n return res\n\n def systeminfo(self):\n res = self.request('get', prefix='/systeminfo')\n return res\n\n def get_users(self):\n res = self.request('get', prefix='/users')\n return res\n\n def get_projects(self, project_name=None, page=1, page_size=20):\n \"\"\"\n :project_name: The name of project\n :page: default is 1.\n :page_size: default is 10, maximum is 100.\n \"\"\"\n params = {'page': page, 'page_size': page_size}\n if project_name:\n params['name'] = project_name\n try:\n res = self.request('get', params, prefix='/projects')\n return res\n except BaseException as e:\n return {'ecode': 500, 'message': e}\n\n def get_repositories(self, project_id, page=1, page_size=20, repo=None):\n params = {'project_id': project_id,\n 'page': page, 'page_size': page_size}\n if repo:\n params['q'] = repo\n try:\n res = self.request('get', params, '/repositories')\n return res\n except BaseException as e:\n return {'ecode': 500, 'message': e}\n\n def get_tags(self, repo):\n try:\n res = self.request('get', prefix='/repositories/%s/tags' % repo)\n tags = [\n {'name': i['name'], 'created': i['created'], 'push_time': i.get(\n 'push_time', None), 'size': i['size']}\n for i in\n res['data']]\n tags.sort(key=lambda k: (k.get('created')), reverse=True)\n return {'ecode': 200, 'data': tags, 'count': len(tags)}\n except BaseException as e:\n return {'ecode': 500, 'message': e}\n\n def fetch_project(self, project_id):\n \"\"\"\n 获取项目信息\n \"\"\"\n try:\n res = self.request(\n 'get', {'project_id': project_id}, prefix=f'/projects/{project_id}')\n return res\n except BaseException as e:\n return {'ecode': 500, 'message': e}\n\n def fetch_tag(self, repo, tag):\n \"\"\"\n 获取指定镜像标签\n \"\"\"\n try:\n res = self.request(\n 'get', prefix=f'/repositories/{repo}/tags/{tag}')\n return res\n except BaseException as e:\n return {'ecode': 500, 'message': e}\n\n def create_project(self, project_name, public=True):\n \"\"\"\n 创建仓库项目\n \"\"\"\n try:\n data = {'project_name': project_name, 'metadata': {\n 'public': 'true' if public else 'false'}}\n res = self.request('post', obj=data, prefix='/projects')\n return res\n except BaseException as e:\n return {'ecode': 500, 'message': e}\n\n def update_project(self, project_id, *args, **kwargs):\n \"\"\"\n 更新仓库项目\n \"\"\"\n try:\n res = self.request('put', obj=kwargs,\n prefix=f'/projects/{project_id}')\n return res\n except BaseException as e:\n return {'ecode': 500, 'message': e}\n\n def project_exists(self, project_name):\n \"\"\"\n 查询项目是否存在\n \"\"\"\n try:\n res = self.request(\n 'head', prefix=f'/projects?project_name={project_name}')\n return res\n except BaseException as e:\n return {'ecode': 500, 'message': e}\n\n def patch_tag(self, repo, src_image, tag_name):\n \"\"\"\n 镜像打标签\n \"\"\"\n try:\n try:\n # 创建仓库项目\n res = self.create_project(repo.split('/')[0])\n except BaseException as e:\n pass\n data = {'tag': tag_name, 'src_image': src_image, 'override': True}\n res = self.request(\n 'post', obj=data, prefix='/repositories/%s/tags' % repo)\n return res\n except BaseException as e:\n return {'ecode': 500, 'message': e}\n\n def delete_tag(self, repo, tag):\n \"\"\"\n 删除标签\n \"\"\"\n try:\n res = self.request(\n 'delete', prefix=f'/repositories/{repo}/tags/{tag}')\n return res\n except BaseException as e:\n logger.ex\n return {'ecode': 500, 'message': e}\n\n def search(self, query):\n \"\"\"\n 搜索\n \"\"\"\n try:\n res = self.request('get', {'q': query}, prefix='/search')\n return res\n except BaseException as e:\n logger.exception(e)\n return {'ecode': 500, 'message': e}" }, { "identifier": "GlueJenkins", "path": "common/utils/JenkinsAPI.py", "snippet": "class GlueJenkins(Jenkins):\n\n def __init__(self, url=None, username=None, password=None):\n self.__url = url\n self.__username = username\n self.__password = password\n super(GlueJenkins, self).__init__(\n self.__url, self.__username, self.__password)\n\n def _get_encoded_params(self, params):\n for k, v in params.items():\n if k in [\"name\", \"msg\", \"short_name\", \"from_short_name\",\n \"to_short_name\", \"folder_url\", \"from_folder_url\", \"to_folder_url\"]:\n params[k] = quote(v.encode('utf8'))\n return params\n\n def _build_url(self, format_spec, variables=None):\n\n if variables:\n url_path = format_spec % self._get_encoded_params(variables)\n else:\n url_path = format_spec\n return str(urljoin(self.server, url_path))\n\n def assert_credential_exists(self, name, folder_name=None, domain_name='_',\n exception_message='credential[%s] does not exist.'):\n '''Raise an exception if credential does not exist in domain of folder\n\n :param name: Name of credential, ``str``\n :param folder_name: Folder name, ``str``\n :param domain_name: Domain name, default is '_', ``str``\n :param exception_message: Message to use for the exception.\n Formatted with ``name``, ``domain_name``,\n and ``folder_name``\n :throws: :class:`JenkinsException` whenever the credentail\n does not exist in domain of folder\n '''\n if not self.credential_exists(name, folder_name, domain_name):\n raise JenkinsException(exception_message\n % name)\n\n def get_credential_global_config(self, name, domain_name='_'):\n '''Get configuration of credential in domain of folder.\n :param name: Name of credentail, ``str``\n :param domain_name: Domain name, default is '_', ``str``\n :returns: Credential configuration (XML format)\n '''\n return self.jenkins_open(requests.Request(\n 'GET', self._build_url(CONFIG_CREDENTIAL_GLOBAL, locals())\n ))\n\n def get_credential_info(self, name, folder_name=None, domain_name='_'):\n '''Get credential information dictionary in domain of folder\n\n :param name: Name of credentail, ``str``\n :param folder_name: folder_name, ``str``\n :param domain_name: Domain name, default is '_', ``str``\n :returns: Dictionary of credential info, ``dict``\n '''\n try:\n response = self.jenkins_open(requests.Request(\n 'GET', self._build_url(CREDENTIAL_INFO_GLOBAL, locals())\n ))\n if response:\n return json.loads(response)\n else:\n raise JenkinsException('credential[%s] does not exist.' % name)\n except (req_exc.HTTPError, NotFoundException):\n raise JenkinsException('credential[%s] does not exist.' % name)\n except ValueError:\n raise JenkinsException(\n 'Could not parse JSON info for credential[%s].' % name\n )\n\n def credential_exists(self, name, folder_name=None, domain_name='_'):\n '''Check whether a credentail exists in domain of folder\n\n :param name: Name of credentail, ``str``\n :param folder_name: Folder name, ``str``\n :param domain_name: Domain name, default is '_', ``str``\n :returns: ``True`` if credentail exists, ``False`` otherwise\n '''\n try:\n return self.get_credential_info(name)['id'] == name\n except JenkinsException:\n return False\n\n def create_credential_global(self, name=None, user=None, password=None, secret=None, comment=None, domain_name='_'):\n '''Create credentail in domain of folder\n\n :param name: username\n :param password: password\n :param comment: comment, ``str``\n :param config_xml: New XML configuration, ``str``\n :param domain_name: Domain name, default is '_', ``str``\n '''\n st = shortuuid.ShortUUID()\n st.set_alphabet(\n f\"0123456789{''.join([chr(i) for i in range(ord('a'), ord('z') + 1)])}\")\n if name is None:\n name = '-'.join(['api', st.random(length=8),\n st.random(length=4), st.random(length=12)])\n config_xml = '''<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>\n <scope>GLOBAL</scope>\n <id>%s</id>\n <description>[%s] Created by DevOps Platform</description>\n <username>%s</username>\n <password>%s</password>\n</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>''' % (name, comment, user, password)\n if user is None:\n config_xml = '''<org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl>\n <scope>GLOBAL</scope>\n <id>%s</id>\n <description>[%s] Created by DevOps Platform</description>\n <secret>%s</secret>\n</org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl>''' % (name, comment, secret)\n if self.credential_exists(name):\n raise JenkinsException('credential[%s] already exists.' % name)\n\n self.jenkins_open(requests.Request(\n 'POST', self._build_url(CREATE_CREDENTIAL_GLOBAL, locals()),\n data=config_xml.encode('utf-8'),\n headers=DEFAULT_HEADERS\n ))\n self.assert_credential_exists(\n name, exception_message='create credential[%s] failed.')\n return {'status': 0, 'data': name}\n\n def reconfig_credential_global(self, name, user=None, password=None, secret=None, comment=None, domain_name='_'):\n \"\"\"\n Reconfig credential with new config in domain of folder\n :param name: name, ``str``\n :param user:\n :param password:\n :param secret:\n :param comment:\n :param domain_name: Domain name, default is '_', ``str``\n :return:\n \"\"\"\n reconfig_url = self._build_url(CONFIG_CREDENTIAL_GLOBAL, locals())\n config_xml = self.get_credential_global_config(name)\n xml_dict = xmltodict.parse(config_xml)\n if user is None:\n xml_dict['org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl']['secret'] = secret\n if comment:\n xml_dict['org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl']['description'] = comment\n else:\n xml_dict['com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl']['username'] = user\n xml_dict['com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl']['password'] = password\n if comment:\n xml_dict['com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl'][\n 'description'] = comment\n config_xml = xmltodict.unparse(xml_dict, pretty=True)\n self.jenkins_open(requests.Request(\n 'POST', reconfig_url,\n data=config_xml.encode('utf-8'),\n headers=DEFAULT_HEADERS\n ))\n\n def create_job(self, name, config_xml):\n '''Create a new Jenkins job\n\n :param name: Name of Jenkins job, ``str``\n :param config_xml: config file text, ``str``\n '''\n folder_url, short_name = self._get_job_folder(name)\n if self.job_exists(name):\n raise JenkinsException('job[%s] already exists' % (name))\n\n try:\n self.jenkins_open(requests.Request(\n 'POST', self._build_url(CREATE_JOB, locals()),\n data=config_xml.encode('utf-8'),\n headers=DEFAULT_HEADERS\n ))\n except NotFoundException:\n raise JenkinsException('Cannot create job[%s] because folder '\n 'for the job does not exist' % (name))\n self.assert_job_exists(name, 'create[%s] failed')\n\n def reconfig_job(self, name, config_xml):\n '''Change configuration of existing Jenkins job.\n\n To create a new job, see :meth:`Jenkins.create_job`.\n\n :param name: Name of Jenkins job, ``str``\n :param config_xml: New XML configuration, ``str``\n '''\n folder_url, short_name = self._get_job_folder(name)\n reconfig_url = self._build_url(CONFIG_JOB, locals())\n self.jenkins_open(requests.Request(\n 'POST', reconfig_url,\n data=config_xml.encode('utf-8'),\n headers=DEFAULT_HEADERS\n ))\n\n def get_stage_describe(self, name, number, node_number):\n \"\"\" 获取 单个stage 详情 \"\"\"\n folder_url, short_name = self._get_job_folder(name)\n try:\n response = self.jenkins_open(requests.Request(\n 'GET', self._build_url(STAGE_DES, locals())\n ))\n\n if response:\n return json.loads(response)\n else:\n raise JenkinsException('job[%s] number[%d] does not exist'\n % (name, number))\n except (req_exc.HTTPError, NotFoundException):\n raise JenkinsException('job[%s] number[%d] does not exist'\n % (name, number))\n except ValueError:\n raise JenkinsException(\n 'Could not parse JSON info for job[%s] number[%d]'\n % (name, number)\n )\n\n def get_stage_logs(self, name, number, node_number):\n \"\"\" 获取 stage 执行日志\"\"\"\n folder_url, short_name = self._get_job_folder(name)\n try:\n response = self.jenkins_open(requests.Request(\n 'GET', self._build_url(STAGE_LOG, locals())\n ))\n if response:\n return json.loads(response)\n else:\n raise JenkinsException('job[%s] number[%d] does not exist'\n % (name, number))\n except (req_exc.HTTPError, NotFoundException):\n raise JenkinsException('job[%s] number[%d] does not exist'\n % (name, number))\n except ValueError:\n raise JenkinsException(\n 'Could not parse JSON info for job[%s] number[%d]'\n % (name, number)\n )\n\n def get_stage_info(self, name, number, depth=0):\n\n folder_url, short_name = self._get_job_folder(name)\n try:\n response = self.jenkins_open(requests.Request(\n 'GET', self._build_url(STAGE_INFO, locals())\n ))\n if response:\n return json.loads(response)\n else:\n raise JenkinsException('job[%s] number[%d] does not exist'\n % (name, number))\n except (req_exc.HTTPError, NotFoundException):\n raise JenkinsException('job[%s] number[%d] does not exist'\n % (name, number))\n except ValueError:\n raise JenkinsException(\n 'Could not parse JSON info for job[%s] number[%d]'\n % (name, number)\n )\n\n def get_flow_detail(self, job_name, build_number):\n stage_data = self.get_stage_info(name=job_name, number=build_number)\n stages = stage_data.get('stages')\n for i in stages:\n logs = ''\n try:\n # 获取stage返回信息\n response = self.jenkins_open(requests.Request(\n 'GET', self._build_url(\n unquote(i['_links']['self']['href']), locals())\n ))\n if response:\n res = json.loads(response)\n for j in res['stageFlowNodes']:\n response = self.jenkins_open(requests.Request(\n 'GET', self._build_url(\n unquote(j['_links']['log']['href']), locals())\n ))\n res = json.loads(response)\n try:\n # 移除href html信息,保留链接文字\n import re\n pat = re.compile('<a href[^>]*>')\n logs = logs + '\\n' + \\\n pat.sub('', res['text'].replace('</a>', ''))\n except:\n pass\n else:\n raise JenkinsException('job[%s] number[%d] does not exist'\n % (job_name, build_number))\n except (req_exc.HTTPError, NotFoundException):\n raise JenkinsException('job[%s] number[%d] does not exist'\n % (job_name, build_number))\n except ValueError:\n raise JenkinsException(\n 'Could not parse JSON info for job[%s] number[%d]'\n % (job_name, build_number)\n )\n\n stage_data[\"stages\"][stages.index(i)]['logs'] = logs\n return stage_data\n\n def get_queue_item(self, number, depth=0):\n '''Get information about a queued item (to-be-created job).\n\n The returned dict will have a \"why\" key if the queued item is still\n waiting for an executor.\n\n The returned dict will have an \"executable\" key if the queued item is\n running on an executor, or has completed running. Use this to\n determine the job number / URL.\n\n :param name: queue number, ``int``\n :returns: dictionary of queued information, ``dict``\n '''\n url = self._build_url(Q_ITEM, locals())\n try:\n response = self.jenkins_open(requests.Request('GET', url))\n if response:\n return json.loads(response)\n else:\n raise JenkinsException('queue number[%d] does not exist'\n % number)\n except (req_exc.HTTPError, NotFoundException):\n raise JenkinsException('queue number[%d] does not exist' % number)\n except ValueError:\n raise JenkinsException(\n 'Could not parse JSON info for queue number[%d]' % number\n )\n\n def build_job(self, name, parameters=None, token=None):\n '''Trigger build job.\n\n This method returns a queue item number that you can pass to\n :meth:`Jenkins.get_queue_item`. Note that this queue number is only\n valid for about five minutes after the job completes, so you should\n get/poll the queue information as soon as possible to determine the\n job's URL.\n\n :param name: name of job\n :param parameters: parameters for job, or ``None``, ``dict``\n :param token: Jenkins API token\n :returns: ``int`` queue item\n '''\n response = self.jenkins_request(requests.Request(\n 'POST', self.build_job_url(name, parameters, token)))\n\n if 'Location' not in response.headers:\n raise EmptyResponseException(\n \"Header 'Location' not found in \"\n \"response from server[%s]\" % self.server)\n\n location = response.headers['Location']\n if location.endswith('/'):\n location = location[:-1]\n parts = location.split('/')\n number = int(parts[-1])\n return number\n\n def get_job_config(self, name):\n '''Get configuration of existing Jenkins job.\n\n :param name: Name of Jenkins job, ``str``\n :returns: job configuration (XML format)\n '''\n folder_url, short_name = self._get_job_folder(name)\n request = requests.Request(\n 'GET', self._build_url(CONFIG_JOB, locals()))\n return self.jenkins_open(request)\n\n def get_job_info(self, name, depth=0, fetch_all_builds=False):\n '''Get job information dictionary.\n\n :param name: Job name, ``str``\n :param depth: JSON depth, ``int``\n :param fetch_all_builds: If true, all builds will be retrieved\n from Jenkins. Otherwise, Jenkins will\n only return the most recent 100\n builds. This comes at the expense of\n an additional API call which may\n return significant amounts of\n data. ``bool``\n :returns: dictionary of job information\n '''\n folder_url, short_name = self._get_job_folder(name)\n try:\n response = self.jenkins_open(requests.Request(\n 'GET', self._build_url(JOB_INFO, locals())\n ))\n if response:\n if fetch_all_builds:\n return self._add_missing_builds(json.loads(response))\n else:\n return json.loads(response)\n else:\n raise JenkinsException('job[%s] does not exist' % name)\n except (req_exc.HTTPError, NotFoundException):\n raise JenkinsException('job[%s] does not exist' % name)\n except ValueError:\n raise JenkinsException(\n \"Could not parse JSON info for job[%s]\" % name)" }, { "identifier": "convert_xml_to_str_with_pipeline", "path": "common/custom_format.py", "snippet": "def convert_xml_to_str_with_pipeline(xml, url, secret, desc, jenkinsfile, scm=True):\n \"\"\"\n scm\n True: jenkinsfile为指定的git地址\n False: jenkinsfile为具体的pipeline\n \"\"\"\n xml_dict = xmltodict.parse(xml)\n if scm:\n xml_dict['flow-definition']['definition']['@class'] = 'org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition'\n xml_dict['flow-definition']['definition']['scm']['userRemoteConfigs']['hudson.plugins.git.UserRemoteConfig'][\n 'url'] = url\n xml_dict['flow-definition']['definition']['scm']['userRemoteConfigs']['hudson.plugins.git.UserRemoteConfig'][\n 'credentialsId'] = secret\n xml_dict['flow-definition']['definition']['scriptPath'] = jenkinsfile\n else:\n xml_dict['flow-definition']['definition']['@class'] = 'org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition'\n xml_dict['flow-definition']['definition']['script'] = jenkinsfile\n xml_dict['flow-definition']['definition']['sandbox'] = 'true'\n xml_dict['flow-definition']['description'] = desc\n result = xmltodict.unparse(\n xml_dict, short_empty_elements=True, pretty=True)\n return result" }, { "identifier": "DASHBOARD_TIME_FORMAT", "path": "common/variables.py", "snippet": "DASHBOARD_TIME_FORMAT = {'year_only': '%Y', 'years': '%Y-%m', 'months': '%Y-%m-%d', 'days': '%Y-%m-%d %H:00:00',\n 'hours': '%Y-%m-%d %H:%M:00', 'minutes': '%Y-%m-%d %H:%M:%S'}" }, { "identifier": "DASHBOARD_TIME_FORMAT_T", "path": "common/variables.py", "snippet": "DASHBOARD_TIME_FORMAT_T = {'years': '%Y', 'months': '%Y-%m', 'days': '%Y-%m-%d', 'hours': \"%Y-%m-%d %H:00:00\",\n 'minutes': \"%Y-%m-%d %H:%M:00\", 'seconds': \"%Y-%m-%d %H:%M:%S\"}" }, { "identifier": "DASHBOARD_TIME_FREQNAMES", "path": "common/variables.py", "snippet": "DASHBOARD_TIME_FREQNAMES = {'year_only': YEARLY, 'years': MONTHLY, 'months': DAILY, 'days': HOURLY, 'hours': MINUTELY,\n 'minutes': SECONDLY}" }, { "identifier": "DASHBOARD_TIME_FREQNAMES_T", "path": "common/variables.py", "snippet": "DASHBOARD_TIME_FREQNAMES_T = {'years': YEARLY, 'months': MONTHLY, 'days': DAILY, 'hours': HOURLY, 'minutes': MINUTELY,\n 'seconds': SECONDLY}" }, { "identifier": "SENSITIVE_KEYS", "path": "common/variables.py", "snippet": "SENSITIVE_KEYS = ['password', 'token', 'access',\n 'refresh', 'AUTHORIZATION', 'COOKIE']" }, { "identifier": "JENKINS_CALLBACK_KEY", "path": "common/variables.py", "snippet": "JENKINS_CALLBACK_KEY = 'jenkins_callback_flag::'" }, { "identifier": "JENKINS_STATUS_MAP", "path": "common/variables.py", "snippet": "JENKINS_STATUS_MAP = {'IN_PROGRESS': 3, 'SUCCESS': 1, 'FAILED': 2, 'ABORTED': 4, 'FAILURE': 2, 'NOT_EXECUTED': 5,\n 'NOT_EXEC_TIMEOUT': 5}" }, { "identifier": "DEV_LANGUAGE_KEY", "path": "common/variables.py", "snippet": "DEV_LANGUAGE_KEY = 'devlanguage:'" }, { "identifier": "AppInfo", "path": "dbapp/models.py", "snippet": "" }, { "identifier": "K8sAPI", "path": "common/utils/K8sAPI.py", "snippet": "class K8sAPI(object):\n def __init__(self, host=None, username=None, password=None, api_key=None, api_key_prefix='Bearer', verify_ssl=False,\n k8s_config=None,\n config_file=None, eks=None):\n \"\"\"\n elk: aws kubernetes\n \"\"\"\n self.__host = host\n self.__username = username\n self.__password = password\n self.__api_key = api_key\n self.__api_key_prefix = api_key_prefix\n self.__verify_ssl = verify_ssl\n if k8s_config is not None:\n config.kube_config.load_kube_config_from_dict(k8s_config)\n self.__client0 = client.CoreApi()\n self.__client = client.CoreV1Api()\n elif config_file is not None:\n config.kube_config.load_kube_config(config_file=config_file)\n self.__client0 = client.CoreApi()\n self.__client = client.CoreV1Api()\n elif self.__host:\n if self.__username and self.__password:\n self.__client = self.get_api()\n else:\n raise Exception('Please input username/password or api_key')\n else:\n raise Exception('Cannot find k8s config')\n self.client = self.__client\n\n def get_token(self):\n pass\n\n def get_api(self):\n configuration = client.Configuration()\n configuration.host = self.__host\n if self.__verify_ssl is False:\n configuration.verify_ssl = False\n configuration.username = self.__username\n configuration.password = self.__password\n basic_auth_token = configuration.get_basic_auth_token()\n api = core_v1_api.CoreV1Api(api_client.ApiClient(configuration=configuration, header_name=\"authorization\",\n header_value=basic_auth_token))\n return api\n\n def get_client(self):\n return self.__client\n\n def set_client(self, obj):\n self.__client = getattr(client, obj)()\n\n def get_apis(self):\n print(\"Supported APIs (* is preferred version):\")\n self.__client2 = client.ApisApi(self.__client0.api_client)\n for api in self.__client2.get_api_versions().groups:\n versions = []\n for v in api.versions:\n name = \"\"\n if v.version == api.preferred_version.version and len(\n api.versions) > 1:\n name += \"*\"\n name += v.version\n versions.append(name)\n\n def get_nodes(self, **kwargs):\n ret = self.__client.list_node(**kwargs)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return rs\n except BaseException as e:\n return {'err': str(e)}\n\n def get_node_info(self, name):\n ret = self.__client.read_node_status(name)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return rs\n except BaseException as e:\n return {'err': str(e)}\n\n def get_namespaces(self, **kwargs):\n ret = self.__client.list_namespace(**kwargs)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return rs\n except BaseException as e:\n return {'err': str(e)}\n\n def create_namespace(self, name):\n payload = {\n \"apiVersion\": \"v1\",\n \"kind\": \"Namespace\",\n \"metadata\": {\n \"name\": name,\n }\n }\n ret = self.__client.create_namespace(body=payload)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n print(rs)\n return rs\n except BaseException as e:\n return {'err': str(e)}\n\n def get_services(self, namespace='default', **kwargs):\n ret = self.__client.list_namespaced_service(namespace, **kwargs)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return rs\n except BaseException as e:\n return {'err': str(e)}\n\n def fetch_service(self, name, namespace='default', api_version='apps/v1'):\n try:\n ret = self.__client.read_namespaced_service(name, namespace)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return {'ecode': 200, 'message': rs}\n except BaseException as e:\n print('reason', e.reason)\n return {'ecode': e.status, 'message': e.body}\n except BaseException as e:\n print('reason', e.reason)\n return {'ecode': e.status, 'message': e.body}\n\n def create_namespace_service(self, name, app=None, targets=list, namespace='default', service_type='NodePort',\n svc_yaml=None):\n \"\"\"\n 目前只支持NodePort类型,对外服务端口随机生成(如手动生成,需配置node_port和endpoints)\n :param name: service name\n :param app: app name\n :param targets: [{port, target_port, protocol, node_port}]\n :param namespace:\n :param service_type:\n :return:\n \"\"\"\n ports = []\n if svc_yaml:\n if isinstance(svc_yaml, str):\n body = yaml.safe_load(svc_yaml)\n else:\n body = svc_yaml\n else:\n for index, target in enumerate(targets):\n port_body = {'name': f\"{name}-{index}\", 'port': target['port'], 'target_port': target['port'],\n 'protocol': target['protocol']}\n if target['node_port'] > 30000:\n port_body['node_port'] = target['node_port']\n ports.append(client.V1ServicePort(**port_body))\n body = client.V1Service(\n api_version=\"v1\",\n kind=\"Service\",\n metadata=client.V1ObjectMeta(\n name=name\n ),\n spec=client.V1ServiceSpec(\n selector={\"app\": app},\n type=service_type,\n ports=ports\n )\n )\n try:\n ret = self.__client.create_namespaced_service(namespace=namespace, body=body,\n **{'_return_http_data_only': False})\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return {'ecode': 200, 'message': rs}\n except BaseException as e:\n logger.error('reason', e)\n return {'error': True, 'message': str(e)}\n except ApiException as e:\n if e.status == 409:\n logger.error('reason', e.reason)\n return {'error': True, 'ecode': e.status, 'message': e.body}\n except BaseException as e:\n return {'error': True, 'message': str(e)}\n\n def update_namespace_service(self, name, app=None, targets=Type[list], namespace='default', service_type='NodePort',\n svc_yaml=None):\n ports = []\n if svc_yaml:\n if isinstance(svc_yaml, str):\n body = yaml.safe_load(svc_yaml)\n else:\n body = svc_yaml\n logger.debug(f'svc_yaml body == {body}')\n func = self.__client.replace_namespaced_service\n else:\n for index, target in enumerate(targets):\n port_body = {'name': target['name'], 'port': target['port'], 'target_port': target['port'],\n 'protocol': target['protocol']}\n if target['node_port'] > 30000:\n port_body['node_port'] = target['node_port']\n ports.append(client.V1ServicePort(**port_body))\n body = client.V1Service(\n api_version=\"v1\",\n kind=\"Service\",\n metadata=client.V1ObjectMeta(\n name=name\n ),\n spec=client.V1ServiceSpec(\n selector={\"app\": name},\n type=service_type,\n ports=ports\n )\n )\n func = self.__client.patch_namespaced_service\n try:\n ret = func(\n name, namespace, body=body,\n **{'_return_http_data_only': False}\n )\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return {'ecode': 200, 'message': rs}\n except BaseException as e:\n logger.error(f'ApiClient sanitize_for_serialization 异常: {e}', )\n return {'error': True, 'message': str(e)}\n except ApiException as e:\n if e.status == 409:\n logger.error(f'ApiException 异常 409 资源冲突: {e} {e.reason}', )\n return {'error': True, 'ecode': e.status, 'message': e.body}\n except BaseException as e:\n logger.error(f'patch_namespaced_service 异常: {e}', )\n return {'error': True, 'message': str(e)}\n\n def delete_namespace_service(self, name, namespace='default', api_version='apps/v1'):\n try:\n ret = self.__client.delete_namespaced_service(name, namespace)\n rs = ApiClient().sanitize_for_serialization(ret)\n return {'ecode': 200, 'message': rs}\n except BaseException as e:\n return {'error': True, 'message': str(e)}\n\n def get_configmaps(self, namespace='default', **kwargs):\n ret = self.__client.list_namespaced_config_map(namespace, **kwargs)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return rs\n except BaseException as e:\n return {'error': True, 'message': str(e)}\n\n def get_configmap(self, name, namespace='default', **kwargs):\n \"\"\"\n get configmap content\n \"\"\"\n try:\n ret = self.__client.read_namespaced_config_map(\n name, namespace, **kwargs)\n rs = ApiClient().sanitize_for_serialization(ret)\n return rs\n except BaseException as e:\n return {'error': True, 'message': str(e)}\n\n def create_namespace_configmap(self, svc_yaml, namespace='default', **kwargs):\n if isinstance(svc_yaml, str):\n body = yaml.safe_load(svc_yaml)\n else:\n body = svc_yaml\n try:\n ret = self.__client.create_namespaced_config_map(\n namespace, body, **kwargs)\n rs = ApiClient().sanitize_for_serialization(ret)\n return {'ecode': 200, 'message': rs}\n except BaseException as e:\n return {'error': True, 'message': str(e)}\n\n def update_namespace_configmap(self, name, svc_yaml, namespace='default', **kwargs):\n if isinstance(svc_yaml, str):\n body = yaml.safe_load(svc_yaml)\n else:\n body = svc_yaml\n try:\n ret = self.__client.patch_namespaced_config_map(\n name, namespace, body, **kwargs)\n rs = ApiClient().sanitize_for_serialization(ret)\n return {'ecode': 200, 'message': rs}\n except BaseException as e:\n return {'error': True, 'message': str(e)}\n\n def delete_namespace_configmap(self, name, namespace='default', api_version='apps/v1'):\n try:\n ret = self.__client.delete_namespaced_config_map(name, namespace)\n rs = ApiClient().sanitize_for_serialization(ret)\n return {'ecode': 200, 'message': rs}\n except BaseException as e:\n return {'error': True, 'message': str(e)}\n\n def get_namespace_deployment(self, namespace='default', api_version='apps/v1', **kwargs):\n self.__client2 = operator.methodcaller(''.join([i.capitalize() for i in api_version.split('/')]) + 'Api',\n self.__client.api_client)(client)\n ret = self.__client2.list_namespaced_deployment(namespace, **kwargs)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return rs\n except BaseException as e:\n return {'err': str(e)}\n\n def create_namespace_deployment(self, name, image=None, port=list, replicas=1, deploy_yaml=None,\n pod_type='Deployment', namespace='default'):\n \"\"\"\n\n :param name:\n :param image:\n :param port: [{containerPort: 8080, protocol: 'TCP'}]\n :param replicas:\n :param pod_type:\n :param namespace:\n :return:\n \"\"\"\n payload = {'kind': pod_type, 'spec': {'replicas': replicas, 'template': {\n 'spec': {'containers': [{'image': image, 'name': name, 'ports': port}]},\n 'metadata': {'labels': {'app': name}}},\n 'selector': {'matchLabels': {'app': name}}},\n 'apiVersion': 'apps/v1beta2',\n 'metadata': {'labels': {'app': name}, 'namespace': namespace,\n 'name': name}}\n if deploy_yaml is not None:\n payload = yaml.safe_load(deploy_yaml)\n payload['metadata'].pop('resourceVersion', None)\n self.__client2 = operator.methodcaller(\n ''.join([i.capitalize() for i in payload.get(\n 'apiVersion', 'apps/v1beta2').split('/')]) + 'Api',\n self.__client.api_client)(client)\n try:\n ret = self.__client2.create_namespaced_deployment(\n namespace=namespace, body=payload)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return {'ecode': 200, 'message': rs}\n except BaseException as e:\n return {'ecode': e.status, 'message': e.body}\n except ApiException as e:\n return {'ecode': e.status, 'message': e.body}\n\n def delete_namespace_deployment(self, name, namespace='default', api_version='apps/v1'):\n self.__client2 = operator.methodcaller(''.join([i.capitalize() for i in api_version.split('/')]) + 'Api',\n self.__client.api_client)(client)\n ret = self.__client2.delete_namespaced_deployment(name, namespace,\n body=client.V1DeleteOptions(grace_period_seconds=0,\n propagation_policy='Foreground'))\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return rs\n except BaseException as e:\n return {'err': str(e)}\n\n def update_deployment(self, name, replicas=None, image=None, envs=None, deploy_yaml=None, namespace='default',\n api_version='apps/v1', force=False):\n \"\"\"\n force: 强制更新\n \"\"\"\n self.__client2 = operator.methodcaller(''.join([i.capitalize() for i in api_version.split('/')]) + 'Api',\n self.__client.api_client)(client)\n payload = {'spec': {'replicas': replicas, 'template': {}}}\n if replicas is None and image is None and deploy_yaml is None:\n return {'err': '缺少参数'}\n if replicas is not None:\n payload['spec']['replicas'] = replicas\n if image is not None:\n payload['spec']['template'] = {\n 'spec': {'containers': [{'image': image, 'name': name}]}}\n\n if envs is not None:\n payload['spec']['template'] = {\n 'spec': {'containers': [{'env': envs}]}}\n\n if deploy_yaml is not None:\n payload = yaml.safe_load(deploy_yaml)\n payload['metadata'].pop('resourceVersion', None)\n try:\n if force:\n ret = self.__client2.replace_namespaced_deployment(\n name, namespace, body=payload)\n else:\n ret = self.__client2.patch_namespaced_deployment(\n name, namespace, body=payload)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return {'ecode': 200, 'message': rs}\n except BaseException as e:\n return {'ecode': e.status, 'message': e.body}\n except ApiException as e:\n return {'ecode': e.status, 'message': e.body}\n\n def update_deployment_replica(self, name, replicas, namespace='default', api_version='apps/v1'):\n self.__client2 = operator.methodcaller(''.join([i.capitalize() for i in api_version.split('/')]) + 'Api',\n self.__client.api_client)(client)\n payload = {'spec': {'replicas': replicas}}\n ret = self.__client2.patch_namespaced_deployment_scale(\n name, namespace, body=payload)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return rs\n except BaseException as e:\n return {'err': str(e)}\n\n def update_deployment_image(self, name, image, namespace='default', api_version='apps/v1'):\n deploy = self.fetch_deployment(name, namespace)\n if deploy.get('ecode', 200) > 399:\n return deploy\n payload = {'spec': deploy['message']['spec']}\n payload['spec']['template']['spec']['containers'][0]['image'] = image\n self.__client2 = operator.methodcaller(''.join([i.capitalize() for i in api_version.split('/')]) + 'Api',\n self.__client.api_client)(client)\n try:\n ret = self.__client2.patch_namespaced_deployment(name, namespace, body=payload,\n **{'_return_http_data_only': False})\n except ApiException as e:\n return {'ecode': e.status, 'message': e.body}\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return {'ecode': 200, 'message': rs}\n except BaseException as e:\n return {'ecode': e.status, 'message': e.body}\n\n def update_deployment_resource(self, name, envs, image_policy, namespace='default', api_version='apps/v1',\n **kwargs):\n payload = {'spec': {'template': {'spec': {'containers': [\n {'name': name, 'env': envs, 'imagePullPolicy': image_policy, 'resources': kwargs['resources']}]}}}}\n self.__client2 = operator.methodcaller(''.join([i.capitalize() for i in api_version.split('/')]) + 'Api',\n self.__client.api_client)(client)\n ret = self.__client2.patch_namespaced_deployment(\n name, namespace, body=payload)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return rs\n except BaseException as e:\n return {'err': str(e)}\n\n def restart_deployment(self, name, namespace='default', api_version='apps/v1'):\n self.__client2 = operator.methodcaller(''.join([i.capitalize() for i in api_version.split('/')]) + 'Api',\n self.__client.api_client)(client)\n payload = {\n 'spec': {\n 'template': {\n 'spec': {\n 'containers': [\n {\n 'name': name,\n 'env': [\n {\n 'name': 'RESTART_',\n 'value': datetime.now().strftime('%Y%m%d%H%M%S')\n }\n ]\n }\n ]\n }\n }\n }\n }\n\n ret = self.__client2.patch_namespaced_deployment(\n name, namespace, body=payload)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return rs\n except BaseException as e:\n return {'err': str(e)}\n\n def fetch_deployment(self, name, namespace='default', api_version='apps/v1'):\n self.__client2 = operator.methodcaller(''.join([i.capitalize() for i in api_version.split('/')]) + 'Api',\n self.__client.api_client)(client)\n try:\n ret = self.__client2.read_namespaced_deployment(name, namespace)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return {'ecode': 200, 'message': rs}\n except ApiException as e:\n return {'ecode': e.status, 'message': e.body}\n except ApiException as e:\n return {'ecode': e.status, 'message': e.body}\n\n def get_replica(self, namespace='default', api_version='apps/v1', **kwargs):\n self.__client2 = operator.methodcaller(''.join([i.capitalize() for i in api_version.split('/')]) + 'Api',\n self.__client.api_client)(client)\n try:\n ret = self.__client2.list_namespaced_replica_set(\n namespace=namespace, **kwargs)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return {'ecode': 200, 'message': rs}\n except ApiException as e:\n return {'ecode': e.status, 'message': e.body}\n except ApiException as e:\n return {'ecode': e.status, 'message': e.body}\n\n def get_pods(self, namespace=None, **kwargs):\n if namespace is None:\n return {}\n try:\n ret = self.__client.list_namespaced_pod(namespace, **kwargs)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return {'ecode': 200, 'message': rs}\n except BaseException as e:\n return {'ecode': e.status, 'message': e.body}\n except ApiException as e:\n return {'ecode': e.status, 'message': e.body}\n\n def fetch_pod(self, name, namespace='default'):\n try:\n ret = self.__client.read_namespaced_pod(\n name=name, namespace=namespace)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return {'ecode': 200, 'message': rs}\n except BaseException as e:\n return {'ecode': e.status, 'message': e.body}\n except BaseException as e:\n return {'ecode': e.status, 'message': e.body}\n\n def get_secrets(self, namespace='default', **kwargs):\n ret = self.__client.list_namespaced_secret(namespace, **kwargs)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return rs\n except BaseException as e:\n return {'error': True, 'message': str(e)}\n\n def get_secret(self, name, namespace='default', **kwargs):\n \"\"\"\n get secret content\n \"\"\"\n ret = self.__client.read_namespaced_secret(name, namespace, **kwargs)\n try:\n ret = self.__client.read_namespaced_secret(\n name, namespace, **kwargs)\n rs = ApiClient().sanitize_for_serialization(ret)\n return rs\n except BaseException as e:\n return {'error': True, 'message': str(e)}\n\n def manage_secret(self, name, namespace='default', api_version='v1', **kwargs):\n payload = kwargs.pop('payload', {})\n body = kubernetes.client.V1Secret(api_version=api_version, **payload)\n ret = {}\n try:\n ret = self.__client.replace_namespaced_secret(\n name, namespace, body, **kwargs)\n except ApiException as e:\n if e.status == 404:\n ret = self.__client.create_namespaced_secret(namespace, body)\n try:\n rs = ApiClient().sanitize_for_serialization(ret)\n return rs\n except BaseException as e:\n return {'error': True, 'message': str(e)}" } ]
from gitlab.exceptions import GitlabGetError from functools import reduce from common.utils.ElasticSearchAPI import generate_docu, Search from common.utils.GitLabAPI import GitLabAPI from common.utils.HarborAPI import HarborAPI from common.utils.JenkinsAPI import GlueJenkins from common.custom_format import convert_xml_to_str_with_pipeline from common.variables import DASHBOARD_TIME_FORMAT, DASHBOARD_TIME_FORMAT_T, DASHBOARD_TIME_FREQNAMES, \ DASHBOARD_TIME_FREQNAMES_T, SENSITIVE_KEYS, JENKINS_CALLBACK_KEY, \ JENKINS_STATUS_MAP, DEV_LANGUAGE_KEY from dbapp.models import AppInfo, Product, KubernetesCluster, KubernetesDeploy, MicroApp, Project, ProjectConfig, DevLanguage, BuildJob, UserProfile, SystemConfig, Role, Permission, Menu, DataDict from django.conf import settings from django.core.cache import cache from django.utils import timezone from django.db.models import Q from social_django.utils import load_strategy from rest_framework.utils.serializer_helpers import ReturnDict from config import SOCIAL_AUTH_GITLAB_API_URL, GITLAB_ADMIN_TOKEN from common.utils.K8sAPI import K8sAPI from urllib.parse import urlparse, quote_plus from dateutil.relativedelta import relativedelta from dateutil.rrule import rrule from ruamel import yaml from datetime import datetime, timedelta from celery import current_app import copy import operator import re import time import pytz import os import json import requests import math import shortuuid import logging
17,777
for i in envs: try: env_value = i.get('value', None) cmname = i.pop('cmname', None) cmkey = i.pop('cmkey', None) if env_value: env_value = env_value.lstrip('"').rstrip( '"').lstrip("'").rstrip("'") i.pop('value', None) i['name'] = i['name'].lstrip('"').rstrip( '"').lstrip("'").rstrip("'") if i.get('valueFrom', None) == 'configMapKeyRef': i['valueFrom'] = {'configMapKeyRef': { 'name': cmname, 'key': cmkey}} else: i['value'] = env_value i['valueFrom'] = None except BaseException as e: pass yaml_template['spec']['template']['spec']['containers'][0]['env'] = envs if template.get('health', False): _d = health_lifecycle_generate('health', True) for k, v in _d.items(): yaml_template['spec']['template']['spec']['containers'][0][k] = v if template.get('lifecycle', False): yaml_template['spec']['template']['spec']['containers'][0]['lifecycle'] = { } _d = health_lifecycle_generate('lifecycle', False) for k, v in _d.items(): yaml_template['spec']['template']['spec']['containers'][0]['lifecycle'][k] = v _vo_mount = [{'mountPath': '/data/logs', 'name': 'logs', 'readOnly': False}] _volumes = [{'name': 'logs', 'type': 'Directory', 'hostPath': { 'path': f'/data/{appinfo_obj.environment.name}-applogs/{appinfo_obj.app.project.name}/'}}] if template.get('storage', None): for k, v in template['storage']['data'].items(): for i in v: _x = {} for m, n in i.items(): if isinstance(n, (str,)): n = n.replace('${APPNAME}', appinfo_obj.app.name) if '_' in m: _t = m.split('_') if _x.get(_t[0], None): _x[_t[0]][_t[1]] = n else: _x[_t[0]] = {_t[1]: n} else: _x[m] = n _t = {'mountPath': _x['mount'], 'name': _x['name'], 'readOnly': True if _x.get('mode', None) == 'ReadOnly' else False} if _x.get('file', None): _t['subPath'] = _x['configMap']['items'][0]['key'] _vo_mount.append(_t) _mode = _x.pop('mode', None) _x.pop('file', None) _x.pop('mount', None) if _x.get('configMap', None): _x['configMap']['defaultMode'] = 0o600 if _mode == 'ReadOnly' else 0o755 _volumes.append(_x) yaml_template['spec']['template']['spec']['containers'][0]['volumeMounts'] = _vo_mount yaml_template['spec']['template']['spec']['volumes'] = _volumes if use_host_network: yaml_template['spec']['template']['spec']['hostNetwork'] = True partial_deploy_yaml_template = None except BaseException as e: logger.exception(f'generate yaml err {e.__class__} {e}') return {'ecode': 500, 'message': str(e)} # 多容器处理 if appinfo_obj.template.get('containers_custom', None): containers = container_generate( appinfo_obj.template.get('containers', [])) else: containers = container_generate( project_config.first().template.get('containers', [])) yaml_template['spec']['template']['spec']['containers'].extend(containers) ret = {'ecode': 200, 'image': image, 'yaml': yaml_template} if partial_deploy_yaml_template: ret['partial_deploy_yaml'] = partial_deploy_yaml_template return ret def get_members(obj): team_members = [j for i in obj.team_members.values() for j in i] return list(set(team_members)) def get_permission_from_role(request): try: perms = request.user.roles.values( 'permissions__method', ).distinct() return [p['permissions__method'] for p in perms] except AttributeError: return [] def get_headers(request=None): """ Function: get_headers(self, request) Description: To get all the headers from request """ regex = re.compile('^HTTP_') return dict((regex.sub('', header), value) for (header, value) in request.META.items() if header.startswith('HTTP_')) def mask_sensitive_data(data): """ Hides sensitive keys specified in sensitive_keys settings. Loops recursively over nested dictionaries. """ if hasattr(settings, 'DRF_API_LOGGER_EXCLUDE_KEYS'): if type(settings.DRF_API_LOGGER_EXCLUDE_KEYS) in (list, tuple):
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author : Charles Lai @Contact : [email protected] @Time : 2020/12/21 上午10:00 @FileName: ext_fun.py @Blog :https://imaojia.com """ logger = logging.getLogger('drf') class ThirdPartyUser(object): def get_user(self): user = UserProfile.objects.get_or_create(username='thirdparty')[0] self.set_permission(user, self.get_role()) return user def get_role(self): return Role.objects.get_or_create(name='thirdparty')[0] def get_perm(self): return Permission.objects.get_or_create(name='Jenkins回调', method='jenkins_callback')[0] def set_permission(self, user, role): role.permissions.set([self.get_perm().id]) user.roles.set([role.id]) def set_redis_data(name, config): cache.set(f"system:{name}", config, None) def get_redis_data(name): ret = cache.get(f"system:{name}") if not ret: try: if name == 'cicd-harbor': qs = SystemConfig.objects.filter(type=name)[0] else: qs = SystemConfig.objects.get(name=name) except BaseException as e: return None ret = json.loads(qs.config) set_redis_data(name, ret) return ret def get_datadict(name, config=0, default_value=None): """ 从数据字典获取数据 """ try: qs = DataDict.objects.get(key=name) except BaseException as e: return default_value if config: ret = json.loads(qs.extra) else: ret = {'id': qs.id, 'key': qs.key, 'value': qs.value, 'desc': qs.desc} return ret def check_pods(cluster_id, k8s_config, namespace, **kwargs): k8s = KubernetesCluster.objects.get(id=cluster_id) cli = k8s_cli(k8s, k8s_config) if not cli: return False count = 3 while count: ret2 = cli.get_pods(namespace, **kwargs) count -= 1 if len(ret2['items']) > 0: return True else: check_pods(k8s_config, namespace, **kwargs) return False def template_svc_generate(appinfo_obj): """ 生成Kubernetes Svc Yaml ### 格式: { "apiVersion": "v1", "kind": "Service", "metadata": { "name": "appname", "namespace": "env-product", "labels": { "app": "appname" } }, "spec": { "ports": [{ "port": 8080, "targetPort": 8080, "protocol": "TCP", "name": "http" }], "selector": { "app": "appname" } } } """ svc_temp = DataDict.objects.filter(key='yaml.svc') if svc_temp.exists(): svc_temp = json.loads(svc_temp.first().extra) if appinfo_obj.environment.name in svc_temp: svc_temp = svc_temp[appinfo_obj.environment.name] namespace = appinfo_obj.namespace svc_temp['metadata']['name'] = appinfo_obj.app.name svc_temp['metadata']['namespace'] = namespace svc_temp['metadata']['labels'] = {'app': appinfo_obj.app.name} labels = [] labels.extend([{'name': 'app', 'value': appinfo_obj.app.name}]) svc_temp['spec']['selector'] = { i['name']: i['value'] for i in labels} return True, svc_temp return False, None def harbor_cli(namespace, **filters): try: harbor = SystemConfig.objects.filter(**filters).first() # 获取harbor配置 harbor_config = json.loads(harbor.config) except BaseException as e: logger.exception(f'创建任务失败, 原因: 获取harbor仓库异常, {e}') return False, f"获取harbor仓库异常:{e}" # 构建前创建harbor项目 cli = HarborAPI(url=harbor_config['url'], username=harbor_config['user'], password=harbor_config['password']) try: cli.create_project( namespace, public=harbor_config.get('public', False)) except BaseException as e: pass return True, harbor_config def k8s_cli(k8s, k8s_config): try: if k8s_config['type'] == 'basic': # basic auth or token auth k8s_config.pop('config', None) k8s_config.pop('type', None) cli = K8sAPI(**k8s_config) else: eks = None eks_token = None k8s_config = yaml.safe_load(k8s_config['config']) if k8s.idc.type == 1 and k8s.idc.supplier.split('.')[-1] == 'aws': return False, 'not support.' cli = K8sAPI(k8s_config=k8s_config, api_key=eks_token, eks=eks) return True, cli except BaseException as e: return False, str(e) def template_generate(appinfo_obj: AppInfo, image=None, partial_deploy_replicas: int = 0): """ 生成Kubernetes Deployment Yaml """ def health_lifecycle_generate(item, enable=True): _c = {} for i in template[item]['data']: _x = {} if i.get('enable', enable): for j in i['items']: if '__' in j['name']: _t = j['name'].split('__') _value = j['value'] if j['name'] == 'exec__command': _value = ["sh", "-c", j['value']] if _x.get(_t[0], None): _x[_t[0]][_t[1]] = _value else: _x[_t[0]] = {_t[1]: _value} else: _x[j['name']] = j['value'] _c[i['name']] = _x return _c def container_generate(container_data): containers = [] for i in container_data: if i.get('enable', None): container = get_datadict(i['key'], config=1) if not container: container = i['extra'] containers.append( container) return containers language_obj = DevLanguage.objects.get(name=appinfo_obj.app.language) project_config = ProjectConfig.objects.filter(project_id=appinfo_obj.app.project.id, environment_id=appinfo_obj.environment.id) namespace = appinfo_obj.namespace harbor_config = get_redis_data('cicd-harbor') harbor_url = harbor_config['url'].split('://')[1] image = f"{harbor_url}/{image}" template = {} # 模板优先级 # 应用模块 -> 应用 -> 项目 -> 环境 if project_config.first(): project_template = project_config.first().template for k, v in project_template.items(): if v and isinstance(v, (dict,)): if v.get('custom', False) is False: if appinfo_obj.environment.template.get(k, None): template[k] = appinfo_obj.environment.template[k] else: if project_template.get(k, None): template[k] = project_template[k] microapp_template = appinfo_obj.app.template for k, v in microapp_template.items(): if '_on' in k and v: _k = k.rstrip('_on') if microapp_template.get(_k, None): template[_k] = microapp_template[_k] use_host_network = False if appinfo_obj.template.get('userHostNetwork', 0): use_host_network = True for k, v in appinfo_obj.template.items(): if v and isinstance(v, (dict,)): if v.get('custom', False) and appinfo_obj.template.get(k, None): template[k] = appinfo_obj.template[k] yaml_template = {'kind': 'Deployment', 'metadata': {}, 'spec': {'strategy': {}, 'template': {'metadata': {}, 'spec': {'containers': [{'ports': [{'containerPort': 8080}], 'resources': []}], 'imagePullSecrets': [{'name': 'loginharbor'}], 'terminationGracePeriodSeconds': 120} } } } try: tz = appinfo_obj.app.project.product.region.extra['timezone'] except BaseException as e: tz = 'Asia/Shanghai' try: if template.get('strategy', None): for i in template['strategy']['data']: if i['key'] in ['maxSurge', 'maxUnavailable']: if yaml_template['spec']['strategy'].get('rollingUpdate', None) is None: yaml_template['spec']['strategy']['rollingUpdate'] = {} yaml_template['spec']['strategy']['rollingUpdate'][i['key'] ] = f"{i['value']}%" else: yaml_template['spec'][i['key']] = i['value'] _d = {} for i in template['resources']['data']: _t = i['key'].split('_') if _d.get(_t[0], None): _d[_t[0]][_t[1]] = f"{i['value']}{i['slot']}" else: _d[_t[0]] = {_t[1]: f"{i['value']}{i['slot']}"} yaml_template['spec']['template']['spec']['containers'][0]['resources'] = _d yaml_template['metadata']['name'] = appinfo_obj.app.name yaml_template['metadata']['namespace'] = namespace yaml_template['spec']['template']['spec']['containers'][0]['name'] = appinfo_obj.app.name yaml_template['spec']['template']['spec']['containers'][0]['image'] = image command = appinfo_obj.app.template.get( 'command', None) or language_obj.labels.get('command', None) if command: if command.startswith('./'): yaml_template['spec']['template']['spec']['containers'][0]['command'] = [ command] else: yaml_template['spec']['template']['spec']['containers'][0]['command'] = [ 'sh', '-c', command] # 优先级: 应用模块>应用>预设>开发语言 labels = template['label']['data'] labels.extend([{'name': 'app', 'value': appinfo_obj.app.name}]) yaml_template['spec']['template']['metadata']['labels'] = { i['name']: i['value'] for i in labels} yaml_template['spec']['template']['metadata']['labels'][ 'status-app-name-for-ops-platform'] = appinfo_obj.app.name yaml_template['spec']['selector'] = { 'matchLabels': {i['name']: i['value'] for i in labels}} selectors = template['selector']['data'] yaml_template['spec']['template']['spec']['nodeSelector'] = { i['name']: i['value'] for i in selectors} if 'annotations' not in yaml_template['spec']['template']['metadata']: yaml_template['spec']['template']['metadata']['annotations'] = {} for i in template['prometheus']['data']: yaml_template['spec']['template']['metadata'][ 'annotations'][f'prometheus.io/{i["name"]}'] = i['value'] if 'prometheus.io/path' in yaml_template['spec']['template']['metadata']['annotations']: yaml_template['spec']['template']['metadata']['annotations'][ 'prometheus.io/app_product'] = appinfo_obj.app.project.product.name yaml_template['spec']['template']['metadata']['annotations'][ 'prometheus.io/app_env'] = appinfo_obj.environment.name yaml_template['spec']['template']['metadata']['annotations'][ 'prometheus.io/app_project'] = appinfo_obj.app.project.name # 环境变量 envs = [{'name': 'TZ', 'value': tz}] envs.extend(template['env']['data']) envs.extend([ {'name': '_RESTART', 'value': datetime.now().strftime( '%Y%m%d%H%M%S')}, # _RESTART变量用于强制更新deployment {'name': 'PRODUCT_NAME', 'value': appinfo_obj.app.project.product.name}, {'name': 'PROJECT_NAME', 'value': appinfo_obj.app.project.name}, {'name': 'APPNAME', 'value': appinfo_obj.app.name}, {'name': 'APPID', 'value': appinfo_obj.app.appid}, {'name': 'ENV', 'value': appinfo_obj.environment.name}, {'name': 'POD_NAMESPACE', 'value': namespace} ]) envs = list({i['name']: i for i in envs}.values()) for i in envs: try: env_value = i.get('value', None) cmname = i.pop('cmname', None) cmkey = i.pop('cmkey', None) if env_value: env_value = env_value.lstrip('"').rstrip( '"').lstrip("'").rstrip("'") i.pop('value', None) i['name'] = i['name'].lstrip('"').rstrip( '"').lstrip("'").rstrip("'") if i.get('valueFrom', None) == 'configMapKeyRef': i['valueFrom'] = {'configMapKeyRef': { 'name': cmname, 'key': cmkey}} else: i['value'] = env_value i['valueFrom'] = None except BaseException as e: pass yaml_template['spec']['template']['spec']['containers'][0]['env'] = envs if template.get('health', False): _d = health_lifecycle_generate('health', True) for k, v in _d.items(): yaml_template['spec']['template']['spec']['containers'][0][k] = v if template.get('lifecycle', False): yaml_template['spec']['template']['spec']['containers'][0]['lifecycle'] = { } _d = health_lifecycle_generate('lifecycle', False) for k, v in _d.items(): yaml_template['spec']['template']['spec']['containers'][0]['lifecycle'][k] = v _vo_mount = [{'mountPath': '/data/logs', 'name': 'logs', 'readOnly': False}] _volumes = [{'name': 'logs', 'type': 'Directory', 'hostPath': { 'path': f'/data/{appinfo_obj.environment.name}-applogs/{appinfo_obj.app.project.name}/'}}] if template.get('storage', None): for k, v in template['storage']['data'].items(): for i in v: _x = {} for m, n in i.items(): if isinstance(n, (str,)): n = n.replace('${APPNAME}', appinfo_obj.app.name) if '_' in m: _t = m.split('_') if _x.get(_t[0], None): _x[_t[0]][_t[1]] = n else: _x[_t[0]] = {_t[1]: n} else: _x[m] = n _t = {'mountPath': _x['mount'], 'name': _x['name'], 'readOnly': True if _x.get('mode', None) == 'ReadOnly' else False} if _x.get('file', None): _t['subPath'] = _x['configMap']['items'][0]['key'] _vo_mount.append(_t) _mode = _x.pop('mode', None) _x.pop('file', None) _x.pop('mount', None) if _x.get('configMap', None): _x['configMap']['defaultMode'] = 0o600 if _mode == 'ReadOnly' else 0o755 _volumes.append(_x) yaml_template['spec']['template']['spec']['containers'][0]['volumeMounts'] = _vo_mount yaml_template['spec']['template']['spec']['volumes'] = _volumes if use_host_network: yaml_template['spec']['template']['spec']['hostNetwork'] = True partial_deploy_yaml_template = None except BaseException as e: logger.exception(f'generate yaml err {e.__class__} {e}') return {'ecode': 500, 'message': str(e)} # 多容器处理 if appinfo_obj.template.get('containers_custom', None): containers = container_generate( appinfo_obj.template.get('containers', [])) else: containers = container_generate( project_config.first().template.get('containers', [])) yaml_template['spec']['template']['spec']['containers'].extend(containers) ret = {'ecode': 200, 'image': image, 'yaml': yaml_template} if partial_deploy_yaml_template: ret['partial_deploy_yaml'] = partial_deploy_yaml_template return ret def get_members(obj): team_members = [j for i in obj.team_members.values() for j in i] return list(set(team_members)) def get_permission_from_role(request): try: perms = request.user.roles.values( 'permissions__method', ).distinct() return [p['permissions__method'] for p in perms] except AttributeError: return [] def get_headers(request=None): """ Function: get_headers(self, request) Description: To get all the headers from request """ regex = re.compile('^HTTP_') return dict((regex.sub('', header), value) for (header, value) in request.META.items() if header.startswith('HTTP_')) def mask_sensitive_data(data): """ Hides sensitive keys specified in sensitive_keys settings. Loops recursively over nested dictionaries. """ if hasattr(settings, 'DRF_API_LOGGER_EXCLUDE_KEYS'): if type(settings.DRF_API_LOGGER_EXCLUDE_KEYS) in (list, tuple):
SENSITIVE_KEYS.extend(settings.DRF_API_LOGGER_EXCLUDE_KEYS)
10
2023-12-13 03:09:32+00:00
24k
MarilynKeller/aitviewer-skel
aitviewer/scene/camera.py
[ { "identifier": "CONFIG", "path": "aitviewer/configuration.py", "snippet": "CONFIG = Configuration()" }, { "identifier": "Lines", "path": "aitviewer/renderables/lines.py", "snippet": "class Lines(Node):\n \"\"\"Render lines as cylinders or cones. Can render approx. 600k lines at 40 fps.\"\"\"\n\n def __init__(\n self,\n lines,\n r_base=0.01,\n r_tip=None,\n color=(0.0, 0.0, 1.0, 1.0),\n mode=\"line_strip\",\n cast_shadow=True,\n **kwargs,\n ):\n \"\"\"\n Initializer.\n :param lines: Set of 3D coordinates as a np array of shape (F, L, 3) or (L, 3).\n :param r_base: Thickness of the line.\n :param r_tip: If set, the thickness of the line will taper from r_base to r_tip. If set to 0.0 it will create\n a proper cone.\n :param color: Color of the line (4-tuple) or array of color (N_LINES, 4), one for each line.\n :param mode: 'lines' or 'line_strip'.\n 'lines': a line is drawn from point 0 to 1, from 2 to 3, and so on, number of lines is L / 2.\n 'line_strip': a line is drawn between all adjacent points, 0 to 1, 1 to 2 and so on, number of lines is L - 1.\n :param cast_shadow: If True the mesh casts a shadow on other objects.\n \"\"\"\n if len(lines.shape) == 2:\n lines = lines[np.newaxis]\n assert len(lines.shape) == 3\n assert mode == \"lines\" or mode == \"line_strip\"\n if mode == \"lines\":\n assert lines.shape[1] % 2 == 0\n\n self._lines = lines\n self.mode = mode\n self.r_base = r_base\n self.r_tip = r_tip if r_tip is not None else r_base\n\n self.vertices, self.faces = self.get_mesh()\n self.n_lines = self.lines.shape[1] // 2 if mode == \"lines\" else self.lines.shape[1] - 1\n\n # Define a default material in case there is None.\n if isinstance(color, tuple) or len(color.shape) == 1:\n kwargs[\"material\"] = kwargs.get(\"material\", Material(color=color, ambient=0.2))\n self.line_colors = kwargs[\"material\"].color\n else:\n assert (\n color.shape[1] == 4 and color.shape[0] == self.n_lines\n ), \"Color must be a tuple of 4 values or a numpy array of shape (N_LINES, 4)\"\n self.line_colors = color\n\n super(Lines, self).__init__(n_frames=self.lines.shape[0], **kwargs)\n\n self._need_upload = True\n self.draw_edges = False\n\n # Render passes.\n self.outline = True\n self.fragmap = True\n self.depth_prepass = True\n self.cast_shadow = cast_shadow\n\n @property\n def bounds(self):\n bounds = self.get_bounds(self.lines)\n r = max(self.r_base, self.r_tip)\n bounds[:, 0] -= r\n bounds[:, 1] += r\n return bounds\n\n @property\n def current_bounds(self):\n bounds = self.get_bounds(self.current_lines)\n r = max(self.r_base, self.r_tip)\n bounds[:, 0] -= r\n bounds[:, 1] += r\n return bounds\n\n @property\n def lines(self):\n return self._lines\n\n @lines.setter\n def lines(self, value):\n self._lines = value if len(value.shape) == 3 else value[np.newaxis]\n self.n_frames = self.lines.shape[0]\n self.redraw()\n\n @property\n def current_lines(self):\n idx = self.current_frame_id if self._lines.shape[0] > 1 else 0\n return self._lines[idx]\n\n @current_lines.setter\n def current_lines(self, lines):\n assert len(lines.shape) == 2\n idx = self.current_frame_id if self._lines.shape[0] > 1 else 0\n self._lines[idx] = lines\n self.redraw()\n\n @Node.color.setter\n def color(self, color):\n self.material.color = color\n self.line_colors = color\n self.redraw()\n\n @property\n def line_colors(self):\n if len(self._line_colors.shape) == 1:\n t = np.tile(np.array(self._line_colors), (self.n_lines, 1))\n return t\n else:\n return self._line_colors\n\n @line_colors.setter\n def line_colors(self, color):\n if isinstance(color, tuple):\n color = np.array(color)\n self._line_colors = color\n self.redraw()\n\n def on_frame_update(self):\n self.redraw()\n\n def redraw(self, **kwargs):\n self._need_upload = True\n\n @Node.once\n def make_renderable(self, ctx: moderngl.Context):\n self.prog = get_lines_instanced_program()\n\n vs_path = \"lines_instanced_positions.vs.glsl\"\n self.outline_program = get_outline_program(vs_path)\n self.depth_only_program = get_depth_only_program(vs_path)\n self.fragmap_program = get_fragmap_program(vs_path)\n\n self.vbo_vertices = ctx.buffer(self.vertices.astype(\"f4\").tobytes())\n self.vbo_indices = ctx.buffer(self.faces.astype(\"i4\").tobytes())\n self.vbo_instance_base = ctx.buffer(reserve=self.n_lines * 12)\n self.vbo_instance_tip = ctx.buffer(reserve=self.n_lines * 12)\n self.vbo_instance_color = ctx.buffer(reserve=self.n_lines * 16)\n\n self.vao = VAO()\n self.vao.buffer(self.vbo_vertices, \"3f4\", \"in_position\")\n self.vao.buffer(self.vbo_instance_base, \"3f4/i\", \"instance_base\")\n self.vao.buffer(self.vbo_instance_tip, \"3f4/i\", \"instance_tip\")\n self.vao.buffer(self.vbo_instance_color, \"4f4/i\", \"instance_color\")\n self.vao.index_buffer(self.vbo_indices)\n\n def _upload_buffers(self):\n if not self.is_renderable or not self._need_upload:\n return\n self._need_upload = False\n\n lines = self.current_lines\n if self.mode == \"lines\":\n v0s = lines[::2]\n v1s = lines[1::2]\n else:\n v0s = lines[:-1]\n v1s = lines[1:]\n\n self.vbo_instance_base.write(v0s.astype(\"f4\").tobytes())\n self.vbo_instance_tip.write(v1s.astype(\"f4\").tobytes())\n\n if len(self._line_colors.shape) > 1:\n self.vbo_instance_color.write(self._line_colors.astype(\"f4\").tobytes())\n\n def render(self, camera, **kwargs):\n self._upload_buffers()\n\n prog = self.prog\n prog[\"r_base\"] = self.r_base\n prog[\"r_tip\"] = self.r_tip\n if len(self._line_colors.shape) == 1:\n prog[\"use_uniform_color\"] = True\n prog[\"uniform_color\"] = tuple(self.color)\n else:\n prog[\"use_uniform_color\"] = False\n prog[\"draw_edges\"].value = 1.0 if self.draw_edges else 0.0\n prog[\"win_size\"].value = kwargs[\"window_size\"]\n prog[\"clip_control\"].value = (0, 0, 0)\n\n self.set_camera_matrices(prog, camera, **kwargs)\n set_lights_in_program(\n prog,\n kwargs[\"lights\"],\n kwargs[\"shadows_enabled\"],\n kwargs[\"ambient_strength\"],\n )\n set_material_properties(prog, self.material)\n self.receive_shadow(prog, **kwargs)\n self.vao.render(prog, moderngl.TRIANGLES, instances=self.n_lines)\n\n def render_positions(self, prog):\n if self.is_renderable:\n self._upload_buffers()\n prog[\"r_base\"] = self.r_base\n prog[\"r_tip\"] = self.r_tip\n self.vao.render(prog, moderngl.TRIANGLES, instances=self.n_lines)\n\n def get_mesh(self):\n v0s = np.array([[0, 0, 0]], np.float32)\n v1s = np.array([[0, 0, 1]], np.float32)\n\n # If r_tip is below a certain threshold, we create a proper cone, i.e. with just a single vertex at the top.\n if self.r_tip < 1e-5:\n data = _create_cone_from_to(v0s, v1s, radius=1.0)\n else:\n data = _create_cylinder_from_to(v0s, v1s, radius1=1.0, radius2=1.0)\n\n return data[\"vertices\"][0], data[\"faces\"]\n\n @hooked\n def release(self):\n if self.is_renderable:\n self.vao.release()\n\n def update_frames(self, lines, frames):\n self.lines[frames] = lines\n self.redraw()\n\n def add_frames(self, lines):\n if len(lines.shape) == 2:\n lines = lines[np.newaxis]\n self.lines = np.append(self.lines, lines, axis=0)\n\n def remove_frames(self, frames):\n self.lines = np.delete(self.lines, frames, axis=0)\n self.redraw()\n\n def export_usd(self, stage, usd_path: str, directory: str = None, verbose=False):\n name = f\"{self.name}_{self.uid:03}\".replace(\" \", \"_\")\n usd_path = f\"{usd_path}/{name}\"\n\n if self.mode == \"lines\":\n v0s = self.lines[:, ::2]\n v1s = self.lines[:, 1::2]\n else:\n v0s = self.lines[:, :-1]\n v1s = self.lines[:, 1:]\n\n print(self.lines.shape)\n print(v0s.shape)\n\n # Data is in the form of (F, N_LINES, 3), convert it to (F*N_LINES, 3)\n v0s = np.reshape(v0s, (-1, 3))\n v1s = np.reshape(v1s, (-1, 3))\n\n self.r_tip = self.r_base if self.r_tip is None else self.r_tip\n\n # If r_tip is below a certain threshold, we create a proper cone, i.e. with just a single vertex at the top.\n if self.r_tip < 10e-6:\n data = _create_cone_from_to(v0s, v1s, radius=self.r_base)\n else:\n data = _create_cylinder_from_to(v0s, v1s, radius1=self.r_base, radius2=self.r_tip)\n\n L = self.n_lines\n V = data[\"vertices\"].shape[1]\n\n vertices = data[\"vertices\"].reshape((self.n_frames, -1, 3))\n faces = data[\"faces\"]\n\n fs = faces[np.newaxis].repeat(L, 0).reshape((L, -1))\n offsets = (np.arange(L) * V).reshape((L, 1))\n faces = (fs + offsets).reshape((-1, 3))\n\n mesh = usd.add_mesh(stage, usd_path, self.name, vertices, faces, self.get_local_transform())\n usd.add_color(stage, mesh, usd_path, self.color[:3])\n\n self._export_usd_recursively(stage, usd_path, directory, verbose)" }, { "identifier": "Meshes", "path": "aitviewer/renderables/meshes.py", "snippet": "class Meshes(Node):\n \"\"\"A sequence of triangle meshes. This assumes that the mesh topology is fixed over the sequence.\"\"\"\n\n def __init__(\n self,\n vertices,\n faces,\n vertex_normals=None,\n face_normals=None,\n vertex_colors=None,\n face_colors=None,\n uv_coords=None,\n path_to_texture=None,\n cast_shadow=True,\n pickable=True,\n flat_shading=False,\n draw_edges=False,\n draw_outline=False,\n instance_transforms=None,\n icon=\"\\u008d\",\n **kwargs,\n ):\n \"\"\"\n Initializer.\n :param vertices: A np array of shape (N, V, 3) or (V, 3).\n :param faces: A np array of shape (F, 3).\n :param vertex_normals: A np array of shape (N, V, 3). If not provided, the vertex normals will be computed,\n which incurs some overhead.\n :param face_normals: A np array of shape (N, F, 3). If not provided, the face normals will be computed, which\n incurs some overhead.\n :param vertex_colors: A np array of shape (N, V, 4) overriding the uniform color.\n :param face_colors: A np array of shape (N, F, 4) overriding the uniform or vertex colors.\n :param uv_coords: A np array of shape (V, 2) if the mesh is to be textured.\n :param path_to_texture: Path to an image file that serves as the texture.\n :param cast_shadow: If True the mesh casts a shadow on other objects.\n :param pickable: If True the mesh can be selected with a mouse click.\n :param flat_shading: If True the each face of the mesh is shaded with a constant normal.\n :param draw_edges: If True the normals the edges of the mesh is drawn on top of the mesh.\n :param draw_outline: If true an outline is drawn around the mesh.\n :instance_transforms: np array of size (N, I, 4, 4) or (I, 4, 4) or None. If not None, 'I' instances of\n the same mesh will be rendered, each with its own transformation matrix.\n \"\"\"\n if len(vertices.shape) == 2 and vertices.shape[-1] == 3:\n vertices = vertices[np.newaxis]\n assert len(vertices.shape) == 3\n assert len(faces.shape) == 2\n n_frames = vertices.shape[0]\n\n # Instancing.\n if instance_transforms is not None:\n # Check shape of transforms.\n if len(instance_transforms.shape) == 3:\n instance_transforms = instance_transforms[np.newaxis]\n assert len(instance_transforms.shape) == 4\n\n # Number of instance frames must match number of frames or be 1.\n assert n_frames == 1 or instance_transforms.shape[0] == 1 or n_frames == instance_transforms.shape[0]\n n_frames = max(n_frames, instance_transforms.shape[0])\n\n self._instance_transforms = instance_transforms\n else:\n self._instance_transforms = None\n\n super(Meshes, self).__init__(n_frames=n_frames, icon=icon, **kwargs)\n\n self._vertices = vertices\n self._faces = faces.astype(np.int32)\n\n # Create these first because other setters can call redraw() which uses this fields.\n self._face_colors = None\n self._vertex_colors = None\n self._has_transparent_vertex_or_face_colors = False\n\n def _maybe_unsqueeze(x):\n return x[np.newaxis] if x is not None and x.ndim == 2 else x\n\n self._vertex_normals = _maybe_unsqueeze(vertex_normals)\n self._face_normals = _maybe_unsqueeze(face_normals)\n self.vertex_colors = _maybe_unsqueeze(vertex_colors)\n self.face_colors = _maybe_unsqueeze(face_colors)\n\n # Texture handling.\n self.has_texture = (uv_coords is not None) and (path_to_texture is not None)\n self.uv_coords = uv_coords\n self.texture_path = path_to_texture\n\n if self.has_texture:\n self.use_pickle_texture = path_to_texture.endswith((\".pickle\", \"pkl\"))\n if self.use_pickle_texture:\n self.texture_image = pickle.load(open(path_to_texture, \"rb\"))\n else:\n self.texture_image = Image.open(path_to_texture).transpose(method=Image.FLIP_TOP_BOTTOM).convert(\"RGB\")\n else:\n self.texture_image = None\n\n # Enable rendering passes\n self.cast_shadow = cast_shadow\n self.fragmap = pickable\n self.depth_prepass = True\n self.outline = True\n\n # Misc.\n self._flat_shading = flat_shading\n self.draw_edges = draw_edges\n self.draw_outline = draw_outline\n self.show_texture = self.has_texture\n self.norm_coloring = False\n self.normals_r = None\n self.need_upload = True\n self._use_uniform_color = self._vertex_colors is None and self._face_colors is None\n self._vertex_faces_sparse = trimesh.geometry.index_sparse(self._vertices.shape[1], self._faces)\n\n self.clip_control = np.array((0, 0, 0), np.int32)\n self.clip_value = np.array((0, 0, 0), np.float32)\n\n @classmethod\n def instanced(cls, *args, positions=None, rotations=None, scales=None, **kwargs):\n \"\"\"\n Creates and returns an instanced sequence of N frames and I instances.\n Each instance will have its own position, rotation and scale.\n :param positions: np array of size (N, I, 3) or (I, 3) or None.\n :param rotations: np array of size (N, I, 3, 3) or (I, 3, 3) or None.\n :param scales: np array of size (N, I) or (I) or None.\n\n *args, and **kwargs are forwarded to the Meshes constructor.\n \"\"\"\n assert positions is not None or rotations is not None or scales is not None\n\n n_instances = 0\n n_frames = 0\n\n def check_array(a, dim):\n nonlocal n_instances, n_frames\n if a is not None:\n if len(a.shape) == dim + 1:\n a = a[np.newaxis]\n n_frames = max(n_frames, a.shape[0])\n n_instances = max(n_instances, a.shape[1])\n return a\n\n positions = check_array(positions, 1)\n rotations = check_array(rotations, 2)\n scales = check_array(scales, 0)\n\n if positions is None:\n positions = np.zeros((n_frames, n_instances, 3))\n if rotations is None:\n rotations = np.zeros((n_frames, n_instances, 3, 3))\n rotations[:, :] = np.eye(3)\n if scales is None:\n scales = np.ones((n_frames, n_instances))\n\n transforms = np.zeros((n_frames, n_instances, 4, 4))\n transforms[:, :, :3, :3] = (rotations.reshape((-1, 9)) * scales.reshape((-1, 1))).reshape(\n (n_frames, n_instances, 3, 3)\n )\n transforms[:, :, :3, 3] = positions\n transforms[:, :, 3, 3] = 1.0\n return cls(*args, **kwargs, instance_transforms=transforms)\n\n @classmethod\n def from_file(cls, file, **kwargs):\n \"\"\"\n Loads a mesh from a file that can be loaded by trimesh (e.g. \".obj\", \".ply\", ...)\n See trimesh.available_formats() for a complete list.\n \"\"\"\n mesh = trimesh.load(file)\n\n uvs = None\n vertex_colors = None\n face_colors = None\n if isinstance(mesh.visual, trimesh.visual.ColorVisuals):\n if mesh.visual.kind == \"vertex_colors\":\n vertex_colors = mesh.visual.vertex_colors\n elif mesh.visual.kind == \"face_colors\":\n face_colors = mesh.visual.vertex_colors\n elif isinstance(mesh.visual, trimesh.visual.TextureVisuals):\n uvs = mesh.visual.uv\n\n return Meshes(\n mesh.vertices,\n mesh.faces,\n vertex_normals=mesh.vertex_normals,\n face_colors=face_colors,\n vertex_colors=vertex_colors,\n uv_coords=uvs,\n **kwargs,\n )\n\n @property\n def vertices(self):\n return self._vertices\n\n @vertices.setter\n def vertices(self, vertices):\n if len(vertices.shape) == 2:\n vertices = vertices[np.newaxis]\n\n # Update vertices and redraw\n self._vertices = vertices\n self.n_frames = len(vertices)\n\n # If vertex or face normals were supplied, they are no longer valid.\n self._vertex_normals = None\n self._face_normals = None\n\n # Must clear all LRU caches where the vertices are used.\n self.compute_vertex_and_face_normals.cache_clear()\n\n self.redraw()\n\n @property\n def faces(self):\n return self._faces\n\n @faces.setter\n def faces(self, f):\n self._faces = f.astype(np.int32)\n self._vertex_faces_sparse = trimesh.geometry.index_sparse(self.vertices.shape[1], self._faces)\n\n @property\n def current_vertices(self):\n idx = self.current_frame_id if self.vertices.shape[0] > 1 else 0\n return self.vertices[idx]\n\n @current_vertices.setter\n def current_vertices(self, vertices):\n idx = self.current_frame_id if self.vertices.shape[0] > 1 else 0\n self._vertices[idx] = vertices\n self.compute_vertex_and_face_normals.cache_clear()\n self.redraw()\n\n @property\n def current_transformed_vertices(self):\n return (self.current_vertices @ self.model_matrix[:3, :3].T) + self.model_matrix[:3, 3]\n\n @property\n def transformed_vertices(self):\n return (self.vertices @ self.model_matrix[:3, :3].T) + self.model_matrix[:3, 3]\n\n @property\n def n_faces(self):\n return self.faces.shape[0]\n\n @property\n def n_vertices(self):\n return self.vertices.shape[1]\n\n @property\n def vertex_faces(self):\n # To compute the normals we need to know a mapping from vertex ID to all faces that this vertex is part of.\n # Because we are lazy we abuse trimesh to compute this for us. Not all vertices have the maximum degree, so\n # this array is padded with -1 if necessary.\n return trimesh.Trimesh(self.vertices[0], self.faces, process=False).vertex_faces\n\n @property\n def vertex_normals(self):\n \"\"\"Get or compute all vertex normals (this might take a while for long sequences).\"\"\"\n if self._vertex_normals is None:\n vertex_normals, _ = compute_vertex_and_face_normals_sparse(\n self.vertices, self.faces, self._vertex_faces_sparse, normalize=True\n )\n self._vertex_normals = vertex_normals\n return self._vertex_normals\n\n @property\n def face_normals(self):\n \"\"\"Get or compute all face normals (this might take a while for long sequences).\"\"\"\n if self._face_normals is None:\n _, face_normals = compute_vertex_and_face_normals_sparse(\n self.vertices, self.faces, self._vertex_faces_sparse, normalize=True\n )\n self._face_normals = face_normals\n return self._face_normals\n\n def vertex_normals_at(self, frame_id):\n \"\"\"Get or compute the vertex normals at the given frame.\"\"\"\n if self._vertex_normals is None:\n vn, _ = self.compute_vertex_and_face_normals(frame_id, normalize=True)\n else:\n assert len(self._vertex_normals.shape) == 3, f\"Got shape {self._vertex_normals.shape}\"\n vn = self._vertex_normals[frame_id]\n return vn\n\n def face_normals_at(self, frame_id):\n \"\"\"Get or compute the face normals at the given frame.\"\"\"\n if self._face_normals is None:\n _, fn = self.compute_vertex_and_face_normals(frame_id, normalize=True)\n else:\n assert len(self._face_normals.shape) == 3, f\"Got shape {self._face_normals.shape}\"\n fn = self._face_normals[frame_id]\n return fn\n\n @property\n def vertex_colors(self):\n if self._vertex_colors is None:\n self._vertex_colors = np.full((self.n_frames, self.n_vertices, 4), self.material.color)\n return self._vertex_colors\n\n @vertex_colors.setter\n def vertex_colors(self, vertex_colors):\n # If vertex_colors are None, we resort to the material color.\n if vertex_colors is None:\n self._vertex_colors = None\n self._use_uniform_color = True\n elif isinstance(vertex_colors, tuple) and len(vertex_colors) == 4:\n self.vertex_colors = None\n self._use_uniform_color = True\n self.material.color = vertex_colors\n else:\n if len(vertex_colors.shape) == 2:\n assert vertex_colors.shape[0] == self.n_vertices\n vertex_colors = np.repeat(vertex_colors[np.newaxis], self.n_frames, axis=0)\n assert len(vertex_colors.shape) == 3\n self._vertex_colors = vertex_colors\n self._use_uniform_color = False\n self.redraw()\n\n @property\n def current_vertex_colors(self):\n if self._use_uniform_color:\n return np.full((self.n_vertices, 4), self.material.color)\n else:\n idx = self.current_frame_id if self.vertex_colors.shape[0] > 1 else 0\n return self.vertex_colors[idx]\n\n @property\n def face_colors(self):\n return self._face_colors\n\n @face_colors.setter\n def face_colors(self, face_colors):\n if face_colors is not None:\n if len(face_colors.shape) == 2:\n face_colors = face_colors[np.newaxis]\n self._face_colors = face_colors\n self._use_uniform_color = False\n else:\n self._face_colors = None\n self.redraw()\n\n @property\n def current_face_colors(self):\n if self._use_uniform_color:\n return np.full((self.n_faces, 4), self.material.color)\n else:\n idx = self.current_frame_id if self.face_colors.shape[0] > 1 else 0\n return self.face_colors[idx]\n\n @Node.color.setter\n def color(self, color):\n self.material.color = color\n\n if self.face_colors is None:\n self.vertex_colors = color\n\n @property\n def flat_shading(self):\n return self._flat_shading\n\n @flat_shading.setter\n def flat_shading(self, flat_shading):\n if self._flat_shading != flat_shading:\n self._flat_shading = flat_shading\n self.redraw()\n\n def closest_vertex_in_triangle(self, tri_id, point):\n face_vertex_id = np.linalg.norm((self.current_vertices[self.faces[tri_id]] - point), axis=-1).argmin()\n return self.faces[tri_id][face_vertex_id]\n\n def get_bc_coords_from_points(self, tri_id, points):\n return points_to_barycentric(self.current_vertices[self.faces[[tri_id]]], points)[0]\n\n @lru_cache(2048)\n def compute_vertex_and_face_normals(self, frame_id, normalize=False):\n \"\"\"\n Compute face and vertex normals for the given frame. We use an LRU cache since this is a potentially\n expensive operation. This function exists because computing the normals on all frames can increase the\n startup time of the viewer considerably.\n\n :param frame_id: On which frame to compute the normals.\n :param normalize: Whether or not to normalize the normals. Not doing it is faster and the shaders typically\n enforce unit length of normals anyway.\n :return: The vertex and face normals as a np arrays of shape (V, 3) and (F, 3) respectively.\n \"\"\"\n vs = self.vertices[frame_id : frame_id + 1] if self.vertices.shape[0] > 1 else self.vertices\n vn, fn = compute_vertex_and_face_normals_sparse(vs, self.faces, self._vertex_faces_sparse, normalize)\n return vn.squeeze(0), fn.squeeze(0)\n\n @property\n def bounds(self):\n if self.instance_transforms is None:\n return self.get_bounds(self.vertices)\n else:\n # Get bounds in local coordinates\n bounds = self.get_local_bounds(self.vertices)\n\n # Transform bounds with instance transforms\n min = np.append(bounds[:, 0], 1.0)\n max = np.append(bounds[:, 1], 1.0)\n transforms = self.instance_transforms.reshape((-1, 4, 4))\n mins = transforms @ min\n maxs = transforms @ max\n\n # Return bounds in world coordinates\n return self.get_bounds(np.vstack((mins, maxs)))\n\n @property\n def current_bounds(self):\n if self.instance_transforms is None:\n return self.get_bounds(self.current_vertices)\n else:\n # Get bounds in local coordinates\n bounds = self.get_local_bounds(self.current_vertices)\n\n # Transform bounds with instance transforms\n min = np.append(bounds[:, 0], 1.0)\n max = np.append(bounds[:, 1], 1.0)\n transforms = self.current_instance_transforms.reshape((-1, 4, 4))\n mins = transforms @ min\n maxs = transforms @ max\n\n # Return bounds in world coordinates\n return self.get_bounds(np.vstack((mins[:, :3], maxs[:, :3])))\n\n def is_transparent(self):\n return self.color[3] < 1.0 or self._has_transparent_vertex_or_face_colors\n\n def on_frame_update(self):\n \"\"\"Called whenever a new frame must be displayed.\"\"\"\n super().on_frame_update()\n self.redraw()\n\n @property\n def current_instance_transforms(self):\n if self._instance_transforms is None:\n return None\n idx = self.current_frame_id if self._instance_transforms.shape[0] > 1 else 0\n return self._instance_transforms[idx]\n\n @property\n def instance_transforms(self):\n return self._instance_transforms\n\n @instance_transforms.setter\n def instance_transforms(self, instance_transforms):\n assert self._instance_transforms.shape == instance_transforms\n self._instance_transforms = instance_transforms\n\n @property\n def n_instances(self):\n if self._instance_transforms is None:\n return 1\n else:\n return self._instance_transforms.shape[1]\n\n def _upload_buffers(self):\n \"\"\"Upload the current frame data to the GPU for rendering.\"\"\"\n if not self.is_renderable or not self._need_upload:\n return\n\n self._need_upload = False\n\n # Write positions.\n self.vbo_vertices.write(self.current_vertices.astype(\"f4\").tobytes())\n\n # Write normals.\n if not self.flat_shading:\n vertex_normals = self.vertex_normals_at(self.current_frame_id)\n self.vbo_normals.write(vertex_normals.astype(\"f4\").tobytes())\n\n if self.face_colors is None:\n # Write vertex colors.\n self.vbo_colors.write(self.current_vertex_colors.astype(\"f4\").tobytes())\n else:\n # Write face colors.\n\n # Compute shape of 2D texture.\n shape = (min(self.faces.shape[0], 8192), (self.faces.shape[0] + 8191) // 8192)\n\n # Write texture left justifying the buffer to fill the last row of the texture.\n self.face_colors_texture.write(\n self.current_face_colors.astype(\"f4\").tobytes().ljust(shape[0] * shape[1] * 16)\n )\n\n # Write uvs.\n if self.has_texture:\n self.vbo_uvs.write(self.uv_coords.astype(\"f4\").tobytes())\n\n # Write instance transforms.\n if self.instance_transforms is not None:\n self.vbo_instance_transforms.write(\n np.transpose(self.current_instance_transforms.astype(\"f4\"), (0, 2, 1)).tobytes()\n )\n\n @hooked\n def redraw(self, **kwargs):\n self._need_upload = True\n\n transparent = False\n if self._vertex_colors is not None:\n transparent = transparent or np.any(self.vertex_colors[:, :, 3] < 1.0)\n if self._face_colors is not None:\n transparent = transparent or np.any(self.face_colors[:, :, 3] < 1.0)\n\n self._has_transparent_vertex_or_face_colors = transparent\n\n def _load_programs(self, vs, positions_vs):\n instanced = 1 if self.instance_transforms is not None else 0\n self.smooth_prog = get_smooth_lit_with_edges_program(vs, instanced)\n self.flat_prog = get_flat_lit_with_edges_program(vs, instanced)\n self.smooth_face_prog = get_smooth_lit_with_edges_face_color_program(vs, instanced)\n self.flat_face_prog = get_flat_lit_with_edges_face_color_program(vs, instanced)\n\n self.depth_only_program = get_depth_only_program(positions_vs, instanced)\n self.outline_program = get_outline_program(positions_vs, instanced)\n self.fragmap_program = get_fragmap_program(positions_vs, instanced)\n\n # noinspection PyAttributeOutsideInit\n @Node.once\n def make_renderable(self, ctx: moderngl.Context):\n \"\"\"Prepares this object for rendering. This function must be called before `render` is used.\"\"\"\n vs = \"lit_with_edges.glsl\"\n positions_vs = \"mesh_positions.vs.glsl\"\n self._load_programs(vs, positions_vs)\n\n vertices = self.current_vertices\n vertex_normals = self.vertex_normals_at(self.current_frame_id)\n vertex_colors = self.current_vertex_colors\n\n self.vbo_vertices = ctx.buffer(vertices.astype(\"f4\").tobytes())\n self.vbo_normals = ctx.buffer(vertex_normals.astype(\"f4\").tobytes())\n self.vbo_colors = ctx.buffer(vertex_colors.astype(\"f4\").tobytes())\n self.vbo_indices = ctx.buffer(self.faces.tobytes())\n\n self.vao = VAO()\n self.vao.buffer(self.vbo_vertices, \"3f4\", \"in_position\")\n self.vao.buffer(self.vbo_normals, \"3f4\", \"in_normal\")\n self.vao.buffer(self.vbo_colors, \"4f4\", \"in_color\")\n self.vao.index_buffer(self.vbo_indices)\n\n if self.instance_transforms is not None:\n self.vbo_instance_transforms = ctx.buffer(\n np.transpose(self.current_instance_transforms.astype(\"f4\"), (0, 2, 1)).tobytes()\n )\n self.vao.buffer(self.vbo_instance_transforms, \"16f4/i\", \"instance_transform\")\n\n # Compute shape of 2D texture.\n shape = (min(self.faces.shape[0], 8192), (self.faces.shape[0] + 8191) // 8192)\n self.face_colors_texture = ctx.texture(shape, 4, dtype=\"f4\")\n if self.face_colors is not None:\n # Write texture left justifying the buffer to fill the last row of the texture.\n self.face_colors_texture.write(\n self.current_face_colors.astype(\"f4\").tobytes().ljust(shape[0] * shape[1] * 16)\n )\n\n if self.has_texture:\n img = self.texture_image\n if self.use_pickle_texture:\n self.texture = ctx.texture(img.shape[:2], img.shape[2], img.tobytes())\n else:\n self.texture = ctx.texture(img.size, 3, img.tobytes())\n self.texture_prog = get_smooth_lit_texturized_program(vs)\n self.vbo_uvs = ctx.buffer(self.uv_coords.astype(\"f4\").tobytes())\n self.vao.buffer(self.vbo_uvs, \"2f4\", \"in_uv\")\n\n @hooked\n def release(self):\n if self.is_renderable:\n self.vao.release()\n if self.has_texture:\n self.texture.release()\n\n def _use_program(self, camera, **kwargs):\n if self.has_texture and self.show_texture:\n prog = self.texture_prog\n prog[\"diffuse_texture\"] = 0\n self.texture.use(0)\n else:\n if self.face_colors is None:\n if self.flat_shading:\n prog = self.flat_prog\n else:\n prog = self.smooth_prog\n else:\n if self.flat_shading:\n prog = self.flat_face_prog\n else:\n prog = self.smooth_face_prog\n self.face_colors_texture.use(0)\n prog[\"face_colors\"] = 0\n prog[\"norm_coloring\"].value = self.norm_coloring\n\n prog[\"use_uniform_color\"] = self._use_uniform_color\n prog[\"uniform_color\"] = self.material.color\n prog[\"draw_edges\"].value = 1.0 if self.draw_edges else 0.0\n prog[\"win_size\"].value = kwargs[\"window_size\"]\n\n prog[\"clip_control\"].value = tuple(self.clip_control)\n prog[\"clip_value\"].value = tuple(self.clip_value)\n\n self.set_camera_matrices(prog, camera, **kwargs)\n set_lights_in_program(\n prog,\n kwargs[\"lights\"],\n kwargs[\"shadows_enabled\"],\n kwargs[\"ambient_strength\"],\n )\n set_material_properties(prog, self.material)\n self.receive_shadow(prog, **kwargs)\n return prog\n\n def render(self, camera, **kwargs):\n self._upload_buffers()\n prog = self._use_program(camera, **kwargs)\n self.vao.render(prog, moderngl.TRIANGLES, instances=self.n_instances)\n\n def render_positions(self, prog):\n if self.is_renderable:\n self._upload_buffers()\n\n prog[\"clip_control\"].value = tuple(self.clip_control)\n prog[\"clip_value\"].value = tuple(self.clip_value)\n\n self.vao.render(prog, moderngl.TRIANGLES, instances=self.n_instances)\n\n def _show_normals(self):\n \"\"\"Create and add normals at runtime\"\"\"\n vn = self.vertex_normals\n\n bounds = self.bounds\n diag = np.linalg.norm(bounds[:, 0] - bounds[:, 1])\n\n length = 0.005 * max(diag, 1) / self.scale\n vn = vn / np.linalg.norm(vn, axis=-1, keepdims=True) * length\n\n # Must import here because if we do it at the top we create a circular dependency.\n from aitviewer.renderables.arrows import Arrows\n\n positions = self.vertices\n self.normals_r = Arrows(\n positions,\n positions + vn,\n r_base=length / 10,\n r_head=2 * length / 10,\n p=0.25,\n name=\"Normals\",\n )\n self.normals_r.current_frame_id = self.current_frame_id\n self.add(self.normals_r)\n\n def gui(self, imgui):\n super(Meshes, self).gui(imgui)\n\n _, self.show_texture = imgui.checkbox(\n \"Render Texture##render_texture{}\".format(self.unique_name),\n self.show_texture,\n )\n _, self.norm_coloring = imgui.checkbox(\n \"Norm Coloring##norm_coloring{}\".format(self.unique_name),\n self.norm_coloring,\n )\n _, self.flat_shading = imgui.checkbox(\n \"Flat shading [F]##flat_shading{}\".format(self.unique_name),\n self.flat_shading,\n )\n _, self.draw_edges = imgui.checkbox(\"Draw edges [E]##draw_edges{}\".format(self.unique_name), self.draw_edges)\n _, self.draw_outline = imgui.checkbox(\n \"Draw outline##draw_outline{}\".format(self.unique_name), self.draw_outline\n )\n\n if self.normals_r is None:\n if imgui.button(\"Show Normals ##show_normals{}\".format(self.unique_name)):\n self._show_normals()\n\n def gui_context_menu(self, imgui, x: int, y: int):\n _, self.flat_shading = imgui.menu_item(\"Flat shading\", \"F\", selected=self.flat_shading, enabled=True)\n _, self.draw_edges = imgui.menu_item(\"Draw edges\", \"E\", selected=self.draw_edges, enabled=True)\n _, self.draw_outline = imgui.menu_item(\"Draw outline\", selected=self.draw_outline)\n\n imgui.spacing()\n imgui.separator()\n imgui.spacing()\n super().gui_context_menu(imgui, x, y)\n\n def gui_io(self, imgui):\n if imgui.button(\"Export OBJ##export_{}\".format(self.unique_name)):\n mesh = trimesh.Trimesh(vertices=self.current_vertices, faces=self.faces, process=False)\n mesh.export(\"../export/\" + self.name + \".obj\")\n\n def key_event(self, key, wnd_keys):\n if key == wnd_keys.F:\n self.flat_shading = not self.flat_shading\n elif key == wnd_keys.E:\n self.draw_edges = not self.draw_edges\n\n def update_frames(self, vertices, frames):\n self.vertices[frames] = vertices\n self.redraw()\n\n def add_frames(self, vertices):\n if len(vertices.shape) == 2:\n vertices = vertices[np.newaxis]\n self.vertices = np.append(self.vertices, vertices, axis=0)\n self.n_frames = max(self.n_frames, self.vertices.shape[0])\n\n def remove_frames(self, frames):\n self.vertices = np.delete(self.vertices, frames, axis=0)\n self.redraw()\n\n def export_usd(self, stage, usd_path: str, directory: str = None, verbose=False):\n name = f\"{self.name}_{self.uid:03}\".replace(\" \", \"_\")\n usd_path = f\"{usd_path}/{name}\"\n\n mesh = usd.add_mesh(stage, usd_path, self.name, self.vertices, self.faces, self.get_local_transform())\n if self.has_texture and not self.use_pickle_texture:\n # UVs.\n a_uv = UsdGeom.PrimvarsAPI(mesh).CreatePrimvar(\n \"st\", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying\n )\n a_uv.Set(time=1, value=self.uv_coords[self.faces.flatten()])\n\n if not directory:\n texture_path = os.path.abspath(self.texture_path)\n else:\n texture_path = usd.copy_texture(self.texture_path, name, directory)\n usd.add_texture(stage, mesh, usd_path, texture_path)\n else:\n # NOTE: Per vertex and per face colors using usd displayColor are not currently\n # loaded by Blender. This code path can be enabled once support is there.\n if False:\n a_colors = mesh.GetDisplayColorAttr()\n if self._face_colors is not None:\n # Per face colors.\n if self._face_colors.shape[0] == 1:\n a_colors.Set(self._face_colors[0, :, :3].astype(np.float32))\n else:\n for i in range(self.n_frames):\n a_colors.Set(time=i + 1, value=self._face_colors[i, :, :3].astype(np.float32))\n elif self._vertex_colors is not None:\n # Per vertex colors.\n if self._vertex_colors.shape[0] == 1:\n a_colors.Set(self._vertex_colors[0, :, :3].astype(np.float32))\n else:\n for i in range(self.n_frames):\n a_colors.Set(time=i + 1, value=self._vertex_colors[i, :, :3].astype(np.float32))\n else:\n # Uniform color.\n a_colors.Set(np.array(self.color, np.float32)[:3])\n else:\n usd.add_color(stage, mesh, usd_path, self.color[:3])\n\n self._export_usd_recursively(stage, usd_path, directory, verbose)" }, { "identifier": "RigidBodies", "path": "aitviewer/renderables/rigid_bodies.py", "snippet": "class RigidBodies(Node):\n \"\"\"\n A sequence of N 3D positions and orientations in space.\n \"\"\"\n\n def __init__(\n self,\n rb_pos,\n rb_ori,\n radius=0.02,\n length=0.2,\n radius_cylinder=None,\n color=(0.0, 1.0, 0.5, 1.0),\n icon=\"\\u0086\",\n **kwargs,\n ):\n \"\"\"\n Initializer.\n :param rb_pos: A np array of shape (F, N, 3) containing N rigid-body centers over F time steps.\n :param rb_ori: A np array of shape (F, N, 3, 3) containing N rigid-body orientations over F time steps.\n :param radius: Radius of the sphere at the origin of the rigid body.\n :param length: Length of arrows representing the orientation of the rigid body.\n :param radius_cylinder: Radius of the cylinder representing the orientation, default is length / 50\n :param color: Color of the rigid body centers (4-tuple).\n \"\"\"\n self._rb_pos = rb_pos[np.newaxis] if rb_pos.ndim == 2 else rb_pos\n self._rb_ori = rb_ori[np.newaxis] if rb_ori.ndim == 3 else rb_ori\n super(RigidBodies, self).__init__(n_frames=self.rb_pos.shape[0], color=color, icon=icon, **kwargs)\n\n self.radius = radius\n self.length = length\n\n self.spheres = Spheres(rb_pos, radius=radius, color=color, is_selectable=False)\n self._add_node(self.spheres, show_in_hierarchy=False)\n\n self.coords = []\n r_base = radius_cylinder or length / 50\n r_head = r_base * 2\n c = [0.0, 0.0, 0.0, 1.0]\n for i in range(3):\n line = self.rb_ori[..., :, i]\n line = line / np.linalg.norm(line, axis=-1, keepdims=True) * length\n color = c.copy()\n color[i] = 1.0\n axs = Arrows(\n self.rb_pos,\n self.rb_pos + line,\n r_base=r_base,\n r_head=r_head,\n color=tuple(color),\n is_selectable=False,\n )\n self._add_node(axs, show_in_hierarchy=False)\n self.coords.append(axs)\n\n @Node.color.setter\n def color(self, color):\n self.material.color = color\n self.spheres.color = color\n\n @property\n def current_rb_pos(self):\n idx = self.current_frame_id if self.rb_pos.shape[0] > 1 else 0\n return self.rb_pos[idx]\n\n @current_rb_pos.setter\n def current_rb_pos(self, pos):\n idx = self.current_frame_id if self.rb_pos.shape[0] > 1 else 0\n self.rb_pos[idx] = pos\n\n @property\n def current_rb_ori(self):\n idx = self.current_frame_id if self.rb_ori.shape[0] > 1 else 0\n return self.rb_ori[idx]\n\n @current_rb_ori.setter\n def current_rb_ori(self, ori):\n idx = self.current_frame_id if self.rb_ori.shape[0] > 1 else 0\n self.rb_ori[idx] = ori\n\n @property\n def rb_pos(self):\n return self._rb_pos\n\n @rb_pos.setter\n def rb_pos(self, rb_pos):\n self._rb_pos = rb_pos if len(rb_pos.shape) == 3 else rb_pos[np.newaxis]\n self.n_frames = self._rb_pos.shape[0]\n\n @property\n def rb_ori(self):\n return self._rb_ori\n\n @rb_ori.setter\n def rb_ori(self, rb_ori):\n self._rb_ori = rb_ori if len(rb_ori.shape) == 4 else rb_ori[np.newaxis]\n self.n_frames = self._rb_ori.shape[0]\n\n @property\n def bounds(self):\n return compute_union_of_bounds(self.coords)\n\n @property\n def current_bounds(self):\n return compute_union_of_current_bounds(self.coords)\n\n def redraw(self, **kwargs):\n if kwargs.get(\"current_frame_only\", False):\n self.spheres.current_sphere_positions = self.current_rb_pos\n\n for i in range(3):\n line = self.rb_ori[..., :, i][self.current_frame_id]\n line = line / np.linalg.norm(line, axis=-1, keepdims=True) * self.length\n axs = self.coords[i]\n axs.current_origins = self.current_rb_pos\n axs.current_tips = self.current_rb_pos + line\n else:\n self.spheres.sphere_positions = self.rb_pos\n\n for i in range(3):\n line = self.rb_ori[..., :, i]\n line = line / np.linalg.norm(line, axis=-1, keepdims=True) * self.length\n axs = self.coords[i]\n axs.origins = self.rb_pos\n axs.tips = self.rb_pos + line\n\n super().redraw(**kwargs)\n\n def color_one(self, index, color):\n self.spheres.color_one(index, color)\n\n def gui(self, imgui):\n _, self.spheres.radius = imgui.drag_float(\n \"Sphere Radius\".format(self.unique_name),\n self.spheres.radius,\n 0.01,\n min_value=0.001,\n max_value=10.0,\n format=\"%.3f\",\n )\n super(RigidBodies, self).gui(imgui)\n\n def update_frames(self, rb_pos, rb_ori, frames):\n self.rb_pos[frames] = rb_pos\n self.rb_ori[frames] = rb_ori\n self.n_frames = self.rb_pos.shape[0]\n self.redraw()\n\n def add_frames(self, rb_pos, rb_ori):\n if len(rb_pos.shape) == 2:\n rb_pos = rb_pos[np.newaxis]\n self.rb_pos = np.append(self.rb_pos, rb_pos, axis=0)\n\n if len(rb_ori.shape) == 3:\n rb_ori = rb_ori[np.newaxis]\n self.rb_ori = np.append(self.rb_ori, rb_ori, axis=0)\n\n self.n_frames = self.rb_pos.shape[0]\n self.redraw()\n\n def remove_frames(self, frames):\n self.rb_pos = np.delete(self.rb_pos, frames, axis=0)\n self.rb_ori = np.delete(self.rb_ori, frames, axis=0)\n\n self.n_frames = self.rb_pos.shape[0]\n self.redraw()" }, { "identifier": "look_at", "path": "aitviewer/scene/camera_utils.py", "snippet": "def look_at(position, target, up):\n \"\"\"\n Create an affine transformation that locates the camera at `position`, s.t. it looks at `target`.\n :param position: The 3D position of the camera in world coordinates.\n :param target: The 3D target where the camera should look at in world coordinates.\n :param up: The vector that is considered to be up in world coordinates.\n :return: Returns the 4-by-4 affine transform that transforms a point in world space into the camera space, i.e.\n it returns the inverse of the camera's 6D pose matrix. Assumes right-multiplication, i.e. x' = [R|t] * x.\n \"\"\"\n\n forward = normalize(position - target) # forward actually points in the other direction than `target` is.\n right = normalize(np.cross(up, forward))\n camera_up = np.cross(forward, right)\n\n # We directly create the inverse matrix (i.e. world2cam) because this is typically how look-at is define.\n rot = np.eye(4)\n rot[0, :3] = right\n rot[1, :3] = camera_up\n rot[2, :3] = forward\n\n trans = np.eye(4)\n trans[:3, 3] = -position\n\n return rot @ trans" }, { "identifier": "normalize", "path": "aitviewer/scene/camera_utils.py", "snippet": "def normalize(x):\n return x / np.linalg.norm(x)" }, { "identifier": "orthographic_projection", "path": "aitviewer/scene/camera_utils.py", "snippet": "def orthographic_projection(scale_x, scale_y, znear, zfar):\n \"\"\"Returns an orthographic projection matrix.\"\"\"\n P = np.zeros((4, 4))\n P[0][0] = 1.0 / scale_x\n P[1][1] = 1.0 / scale_y\n P[2][2] = 2.0 / (znear - zfar)\n P[2][3] = (zfar + znear) / (znear - zfar)\n P[3][3] = 1.0\n return P" }, { "identifier": "perspective_projection", "path": "aitviewer/scene/camera_utils.py", "snippet": "def perspective_projection(fov, aspect_ratio, znear, zfar):\n \"\"\"Returns a perspective projection matrix.\"\"\"\n ar = aspect_ratio\n t = np.tan(fov / 2.0)\n\n P = np.zeros((4, 4))\n P[0][0] = 1.0 / (ar * t)\n P[1][1] = 1.0 / t\n P[3][2] = -1.0\n\n f, n = zfar, znear\n if f is None:\n P[2][2] = -1.0\n P[2][3] = -2.0 * n\n else:\n P[2][2] = (f + n) / (n - f)\n P[2][3] = (2 * f * n) / (n - f)\n\n return P" }, { "identifier": "Node", "path": "aitviewer/scene/node.py", "snippet": "class Node(object):\n \"\"\"Interface for nodes.\"\"\"\n\n def __init__(\n self,\n name=None,\n icon=None,\n position=None,\n rotation=None,\n scale=1.0,\n color=(0.5, 0.5, 0.5, 1.0),\n material=None,\n is_selectable=True,\n gui_affine=True,\n gui_material=True,\n enabled_frames=None,\n n_frames=1,\n ):\n \"\"\"\n :param name: Name of the node\n :param icon: Custom Node Icon using custom Icon font\n :param position: Starting position in the format (X,Y,Z) or np array of positions with shape (F, 3)\n :param rotation: Starting rotation in rotation matrix representation (3,3) or np array of rotations with shape (F, 3, 3)\n :param scale: Starting scale (scalar) or np array of scale values with shape (F)\n :param color: (R,G,B,A) 0-1 formatted color value.\n :param material: Object material properties. The color specified in the material will override node color\n :param is_selectable: If True the node is selectable when clicked on, otherwise the parent node will be selected.\n :param gui_affine: If True the node will have transform controls (position, rotation, scale) in the GUI.\n :param gui_material: If True the node will have material controls in the GUI.\n :param enabled_frames: Numpy array of boolean values, the object will be enabled only in frames where the value is True,\n the number of ones in the mask must match the number of frames of the object.\n :param n_frames: How many frames this renderable has.\n \"\"\"\n # Transform & Animation\n position = np.zeros(3, dtype=np.float32) if position is None else np.array(position, dtype=np.float32)\n rotation = np.eye(3, dtype=np.float32) if rotation is None else np.array(rotation, dtype=np.float32)\n\n self._positions = position if len(position.shape) != 1 else position[np.newaxis]\n self._rotations = rotation if len(rotation.shape) != 2 else rotation[np.newaxis]\n self._scales = (scale if isinstance(scale, np.ndarray) else np.array([scale])).astype(np.float32)\n\n n_positions = self._positions.shape[0]\n n_rotations = self._rotations.shape[0]\n n_scales = self._scales.shape[0]\n\n if n_frames > 1:\n assert n_positions == 1 or n_frames == n_positions, (\n f\"Number of position frames\" f\" ({n_positions}) must be 1 or match number of Node frames {n_frames}\"\n )\n assert n_rotations == 1 or n_frames == n_rotations, (\n f\"Number of rotations frames\" f\" ({n_rotations}) must be 1 or match number of Node frames {n_frames}\"\n )\n assert n_scales == 1 or n_frames == n_scales, (\n f\"Number of scales frames\" f\" ({n_scales}) must be 1 or match number of Node frames {n_frames}\"\n )\n else:\n n_frames = max(n_positions, n_rotations, n_scales)\n assert (\n (n_positions == 1 or n_positions == n_frames)\n and (n_rotations == 1 or n_rotations == n_frames)\n and (n_scales == 1 or n_scales == n_frames)\n ), (\n f\"Number of position\"\n f\"({n_positions}), rotation ({n_rotations}) and scale ({n_scales})\"\n \"frames must be 1 or match.\"\n )\n\n # Frames\n self._n_frames = n_frames\n self._current_frame_id = 0\n self.model_matrix = self.get_local_transform()\n self._enabled_frames = enabled_frames\n if self._enabled_frames is not None:\n assert np.count_nonzero(self._enabled_frames) == n_frames, (\n f\"Number of non-zero elements in enabled_frames\"\n f\" ({np.count_nonzero(self._enabled_frames)}) must match number of frames in sequence ({n_frames})\"\n )\n # Create an array that maps from the true frame id (counting also disabled frames) to the index of the\n # first existing frame in the sequence.\n self._enabled_frame_id = np.cumsum(self._enabled_frames) - 1\n\n # Stores the true frame id (counting also disabled frames) we use this to allow going\n # through both enabled and disabled frames from the GUI.\n self._internal_frame_id = 0\n\n # Material\n self.material = Material(color=color) if material is None else material\n\n # Renderable Attributes\n self.is_renderable = False\n self.backface_culling = True\n self.backface_fragmap = False\n self.draw_outline = False\n\n # Flags to enable rendering passes\n self.cast_shadow = False\n self.depth_prepass = False\n self.fragmap = False\n self.outline = False\n\n # Programs for render passes. Subclasses are responsible for setting these.\n self.depth_only_program = None # Required for depth_prepass and cast_shadow passes\n self.fragmap_program = None # Required for fragmap pass\n self.outline_program = None # Required for outline pass\n\n # GUI\n self.name = name if name is not None else type(self).__name__\n self.uid = C.next_gui_id()\n self.unique_name = self.name + \"{}\".format(self.uid)\n self.icon = icon if icon is not None else \"\\u0082\"\n self._enabled = True\n self._expanded = False\n self.gui_controls = {\n \"affine\": {\n \"fn\": self.gui_affine,\n \"icon\": \"\\u009b\",\n \"is_visible\": gui_affine,\n },\n \"material\": {\n \"fn\": self.gui_material,\n \"icon\": \"\\u0088\",\n \"is_visible\": gui_material,\n },\n \"animation\": {\n \"fn\": self.gui_animation,\n \"icon\": \"\\u0098\",\n \"is_visible\": (lambda: self._n_frames > 1)(),\n },\n \"io\": {\n \"fn\": self.gui_io,\n \"icon\": \"\\u009a\",\n \"is_visible\": (lambda: self.gui_io.__func__ is not Node.gui_io)(),\n },\n }\n self.gui_modes = {\"view\": {\"title\": \" View\", \"fn\": self.gui_mode_view, \"icon\": \"\\u0099\"}}\n self._selected_mode = \"view\"\n self._show_in_hierarchy = True\n self.is_selectable = is_selectable\n self.export_usd_enabled = True\n self.export_usd_expanded = True\n\n self.nodes: List[Node] = []\n self.parent: Node = None\n\n # Selected Mode\n @property\n def selected_mode(self):\n return self._selected_mode\n\n @selected_mode.setter\n def selected_mode(self, selected_mode):\n self._selected_mode = selected_mode\n\n # Transform\n @property\n def position(self):\n idx = self.current_frame_id if self._positions.shape[0] > 1 else 0\n return self._positions[idx]\n\n @position.setter\n def position(self, position):\n idx = self.current_frame_id if self._positions.shape[0] > 1 else 0\n self._positions[idx] = np.array(position, dtype=np.float32).copy()\n self.update_transform(None if self.parent is None else self.parent.model_matrix)\n\n @property\n def positions(self):\n return self._positions\n\n @positions.setter\n def positions(self, positions):\n self._positions = positions\n self.update_transform(None if self.parent is None else self.parent.model_matrix)\n\n @property\n def rotation(self):\n idx = self.current_frame_id if self._rotations.shape[0] > 1 else 0\n return self._rotations[idx]\n\n @rotation.setter\n def rotation(self, rotation):\n idx = self.current_frame_id if self._rotations.shape[0] > 1 else 0\n self._rotations[idx] = rotation\n self.update_transform(None if self.parent is None else self.parent.model_matrix)\n\n @property\n def rotations(self):\n return self._rotations\n\n @rotations.setter\n def rotations(self, rotations):\n self._rotations = rotations\n self.update_transform(None if self.parent is None else self.parent.model_matrix)\n\n @property\n def scale(self):\n idx = self.current_frame_id if self._scales.shape[0] > 1 else 0\n return self._scales[idx]\n\n @scale.setter\n def scale(self, scale):\n idx = self.current_frame_id if self._scales.shape[0] > 1 else 0\n self._scales[idx] = scale\n self.update_transform(None if self.parent is None else self.parent.model_matrix)\n\n @property\n def scales(self):\n return self._scales\n\n @scales.setter\n def scales(self, scales):\n self._scales = scales\n self.update_transform(None if self.parent is None else self.parent.model_matrix)\n\n @staticmethod\n @lru_cache()\n def _compute_transform(pos, rot, scale):\n rotation = np.eye(4)\n rotation[:3, :3] = np.array(rot)\n\n trans = np.eye(4)\n trans[:3, 3] = np.array(pos)\n\n scale = np.diag([scale, scale, scale, 1])\n\n return (trans @ rotation @ scale).astype(\"f4\")\n\n def get_local_transform(self):\n \"\"\"Construct local transform as a 4x4 matrix from this node's position, orientation and scale.\"\"\"\n return self._compute_transform(tuple(self.position), tuple(map(tuple, self.rotation)), self.scale)\n\n def update_transform(self, parent_transform=None):\n \"\"\"Update the model matrix of this node and all of its descendants.\"\"\"\n if parent_transform is None:\n self.model_matrix = self.get_local_transform()\n else:\n self.model_matrix = parent_transform.astype(\"f4\") @ self.get_local_transform()\n\n for n in self.nodes:\n n.update_transform(self.model_matrix)\n\n @property\n def color(self):\n return self.material.color\n\n @color.setter\n def color(self, color):\n self.material.color = color\n\n @property\n def bounds(self):\n \"\"\"The bounds in the format ((x_min, x_max), (y_min, y_max), (z_min, z_max))\"\"\"\n return np.array([[0, 0], [0, 0], [0, 0]])\n\n @property\n def current_bounds(self):\n return np.array([[0, 0], [0, 0], [0, 0]])\n\n @property\n def current_center(self):\n return self.current_bounds.mean(-1)\n\n @property\n def center(self):\n return self.bounds.mean(-1)\n\n def get_local_bounds(self, points):\n if len(points.shape) == 2 and points.shape[-1] == 3:\n points = points[np.newaxis]\n assert len(points.shape) == 3\n\n # Compute min and max coordinates of the bounding box ignoring NaNs.\n val = np.array(\n [\n [np.nanmin(points[:, :, 0]), np.nanmax(points[:, :, 0])],\n [np.nanmin(points[:, :, 1]), np.nanmax(points[:, :, 1])],\n [np.nanmin(points[:, :, 2]), np.nanmax(points[:, :, 2])],\n ]\n )\n\n # If any of the elements is NaN return an empty bounding box.\n if np.isnan(val).any():\n return np.array([[0, 0], [0, 0], [0, 0]])\n else:\n return val\n\n def get_bounds(self, points):\n val = self.get_local_bounds(points)\n\n # Transform bounding box with the model matrix.\n val = (self.model_matrix @ np.vstack((val, np.array([1.0, 1.0]))))[:3]\n\n # If any of the elements is NaN return an empty bounding box.\n if np.isnan(val).any():\n return np.array([[0, 0], [0, 0], [0, 0]])\n else:\n return val\n\n @property\n def n_frames(self):\n return self._n_frames\n\n @n_frames.setter\n def n_frames(self, n_frames):\n self._n_frames = n_frames\n\n def __len__(self):\n return self.n_frames\n\n @property\n def current_frame_id(self):\n return self._current_frame_id\n\n @current_frame_id.setter\n def current_frame_id(self, frame_id):\n # Check if the frame changed.\n last_frame_id = self._current_frame_id if self._enabled_frames is None else self._internal_frame_id\n if self.n_frames == 1 or frame_id == last_frame_id:\n return\n\n self.on_before_frame_update()\n if self._enabled_frames is None:\n if frame_id < 0:\n self._current_frame_id = 0\n elif frame_id >= len(self):\n self._current_frame_id = len(self) - 1\n else:\n self._current_frame_id = frame_id\n else:\n # If an enabled_frames is present use it to get the current frame.\n if frame_id < 0:\n self._internal_frame_id = 0\n elif frame_id >= self._enabled_frames.shape[0]:\n self._internal_frame_id = self._enabled_frames.shape[0] - 1\n else:\n self._internal_frame_id = frame_id\n self._current_frame_id = self._enabled_frame_id[self._internal_frame_id]\n # Update enabled using the mask.\n self.enabled = self._enabled_frames[self._internal_frame_id]\n\n # Update frame id of all children nodes.\n for n in self.nodes:\n n.current_frame_id = self._current_frame_id\n\n self.on_frame_update()\n if self.parent and (self._positions.shape[0] > 1 or self._rotations.shape[0] > 1 or self._scales.shape[0] > 1):\n self.update_transform(self.parent.model_matrix)\n\n def next_frame(self):\n self.current_frame_id = self.current_frame_id + 1 if self.current_frame_id < len(self) - 1 else 0\n\n def previous_frame(self):\n self.current_frame_id = self.current_frame_id - 1 if self.current_frame_id > 0 else len(self) - 1\n\n def on_before_frame_update(self):\n \"\"\"Called when the current frame is about to change, 'self.current_frame_id' still has the id of the\n previous frame.\"\"\"\n pass\n\n def on_frame_update(self):\n \"\"\"Called when the current frame is changed.\"\"\"\n pass\n\n def add(self, *nodes, **kwargs):\n self._add_nodes(*nodes, **kwargs)\n\n def _add_node(self, n: \"Node\", show_in_hierarchy=True, expanded=False, enabled=True):\n \"\"\"\n Add a single node\n :param show_in_hierarchy: Whether to show the node in the scene hierarchy.\n :param expanded: Whether the node is initially expanded in the GUI.\n \"\"\"\n if n is None:\n return\n n._show_in_hierarchy = show_in_hierarchy\n n._expanded = expanded\n n._enabled = enabled if n._enabled_frames is None else n._enabled_frames[n.current_frame_id]\n self.nodes.append(n)\n n.parent = self\n n.update_transform(self.model_matrix)\n\n def _add_nodes(self, *nodes, **kwargs):\n \"\"\"Add multiple nodes\"\"\"\n for n in nodes:\n self._add_node(n, **kwargs)\n\n def remove(self, *nodes):\n for n in nodes:\n n.release()\n try:\n self.nodes.remove(n)\n except:\n pass\n\n @property\n def show_in_hierarchy(self):\n return self._show_in_hierarchy\n\n @property\n def enabled(self):\n return self._enabled\n\n @enabled.setter\n def enabled(self, enabled):\n self._enabled = enabled\n\n @property\n def expanded(self):\n return self._expanded\n\n @expanded.setter\n def expanded(self, expanded):\n self._expanded = expanded\n\n def is_transparent(self):\n \"\"\"\n Returns true if the object is transparent and should thus be sorted when rendering.\n Subclassess that use a different color should implement this method to be rendered correctly when transparent.\n \"\"\"\n return self.material.color[3] < 1.0\n\n def gui(self, imgui):\n \"\"\"\n Render GUI for custom node properties and controls. Implementation optional.\n Elements rendered here will show up in the scene hierarchy\n :param imgui: imgui context.\n See https://pyimgui.readthedocs.io/en/latest/reference/imgui.core.html for available elements to render\n \"\"\"\n pass\n\n def gui_modes(self, imgui):\n \"\"\"Render GUI with toolbar (tools) for this particular node\"\"\"\n\n def gui_animation(self, imgui):\n \"\"\"Render GUI for animation related settings\"\"\"\n\n if self._enabled_frames is None:\n if self.n_frames > 1:\n u, fid = imgui.slider_int(\n \"Frame##r_{}\".format(self.unique_name),\n self.current_frame_id,\n min_value=0,\n max_value=self.n_frames - 1,\n )\n if u:\n self.current_frame_id = fid\n else:\n u, fid = imgui.slider_int(\n \"Frame##r_{}\".format(self.unique_name),\n self._internal_frame_id,\n min_value=0,\n max_value=self._enabled_frames.shape[0] - 1,\n )\n if u:\n self.current_frame_id = fid\n\n def gui_affine(self, imgui):\n \"\"\"Render GUI for affine transformations\"\"\"\n # Position controls\n up, pos = imgui.drag_float3(\n \"Position##pos{}\".format(self.unique_name),\n *self.position,\n 1e-2,\n format=\"%.2f\",\n )\n if up:\n self.position = pos\n\n # Rotation controls\n euler_angles = rot2euler_numpy(self.rotation[np.newaxis], degrees=True)[0]\n ur, euler_angles = imgui.drag_float3(\n \"Rotation##pos{}\".format(self.unique_name),\n *euler_angles,\n 1e-2,\n format=\"%.2f\",\n )\n if ur:\n self.rotation = euler2rot_numpy(np.array(euler_angles)[np.newaxis], degrees=True)[0]\n\n # Scale controls\n us, scale = imgui.drag_float(\n \"Scale##scale{}\".format(self.unique_name),\n self.scale,\n 1e-2,\n min_value=0.001,\n max_value=100.0,\n format=\"%.3f\",\n )\n if us:\n self.scale = scale\n\n def gui_material(self, imgui):\n \"\"\"Render GUI with material properties\"\"\"\n\n # Color Control\n uc, color = imgui.color_edit4(\"Color##color{}'\".format(self.unique_name), *self.material.color)\n if uc:\n self.color = color\n\n # Diffuse\n ud, diffuse = imgui.slider_float(\n \"Diffuse##diffuse{}\".format(self.unique_name),\n self.material.diffuse,\n 0.0,\n 1.0,\n \"%.2f\",\n )\n if ud:\n self.material.diffuse = diffuse\n\n # Ambient\n ua, ambient = imgui.slider_float(\n \"Ambient##ambient{}\".format(self.unique_name),\n self.material.ambient,\n 0.0,\n 1.0,\n \"%.2f\",\n )\n if ua:\n self.material.ambient = ambient\n\n def gui_io(self, imgui):\n \"\"\"Render GUI for import/export\"\"\"\n pass\n\n def gui_mode_view(self, imgui):\n \"\"\"Render custom GUI for view mode\"\"\"\n pass\n\n def gui_context_menu(self, imgui, x: int, y: int):\n _, self.enabled = imgui.checkbox(\"Enabled\", self.enabled)\n if any([n._show_in_hierarchy for n in self.nodes]):\n imgui.spacing()\n imgui.separator()\n imgui.spacing()\n for n in self.nodes:\n if not n._show_in_hierarchy:\n continue\n if imgui.begin_menu(f\"{n.name}##{n.uid}\"):\n n.gui_context_menu(imgui, x, y)\n imgui.end_menu()\n\n # Renderable\n @staticmethod\n def once(func):\n def _decorator(self, *args, **kwargs):\n if self.is_renderable:\n return\n else:\n func(self, *args, **kwargs)\n self.is_renderable = True\n\n return _decorator\n\n def make_renderable(self, ctx):\n \"\"\"\n Prepares this object for rendering. This function must be called before `render` is used.\n :param ctx: The moderngl context.\n \"\"\"\n pass\n\n def render(self, camera, position=None, rotation=None, **kwargs):\n \"\"\"Render the current frame in this sequence.\"\"\"\n pass\n\n def render_positions(self, prog):\n \"\"\"\n Render with a VAO with only positions bound, used for shadow mapping, fragmap and depth prepass.\n \"\"\"\n pass\n\n def redraw(self, **kwargs):\n \"\"\"Perform update and redraw operations. Push to the GPU when finished. Recursively redraw child nodes\"\"\"\n for n in self.nodes:\n n.redraw(**kwargs)\n\n def set_camera_matrices(self, prog, camera, **kwargs):\n \"\"\"Set the model view projection matrix in the given program.\"\"\"\n # Transpose because np is row-major but OpenGL expects column-major.\n prog[\"model_matrix\"].write(self.model_matrix.T.astype(\"f4\").tobytes())\n prog[\"view_projection_matrix\"].write(camera.get_view_projection_matrix().T.astype(\"f4\").tobytes())\n\n def receive_shadow(self, program, **kwargs):\n \"\"\"\n Call this function if the renderable is to receive shadows.\n :param program: The shader program that can shade with shadows.\n :param kwargs: The render kwargs.\n \"\"\"\n if kwargs.get(\"shadows_enabled\", False):\n lights = kwargs[\"lights\"]\n\n for i, light in enumerate(lights):\n if light.shadow_enabled and light.shadow_map:\n light_matrix = light.mvp() @ self.model_matrix\n program[f\"dirLights[{i}].matrix\"].write(light_matrix.T.tobytes())\n\n # Bind shadowmap to slot i + 1, we reserve slot 0 for the mesh texture\n # and use slots 1 to (#lights + 1) for shadow maps\n light.shadow_map.use(location=i + 1)\n\n # Set sampler uniforms\n uniform = program[f\"shadow_maps\"]\n uniform.value = 1 if uniform.array_length == 1 else [*range(1, len(lights) + 1)]\n\n def render_shadowmap(self, light_matrix):\n if not self.cast_shadow or self.depth_only_program is None or self.color[3] == 0.0:\n return\n\n prog = self.depth_only_program\n prog[\"model_matrix\"].write(self.model_matrix.T.tobytes())\n prog[\"view_projection_matrix\"].write(light_matrix.T.tobytes())\n\n self.render_positions(prog)\n\n def render_fragmap(self, ctx, camera, uid=None):\n if not self.fragmap or self.fragmap_program is None:\n return\n\n # Transpose because np is row-major but OpenGL expects column-major.\n prog = self.fragmap_program\n self.set_camera_matrices(prog, camera)\n\n # Render with the specified object uid, if None use the node uid instead.\n prog[\"obj_id\"] = uid or self.uid\n\n if self.backface_culling or self.backface_fragmap:\n ctx.enable(moderngl.CULL_FACE)\n else:\n ctx.disable(moderngl.CULL_FACE)\n\n # If backface_fragmap is enabled for this node only render backfaces\n if self.backface_fragmap:\n ctx.cull_face = \"front\"\n\n self.render_positions(prog)\n\n # Restore cull face to back\n if self.backface_fragmap:\n ctx.cull_face = \"back\"\n\n def render_depth_prepass(self, camera, **kwargs):\n if not self.depth_prepass or self.depth_only_program is None:\n return\n\n prog = self.depth_only_program\n self.set_camera_matrices(prog, camera)\n self.render_positions(prog)\n\n def render_outline(self, ctx, camera):\n if self.outline and self.outline_program is not None:\n prog = self.outline_program\n self.set_camera_matrices(prog, camera)\n\n if self.backface_culling:\n ctx.enable(moderngl.CULL_FACE)\n else:\n ctx.disable(moderngl.CULL_FACE)\n self.render_positions(prog)\n\n # Render children node recursively.\n for n in self.nodes:\n n.render_outline(ctx, camera)\n\n def release(self):\n \"\"\"\n Release all OpenGL resources used by this node and any of its children. Subclasses that instantiate OpenGL\n objects should implement this method with '@hooked' to avoid leaking resources.\n \"\"\"\n for n in self.nodes:\n n.release()\n\n def on_selection(self, node, instance_id, tri_id):\n \"\"\"\n Called when the node is selected\n\n :param node: the node which was clicked (can be None if the selection wasn't a mouse event)\n :param instance_id: the id of the instance that was clicked, 0 if the object is not instanced\n (can be None if the selection wasn't a mouse event)\n :param tri_id: the id of the triangle that was clicked from the 'node' mesh\n (can be None if the selection wasn't a mouse event)\n \"\"\"\n pass\n\n def key_event(self, key, wnd_keys):\n \"\"\"\n Handle shortcut key presses (if you are the selected object)\n \"\"\"\n pass\n\n def update_frames(self, *args, **kwargs):\n pass\n\n def add_frames(self, *args, **kwargs):\n pass\n\n def remove_frames(self, *args, **kwargs):\n pass\n\n def _export_usd_recursively(self, stage, usd_path, directory, verbose):\n if verbose:\n print(usd_path)\n for n in self.nodes:\n if n.export_usd_enabled:\n n.export_usd(stage, usd_path, directory, verbose)\n\n def export_usd(self, stage, usd_path: str, directory: str = None, verbose=False):\n \"\"\"\n Export the node into an USD file. Nodes that implement this method should use\n recursively call this for every children that should also be exported.\n\n :param stage: an object of type Usd.Stage into which to export the node\n :param usd_path: the path of the parent object in the USD file scene hierarchy.\n \"\"\"\n from pxr import Gf, UsdGeom\n\n usd_path = f\"{usd_path}/{self.name.replace(' ', '_')}_{self.uid:03}\"\n\n # Transform.\n xform = UsdGeom.Xform.Define(stage, usd_path)\n a_xform = xform.AddTransformOp()\n a_xform.Set(Gf.Matrix4d(self.get_local_transform().astype(np.float64).T))\n\n self._export_usd_recursively(stage, usd_path, directory, verbose)" }, { "identifier": "hooked", "path": "aitviewer/utils/decorators.py", "snippet": "class hooked:\n def __init__(self, fn):\n self.fn = fn\n\n def __set_name__(self, owner, name):\n func = self.fn\n\n def _decorator(self, *args, **kwargs):\n super_obj = super(owner, self)\n super_fn = getattr(super_obj, func.__name__)\n super_fn(*args, **kwargs)\n return func(self, *args, **kwargs)\n\n setattr(owner, name, _decorator)\n\n def __call__(self):\n assert (\n False\n ), \"@hooked decorator object should never be called directly. This can happen if you apply this decorator to a function that is not a method.\"" } ]
import os import joblib import numpy as np from abc import ABC, abstractmethod from trimesh.transformations import rotation_matrix from aitviewer.configuration import CONFIG as C from aitviewer.renderables.lines import Lines from aitviewer.renderables.meshes import Meshes from aitviewer.renderables.rigid_bodies import RigidBodies from aitviewer.scene.camera_utils import ( look_at, normalize, orthographic_projection, perspective_projection, ) from aitviewer.scene.node import Node from aitviewer.utils.decorators import hooked
21,087
self.projection_matrix = None self.view_matrix = None self.view_projection_matrix = None def get_projection_matrix(self): if self.projection_matrix is None: raise ValueError("update_matrices() must be called before to update the projection matrix") return self.projection_matrix def get_view_matrix(self): if self.view_matrix is None: raise ValueError("update_matrices() must be called before to update the view matrix") return self.view_matrix def get_view_projection_matrix(self): if self.view_projection_matrix is None: raise ValueError("update_matrices() must be called before to update the view-projection matrix") return self.view_projection_matrix @abstractmethod def update_matrices(self, width, height): pass @property @abstractmethod def position(self): pass @property @abstractmethod def forward(self): pass @property @abstractmethod def up(self): pass @property @abstractmethod def right(self): pass def gui(self, imgui): pass class Camera(Node, CameraInterface): """ A base camera object that provides rendering of a camera mesh and visualization of the camera frustum and coordinate system. Subclasses of this class must implement the CameraInterface abstract methods. """ def __init__( self, inactive_color=(0.5, 0.5, 0.5, 1), active_color=(0.6, 0.1, 0.1, 1), viewer=None, **kwargs, ): """Initializer :param inactive_color: Color that will be used for rendering this object when inactive :param active_color: Color that will be used for rendering this object when active :param viewer: The current viewer, if not None the gui for this object will show a button for viewing from this camera in the viewer """ super(Camera, self).__init__(icon="\u0084", gui_material=False, **kwargs) # Camera object geometry vertices = np.array( [ # Body [0, 0, 0], [-1, -1, 1], [-1, 1, 1], [1, -1, 1], [1, 1, 1], # Triangle front [0.5, 1.1, 1], [-0.5, 1.1, 1], [0, 2, 1], # Triangle back [0.5, 1.1, 1], [-0.5, 1.1, 1], [0, 2, 1], ], dtype=np.float32, ) # Scale dimensions vertices[:, 0] *= 0.05 vertices[:, 1] *= 0.03 vertices[:, 2] *= 0.15 # Slide such that the origin is in front of the object vertices[:, 2] -= vertices[1, 2] * 1.1 # Reverse z since we use the opengl convention that camera forward is -z vertices[:, 2] *= -1 # Reverse x too to maintain a consistent triangle winding vertices[:, 0] *= -1 faces = np.array( [ [0, 1, 2], [0, 2, 4], [0, 4, 3], [0, 3, 1], [1, 3, 2], [4, 2, 3], [5, 6, 7], [8, 10, 9], ] ) self._active = False self.active_color = active_color self.inactive_color = inactive_color
# Copyright (C) 2023 ETH Zurich, Manuel Kaufmann, Velko Vechev, Dario Mylonopoulos def _transform_vector(transform, vector): """Apply affine transformation (4-by-4 matrix) to a 3D vector.""" return (transform @ np.concatenate([vector, np.array([1])]))[:3] def _transform_direction(transform, vector): """Apply affine transformation (4-by-4 matrix) to a 3D directon.""" return (transform @ np.concatenate([vector, np.array([0])]))[:3] class CameraInterface(ABC): """ An abstract class which describes the interface expected by the viewer for using this object as a camera """ def __init__(self): self.projection_matrix = None self.view_matrix = None self.view_projection_matrix = None def get_projection_matrix(self): if self.projection_matrix is None: raise ValueError("update_matrices() must be called before to update the projection matrix") return self.projection_matrix def get_view_matrix(self): if self.view_matrix is None: raise ValueError("update_matrices() must be called before to update the view matrix") return self.view_matrix def get_view_projection_matrix(self): if self.view_projection_matrix is None: raise ValueError("update_matrices() must be called before to update the view-projection matrix") return self.view_projection_matrix @abstractmethod def update_matrices(self, width, height): pass @property @abstractmethod def position(self): pass @property @abstractmethod def forward(self): pass @property @abstractmethod def up(self): pass @property @abstractmethod def right(self): pass def gui(self, imgui): pass class Camera(Node, CameraInterface): """ A base camera object that provides rendering of a camera mesh and visualization of the camera frustum and coordinate system. Subclasses of this class must implement the CameraInterface abstract methods. """ def __init__( self, inactive_color=(0.5, 0.5, 0.5, 1), active_color=(0.6, 0.1, 0.1, 1), viewer=None, **kwargs, ): """Initializer :param inactive_color: Color that will be used for rendering this object when inactive :param active_color: Color that will be used for rendering this object when active :param viewer: The current viewer, if not None the gui for this object will show a button for viewing from this camera in the viewer """ super(Camera, self).__init__(icon="\u0084", gui_material=False, **kwargs) # Camera object geometry vertices = np.array( [ # Body [0, 0, 0], [-1, -1, 1], [-1, 1, 1], [1, -1, 1], [1, 1, 1], # Triangle front [0.5, 1.1, 1], [-0.5, 1.1, 1], [0, 2, 1], # Triangle back [0.5, 1.1, 1], [-0.5, 1.1, 1], [0, 2, 1], ], dtype=np.float32, ) # Scale dimensions vertices[:, 0] *= 0.05 vertices[:, 1] *= 0.03 vertices[:, 2] *= 0.15 # Slide such that the origin is in front of the object vertices[:, 2] -= vertices[1, 2] * 1.1 # Reverse z since we use the opengl convention that camera forward is -z vertices[:, 2] *= -1 # Reverse x too to maintain a consistent triangle winding vertices[:, 0] *= -1 faces = np.array( [ [0, 1, 2], [0, 2, 4], [0, 4, 3], [0, 3, 1], [1, 3, 2], [4, 2, 3], [5, 6, 7], [8, 10, 9], ] ) self._active = False self.active_color = active_color self.inactive_color = inactive_color
self.mesh = Meshes(
2
2023-12-07 16:13:50+00:00
24k
nexB/dejacode
component_catalog/models.py
[ { "identifier": "build_licensing", "path": "component_catalog/license_expression_dje.py", "snippet": "def build_licensing(licenses=None):\n \"\"\"\n Return a Licensing from `licenses`: either a License QuerySet or a\n pre-built Licensing object (which is returned as-is).\n \"\"\"\n if isinstance(licenses, Licensing):\n return licenses\n return Licensing(licenses)" }, { "identifier": "get_license_objects", "path": "component_catalog/license_expression_dje.py", "snippet": "def get_license_objects(expression, licenses=None):\n \"\"\"\n Return a list of unique License instances from an expression string.\n Raise Exceptions on parsing errors.\n\n Check and parse the expression license symbols against an optional\n `licenses` object that can be either a License QuerySet or a pre-\n built Licensing object.\n\n The expression is assumed to:\n - be composed only from license keys (and not from license names)\n - contain ONLY known license keys\n\n Furthermore, the validity of \"WITH\" expression is not checked\n (e.g. `validate_strict` is not used when parsing then expression).\n \"\"\"\n licensing = build_licensing(licenses)\n # note: we use the simple tokenizer since we support only keys here.\n parsed = licensing.parse(expression, validate=False, strict=False, simple=True)\n symbols = licensing.license_symbols(parsed, unique=True, decompose=True)\n return [symbol.wrapped for symbol in symbols if isinstance(symbol, LicenseSymbolLike)]" }, { "identifier": "parse_expression", "path": "component_catalog/license_expression_dje.py", "snippet": "def parse_expression(\n expression, licenses=None, validate_known=True, validate_strict=False, simple=False\n):\n \"\"\"\n Return a parsed expression object given an expression string.\n Raise Exceptions on parsing errors\n\n Check and parse the expression license symbols against an optional\n `licenses` object that can be either a License QuerySet or a pre-\n built Licensing object.\n\n If `validate_known` is True, raise a ValidationError if a license\n symbol is unknown. Also include in exception message information\n about the available licenses.\n\n If `validate_strict` is True, raise a ValidationError if license\n symbol in a \"WITH\" exception expression is invalid e.g. in \"a WITH\n b\" either: \"a\" is an exception or \"b\" is not an exception.\n \"\"\"\n licensing = build_licensing(licenses)\n return licensing.parse(\n expression, validate=validate_known, strict=validate_strict, simple=simple\n )" }, { "identifier": "spdx", "path": "dejacode_toolkit/spdx.py", "snippet": "SPDX_SPEC_VERSION = \"2.3\"\nSPDX_LICENSE_LIST_VERSION = \"3.18\"\nSPDX_JSON_SCHEMA_LOCATION = \"spdx-schema-2.3.json\"\nSPDX_JSON_SCHEMA_URL = (\n \"https://raw.githubusercontent.com/spdx/spdx-spec/v2.3/schemas/spdx-schema.json\"\n)\nclass CreationInfo:\nclass Checksum:\nclass ExternalRef:\nclass ExtractedLicensingInfo:\nclass Package:\nclass File:\nclass Relationship:\nclass Document:\n def as_dict(self):\n def get_creators(self):\n def as_dict(self):\n def as_dict(self):\n def as_dict(self):\n def as_dict(self):\n def date_to_iso(date_str):\n def as_dict(self):\n def as_dict(self):\n def as_dict(self):\n def as_json(self, indent=2):\n def safe_document_name(name):\n def validate(self, schema):\ndef validate_document(document, schema):" }, { "identifier": "DataCollectionException", "path": "dejacode_toolkit/download.py", "snippet": "class DataCollectionException(Exception):\n pass" }, { "identifier": "collect_package_data", "path": "dejacode_toolkit/download.py", "snippet": "def collect_package_data(url):\n try:\n response = requests.get(url, timeout=5, stream=True)\n except (requests.RequestException, socket.timeout) as e:\n raise DataCollectionException(e)\n\n if response.status_code != 200:\n raise DataCollectionException(f\"Could not download content: {url}\")\n\n content_type = response.headers.get(\"content-type\", \"\").lower()\n if \"html\" in content_type:\n raise DataCollectionException(\"Content not downloadable.\")\n\n # Since we use stream=True, exceptions may occur on accessing response.content\n # for the first time.\n try:\n size = int(len(response.content))\n except requests.RequestException as e:\n raise DataCollectionException(e)\n\n # We cannot rely on the 'content-length' header as it is not always available.\n if size > CONTENT_MAX_LENGTH:\n raise DataCollectionException(\n f\"Downloaded content too large (Max: {filesizeformat(CONTENT_MAX_LENGTH)}).\"\n )\n\n content_disposition = response.headers.get(\"content-disposition\", \"\")\n _, params = cgi.parse_header(content_disposition)\n\n filename = params.get(\"filename\")\n if not filename:\n # Using ``response.url`` in place of provided ``url`` arg since the former\n # will be more accurate in case of HTTP redirect.\n filename = unquote(Path(urlparse(response.url).path).name)\n\n package_data = {\n \"download_url\": url,\n \"filename\": filename,\n \"size\": size,\n \"md5\": md5(response.content),\n \"sha1\": sha1(response.content),\n \"sha256\": sha256(response.content),\n \"sha512\": sha512(response.content),\n }\n\n return package_data" }, { "identifier": "PurlDB", "path": "dejacode_toolkit/purldb.py", "snippet": "class PurlDB(BaseService):\n label = \"PurlDB\"\n settings_prefix = \"PURLDB\"\n url_field_name = \"purldb_url\"\n api_key_field_name = \"purldb_api_key\"\n\n def __init__(self, user):\n super().__init__(user)\n self.package_api_url = f\"{self.api_url}packages/\"\n\n def get_package_list(\n self,\n search=None,\n page_size=None,\n page=None,\n timeout=None,\n extra_payload=None,\n ):\n \"\"\"\n Get the PurlDB packages list.\n An optional `search` can be providing for global search.\n Pagination is managed with `page_size` and `page`.\n \"\"\"\n payload = {}\n\n if search:\n # If the search string looks like a purl, use the purl filter\n field = \"purl\" if \"/\" in search else \"search\"\n payload[field] = search\n\n if page_size:\n payload[\"page_size\"] = page_size\n\n if page:\n payload[\"page\"] = page\n\n if extra_payload:\n payload.update(extra_payload)\n\n return self.request_get(self.package_api_url, params=payload, timeout=timeout)\n\n def get_package(self, uuid):\n \"\"\"Get a Package details entry providing its `uuid`.\"\"\"\n return self.request_get(url=f\"{self.package_api_url}{uuid}/\")\n\n def find_packages(self, payload, timeout=None):\n \"\"\"Get Packages details using provided `payload` filters on the PurlDB package list.\"\"\"\n response = self.request_get(self.package_api_url, params=payload, timeout=timeout)\n if response and response.get(\"count\") > 0:\n return response.get(\"results\")" }, { "identifier": "urn", "path": "dje/urn.py", "snippet": "class URNValidationError(Exception):\nURN_SCHEMAS = {\n \"license\": [\"key\"],\n \"owner\": [\"name\"],\n \"component\": [\"name\", \"version\"],\n}\nMAX_SEGMENTS = 4\ndef build(object_name, **fields):\ndef parse(urn):" }, { "identifier": "post_copy", "path": "dje/copier.py", "snippet": "SKIP = \"SKIP\"\nCOPY_DEFAULT_EXCLUDE = {\n \"License Library\": {\n \"license\": [\n \"guidance\",\n \"guidance_url\",\n \"usage_policy\",\n ],\n },\n \"Component Catalog\": {\n \"component\": [\n \"usage_policy\",\n \"guidance\",\n \"acceptable_linkages\",\n ],\n \"subcomponent relationship\": [\n \"extra_attribution_text\",\n \"usage_policy\",\n ],\n },\n}\nALWAYS_EXCLUDE = [\n \"created_date\",\n \"created_by\",\n \"last_modified_date\",\n \"last_modified_by\",\n \"request_count\",\n \"scanned_by\",\n \"project_uuid\",\n \"default_assignee\",\n]\ndef get_object_in(reference_obj, target_dataspace):\ndef get_or_create_in(reference_obj, target_dataspace, user, **kwargs):\ndef get_copy_defaults(dataspace, model_class):\ndef get_excluded_fields(exclude_dict, dataspace, model_class):\ndef copy_object(reference_obj, target_dataspace, user, update=False, **kwargs):\ndef copy_to(reference_obj, target_dataspace, user, **kwargs):\ndef get_generic_foreignkeys_fields(model_class):\ndef fix_generic_foreignkeys(reference_obj, target_obj):\ndef copy_foreignfields(reference_obj, target_obj, excluded_fields, user, **kwargs):\ndef copy_relational_fields(reference_obj, target_dataspace, user, update=False, **kwargs):\ndef copy_m2m_fields(reference_obj, target_dataspace, user, update=False, **kwargs):\ndef update_to(reference_obj, target_obj, user, **kwargs):" }, { "identifier": "post_update", "path": "dje/copier.py", "snippet": "SKIP = \"SKIP\"\nCOPY_DEFAULT_EXCLUDE = {\n \"License Library\": {\n \"license\": [\n \"guidance\",\n \"guidance_url\",\n \"usage_policy\",\n ],\n },\n \"Component Catalog\": {\n \"component\": [\n \"usage_policy\",\n \"guidance\",\n \"acceptable_linkages\",\n ],\n \"subcomponent relationship\": [\n \"extra_attribution_text\",\n \"usage_policy\",\n ],\n },\n}\nALWAYS_EXCLUDE = [\n \"created_date\",\n \"created_by\",\n \"last_modified_date\",\n \"last_modified_by\",\n \"request_count\",\n \"scanned_by\",\n \"project_uuid\",\n \"default_assignee\",\n]\ndef get_object_in(reference_obj, target_dataspace):\ndef get_or_create_in(reference_obj, target_dataspace, user, **kwargs):\ndef get_copy_defaults(dataspace, model_class):\ndef get_excluded_fields(exclude_dict, dataspace, model_class):\ndef copy_object(reference_obj, target_dataspace, user, update=False, **kwargs):\ndef copy_to(reference_obj, target_dataspace, user, **kwargs):\ndef get_generic_foreignkeys_fields(model_class):\ndef fix_generic_foreignkeys(reference_obj, target_obj):\ndef copy_foreignfields(reference_obj, target_obj, excluded_fields, user, **kwargs):\ndef copy_relational_fields(reference_obj, target_dataspace, user, update=False, **kwargs):\ndef copy_m2m_fields(reference_obj, target_dataspace, user, update=False, **kwargs):\ndef update_to(reference_obj, target_obj, user, **kwargs):" }, { "identifier": "JSONListField", "path": "dje/fields.py", "snippet": "class JSONListField(models.JSONField):\n \"\"\"\n Store a list of values in a JSONField.\n\n The value \"list\" is set as the default and validation is applied to ensure\n that the provided value is a valid JSON list.\n \"\"\"\n\n description = _(\"A JSON list object\")\n empty_values = [list()]\n default_error_messages = {\n \"invalid_list\": _('Value must be valid JSON list: [\"item1\", \"item2\"].'),\n }\n _default_hint = (\"list\", \"[]\")\n default_validators = [validate_list]\n\n def __init__(self, *args, **kwargs):\n kwargs[\"default\"] = list\n super().__init__(*args, **kwargs)" }, { "identifier": "NoStripTextField", "path": "dje/fields.py", "snippet": "class NoStripTextField(models.TextField):\n \"\"\"\n TextField without the default stripping.\n Also normalize CRLF and CR newlines to just LF.\n \"\"\"\n\n def formfield(self, **kwargs):\n kwargs[\"strip\"] = False\n return super().formfield(**kwargs)\n\n def to_python(self, value):\n value = super().to_python(value)\n return normalize_newlines(value)" }, { "identifier": "DataspacedManager", "path": "dje/models.py", "snippet": "class DataspacedManager(models.Manager.from_queryset(DataspacedQuerySet)):\n def get_queryset(self):\n return super().get_queryset().select_related(\"dataspace\")" }, { "identifier": "DataspacedModel", "path": "dje/models.py", "snippet": "class DataspacedModel(models.Model):\n \"\"\"Abstract base model for all models that are keyed by Dataspace.\"\"\"\n\n dataspace = models.ForeignKey(\n to=\"dje.Dataspace\",\n on_delete=models.PROTECT,\n editable=False,\n help_text=DATASPACE_FIELD_HELP_TEXT,\n )\n\n # This field does not have unique=True because subclasses of\n # ``DataspacedModel`` should declare a unique_together meta option\n # for ``dataspace`` and ``uuid``. Objects that inherit from\n # ``DataspacedModel`` and that are copied between dataspaces will\n # have the same uuid. This means that an object's universally unique\n # identifier (uuid) may *not* be universally unique to a database row.\n uuid = models.UUIDField(\n _(\"UUID\"),\n default=uuid.uuid4,\n editable=False,\n )\n\n # From: https://docs.djangoproject.com/en/dev/topics/db/managers/\n # \"Managers from abstract base classes are always inherited by the child\n # class, [...]. Abstract base classes are designed to capture information\n # and behavior that is common to their child classes. Defining common\n # managers is an appropriate part of this common information.\"\n # As a result, all DataspacedModel models will inherit from the\n # appropriate DataspacedManager by default.\n # When the `objects` attribute is overridden in the child class, we enforce\n # that the Manager class defined is a child of the DataspacedManager\n # using the Django \"System check framework\".\n objects = DataspacedManager()\n\n def get_dataspace(self):\n return self.dataspace\n\n get_dataspace.short_description = _(\"Dataspace\")\n get_dataspace.admin_order_field = \"dataspace\"\n\n class Meta:\n abstract = True\n\n def natural_key(self):\n return self.dataspace.name, self.uuid\n\n @classmethod\n def check(cls, **kwargs):\n \"\"\"\n Enforce the usage of DataspacedManager (or child class) as the\n default Manager using the Django \"System check framework\".\n Note that Manager generated from a subclass of DataspacedQuerySet are valid:\n Manager(models.Manager.from_queryset(DataspacedQuerySet))\n \"\"\"\n errors = super().check(**kwargs)\n enforced_manager = DataspacedManager\n enforced_queryset = DataspacedQuerySet\n\n has_valid_manager = any(\n [\n isinstance(cls._default_manager, enforced_manager),\n issubclass(cls._default_manager._queryset_class, enforced_queryset),\n ]\n )\n\n if not has_valid_manager:\n manager_name = enforced_manager.__name__\n errors.append(\n checks.Error(\n f\"Manager is not a subclass of {manager_name}\",\n hint=f\"Set the proper {manager_name} Manager\",\n obj=cls,\n )\n )\n\n if cls._meta.managed and not cls._meta.unique_together:\n errors.append(\n checks.Error(\n \"`unique_together` must be defined on DataspacedModel.\",\n hint=\"Add a value for unique_together on this model Meta class.\",\n obj=cls,\n )\n )\n\n return errors\n\n def save(self, *args, **kwargs):\n \"\"\"Enforces related object to share the same Dataspace as self.\"\"\"\n # A `copy` argument is provided when calling save() from the copy.\n # It needs to be poped before calling the super().save()\n kwargs.pop(\"copy\", None)\n\n # For these model classes, related objects can still be saved even if\n # they have a dataspace which is not the current one.\n allowed_models = [Dataspace, get_user_model(), ContentType]\n\n for field in self.local_foreign_fields:\n if field.related_model not in allowed_models:\n attr_value = getattr(self, field.name)\n if attr_value and attr_value.dataspace != self.dataspace:\n raise ValueError(\n f'The Dataspace of the related object: \"{attr_value}\" '\n f'is not \"{self.dataspace}\"'\n )\n\n self.clean_extra_spaces_in_identifier_fields()\n super().save(*args, **kwargs)\n\n @classmethod\n def model_fields(cls):\n \"\"\"Return the list of fields name available on this model.\"\"\"\n return [field.name for field in cls._meta.get_fields()]\n\n @classmethod\n def create_from_data(cls, user, data, validate=False):\n \"\"\"\n Create and Return an instance of this `cls` using the provided `data`.\n The instance is created in the provided `user` Dataspace.\n\n If `validate` is enabled, the data with be validated using the `full_clean`\n method before attempting the `save`. This has the benefit of catching\n data issues and returning those as `ValidationError` instead of `DatabaseError`\n at save time, that will have an impact in the database transaction management.\n \"\"\"\n model_fields = cls.model_fields()\n cleaned_data = {\n field_name: value for field_name, value in data.items() if field_name in model_fields\n }\n\n instance = cls(\n dataspace=user.dataspace,\n created_by=user,\n **cleaned_data,\n )\n\n if validate:\n instance.full_clean()\n instance.save()\n\n return instance\n\n def update_from_data(self, user, data, override=False):\n \"\"\"\n Update this object instance with the provided `data`.\n The `save()` method is called only if at least one field was modified.\n \"\"\"\n model_fields = self.model_fields()\n updated_fields = []\n\n for field_name, value in data.items():\n if value in EMPTY_VALUES or field_name not in model_fields:\n continue\n\n current_value = getattr(self, field_name, None)\n if not current_value or (current_value != value and override):\n setattr(self, field_name, value)\n updated_fields.append(field_name)\n\n if updated_fields:\n self.last_modified_by = user\n self.save()\n\n return updated_fields\n\n def as_json(self):\n try:\n serialized_data = serialize(\n \"json\",\n [self],\n use_natural_foreign_keys=True,\n use_natural_primary_keys=True,\n )\n except SerializationError:\n serialized_data = None\n\n return serialized_data\n\n def get_verbose_name(self):\n return self._meta.verbose_name\n\n def get_url(self, name, params):\n opts = self._meta\n viewname = f\"{opts.app_label}:{opts.model_name}_{name}\"\n return reverse(viewname, args=params)\n\n def get_admin_url(self):\n opts = self._meta\n viewname = f\"admin:{opts.app_label}_{opts.model_name}_change\"\n try:\n url = reverse(viewname, args=[self.pk])\n except NoReverseMatch:\n return\n return url\n\n def get_change_url(self):\n \"\"\"\n Return the admin URL by default.\n Override this method if the object has a custom change view.\n \"\"\"\n return self.get_admin_url()\n\n def get_admin_action_url(self, name):\n opts = self._meta\n try:\n url = reverse(f\"admin:{opts.app_label}_{opts.model_name}_{name}\")\n except NoReverseMatch:\n return\n return f\"{url}?ids={self.pk}\"\n\n def get_copy_url(self):\n return self.get_admin_action_url(\"copy\")\n\n def get_api_copy_to_my_dataspace_url(self):\n model_name = self._meta.model_name\n return reverse(f\"api_v2:{model_name}-copy-to-my-dataspace\", args=[self.uuid])\n\n def get_compare_url(self):\n return self.get_admin_action_url(\"compare\")\n\n def get_html_link(self, href, **attrs):\n \"\"\"\n Return a HTML link using the given href and __str__ of the object\n as value.\n\n Anything given as kwargs will be added as attributes on the anchor.\n instance.get_html_link('a_href', target='_blank', title='Title')\n\n A dict can be also be given like this:\n attributes = **{'target': '_blank', 'title': 'Title'}\n\n A special 'field_name' attribute can be used to replace the __str__ value\n by the given model field value of the instance.\n \"\"\"\n value = attrs.pop(\"value\", None)\n if not value:\n field_name = attrs.pop(\"field_name\", None)\n value = getattr(self, field_name) if field_name else self\n\n final_attrs = {\"href\": smart_urlquote(href)}\n if attrs is not None:\n final_attrs.update(attrs)\n\n return format_html(\"<a{}>{}</a>\", flatatt(final_attrs), value)\n\n def get_admin_link(self, **attrs):\n \"\"\"Return a HTML link using the get_admin_url() as href.\"\"\"\n admin_url = self.get_admin_url()\n if admin_url:\n return self.get_html_link(self.get_admin_url(), **attrs)\n\n def get_absolute_link(self, **attrs):\n \"\"\"Return a HTML link using the get_absolute_url() as href.\"\"\"\n if hasattr(self, \"get_absolute_url\"):\n return self.get_html_link(self.get_absolute_url(), **attrs)\n\n @property\n def urn_link(self):\n \"\"\"Require the `urn` property to be implemented on the Model.\"\"\"\n urn = getattr(self, \"urn\", None)\n if urn:\n return format_html('<a href=\"{}\">{}</a>', reverse(\"urn_resolve\", args=[urn]), urn)\n\n def _get_local_foreign_fields(self):\n \"\"\"\n Return a list of ForeignKey type fields of the model.\n GenericForeignKey are not included, filtered out with field.concrete\n \"\"\"\n return [field for field in self._meta.get_fields() if field.many_to_one and field.concrete]\n\n local_foreign_fields = property(_get_local_foreign_fields)\n\n @classmethod\n def get_identifier_fields(cls):\n \"\"\"\n Return a list of the fields, based on the Meta unique_together, to be\n used to match a unique instance within a Dataspace.\n \"\"\"\n unique_fields = cls._meta.unique_together\n\n # Using only the first part of the declared unicity\n if type(unique_fields[0]) is tuple:\n unique_fields = unique_fields[0]\n\n return [str(field_name) for field_name in unique_fields if field_name != \"dataspace\"]\n\n def get_exclude_candidates_fields(self):\n \"\"\"\n Return the fields supported by the copy exclude feature.\n This exclude all the fields like the dataspace, id, uuid and\n field that do not accept a NULL value.\n \"\"\"\n from dje.copier import ALWAYS_EXCLUDE\n\n fields = []\n for field in self._meta.fields:\n skip_conditions = [\n field.related_model is Dataspace,\n isinstance(field, models.AutoField),\n isinstance(field, models.UUIDField),\n not field.null and not field.blank and not field.has_default(),\n field.name in ALWAYS_EXCLUDE,\n ]\n\n if not any(skip_conditions):\n fields.append(field)\n\n return fields\n\n @classmethod\n def get_exclude_choices(cls):\n return sorted(\n (\n (field.name, capfirst(field.verbose_name))\n for field in cls().get_exclude_candidates_fields()\n ),\n key=operator.itemgetter(1), # Sorts the choices by their verbose_name\n )\n\n def unique_filters_for(self, target):\n \"\"\"\n Return a dictionary of filters based on unicity constraints.\n (i.e. the Model Meta \"unique_together\" of the object.)\n\n The filters are used to \"match\" an existing entry in the\n \"target\" Dataspace.\n\n The result of the match is used to know if it's a copy or update case.\n Only the first field (or set of fields) declared in the unique_together\n is used as a unique_filters.\n\n This function is used during the Object \"copy\" and \"update\" to another\n Dataspace.\n \"\"\"\n unique_filters = {}\n\n for field_name in self.get_identifier_fields():\n field_instance = getattr(self, field_name)\n\n if isinstance(field_instance, DataspacedModel):\n # In this case, the current field_instance is a FK to another\n # DataspacedModel instance.\n # Trying to match the object in \"target\"...\n manager = field_instance.__class__.objects\n # ...with the UUID first\n result = manager.filter(uuid=self.uuid, dataspace=target)\n # ... with current unique_filters_for method if nothing matched\n if not result:\n filters = field_instance.unique_filters_for(target)\n result = manager.filter(**filters)\n\n if result:\n unique_filters.update({field_name: result[0]})\n else:\n unique_filters.update({field_name: None})\n else:\n unique_filters.update({field_name: field_instance})\n\n unique_filters.update({\"dataspace\": target})\n return unique_filters\n\n @staticmethod\n def get_extra_relational_fields():\n \"\"\"\n Return a list of related_name as declared on the \"Many\" part of the\n relation.\n Hook to explicitly declare the relational fields,\n like OneToMany and GenericForeignKey pointing to this Model.\n This is one by the object_copy feature.\n Default: '<fk_model_name>_set'\n \"\"\"\n return []\n\n def clean(self, from_api=False):\n if self.id: # Addition only\n return\n\n self.validate_case_insensitive_unique_on()\n self.validate_against_reference_data(from_api)\n\n def validate_case_insensitive_unique_on(self):\n \"\"\"\n Validate uniqueness via case-insensitive match, using the field\n set on this Model `case_insensitive_unique_on` property.\n The validation is only applied on Addition.\n \"\"\"\n errors = {}\n\n for field_name in getattr(self, \"case_insensitive_unique_on\", []):\n value = getattr(self, field_name, None)\n if not value:\n return\n\n msg = (\n 'The application object that you are creating already exists as \"{}\". '\n \"Note that a different case in the object name is not sufficient to \"\n \"make it unique.\"\n )\n\n qs = (\n self.__class__._default_manager.scope(self.dataspace)\n .filter(**{f\"{field_name}__iexact\": value})\n .exclude(**{f\"{field_name}__exact\": value})\n )\n\n if qs.exists():\n error = msg.format(getattr(qs.first(), field_name))\n errors.setdefault(field_name, []).append(error)\n\n if errors:\n raise ValidationError(errors)\n\n def validate_against_reference_data(self, from_api=False):\n \"\"\"\n Validate values set on a non-reference dataspace instance against reference data.\n\n Inspired by django.db.models.Model._perform_unique_checks()\n \"\"\"\n LIMITED_TO_MODELS = [\n \"Owner\",\n \"License\",\n \"LicenseCategory\",\n \"LicenseProfile\",\n \"LicenseStatus\",\n \"LicenseStyle\",\n \"LicenseTag\",\n \"Component\",\n \"ComponentKeyword\",\n \"ComponentStatus\",\n \"ComponentType\",\n \"Package\",\n ]\n\n if self.__class__.__name__ not in LIMITED_TO_MODELS:\n return\n\n reference_dataspace = Dataspace.objects.get_reference()\n dataspace = getattr(self, \"dataspace\", None)\n run_validation = all(\n [\n dataspace,\n reference_dataspace,\n dataspace != reference_dataspace,\n ]\n )\n if not run_validation:\n return\n\n or_queries = []\n involved_lookup_fields = []\n uniques_lookups = [fields for fields in self._meta.unique_together if \"uuid\" not in fields]\n\n for fields in uniques_lookups:\n lookup_kwargs = {}\n for field_name in fields:\n lookup_value = None\n if field_name != \"dataspace\":\n lookup_value = getattr(self, field_name, None)\n if lookup_value is None:\n continue\n lookup_kwargs[str(field_name)] = lookup_value\n involved_lookup_fields.append(field_name)\n\n if lookup_kwargs:\n or_queries.append(models.Q(**lookup_kwargs))\n\n if not or_queries:\n return\n\n qs = self.__class__._default_manager.filter(reduce(operator.or_, or_queries))\n\n if qs.scope(self.dataspace).exists():\n return # Skip validation if the object already exists in my own Dataspace\n\n if qs.scope(reference_dataspace).exists():\n reference_object = qs.first()\n msg = (\n \"The application object that you are creating already exists as {} \"\n \"in the reference dataspace.\"\n )\n\n if not from_api:\n copy_link = self.get_html_link(\n reference_object.get_copy_url(),\n value=_(\"Copy to my Dataspace\"),\n target=\"_blank\",\n )\n msg += f\" {copy_link}\"\n if hasattr(reference_object, \"get_absolute_url\"):\n reference_object = reference_object.get_absolute_link(target=\"_blank\")\n else:\n copy_link = reference_object.get_api_copy_to_my_dataspace_url()\n msg += (\n f\" Use the following URL to copy the reference object to your \"\n f\"local Dataspace: {copy_link}\"\n )\n\n error = format_html(msg, reference_object)\n\n if from_api:\n errors = {\n \"error\": error,\n \"copy_url\": copy_link,\n }\n else:\n errors = {field: error for field in involved_lookup_fields}\n\n raise ValidationError(errors)\n\n def clean_extra_spaces_in_identifier_fields(self):\n \"\"\"Remove extra spaces in identifier fields value.\"\"\"\n for field_name in self.get_identifier_fields():\n field_instance = self._meta.get_field(field_name)\n if isinstance(field_instance, models.CharField):\n field_value = getattr(self, field_name, \"\")\n if \" \" in field_value:\n setattr(self, field_name, \" \".join(field_value.split()))\n\n def mark_all_notifications_as_read(self, user):\n unread_notifications = Notification.objects.unread().filter(\n action_object_content_type__model=self._meta.model_name,\n action_object_object_id=self.id,\n recipient=user,\n )\n if unread_notifications:\n unread_notifications.update(unread=False)" }, { "identifier": "DataspacedQuerySet", "path": "dje/models.py", "snippet": "class DataspacedQuerySet(models.QuerySet):\n \"\"\"\n QuerySet for the DataspacedModel to be used on the Models as\n DataspacedManager (using Manager.from_queryset)\n\n Provide filters related to the Dataspace system.\n \"\"\"\n\n def get_by_natural_key(self, dataspace_name, uuid):\n return self.get(dataspace__name=dataspace_name, uuid=uuid)\n\n def scope(self, dataspace, include_reference=False):\n \"\"\"\n Limit the QuerySet results to the provided `dataspace`.\n The reference Dataspace results can be included using the\n `include_reference` argument.\n When a string is provided for `dataspace` in place of a Dataspace\n instance, the `scope_by_name` method will be called.\n \"\"\"\n if type(dataspace) is str:\n return self.scope_by_name(dataspace_name=dataspace)\n\n dataspaces = {dataspace}\n if include_reference:\n reference = Dataspace.objects.get_reference()\n if reference:\n dataspaces.add(reference)\n\n return self.filter(dataspace__in=dataspaces)\n\n def scope_by_name(self, dataspace_name):\n return self.filter(dataspace__name=dataspace_name)\n\n def scope_by_id(self, dataspace_id):\n return self.filter(dataspace__id=dataspace_id)\n\n def scope_for_user(self, user):\n return self.filter(dataspace=user.dataspace)\n\n def scope_for_user_in_admin(self, user):\n # Used in DataspacedAdmin.get_queryset()\n if user.dataspace.is_reference:\n return self # no filtering\n return self.scope(user.dataspace, include_reference=True)\n\n def get_or_none(self, *args, **kwargs):\n \"\"\"Return a single object matching the given keyword arguments, `None` otherwise.\"\"\"\n with suppress(self.model.DoesNotExist, ValidationError):\n return self.get(*args, **kwargs)\n\n def group_by(self, field_name):\n \"\"\"Return a dict of QS instances grouped by the given `field_name`.\"\"\"\n # Not using a dict comprehension to support QS without `.order_by(field_name)`.\n grouped = defaultdict(list)\n\n for field_value, group in groupby(self, attrgetter(field_name)):\n grouped[field_value].extend(list(group))\n\n return dict(grouped)" }, { "identifier": "ExternalReferenceMixin", "path": "dje/models.py", "snippet": "class ExternalReferenceMixin(models.Model):\n \"\"\"\n Abstract Model Mixin to add proper ExternalReference deletion behavior.\n\n From the documentation: if you delete an object that has a GenericRelation,\n any objects which have a GenericForeignKey pointing at it will be deleted as\n well.\n \"\"\"\n\n external_references = GenericRelation(ExternalReference)\n\n class Meta:\n abstract = True" }, { "identifier": "History", "path": "dje/models.py", "snippet": "class History(models.Model):\n ADDITION = ADDITION\n CHANGE = CHANGE\n DELETION = DELETION\n\n ACTION_FLAG_CHOICES = (\n (ADDITION, _(\"Addition\")),\n (CHANGE, _(\"Change\")),\n (DELETION, _(\"Deletion\")),\n )\n\n object_dataspace = models.ForeignKey(\n to=\"dje.Dataspace\",\n on_delete=models.CASCADE,\n null=True,\n blank=True,\n editable=False,\n )\n\n serialized_data = models.TextField(\n null=True,\n blank=True,\n editable=False,\n help_text=_(\"Serialized data of the instance just before this change.\"),\n )\n\n # The following fields are directly taken from django.contrib.admin.models.LogEntry\n # Since the LogEntry is not abstract we cannot properly inherit from it.\n\n action_time = models.DateTimeField(\n _(\"action time\"),\n default=timezone.now,\n editable=False,\n )\n\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n models.CASCADE,\n verbose_name=_(\"user\"),\n )\n\n content_type = models.ForeignKey(\n ContentType,\n models.SET_NULL,\n verbose_name=_(\"content type\"),\n blank=True,\n null=True,\n )\n\n object_id = models.TextField(\n _(\"object id\"),\n blank=True,\n null=True,\n )\n\n object_repr = models.CharField(\n _(\"object repr\"),\n max_length=200,\n )\n\n action_flag = models.PositiveSmallIntegerField(\n _(\"action flag\"),\n choices=ACTION_FLAG_CHOICES,\n )\n\n # change_message is either a string or a JSON structure\n change_message = models.TextField(\n _(\"change message\"),\n blank=True,\n )\n\n objects = HistoryManager()\n\n class Meta:\n verbose_name = _(\"history entry\")\n verbose_name_plural = _(\"history entries\")\n ordering = (\"-action_time\",)\n\n # Clone the method from Django's LogEntry model.\n __repr__ = LogEntry.__repr__\n __str__ = LogEntry.__str__\n is_addition = LogEntry.is_addition\n is_change = LogEntry.is_change\n is_deletion = LogEntry.is_deletion\n get_change_message = LogEntry.get_change_message\n get_edited_object = LogEntry.get_edited_object\n get_admin_url = LogEntry.get_edited_object\n\n @classmethod\n def log_addition(cls, user, obj, message=None):\n \"\"\"Create History entry on Addition with the proper `change_message`.\"\"\"\n if not message:\n message = [{\"added\": {}}]\n\n return cls.objects.log_action(user, obj, cls.ADDITION, message)\n\n @classmethod\n def log_change(cls, user, obj, message, serialized_data=None):\n \"\"\"Create History entry on Change.\"\"\"\n return cls.objects.log_action(user, obj, cls.CHANGE, message, serialized_data)\n\n @classmethod\n def log_deletion(cls, user, obj):\n \"\"\"\n Create History entry on Deletion.\n Include the serialized_data if `as_json()` is available on the model class.\n \"\"\"\n serialized_data = None\n with suppress(AttributeError):\n serialized_data = obj.as_json()\n\n return cls.objects.log_action(user, obj, cls.DELETION, serialized_data=serialized_data)" }, { "identifier": "HistoryFieldsMixin", "path": "dje/models.py", "snippet": "class HistoryFieldsMixin(HistoryUserFieldsMixin, HistoryDateFieldsMixin):\n \"\"\"Add the created_date, last_modified_date, created_by, last_modified_by fields.\"\"\"\n\n class Meta:\n abstract = True" }, { "identifier": "ParentChildModelMixin", "path": "dje/models.py", "snippet": "class ParentChildModelMixin:\n \"\"\"\n Provide methods for Parent/Child m2m relationship.\n It requires to be associate with a 'through' Model that extends from\n ParentChildRelationshipModel and that declares 2 FKs 'parent' and 'child'\n to this Model.\n One ManyToManyField can be explicitly declared on this Model to enable the\n copy of children only (parent copy is not wanted/supported).\n\n children = models.ManyToManyField(\n 'self', through='ParentChildRelationshipModel', symmetrical=False)\n \"\"\"\n\n def get_parents(self):\n \"\"\"\n Return the direct parents of the self Object as a QuerySet.\n The default ordering is set on the m2m Model.\n \"\"\"\n parents_ids = self.related_parents.values(\"parent__id\")\n return self.__class__._default_manager.filter(id__in=parents_ids)\n\n def get_children(self):\n \"\"\"\n Return the direct children of the self Object as a QuerySet.\n The default ordering is set on the m2m Model.\n \"\"\"\n children_ids = self.related_children.values(\"child__id\")\n return self.__class__._default_manager.filter(id__in=children_ids)\n\n def is_parent_of(self, obj):\n \"\"\"Return True if the self Object is a direct parent of the given one.\"\"\"\n return self in obj.get_parents()\n\n def is_child_of(self, obj):\n \"\"\"Return True if the self Object is a direct child of the given one.\"\"\"\n return self in obj.get_children()\n\n def get_ancestors(self):\n \"\"\"Return a set of all the ancestors of the self object.\"\"\"\n ancestors = set()\n for parent in self.get_parents():\n ancestors.add(parent)\n ancestors.update(parent.get_ancestors())\n return ancestors\n\n def get_descendants(self, set_direct_parent=False):\n \"\"\"Return a set of all the descendants of the self object.\"\"\"\n descendants = set()\n for child in self.get_children():\n if set_direct_parent:\n child.direct_parent = self\n descendants.add(child)\n descendants.update(child.get_descendants())\n return descendants\n\n def get_ancestor_ids(self):\n \"\"\"Return a list of ids of all the ancestors of the self object.\"\"\"\n return [instance.id for instance in self.get_ancestors()]\n\n def get_descendant_ids(self):\n \"\"\"Return a list of ids of all the descendants of the self object.\"\"\"\n return [instance.id for instance in self.get_descendants()]\n\n def get_related_ancestors(self):\n \"\"\"\n Return a set of all the *related* ancestors of the self object.\n Where get_ancestors() Return the objects at the end of the relation,\n this return the intermediary 'through' objects.\n \"\"\"\n ancestors = set()\n for related_parent in self.related_parents.all():\n ancestors.add(related_parent)\n ancestors.update(related_parent.parent.get_related_ancestors())\n return ancestors\n\n def get_related_descendants(self):\n \"\"\"\n Return a set of all the *related* descendants of the self object.\n Where get_descendants() Return the objects at the end of the relation,\n this return the intermediary 'through' objects.\n \"\"\"\n descendants = set()\n for related_child in self.related_children.all():\n descendants.add(related_child)\n descendants.update(related_child.child.get_related_descendants())\n return descendants\n\n def is_ancestor_of(self, obj):\n \"\"\"Return True if the current self Object is an ancestor of the given one.\"\"\"\n return self in obj.get_ancestors()\n\n def is_descendant_of(self, obj):\n \"\"\"Return True if the self Object is a descendant of the given one.\"\"\"\n return self in obj.get_descendants()\n\n def has_parent_or_child(self):\n \"\"\"\n Return True if the self Object is part of at least 1 m2m relation,\n either as a child or as a parent.\n \"\"\"\n return self.related_parents.exists() or self.related_children.exists()" }, { "identifier": "ParentChildRelationshipModel", "path": "dje/models.py", "snippet": "class ParentChildRelationshipModel(DataspacedModel):\n \"\"\"\n Define a parent/child relation.\n\n This Model needs to be used with the ParentChildModel.\n The 2 following fields are required to be declared this way:\n\n parent = models.ForeignKey(ParentChildModel, related_name='related_children')\n child = models.ForeignKey(ParentChildModel, related_name='related_parents')\n\n Extra fields are possible.\n \"\"\"\n\n class Meta:\n abstract = True\n unique_together = ((\"parent\", \"child\"), (\"dataspace\", \"uuid\"))\n ordering = [\"parent\", \"child\"]\n\n def __str__(self):\n return f\"Parent: {self.parent} ; Child: {self.child}\"\n\n def clean(self, from_api=False):\n # If one of the main Object (child or parent) is not saved in the DB\n # yet then no further validation possible.\n if not self.child_id or not self.parent_id:\n return\n\n if self.parent == self.child:\n raise ValidationError(\"This Object cannot be his own child or parent.\")\n\n if self.parent.is_descendant_of(self.child):\n raise ValidationError(\n \"The current Object is a descendant of the selected child, \"\n \"it cannot also be a parent for it.\"\n )\n\n super().clean(from_api)" }, { "identifier": "ReferenceNotesMixin", "path": "dje/models.py", "snippet": "class ReferenceNotesMixin(models.Model):\n \"\"\"Add the reference_notes field.\"\"\"\n\n reference_notes = models.TextField(\n blank=True,\n help_text=_(\n \"Reference Notes provide background details about the sofware and \"\n \"licenses in DejaCode, alerting you to pertinent ownership history \"\n \"or licensing complexities\"\n ),\n )\n\n class Meta:\n abstract = True" }, { "identifier": "tasks_logger", "path": "dje/tasks.py", "snippet": "def send_mail_task(subject, message, from_email, recipient_list, fail_silently=True):\ndef send_mail_to_admins_task(subject, message, from_email=None, fail_silently=True):\ndef call_management_command(name, *args, **options):\ndef package_collect_data(instance_id):\ndef scancodeio_submit_scan(uris, user_uuid, dataspace_uuid):\ndef scancodeio_submit_manifest_inspection(scancodeproject_uuid, user_uuid):\ndef pull_project_data_from_scancodeio(scancodeproject_uuid):" }, { "identifier": "set_fields_from_object", "path": "dje/utils.py", "snippet": "def set_fields_from_object(source, target, fields):\n \"\"\"\n Get values from `source` object and set on `target` for the given list\n of `fields`.\n\n Return the list of changed fields.\n \"\"\"\n changed_fields = []\n\n for field_name in fields:\n source_value = getattr(source, field_name, None)\n target_value = getattr(target, field_name, None)\n\n if source_value and not target_value:\n setattr(target, field_name, source_value)\n changed_fields.append(field_name)\n\n return changed_fields" }, { "identifier": "generic_uri_validator", "path": "dje/validators.py", "snippet": "def validate_list(value):\n def validate(self, password, user=None):\n def get_help_text(self):\nclass SpecialCharacterPasswordValidator:\n SPECIAL_CHARS = \"!?*@#$%^&+~=,.:;_/(){}<>\\\\-\"" }, { "identifier": "validate_url_segment", "path": "dje/validators.py", "snippet": "def validate_list(value):\n def validate(self, password, user=None):\n def get_help_text(self):\nclass SpecialCharacterPasswordValidator:\n SPECIAL_CHARS = \"!?*@#$%^&+~=,.:;_/(){}<>\\\\-\"" }, { "identifier": "validate_version", "path": "dje/validators.py", "snippet": "def validate_list(value):\n def validate(self, password, user=None):\n def get_help_text(self):\nclass SpecialCharacterPasswordValidator:\n SPECIAL_CHARS = \"!?*@#$%^&+~=,.:;_/(){}<>\\\\-\"" }, { "identifier": "License", "path": "license_library/models.py", "snippet": "class License(\n LicenseSymbolMixin,\n ReferenceNotesMixin,\n UsagePolicyMixin,\n ExternalReferenceMixin,\n HistoryFieldsMixin,\n RequestMixin,\n DataspacedModel,\n):\n owner = models.ForeignKey(\n to=\"organization.Owner\",\n on_delete=models.PROTECT,\n help_text=_(\n \"An owner is an entity that is the original author or custodian of one or \"\n \"more software licenses, and which is responsible for the text of that license.\"\n ),\n )\n\n key = models.CharField(\n db_index=True,\n max_length=50,\n help_text=_(\"Unique key name of the license.\"),\n validators=[validate_slug_plus],\n )\n\n name = models.CharField(\n db_index=True,\n max_length=100,\n help_text=_(\"The full name of the license, as provided by the original authors.\"),\n )\n\n short_name = models.CharField(\n db_index=True,\n max_length=50,\n verbose_name=_(\"Short Name\"),\n help_text=_(\"Most commonly used name for the license, often abbreviated.\"),\n )\n\n keywords = models.CharField(\n db_index=True,\n max_length=500,\n blank=True,\n help_text=_(\n \"Keywords to associate with a license to ensure that the license will be \"\n \"found when a user searches on one or more of the keywords. Examples include \"\n \"alternative names for the license, or file/product names that are commonly \"\n \"associated with the license.\"\n ),\n )\n\n homepage_url = models.URLField(\n _(\"Homepage URL\"),\n max_length=1024,\n blank=True,\n help_text=_(\"Homepage URL for the license.\"),\n )\n\n full_text = NoStripTextField(\n blank=True,\n help_text=_(\n \"The full text of the license. Note that actual usage of a license with \"\n \"software may include copyright statements and owner information.\"\n ),\n )\n\n standard_notice = NoStripTextField(\n blank=True,\n help_text=_(\"The standard notice text for this license if it exists.\"),\n )\n\n text_urls = models.TextField(\n _(\"Text URLs\"),\n blank=True,\n help_text=_(\n \"URLs to the text of the license (plain text or HTML) on the main site of \"\n \"this license.\"\n ),\n )\n\n faq_url = models.URLField(\n _(\"FAQ URL\"),\n max_length=1024,\n blank=True,\n help_text=_(\"URL of a page with Frequently Asked Questions about this license.\"),\n )\n\n osi_url = models.URLField(\n _(\"OSI URL\"),\n max_length=1024,\n blank=True,\n help_text=_(\"URL on the OSI website http://opensource.org for OSI-approved licenses.\"),\n )\n\n other_urls = models.TextField(\n _(\"Other URLs\"),\n blank=True,\n help_text=_(\n \"Other URLs that identify this license, such as URLs to this license in \"\n \"different open-source projects. Obsolete links may be kept here, as they \"\n \"may be useful for historical analysis purpose.\"\n ),\n )\n\n reviewed = models.BooleanField(\n default=False,\n help_text=_(\n \"True / False (yes/no) - regarding whether a system license definition has \"\n \"been reviewed by an administrator. Defaults to False.\"\n ),\n )\n\n publication_year = models.CharField(\n max_length=4,\n blank=True,\n help_text=_(\"Year this license was first published, in four-digits format.\"),\n )\n\n spdx_license_key = models.CharField(\n _(\"SPDX short identifier\"),\n db_index=True,\n blank=True,\n max_length=50,\n validators=[validate_spdx_license_key],\n help_text=_(\n \"Short identifier of the license as stated on each license detail page at \"\n \"https://spdx.org/licenses/ or a LicenseRef value that points to another \"\n \"license list.\"\n ),\n )\n\n category = models.ForeignKey(\n to=\"license_library.LicenseCategory\",\n null=True,\n blank=True,\n on_delete=models.PROTECT,\n help_text=_(\n \"A license category, identified by a code, provides a major grouping for \"\n \"licenses, generally describing the relationship between the licensor and \"\n \"licensee.\"\n ),\n )\n\n license_style = models.ForeignKey(\n to=\"license_library.LicenseStyle\",\n on_delete=models.PROTECT,\n null=True,\n blank=True,\n help_text=_(\n \"A license style identifies a group of miscellaneous characteristics about a \"\n \"license, which may include a combination of restrictions about software \"\n \"modification and usage\"\n ),\n )\n\n license_profile = models.ForeignKey(\n to=\"license_library.LicenseProfile\",\n on_delete=models.PROTECT,\n null=True,\n blank=True,\n verbose_name=_(\"License profile\"),\n help_text=format_lazy(\n \"{verbose_name}: a selection of license tags and their values, identified by a \"\n \"numeric code, in order to provide a convenient way to assign a set of tag values to \"\n \"a license. \"\n 'A \"Tag\" identifies a frequently encountered obligation, restriction, or other '\n \"notable characteristic of license terms. \"\n \"Note that individual tag value assignments may vary by license.\",\n verbose_name=_(\"License profile\"),\n ),\n )\n\n license_status = models.ForeignKey(\n to=\"license_library.LicenseStatus\",\n verbose_name=_(\"configuration status\"),\n on_delete=models.PROTECT,\n null=True,\n blank=True,\n help_text=_(\n \"An organization can use the license status to communicate the current stage \"\n \"of the license configuration review process.\"\n ),\n )\n\n is_active = models.BooleanField(\n verbose_name=_(\"Is active\"),\n null=True,\n db_index=True,\n help_text=_(\n \"When set to True (Yes), this field indicates that a license definition in the \"\n \"library is currently in use (active). When set to False (No), this field indicates \"\n \"that a license is deprecated (inactive) and should not be used, and the license \"\n \"will not appear in the user views. When the field value is Unknown, the license \"\n \"will not appear in the user views, usually suggesting that the license has not \"\n \"yet been evaluated.\"\n ),\n )\n\n curation_level = models.PositiveSmallIntegerField(\n db_index=True,\n default=0,\n validators=[validators.MaxValueValidator(100)],\n help_text=_(\n \"A numeric value, from 0 to 100, that indicates the level of completeness of all the \"\n \"pertinent license data, as well as the state of that data being reviewed by a senior \"\n 'administrator. General Guidelines: \"10\" indicates basic data present. \"20\" indicates '\n 'Category and License Style assigned. \"30\" indicates all Obligation Tags are set. '\n '\"40\" indicates all License Tags are set. \"50\" indicates all previous conditions '\n \"plus URL fields set. Anything above that is at the discretion of a senior \"\n \"administrative reviewer.\"\n ),\n )\n\n admin_notes = models.TextField(\n blank=True,\n help_text=_(\n \"Internal notes for administrative use only, primarily intended to \"\n \"communicate special considerations about the interpretation of a license.\"\n ),\n )\n\n guidance = models.TextField(\n blank=True,\n help_text=format_lazy(\n \"Guidance notes maintained by an administrator to be communicated to the users who \"\n \"view the {license_app}, primarily intended to provide cautionary and/or policy \"\n \"information.\",\n license_app=_(\"License Library\"),\n ),\n )\n\n special_obligations = models.TextField(\n blank=True,\n help_text=format_lazy(\n \"A concise description, maintained by an administrator, of the obligations \"\n \"(or restrictions) mandated by the license which are not communicated by the \"\n \"standard tag assignments of {license_profile} associated with this License.\",\n license_profile=_(\"License profile\"),\n ),\n )\n\n tags = models.ManyToManyField(\n to=\"license_library.LicenseTag\",\n through=\"LicenseAssignedTag\",\n )\n\n is_component_license = models.BooleanField(\n default=False,\n db_index=True,\n help_text=_(\n \"When set to Yes, indicates that this license is assigned by a \"\n \"component-creator to one or more versions of a component, and is not \"\n \"generally used by other components.\"\n ),\n )\n\n is_exception = models.BooleanField(\n default=False,\n db_index=True,\n help_text=_(\n \"When set to Yes, indicates that this license is actually an \"\n \"exception applied to another license in order to modify \"\n \"specific conditions of that other license.\"\n ),\n )\n\n guidance_url = models.CharField(\n _(\"Guidance URL\"),\n max_length=1024,\n blank=True,\n help_text=_(\n \"A URL to a page that documents your organization's policies and procedures \"\n \"that relate to the obligations and restrictions associated with this \"\n \"license or with similar licenses.\"\n ),\n )\n\n popularity = models.PositiveSmallIntegerField(\n db_index=True,\n default=0,\n help_text=_(\n \"A numeric value assigned to a license and maintained by a DejaCode \"\n \"administrator, that indicates the relative popularity of a license as used by \"\n \"public software projects. The value influences the default license ordering \"\n \"of the User License List, as well as the ordering of the suggested licenses \"\n \"presented as a dropdown list when you enter text in a DejaCode license \"\n \"expression field. Popularity values are originally provided in DejaCode \"\n \"Reference Data, but your administrator has the option to modify them for your \"\n \"dataspace.\"\n ),\n )\n\n language = models.CharField(\n max_length=10,\n choices=license_library_app.languages,\n blank=True,\n help_text=_(\"The language for this license, stored in standard language ID format.\"),\n )\n\n objects = DataspacedManager.from_queryset(LicenseQuerySet)()\n\n class Meta:\n # This is a special case for the unique_together, ie several entries\n # It's important that's the first entry is 'key' in this case as it is\n # used to Match a License inside a dataspace\n unique_together = (\n (\"dataspace\", \"key\"),\n (\"dataspace\", \"name\"),\n (\"dataspace\", \"short_name\"),\n (\"dataspace\", \"uuid\"),\n )\n ordering = [\"-popularity\", \"name\"]\n permissions = (\n (\"change_usage_policy_on_license\", \"Can change the usage_policy of license\"),\n )\n\n def __str__(self):\n return f\"{self.short_name} ({self.key})\"\n\n def clean(self, from_api=False):\n if self.is_active is False and self.spdx_license_key:\n raise ValidationError(\"A deprecated license must not have an SPDX license key.\")\n super().clean(from_api)\n\n def _get_unique_checks(self, exclude=None):\n \"\"\"\n Ensure SPDX license key are unique within a Dataspace.\n This is a soft-constraint, ie not enforced at the database level.\n The check on `spdx_license_key` is not included if the value is blank.\n \"\"\"\n unique_checks, date_checks = super()._get_unique_checks(exclude)\n\n if self.spdx_license_key:\n unique_together = (\"dataspace\", \"spdx_license_key\")\n unique_checks.append((self.__class__, unique_together))\n\n return unique_checks, date_checks\n\n @property\n def urn(self):\n return urn.build(\"license\", key=self.key)\n\n def get_url(self, name, params=None):\n if not params:\n params = [self.dataspace.name, self.key]\n return super().get_url(name, params)\n\n def get_absolute_url(self):\n return self.get_url(\"details\")\n\n @property\n def details_url(self):\n return self.get_absolute_url()\n\n def get_delete_url(self):\n return self.get_url(\"delete\")\n\n def get_download_text_url(self):\n return self.get_url(\"download_text\")\n\n def get_details_url_for_expression(self):\n return self.get_absolute_link(field_name=\"key\", title=self.short_name)\n\n @property\n def permission_protected_fields(self):\n return {\"usage_policy\": \"change_usage_policy_on_license\"}\n\n @property\n def case_insensitive_unique_on(self):\n return [\"name\", \"short_name\", \"key\"]\n\n def where_used(self, user):\n \"\"\"Callable for the reporting system.\"\"\"\n return (\n f\"Product {self.product_set.get_related_secured_queryset(user).count()}\\n\"\n f\"Component {self.component_set.count()}\\n\"\n f\"Subcomponent {self.subcomponent_set.count()}\\n\"\n f\"Package {self.package_set.count()}\\n\"\n f\"ProductComponent {self.productcomponent_set.count()}\\n\"\n f\"ProductPackage {self.productpackage_set.count()}\"\n )\n\n def get_license_tab_displayed_tags(self):\n \"\"\"\n Return a list of the assigned tags for the given License limiting\n the tags where the value is set to True.\n Tags that are not in a LicenseTagGroup are not included.\n\n Use `LicenseAssignedTag.prefetch_for_license_tab()` in prefect_related of the QuerySet.\n \"\"\"\n assigned_tag_qs = self.licenseassignedtag_set.filter(\n license_tag__licensetaggroupassignedtag__isnull=False\n ).order_by(\"license_tag__licensetaggroupassignedtag\")\n\n return [\n (assigned_tag.license_tag.label, assigned_tag.value, assigned_tag.license_tag.text)\n for assigned_tag in assigned_tag_qs\n # equivalent to \"filter(value=True)\" without triggering another Query\n if assigned_tag.value\n ]\n\n def get_tagset(self, include_unknown=False, include_no_group=False):\n \"\"\"\n Return a tagset for the given License.\n A \"tagset\" is a the collection of all the LicenseTags assigned to a\n License grouped by LicenseTagGroup and ordered by the Sequence.\n Groups are ordered by their sequence and tags are also ordered by\n their sequence inside a Group.\n LicenseAssignedTag with \"Unknown\" value can be included using the\n include_unknown parameter.\n Tag not assigned in a LicenseTagGroup can be included using the\n include_no_group parameter, an extra Group \"(No Group)\" will be added.\n \"tagset\" format is:\n OrderedDict(\n [('GroupName', [\n ('TagName', 'AssignedTagValue', 'TagText', Annotations),]\n )]\n )\n \"\"\"\n filters = {\"license\": self}\n if not include_unknown:\n filters[\"value__isnull\"] = False\n\n license_assigned_tags = (\n LicenseAssignedTag.objects.scope(self.dataspace)\n .filter(**filters)\n .select_related(\"license_tag\")\n .prefetch_related(\"licenseannotation_set\")\n )\n\n # Building a dictionary with the assigned tags of the current License\n license_tags_dict = {\n t.license_tag.label: (t.value, t.license_tag.text, t.licenseannotation_set.all())\n for t in license_assigned_tags\n }\n\n # Creating a 'tabset' dictionary ordered by Group and Tag sequence\n ordered_assigned_tags = (\n LicenseTagGroupAssignedTag.objects.scope(self.dataspace)\n .order_by(\"license_tag_group__seq\", \"seq\")\n .select_related(\"license_tag_group\", \"license_tag\")\n )\n\n # Using an OrderedDict to keep the QS ordering as we build the results\n license_tagset = OrderedDict()\n for assigned_tag in ordered_assigned_tags:\n label = assigned_tag.license_tag.label\n if label in license_tags_dict:\n # Using pop() to remove the entry from the dict, so we keep a\n # list of tags that are not assigned into a LicenseTagGroup\n value, text, annotations = license_tags_dict.pop(label)\n group_name = assigned_tag.license_tag_group.name\n license_tagset.setdefault(group_name, []).append([label, value, text, annotations])\n\n # If there is still entries in license_tags_dict, that mean those tags\n # are not assigned into a LicenseTagGroup, we are adding those in the\n # result if the include_no_group is True\n if include_no_group and license_tags_dict:\n leftover_tags = [[label] + list(values) for label, values in license_tags_dict.items()]\n license_tagset.update({\"(No Group)\": leftover_tags})\n\n return license_tagset\n\n def get_tag_labels(self):\n \"\"\"Return the labels of all the tags associated with this license.\"\"\"\n return self.tags.values_list(\"label\", flat=True)\n\n def get_tag_value_from_label(self, label):\n try:\n assigned_tag = LicenseAssignedTag.objects.get(license=self, license_tag__label=label)\n except (ObjectDoesNotExist, MultipleObjectsReturned):\n return \"\" # Empty string rather than Error when no value available\n return str(assigned_tag.value)\n\n def set_assigned_tags_from_license_profile(self):\n \"\"\"Update or create missing LicenseAssignedTag from the license_profile.\"\"\"\n if not self.license_profile:\n return\n\n for profile_assigned_tag in self.license_profile.licenseprofileassignedtag_set.all():\n LicenseAssignedTag.objects.update_or_create(\n license=self,\n license_tag=profile_assigned_tag.license_tag,\n dataspace=self.dataspace,\n defaults={\"value\": profile_assigned_tag.value},\n )\n\n @staticmethod\n def get_extra_relational_fields():\n return [\"annotations\", \"external_references\"]\n\n @property\n def scancode_url(self):\n return SCANCODE_LICENSE_URL.format(self.key)\n\n @property\n def licensedb_url(self):\n return SCANCODE_LICENSEDB_URL.format(self.key)\n\n @property\n def spdx_url(self):\n \"\"\"\n Return a URL to the https://spdx.org/licenses/ list using the short identifier.\n Return None for SPDX license key starting with \"LicenseRef-\" as those are not\n available in the SPDX list.\n \"\"\"\n if self.spdx_license_key and not self.spdx_license_key.startswith(\"LicenseRef-\"):\n return SPDX_LICENSE_URL.format(self.spdx_license_key)\n\n @property\n def spdx_link(self):\n \"\"\"\n Return a link base on the `spdx_url` value.\n Return the `spdx_license_key` when the URL is not available.\n \"\"\"\n spdx_url = self.spdx_url\n if spdx_url:\n return self.get_html_link(self.spdx_url, value=self.spdx_license_key, target=\"_blank\")\n return self.spdx_license_key\n\n @property\n def spdx_id(self):\n \"\"\"\n Return the `spdx_license_key` when available or a crafted LicenseRef using\n the license key.\n \"\"\"\n return self.spdx_license_key or f\"LicenseRef-dejacode-{self.key}\"\n\n def as_spdx(self):\n \"\"\"Return this License as an SPDX ExtractedLicensingInfo entry.\"\"\"\n return spdx.ExtractedLicensingInfo(\n license_id=self.spdx_id,\n extracted_text=self.full_text,\n name=self.name,\n see_alsos=self.get_all_urls(),\n )\n\n def get_all_urls(self):\n \"\"\"Return all URLs set in URL-based fields of this License instance.\"\"\"\n url_fields = [\n \"licensedb_url\",\n \"scancode_url\",\n \"homepage_url\",\n \"osi_url\",\n \"faq_url\",\n \"text_urls\",\n \"other_urls\",\n ]\n\n urls = []\n for url_field in url_fields:\n url_value = getattr(self, url_field)\n if url_value:\n urls.extend([url for url in url_value.split() if url])\n\n return sorted(set(urls))\n\n def has_tag_field_enabled(self, tag_field):\n # Make sure to include the following prefetch on the QuerySet:\n # prefetch_related('licenseassignedtag_set__license_tag')\n for assigned_tag in self.licenseassignedtag_set.all():\n if getattr(assigned_tag.license_tag, tag_field) and assigned_tag.value:\n return True\n return False\n\n @property\n def attribution_required(self):\n return self.has_tag_field_enabled(\"attribution_required\")\n\n @property\n def redistribution_required(self):\n return self.has_tag_field_enabled(\"redistribution_required\")\n\n @property\n def change_tracking_required(self):\n return self.has_tag_field_enabled(\"change_tracking_required\")\n\n @property\n def language_code(self):\n return self.language" }, { "identifier": "LicenseChoice", "path": "license_library/models.py", "snippet": "class LicenseChoice(DataspacedModel):\n \"\"\"\n Each choice is applied once rather than recursively,\n to prevent risk of infinite loop.\n\n - Or later type licenses:\n gps-2.0-plus -> gps-2.0 OR gps-2.0-plus OR gps-3.0 OR gps-3.0-plus\n\n - Dual licenses:\n (seq:0) dual-bsd-gpl -> bsd-new OR gps-2.0\n (seq:1) bsd-new OR gps-2.0 -> bsd-new\n\n - Unknown gpl version in license text:\n (seq:0) brian-gladman-dual -> bsd-new OR gps-1.0-plus\n (seq:1) bsd-new OR gps-1.0-plus -> bsd-new\n \"\"\"\n\n from_expression = models.CharField(\n max_length=1024,\n help_text=_(\"A license key or license expression snippet.\"),\n )\n\n to_expression = models.CharField(\n max_length=1024,\n help_text=_(\"A license key or license expression snippet.\"),\n )\n\n seq = models.PositiveSmallIntegerField(\n default=0,\n db_index=True,\n help_text=_(\n \"Use the sequence value to indicate your license choice preference policies for a \"\n \"particular license expression, using zero (0) as the first and preferred choice, \"\n \"followed by other sequences that define acceptable choices.\"\n ),\n )\n\n notes = models.TextField(\n blank=True,\n help_text=_(\"Notes.\"),\n )\n\n objects = LicenseChoiceManager()\n\n class Meta:\n unique_together = (\"dataspace\", \"uuid\")\n ordering = [\"seq\"]\n\n def __str__(self):\n return f\"{self.from_expression} -> {self.to_expression}\"" }, { "identifier": "SetPolicyFromLicenseMixin", "path": "policy/models.py", "snippet": "class SetPolicyFromLicenseMixin:\n def save(self, *args, **kwargs):\n \"\"\"\n Set a usage policy to Components/Packages based on its license expression,\n when the flag is enabled on the dataspace and no usage_policy is provided.\n Located in save() so this behavior is shared for import, copy, API, and forms.\n \"\"\"\n set_usage_policy = all(\n [\n not self.usage_policy,\n self.license_expression,\n self.dataspace.set_usage_policy_on_new_component_from_licenses,\n ]\n )\n\n if set_usage_policy:\n self.usage_policy = self.policy_from_primary_license\n\n super().save(*args, **kwargs)" }, { "identifier": "UsagePolicyMixin", "path": "policy/models.py", "snippet": "class UsagePolicyMixin(models.Model):\n \"\"\"Abstract Model Mixin to include the field and API for usage policy.\"\"\"\n\n usage_policy = models.ForeignKey(\n to=\"policy.UsagePolicy\",\n null=True,\n blank=True,\n on_delete=models.PROTECT,\n help_text=_(\n \"An administrator can communicate company policy for an \"\n \"entry by setting the Usage Policy indicator.\"\n ),\n )\n\n class Meta:\n abstract = True\n\n def get_usage_policy_as_icon(self):\n if self.usage_policy:\n return self.usage_policy.get_icon_as_html()\n\n def get_usage_policy_display_with_icon(self):\n if self.usage_policy:\n return format_html(\n '{}<span class=\"ms-1\">{}</span>',\n self.get_usage_policy_as_icon(),\n self.usage_policy.label,\n )\n\n def get_usage_policy_color(self):\n return self.usage_policy.get_color_code()\n\n def get_usage_policy_icon_tooltip(self):\n return format_html(\n '<span class=\"cursor-help policy-icon\" data-bs-toggle=\"tooltip\" title=\"{}\">{}</span>',\n self.usage_policy,\n self.usage_policy.get_icon_as_html(),\n )\n\n def get_policy_from_primary_license(self):\n \"\"\"Return the UsagePolicy associated to this Component/Package primary_license.\"\"\"\n License = apps.get_model(\"license_library\", \"license\")\n\n try:\n license_instance = License.objects.get(\n key=self.primary_license,\n dataspace=self.dataspace,\n )\n except models.ObjectDoesNotExist:\n return\n\n if license_instance.usage_policy:\n return license_instance.usage_policy.get_associated_policy_to_model(self)\n\n policy_from_primary_license = cached_property(get_policy_from_primary_license)" }, { "identifier": "RequestMixin", "path": "workflow/models.py", "snippet": "class RequestMixin(models.Model):\n \"\"\"Provide fields and methods for Request related models.\"\"\"\n\n request_count = models.PositiveSmallIntegerField(\n blank=True,\n null=True,\n )\n\n class Meta:\n abstract = True\n\n def get_requests(self, user):\n \"\"\"\n We could use django.contrib.contenttypes.fields.GenericRelation\n instead but we don't want to avoid the cascade-deletion behavior.\n\n Private requests are included in the QuerySet but their content is not displayed.\n \"\"\"\n return Request.objects.for_activity_tab(self, user)\n\n def count_requests(self):\n \"\"\"\n Return the count of Request objects attached to this instance.\n Bypass the Product secured system since we need the proper count but do\n not have a user to provide.\n \"\"\"\n return Request.objects.for_content_object(self).count()\n\n def update_request_count(self):\n \"\"\"\n Update the `request_count` field on the instance.\n Using update() rather than save() to avoid noise in the history.\n The update is only applied if the current stored count is not the true\n database count.\n Return True if the request_count was updated.\n \"\"\"\n model_class = self.__class__\n # We should have default=0 on the `request_count` field instead\n strored_count = self.request_count or 0\n true_count = self.count_requests()\n\n if strored_count != true_count:\n # Use the unsecured_manager to bypass the security system and get the proper count\n get_unsecured_manager(model_class).filter(pk=self.pk).update(request_count=true_count)\n msg = f\"Updated <{model_class.__name__} id={self.pk}>.request_count={true_count}\"\n logger.debug(msg)\n return True" } ]
import logging import re from contextlib import suppress from urllib.parse import quote_plus from django.contrib.postgres.fields import ArrayField from django.core import validators from django.core.exceptions import MultipleObjectsReturned from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ValidationError from django.core.validators import EMPTY_VALUES from django.db import models from django.db.models import CharField from django.db.models import Exists from django.db.models import OuterRef from django.db.models.functions import Concat from django.dispatch import receiver from django.template.defaultfilters import filesizeformat from django.utils.functional import cached_property from django.utils.html import format_html from django.utils.text import format_lazy from django.utils.text import get_valid_filename from django.utils.text import normalize_newlines from django.utils.translation import gettext_lazy as _ from attributecode.model import About from cyclonedx import model as cyclonedx_model from cyclonedx.model import component as cyclonedx_component from packageurl import PackageURL from packageurl.contrib import purl2url from packageurl.contrib import url2purl from packageurl.contrib.django.models import PackageURLMixin from packageurl.contrib.django.models import PackageURLQuerySetMixin from packageurl.contrib.django.utils import without_empty_values from component_catalog.license_expression_dje import build_licensing from component_catalog.license_expression_dje import get_license_objects from component_catalog.license_expression_dje import parse_expression from dejacode_toolkit import spdx from dejacode_toolkit.download import DataCollectionException from dejacode_toolkit.download import collect_package_data from dejacode_toolkit.purldb import PurlDB from dje import urn from dje.copier import post_copy from dje.copier import post_update from dje.fields import JSONListField from dje.fields import NoStripTextField from dje.models import DataspacedManager from dje.models import DataspacedModel from dje.models import DataspacedQuerySet from dje.models import ExternalReferenceMixin from dje.models import History from dje.models import HistoryFieldsMixin from dje.models import ParentChildModelMixin from dje.models import ParentChildRelationshipModel from dje.models import ReferenceNotesMixin from dje.tasks import tasks_logger from dje.utils import set_fields_from_object from dje.validators import generic_uri_validator from dje.validators import validate_url_segment from dje.validators import validate_version from license_library.models import License from license_library.models import LicenseChoice from policy.models import SetPolicyFromLicenseMixin from policy.models import UsagePolicyMixin from workflow.models import RequestMixin
18,940
self.license_expression, licenses=self.licensing, validate_known=False, validate_strict=False, ) normalized_expression = cached_property(_get_normalized_expression) def get_license_expression(self, template="{symbol.key}", as_link=False, show_policy=False): """ Validate and Return the license_expression value set on this instance. The license expression is NOT validated for known symbols. Use the `template` format string to render each license in the expression. if `as_link` is True, render the expression as a link. """ if self.license_expression: rendered = self.normalized_expression.render_as_readable( template, as_link=as_link, show_policy=show_policy, ) return format_html(rendered) def get_license_expression_attribution(self): # note: the fields use in the template must be available as attributes or # properties on a License. template = '<a href="#license_{symbol.key}">{symbol.short_name}</a>' return self.get_license_expression(template) license_expression_attribution = cached_property(get_license_expression_attribution) def get_license_expression_linked(self): return self.get_license_expression(as_link=True) license_expression_linked = cached_property(get_license_expression_linked) def get_license_expression_linked_with_policy(self): license_expression = self.get_license_expression(as_link=True, show_policy=True) if license_expression: return format_html('<span class="license-expression">{}</span>', license_expression) def get_license_expression_spdx_id(self): """ Return the license_expression formatted for SPDX compatibility. This includes a workaround for a SPDX spec limitation, where license exceptions that do not exist in the SPDX list cannot be provided as "LicenseRef-" in the "hasExtractedLicensingInfos". The current fix is to use AND rather than WITH for any exception that is a "LicenseRef-". See discussion at https://github.com/spdx/tools-java/issues/73 """ expression = self.get_license_expression("{symbol.spdx_id}") if expression: return expression.replace("WITH LicenseRef-", "AND LicenseRef-") def _get_primary_license(self): """ Return the primary license key of this instance or None. The primary license is the left most license of the expression. It can be the combination of a license WITH an exception and therefore may contain more than one key. WARNING: This does not support exception as primary_license. """ if self.license_expression: licensing = build_licensing() return licensing.primary_license_key(self.license_expression) primary_license = cached_property(_get_primary_license) def save(self, *args, **kwargs): """ Call the handle_assigned_licenses method on save, except during copy. During copy, as some Licenses referenced by the license_expression may not exists in the target Dataspace yet, the handle_assigned_licenses() would not be able to create the proper assignments and the UUID of those assignments would not be shared with reference Dataspace. Thus, the handle_assigned_licenses() is skipped during the copy process and the License assignments are handled by the m2m copy. """ super().save(*args, **kwargs) self.handle_assigned_licenses(copy=kwargs.get("copy")) def handle_assigned_licenses(self, copy=False): """ Create missing AssignedLicense instances and deletes the ones non-referenced in the license_expression. In `copy` mode, all the license assignments are deleted to avoid any conflicts during the copy/update process where all the assignments are properly created. """ licenses_field = self._meta.get_field("licenses") AssignedLicense = licenses_field.remote_field.through # Looking for the FK field name, on the AssignedLicense, that points to this Model fk_field_name = [ field for field in AssignedLicense._meta.get_fields() if field.many_to_one and field.concrete and field.related_model == self.__class__ ] if len(fk_field_name) != 1: return fk_field_name = fk_field_name[0].name assigned_license_qs = AssignedLicense.objects.filter( **{"dataspace": self.dataspace, fk_field_name: self} ) if copy: # Deletes all existing license assignments to ensure UUID integrity # as the licenses will be properly assigned during the copy/update process assigned_license_qs.delete() return # Get the full list of licenses is required here for proper # validation. We cannot rely on the assigned licenses since we # are modifying those assignments. all_licenses = License.objects.scope(self.dataspace).for_expression()
# # Copyright (c) nexB Inc. and others. All rights reserved. # DejaCode is a trademark of nexB Inc. # SPDX-License-Identifier: AGPL-3.0-only # See https://github.com/nexB/dejacode for support or download. # See https://aboutcode.org for more information about AboutCode FOSS projects. # logger = logging.getLogger("dje") COMPONENT_PACKAGE_COMMON_FIELDS = [ "copyright", "dependencies", "description", "holder", "homepage_url", "license_expression", "name", "notice_text", "primary_language", "release_date", "version", ] def validate_filename(value): invalid_chars = ["/", "\\", ":"] if any(char in value for char in invalid_chars): raise ValidationError( _("Enter a valid filename: slash, backslash, or colon are not allowed.") ) class LicenseExpressionMixin: """Model mixin for models that store license expressions.""" def _get_licensing(self): """Return a Licensing object built from the assigned licenses.""" # WARNING: Do not apply select/prefect_related here but on the main QuerySet instead # For example: prefetch_related('component_set__licenses__dataspace') return build_licensing(self.licenses.all()) licensing = cached_property(_get_licensing) def _get_normalized_expression(self): """ Return this object ``license_expression`` field value as a normalized parsed expression object. """ if self.license_expression: return parse_expression( self.license_expression, licenses=self.licensing, validate_known=False, validate_strict=False, ) normalized_expression = cached_property(_get_normalized_expression) def get_license_expression(self, template="{symbol.key}", as_link=False, show_policy=False): """ Validate and Return the license_expression value set on this instance. The license expression is NOT validated for known symbols. Use the `template` format string to render each license in the expression. if `as_link` is True, render the expression as a link. """ if self.license_expression: rendered = self.normalized_expression.render_as_readable( template, as_link=as_link, show_policy=show_policy, ) return format_html(rendered) def get_license_expression_attribution(self): # note: the fields use in the template must be available as attributes or # properties on a License. template = '<a href="#license_{symbol.key}">{symbol.short_name}</a>' return self.get_license_expression(template) license_expression_attribution = cached_property(get_license_expression_attribution) def get_license_expression_linked(self): return self.get_license_expression(as_link=True) license_expression_linked = cached_property(get_license_expression_linked) def get_license_expression_linked_with_policy(self): license_expression = self.get_license_expression(as_link=True, show_policy=True) if license_expression: return format_html('<span class="license-expression">{}</span>', license_expression) def get_license_expression_spdx_id(self): """ Return the license_expression formatted for SPDX compatibility. This includes a workaround for a SPDX spec limitation, where license exceptions that do not exist in the SPDX list cannot be provided as "LicenseRef-" in the "hasExtractedLicensingInfos". The current fix is to use AND rather than WITH for any exception that is a "LicenseRef-". See discussion at https://github.com/spdx/tools-java/issues/73 """ expression = self.get_license_expression("{symbol.spdx_id}") if expression: return expression.replace("WITH LicenseRef-", "AND LicenseRef-") def _get_primary_license(self): """ Return the primary license key of this instance or None. The primary license is the left most license of the expression. It can be the combination of a license WITH an exception and therefore may contain more than one key. WARNING: This does not support exception as primary_license. """ if self.license_expression: licensing = build_licensing() return licensing.primary_license_key(self.license_expression) primary_license = cached_property(_get_primary_license) def save(self, *args, **kwargs): """ Call the handle_assigned_licenses method on save, except during copy. During copy, as some Licenses referenced by the license_expression may not exists in the target Dataspace yet, the handle_assigned_licenses() would not be able to create the proper assignments and the UUID of those assignments would not be shared with reference Dataspace. Thus, the handle_assigned_licenses() is skipped during the copy process and the License assignments are handled by the m2m copy. """ super().save(*args, **kwargs) self.handle_assigned_licenses(copy=kwargs.get("copy")) def handle_assigned_licenses(self, copy=False): """ Create missing AssignedLicense instances and deletes the ones non-referenced in the license_expression. In `copy` mode, all the license assignments are deleted to avoid any conflicts during the copy/update process where all the assignments are properly created. """ licenses_field = self._meta.get_field("licenses") AssignedLicense = licenses_field.remote_field.through # Looking for the FK field name, on the AssignedLicense, that points to this Model fk_field_name = [ field for field in AssignedLicense._meta.get_fields() if field.many_to_one and field.concrete and field.related_model == self.__class__ ] if len(fk_field_name) != 1: return fk_field_name = fk_field_name[0].name assigned_license_qs = AssignedLicense.objects.filter( **{"dataspace": self.dataspace, fk_field_name: self} ) if copy: # Deletes all existing license assignments to ensure UUID integrity # as the licenses will be properly assigned during the copy/update process assigned_license_qs.delete() return # Get the full list of licenses is required here for proper # validation. We cannot rely on the assigned licenses since we # are modifying those assignments. all_licenses = License.objects.scope(self.dataspace).for_expression()
licenses = get_license_objects(self.license_expression, all_licenses)
1
2023-12-07 16:57:42+00:00
24k
wusize/CLIM
src/open_clip/model.py
[ { "identifier": "HFTextEncoder", "path": "src/open_clip/hf_model.py", "snippet": "class HFTextEncoder(nn.Module):\n \"\"\"HuggingFace model adapter\"\"\"\n output_tokens: torch.jit.Final[bool]\n\n def __init__(\n self,\n model_name_or_path: str,\n output_dim: int,\n config: PretrainedConfig = None,\n pooler_type: str = None,\n proj: str = None,\n pretrained: bool = True,\n output_tokens: bool = False,\n ):\n super().__init__()\n self.output_tokens = output_tokens\n self.output_dim = output_dim\n\n # TODO: find better way to get this information\n uses_transformer_pooler = (pooler_type == \"cls_pooler\")\n\n if transformers is None:\n raise RuntimeError(\"Please `pip install transformers` to use pre-trained HuggingFace models\")\n if config is None:\n self.config = AutoConfig.from_pretrained(model_name_or_path)\n create_func, model_args = (AutoModel.from_pretrained, model_name_or_path) if pretrained else (\n AutoModel.from_config, self.config)\n # TODO: do all model configs have this attribute? PretrainedConfig does so yes??\n if hasattr(self.config, \"is_encoder_decoder\") and self.config.is_encoder_decoder:\n self.transformer = create_func(model_args)\n self.transformer = self.transformer.encoder\n else:\n self.transformer = create_func(model_args, add_pooling_layer=uses_transformer_pooler)\n else:\n self.config = config\n self.transformer = AutoModel.from_config(config)\n if pooler_type is None: # get default arch pooler\n pooler_type = (arch_dict[self.config.model_type][\"pooler\"])\n \n self.pooler = _POOLERS[pooler_type]()\n\n d_model = getattr(self.config, arch_dict[self.config.model_type][\"config_names\"][\"width\"])\n if (d_model == output_dim) and (proj is None): # do we always need a proj?\n self.proj = nn.Identity()\n elif proj == 'linear':\n self.proj = nn.Linear(d_model, output_dim, bias=False)\n elif proj == 'mlp':\n hidden_size = (d_model + output_dim) // 2\n self.proj = nn.Sequential(\n nn.Linear(d_model, hidden_size, bias=False),\n nn.GELU(),\n nn.Linear(hidden_size, output_dim, bias=False),\n )\n\n def forward(self, x: TensorType):\n attn_mask = (x != self.config.pad_token_id).long()\n out = self.transformer(input_ids=x, attention_mask=attn_mask)\n pooled_out = self.pooler(out, attn_mask)\n projected = self.proj(pooled_out)\n\n seq_len = out.last_hidden_state.shape[1]\n tokens = (\n out.last_hidden_state[:, torch.arange(seq_len) != self.pooler.cls_token_position, :] \n if type(self.pooler) == ClsPooler \n else out.last_hidden_state\n )\n \n if self.output_tokens:\n return projected, tokens\n return projected\n\n def lock(self, unlocked_layers: int = 0, freeze_layer_norm: bool = True):\n if not unlocked_layers: # full freezing\n for n, p in self.transformer.named_parameters():\n p.requires_grad = (not freeze_layer_norm) if \"LayerNorm\" in n.split(\".\") else False\n return\n\n encoder = self.transformer.encoder if hasattr(self.transformer, 'encoder') else self.transformer\n layer_list = getattr(encoder, arch_dict[self.config.model_type][\"config_names\"][\"layer_attr\"])\n print(f\"Unlocking {unlocked_layers}/{len(layer_list) + 1} layers of hf model\")\n embeddings = getattr(\n self.transformer, arch_dict[self.config.model_type][\"config_names\"][\"token_embeddings_attr\"])\n modules = [embeddings, *layer_list][:-unlocked_layers]\n # freeze layers\n for module in modules:\n for n, p in module.named_parameters():\n p.requires_grad = (not freeze_layer_norm) if \"LayerNorm\" in n.split(\".\") else False\n\n @torch.jit.ignore\n def set_grad_checkpointing(self, enable=True):\n self.transformer.gradient_checkpointing_enable()\n\n def init_parameters(self):\n pass" }, { "identifier": "ModifiedResNet", "path": "src/open_clip/modified_resnet.py", "snippet": "class ModifiedResNet(nn.Module):\n \"\"\"\n A ResNet class that is similar to torchvision's but contains the following changes:\n - There are now 3 \"stem\" convolutions as opposed to 1, with an average pool instead of a max pool.\n - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1\n - The final pooling layer is a QKV attention instead of an average pool\n \"\"\"\n\n def __init__(self, layers, output_dim, heads, image_size=224, width=64,\n freeze_output=True,\n freeze_all_bns=True):\n super().__init__()\n self.output_dim = output_dim\n self.image_size = image_size\n self.freeze_output = freeze_output\n self.freeze_all_bns = freeze_all_bns\n # the 3-layer stem\n self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(width // 2)\n self.act1 = nn.ReLU(inplace=True)\n self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(width // 2)\n self.act2 = nn.ReLU(inplace=True)\n self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)\n self.bn3 = nn.BatchNorm2d(width)\n self.act3 = nn.ReLU(inplace=True)\n self.avgpool = nn.AvgPool2d(2)\n\n # residual layers\n self._inplanes = width # this is a *mutable* variable used during construction\n self.layer1 = self._make_layer(width, layers[0])\n self.layer2 = self._make_layer(width * 2, layers[1], stride=2)\n self.layer3 = self._make_layer(width * 4, layers[2], stride=2)\n self.layer4 = self._make_layer(width * 8, layers[3], stride=2)\n\n embed_dim = width * 32 # the ResNet feature dimension\n self.attnpool = AttentionPool2d(image_size // 32, embed_dim, heads, output_dim, freeze_output)\n self.attnpool_input_size = image_size // 32\n\n def _make_layer(self, planes, blocks, stride=1):\n layers = [Bottleneck(self._inplanes, planes, stride)]\n\n self._inplanes = planes * Bottleneck.expansion\n for _ in range(1, blocks):\n layers.append(Bottleneck(self._inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def lock(self, unlocked_groups=0, freeze_bn_stats=True):\n assert freeze_bn_stats\n def _lock(module):\n for param in module.parameters():\n param.requires_grad = False\n if freeze_bn_stats:\n freeze_batch_norm_2d(module)\n module.eval()\n\n freeze_at = 5 - unlocked_groups\n print(f'Freeze the resnet at {freeze_at}', flush=True)\n\n if freeze_at >= 1: # stem\n _lock(self.conv1)\n _lock(self.bn1)\n _lock(self.conv2)\n _lock(self.bn2)\n _lock(self.conv3)\n _lock(self.bn3)\n # each stage is a torch.nn.modules.container.Sequential\n for idx, stage in enumerate([self.layer1, self.layer2, self.layer3, self.layer4], start=2):\n if freeze_at >= idx:\n for block in stage.children(): # each block is a Bottleneck\n _lock(block)\n if self.freeze_all_bns:\n print(f'Freeze all bn layers', flush=True) # TODO: study if this is necessary\n freeze_batch_norm_2d(self)\n\n @torch.jit.ignore\n def set_grad_checkpointing(self, enable=True):\n # FIXME support for non-transformer\n pass\n\n def stem(self, x):\n x = self.act1(self.bn1(self.conv1(x)))\n x = self.act2(self.bn2(self.conv2(x)))\n x = self.act3(self.bn3(self.conv3(x)))\n x = self.avgpool(x)\n return x\n\n def forward(self, x):\n with torch.no_grad():\n x = self.stem(x)\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n x = self.attnpool(x)\n\n return x\n\n @staticmethod\n def _denormalize_boxes(normed_boxes, x):\n h, w = x.shape[-2:]\n denormed_boxes = []\n for boxes in normed_boxes:\n new_boxes = boxes.clone() # FIXME: do not change the value in normed_boxes!\n new_boxes[:, [0, 2]] *= w\n new_boxes[:, [1, 3]] *= h\n denormed_boxes.append(new_boxes)\n return denormed_boxes\n\n def extract_roi_features(self, x, normed_boxes, extract_type='v2'):\n if extract_type == 'v1':\n return self._extract_roi_features_v1(x, normed_boxes)\n else:\n assert extract_type == 'v2'\n return self._extract_roi_features_v2(x, normed_boxes)\n\n def mask_attn_pool(self, image, masks):\n return self.mask_pool(image, masks)\n\n def mask_pool(self, image, masks):\n x = self.stem(image)\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n feature_map = self.attnpool.forward_dense(x)\n feature_map = F.normalize(feature_map, dim=1) # remember to normalize!\n\n feature_map = feature_map.flatten(-2, -1) # bs, c, h*w\n num_masks_per_image = [len(masks_per_image) for masks_per_image in masks]\n masks = torch.cat(masks).float().flatten(-2, -1) # bs, h*w\n feature_map = torch.repeat_interleave(\n feature_map, torch.tensor(num_masks_per_image, device=feature_map.device), dim=0)\n features = (feature_map * masks[:, None]).sum(-1) / (masks.sum(1, keepdim=True) + 1e-12)\n\n return features\n\n def _extract_roi_features_v1(self, x, normed_boxes, **kwargs):\n with torch.no_grad():\n x = self.stem(x)\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.attnpool.forward_dense(x)\n x = F.normalize(x, dim=1) # remember to normalize!\n # TODO: debug\n roi_feats = roi_align(x, self._denormalize_boxes(normed_boxes, x),\n (1, 1), 1.0, -1, True)[:, :, 0, 0]\n return roi_feats\n\n def _extract_roi_features_v2(self, x, normed_boxes, **kwargs):\n with torch.no_grad():\n x = self.stem(x)\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x) # only the last layer is finetuned in our implementation\n\n tar_size = self.attnpool_input_size\n # TODO: debug\n roi_feats = roi_align(x, self._denormalize_boxes(normed_boxes, x),\n (tar_size, tar_size), 1.0, -1, True)\n\n roi_feats = self.attnpool(roi_feats)\n\n return roi_feats\n\n def encode_dense(self, x, keep_shape=True):\n x = self.stem(x)\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n feature_map = self.attnpool.forward_dense(x)\n feature_map = F.normalize(feature_map, dim=1) # remember to normalize!\n\n return feature_map" }, { "identifier": "TimmModel", "path": "src/open_clip/timm_model.py", "snippet": "class TimmModel(nn.Module):\n \"\"\" timm model adapter\n \"\"\"\n\n def __init__(\n self,\n model_name,\n embed_dim,\n image_size=224,\n pool='avg',\n proj='linear',\n proj_bias=False,\n drop=0.,\n drop_path=None,\n patch_drop=None,\n pretrained=False,\n ):\n super().__init__()\n if timm is None:\n raise RuntimeError(\"Please `pip install timm` to use timm models.\")\n self.image_size = to_2tuple(image_size)\n\n # setup kwargs that may not be common across all models\n timm_kwargs = {}\n if drop_path is not None:\n timm_kwargs['drop_path_rate'] = drop_path\n if patch_drop is not None:\n timm_kwargs['patch_drop_rate'] = patch_drop\n\n custom_pool = pool in ('abs_attn', 'rot_attn')\n if not proj and not custom_pool:\n # use network classifier head as projection if no proj specified and no custom pooling used\n self.trunk = timm.create_model(\n model_name,\n num_classes=embed_dim,\n global_pool=pool,\n pretrained=pretrained,\n **timm_kwargs,\n )\n prev_chs = embed_dim\n else:\n self.trunk = timm.create_model(\n model_name,\n pretrained=pretrained,\n **timm_kwargs,\n )\n feat_size = self.trunk.default_cfg.get('pool_size', None)\n feature_ndim = 1 if not feat_size else 2\n if custom_pool:\n assert feature_ndim == 2\n # if attn pooling used, remove both classifier and default pool\n self.trunk.reset_classifier(0, global_pool='')\n else:\n # reset global pool if pool config set, otherwise leave as network default\n reset_kwargs = dict(global_pool=pool) if pool else {}\n self.trunk.reset_classifier(0, **reset_kwargs)\n prev_chs = self.trunk.num_features\n\n head_layers = OrderedDict()\n\n # Add custom pooling to head\n if pool == 'abs_attn':\n head_layers['pool'] = AbsAttentionPool2d(prev_chs, feat_size=feat_size, out_features=embed_dim)\n prev_chs = embed_dim\n elif pool == 'rot_attn':\n head_layers['pool'] = RotAttentionPool2d(prev_chs, out_features=embed_dim)\n prev_chs = embed_dim\n\n # NOTE attention pool ends with a projection layer, so proj should usually be set to '' if such pooling is used\n if proj == 'linear':\n head_layers['drop'] = nn.Dropout(drop)\n head_layers['proj'] = nn.Linear(prev_chs, embed_dim, bias=proj_bias)\n elif proj == 'mlp':\n head_layers['mlp'] = Mlp(prev_chs, 2 * embed_dim, embed_dim, drop=(drop, 0), bias=(True, proj_bias))\n else:\n assert not proj, f'Unknown projection type {proj}.'\n\n self.head = nn.Sequential(head_layers)\n\n def lock(self, unlocked_groups=0, freeze_bn_stats=False):\n \"\"\" lock modules\n Args:\n unlocked_groups (int): leave last n layer groups unlocked (default: 0)\n \"\"\"\n if not unlocked_groups:\n # lock full model\n for param in self.trunk.parameters():\n param.requires_grad = False\n if freeze_bn_stats:\n freeze_batch_norm_2d(self.trunk)\n else:\n # NOTE: partial freeze requires latest timm (master) branch and is subject to change\n try:\n # FIXME import here until API stable and in an official release\n from timm.models.helpers import group_parameters, group_modules\n except ImportError:\n raise RuntimeError(\n 'Please install latest timm `pip install git+https://github.com/rwightman/pytorch-image-models`')\n matcher = self.trunk.group_matcher()\n gparams = group_parameters(self.trunk, matcher)\n max_layer_id = max(gparams.keys())\n max_layer_id = max_layer_id - unlocked_groups\n for group_idx in range(max_layer_id + 1):\n group = gparams[group_idx]\n for param in group:\n self.trunk.get_parameter(param).requires_grad = False\n if freeze_bn_stats:\n gmodules = group_modules(self.trunk, matcher, reverse=True)\n gmodules = {k for k, v in gmodules.items() if v <= max_layer_id}\n freeze_batch_norm_2d(self.trunk, gmodules)\n\n @torch.jit.ignore\n def set_grad_checkpointing(self, enable=True):\n try:\n self.trunk.set_grad_checkpointing(enable)\n except Exception as e:\n logging.warning('grad checkpointing not supported for this timm image tower, continuing without...')\n\n def forward(self, x):\n x = self.trunk(x)\n x = self.head(x)\n return x\n\n @staticmethod\n def _denormalize_boxes(normed_boxes, x):\n h, w = x.shape[-2:]\n denormed_boxes = []\n for boxes in normed_boxes:\n new_boxes = boxes.clone() # FIXME: do not change the value in normed_boxes!\n new_boxes[:, [0, 2]] *= w\n new_boxes[:, [1, 3]] *= h\n denormed_boxes.append(new_boxes)\n return denormed_boxes\n\n def _extract_roi_features_v1(self, x, normed_boxes, **kwargs):\n h, w = x.shape[-2:]\n x = self.trunk.forward_features(x)\n h_f, w_f = x.shape[-2:]\n tar_h = (self.image_size[0] * h_f) // h\n tar_w = (self.image_size[1] * w_f) // w\n x = roi_align(x, self._denormalize_boxes(normed_boxes, x), (tar_h, tar_w),\n 1.0, -1, True)\n\n x = self.trunk.forward_head(x)\n x = self.head(x)\n\n return x\n\n def encode_dense(self, x, **kwargs):\n x = self.trunk.forward_features(x)\n x = self.dense_trunk_head(x)\n x = self.head(x)\n x = x.permute(0, 3, 1, 2)\n\n return x\n\n def dense_trunk_head(self, x):\n x = self.trunk.head.norm(x)\n x = x.permute(0, 2, 3, 1)\n x = self.trunk.head.drop(x)\n # x = x.permute(0, 3, 1, 2)\n\n return x\n\n def mask_pool(self, image, masks):\n feature_map = self.encode_dense(image)\n feature_map = F.normalize(feature_map, dim=1) # remember to normalize!\n feature_map = feature_map.flatten(-2, -1) # bs, c, h*w\n num_masks_per_image = [len(masks_per_image) for masks_per_image in masks]\n masks = torch.cat(masks).float().flatten(-2, -1) # bs, h*w\n feature_map = torch.repeat_interleave(\n feature_map, torch.tensor(num_masks_per_image, device=feature_map.device), dim=0)\n features = (feature_map * masks[:, None]).sum(-1) / (masks.sum(1, keepdim=True) + 1e-12)\n\n return features\n\n def extract_roi_features(self, x, normed_boxes, extract_type='v1'):\n assert extract_type == \"v1\"\n if extract_type == 'v1':\n return self._extract_roi_features_v1(x, normed_boxes)\n else:\n assert extract_type == 'v2'\n return self._extract_roi_features_v2(x, normed_boxes)\n\n def _extract_roi_features_v2(self, x, normed_boxes, **kwargs):\n x = self.encode_dense(x)\n x = F.normalize(x, dim=1) # remember to normalize!\n\n roi_feats = roi_align(x, self._denormalize_boxes(normed_boxes, x), (1, 1),\n 1.0, -1, True)[..., 0, 0]\n return roi_feats\n\n def encode_rois_and_image(self, x, normed_boxes, **kwargs):\n h, w = x.shape[-2:]\n x = self.trunk.forward_features(x)\n h_f, w_f = x.shape[-2:]\n tar_h = (self.image_size[0] * h_f) // h\n tar_w = (self.image_size[1] * w_f) // w\n x_image = x\n x_rois = roi_align(x, self._denormalize_boxes(normed_boxes, x), (tar_h, tar_w),\n 1.0, -1, True)\n\n x_rois = self.trunk.forward_head(x_rois)\n x_rois = self.head(x_rois)\n x_rois = F.normalize(x_rois, dim=-1)\n\n x_image = self.trunk.forward_head(x_image)\n x_image = self.head(x_image)\n x_image = F.normalize(x_image, dim=-1)\n\n return x_rois, x_image" }, { "identifier": "LayerNormFp32", "path": "src/open_clip/transformer.py", "snippet": "class LayerNormFp32(nn.LayerNorm):\n \"\"\"Subclass torch's LayerNorm to handle fp16 (by casting to float32 and back).\"\"\"\n\n def forward(self, x: torch.Tensor):\n orig_type = x.dtype\n x = F.layer_norm(x.to(torch.float32), self.normalized_shape, self.weight, self.bias, self.eps)\n return x.to(orig_type)" }, { "identifier": "LayerNorm", "path": "src/open_clip/transformer.py", "snippet": "class LayerNorm(nn.LayerNorm):\n \"\"\"Subclass torch's LayerNorm (with cast back to input dtype).\"\"\"\n\n def forward(self, x: torch.Tensor):\n orig_type = x.dtype\n x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)\n return x.to(orig_type)" }, { "identifier": "QuickGELU", "path": "src/open_clip/transformer.py", "snippet": "class QuickGELU(nn.Module):\n # NOTE This is slower than nn.GELU or nn.SiLU and uses more GPU memory\n def forward(self, x: torch.Tensor):\n return x * torch.sigmoid(1.702 * x)" }, { "identifier": "Attention", "path": "src/open_clip/transformer.py", "snippet": "class Attention(nn.Module):\n def __init__(\n self,\n dim,\n num_heads=8,\n qkv_bias=True,\n scaled_cosine=False,\n scale_heads=False,\n logit_scale_max=math.log(1. / 0.01),\n attn_drop=0.,\n proj_drop=0.\n ):\n super().__init__()\n self.scaled_cosine = scaled_cosine\n self.scale_heads = scale_heads\n assert dim % num_heads == 0, 'dim should be divisible by num_heads'\n self.num_heads = num_heads\n self.head_dim = dim // num_heads\n self.scale = self.head_dim ** -0.5\n self.logit_scale_max = logit_scale_max\n\n # keeping in_proj in this form (instead of nn.Linear) to match weight scheme of original\n self.in_proj_weight = nn.Parameter(torch.randn((dim * 3, dim)) * self.scale)\n if qkv_bias:\n self.in_proj_bias = nn.Parameter(torch.zeros(dim * 3))\n else:\n self.in_proj_bias = None\n\n if self.scaled_cosine:\n self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1))))\n else:\n self.logit_scale = None\n self.attn_drop = nn.Dropout(attn_drop)\n if self.scale_heads:\n self.head_scale = nn.Parameter(torch.ones((num_heads, 1, 1)))\n else:\n self.head_scale = None\n self.out_proj = nn.Linear(dim, dim)\n self.out_drop = nn.Dropout(proj_drop)\n\n def forward(self, x, attn_mask: Optional[torch.Tensor] = None):\n L, N, C = x.shape\n q, k, v = F.linear(x, self.in_proj_weight, self.in_proj_bias).chunk(3, dim=-1)\n q = q.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)\n k = k.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)\n v = v.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)\n\n if self.logit_scale is not None:\n attn = torch.bmm(F.normalize(q, dim=-1), F.normalize(k, dim=-1).transpose(-1, -2))\n logit_scale = torch.clamp(self.logit_scale, max=self.logit_scale_max).exp()\n attn = attn.view(N, self.num_heads, L, L) * logit_scale\n attn = attn.view(-1, L, L)\n else:\n q = q * self.scale\n attn = torch.bmm(q, k.transpose(-1, -2))\n\n if attn_mask is not None:\n if attn_mask.dtype == torch.bool:\n new_attn_mask = torch.zeros_like(attn_mask, dtype=q.dtype)\n new_attn_mask.masked_fill_(attn_mask, float(\"-inf\"))\n attn_mask = new_attn_mask\n attn += attn_mask\n\n attn = attn.softmax(dim=-1)\n attn = self.attn_drop(attn)\n\n x = torch.bmm(attn, v)\n if self.head_scale is not None:\n x = x.view(N, self.num_heads, L, C) * self.head_scale\n x = x.view(-1, L, C)\n x = x.transpose(0, 1).reshape(L, N, C)\n x = self.out_proj(x)\n x = self.out_drop(x)\n return x" }, { "identifier": "VisionTransformer", "path": "src/open_clip/transformer.py", "snippet": "class VisionTransformer(nn.Module):\n output_tokens: torch.jit.Final[bool]\n\n def __init__(\n self,\n image_size: int,\n patch_size: int,\n width: int,\n layers: int,\n heads: int,\n mlp_ratio: float,\n ls_init_value: float = None,\n global_average_pool: bool = False,\n attentional_pool: bool = False,\n n_queries: int = 256,\n attn_pooler_heads: int = 8,\n output_dim: int = 512,\n patch_dropout: float = 0.,\n input_patchnorm: bool = False,\n act_layer: Callable = nn.GELU,\n norm_layer: Callable = LayerNorm,\n output_tokens: bool = False\n ):\n super().__init__()\n self.output_tokens = output_tokens\n image_height, image_width = self.image_size = to_2tuple(image_size)\n patch_height, patch_width = self.patch_size = to_2tuple(patch_size)\n self.grid_size = (image_height // patch_height, image_width // patch_width)\n self.output_dim = output_dim\n\n # whether to layernorm each patch, as done in dual patchnorm paper - https://arxiv.org/abs/2302.01327v1\n self.input_patchnorm = input_patchnorm\n assert not input_patchnorm\n if input_patchnorm:\n patch_input_dim = patch_height * patch_width * 3\n self.patchnorm_pre_ln = LayerNorm(patch_input_dim)\n self.conv1 = nn.Linear(patch_input_dim, width)\n else:\n self.patchnorm_pre_ln = nn.Identity()\n self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)\n\n # class embeddings and positional embeddings\n scale = width ** -0.5\n self.class_embedding = nn.Parameter(scale * torch.randn(width))\n self.positional_embedding = nn.Parameter(scale * torch.randn(self.grid_size[0] * self.grid_size[1] + 1, width))\n\n # setting a patch_dropout of 0. would mean it is disabled and this function would be the identity fn\n self.patch_dropout = PatchDropout(patch_dropout) if patch_dropout > 0. else nn.Identity()\n\n self.ln_pre = norm_layer(width)\n self.transformer = Transformer(\n width,\n layers,\n heads,\n mlp_ratio,\n ls_init_value=ls_init_value,\n act_layer=act_layer,\n norm_layer=norm_layer,\n )\n self.num_heads = heads\n\n self.global_average_pool = global_average_pool\n if attentional_pool:\n self.attn_pool = AttentionalPooler(output_dim, width, n_head=attn_pooler_heads, n_queries=n_queries)\n self.ln_post = norm_layer(output_dim)\n self.proj = nn.Parameter(scale * torch.randn(output_dim, output_dim))\n else:\n self.attn_pool = None\n self.ln_post = norm_layer(width)\n self.proj = nn.Parameter(scale * torch.randn(width, output_dim))\n\n self.init_parameters()\n\n def lock(self, unlocked_groups=0, freeze_bn_stats=False):\n for param in self.parameters():\n param.requires_grad = False\n\n if unlocked_groups != 0:\n groups = [\n [\n self.conv1,\n self.class_embedding,\n self.ln_pre,\n ],\n self.positional_embedding,\n *self.transformer.resblocks[:-1],\n [\n self.transformer.resblocks[-1],\n # self.ln_post, # fix layer norm\n ],\n # self.proj, # fix output layers\n ]\n\n def _unlock(x):\n if isinstance(x, Sequence):\n for g in x:\n _unlock(g)\n else:\n if isinstance(x, torch.nn.Parameter):\n x.requires_grad = True\n else:\n for p in x.parameters():\n p.requires_grad = True\n\n _unlock(groups[-unlocked_groups:])\n\n def attention_lock(self, **kwargs):\n for name, params in self.named_parameters():\n params.requires_grad = True if \"attn\" in name or \"position\" in name else False\n\n def init_parameters(self):\n # FIXME OpenAI CLIP did not define an init for the VisualTransformer\n # TODO experiment if default PyTorch init, below, or alternate init is best.\n pass\n\n @torch.jit.ignore\n def set_grad_checkpointing(self, enable=True):\n self.transformer.grad_checkpointing = enable\n\n def _global_pool(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n if self.global_average_pool:\n return x.mean(dim=1), x\n else:\n return x[:, 0], x[:, 1:]\n\n def forward(self, x: torch.Tensor):\n\n # to patches - whether to use dual patchnorm - https://arxiv.org/abs/2302.01327v1\n # if self.input_patchnorm:\n # # einops - rearrange(x, 'b c (h p1) (w p2) -> b (h w) (c p1 p2)')\n # x = x.reshape(x.shape[0], x.shape[1], self.grid_size[0], self.patch_size[0], self.grid_size[1], self.patch_size[1])\n # x = x.permute(0, 2, 4, 1, 3, 5)\n # x = x.reshape(x.shape[0], self.grid_size[0] * self.grid_size[1], -1)\n # x = self.patchnorm_pre_ln(x)\n # x = self.conv1(x)\n # else:\n x = self.conv1(x) # shape = [*, width, grid, grid]\n bs, _, h, w = x.shape\n x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]\n x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]\n\n # class embeddings and positional embeddings\n x = torch.cat(\n [self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device),\n x], dim=1) # shape = [*, grid ** 2 + 1, width]\n # TODO: Allow interpolating the positional embeddings\n\n if (h, w) == self.grid_size:\n pe = self.positional_embedding.to(x.dtype)\n else:\n pe = self.rescale_positional_embedding(out_size=(h, w), dtype=x.dtype)\n\n x = x + pe\n\n # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in\n x = self.patch_dropout(x)\n x = self.ln_pre(x)\n\n x = x.permute(1, 0, 2) # NLD -> LND\n x = self.transformer(x)\n x = x.permute(1, 0, 2) # LND -> NLD\n\n if self.attn_pool is not None:\n x = self.attn_pool(x)\n x = self.ln_post(x)\n pooled, tokens = self._global_pool(x)\n else:\n pooled, tokens = self._global_pool(x)\n pooled = self.ln_post(pooled)\n\n if self.proj is not None:\n pooled = pooled @ self.proj\n\n if self.output_tokens:\n return pooled, tokens\n \n return pooled\n\n def post_attention(self, x):\n x = x.permute(1, 0, 2) # LND -> NLD\n\n if self.attn_pool is not None:\n x = self.attn_pool(x)\n x = self.ln_post(x)\n pooled, tokens = self._global_pool(x)\n else:\n pooled, tokens = self._global_pool(x)\n pooled = self.ln_post(pooled)\n\n if self.proj is not None:\n pooled = pooled @ self.proj\n\n if self.output_tokens:\n return pooled, tokens\n\n return pooled\n\n def extract_roi_features(self, x, normed_boxes, extract_type='v2'):\n if extract_type == 'v1':\n return self._extract_roi_features_v1(x, normed_boxes)\n elif extract_type == 'v2':\n return self._extract_roi_features_v2(x, normed_boxes)\n else:\n raise NotImplementedError\n # assert extract_type == 'v3'\n # return self._extract_roi_features_v3(x, normed_boxes)\n\n def mask_pool(self, x, masks):\n feature_map = self.encode_dense(x)\n feature_map = F.normalize(feature_map, dim=-1)\n\n num_masks_per_image = [len(masks_per_image) for masks_per_image in masks]\n masks = torch.cat(masks).float().flatten(-2, -1) # bs, h*w\n feature_map = torch.repeat_interleave(\n feature_map, torch.tensor(num_masks_per_image, device=feature_map.device), dim=0)\n features = (feature_map * masks.unsqueeze(-1)).sum(1) / (masks.sum(1, keepdim=True) + 1e-12)\n\n return features\n\n def mask_features(self, x, masks):\n feature_map = self.encode_dense(x)\n feature_map = F.normalize(feature_map, dim=-1)\n\n num_masks_per_image = [len(masks_per_image) for masks_per_image in masks]\n masks = torch.cat(masks).flatten(-2, -1) > 0 # bs, h*w\n feature_map = torch.repeat_interleave(\n feature_map, torch.tensor(num_masks_per_image, device=feature_map.device), dim=0)\n\n mask_features = [f[m] for m, f in zip(masks, feature_map)]\n\n return mask_features\n\n def encode_dense(self, x, keep_shape=False):\n x = self.conv1(x) # shape = [*, width, grid, grid]\n bs, _, h, w = x.shape\n # assert h == w # TODO: support input of any shape, need to change the normed boxes to real boxes\n x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]\n x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]\n x = torch.cat(\n [self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device),\n x], dim=1) # shape = [*, grid ** 2 + 1, width]\n if (h, w) == self.grid_size:\n pe = self.positional_embedding.to(x.dtype)\n else:\n pe = self.rescale_positional_embedding(out_size=(h, w), dtype=x.dtype)\n\n x = x + pe\n\n # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in\n x = self.patch_dropout(x)\n x = self.ln_pre(x)\n\n x = x.permute(1, 0, 2) # NLD -> LND\n x = self.transformer.extract_feature_map(x)\n x = x.permute(1, 0, 2) # LND -> NLD\n\n if self.attn_pool is not None:\n x = self.attn_pool(x)\n x = self.ln_post(x)\n _, tokens = self._global_pool(x)\n else:\n _, tokens = self._global_pool(x)\n tokens = self.ln_post(tokens)\n\n if self.proj is not None:\n tokens = tokens @ self.proj\n\n feature_map = tokens.view(bs, h * w, -1) # .permute(0, 3, 1, 2)\n feature_map = F.normalize(feature_map, dim=-1) # normalize at the last dimension\n if keep_shape:\n feature_map = feature_map.view(bs, h, w, -1).permute(0, 3, 1, 2)\n return feature_map\n\n def mask_crop(self, x, masks):\n x = self.conv1(x) # shape = [*, width, grid, grid]\n num_masks_per_image = [len(masks_per_image) for masks_per_image in masks]\n masks = torch.cat(masks).to(x) # bs, h, w\n x = torch.repeat_interleave(\n x, torch.tensor(num_masks_per_image, device=x.device), dim=0)\n x = x * masks[:, None]\n bs, _, h, w = x.shape\n x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]\n x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]\n\n # class embeddings and positional embeddings\n x = torch.cat(\n [self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device),\n x], dim=1) # shape = [*, grid ** 2 + 1, width]\n # TODO: Allow interpolating the positional embeddings\n\n if (h, w) == self.grid_size:\n pe = self.positional_embedding.to(x.dtype)\n else:\n pe = self.rescale_positional_embedding(out_size=(h, w), dtype=x.dtype)\n\n x = x + pe\n\n x = self.patch_dropout(x)\n x = self.ln_pre(x)\n\n x = x.permute(1, 0, 2) # NLD -> LND\n x = self.transformer(x)\n x = x.permute(1, 0, 2) # LND -> NLD\n\n if self.attn_pool is not None:\n x = self.attn_pool(x)\n x = self.ln_post(x)\n pooled, tokens = self._global_pool(x)\n else:\n pooled, tokens = self._global_pool(x)\n pooled = self.ln_post(pooled)\n\n if self.proj is not None:\n pooled = pooled @ self.proj\n\n return pooled\n\n @staticmethod\n def _generate_masks_per_image(normed_boxes, mask_h, mask_w):\n num_boxes = len(normed_boxes)\n boxes = normed_boxes * torch.tensor(\n [[mask_w, mask_h, mask_w, mask_h]], device=normed_boxes.device)\n masks = torch.zeros(num_boxes, mask_h, mask_w,\n dtype=torch.bool, device=normed_boxes.device)\n for i, box in enumerate(boxes):\n x0, y0, x1, y1 = box.long().tolist()\n masks[i, y0:y1, x0:x1] = True\n\n return masks\n \n @staticmethod\n def _denormalize_boxes(normed_boxes, x):\n h, w = x.shape[-2:]\n denormed_boxes = []\n for boxes in normed_boxes:\n new_boxes = boxes.clone() # FIXME: do not change the value in normed_boxes!\n new_boxes[:, [0, 2]] *= w\n new_boxes[:, [1, 3]] *= h\n denormed_boxes.append(new_boxes)\n return denormed_boxes\n\n def _extract_roi_features_v1(self, x, normed_boxes):\n # used masks\n bs, _, h, w = x.shape\n patch_height, patch_width = self.patch_size\n mask_h, mask_w = h // patch_height, w // patch_width\n masks = [self._generate_masks_per_image(normed_boxes_, mask_h, mask_w)\n for normed_boxes_ in normed_boxes]\n\n return self.mask_attn_pool(x, masks)\n\n def _extract_roi_features_v3(self, x, normed_boxes): # v3 for extract two types\n # used masks\n bs, _, h, w = x.shape\n patch_height, patch_width = self.patch_size\n mask_h, mask_w = h // patch_height, w // patch_width\n masks = [self._generate_masks_per_image(normed_boxes_, mask_h, mask_w)\n for normed_boxes_ in normed_boxes]\n\n roi_features_v1, dense_x = self.mask_attn_pool(x, masks, return_dense=True)\n dense_x = F.normalize(dense_x, dim=-1) # normalize along last dimension\n dense_x = dense_x.permute(0, 3, 1, 2)\n roi_features_v2 = roi_align(dense_x, self._denormalize_boxes(normed_boxes, dense_x), \n (1, 1), 1.0, -1, True)[..., 0, 0]\n\n return roi_features_v1, roi_features_v2\n\n def _extract_roi_features_v2(self, x, normed_boxes):\n x = self.conv1(x) # shape = [*, width, grid, grid]\n bs, _, h, w = x.shape\n # assert h == w # TODO: support input of any shape, need to change the normed boxes to real boxes\n x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]\n x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]\n x = torch.cat(\n [self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device),\n x], dim=1) # shape = [*, grid ** 2 + 1, width]\n if (h, w) == self.grid_size:\n pe = self.positional_embedding.to(x.dtype)\n else:\n pe = self.rescale_positional_embedding(out_size=(h, w), dtype=x.dtype)\n\n x = x + pe\n\n # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in\n x = self.patch_dropout(x)\n x = self.ln_pre(x)\n\n x = x.permute(1, 0, 2) # NLD -> LND\n x = self.transformer.extract_feature_map(x)\n x = x.permute(1, 0, 2) # LND -> NLD\n\n if self.attn_pool is not None:\n x = self.attn_pool(x)\n x = self.ln_post(x)\n _, tokens = self._global_pool(x)\n else:\n _, tokens = self._global_pool(x)\n tokens = self.ln_post(tokens)\n\n if self.proj is not None:\n tokens = tokens @ self.proj\n tokens = F.normalize(tokens, dim=-1) # normalize along last dimension\n tokens = tokens.view(bs, h, w, -1).permute(0, 3, 1, 2)\n return roi_align(tokens, self._denormalize_boxes(normed_boxes, tokens),\n (1, 1), 1.0, -1, True)[..., 0, 0]\n\n def rescale_positional_embedding(self, out_size, dtype):\n h, w = out_size\n rescaled_positional_embedding = \\\n self.positional_embedding.new_zeros(1 + h*w, self.positional_embedding.shape[1])\n rescaled_positional_embedding[0] = self.positional_embedding[0]\n pe_2d = self.positional_embedding[1:].T.contiguous().view(\n 1, -1, *self.grid_size)\n pe_2d = F.interpolate(pe_2d, out_size, mode='bicubic', align_corners=False).view(-1, h*w)\n rescaled_positional_embedding[1:] = pe_2d.T.contiguous()\n\n return rescaled_positional_embedding.to(dtype=dtype)\n\n def _mask_attn_pool(self, x: torch.Tensor, attn_mask: torch.Tensor, num_mask_tokens: int, return_dense=False):\n x = self.conv1(x) # shape = [*, width, grid, grid]\n bs, _, h, w = x.shape\n x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]\n x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]\n x = torch.cat(\n [\n self.class_embedding.to(x.dtype)\n + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device),\n x,\n ],\n dim=1,\n ) # shape = [*, grid ** 2 + 1, width]\n if (h, w) == self.grid_size:\n pe = self.positional_embedding.to(x.dtype)\n else:\n pe = self.rescale_positional_embedding(out_size=(h, w), dtype=x.dtype)\n\n x = x + pe\n x = self.ln_pre(x)\n\n x = x.permute(1, 0, 2) # NLD -> LND\n cls_embed = x[0:1]\n cls_embed = cls_embed.expand(num_mask_tokens, -1, -1)\n x = torch.cat([cls_embed, x], dim=0)\n if return_dense:\n x, x_dense = self.transformer.forward_image_dense(x, attn_mask)\n x_dense = x_dense.permute(1, 0, 2) # LND -> NLD\n x_dense = x_dense[:, num_mask_tokens + 1:]\n\n x_dense = self.ln_post(x_dense)\n\n if self.proj is not None:\n x_dense = x_dense @ self.proj\n x_dense = F.normalize(x_dense, dim=-1) # normalize along last dimension\n x_dense = x_dense.view(bs, h, w, -1)\n else:\n x = self.transformer(x, attn_mask)\n x_dense = None\n x = x.permute(1, 0, 2) # LND -> NLD\n\n # [N, L, D]\n x = self.ln_post(x[:, :num_mask_tokens, :])\n\n if self.proj is not None:\n x = torch.einsum(\"nld,dc->nlc\", x, self.proj)\n\n return x, x_dense\n\n def mask_attn_pool(self, image, masks, return_dense=False):\n assert hasattr(self, \"positional_embedding\")\n batch_size = image.shape[0]\n assert batch_size == len(masks)\n num_masks_per_image = [mask.shape[0] for mask in masks]\n num_queries = max(num_masks_per_image)\n mask_h, mask_w = masks[0].shape[1:]\n\n batch_masks = torch.ones(batch_size, num_queries, mask_h, mask_w, dtype=torch.bool).to(image.device)\n for batch_id, mask in enumerate(masks):\n batch_masks[batch_id, :mask.shape[0]] = mask\n\n mask_token_attn_mask = torch.logical_not(batch_masks)\n # [B, Q, H//P x W//P]\n mask_token_attn_mask = mask_token_attn_mask.reshape(batch_size, num_queries, -1)\n\n num_mask_token = num_queries\n num_image_cls_token = (mask_h * mask_w + 1)\n num_image_token = num_image_cls_token - 1\n num_all_token = num_mask_token + num_image_cls_token\n\n # we start with no mask out\n attn_mask = torch.zeros(\n (num_all_token, num_all_token), dtype=torch.bool, device=image.device\n )\n\n # mask+cls+image token to mask token attention is masked out\n attn_mask[:, :num_mask_token] = True\n\n attn_mask = attn_mask.unsqueeze(0).repeat_interleave(batch_size, dim=0)\n attn_mask[:, :num_mask_token, -num_image_token:] = mask_token_attn_mask\n num_heads = self.num_heads # head width 64\n attn_mask = attn_mask.unsqueeze(1).expand(-1, num_heads, -1, -1)\n attn_mask = attn_mask.reshape(batch_size * num_heads, num_all_token, num_all_token)\n\n batch_mask_features, x_dense = self._mask_attn_pool(image, attn_mask, num_mask_token,\n return_dense=return_dense)\n\n mask_features = [batch_mask_features[batch_id, :num_masks]\n for batch_id, num_masks, in enumerate(num_masks_per_image)]\n if return_dense:\n # x_dense = F.normalize(x_dense, dim=-1).flatten(1, 2) # bs, h*w, c\n # masks = torch.cat(masks).float().flatten(-2, -1) # bs, h*w\n # x_dense = torch.repeat_interleave(\n # x_dense, torch.tensor(num_masks_per_image, device=x_dense.device), dim=0)\n # x_dense = (x_dense * masks.unsqueeze(-1)).sum(1) / masks.sum(1, keepdim=True)\n\n return torch.cat(mask_features), x_dense\n else:\n return torch.cat(mask_features)\n\n def encode_rois_and_image(self, x, normed_boxes):\n x = self.conv1(x) # shape = [*, width, grid, grid]\n bs, _, h, w = x.shape\n # assert h == w # TODO: support input of any shape, need to change the normed boxes to real boxes\n x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]\n x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]\n x = torch.cat(\n [self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device),\n x], dim=1) # shape = [*, grid ** 2 + 1, width]\n if (h, w) == self.grid_size:\n pe = self.positional_embedding.to(x.dtype)\n else:\n pe = self.rescale_positional_embedding(out_size=(h, w), dtype=x.dtype)\n\n x = x + pe\n\n # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in\n x = self.patch_dropout(x)\n x = self.ln_pre(x)\n\n x = x.permute(1, 0, 2) # NLD -> LND\n x, x_image = self.transformer.extract_feature_map(x, return_forward=True)\n x = x.permute(1, 0, 2) # LND -> NLD\n\n if self.attn_pool is not None:\n x = self.attn_pool(x)\n x = self.ln_post(x)\n _, tokens = self._global_pool(x)\n else:\n _, tokens = self._global_pool(x)\n tokens = self.ln_post(tokens)\n\n if self.proj is not None:\n tokens = tokens @ self.proj\n\n feature_map = tokens.view(bs, h * w, -1) # .permute(0, 3, 1, 2)\n feature_map = F.normalize(feature_map, dim=-1)\n feature_map = feature_map.view(bs, h, w, -1).permute(0, 3, 1, 2)\n x_rois = roi_align(feature_map, self._denormalize_boxes(normed_boxes, feature_map),\n (1, 1), 1.0, -1, True)[..., 0, 0]\n x_rois = F.normalize(x_rois, dim=-1)\n\n x_image = self.post_attention(x_image)\n x_image = F.normalize(x_image, dim=-1)\n\n return x_rois, x_image" }, { "identifier": "TextTransformer", "path": "src/open_clip/transformer.py", "snippet": "class TextTransformer(nn.Module):\n output_tokens: torch.jit.Final[bool]\n\n def __init__(\n self,\n context_length: int = 77,\n vocab_size: int = 49408,\n width: int = 512,\n heads: int = 8,\n layers: int = 12,\n ls_init_value: float = None,\n output_dim: int = 512,\n act_layer: Callable = nn.GELU,\n norm_layer: Callable = LayerNorm,\n embed_cls: bool = False,\n pad_id: int = 0,\n output_tokens: bool = False,\n ):\n super().__init__()\n self.output_tokens = output_tokens\n self.num_pos = self.context_length = context_length\n self.vocab_size = vocab_size\n self.width = width\n self.output_dim = output_dim\n self.heads = heads\n self.pad_id = pad_id\n\n self.text_projection = nn.Parameter(torch.empty(width, output_dim))\n\n if embed_cls:\n self.cls_emb = nn.Parameter(torch.empty(width))\n self.num_pos += 1\n else:\n self.cls_emb = None\n\n self.token_embedding = nn.Embedding(vocab_size, width)\n self.positional_embedding = nn.Parameter(torch.empty(self.num_pos, width))\n self.transformer = Transformer(\n width=width,\n layers=layers,\n heads=heads,\n ls_init_value=ls_init_value,\n act_layer=act_layer,\n norm_layer=norm_layer,\n )\n self.ln_final = norm_layer(width)\n\n self.register_buffer('attn_mask', self.build_attention_mask(), persistent=False)\n\n self.init_parameters()\n\n def init_parameters(self):\n nn.init.normal_(self.token_embedding.weight, std=0.02)\n nn.init.normal_(self.positional_embedding, std=0.01)\n if self.cls_emb is not None:\n nn.init.normal_(self.cls_emb, std=0.01)\n\n proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)\n attn_std = self.transformer.width ** -0.5\n fc_std = (2 * self.transformer.width) ** -0.5\n for block in self.transformer.resblocks:\n nn.init.normal_(block.attn.in_proj_weight, std=attn_std)\n nn.init.normal_(block.attn.out_proj.weight, std=proj_std)\n nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)\n nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)\n\n if self.text_projection is not None:\n nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)\n\n def lock(self, unlocked_layers: int = 0, freeze_layer_norm: bool = True):\n assert unlocked_layers == 0 and freeze_layer_norm\n print(f'Freeze the text encoder', flush=True)\n for p in self.parameters():\n p.requires_grad = False\n\n @torch.jit.ignore\n def set_grad_checkpointing(self, enable=True):\n self.transformer.grad_checkpointing = enable\n\n def build_attention_mask(self):\n # lazily create causal attention mask, with full attention between the tokens\n # pytorch uses additive attention mask; fill with -inf\n mask = torch.empty(self.num_pos, self.num_pos)\n mask.fill_(float(\"-inf\"))\n mask.triu_(1) # zero out the lower diagonal\n return mask\n\n def build_cls_mask(self, text, cast_dtype: torch.dtype):\n cls_mask = (text != self.pad_id).unsqueeze(1)\n cls_mask = F.pad(cls_mask, (1, 0, cls_mask.shape[2], 0), value=1.0)\n additive_mask = torch.empty(cls_mask.shape, dtype=cast_dtype, device=cls_mask.device)\n additive_mask.fill_(0)\n additive_mask.masked_fill_(~cls_mask, float(\"-inf\"))\n additive_mask = torch.repeat_interleave(additive_mask, self.heads, 0)\n return additive_mask\n\n def _repeat(self, t, N: int):\n return t.reshape(1, 1, -1).repeat(N, 1, 1)\n\n def forward(self, text):\n cast_dtype = self.transformer.get_cast_dtype()\n seq_len = text.shape[1]\n\n x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model]\n attn_mask = self.attn_mask\n if self.cls_emb is not None:\n seq_len += 1\n x = torch.cat([x, self._repeat(self.cls_emb, x.shape[0])], dim=1)\n cls_mask = self.build_cls_mask(text, cast_dtype)\n attn_mask = attn_mask[None, :seq_len, :seq_len] + cls_mask[:, :seq_len, :seq_len]\n\n x = x + self.positional_embedding[:seq_len].to(cast_dtype)\n x = x.permute(1, 0, 2) # NLD -> LND\n x = self.transformer(x, attn_mask=attn_mask)\n x = x.permute(1, 0, 2) # LND -> NLD\n\n # x.shape = [batch_size, n_ctx, transformer.width]\n # take features from the eot embedding (eot_token is the highest number in each sequence)\n if self.cls_emb is not None:\n pooled, tokens = x[:, -1], x[:, :-1]\n pooled = self.ln_final(pooled)\n else:\n x = self.ln_final(x)\n pooled, tokens = x[torch.arange(x.shape[0]), text.argmax(dim=-1)], x\n\n if self.text_projection is not None:\n pooled = pooled @ self.text_projection\n\n if self.output_tokens:\n return pooled, tokens\n\n return pooled" }, { "identifier": "to_2tuple", "path": "src/open_clip/utils.py", "snippet": "def freeze_batch_norm_2d(module, module_match={}, name=''):\ndef _ntuple(n):\n def parse(x):" } ]
from dataclasses import dataclass from typing import Optional, Tuple, Union from torch import nn from torch.utils.checkpoint import checkpoint from .hf_model import HFTextEncoder from .modified_resnet import ModifiedResNet from .timm_model import TimmModel from .transformer import LayerNormFp32, LayerNorm, QuickGELU, Attention, VisionTransformer, TextTransformer from .utils import to_2tuple import logging import math import numpy as np import torch import torch.nn.functional as F
17,555
mask_pooled_v2 = (x_dense * masks.unsqueeze(-1)).sum(1) / masks.sum(1, keepdim=True) if normalize: mask_pooled_v1 = F.normalize(mask_pooled_v1, dim=-1) mask_pooled_v2 = F.normalize(mask_pooled_v2, dim=-1) return mask_pooled_v1, mask_pooled_v2 def encode_masks(self, image, masks, normalize=True, mask_attn=False): return self._pool_masks(image, masks, normalize, mask_attn) def encode_text(self, text, normalize: bool = False): cast_dtype = self.transformer.get_cast_dtype() x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model] x = x + self.positional_embedding.to(cast_dtype) x = x.permute(1, 0, 2) # NLD -> LND x = self.transformer(x, attn_mask=self.attn_mask) x = x.permute(1, 0, 2) # LND -> NLD x = self.ln_final(x) # [batch_size, n_ctx, transformer.width] # take features from the eot embedding (eot_token is the highest number in each sequence) x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection return F.normalize(x, dim=-1) if normalize else x def forward(self, image, text=None): image_features = self.encode_image(image, normalize=True) if text is None: text_features = None else: text_features = self.encode_text(text, normalize=True) if self.output_dict: return { "image_features": image_features, "text_features": text_features, "logit_scale": self.logit_scale.exp() } return image_features, text_features, self.logit_scale.exp() def train(self, mode: bool = True): if not isinstance(mode, bool): raise ValueError("training mode is expected to be boolean") self.training = mode for name, module in self.named_children(): if name == 'visual': if mode: logging.info(f'========Set module {name} as train mode========') else: logging.info(f'========Set module {name} as eval mode========') module.train(mode) else: logging.info(f'========Set module {name} as eval mode========') module.train(mode=False) return self class CustomTextCLIP(nn.Module): output_dict: torch.jit.Final[bool] def __init__( self, embed_dim: int, vision_cfg: CLIPVisionCfg, text_cfg: CLIPTextCfg, quick_gelu: bool = False, cast_dtype: Optional[torch.dtype] = None, output_dict: bool = False, ): super().__init__() self.output_dict = output_dict self.visual = _build_vision_tower(embed_dim, vision_cfg, quick_gelu, cast_dtype) self.text = _build_text_tower(embed_dim, text_cfg, quick_gelu, cast_dtype) self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) def lock_image_tower(self, unlocked_groups=0, freeze_bn_stats=False): # lock image tower as per LiT - https://arxiv.org/abs/2111.07991 self.visual.lock(unlocked_groups=unlocked_groups, freeze_bn_stats=freeze_bn_stats) def lock_text_tower(self, unlocked_layers: int = 0, freeze_layer_norm: bool = True): self.text.lock(unlocked_layers, freeze_layer_norm) @torch.jit.ignore def set_grad_checkpointing(self, enable=True): self.visual.set_grad_checkpointing(enable) self.text.set_grad_checkpointing(enable) def encode_pseudo_boxes(self, image, normed_boxes, normalize: bool = False): features = self.visual.extract_roi_features(image, normed_boxes) return F.normalize(features, dim=-1) if normalize else features def encode_image(self, image, normalize: bool = False): features = self.visual(image) return F.normalize(features, dim=-1) if normalize else features def encode_text(self, text, normalize: bool = False): features = self.text(text) return F.normalize(features, dim=-1) if normalize else features def forward(self, image, text): image_features = self.encode_image(image, normalize=True) if text is None: text_features = None else: text_features = self.encode_text(text, normalize=True) if self.output_dict: return { "image_features": image_features, "text_features": text_features, "logit_scale": self.logit_scale.exp() } return image_features, text_features, self.logit_scale.exp() def convert_weights_to_lp(model: nn.Module, dtype=torch.float16): """Convert applicable model parameters to low-precision (bf16 or fp16)""" def _convert_weights(l): if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): l.weight.data = l.weight.data.to(dtype) if l.bias is not None: l.bias.data = l.bias.data.to(dtype)
""" CLIP Model Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. """ @dataclass class CLIPVisionCfg: layers: Union[Tuple[int, int, int, int], int] = 12 width: int = 768 head_width: int = 64 mlp_ratio: float = 4.0 patch_size: int = 16 image_size: Union[Tuple[int, int], int] = 224 ls_init_value: Optional[float] = None # layer scale initial value patch_dropout: float = 0. # what fraction of patches to dropout during training (0 would mean disabled and no patches dropped) - 0.5 to 0.75 recommended in the paper for optimal results input_patchnorm: bool = False # whether to use dual patchnorm - would only apply the input layernorm on each patch, as post-layernorm already exist in original clip vit design global_average_pool: bool = False # whether to global average pool the last embedding layer, instead of using CLS token (https://arxiv.org/abs/2205.01580) attentional_pool: bool = False # whether to use attentional pooler in the last embedding layer n_queries: int = 256 # n_queries for attentional pooler attn_pooler_heads: int = 8 # n heads for attentional_pooling timm_model_name: str = None # a valid model name overrides layers, width, patch_size timm_model_pretrained: bool = False # use (imagenet) pretrained weights for named model timm_pool: str = 'avg' # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '') timm_proj: str = 'linear' # linear projection for timm model output ('linear', 'mlp', '') timm_proj_bias: bool = False # enable bias final projection timm_drop: float = 0. # head dropout timm_drop_path: Optional[float] = None # backbone stochastic depth output_tokens: bool = False freeze_output = True freeze_all_bns = True @dataclass class CLIPTextCfg: context_length: int = 77 vocab_size: int = 49408 width: int = 512 heads: int = 8 layers: int = 12 ls_init_value: Optional[float] = None # layer scale initial value hf_model_name: str = None hf_tokenizer_name: str = None hf_model_pretrained: bool = True proj: str = 'mlp' pooler_type: str = 'mean_pooler' embed_cls: bool = False pad_id: int = 0 output_tokens: bool = False def get_cast_dtype(precision: str): cast_dtype = None if precision == 'bf16': cast_dtype = torch.bfloat16 elif precision == 'fp16': cast_dtype = torch.float16 return cast_dtype def _build_vision_tower( embed_dim: int, vision_cfg: CLIPVisionCfg, quick_gelu: bool = False, cast_dtype: Optional[torch.dtype] = None ): if isinstance(vision_cfg, dict): vision_cfg = CLIPVisionCfg(**vision_cfg) # OpenAI models are pretrained w/ QuickGELU but native nn.GELU is both faster and more # memory efficient in recent PyTorch releases (>= 1.10). # NOTE: timm models always use native GELU regardless of quick_gelu flag. act_layer = QuickGELU if quick_gelu else nn.GELU if vision_cfg.timm_model_name: visual = TimmModel( vision_cfg.timm_model_name, pretrained=vision_cfg.timm_model_pretrained, pool=vision_cfg.timm_pool, proj=vision_cfg.timm_proj, proj_bias=vision_cfg.timm_proj_bias, drop=vision_cfg.timm_drop, drop_path=vision_cfg.timm_drop_path, patch_drop=vision_cfg.patch_dropout if vision_cfg.patch_dropout > 0 else None, embed_dim=embed_dim, image_size=vision_cfg.image_size, ) act_layer = nn.GELU # so that text transformer doesn't use QuickGELU w/ timm models elif isinstance(vision_cfg.layers, (tuple, list)): vision_heads = vision_cfg.width * 32 // vision_cfg.head_width visual = ModifiedResNet( layers=vision_cfg.layers, output_dim=embed_dim, heads=vision_heads, image_size=vision_cfg.image_size, width=vision_cfg.width, freeze_output=vision_cfg.freeze_output, freeze_all_bns=vision_cfg.freeze_all_bns ) else: vision_heads = vision_cfg.width // vision_cfg.head_width norm_layer = LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm visual = VisionTransformer( image_size=vision_cfg.image_size, patch_size=vision_cfg.patch_size, width=vision_cfg.width, layers=vision_cfg.layers, heads=vision_heads, mlp_ratio=vision_cfg.mlp_ratio, ls_init_value=vision_cfg.ls_init_value, patch_dropout=vision_cfg.patch_dropout, input_patchnorm=vision_cfg.input_patchnorm, global_average_pool=vision_cfg.global_average_pool, attentional_pool=vision_cfg.attentional_pool, n_queries=vision_cfg.n_queries, attn_pooler_heads=vision_cfg.attn_pooler_heads, output_tokens=vision_cfg.output_tokens, output_dim=embed_dim, act_layer=act_layer, norm_layer=norm_layer, ) return visual def _build_text_tower( embed_dim: int, text_cfg: CLIPTextCfg, quick_gelu: bool = False, cast_dtype: Optional[torch.dtype] = None, ): if isinstance(text_cfg, dict): text_cfg = CLIPTextCfg(**text_cfg) if text_cfg.hf_model_name: text = HFTextEncoder( text_cfg.hf_model_name, output_dim=embed_dim, proj=text_cfg.proj, pooler_type=text_cfg.pooler_type, pretrained=text_cfg.hf_model_pretrained, output_tokens=text_cfg.output_tokens, ) else: act_layer = QuickGELU if quick_gelu else nn.GELU norm_layer = LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm text = TextTransformer( context_length=text_cfg.context_length, vocab_size=text_cfg.vocab_size, width=text_cfg.width, heads=text_cfg.heads, layers=text_cfg.layers, ls_init_value=text_cfg.ls_init_value, output_dim=embed_dim, embed_cls=text_cfg.embed_cls, output_tokens=text_cfg.output_tokens, pad_id=text_cfg.pad_id, act_layer=act_layer, norm_layer=norm_layer, ) return text class CLIP(nn.Module): output_dict: torch.jit.Final[bool] def __init__( self, embed_dim: int, vision_cfg: CLIPVisionCfg, text_cfg: CLIPTextCfg, quick_gelu: bool = False, cast_dtype: Optional[torch.dtype] = None, output_dict: bool = False, freeze_text=True, ): assert freeze_text, 'For now we must freeze text' super().__init__() self.output_dict = output_dict self.visual = _build_vision_tower(embed_dim, vision_cfg, quick_gelu, cast_dtype) text = _build_text_tower(embed_dim, text_cfg, quick_gelu, cast_dtype) if freeze_text: print(f'Freeze text encoder parameters', flush=True) for param in text.parameters(): param.requires_grad = False text.eval() self.transformer = text.transformer self.vocab_size = text.vocab_size self.embed_dim = embed_dim self.token_embedding = text.token_embedding self.positional_embedding = text.positional_embedding self.ln_final = text.ln_final self.text_projection = text.text_projection self.register_buffer('attn_mask', text.attn_mask, persistent=False) self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) def lock_image_tower(self, unlocked_groups=0, freeze_bn_stats=False, **kwargs): self.visual.lock(unlocked_groups=unlocked_groups, freeze_bn_stats=freeze_bn_stats) @torch.jit.ignore def set_grad_checkpointing(self, enable=True): self.visual.set_grad_checkpointing(enable) self.transformer.grad_checkpointing = enable def encode_image(self, image, normalize: bool = False): features = self.visual(image) return F.normalize(features, dim=-1) if normalize else features def encode_dense(self, image, normalize: bool = False, keep_shape=False): features = self.visual.encode_dense(image, keep_shape=keep_shape) if normalize: if keep_shape: features = F.normalize(features, dim=1) else: features = F.normalize(features, dim=-1) return features def encode_pseudo_boxes(self, image, normed_boxes, normalize: bool = False, extract_type='v1'): features = self.visual.extract_roi_features(image, normed_boxes, extract_type=extract_type) if normalize: features = F.normalize(features, dim=-1) return features def _pool_masks(self, image, masks, normalize, mask_attn=False): if mask_attn: mask_pooled = self.visual.mask_attn_pool(image, masks) else: mask_pooled = self.visual.mask_pool(image, masks) if normalize: mask_pooled = F.normalize(mask_pooled, dim=-1) return mask_pooled def _pool_masks_v3(self, image, masks, normalize): mask_pooled_v1, x_dense = self.visual.mask_attn_pool(image, masks, return_dense=True) x_dense = F.normalize(x_dense, dim=-1).flatten(1, 2) # bs, h*w, c x_dense = torch.repeat_interleave( x_dense, torch.tensor([len(m) for m in masks], device=x_dense.device), dim=0) masks = torch.cat(masks).float().flatten(-2, -1) # bs, h*w mask_pooled_v2 = (x_dense * masks.unsqueeze(-1)).sum(1) / masks.sum(1, keepdim=True) if normalize: mask_pooled_v1 = F.normalize(mask_pooled_v1, dim=-1) mask_pooled_v2 = F.normalize(mask_pooled_v2, dim=-1) return mask_pooled_v1, mask_pooled_v2 def encode_masks(self, image, masks, normalize=True, mask_attn=False): return self._pool_masks(image, masks, normalize, mask_attn) def encode_text(self, text, normalize: bool = False): cast_dtype = self.transformer.get_cast_dtype() x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model] x = x + self.positional_embedding.to(cast_dtype) x = x.permute(1, 0, 2) # NLD -> LND x = self.transformer(x, attn_mask=self.attn_mask) x = x.permute(1, 0, 2) # LND -> NLD x = self.ln_final(x) # [batch_size, n_ctx, transformer.width] # take features from the eot embedding (eot_token is the highest number in each sequence) x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection return F.normalize(x, dim=-1) if normalize else x def forward(self, image, text=None): image_features = self.encode_image(image, normalize=True) if text is None: text_features = None else: text_features = self.encode_text(text, normalize=True) if self.output_dict: return { "image_features": image_features, "text_features": text_features, "logit_scale": self.logit_scale.exp() } return image_features, text_features, self.logit_scale.exp() def train(self, mode: bool = True): if not isinstance(mode, bool): raise ValueError("training mode is expected to be boolean") self.training = mode for name, module in self.named_children(): if name == 'visual': if mode: logging.info(f'========Set module {name} as train mode========') else: logging.info(f'========Set module {name} as eval mode========') module.train(mode) else: logging.info(f'========Set module {name} as eval mode========') module.train(mode=False) return self class CustomTextCLIP(nn.Module): output_dict: torch.jit.Final[bool] def __init__( self, embed_dim: int, vision_cfg: CLIPVisionCfg, text_cfg: CLIPTextCfg, quick_gelu: bool = False, cast_dtype: Optional[torch.dtype] = None, output_dict: bool = False, ): super().__init__() self.output_dict = output_dict self.visual = _build_vision_tower(embed_dim, vision_cfg, quick_gelu, cast_dtype) self.text = _build_text_tower(embed_dim, text_cfg, quick_gelu, cast_dtype) self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) def lock_image_tower(self, unlocked_groups=0, freeze_bn_stats=False): # lock image tower as per LiT - https://arxiv.org/abs/2111.07991 self.visual.lock(unlocked_groups=unlocked_groups, freeze_bn_stats=freeze_bn_stats) def lock_text_tower(self, unlocked_layers: int = 0, freeze_layer_norm: bool = True): self.text.lock(unlocked_layers, freeze_layer_norm) @torch.jit.ignore def set_grad_checkpointing(self, enable=True): self.visual.set_grad_checkpointing(enable) self.text.set_grad_checkpointing(enable) def encode_pseudo_boxes(self, image, normed_boxes, normalize: bool = False): features = self.visual.extract_roi_features(image, normed_boxes) return F.normalize(features, dim=-1) if normalize else features def encode_image(self, image, normalize: bool = False): features = self.visual(image) return F.normalize(features, dim=-1) if normalize else features def encode_text(self, text, normalize: bool = False): features = self.text(text) return F.normalize(features, dim=-1) if normalize else features def forward(self, image, text): image_features = self.encode_image(image, normalize=True) if text is None: text_features = None else: text_features = self.encode_text(text, normalize=True) if self.output_dict: return { "image_features": image_features, "text_features": text_features, "logit_scale": self.logit_scale.exp() } return image_features, text_features, self.logit_scale.exp() def convert_weights_to_lp(model: nn.Module, dtype=torch.float16): """Convert applicable model parameters to low-precision (bf16 or fp16)""" def _convert_weights(l): if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): l.weight.data = l.weight.data.to(dtype) if l.bias is not None: l.bias.data = l.bias.data.to(dtype)
if isinstance(l, (nn.MultiheadAttention, Attention)):
6
2023-12-09 05:43:08+00:00
24k
LkPrtctrd/BSL-V53
Heart/Logic/LogicLaserMessageFactory.py
[ { "identifier": "ClientHelloMessage", "path": "Heart/Packets/Client/Authentification/ClientHelloMessage.py", "snippet": "class ClientHelloMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields):\n pass\n\n def decode(self):\n fields = {}\n fields[\"Protocol\"] = self.readInt()\n fields[\"KeyVersion\"] = self.readInt()\n fields[\"MajorVersion\"] = self.readInt()\n fields[\"MinorVersion\"] = self.readInt()\n fields[\"Build\"] = self.readInt()\n fields[\"ContentHash\"] = self.readString()\n fields[\"DeviceType\"] = self.readInt()\n fields[\"AppStore\"] = self.readInt()\n super().decode(fields)\n return fields\n\n def execute(message, calling_instance, fields, cryptoInit):\n fields[\"Socket\"] = calling_instance.client\n Messaging.sendMessage(20100, fields, cryptoInit)\n\n def getMessageType(self):\n return 10100\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "LoginMessage", "path": "Heart/Packets/Client/Authentification/LoginMessage.py", "snippet": "class LoginMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields):\n pass\n\n def decode(self):\n fields = {}\n fields[\"AccountID\"] = self.readLong()\n fields[\"PassToken\"] = self.readString()\n fields[\"ClientMajor\"] = self.readInt()\n fields[\"ClientMinor\"] = self.readInt()\n fields[\"ClientBuild\"] = self.readInt()\n fields[\"ResourceSha\"] = self.readString()\n fields[\"Device\"] = self.readString()\n fields[\"PreferredLanguage\"] = self.readDataReference()\n fields[\"PreferredDeviceLanguage\"] = self.readString()\n fields[\"OSVersion\"] = self.readString()\n fields[\"isAndroid\"] = self.readBoolean()\n fields[\"IMEI\"] = self.readString()\n fields[\"AndroidID\"] = self.readString()\n fields[\"isAdvertisingEnabled\"] = self.readBoolean()\n fields[\"AppleIFV\"] = self.readString()\n fields[\"RndKey\"] = self.readInt()\n fields[\"AppStore\"] = self.readVInt()\n fields[\"ClientVersion\"] = self.readString()\n fields[\"TencentOpenId\"] = self.readString()\n fields[\"TencentToken\"] = self.readString()\n fields[\"TencentPlatform\"] = self.readVInt()\n fields[\"DeviceVerifierResponse\"] = self.readString()\n fields[\"AppLicensingSignature\"] = self.readString()\n fields[\"DeviceVerifierResponse\"] = self.readString()\n super().decode(fields)\n return fields\n\n def execute(message, calling_instance, fields, cryptoInit):\n if fields[\"ClientMajor\"]==53:\n calling_instance.player.ClientVersion = f'{str(fields[\"ClientMajor\"])}.{str(fields[\"ClientBuild\"])}.{str(fields[\"ClientMinor\"])}'\n fields[\"Socket\"] = calling_instance.client\n db_instance = DatabaseHandler()\n if db_instance.playerExist(fields[\"PassToken\"], fields[\"AccountID\"]):\n player_data = json.loads(db_instance.getPlayerEntry(fields[\"AccountID\"])[2])\n db_instance.loadAccount(calling_instance.player, fields[\"AccountID\"])\n else:\n db_instance.createAccount(calling_instance.player.getDataTemplate(fields[\"AccountID\"][0], fields[\"AccountID\"][1], fields[\"PassToken\"]))\n ClientsManager.AddPlayer(calling_instance.player.ID, calling_instance.client)\n Messaging.sendMessage(20104, fields, cryptoInit, calling_instance.player)\n Messaging.sendMessage(24101, fields, cryptoInit, calling_instance.player)\n Messaging.sendMessage(24399, fields, cryptoInit, calling_instance.player)\n\n def getMessageType(self):\n return 10101\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "AskForBattleEndMessage", "path": "Heart/Packets/Client/Battle/AskForBattleEndMessage.py", "snippet": "class AskForBattleEndMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields):\n pass\n\n def decode(self):\n fields = {}\n fields[\"Unk1\"] = self.readVInt()\n fields[\"Result\"] = self.readVInt()\n fields[\"Rank\"] = self.readVInt()\n fields[\"MapID\"] = self.readDataReference()\n fields[\"HeroesCount\"] = self.readVInt()\n fields[\"Heroes\"] = []\n for i in range(fields[\"HeroesCount\"]): fields[\"Heroes\"].append({\"Brawler\": {\"ID\": self.readDataReference(), \"SkinID\": self.readDataReference()}, \"Team\": self.readVInt(), \"IsPlayer\": self.readBoolean(), \"PlayerName\": self.readString()})\n super().decode(fields)\n return fields\n\n def execute(message, calling_instance, fields, cryptoInit):\n fields[\"Socket\"] = calling_instance.client\n Messaging.sendMessage(23456, fields, cryptoInit, calling_instance.player)\n\n def getMessageType(self):\n return 14110\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "ChangeAvatarNameMessage", "path": "Heart/Packets/Client/Home/ChangeAvatarNameMessage.py", "snippet": "class ChangeAvatarNameMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields):\n self.writeString(fields[\"Name\"])\n self.writeBoolean(fields[\"NameSetByUser\"])\n\n def decode(self):\n fields = {}\n fields[\"Name\"] = self.readString()\n fields[\"NameSetByUser\"] = self.readBoolean()\n super().decode(fields)\n return fields\n\n def execute(message, calling_instance, fields, cryptoInit):\n db_instance = DatabaseHandler()\n playerData = db_instance.getPlayer(calling_instance.player.ID)\n playerData[\"Name\"] = fields[\"Name\"]\n playerData[\"Registered\"] = True\n db_instance.updatePlayerData(playerData, calling_instance)\n fields[\"Socket\"] = calling_instance.client\n fields[\"Command\"] = {\"ID\": 201}\n Messaging.sendMessage(24111, fields, cryptoInit, calling_instance.player)\n\n def getMessageType(self):\n return 10212\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "EndClientTurnMessage", "path": "Heart/Packets/Client/Home/EndClientTurnMessage.py", "snippet": "class EndClientTurnMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields):\n pass\n\n def decode(self):\n fields = {}\n self.readBoolean()\n fields[\"Tick\"] = self.readVInt()\n fields[\"Checksum\"] = self.readVInt()\n fields[\"CommandsCount\"] = self.readVInt()\n super().decode(fields)\n fields[\"Commands\"] = []\n for i in range(fields[\"CommandsCount\"]):\n fields[\"Commands\"].append({\"ID\": self.readVInt()})\n if LogicCommandManager.commandExist(fields[\"Commands\"][i][\"ID\"]):\n command = LogicCommandManager.createCommand(fields[\"Commands\"][i][\"ID\"])\n print(\"Command\", LogicCommandManager.getCommandsName(fields[\"Commands\"][i][\"ID\"]))\n if command is not None:\n fields[\"Commands\"][i][\"Fields\"] = command.decode(self)\n fields[\"Commands\"][i][\"Instance\"] = command\n return fields\n\n def execute(message, calling_instance, fields, cryptoInit):\n fields[\"Socket\"] = calling_instance.client\n for command in fields[\"Commands\"]:\n if \"Instance\" not in command.keys():\n return\n\n if hasattr(command[\"Instance\"], 'execute'):\n command[\"Instance\"].execute(calling_instance, command[\"Fields\"], cryptoInit)\n if command[\"ID\"] == 519:\n Messaging.sendMessage(24104, {\"Socket\": calling_instance.client, \"ServerChecksum\": 0, \"ClientChecksum\": 0, \"Tick\": 0}, cryptoInit)\n\n def getMessageType(self):\n return 14102\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "GoHomeFromOfflinePractiseMessage", "path": "Heart/Packets/Client/Home/GoHomeFromOfflinePractiseMessage.py", "snippet": "class GoHomeFromOfflinePractiseMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields):\n pass\n\n def decode(self):\n fields = {}\n self.readBoolean()\n return fields\n\n def execute(message, calling_instance, fields, cryptoInit):\n fields[\"Socket\"] = calling_instance.client\n Messaging.sendMessage(24101, fields, cryptoInit, calling_instance.player)\n\n def getMessageType(self):\n return 14109\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "GoHomeMessage", "path": "Heart/Packets/Client/Home/GoHomeMessage.py", "snippet": "class GoHomeMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields):\n pass\n\n def decode(self):\n fields = {}\n self.readBoolean()\n return fields\n\n def execute(message, calling_instance, fields, cryptoInit):\n fields[\"Socket\"] = calling_instance.client\n Messaging.sendMessage(24101, fields, cryptoInit, calling_instance.player)\n\n def getMessageType(self):\n return 17750\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "GetPlayerProfileMessage", "path": "Heart/Packets/Client/Home/GetPlayerProfileMessage.py", "snippet": "class GetPlayerProfileMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields):\n pass\n\n def decode(self):\n fields = {}\n fields[\"BattleInfoBoolean\"] = self.readBoolean()\n if fields[\"BattleInfoBoolean\"]:\n fields[\"unk1\"] = self.readVInt()\n fields[\"AnotherID\"] = self.readLong()\n fields[\"unk2\"] = self.readVInt()\n for i in self.readVInt():\n fields[\"CsvID\"] = self.readDataReference()\n fields[\"unk3\"] = self.readVInt()\n fields[\"unk4\"] = self.readVInt()\n fields[\"unk5\"] = self.readVInt()\n fields[\"unk6\"] = self.readVInt()\n fields[\"PlayerName\"] = self.readString()\n fields[\"unk7\"] = self.readVInt()\n fields[\"Thumbnail\"] = self.readVInt()\n fields[\"NameColor\"] = self.readVInt()\n fields[\"unk10\"] = self.readVInt()\n fields[\"unk11\"] = self.readVInt()\n fields[\"PlayerHighID\"] = self.readInt()\n fields[\"PlayerLowID\"] = self.readInt()\n super().decode(fields)\n\n\n return fields\n\n def execute(message, calling_instance, fields, cryptoInit):\n fields[\"Socket\"] = calling_instance.client\n Messaging.sendMessage(24113, fields, cryptoInit, calling_instance.player)\n\n def getMessageType(self):\n return 15081\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "AskForAllianceDataMessage", "path": "Heart/Packets/Client/Home/AskForAllianceDataMessage.py", "snippet": "class AskForAllianceDataMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields):\n pass\n\n def decode(self):\n fields = {}\n fields[\"id\"] = self.readVLong()\n fields[\"isInAlliance\"] = self.readBoolean()\n if fields[\"isInAlliance\"] == True:\n fields[\"anotherIDHigh\"] = self.readVInt()\n fields[\"anotherIDLow\"] = self.readVInt()\n super().decode(fields)\n\n return fields\n\n def execute(message, calling_instance, fields, cryptoInit):\n fields[\"Socket\"] = calling_instance.client\n Messaging.sendMessage(24301, fields, cryptoInit, calling_instance.player)\n\n def getMessageType(self):\n return 14302\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "KeepAliveMessage", "path": "Heart/Packets/Client/Socket/KeepAliveMessage.py", "snippet": "class KeepAliveMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields):\n pass\n\n def decode(self):\n return {}\n\n def execute(message, calling_instance, fields, cryptoInit):\n fields[\"Socket\"] = calling_instance.client\n Messaging.sendMessage(20108, fields, cryptoInit)\n\n def getMessageType(self):\n return 10108\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "LoginFailedMessage", "path": "Heart/Packets/Server/Authentification/LoginFailedMessage.py", "snippet": "class LoginFailedMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields):\n self.writeInt(fields['ErrorID'])\n self.writeString(fields['FingerprintData'])\n self.writeString()\n self.writeString(fields['ContentURL'])\n self.writeString()\n self.writeString(fields['Message'])\n self.writeInt(0)\n self.writeBoolean(False)\n self.writeInt(0)\n self.writeInt(0)\n self.writeInt(0)\n self.writeInt(0)\n self.writeString()\n self.writeInt(0)\n self.writeBoolean(True)\n self.writeBoolean(True)\n self.writeString()\n self.writeVInt(0)\n self.writeString()\n self.writeBoolean(False)\n\n def decode(self):\n fields = {}\n fields[\"ErrorCode\"] = self.readInt()\n fields[\"ResourceFingerprintData\"] = self.readString()\n fields[\"RedirectDomain\"] = self.readString()\n fields[\"ContentURL\"] = self.readString()\n fields[\"UpdateURL\"] = self.readString()\n fields[\"Reason\"] = self.readString()\n fields[\"SecondsUntilMaintenanceEnd\"] = self.readInt()\n fields[\"ShowContactSupportForBan\"] = self.readBoolean()\n fields[\"CompressedFingerprintData\"] = self.readBytesWithoutLength()\n fields[\"ContentURLListCount\"] = self.readInt()\n fields[\"ContentURLList\"] = []\n for i in range(fields[\"ContentURLListCount\"]):\n fields[\"ContentURLList\"].append(self.readString())\n fields[\"KunlunAppStore\"] = self.readInt()\n fields[\"MaintenanceType\"] = self.readInt()\n fields[\"HelpshiftFaqId\"] = self.readString()\n fields[\"Tier\"] = self.readInt()\n fields[\"Unk1\"] = self.readBoolean()\n fields[\"Unk2\"] = self.readBoolean()\n fields[\"Unk3\"] = self.readString()\n fields[\"Unk4\"] = self.readVInt()\n fields[\"Unk5\"] = self.readString()\n fields[\"OptionalTargetedAccountIdState\"] = self.readBoolean()\n if fields[\"OptionalTargetedAccountIdState\"] == True:\n fields[\"OptionalTargetedAccountId\"] = self.readLong()\n super().decode(fields)\n return fields\n\n def execute(message, calling_instance, fields):\n pass\n\n def getMessageType(self):\n return 20103\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "LoginOkMessage", "path": "Heart/Packets/Server/Authentification/LoginOkMessage.py", "snippet": "class LoginOkMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 1\n\n def encode(self, fields, player):\n self.writeLong(player.ID[0], player.ID[1])\n self.writeLong(player.ID[0], player.ID[1])\n self.writeString(player.Token)\n self.writeString()\n self.writeString()\n self.writeInt(53)\n self.writeInt(176)\n self.writeInt(1)\n self.writeString(\"dev\")\n self.writeInt(0)\n self.writeInt(0)\n self.writeInt(0)\n self.writeString()\n self.writeString()\n self.writeString()\n self.writeInt(0)\n self.writeString()\n self.writeString(\"RU\")\n self.writeString()\n self.writeInt(0)\n self.writeString()\n self.writeInt(2)\n self.writeString('https://game-assets.brawlstarsgame.com')\n self.writeString('http://a678dbc1c015a893c9fd-4e8cc3b1ad3a3c940c504815caefa967.r87.cf2.rackcdn.com')\n self.writeInt(2)\n self.writeString('https://event-assets.brawlstars.com')\n self.writeString('https://24b999e6da07674e22b0-8209975788a0f2469e68e84405ae4fcf.ssl.cf2.rackcdn.com/event-assets')\n self.writeVInt(0)\n self.writeCompressedString(b'')\n self.writeBoolean(True)\n self.writeBoolean(False)\n self.writeString()\n self.writeString()\n self.writeString()\n self.writeString('https://play.google.com/store/apps/details?id=com.supercell.brawlstars')\n self.writeString()\n self.writeBoolean(False)\n\n self.writeBoolean(False)\n if False:\n self.writeString()\n\n self.writeBoolean(False)\n if False:\n self.writeString()\n\n self.writeBoolean(False)\n if False:\n self.writeString()\n\n self.writeBoolean(False)\n if False:\n self.writeString()\n\n\n def decode(self):\n fields = {}\n fields[\"AccountID\"] = self.readLong()\n fields[\"HomeID\"] = self.readLong()\n fields[\"PassToken\"] = self.readString()\n fields[\"FacebookID\"] = self.readString()\n fields[\"GamecenterID\"] = self.readString()\n fields[\"ServerMajorVersion\"] = self.readInt()\n fields[\"ContentVersion\"] = self.readInt()\n fields[\"ServerBuild\"] = self.readInt()\n fields[\"ServerEnvironment\"] = self.readString()\n fields[\"SessionCount\"] = self.readInt()\n fields[\"PlayTimeSeconds\"] = self.readInt()\n fields[\"DaysSinceStartedPlaying\"] = self.readInt()\n fields[\"FacebookAppID\"] = self.readString()\n fields[\"ServerTime\"] = self.readString()\n fields[\"AccountCreatedDate\"] = self.readString()\n fields[\"StartupCooldownSeconds\"] = self.readInt()\n fields[\"GoogleServiceID\"] = self.readString()\n fields[\"LoginCountry\"] = self.readString()\n fields[\"KunlunID\"] = self.readString()\n fields[\"Tier\"] = self.readInt()\n fields[\"TencentID\"] = self.readString()\n\n ContentUrlCount = self.readInt()\n fields[\"GameAssetsUrls\"] = []\n for i in range(ContentUrlCount):\n fields[\"GameAssetsUrls\"].append(self.readString())\n\n EventUrlCount = self.readInt()\n fields[\"EventAssetsUrls\"] = []\n for i in range(EventUrlCount):\n fields[\"EventAssetsUrls\"].append(self.readString())\n\n fields[\"SecondsUntilAccountDeletion\"] = self.readVInt()\n fields[\"SupercellIDToken\"] = self.readCompressedString()\n fields[\"IsSupercellIDLogoutAllDevicesAllowed\"] = self.readBoolean()\n fields[\"isSupercellIDEligible\"] = self.readBoolean()\n fields[\"LineID\"] = self.readString()\n fields[\"SessionID\"] = self.readString()\n fields[\"KakaoID\"] = self.readString()\n fields[\"UpdateURL\"] = self.readString()\n fields[\"YoozooPayNotifyUrl\"] = self.readString()\n fields[\"UnbotifyEnabled\"] = self.readBoolean()\n\n Unknown1 = self.readBoolean()\n fields[\"Unknown1\"] = Unknown1\n if Unknown1:\n fields[\"Unknown2\"] = self.readString()\n\n Unknown3 = self.readBoolean()\n fields[\"Unknown3\"] = Unknown1\n if Unknown3:\n fields[\"Unknown4\"] = self.readString()\n\n Unknown5 = self.readBoolean()\n fields[\"Unknown5\"] = Unknown1\n if Unknown5:\n fields[\"Unknown6\"] = self.readString()\n\n Unknown7 = self.readBoolean()\n fields[\"Unknown7\"] = Unknown1\n if Unknown7:\n fields[\"Unknown8\"] = self.readString()\n super().decode(fields)\n return fields\n\n def execute(message, calling_instance, fields):\n pass\n\n def getMessageType(self):\n return 20104\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "OutOfSyncMessage", "path": "Heart/Packets/Server/Authentification/OutOfSyncMessage.py", "snippet": "class OutOfSyncMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields):\n self.writeVInt(fields[\"ServerChecksum\"])\n self.writeVInt(fields[\"ClientChecksum\"])\n self.writeVInt(fields[\"Tick\"])\n\n def decode(self):\n fields = {}\n fields[\"ServerChecksum\"] = self.readVInt()\n fields[\"ClientChecksum\"] = self.readVInt()\n fields[\"Tick\"] = self.readVInt()\n super().decode(fields)\n return fields\n\n def execute(message, calling_instance, fields):\n pass\n\n def getMessageType(self):\n return 24104\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "ServerHelloMessage", "path": "Heart/Packets/Server/Authentification/ServerHelloMessage.py", "snippet": "class ServerHelloMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields):\n self.writeBytes(urandom(24), 24)\n\n def decode(self):\n fields = {}\n fields[\"Random\"] = self.readBytesWithoutLength()\n super().decode(fields)\n return fields\n\n def execute(message, calling_instance, fields):\n pass\n\n def getMessageType(self):\n return 20100\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "BattleEndMessage", "path": "Heart/Packets/Server/Battle/BattleEndMessage.py", "snippet": "class BattleEndMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields, player):\n self.writeLong(0, 0) # Battle UUID High\n self.writeLong(0, 0) # Battle UUID Low\n self.writeVInt(2) # Battle End Game Mode (gametype)\n self.writeVInt(fields[\"Rank\"]) # Result (Victory/Defeat/Draw/Rank Score)\n self.writeVInt(0) # Tokens Gained (Gained Keys)\n self.writeVInt(0) # Trophies Result (Metascore change)\n self.writeVInt(0) # Power Play Points Gained (Pro League Points)\n self.writeVInt(0) # Doubled Tokens (Double Keys)\n self.writeVInt(0) # Double Token Event (Double Event Keys)\n self.writeVInt(0) # Token Doubler Remaining (Double Keys Remaining)\n self.writeVInt(0) # game Lenght In Seconds\n self.writeVInt(0) # Epic Win Power Play Points Gained (op Win Points)\n self.writeVInt(0) # Championship Level Reached (CC Wins)\n self.writeBoolean(False)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeBoolean(False)\n self.writeBoolean(False)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeBoolean(False)\n self.writeBoolean(False)\n self.writeBoolean(False)\n self.writeBoolean(True)\n self.writeBoolean(False)\n self.writeBoolean(False)\n self.writeBoolean(False)\n self.writeVInt(-1)\n self.writeBoolean(False)\n\n self.writeVInt(fields[\"HeroesCount\"])\n for heroEntry in fields[\"Heroes\"]:\n self.writeBoolean(heroEntry[\"IsPlayer\"])\n self.writeBoolean(bool(heroEntry[\"Team\"]))\n self.writeBoolean(bool(heroEntry[\"Team\"]))\n self.writeByte(1)\n for i in range(1):\n self.writeDataReference(heroEntry[\"Brawler\"][\"ID\"][0], heroEntry[\"Brawler\"][\"ID\"][1])\n self.writeByte(1)\n for i in range(1):\n if (heroEntry[\"Brawler\"][\"SkinID\"] is None):\n self.writeVInt(0)\n else:\n self.writeDataReference(heroEntry[\"Brawler\"][\"SkinID\"][0], heroEntry[\"Brawler\"][\"SkinID\"][1])\n self.writeByte(1)\n for i in range(1):\n self.writeVInt(1250)\n self.writeByte(1)\n for i in range(1):\n self.writeVInt(11)\n self.writeByte(1)\n for i in range(1):\n self.writeVInt(0)\n\n self.writeVInt(0)\n self.writeVInt(0)\n\n self.writeBoolean(heroEntry[\"IsPlayer\"])\n if heroEntry[\"IsPlayer\"]:\n self.writeLong(player.ID[0], player.ID[1])\n self.writeString(heroEntry[\"PlayerName\"])\n self.writeVInt(100)\n self.writeVInt(28000000)\n self.writeVInt(43000000)\n self.writeVInt(-2)\n if heroEntry[\"IsPlayer\"]:\n self.writeBoolean(True)\n self.writeVLong(5, 4181497)\n self.writeString('haccer club')\n self.writeDataReference(8, 16)\n else:\n self.writeBoolean(False)\n\n self.writeInt8(1)\n self.writeVInt(5978)\n self.writeInt8(1)\n self.writeVInt(0)\n\n self.writeInt16(5)\n self.writeInt16(3)\n self.writeInt(27328)\n self.writeInt(25659)\n\n self.writeDataReference(0)\n\n self.writeVInt(0)\n self.writeVInt(1)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeBoolean(False) # 0x0\n self.writeBoolean(False) # 0x0\n self.writeBoolean(False) # 0x0\n self.writeBoolean(False) # 0x0\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeBoolean(False) # 0x0\n self.writeVInt(0)\n self.writeBoolean(False) # 0x0\n self.writeVInt(0)\n self.writeBoolean(False) # 0x0\n self.writeBoolean(False) # 0x0\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeBoolean(False) # 0x0\n self.writeBoolean(False) # 0x0\n self.writeBoolean(False) # 0x0\n\n def decode(self):\n fields = {}\n return {}\n\n def execute(message, calling_instance, fields):\n pass\n\n def getMessageType(self):\n return 23456\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "AvailableServerCommandMessage", "path": "Heart/Packets/Server/Home/AvailableServerCommandMessage.py", "snippet": "class AvailableServerCommandMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields, player):\n self.writeVInt(fields[\"Command\"][\"ID\"])\n command = LogicCommandManager.createCommand(fields[\"Command\"][\"ID\"], self.messagePayload)\n self.messagePayload = command.encode(fields)\n\n def decode(self):\n return {}\n\n def execute(message, calling_instance, fields):\n pass\n\n def getMessageType(self):\n return 24111\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "LobbyInfoMessage", "path": "Heart/Packets/Server/Home/LobbyInfoMessage.py", "snippet": "class LobbyInfoMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields, player):\n self.writeVInt(ClientsManager.GetCount())\n self.writeString(f\"\"\"Version: {player.ClientVersion}\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\"\"\")\n self.writeVInt(0) # count event\n self.writeVInt(0) # new timer in v51\n\n def decode(self):\n fields = {}\n fields[\"PlayerCount\"] = self.readVInt()\n fields[\"Text\"] = self.readString()\n fields[\"Unk1\"] = self.readVInt()\n super().decode(fields)\n return {}\n\n def execute(message, calling_instance, fields):\n pass\n\n def getMessageType(self):\n return 23457\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "OwnHomeDataMessage", "path": "Heart/Packets/Server/Home/OwnHomeDataMessage.py", "snippet": "class OwnHomeDataMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields, player):\n self.writeVInt(1688816070)\n self.writeVInt(1191532375)\n self.writeVInt(2023189)\n self.writeVInt(73530)\n\n self.writeVInt(player.Trophies)\n self.writeVInt(player.HighestTrophies)\n self.writeVInt(player.HighestTrophies) \n self.writeVInt(player.TrophyRoadTier)\n self.writeVInt(player.Experience)\n self.writeDataReference(28, player.Thumbnail)\n self.writeDataReference(43, player.Namecolor)\n\n self.writeVInt(26)\n for x in range(26):\n self.writeVInt(x)\n\n self.writeVInt(0)\n\n self.writeVInt(0)\n\n self.writeVInt(0)\n \n self.writeVInt(len(player.OwnedSkins))\n for x in player.OwnedSkins:\n self.writeDataReference(29, x)\n\n self.writeVInt(0)\n\n self.writeVInt(0)\n\n self.writeVInt(0)\n self.writeVInt(player.HighestTrophies)\n self.writeVInt(0)\n self.writeVInt(2)\n self.writeBoolean(True)\n self.writeVInt(0)\n self.writeVInt(115)\n self.writeVInt(335442)\n self.writeVInt(1001442)\n self.writeVInt(5778642) \n\n self.writeVInt(120)\n self.writeVInt(200)\n self.writeVInt(0)\n\n self.writeBoolean(True)\n self.writeVInt(2)\n self.writeVInt(2)\n self.writeVInt(2)\n self.writeVInt(0)\n self.writeVInt(0)\n\n self.writeVInt(1) # Shop Offers\n\n self.writeVInt(1) # RewardCount\n\n self.writeVInt(38) # ItemType\n self.writeVInt(1337) # Amount\n self.writeDataReference(0) # CsvID\n self.writeVInt(0) # SkinID\n\n self.writeVInt(0) # Currency(0-Gems, 1-Gold, 3-StarpoInts)\n self.writeVInt(0) # Cost\n self.writeVInt(0) # Time\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeBoolean(False)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeBoolean(False) # Daily Offer\n self.writeVInt(0) # Old price\n self.writeString('Offer') # Text\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeString(\"offer_bgr_xmas23\") # Background\n self.writeVInt(0)\n self.writeBoolean(False) # This purchase is already being processed\n self.writeVInt(0) # Type Benefit\n self.writeVInt(0) # Benefit\n self.writeString()\n self.writeBoolean(False) # One time offer\n self.writeBoolean(False) # Claimed\n self.writeDataReference(0)\n self.writeDataReference(0)\n self.writeBoolean(False)\n self.writeBoolean(False)\n self.writeBoolean(False)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeBoolean(False)\n self.writeBoolean(False)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeBoolean(False)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n \n self.writeVInt(20)\n self.writeVInt(1428)\n\n self.writeVInt(0)\n\n self.writeVInt(1)\n self.writeVInt(30)\n\n self.writeByte(1) # count brawlers selected\n self.writeDataReference(16, player.SelectedBrawlers[0]) # selected brawler\n self.writeString(player.Region) # location\n self.writeString(player.ContentCreator) # supported creator\n\n self.writeVInt(6) \n self.writeVInt(1) \n self.writeVInt(9) \n self.writeVInt(1) \n self.writeVInt(22) \n self.writeVInt(3) \n self.writeVInt(25) \n self.writeVInt(1) \n self.writeVInt(24) \n self.writeVInt(0)\n self.writeVInt(15)\n self.writeVInt(32447)\n self.writeVInt(28)\n\n\n self.writeVInt(0)\n\n self.writeVInt(1)\n for season in range(1):\n self.writeVInt(22-1)\n self.writeVInt(40000)\n self.writeBoolean(True)\n self.writeVInt(0)\n self.writeBoolean(False)\n self.writeBoolean(True)\n self.writeInt(0)\n self.writeInt(0)\n self.writeInt(0)\n self.writeInt(0)\n self.writeBoolean(True)\n self.writeInt(0)\n self.writeInt(0)\n self.writeInt(0)\n self.writeInt(0)\n self.writeBoolean(True)\n self.writeBoolean(True)\n self.writeInt(0)\n self.writeInt(0)\n self.writeInt(0)\n self.writeInt(0)\n\n self.writeVInt(0)\n\n self.writeBoolean(True)\n self.writeVInt(0)\n self.writeVInt(1)\n self.writeVInt(2)\n self.writeVInt(0) \n\n self.writeBoolean(True) # Vanity items\n self.writeVInt(len(player.OwnedThumbnails)+len(player.OwnedPins))\n for x in player.OwnedThumbnails:\n self.writeVInt(28)\n self.writeVInt(x)\n self.writeVInt(0)\n for x in player.OwnedPins:\n self.writeVInt(52)\n self.writeVInt(x)\n self.writeVInt(0)\n\n\n self.writeBoolean(False) # Power league season data\n\n self.writeInt(0)\n self.writeVInt(0)\n self.writeVInt(16)\n self.writeVInt(76)\n self.writeBoolean(False)\n self.writeVInt(0)\n self.writeVInt(0)\n\n self.writeVInt(2023189)\n\n self.writeVInt(35) # event slot id\n self.writeVInt(1)\n self.writeVInt(2)\n self.writeVInt(3)\n self.writeVInt(4)\n self.writeVInt(5)\n self.writeVInt(6)\n self.writeVInt(7)\n self.writeVInt(8)\n self.writeVInt(9)\n self.writeVInt(10)\n self.writeVInt(11)\n self.writeVInt(12)\n self.writeVInt(13) \n self.writeVInt(14)\n self.writeVInt(15)\n self.writeVInt(16)\n self.writeVInt(17)\n self.writeVInt(18) \n self.writeVInt(19)\n self.writeVInt(20)\n self.writeVInt(21) \n self.writeVInt(22)\n self.writeVInt(23)\n self.writeVInt(24)\n self.writeVInt(25)\n self.writeVInt(26)\n self.writeVInt(27)\n self.writeVInt(28)\n self.writeVInt(29)\n self.writeVInt(30)\n self.writeVInt(31)\n self.writeVInt(32)\n self.writeVInt(33)\n self.writeVInt(34)\n self.writeVInt(35)\n\n self.writeVInt(1)\n\n self.writeVInt(4)\n self.writeVInt(7)\n self.writeVInt(1)\n self.writeVInt(0)\n self.writeVInt(72292)\n self.writeVInt(10) \n self.writeDataReference(15, 21) # map id\n self.writeVInt(-1)\n self.writeVInt(2)\n self.writeString(\"\")\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeBoolean(False) # MapMaker map structure array\n self.writeVInt(0)\n self.writeBoolean(False) # Power League array entry\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeBoolean(False)\n self.writeBoolean(False)\n self.writeBoolean(False)\n self.writeVInt(-1)\n self.writeBoolean(False)\n self.writeBoolean(False)\n self.writeVInt(-1)\n self.writeVInt(0) \n self.writeVInt(0) \n self.writeVInt(0) \n self.writeBoolean(False) \n\n self.writeVInt(0)\n \n ByteStreamHelper.encodeIntList(self, [20, 35, 75, 140, 290, 480, 800, 1250, 1875, 2800])\n ByteStreamHelper.encodeIntList(self, [30, 80, 170, 360]) # Shop Coins Price\n ByteStreamHelper.encodeIntList(self, [300, 880, 2040, 4680]) # Shop Coins Amount\n\n self.writeVInt(0) \n\n self.writeVInt(1)\n self.writeVInt(41000086) # theme\n self.writeVInt(1)\n\n self.writeVInt(0) \n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n\n self.writeVInt(2)\n self.writeVInt(1)\n self.writeVInt(2)\n self.writeVInt(2)\n self.writeVInt(1)\n self.writeVInt(-1)\n self.writeVInt(2)\n self.writeVInt(1)\n self.writeVInt(4)\n\n ByteStreamHelper.encodeIntList(self, [0, 29, 79, 169, 349, 699])\n ByteStreamHelper.encodeIntList(self, [0, 160, 450, 500, 1250, 2500])\n\n self.writeLong(0, 1) # Player ID\n\n self.writeVInt(0) # Notification factory\n \n self.writeVInt(1)\n self.writeBoolean(False)\n self.writeVInt(0)\n self.writeVInt(0) \n self.writeVInt(0)\n self.writeBoolean(False) # Login Calendar\n self.writeVInt(0)\n self.writeBoolean(True) # Starr Road\n for i in range(7):\n self.writeVInt(0)\n\n self.writeVInt(0) # Mastery\n\n #BattleCard\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeBoolean(False)\n self.writeBoolean(False)\n self.writeBoolean(False)\n self.writeBoolean(False)\n\n self.writeVInt(0) #Brawler's BattleCards\n\n self.writeVInt(5)\n for i in range(5):\n self.writeDataReference(80, i)\n self.writeVInt(-1)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeInt(0)\n self.writeVInt(0) \n self.writeVInt(0)\n self.writeVInt(86400*24)\n self.writeVInt(0)\n self.writeVInt(0)\n\n self.writeBoolean(False)\n\n # end LogicClientHome\n\n self.writeVLong(player.ID[0], player.ID[1])\n self.writeVLong(player.ID[0], player.ID[1])\n self.writeVLong(player.ID[0], player.ID[1])\n self.writeStringReference(player.Name)\n self.writeBoolean(player.Registered)\n self.writeInt(-1)\n\n self.writeVInt(17)\n unlocked_brawler = [i['CardID'] for x,i in player.OwnedBrawlers.items()]\n self.writeVInt(len(unlocked_brawler) + 2)\n for x in unlocked_brawler:\n self.writeDataReference(23, x)\n self.writeVInt(-1)\n self.writeVInt(1)\n\n self.writeDataReference(5, 8)\n self.writeVInt(-1)\n self.writeVInt(player.Coins)\n\n self.writeDataReference(5, 23)\n self.writeVInt(-1)\n self.writeVInt(player.Blings)\n\n self.writeVInt(len(player.OwnedBrawlers)) # HeroScore\n for x,i in player.OwnedBrawlers.items():\n self.writeDataReference(16, x)\n self.writeVInt(-1)\n self.writeVInt(i[\"Trophies\"])\n\n self.writeVInt(len(player.OwnedBrawlers)) # HeroHighScore\n for x,i in player.OwnedBrawlers.items():\n self.writeDataReference(16, x)\n self.writeVInt(-1)\n self.writeVInt(i[\"HighestTrophies\"])\n\n self.writeVInt(0) # Array\n\n self.writeVInt(0) # HeroPower\n \n self.writeVInt(len(player.OwnedBrawlers)) # HeroLevel\n for x,i in player.OwnedBrawlers.items():\n self.writeDataReference(16, x)\n self.writeVInt(-1)\n self.writeVInt(i[\"PowerLevel\"]-1)\n\n self.writeVInt(0) # hero star power gadget and hypercharge\n\n self.writeVInt(len(player.OwnedBrawlers)) # HeroSeenState\n for x,i in player.OwnedBrawlers.items():\n self.writeDataReference(16, x)\n self.writeVInt(-1)\n self.writeVInt(2)\n\n self.writeVInt(0) # Array\n self.writeVInt(0) # Array\n self.writeVInt(0) # Array\n self.writeVInt(0) # Array\n self.writeVInt(0) # Array\n self.writeVInt(0) # Array\n self.writeVInt(0) # Array\n self.writeVInt(0) # Array\n self.writeVInt(0) # Array\n\n self.writeVInt(player.Gems) # Diamonds\n self.writeVInt(player.Gems) # Free Diamonds\n self.writeVInt(10) # Player Level\n self.writeVInt(100)\n self.writeVInt(0) # CumulativePurchasedDiamonds or Avatar User Level Tier | 10000 < Level Tier = 3 | 1000 < Level Tier = 2 | 0 < Level Tier = 1\n self.writeVInt(100) # Battle Count\n self.writeVInt(10) # WinCount\n self.writeVInt(80) # LoseCount\n self.writeVInt(50) # WinLooseStreak\n self.writeVInt(20) # NpcWinCount\n self.writeVInt(0) # NpcLoseCount\n self.writeVInt(2) # TutorialState | shouldGoToFirstTutorialBattle = State == 0\n self.writeVInt(12)\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeString()\n self.writeVInt(0)\n self.writeVInt(0)\n self.writeVInt(1)\n\n def decode(self):\n fields = {}\n return fields\n\n def execute(message, calling_instance, fields):\n pass\n\n def getMessageType(self):\n return 24101\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "KeepAliveServerMessage", "path": "Heart/Packets/Server/Socket/KeepAliveServerMessage.py", "snippet": "class KeepAliveServerMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields):\n pass\n\n def decode(self):\n return {}\n\n def execute(message, calling_instance, fields):\n pass\n\n def getMessageType(self):\n return 20108\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "PlayerProfileMessage", "path": "Heart/Packets/Server/Home/PlayerProfileMessage.py", "snippet": "class PlayerProfileMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields, player):\n self.writeVLong(fields[\"PlayerHighID\"], fields[\"PlayerLowID\"])\n self.writeDataReference(16,11) # \n self.writeVInt(70)\n for i in range(70):\n self.writeDataReference(16, i)\n self.writeDataReference(0)\n self.writeVInt(500) # trophies\n self.writeVInt(1250) # highestTrophies\n self.writeVInt(11) #power level\n \n self.writeVInt(18)\n\n self.writeVInt(1) \n self.writeVInt(1) # 3v3 victories\n\n self.writeVInt(2)\n self.writeVInt(528859) # total exp\n\n self.writeVInt(3)\n self.writeVInt(3) # current trophies\n\n self.writeVInt(4)\n self.writeVInt(4) # highest trophies\n\n self.writeVInt(5) \n self.writeVInt(5) # unlocked brawler?\n\n self.writeVInt(8)\n self.writeVInt(6) # solo victories\n\n self.writeVInt(11) \n self.writeVInt(7) # duo victories\n\n self.writeVInt(9) \n self.writeVInt(8) # highest level robo rumble\n\n self.writeVInt(12) \n self.writeVInt(9) # highest level boss fight\n\n self.writeVInt(13)\n self.writeVInt(10) # highest power league points\n\n self.writeVInt(14)\n self.writeVInt(11) # some power league stuff\n\n self.writeVInt(15)\n self.writeVInt(12) # most challenge win\n\n self.writeVInt(16) #highest level city rampage\n self.writeVInt(13)\n\n self.writeVInt(18) #highest solo power league rank\n self.writeVInt(14)\n\n self.writeVInt(17) #highest team power league rank\n self.writeVInt(15)\n\n self.writeVInt(19) # highest Club league rank\n self.writeVInt(16)\n\n self.writeVInt(20) # number fame\n self.writeVInt(1000)\n\n self.writeVInt(21)\n self.writeVInt(502052) #v50\n\n self.writeString(player.Name) #PlayerInfo\n self.writeVInt(100)\n self.writeVInt(28000000 + player.Thumbnail)\n self.writeVInt(43000000 + player.Namecolor)\n self.writeVInt(14)\n\n self.writeBoolean(True)\n self.writeVInt(300)\n\n self.writeString(\"hello world\")\n self.writeVInt(100)\n self.writeVInt(200)\n self.writeDataReference(29, 558)\n self.writeDataReference(0)\n self.writeDataReference(0)\n self.writeDataReference(0)\n self.writeDataReference(0)\n\n self.writeBoolean(True) #alliance\n self.writeLong(0,1) #alliance ID\n self.writeString(\"haccers\") #alliance name\n self.writeDataReference(8,1) # alliance icon\n self.writeVInt(1) # type\n self.writeVInt(1) # member count\n self.writeVInt(10000) # total trophies\n self.writeVInt(1) # minimum trophies to enter\n self.writeDataReference(0)\n self.writeString(\"RU\") #location\n self.writeVInt(4) # unknown\n self.writeBoolean(True) #is Family friendly\n self.writeVInt(0)\n \n\n self.writeDataReference(25, 1) #alliance role\n self.writeVInt(16)\n\n def decode(self):\n pass\n # fields = {}\n # fields[\"PlayerCount\"] = self.readVInt()\n # fields[\"Text\"] = self.readString()\n # fields[\"Unk1\"] = self.readVInt()\n # super().decode(fields)\n return {}\n\n def execute(message, calling_instance, fields):\n pass\n\n def getMessageType(self):\n return 24113\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "MyAllianceMessage", "path": "Heart/Packets/Server/Home/MyAllianceMessage.py", "snippet": "class MyAllianceMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields, player):\n self.writeVInt(1) # Online people in alliance\n self.writeBoolean(True) # isInAlliance\n self.writeDataReference(25, 4)\n self.writeLong(0, 1) # alliance ID\n self.writeString(player.ContentCreator) # alliance name\n self.writeDataReference(8, 37) # alliance icon\n self.writeVInt(3) # type\n self.writeVInt(1) # member count\n self.writeVInt(9500) # total trophies\n self.writeVInt(1) # minimum trophies to enter\n self.writeVInt(0) # 0\n self.writeString('RU') # location\n self.writeVInt(3) # unknown\n self.writeBoolean(True) # isFamilyFriendly\n self.writeVInt(0)\n\n def decode(self):\n fields = {}\n super().decode(fields)\n return {}\n\n def execute(message, calling_instance, fields):\n pass\n\n def getMessageType(self):\n return 24399\n\n def getMessageVersion(self):\n return self.messageVersion" }, { "identifier": "AllianceDataMessage", "path": "Heart/Packets/Server/Home/AllianceDataMessage.py", "snippet": "class AllianceDataMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields, player):\n self.writeBoolean(True)\n\n self.writeLong(0, 1) # alliance ID\n self.writeString(player.ContentCreator) # alliance name\n self.writeDataReference(8, 37) # alliance icon\n self.writeVInt(1) # type\n self.writeVInt(1) # member count\n self.writeVInt(player.Trophies) # total trophies\n self.writeVInt(0) # minimum trophies to enter\n self.writeVInt(0) # 0\n self.writeString('RU') # location\n self.writeVInt(1) # people online\n self.writeBoolean(True) # isFamilyFriendly\n self.writeVInt(0)\n\n self.writeString(\"this is the hacciest club in the world\")\n\n self.writeVInt(1) # member count\n self.writeLong(player.ID[0], player.ID[1]) # player ID\n self.writeVInt(2) # role\n self.writeVInt(player.Trophies) # trophies\n self.writeVInt(0) # status: 0=offline 2=online\n self.writeVInt(1) # last connected time seconds ?\n highestPowerLeagueRank = 2\n self.writeVInt(highestPowerLeagueRank)\n if highestPowerLeagueRank != 0:\n self.writeVInt(2) #solo\n self.writeVInt(1) #duo\n self.writeBoolean(False) # boolean always false?\n\n self.writeString(player.Name) # player name\n self.writeVInt(100) # VInt always 100\n self.writeVInt(28000000 + player.Thumbnail) # thumbnail\n self.writeVInt(43000000 + player.Namecolor) # name color\n self.writeVInt(46000000 + player.Namecolor)\n\n self.writeVInt(-1) # most people have it -1 but some with something\n self.writeBoolean(False) # whats this ? only 2/30 people have it true in my club\n week = 58 # week 58 of club league as of 2023/07/05, this number is 0 if you just arrived in the club\n self.writeVInt(week)\n if week != 0: # club league week number?\n self.writeVInt(3) # day\n self.writeVInt(18) # total club trophies earned\n self.writeVInt(0) # event day club trophies earned\n self.writeVInt(8) # total tickets used\n self.writeVInt(0) # event day tickets used\n self.writeVInt(6) # event day max tickets\n self.writeVInt(6) # event day tickets left\n self.writeVInt(0) # event day player ranking\n self.writeBoolean(True) # everyone have it to true\n self.writeVInt(200) # player experience lvl but why tf it doesn't show for some people\n\n def decode(self):\n fields = {}\n super().decode(fields)\n return {}\n\n def execute(message, calling_instance, fields):\n pass\n\n def getMessageType(self):\n return 24301\n\n def getMessageVersion(self):\n return self.messageVersion" } ]
from Heart.Packets.Client.Authentification.ClientHelloMessage import ClientHelloMessage from Heart.Packets.Client.Authentification.LoginMessage import LoginMessage from Heart.Packets.Client.Battle.AskForBattleEndMessage import AskForBattleEndMessage from Heart.Packets.Client.Home.ChangeAvatarNameMessage import ChangeAvatarNameMessage from Heart.Packets.Client.Home.EndClientTurnMessage import EndClientTurnMessage from Heart.Packets.Client.Home.GoHomeFromOfflinePractiseMessage import GoHomeFromOfflinePractiseMessage from Heart.Packets.Client.Home.GoHomeMessage import GoHomeMessage from Heart.Packets.Client.Home.GetPlayerProfileMessage import GetPlayerProfileMessage from Heart.Packets.Client.Home.AskForAllianceDataMessage import AskForAllianceDataMessage from Heart.Packets.Client.Socket.KeepAliveMessage import KeepAliveMessage from Heart.Packets.Server.Authentification.LoginFailedMessage import LoginFailedMessage from Heart.Packets.Server.Authentification.LoginOkMessage import LoginOkMessage from Heart.Packets.Server.Authentification.OutOfSyncMessage import OutOfSyncMessage from Heart.Packets.Server.Authentification.ServerHelloMessage import ServerHelloMessage from Heart.Packets.Server.Battle.BattleEndMessage import BattleEndMessage from Heart.Packets.Server.Home.AvailableServerCommandMessage import AvailableServerCommandMessage from Heart.Packets.Server.Home.LobbyInfoMessage import LobbyInfoMessage from Heart.Packets.Server.Home.OwnHomeDataMessage import OwnHomeDataMessage from Heart.Packets.Server.Socket.KeepAliveServerMessage import KeepAliveServerMessage from Heart.Packets.Server.Home.PlayerProfileMessage import PlayerProfileMessage from Heart.Packets.Server.Home.MyAllianceMessage import MyAllianceMessage from Heart.Packets.Server.Home.AllianceDataMessage import AllianceDataMessage
16,888
14363: 'TeamSetLocationMessage', 14364: 'TeamReportChatMessage', 14365: 'TeamInviteMessage', 14366: 'PlayerStatusMessage', 14367: 'TeamClearInviteMessage', 14368: 'TeamInviteResponseMessage', 14369: 'TeamPremadeChatMessage', 14370: 'TeamAllianceMemberInviteMessage', 14371: 'TeamJoinOrCreateGameRoomMessage', 14372: 'TeamToggleSettingsMessage', 14373: 'TeamBotSlotDisableMessage', 14403: 'GetLeaderboardMessage', 14405: 'AskForAvatarStreamMessage', 14406: 'AskForBattleReplayStreamMessage', 14418: 'RemoveAvatarStreamEntryMessage', 14469: 'AlliancePremadeChatMessage', 14479: 'TeamInvitationResponseMessage', 14600: 'AvatarNameCheckRequestMessage', 14700: 'ListBrawlTvChannelsMessage', 14701: 'TuneBrawlTvChannelMessage', 14715: 'SendGlobalChatLineMessage', 14777: 'SetInvitesBlockedMessage', 14778: 'SetTeamChatMutedMessage', 14867: 'SetRegionMessage', 14880: 'TeamRequestJoinCancelMessage', 14881: 'TeamRequestJoinMessage', 14882: 'TeamRequestJoinApproveMessage', 15081: GetPlayerProfileMessage, #v50 15793: 'GetTokenFriendMessage', 16000: 'LogicDeviceLinkCodeRequestMessage', 16001: 'LogicDeviceLinkMenuClosedMessage', 16002: 'LogicDeviceLinkEnterCodeMessage', 16003: 'LogicDeviceLinkConfirmYesMessage', 16939: 'AskApiTokenMessage', 17000: 'LogicAccountTransferCodeRequestMessage', 17190: 'JoinAllianceUsingTokenMessage', 17337: 'UnbotifyReportMessage', 17338: 'AdjustPackageMessage', 17750: GoHomeFromOfflinePractiseMessage, #v50 18686: 'SetSupportedCreatorMessage', 19001: 'LatencyTestResultMessage', 19002: 'UdpLatencyTestRequestMessage', 19003: 'TriggerStartLatencyTestMessage', 19004: 'RequestLatencyTestStatusMessage', 20000: 'SetEncryptionMessage', 20100: ServerHelloMessage, 20101: 'CreateAccountOkMessage', 20103: LoginFailedMessage, 20104: LoginOkMessage, 20105: 'FriendListMessage', 20106: 'FriendListUpdateMessage', 20107: 'AddableFriendsMessage', 20108: KeepAliveServerMessage, 20109: 'FriendOnlineStatusMessage', 20110: 'FriendLoggedInMessage', 20111: 'FriendLoggedOutMessage', 20112: 'AddFriendFailedMessage', 20117: 'ReportUserStatusMessage', 20118: 'ChatAccountBanStatusMessage', 20121: 'BillingRequestFailedMessage', 20132: 'UnlockAccountOkMessage', 20133: 'UnlockAccountFailedMessage', 20151: 'AppleBillingProcessedByServerMessage', 20152: 'GoogleBillingProcessedByServerMessage', 20153: 'TencentBillingProcessedByServerMessage', 20154: 'CafeBazaarBillingProcessedByServerMessage', 20156: 'KunlunBillingProcessedByServerMessage', 20161: 'ShutdownStartedMessage', 20171: 'PersonalBreakStartedMessage', 20173: 'YoozooBillingProcessedByServerMessage', 20199: 'FriendSuggestionsMessage', 20205: 'AvatarNameChangeFailedMessage', 20206: 'AvatarOnlineStatusUpdated', 20207: 'AllianceOnlineStatusUpdatedMessage', 20300: 'AvatarNameCheckResponseMessage', 20402: 'CreateGameFailedMessage', 20405: 'MatchMakingStatusMessage', 20406: 'MatchMakingCancelledMessage', 20501: 'AcceptFriendFailedMessage', 20523: 'YoozooOrderAvailableMessage', 20545: 'YoozooOrderDeliveryFailedMessage', 20559: 'StartLoadingMessage', 20801: 'NotificationMessage', 20802: 'OpponentRejoinsMatchNotificationMessage', 20931: 'AntiAddictionDataUpdatedMessage', 22089: 'GetTokenFriendResultMessage', 22100: 'CreatePlayerMapResponseMessage', 22101: 'DeletePlayerMapResponseMessage', 22102: 'PlayerMapsMessage', 22103: 'UpdatePlayerMapResponseMessage', 22104: 'SubmitPlayerMapResponseMessage', 22105: 'PublishPlayerMapResponseMessage', 22106: 'ChangePlayerMapNameMResponseMessage', 22107: 'PlayerMapInfoUpdatedMessage', 22109: 'DebugPlayerMapReviewResultOverrideSetMessage', 22111: 'PlayerMapGreenlightedMessage', 22125: 'ReportPlayerMapResponseMessage', 22150: 'RankedMatchStartMessage', 22151: 'RankedMatchBanStartedMessage', 22152: 'RankedMatchBanHeroResponseMessage', 22153: 'RankedMatchBanEndedMessage', 22154: 'RankedMatchPickStartedMessage', 22155: 'RankedMatchPickHeroFailedMessage', 22156: 'RankedMatchHeroPickedMessage', 22157: 'RankedMatchHeroDataUpdatedMessage', 22158: 'RankedMatchFinalPreparationStartedMessage', 22159: 'RankedMatchTerminatedMessage', 22202: 'MapPreviewMessage', 22377: 'GoogleServiceAccountBoundMessage', 22687: 'GamecenterAccountAlreadyBoundMessage', 22957: 'PvpMatchmakeNotificationMessage', 23067: 'SCIDLogoutAllDevicesResultMessage', 23302: 'GetAllianceInviteTokenResultMessage', 23456: BattleEndMessage, 23457: LobbyInfoMessage, 23458: 'BattleLogMessage', 23459: 'BattleLogReplayAvailableMessage', 23494: 'GoogleServiceAccountAlreadyBoundMessage', 23774: 'PlayerJWTokenMessage', 24101: OwnHomeDataMessage,
class LogicLaserMessageFactory: messagesList = { 10055: 'AskPlayerJWTokenMessage', 10099: 'ClientCryptoErrorMessage', 10100: ClientHelloMessage, 10101: LoginMessage, 10102: 'LoginUsingSessionMessage', 10103: 'CreateAccountMessage', 10107: 'ClientCapabilitiesMessage', 10108: KeepAliveMessage, 10109: 'UdpCheckConnectionMessage', 10110: 'AnalyticEventMessage', 10111: 'AccountIdentifiersMessage', 10112: 'AuthenticationCheckMessage', 10113: 'SetDeviceTokenMessage', 10116: 'ResetAccountMessage', 10117: 'ReportUserMessage', 10118: 'AccountSwitchedMessage', 10119: 'ReportAllianceStreamMessage', 10121: 'UnlockAccountMessage', 10150: 'AppleBillingRequestMessage', 10151: 'GoogleBillingRequestMessage', 10152: 'TencentBillingRequestMessage', 10153: 'CafeBazaarBillingRequestMessage', 10159: 'KunlunBillingRequestMessage', 10160: 'BillingCancelledByClientMessage', 10177: 'ClientInfoMessage', 10212: ChangeAvatarNameMessage, 10309: 'GetAllianceInviteTokenMessage', 10321: 'AttributionEventMessage', 10401: 'CreateGameMessage', 10501: 'AcceptFriendMessage', 10502: 'AddFriendMessage', 10503: 'AskForAddableFriendsMessage', 10504: 'AskForFriendListMessage', 10506: 'RemoveFriendMessage', 10507: 'AddFriendByEmailMessage', 10509: 'AddFriendByAvatarNameAndCodeMessage', 10512: 'AskForPlayingGamecenterFriendsMessage', 10513: 'AskForPlayingFacebookFriendsMessage', 10514: 'AskForPlayingKakaoFriendsMessage', 10515: 'AskForPlayingTencentFriendsMessage', 10516: 'AskForPlayingLineFriendsMessage', 10517: 'AskForPlayingSupercellFriendsMessage', 10523: 'YoozooBillingRequestMessage', 10555: 'ClientInputMessage', 10576: 'SetBlockFriendRequestsMessage', 10599: 'AskForFriendSuggestionsMessage', 10636: 'SCIDBindAccountMessage', 11736: 'SCIDLogoutAllDevicesMessage', 12100: 'CreatePlayerMapMessage', 12101: 'DeletePlayerMapMessage', 12102: 'GetPlayerMapsMessage', 12103: 'UpdatePlayerMapMessage', 12104: 'SubmitPlayerMapMessage', 12105: 'PublishPlayerMapMessage', 12106: 'ChangePlayerMapNameMessage', 12107: 'EnterMapEditorMessage', 12108: 'GoHomeFromMapEditorMessage', 12110: 'TeamSetPlayerMapMessage', 12111: 'SignoffPlayerMapMessage', 12125: 'ReportPlayerMapMessage', 12152: 'RankedMatchBanHeroMessage', 12155: 'RankedMatchPickHeroMessage', 12157: 'RankedMatchUpdateHeroDataMessage', 12905: 'GetCurrentBattleReplayDataMessage', 12998: 'SetCountryMessage', 13922: 'AcceptTokenFriendMessage', 14101: GoHomeMessage, 14102: EndClientTurnMessage, 14103: 'StartGameMessage', 14104: 'StartSpectateMessage', 14105: 'HomeLogicStoppedMessage', 14106: 'CancelMatchmakingMessage', 14107: 'StopSpectateMessage', 14108: 'GoHomeFromSpectateMessage', #14109: GoHomeFromOfflinePractiseMessage, //before v50 14110: AskForBattleEndMessage, #14113: GetPlayerProfileMessage, //before v50 14114: 'GetBattleLogMessage', 14115: 'BattleLogViewReplayMessage', 14116: 'ViewReplayByStringMessage', 14117: 'RequestMatchCancelMessage', 14118: 'SinglePlayerMatchRequestMessage', 14166: 'ChronosEventSeenMessage', 14167: 'ChronosEventSeenMessage', 14177: 'PlayAgainMessage', 14178: 'DebugCommandMessage', 14199: 'LookForGameRoomRequestMessage', 14211: 'UnbindFacebookAccountMessage', 14201: 'BindFacebookAccountMessage', 14202: 'BindKakaoAccountMessage', 14203: 'BingLineAccountMessage', 14212: 'BindGamecenterAccountMessage', 14213: 'UnbindKakaoAccountMessage', 14214: 'UnbindLineAccountMessage', 14262: 'BindGoogleServiceAccountMessage', 14266: 'BindTencentAccountMessage', 14268: 'TencentCheckCanPayMessage', 14276: 'TencentAntiAddictionInstructionExecutedMessage', 14277: 'GetSeasonRewardsMessage', 14299: 'SetAllianceCountryMessage', 14301: 'CreateAllianceMessage', 14302: AskForAllianceDataMessage, 14303: 'AskForJoinableAlliancesListMessage', 14304: 'AskForAllianceStreamMessage', 14305: 'JoinAllianceMessage', 14306: 'ChangeAllianceMemberRoleMessage', 14307: 'KickAllianceMemberMessage', 14308: 'LeaveAllianceMessage', 14315: 'ChatToAllianceStreamMessage', 14316: 'ChangeAllianceSettingsMessage', 14317: 'RequestJoinAllianceMessage', 14321: 'RespondToAllianceJoinRequestMessage', 14322: 'SendAllianceInvitationMessage', 14323: 'JoinAllianceUsingInvitationMessage', 14324: 'SearchAlliancesMessage', 14326: 'SendAllianceInvitationToFriendMessage', 14330: 'SendAllianceMailMessage', 14350: 'TeamCreateMessage', 14351: 'TeamJoinMessage', 14352: 'TeamKickMessage', 14353: 'TeamLeaveMessage', 14354: 'TeamChangeMemberSettingsMessage', 14355: 'TeamSetMemberReadyMessage', 14356: 'TeamTogglePractiseMessage', 14357: 'TeamToggleMemberSideMessage', 14358: 'TeamSpectateMessage', 14359: 'TeamChatMessage', 14360: 'TeamPostAdMessage', 14361: 'TeamMemberStatusMessage', 14362: 'TeamSetEventMessage', 14363: 'TeamSetLocationMessage', 14364: 'TeamReportChatMessage', 14365: 'TeamInviteMessage', 14366: 'PlayerStatusMessage', 14367: 'TeamClearInviteMessage', 14368: 'TeamInviteResponseMessage', 14369: 'TeamPremadeChatMessage', 14370: 'TeamAllianceMemberInviteMessage', 14371: 'TeamJoinOrCreateGameRoomMessage', 14372: 'TeamToggleSettingsMessage', 14373: 'TeamBotSlotDisableMessage', 14403: 'GetLeaderboardMessage', 14405: 'AskForAvatarStreamMessage', 14406: 'AskForBattleReplayStreamMessage', 14418: 'RemoveAvatarStreamEntryMessage', 14469: 'AlliancePremadeChatMessage', 14479: 'TeamInvitationResponseMessage', 14600: 'AvatarNameCheckRequestMessage', 14700: 'ListBrawlTvChannelsMessage', 14701: 'TuneBrawlTvChannelMessage', 14715: 'SendGlobalChatLineMessage', 14777: 'SetInvitesBlockedMessage', 14778: 'SetTeamChatMutedMessage', 14867: 'SetRegionMessage', 14880: 'TeamRequestJoinCancelMessage', 14881: 'TeamRequestJoinMessage', 14882: 'TeamRequestJoinApproveMessage', 15081: GetPlayerProfileMessage, #v50 15793: 'GetTokenFriendMessage', 16000: 'LogicDeviceLinkCodeRequestMessage', 16001: 'LogicDeviceLinkMenuClosedMessage', 16002: 'LogicDeviceLinkEnterCodeMessage', 16003: 'LogicDeviceLinkConfirmYesMessage', 16939: 'AskApiTokenMessage', 17000: 'LogicAccountTransferCodeRequestMessage', 17190: 'JoinAllianceUsingTokenMessage', 17337: 'UnbotifyReportMessage', 17338: 'AdjustPackageMessage', 17750: GoHomeFromOfflinePractiseMessage, #v50 18686: 'SetSupportedCreatorMessage', 19001: 'LatencyTestResultMessage', 19002: 'UdpLatencyTestRequestMessage', 19003: 'TriggerStartLatencyTestMessage', 19004: 'RequestLatencyTestStatusMessage', 20000: 'SetEncryptionMessage', 20100: ServerHelloMessage, 20101: 'CreateAccountOkMessage', 20103: LoginFailedMessage, 20104: LoginOkMessage, 20105: 'FriendListMessage', 20106: 'FriendListUpdateMessage', 20107: 'AddableFriendsMessage', 20108: KeepAliveServerMessage, 20109: 'FriendOnlineStatusMessage', 20110: 'FriendLoggedInMessage', 20111: 'FriendLoggedOutMessage', 20112: 'AddFriendFailedMessage', 20117: 'ReportUserStatusMessage', 20118: 'ChatAccountBanStatusMessage', 20121: 'BillingRequestFailedMessage', 20132: 'UnlockAccountOkMessage', 20133: 'UnlockAccountFailedMessage', 20151: 'AppleBillingProcessedByServerMessage', 20152: 'GoogleBillingProcessedByServerMessage', 20153: 'TencentBillingProcessedByServerMessage', 20154: 'CafeBazaarBillingProcessedByServerMessage', 20156: 'KunlunBillingProcessedByServerMessage', 20161: 'ShutdownStartedMessage', 20171: 'PersonalBreakStartedMessage', 20173: 'YoozooBillingProcessedByServerMessage', 20199: 'FriendSuggestionsMessage', 20205: 'AvatarNameChangeFailedMessage', 20206: 'AvatarOnlineStatusUpdated', 20207: 'AllianceOnlineStatusUpdatedMessage', 20300: 'AvatarNameCheckResponseMessage', 20402: 'CreateGameFailedMessage', 20405: 'MatchMakingStatusMessage', 20406: 'MatchMakingCancelledMessage', 20501: 'AcceptFriendFailedMessage', 20523: 'YoozooOrderAvailableMessage', 20545: 'YoozooOrderDeliveryFailedMessage', 20559: 'StartLoadingMessage', 20801: 'NotificationMessage', 20802: 'OpponentRejoinsMatchNotificationMessage', 20931: 'AntiAddictionDataUpdatedMessage', 22089: 'GetTokenFriendResultMessage', 22100: 'CreatePlayerMapResponseMessage', 22101: 'DeletePlayerMapResponseMessage', 22102: 'PlayerMapsMessage', 22103: 'UpdatePlayerMapResponseMessage', 22104: 'SubmitPlayerMapResponseMessage', 22105: 'PublishPlayerMapResponseMessage', 22106: 'ChangePlayerMapNameMResponseMessage', 22107: 'PlayerMapInfoUpdatedMessage', 22109: 'DebugPlayerMapReviewResultOverrideSetMessage', 22111: 'PlayerMapGreenlightedMessage', 22125: 'ReportPlayerMapResponseMessage', 22150: 'RankedMatchStartMessage', 22151: 'RankedMatchBanStartedMessage', 22152: 'RankedMatchBanHeroResponseMessage', 22153: 'RankedMatchBanEndedMessage', 22154: 'RankedMatchPickStartedMessage', 22155: 'RankedMatchPickHeroFailedMessage', 22156: 'RankedMatchHeroPickedMessage', 22157: 'RankedMatchHeroDataUpdatedMessage', 22158: 'RankedMatchFinalPreparationStartedMessage', 22159: 'RankedMatchTerminatedMessage', 22202: 'MapPreviewMessage', 22377: 'GoogleServiceAccountBoundMessage', 22687: 'GamecenterAccountAlreadyBoundMessage', 22957: 'PvpMatchmakeNotificationMessage', 23067: 'SCIDLogoutAllDevicesResultMessage', 23302: 'GetAllianceInviteTokenResultMessage', 23456: BattleEndMessage, 23457: LobbyInfoMessage, 23458: 'BattleLogMessage', 23459: 'BattleLogReplayAvailableMessage', 23494: 'GoogleServiceAccountAlreadyBoundMessage', 23774: 'PlayerJWTokenMessage', 24101: OwnHomeDataMessage,
24104: OutOfSyncMessage,
12
2023-12-14 18:57:56+00:00
24k
GXNU-ZhongLab/ODTrack
lib/train/base_functions.py
[ { "identifier": "Lasot", "path": "lib/train/dataset/lasot.py", "snippet": "class Lasot(BaseVideoDataset):\n \"\"\" LaSOT dataset.\n\n Publication:\n LaSOT: A High-quality Benchmark for Large-scale Single Object Tracking\n Heng Fan, Liting Lin, Fan Yang, Peng Chu, Ge Deng, Sijia Yu, Hexin Bai, Yong Xu, Chunyuan Liao and Haibin Ling\n CVPR, 2019\n https://arxiv.org/pdf/1809.07845.pdf\n\n Download the dataset from https://cis.temple.edu/lasot/download.html\n \"\"\"\n\n def __init__(self, root=None, image_loader=jpeg4py_loader, vid_ids=None, split=None, data_fraction=None):\n \"\"\"\n args:\n root - path to the lasot dataset.\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\n is used by default.\n vid_ids - List containing the ids of the videos (1 - 20) used for training. If vid_ids = [1, 3, 5], then the\n videos with subscripts -1, -3, and -5 from each class will be used for training.\n split - If split='train', the official train split (protocol-II) is used for training. Note: Only one of\n vid_ids or split option can be used at a time.\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\n \"\"\"\n root = env_settings().lasot_dir if root is None else root\n super().__init__('LaSOT', root, image_loader)\n\n # Keep a list of all classes\n self.class_list = [f for f in os.listdir(self.root)]\n self.class_to_id = {cls_name: cls_id for cls_id, cls_name in enumerate(self.class_list)}\n\n self.sequence_list = self._build_sequence_list(vid_ids, split)\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))\n\n self.seq_per_class = self._build_class_list()\n\n def _build_sequence_list(self, vid_ids=None, split=None):\n if split is not None:\n if vid_ids is not None:\n raise ValueError('Cannot set both split_name and vid_ids.')\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\n if split == 'train':\n file_path = os.path.join(ltr_path, 'data_specs', 'lasot_train_split.txt')\n else:\n raise ValueError('Unknown split name.')\n # sequence_list = pandas.read_csv(file_path, header=None, squeeze=True).values.tolist()\n sequence_list = pandas.read_csv(file_path, header=None).squeeze(\"columns\").values.tolist()\n elif vid_ids is not None:\n sequence_list = [c+'-'+str(v) for c in self.class_list for v in vid_ids]\n else:\n raise ValueError('Set either split_name or vid_ids.')\n\n return sequence_list\n\n def _build_class_list(self):\n seq_per_class = {}\n for seq_id, seq_name in enumerate(self.sequence_list):\n class_name = seq_name.split('-')[0]\n if class_name in seq_per_class:\n seq_per_class[class_name].append(seq_id)\n else:\n seq_per_class[class_name] = [seq_id]\n\n return seq_per_class\n\n def get_name(self):\n return 'lasot'\n\n def has_class_info(self):\n return True\n\n def has_occlusion_info(self):\n return True\n\n def get_num_sequences(self):\n return len(self.sequence_list)\n\n def get_num_classes(self):\n return len(self.class_list)\n\n def get_sequences_in_class(self, class_name):\n return self.seq_per_class[class_name]\n\n def _read_bb_anno(self, seq_path):\n bb_anno_file = os.path.join(seq_path, \"groundtruth.txt\")\n gt = pandas.read_csv(bb_anno_file, delimiter=',', header=None, dtype=np.float32, na_filter=False, low_memory=False).values\n return torch.tensor(gt)\n\n def _read_target_visible(self, seq_path):\n # Read full occlusion and out_of_view\n occlusion_file = os.path.join(seq_path, \"full_occlusion.txt\")\n out_of_view_file = os.path.join(seq_path, \"out_of_view.txt\")\n\n with open(occlusion_file, 'r', newline='') as f:\n occlusion = torch.ByteTensor([int(v) for v in list(csv.reader(f))[0]])\n with open(out_of_view_file, 'r') as f:\n out_of_view = torch.ByteTensor([int(v) for v in list(csv.reader(f))[0]])\n\n target_visible = ~occlusion & ~out_of_view\n\n return target_visible\n\n def _get_sequence_path(self, seq_id):\n seq_name = self.sequence_list[seq_id]\n class_name = seq_name.split('-')[0]\n vid_id = seq_name.split('-')[1]\n\n return os.path.join(self.root, class_name, class_name + '-' + vid_id)\n\n def get_sequence_info(self, seq_id):\n seq_path = self._get_sequence_path(seq_id)\n bbox = self._read_bb_anno(seq_path)\n\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\n visible = self._read_target_visible(seq_path) & valid.byte()\n\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\n\n def _get_frame_path(self, seq_path, frame_id):\n return os.path.join(seq_path, 'img', '{:08}.jpg'.format(frame_id+1)) # frames start from 1\n\n def _get_frame(self, seq_path, frame_id):\n return self.image_loader(self._get_frame_path(seq_path, frame_id))\n\n def _get_class(self, seq_path):\n raw_class = seq_path.split('/')[-2]\n return raw_class\n\n def get_class_name(self, seq_id):\n seq_path = self._get_sequence_path(seq_id)\n obj_class = self._get_class(seq_path)\n\n return obj_class\n\n def get_frames(self, seq_id, frame_ids, anno=None):\n seq_path = self._get_sequence_path(seq_id)\n\n obj_class = self._get_class(seq_path)\n frame_list = [self._get_frame(seq_path, f_id) for f_id in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\n\n object_meta = OrderedDict({'object_class_name': obj_class,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n\n return frame_list, anno_frames, object_meta" }, { "identifier": "Got10k", "path": "lib/train/dataset/got10k.py", "snippet": "class Got10k(BaseVideoDataset):\n \"\"\" GOT-10k dataset.\n\n Publication:\n GOT-10k: A Large High-Diversity Benchmark for Generic Object Tracking in the Wild\n Lianghua Huang, Xin Zhao, and Kaiqi Huang\n arXiv:1810.11981, 2018\n https://arxiv.org/pdf/1810.11981.pdf\n\n Download dataset from http://got-10k.aitestunion.com/downloads\n \"\"\"\n\n def __init__(self, root=None, image_loader=jpeg4py_loader, split=None, seq_ids=None, data_fraction=None):\n \"\"\"\n args:\n root - path to the got-10k training data. Note: This should point to the 'train' folder inside GOT-10k\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\n is used by default.\n split - 'train' or 'val'. Note: The validation split here is a subset of the official got-10k train split,\n not NOT the official got-10k validation split. To use the official validation split, provide that as\n the root folder instead.\n seq_ids - List containing the ids of the videos to be used for training. Note: Only one of 'split' or 'seq_ids'\n options can be used at the same time.\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\n \"\"\"\n root = env_settings().got10k_dir if root is None else root\n super().__init__('GOT10k', root, image_loader)\n\n # all folders inside the root\n self.sequence_list = self._get_sequence_list()\n\n # seq_id is the index of the folder inside the got10k root path\n if split is not None:\n if seq_ids is not None:\n raise ValueError('Cannot set both split_name and seq_ids.')\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\n if split == 'train':\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_train_split.txt')\n elif split == 'val':\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_val_split.txt')\n elif split == 'train_full':\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_train_full_split.txt')\n elif split == 'vottrain':\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_vot_train_split.txt')\n elif split == 'votval':\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_vot_val_split.txt')\n else:\n raise ValueError('Unknown split name.')\n # seq_ids = pandas.read_csv(file_path, header=None, squeeze=True, dtype=np.int64).values.tolist()\n seq_ids = pandas.read_csv(file_path, header=None, dtype=np.int64).squeeze(\"columns\").values.tolist()\n elif seq_ids is None:\n seq_ids = list(range(0, len(self.sequence_list)))\n\n self.sequence_list = [self.sequence_list[i] for i in seq_ids]\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))\n\n self.sequence_meta_info = self._load_meta_info()\n self.seq_per_class = self._build_seq_per_class()\n\n self.class_list = list(self.seq_per_class.keys())\n self.class_list.sort()\n\n def get_name(self):\n return 'got10k'\n\n def has_class_info(self):\n return True\n\n def has_occlusion_info(self):\n return True\n\n def _load_meta_info(self):\n sequence_meta_info = {s: self._read_meta(os.path.join(self.root, s)) for s in self.sequence_list}\n return sequence_meta_info\n\n def _read_meta(self, seq_path):\n try:\n with open(os.path.join(seq_path, 'meta_info.ini')) as f:\n meta_info = f.readlines()\n object_meta = OrderedDict({'object_class_name': meta_info[5].split(': ')[-1][:-1],\n 'motion_class': meta_info[6].split(': ')[-1][:-1],\n 'major_class': meta_info[7].split(': ')[-1][:-1],\n 'root_class': meta_info[8].split(': ')[-1][:-1],\n 'motion_adverb': meta_info[9].split(': ')[-1][:-1]})\n except:\n object_meta = OrderedDict({'object_class_name': None,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n return object_meta\n\n def _build_seq_per_class(self):\n seq_per_class = {}\n\n for i, s in enumerate(self.sequence_list):\n object_class = self.sequence_meta_info[s]['object_class_name']\n if object_class in seq_per_class:\n seq_per_class[object_class].append(i)\n else:\n seq_per_class[object_class] = [i]\n\n return seq_per_class\n\n def get_sequences_in_class(self, class_name):\n return self.seq_per_class[class_name]\n\n def _get_sequence_list(self):\n with open(os.path.join(self.root, 'list.txt')) as f:\n dir_list = list(csv.reader(f))\n dir_list = [dir_name[0] for dir_name in dir_list]\n return dir_list\n\n def _read_bb_anno(self, seq_path):\n bb_anno_file = os.path.join(seq_path, \"groundtruth.txt\")\n gt = pandas.read_csv(bb_anno_file, delimiter=',', header=None, dtype=np.float32, na_filter=False, low_memory=False).values\n return torch.tensor(gt)\n\n def _read_target_visible(self, seq_path):\n # Read full occlusion and out_of_view\n occlusion_file = os.path.join(seq_path, \"absence.label\")\n cover_file = os.path.join(seq_path, \"cover.label\")\n\n with open(occlusion_file, 'r', newline='') as f:\n occlusion = torch.ByteTensor([int(v[0]) for v in csv.reader(f)])\n with open(cover_file, 'r', newline='') as f:\n cover = torch.ByteTensor([int(v[0]) for v in csv.reader(f)])\n\n target_visible = ~occlusion & (cover>0).byte()\n\n visible_ratio = cover.float() / 8\n return target_visible, visible_ratio\n\n def _get_sequence_path(self, seq_id):\n return os.path.join(self.root, self.sequence_list[seq_id])\n\n def get_sequence_info(self, seq_id):\n seq_path = self._get_sequence_path(seq_id)\n bbox = self._read_bb_anno(seq_path)\n\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\n visible, visible_ratio = self._read_target_visible(seq_path)\n visible = visible & valid.byte()\n\n return {'bbox': bbox, 'valid': valid, 'visible': visible, 'visible_ratio': visible_ratio}\n\n def _get_frame_path(self, seq_path, frame_id):\n return os.path.join(seq_path, '{:08}.jpg'.format(frame_id+1)) # frames start from 1\n\n def _get_frame(self, seq_path, frame_id):\n return self.image_loader(self._get_frame_path(seq_path, frame_id))\n\n def get_class_name(self, seq_id):\n obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]\n\n return obj_meta['object_class_name']\n\n def get_frames(self, seq_id, frame_ids, anno=None):\n seq_path = self._get_sequence_path(seq_id)\n obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]\n\n frame_list = [self._get_frame(seq_path, f_id) for f_id in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\n\n return frame_list, anno_frames, obj_meta" }, { "identifier": "TrackingNet", "path": "lib/train/dataset/tracking_net.py", "snippet": "class TrackingNet(BaseVideoDataset):\n \"\"\" TrackingNet dataset.\n\n Publication:\n TrackingNet: A Large-Scale Dataset and Benchmark for Object Tracking in the Wild.\n Matthias Mueller,Adel Bibi, Silvio Giancola, Salman Al-Subaihi and Bernard Ghanem\n ECCV, 2018\n https://ivul.kaust.edu.sa/Documents/Publications/2018/TrackingNet%20A%20Large%20Scale%20Dataset%20and%20Benchmark%20for%20Object%20Tracking%20in%20the%20Wild.pdf\n\n Download the dataset using the toolkit https://github.com/SilvioGiancola/TrackingNet-devkit.\n \"\"\"\n def __init__(self, root=None, image_loader=jpeg4py_loader, set_ids=None, data_fraction=None):\n \"\"\"\n args:\n root - The path to the TrackingNet folder, containing the training sets.\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\n is used by default.\n set_ids (None) - List containing the ids of the TrackingNet sets to be used for training. If None, all the\n sets (0 - 11) will be used.\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\n \"\"\"\n root = env_settings().trackingnet_dir if root is None else root\n super().__init__('TrackingNet', root, image_loader)\n\n if set_ids is None:\n set_ids = [i for i in range(12)]\n\n self.set_ids = set_ids\n\n # Keep a list of all videos. Sequence list is a list of tuples (set_id, video_name) containing the set_id and\n # video_name for each sequence\n self.sequence_list = list_sequences(self.root, self.set_ids)\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\n\n self.seq_to_class_map, self.seq_per_class = self._load_class_info()\n\n # we do not have the class_lists for the tracking net\n self.class_list = list(self.seq_per_class.keys())\n self.class_list.sort()\n\n def _load_class_info(self):\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\n class_map_path = os.path.join(ltr_path, 'data_specs', 'trackingnet_classmap.txt')\n\n with open(class_map_path, 'r') as f:\n seq_to_class_map = {seq_class.split('\\t')[0]: seq_class.rstrip().split('\\t')[1] for seq_class in f}\n\n seq_per_class = {}\n for i, seq in enumerate(self.sequence_list):\n class_name = seq_to_class_map.get(seq[1], 'Unknown')\n if class_name not in seq_per_class:\n seq_per_class[class_name] = [i]\n else:\n seq_per_class[class_name].append(i)\n\n return seq_to_class_map, seq_per_class\n\n def get_name(self):\n return 'trackingnet'\n\n def has_class_info(self):\n return True\n\n def get_sequences_in_class(self, class_name):\n return self.seq_per_class[class_name]\n\n def _read_bb_anno(self, seq_id):\n set_id = self.sequence_list[seq_id][0]\n vid_name = self.sequence_list[seq_id][1]\n bb_anno_file = os.path.join(self.root, \"TRAIN_\" + str(set_id), \"anno\", vid_name + \".txt\")\n gt = pandas.read_csv(bb_anno_file, delimiter=',', header=None, dtype=np.float32, na_filter=False,\n low_memory=False).values\n return torch.tensor(gt)\n\n def get_sequence_info(self, seq_id):\n bbox = self._read_bb_anno(seq_id)\n\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\n visible = valid.clone().byte()\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\n\n def _get_frame(self, seq_id, frame_id):\n set_id = self.sequence_list[seq_id][0]\n vid_name = self.sequence_list[seq_id][1]\n frame_path = os.path.join(self.root, \"TRAIN_\" + str(set_id), \"frames\", vid_name, str(frame_id) + \".jpg\")\n return self.image_loader(frame_path)\n\n def _get_class(self, seq_id):\n seq_name = self.sequence_list[seq_id][1]\n return self.seq_to_class_map[seq_name]\n\n def get_class_name(self, seq_id):\n obj_class = self._get_class(seq_id)\n\n return obj_class\n\n def get_frames(self, seq_id, frame_ids, anno=None):\n frame_list = [self._get_frame(seq_id, f) for f in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\n\n obj_class = self._get_class(seq_id)\n\n object_meta = OrderedDict({'object_class_name': obj_class,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n\n return frame_list, anno_frames, object_meta" }, { "identifier": "ImagenetVID", "path": "lib/train/dataset/imagenetvid.py", "snippet": "class ImagenetVID(BaseVideoDataset):\n \"\"\" Imagenet VID dataset.\n\n Publication:\n ImageNet Large Scale Visual Recognition Challenge\n Olga Russakovsky, Jia Deng, Hao Su, Jonathan Krause, Sanjeev Satheesh, Sean Ma, Zhiheng Huang, Andrej Karpathy,\n Aditya Khosla, Michael Bernstein, Alexander C. Berg and Li Fei-Fei\n IJCV, 2015\n https://arxiv.org/pdf/1409.0575.pdf\n\n Download the dataset from http://image-net.org/\n \"\"\"\n def __init__(self, root=None, image_loader=jpeg4py_loader, min_length=0, max_target_area=1):\n \"\"\"\n args:\n root - path to the imagenet vid dataset.\n image_loader (default_image_loader) - The function to read the images. If installed,\n jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,\n opencv's imread is used.\n min_length - Minimum allowed sequence length.\n max_target_area - max allowed ratio between target area and image area. Can be used to filter out targets\n which cover complete image.\n \"\"\"\n root = env_settings().imagenet_dir if root is None else root\n super().__init__(\"imagenetvid\", root, image_loader)\n\n cache_file = os.path.join(root, 'cache.json')\n if os.path.isfile(cache_file):\n # If available, load the pre-processed cache file containing meta-info for each sequence\n with open(cache_file, 'r') as f:\n sequence_list_dict = json.load(f)\n\n self.sequence_list = sequence_list_dict\n else:\n # Else process the imagenet annotations and generate the cache file\n self.sequence_list = self._process_anno(root)\n\n with open(cache_file, 'w') as f:\n json.dump(self.sequence_list, f)\n\n # Filter the sequences based on min_length and max_target_area in the first frame\n self.sequence_list = [x for x in self.sequence_list if len(x['anno']) >= min_length and\n get_target_to_image_ratio(x) < max_target_area]\n\n def get_name(self):\n return 'imagenetvid'\n\n def get_num_sequences(self):\n return len(self.sequence_list)\n\n def get_sequence_info(self, seq_id):\n bb_anno = torch.Tensor(self.sequence_list[seq_id]['anno'])\n valid = (bb_anno[:, 2] > 0) & (bb_anno[:, 3] > 0)\n visible = torch.ByteTensor(self.sequence_list[seq_id]['target_visible']) & valid.byte()\n return {'bbox': bb_anno, 'valid': valid, 'visible': visible}\n\n def _get_frame(self, sequence, frame_id):\n set_name = 'ILSVRC2015_VID_train_{:04d}'.format(sequence['set_id'])\n vid_name = 'ILSVRC2015_train_{:08d}'.format(sequence['vid_id'])\n frame_number = frame_id + sequence['start_frame']\n frame_path = os.path.join(self.root, 'Data', 'VID', 'train', set_name, vid_name,\n '{:06d}.JPEG'.format(frame_number))\n return self.image_loader(frame_path)\n\n def get_frames(self, seq_id, frame_ids, anno=None):\n sequence = self.sequence_list[seq_id]\n\n frame_list = [self._get_frame(sequence, f) for f in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n # Create anno dict\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\n\n # added the class info to the meta info\n object_meta = OrderedDict({'object_class': sequence['class_name'],\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n\n return frame_list, anno_frames, object_meta\n\n def _process_anno(self, root):\n # Builds individual tracklets\n base_vid_anno_path = os.path.join(root, 'Annotations', 'VID', 'train')\n\n all_sequences = []\n for set in sorted(os.listdir(base_vid_anno_path)):\n set_id = int(set.split('_')[-1])\n for vid in sorted(os.listdir(os.path.join(base_vid_anno_path, set))):\n\n vid_id = int(vid.split('_')[-1])\n anno_files = sorted(os.listdir(os.path.join(base_vid_anno_path, set, vid)))\n\n frame1_anno = ET.parse(os.path.join(base_vid_anno_path, set, vid, anno_files[0]))\n image_size = [int(frame1_anno.find('size/width').text), int(frame1_anno.find('size/height').text)]\n\n objects = [ET.ElementTree(file=os.path.join(base_vid_anno_path, set, vid, f)).findall('object')\n for f in anno_files]\n\n tracklets = {}\n\n # Find all tracklets along with start frame\n for f_id, all_targets in enumerate(objects):\n for target in all_targets:\n tracklet_id = target.find('trackid').text\n if tracklet_id not in tracklets:\n tracklets[tracklet_id] = f_id\n\n for tracklet_id, tracklet_start in tracklets.items():\n tracklet_anno = []\n target_visible = []\n class_name_id = None\n\n for f_id in range(tracklet_start, len(objects)):\n found = False\n for target in objects[f_id]:\n if target.find('trackid').text == tracklet_id:\n if not class_name_id:\n class_name_id = target.find('name').text\n x1 = int(target.find('bndbox/xmin').text)\n y1 = int(target.find('bndbox/ymin').text)\n x2 = int(target.find('bndbox/xmax').text)\n y2 = int(target.find('bndbox/ymax').text)\n\n tracklet_anno.append([x1, y1, x2 - x1, y2 - y1])\n target_visible.append(target.find('occluded').text == '0')\n\n found = True\n break\n if not found:\n break\n\n new_sequence = {'set_id': set_id, 'vid_id': vid_id, 'class_name': class_name_id,\n 'start_frame': tracklet_start, 'anno': tracklet_anno,\n 'target_visible': target_visible, 'image_size': image_size}\n all_sequences.append(new_sequence)\n\n return all_sequences" }, { "identifier": "MSCOCOSeq", "path": "lib/train/dataset/coco_seq.py", "snippet": "class MSCOCOSeq(BaseVideoDataset):\n \"\"\" The COCO dataset. COCO is an image dataset. Thus, we treat each image as a sequence of length 1.\n\n Publication:\n Microsoft COCO: Common Objects in Context.\n Tsung-Yi Lin, Michael Maire, Serge J. Belongie, Lubomir D. Bourdev, Ross B. Girshick, James Hays, Pietro Perona,\n Deva Ramanan, Piotr Dollar and C. Lawrence Zitnick\n ECCV, 2014\n https://arxiv.org/pdf/1405.0312.pdf\n\n Download the images along with annotations from http://cocodataset.org/#download. The root folder should be\n organized as follows.\n - coco_root\n - annotations\n - instances_train2014.json\n - instances_train2017.json\n - images\n - train2014\n - train2017\n\n Note: You also have to install the coco pythonAPI from https://github.com/cocodataset/cocoapi.\n \"\"\"\n\n def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None, split=\"train\", version=\"2014\"):\n \"\"\"\n args:\n root - path to the coco dataset.\n image_loader (default_image_loader) - The function to read the images. If installed,\n jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,\n opencv's imread is used.\n data_fraction (None) - Fraction of images to be used. The images are selected randomly. If None, all the\n images will be used\n split - 'train' or 'val'.\n version - version of coco dataset (2014 or 2017)\n \"\"\"\n root = env_settings().coco_dir if root is None else root\n super().__init__('COCO', root, image_loader)\n\n self.img_pth = os.path.join(root, 'images/{}{}/'.format(split, version))\n self.anno_path = os.path.join(root, 'annotations/instances_{}{}.json'.format(split, version))\n\n # Load the COCO set.\n self.coco_set = COCO(self.anno_path)\n\n self.cats = self.coco_set.cats\n\n self.class_list = self.get_class_list()\n\n self.sequence_list = self._get_sequence_list()\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))\n self.seq_per_class = self._build_seq_per_class()\n\n def _get_sequence_list(self):\n ann_list = list(self.coco_set.anns.keys())\n seq_list = [a for a in ann_list if self.coco_set.anns[a]['iscrowd'] == 0]\n\n return seq_list\n\n def is_video_sequence(self):\n return False\n\n def get_num_classes(self):\n return len(self.class_list)\n\n def get_name(self):\n return 'coco'\n\n def has_class_info(self):\n return True\n\n def get_class_list(self):\n class_list = []\n for cat_id in self.cats.keys():\n class_list.append(self.cats[cat_id]['name'])\n return class_list\n\n def has_segmentation_info(self):\n return True\n\n def get_num_sequences(self):\n return len(self.sequence_list)\n\n def _build_seq_per_class(self):\n seq_per_class = {}\n for i, seq in enumerate(self.sequence_list):\n class_name = self.cats[self.coco_set.anns[seq]['category_id']]['name']\n if class_name not in seq_per_class:\n seq_per_class[class_name] = [i]\n else:\n seq_per_class[class_name].append(i)\n\n return seq_per_class\n\n def get_sequences_in_class(self, class_name):\n return self.seq_per_class[class_name]\n\n def get_sequence_info(self, seq_id):\n anno = self._get_anno(seq_id)\n\n bbox = torch.Tensor(anno['bbox']).view(1, 4)\n\n mask = torch.Tensor(self.coco_set.annToMask(anno)).unsqueeze(dim=0)\n\n '''2021.1.3 To avoid too small bounding boxes. Here we change the threshold to 50 pixels'''\n valid = (bbox[:, 2] > 50) & (bbox[:, 3] > 50)\n\n visible = valid.clone().byte()\n\n return {'bbox': bbox, 'mask': mask, 'valid': valid, 'visible': visible}\n\n def _get_anno(self, seq_id):\n anno = self.coco_set.anns[self.sequence_list[seq_id]]\n\n return anno\n\n def _get_frames(self, seq_id):\n path = self.coco_set.loadImgs([self.coco_set.anns[self.sequence_list[seq_id]]['image_id']])[0]['file_name']\n img = self.image_loader(os.path.join(self.img_pth, path))\n return img\n\n def get_meta_info(self, seq_id):\n try:\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\n object_meta = OrderedDict({'object_class_name': cat_dict_current['name'],\n 'motion_class': None,\n 'major_class': cat_dict_current['supercategory'],\n 'root_class': None,\n 'motion_adverb': None})\n except:\n object_meta = OrderedDict({'object_class_name': None,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n return object_meta\n\n\n def get_class_name(self, seq_id):\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\n return cat_dict_current['name']\n\n def get_frames(self, seq_id=None, frame_ids=None, anno=None):\n # COCO is an image dataset. Thus we replicate the image denoted by seq_id len(frame_ids) times, and return a\n # list containing these replicated images.\n frame = self._get_frames(seq_id)\n\n frame_list = [frame.copy() for _ in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[0, ...] for _ in frame_ids]\n\n object_meta = self.get_meta_info(seq_id)\n\n return frame_list, anno_frames, object_meta" }, { "identifier": "Got10k_lmdb", "path": "lib/train/dataset/got10k_lmdb.py", "snippet": "class Got10k_lmdb(BaseVideoDataset):\n\n def __init__(self, root=None, image_loader=jpeg4py_loader, split=None, seq_ids=None, data_fraction=None):\n \"\"\"\n args:\n root - path to the got-10k training data. Note: This should point to the 'train' folder inside GOT-10k\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\n is used by default.\n split - 'train' or 'val'. Note: The validation split here is a subset of the official got-10k train split,\n not NOT the official got-10k validation split. To use the official validation split, provide that as\n the root folder instead.\n seq_ids - List containing the ids of the videos to be used for training. Note: Only one of 'split' or 'seq_ids'\n options can be used at the same time.\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\n use_lmdb - whether the dataset is stored in lmdb format\n \"\"\"\n root = env_settings().got10k_lmdb_dir if root is None else root\n super().__init__('GOT10k_lmdb', root, image_loader)\n\n # all folders inside the root\n self.sequence_list = self._get_sequence_list()\n\n # seq_id is the index of the folder inside the got10k root path\n if split is not None:\n if seq_ids is not None:\n raise ValueError('Cannot set both split_name and seq_ids.')\n train_lib_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\n if split == 'train':\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_train_split.txt')\n elif split == 'val':\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_val_split.txt')\n elif split == 'train_full':\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_train_full_split.txt')\n elif split == 'vottrain':\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_vot_train_split.txt')\n elif split == 'votval':\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_vot_val_split.txt')\n else:\n raise ValueError('Unknown split name.')\n seq_ids = pandas.read_csv(file_path, header=None, squeeze=True, dtype=np.int64).values.tolist()\n elif seq_ids is None:\n seq_ids = list(range(0, len(self.sequence_list)))\n\n self.sequence_list = [self.sequence_list[i] for i in seq_ids]\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))\n\n self.sequence_meta_info = self._load_meta_info()\n self.seq_per_class = self._build_seq_per_class()\n\n self.class_list = list(self.seq_per_class.keys())\n self.class_list.sort()\n\n def get_name(self):\n return 'got10k_lmdb'\n\n def has_class_info(self):\n return True\n\n def has_occlusion_info(self):\n return True\n\n def _load_meta_info(self):\n def _read_meta(meta_info):\n\n object_meta = OrderedDict({'object_class_name': meta_info[5].split(': ')[-1],\n 'motion_class': meta_info[6].split(': ')[-1],\n 'major_class': meta_info[7].split(': ')[-1],\n 'root_class': meta_info[8].split(': ')[-1],\n 'motion_adverb': meta_info[9].split(': ')[-1]})\n\n return object_meta\n sequence_meta_info = {}\n for s in self.sequence_list:\n try:\n meta_str = decode_str(self.root, \"train/%s/meta_info.ini\" %s)\n sequence_meta_info[s] = _read_meta(meta_str.split('\\n'))\n except:\n sequence_meta_info[s] = OrderedDict({'object_class_name': None,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n return sequence_meta_info\n\n def _build_seq_per_class(self):\n seq_per_class = {}\n\n for i, s in enumerate(self.sequence_list):\n object_class = self.sequence_meta_info[s]['object_class_name']\n if object_class in seq_per_class:\n seq_per_class[object_class].append(i)\n else:\n seq_per_class[object_class] = [i]\n\n return seq_per_class\n\n def get_sequences_in_class(self, class_name):\n return self.seq_per_class[class_name]\n\n def _get_sequence_list(self):\n dir_str = decode_str(self.root, 'train/list.txt')\n dir_list = dir_str.split('\\n')\n return dir_list\n\n def _read_bb_anno(self, seq_path):\n bb_anno_file = os.path.join(seq_path, \"groundtruth.txt\")\n gt_str_list = decode_str(self.root, bb_anno_file).split('\\n')[:-1] # the last line in got10k is empty\n gt_list = [list(map(float, line.split(','))) for line in gt_str_list]\n gt_arr = np.array(gt_list).astype(np.float32)\n\n return torch.tensor(gt_arr)\n\n def _read_target_visible(self, seq_path):\n # full occlusion and out_of_view files\n occlusion_file = os.path.join(seq_path, \"absence.label\")\n cover_file = os.path.join(seq_path, \"cover.label\")\n # Read these files\n occ_list = list(map(int, decode_str(self.root, occlusion_file).split('\\n')[:-1])) # the last line in got10k is empty\n occlusion = torch.ByteTensor(occ_list)\n cover_list = list(map(int, decode_str(self.root, cover_file).split('\\n')[:-1])) # the last line in got10k is empty\n cover = torch.ByteTensor(cover_list)\n\n target_visible = ~occlusion & (cover>0).byte()\n\n visible_ratio = cover.float() / 8\n return target_visible, visible_ratio\n\n def _get_sequence_path(self, seq_id):\n return os.path.join(\"train\", self.sequence_list[seq_id])\n\n def get_sequence_info(self, seq_id):\n seq_path = self._get_sequence_path(seq_id)\n bbox = self._read_bb_anno(seq_path)\n\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\n visible, visible_ratio = self._read_target_visible(seq_path)\n visible = visible & valid.byte()\n\n return {'bbox': bbox, 'valid': valid, 'visible': visible, 'visible_ratio': visible_ratio}\n\n def _get_frame_path(self, seq_path, frame_id):\n return os.path.join(seq_path, '{:08}.jpg'.format(frame_id+1)) # frames start from 1\n\n def _get_frame(self, seq_path, frame_id):\n return decode_img(self.root, self._get_frame_path(seq_path, frame_id))\n\n def get_class_name(self, seq_id):\n obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]\n\n return obj_meta['object_class_name']\n\n def get_frames(self, seq_id, frame_ids, anno=None):\n seq_path = self._get_sequence_path(seq_id)\n obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]\n\n frame_list = [self._get_frame(seq_path, f_id) for f_id in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\n\n return frame_list, anno_frames, obj_meta" }, { "identifier": "Lasot_lmdb", "path": "lib/train/dataset/lasot_lmdb.py", "snippet": "class Lasot_lmdb(BaseVideoDataset):\n\n def __init__(self, root=None, image_loader=jpeg4py_loader, vid_ids=None, split=None, data_fraction=None):\n \"\"\"\n args:\n root - path to the lasot dataset.\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\n is used by default.\n vid_ids - List containing the ids of the videos (1 - 20) used for training. If vid_ids = [1, 3, 5], then the\n videos with subscripts -1, -3, and -5 from each class will be used for training.\n split - If split='train', the official train split (protocol-II) is used for training. Note: Only one of\n vid_ids or split option can be used at a time.\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\n \"\"\"\n root = env_settings().lasot_lmdb_dir if root is None else root\n super().__init__('LaSOT_lmdb', root, image_loader)\n\n self.sequence_list = self._build_sequence_list(vid_ids, split)\n class_list = [seq_name.split('-')[0] for seq_name in self.sequence_list]\n self.class_list = []\n for ele in class_list:\n if ele not in self.class_list:\n self.class_list.append(ele)\n # Keep a list of all classes\n self.class_to_id = {cls_name: cls_id for cls_id, cls_name in enumerate(self.class_list)}\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))\n\n self.seq_per_class = self._build_class_list()\n\n def _build_sequence_list(self, vid_ids=None, split=None):\n if split is not None:\n if vid_ids is not None:\n raise ValueError('Cannot set both split_name and vid_ids.')\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\n if split == 'train':\n file_path = os.path.join(ltr_path, 'data_specs', 'lasot_train_split.txt')\n else:\n raise ValueError('Unknown split name.')\n sequence_list = pandas.read_csv(file_path, header=None, squeeze=True).values.tolist()\n elif vid_ids is not None:\n sequence_list = [c+'-'+str(v) for c in self.class_list for v in vid_ids]\n else:\n raise ValueError('Set either split_name or vid_ids.')\n\n return sequence_list\n\n def _build_class_list(self):\n seq_per_class = {}\n for seq_id, seq_name in enumerate(self.sequence_list):\n class_name = seq_name.split('-')[0]\n if class_name in seq_per_class:\n seq_per_class[class_name].append(seq_id)\n else:\n seq_per_class[class_name] = [seq_id]\n\n return seq_per_class\n\n def get_name(self):\n return 'lasot_lmdb'\n\n def has_class_info(self):\n return True\n\n def has_occlusion_info(self):\n return True\n\n def get_num_sequences(self):\n return len(self.sequence_list)\n\n def get_num_classes(self):\n return len(self.class_list)\n\n def get_sequences_in_class(self, class_name):\n return self.seq_per_class[class_name]\n\n def _read_bb_anno(self, seq_path):\n bb_anno_file = os.path.join(seq_path, \"groundtruth.txt\")\n gt_str_list = decode_str(self.root, bb_anno_file).split('\\n')[:-1] # the last line is empty\n gt_list = [list(map(float, line.split(','))) for line in gt_str_list]\n gt_arr = np.array(gt_list).astype(np.float32)\n return torch.tensor(gt_arr)\n\n def _read_target_visible(self, seq_path):\n # Read full occlusion and out_of_view\n occlusion_file = os.path.join(seq_path, \"full_occlusion.txt\")\n out_of_view_file = os.path.join(seq_path, \"out_of_view.txt\")\n\n occ_list = list(map(int, decode_str(self.root, occlusion_file).split(',')))\n occlusion = torch.ByteTensor(occ_list)\n out_view_list = list(map(int, decode_str(self.root, out_of_view_file).split(',')))\n out_of_view = torch.ByteTensor(out_view_list)\n\n target_visible = ~occlusion & ~out_of_view\n\n return target_visible\n\n def _get_sequence_path(self, seq_id):\n seq_name = self.sequence_list[seq_id]\n class_name = seq_name.split('-')[0]\n vid_id = seq_name.split('-')[1]\n\n return os.path.join(class_name, class_name + '-' + vid_id)\n\n def get_sequence_info(self, seq_id):\n seq_path = self._get_sequence_path(seq_id)\n bbox = self._read_bb_anno(seq_path)\n\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\n visible = self._read_target_visible(seq_path) & valid.byte()\n\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\n\n def _get_frame_path(self, seq_path, frame_id):\n return os.path.join(seq_path, 'img', '{:08}.jpg'.format(frame_id+1)) # frames start from 1\n\n def _get_frame(self, seq_path, frame_id):\n return decode_img(self.root, self._get_frame_path(seq_path, frame_id))\n\n def _get_class(self, seq_path):\n raw_class = seq_path.split('/')[-2]\n return raw_class\n\n def get_class_name(self, seq_id):\n seq_path = self._get_sequence_path(seq_id)\n obj_class = self._get_class(seq_path)\n\n return obj_class\n\n def get_frames(self, seq_id, frame_ids, anno=None):\n seq_path = self._get_sequence_path(seq_id)\n\n obj_class = self._get_class(seq_path)\n frame_list = [self._get_frame(seq_path, f_id) for f_id in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\n\n object_meta = OrderedDict({'object_class_name': obj_class,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n\n return frame_list, anno_frames, object_meta" }, { "identifier": "ImagenetVID_lmdb", "path": "lib/train/dataset/imagenetvid_lmdb.py", "snippet": "class ImagenetVID_lmdb(BaseVideoDataset):\n \"\"\" Imagenet VID dataset.\n\n Publication:\n ImageNet Large Scale Visual Recognition Challenge\n Olga Russakovsky, Jia Deng, Hao Su, Jonathan Krause, Sanjeev Satheesh, Sean Ma, Zhiheng Huang, Andrej Karpathy,\n Aditya Khosla, Michael Bernstein, Alexander C. Berg and Li Fei-Fei\n IJCV, 2015\n https://arxiv.org/pdf/1409.0575.pdf\n\n Download the dataset from http://image-net.org/\n \"\"\"\n def __init__(self, root=None, image_loader=jpeg4py_loader, min_length=0, max_target_area=1):\n \"\"\"\n args:\n root - path to the imagenet vid dataset.\n image_loader (default_image_loader) - The function to read the images. If installed,\n jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,\n opencv's imread is used.\n min_length - Minimum allowed sequence length.\n max_target_area - max allowed ratio between target area and image area. Can be used to filter out targets\n which cover complete image.\n \"\"\"\n root = env_settings().imagenet_dir if root is None else root\n super().__init__(\"imagenetvid_lmdb\", root, image_loader)\n\n sequence_list_dict = decode_json(root, \"cache.json\")\n self.sequence_list = sequence_list_dict\n\n # Filter the sequences based on min_length and max_target_area in the first frame\n self.sequence_list = [x for x in self.sequence_list if len(x['anno']) >= min_length and\n get_target_to_image_ratio(x) < max_target_area]\n\n def get_name(self):\n return 'imagenetvid_lmdb'\n\n def get_num_sequences(self):\n return len(self.sequence_list)\n\n def get_sequence_info(self, seq_id):\n bb_anno = torch.Tensor(self.sequence_list[seq_id]['anno'])\n valid = (bb_anno[:, 2] > 0) & (bb_anno[:, 3] > 0)\n visible = torch.ByteTensor(self.sequence_list[seq_id]['target_visible']) & valid.byte()\n return {'bbox': bb_anno, 'valid': valid, 'visible': visible}\n\n def _get_frame(self, sequence, frame_id):\n set_name = 'ILSVRC2015_VID_train_{:04d}'.format(sequence['set_id'])\n vid_name = 'ILSVRC2015_train_{:08d}'.format(sequence['vid_id'])\n frame_number = frame_id + sequence['start_frame']\n frame_path = os.path.join('Data', 'VID', 'train', set_name, vid_name,\n '{:06d}.JPEG'.format(frame_number))\n return decode_img(self.root, frame_path)\n\n def get_frames(self, seq_id, frame_ids, anno=None):\n sequence = self.sequence_list[seq_id]\n\n frame_list = [self._get_frame(sequence, f) for f in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n # Create anno dict\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\n\n # added the class info to the meta info\n object_meta = OrderedDict({'object_class': sequence['class_name'],\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n\n return frame_list, anno_frames, object_meta" }, { "identifier": "MSCOCOSeq_lmdb", "path": "lib/train/dataset/coco_seq_lmdb.py", "snippet": "class MSCOCOSeq_lmdb(BaseVideoDataset):\n \"\"\" The COCO dataset. COCO is an image dataset. Thus, we treat each image as a sequence of length 1.\n\n Publication:\n Microsoft COCO: Common Objects in Context.\n Tsung-Yi Lin, Michael Maire, Serge J. Belongie, Lubomir D. Bourdev, Ross B. Girshick, James Hays, Pietro Perona,\n Deva Ramanan, Piotr Dollar and C. Lawrence Zitnick\n ECCV, 2014\n https://arxiv.org/pdf/1405.0312.pdf\n\n Download the images along with annotations from http://cocodataset.org/#download. The root folder should be\n organized as follows.\n - coco_root\n - annotations\n - instances_train2014.json\n - instances_train2017.json\n - images\n - train2014\n - train2017\n\n Note: You also have to install the coco pythonAPI from https://github.com/cocodataset/cocoapi.\n \"\"\"\n\n def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None, split=\"train\", version=\"2014\"):\n \"\"\"\n args:\n root - path to the coco dataset.\n image_loader (default_image_loader) - The function to read the images. If installed,\n jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,\n opencv's imread is used.\n data_fraction (None) - Fraction of images to be used. The images are selected randomly. If None, all the\n images will be used\n split - 'train' or 'val'.\n version - version of coco dataset (2014 or 2017)\n \"\"\"\n root = env_settings().coco_dir if root is None else root\n super().__init__('COCO_lmdb', root, image_loader)\n self.root = root\n self.img_pth = 'images/{}{}/'.format(split, version)\n self.anno_path = 'annotations/instances_{}{}.json'.format(split, version)\n\n # Load the COCO set.\n print('loading annotations into memory...')\n tic = time.time()\n coco_json = decode_json(root, self.anno_path)\n print('Done (t={:0.2f}s)'.format(time.time() - tic))\n\n self.coco_set = COCO(coco_json)\n\n self.cats = self.coco_set.cats\n\n self.class_list = self.get_class_list()\n\n self.sequence_list = self._get_sequence_list()\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))\n self.seq_per_class = self._build_seq_per_class()\n\n def _get_sequence_list(self):\n ann_list = list(self.coco_set.anns.keys())\n seq_list = [a for a in ann_list if self.coco_set.anns[a]['iscrowd'] == 0]\n\n return seq_list\n\n def is_video_sequence(self):\n return False\n\n def get_num_classes(self):\n return len(self.class_list)\n\n def get_name(self):\n return 'coco_lmdb'\n\n def has_class_info(self):\n return True\n\n def get_class_list(self):\n class_list = []\n for cat_id in self.cats.keys():\n class_list.append(self.cats[cat_id]['name'])\n return class_list\n\n def has_segmentation_info(self):\n return True\n\n def get_num_sequences(self):\n return len(self.sequence_list)\n\n def _build_seq_per_class(self):\n seq_per_class = {}\n for i, seq in enumerate(self.sequence_list):\n class_name = self.cats[self.coco_set.anns[seq]['category_id']]['name']\n if class_name not in seq_per_class:\n seq_per_class[class_name] = [i]\n else:\n seq_per_class[class_name].append(i)\n\n return seq_per_class\n\n def get_sequences_in_class(self, class_name):\n return self.seq_per_class[class_name]\n\n def get_sequence_info(self, seq_id):\n anno = self._get_anno(seq_id)\n\n bbox = torch.Tensor(anno['bbox']).view(1, 4)\n\n mask = torch.Tensor(self.coco_set.annToMask(anno)).unsqueeze(dim=0)\n\n '''2021.1.3 To avoid too small bounding boxes. Here we change the threshold to 50 pixels'''\n valid = (bbox[:, 2] > 50) & (bbox[:, 3] > 50)\n\n visible = valid.clone().byte()\n\n return {'bbox': bbox, 'mask': mask, 'valid': valid, 'visible': visible}\n\n def _get_anno(self, seq_id):\n anno = self.coco_set.anns[self.sequence_list[seq_id]]\n\n return anno\n\n def _get_frames(self, seq_id):\n path = self.coco_set.loadImgs([self.coco_set.anns[self.sequence_list[seq_id]]['image_id']])[0]['file_name']\n # img = self.image_loader(os.path.join(self.img_pth, path))\n img = decode_img(self.root, os.path.join(self.img_pth, path))\n return img\n\n def get_meta_info(self, seq_id):\n try:\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\n object_meta = OrderedDict({'object_class_name': cat_dict_current['name'],\n 'motion_class': None,\n 'major_class': cat_dict_current['supercategory'],\n 'root_class': None,\n 'motion_adverb': None})\n except:\n object_meta = OrderedDict({'object_class_name': None,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n return object_meta\n\n\n def get_class_name(self, seq_id):\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\n return cat_dict_current['name']\n\n def get_frames(self, seq_id=None, frame_ids=None, anno=None):\n # COCO is an image dataset. Thus we replicate the image denoted by seq_id len(frame_ids) times, and return a\n # list containing these replicated images.\n frame = self._get_frames(seq_id)\n\n frame_list = [frame.copy() for _ in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[0, ...] for _ in frame_ids]\n\n object_meta = self.get_meta_info(seq_id)\n\n return frame_list, anno_frames, object_meta" }, { "identifier": "TrackingNet_lmdb", "path": "lib/train/dataset/tracking_net_lmdb.py", "snippet": "class TrackingNet_lmdb(BaseVideoDataset):\n \"\"\" TrackingNet dataset.\n\n Publication:\n TrackingNet: A Large-Scale Dataset and Benchmark for Object Tracking in the Wild.\n Matthias Mueller,Adel Bibi, Silvio Giancola, Salman Al-Subaihi and Bernard Ghanem\n ECCV, 2018\n https://ivul.kaust.edu.sa/Documents/Publications/2018/TrackingNet%20A%20Large%20Scale%20Dataset%20and%20Benchmark%20for%20Object%20Tracking%20in%20the%20Wild.pdf\n\n Download the dataset using the toolkit https://github.com/SilvioGiancola/TrackingNet-devkit.\n \"\"\"\n def __init__(self, root=None, image_loader=jpeg4py_loader, set_ids=None, data_fraction=None):\n \"\"\"\n args:\n root - The path to the TrackingNet folder, containing the training sets.\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\n is used by default.\n set_ids (None) - List containing the ids of the TrackingNet sets to be used for training. If None, all the\n sets (0 - 11) will be used.\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\n \"\"\"\n root = env_settings().trackingnet_lmdb_dir if root is None else root\n super().__init__('TrackingNet_lmdb', root, image_loader)\n\n if set_ids is None:\n set_ids = [i for i in range(12)]\n\n self.set_ids = set_ids\n\n # Keep a list of all videos. Sequence list is a list of tuples (set_id, video_name) containing the set_id and\n # video_name for each sequence\n self.sequence_list = list_sequences(self.root)\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\n\n self.seq_to_class_map, self.seq_per_class = self._load_class_info()\n\n # we do not have the class_lists for the tracking net\n self.class_list = list(self.seq_per_class.keys())\n self.class_list.sort()\n\n def _load_class_info(self):\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\n class_map_path = os.path.join(ltr_path, 'data_specs', 'trackingnet_classmap.txt')\n\n with open(class_map_path, 'r') as f:\n seq_to_class_map = {seq_class.split('\\t')[0]: seq_class.rstrip().split('\\t')[1] for seq_class in f}\n\n seq_per_class = {}\n for i, seq in enumerate(self.sequence_list):\n class_name = seq_to_class_map.get(seq[1], 'Unknown')\n if class_name not in seq_per_class:\n seq_per_class[class_name] = [i]\n else:\n seq_per_class[class_name].append(i)\n\n return seq_to_class_map, seq_per_class\n\n def get_name(self):\n return 'trackingnet_lmdb'\n\n def has_class_info(self):\n return True\n\n def get_sequences_in_class(self, class_name):\n return self.seq_per_class[class_name]\n\n def _read_bb_anno(self, seq_id):\n set_id = self.sequence_list[seq_id][0]\n vid_name = self.sequence_list[seq_id][1]\n gt_str_list = decode_str(os.path.join(self.root, \"TRAIN_%d_lmdb\" % set_id),\n os.path.join(\"anno\", vid_name + \".txt\")).split('\\n')[:-1]\n gt_list = [list(map(float, line.split(','))) for line in gt_str_list]\n gt_arr = np.array(gt_list).astype(np.float32)\n return torch.tensor(gt_arr)\n\n def get_sequence_info(self, seq_id):\n bbox = self._read_bb_anno(seq_id)\n\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\n visible = valid.clone().byte()\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\n\n def _get_frame(self, seq_id, frame_id):\n set_id = self.sequence_list[seq_id][0]\n vid_name = self.sequence_list[seq_id][1]\n return decode_img(os.path.join(self.root, \"TRAIN_%d_lmdb\" % set_id),\n os.path.join(\"frames\", vid_name, str(frame_id) + \".jpg\"))\n\n def _get_class(self, seq_id):\n seq_name = self.sequence_list[seq_id][1]\n return self.seq_to_class_map[seq_name]\n\n def get_class_name(self, seq_id):\n obj_class = self._get_class(seq_id)\n\n return obj_class\n\n def get_frames(self, seq_id, frame_ids, anno=None):\n frame_list = [self._get_frame(seq_id, f) for f in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\n\n obj_class = self._get_class(seq_id)\n\n object_meta = OrderedDict({'object_class_name': obj_class,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n\n return frame_list, anno_frames, object_meta" }, { "identifier": "sampler", "path": "lib/train/data/sampler.py", "snippet": "def no_processing(data):\n def __init__(self, datasets, p_datasets, samples_per_epoch, max_gap,\n num_search_frames, num_template_frames=1, processing=no_processing, frame_sample_mode='causal',\n train_cls=False, pos_prob=0.5):\n def __len__(self):\n def _sample_visible_ids(self, visible, num_ids=1, min_id=None, max_id=None,\n allow_invisible=False, force_invisible=False):\n def __getitem__(self, index):\n def getitem(self):\n def getitem_cls(self):\n def get_center_box(self, H, W, ratio=1/8):\n def sample_seq_from_dataset(self, dataset, is_video_dataset):\n def get_one_search(self):\n def get_frame_ids_trident(self, visible):\n def get_frame_ids_stark(self, visible, valid):\nclass TrackingSampler(torch.utils.data.Dataset):\n H, W, _ = template_frames[0].shape\n H, W, _ = template_frames[0].shape\n H, W, _ = search_frames[0].shape" }, { "identifier": "processing", "path": "lib/train/data/processing.py", "snippet": "def stack_tensors(x):\n def __init__(self, transform=transforms.ToTensor(), template_transform=None, search_transform=None, joint_transform=None):\n def __call__(self, data: TensorDict):\n def __init__(self, search_area_factor, output_sz, center_jitter_factor, scale_jitter_factor,\n mode='pair', settings=None, *args, **kwargs):\n def _get_jittered_box(self, box, mode):\n def __call__(self, data: TensorDict):\nclass BaseProcessing:\nclass STARKProcessing(BaseProcessing):" }, { "identifier": "LTRLoader", "path": "lib/train/data/loader.py", "snippet": "class LTRLoader(torch.utils.data.dataloader.DataLoader):\n \"\"\"\n Data loader. Combines a dataset and a sampler, and provides\n single- or multi-process iterators over the dataset.\n\n Note: The only difference with default pytorch DataLoader is that an additional option stack_dim is available to\n select along which dimension the data should be stacked to form a batch.\n\n Arguments:\n dataset (Dataset): dataset from which to load the data.\n batch_size (int, optional): how many samples per batch to load\n (default: 1).\n shuffle (bool, optional): set to ``True`` to have the data reshuffled\n at every epoch (default: False).\n sampler (Sampler, optional): defines the strategy to draw samples from\n the dataset. If specified, ``shuffle`` must be False.\n batch_sampler (Sampler, optional): like sampler, but returns a batch of\n indices at a time. Mutually exclusive with batch_size, shuffle,\n sampler, and drop_last.\n num_workers (int, optional): how many subprocesses to use for data\n loading. 0 means that the data will be loaded in the main process.\n (default: 0)\n collate_fn (callable, optional): merges a list of samples to form a mini-batch.\n stack_dim (int): Dimension along which to stack to form the batch. (default: 0)\n pin_memory (bool, optional): If ``True``, the data loader will copy tensors\n into CUDA pinned memory before returning them.\n drop_last (bool, optional): set to ``True`` to drop the last incomplete batch,\n if the dataset size is not divisible by the batch size. If ``False`` and\n the size of dataset is not divisible by the batch size, then the last batch\n will be smaller. (default: False)\n timeout (numeric, optional): if positive, the timeout value for collecting a batch\n from workers. Should always be non-negative. (default: 0)\n worker_init_fn (callable, optional): If not None, this will be called on each\n worker subprocess with the worker id (an int in ``[0, num_workers - 1]``) as\n input, after seeding and before data loading. (default: None)\n\n .. note:: By default, each worker will have its PyTorch seed set to\n ``base_seed + worker_id``, where ``base_seed`` is a long generated\n by main process using its RNG. However, seeds for other libraries\n may be duplicated upon initializing workers (w.g., NumPy), causing\n each worker to return identical random numbers. (See\n :ref:`dataloader-workers-random-seed` section in FAQ.) You may\n use ``torch.initial_seed()`` to access the PyTorch seed for each\n worker in :attr:`worker_init_fn`, and use it to set other seeds\n before data loading.\n\n .. warning:: If ``spawn`` start method is used, :attr:`worker_init_fn` cannot be an\n unpicklable object, e.g., a lambda function.\n \"\"\"\n\n __initialized = False\n\n def __init__(self, name, dataset, training=True, batch_size=1, shuffle=False, sampler=None, batch_sampler=None,\n num_workers=0, epoch_interval=1, collate_fn=None, stack_dim=0, pin_memory=False, drop_last=False,\n timeout=0, worker_init_fn=None):\n if collate_fn is None:\n if stack_dim == 0:\n collate_fn = ltr_collate\n elif stack_dim == 1:\n collate_fn = ltr_collate_stack1\n else:\n raise ValueError('Stack dim no supported. Must be 0 or 1.')\n\n super(LTRLoader, self).__init__(dataset, batch_size, shuffle, sampler, batch_sampler,\n num_workers, collate_fn, pin_memory, drop_last,\n timeout, worker_init_fn)\n\n self.name = name\n self.training = training\n self.epoch_interval = epoch_interval\n self.stack_dim = stack_dim" }, { "identifier": "opencv_loader", "path": "lib/train/data/image_loader.py", "snippet": "def opencv_loader(path):\n \"\"\" Read image using opencv's imread function and returns it in rgb format\"\"\"\n try:\n im = cv.imread(path, cv.IMREAD_COLOR)\n\n # convert to rgb and return\n return cv.cvtColor(im, cv.COLOR_BGR2RGB)\n except Exception as e:\n print('ERROR: Could not read image \"{}\"'.format(path))\n print(e)\n return None" }, { "identifier": "is_main_process", "path": "lib/utils/misc.py", "snippet": "def is_main_process():\n return get_rank() == 0" } ]
import os import torch import lib.train.data.transforms as tfm from torch.utils.data.distributed import DistributedSampler from lib.train.dataset import Lasot, Got10k, MSCOCOSeq, ImagenetVID, TrackingNet from lib.train.dataset import Lasot_lmdb, Got10k_lmdb, MSCOCOSeq_lmdb, ImagenetVID_lmdb, TrackingNet_lmdb from lib.train.data import sampler, opencv_loader, processing, LTRLoader from lib.utils.misc import is_main_process
19,146
print("Building got10k_train_full from lmdb") datasets.append(Got10k_lmdb(settings.env.got10k_lmdb_dir, split='train_full', image_loader=image_loader)) else: datasets.append(Got10k(settings.env.got10k_dir, split='train_full', image_loader=image_loader)) if name == "GOT10K_votval": if settings.use_lmdb: print("Building got10k from lmdb") datasets.append(Got10k_lmdb(settings.env.got10k_lmdb_dir, split='votval', image_loader=image_loader)) else: datasets.append(Got10k(settings.env.got10k_dir, split='votval', image_loader=image_loader)) if name == "GOT10K_official_val": if settings.use_lmdb: raise ValueError("Not implement") else: datasets.append(Got10k(settings.env.got10k_val_dir, split=None, image_loader=image_loader)) if name == "COCO17": if settings.use_lmdb: print("Building COCO2017 from lmdb") datasets.append(MSCOCOSeq_lmdb(settings.env.coco_lmdb_dir, version="2017", image_loader=image_loader)) else: datasets.append(MSCOCOSeq(settings.env.coco_dir, version="2017", image_loader=image_loader)) if name == "VID": if settings.use_lmdb: print("Building VID from lmdb") datasets.append(ImagenetVID_lmdb(settings.env.imagenet_lmdb_dir, image_loader=image_loader)) else: datasets.append(ImagenetVID(settings.env.imagenet_dir, image_loader=image_loader)) if name == "TRACKINGNET": if settings.use_lmdb: print("Building TrackingNet from lmdb") datasets.append(TrackingNet_lmdb(settings.env.trackingnet_lmdb_dir, image_loader=image_loader)) else: # raise ValueError("NOW WE CAN ONLY USE TRACKINGNET FROM LMDB") datasets.append(TrackingNet(settings.env.trackingnet_dir, image_loader=image_loader)) return datasets def build_dataloaders(cfg, settings): # Data transform transform_joint = tfm.Transform(tfm.ToGrayscale(probability=0.05), tfm.RandomHorizontalFlip(probability=0.5)) transform_train = tfm.Transform(tfm.ToTensorAndJitter(0.2), tfm.RandomHorizontalFlip_Norm(probability=0.5), # tfm.RandomHorizontalFlip(probability=0.5), tfm.Normalize(mean=cfg.DATA.MEAN, std=cfg.DATA.STD)) transform_val = tfm.Transform(tfm.ToTensor(), tfm.Normalize(mean=cfg.DATA.MEAN, std=cfg.DATA.STD)) # The tracking pairs processing module output_sz = settings.output_sz search_area_factor = settings.search_area_factor data_processing_train = processing.STARKProcessing(search_area_factor=search_area_factor, output_sz=output_sz, center_jitter_factor=settings.center_jitter_factor, scale_jitter_factor=settings.scale_jitter_factor, mode='sequence', transform=transform_train, joint_transform=transform_joint, settings=settings) data_processing_val = processing.STARKProcessing(search_area_factor=search_area_factor, output_sz=output_sz, center_jitter_factor=settings.center_jitter_factor, scale_jitter_factor=settings.scale_jitter_factor, mode='sequence', transform=transform_val, joint_transform=transform_joint, settings=settings) # Train sampler and loader settings.num_template = getattr(cfg.DATA.TEMPLATE, "NUMBER", 1) settings.num_search = getattr(cfg.DATA.SEARCH, "NUMBER", 1) sampler_mode = getattr(cfg.DATA, "SAMPLER_MODE", "causal") train_cls = getattr(cfg.TRAIN, "TRAIN_CLS", False) print("sampler_mode: ", sampler_mode) dataset_train = sampler.TrackingSampler(datasets=names2datasets(cfg.DATA.TRAIN.DATASETS_NAME, settings, opencv_loader), p_datasets=cfg.DATA.TRAIN.DATASETS_RATIO, samples_per_epoch=cfg.DATA.TRAIN.SAMPLE_PER_EPOCH, max_gap=cfg.DATA.MAX_SAMPLE_INTERVAL, num_search_frames=settings.num_search, num_template_frames=settings.num_template, processing=data_processing_train, frame_sample_mode=sampler_mode, train_cls=train_cls) train_sampler = DistributedSampler(dataset_train) if settings.local_rank != -1 else None shuffle = False if settings.local_rank != -1 else True loader_train = LTRLoader('train', dataset_train, training=True, batch_size=cfg.TRAIN.BATCH_SIZE, shuffle=shuffle, num_workers=cfg.TRAIN.NUM_WORKER, drop_last=True, stack_dim=1, sampler=train_sampler) # Validation samplers and loaders dataset_val = sampler.TrackingSampler(datasets=names2datasets(cfg.DATA.VAL.DATASETS_NAME, settings, opencv_loader), p_datasets=cfg.DATA.VAL.DATASETS_RATIO, samples_per_epoch=cfg.DATA.VAL.SAMPLE_PER_EPOCH, max_gap=cfg.DATA.MAX_SAMPLE_INTERVAL, num_search_frames=settings.num_search, num_template_frames=settings.num_template, processing=data_processing_val, frame_sample_mode=sampler_mode, train_cls=train_cls) val_sampler = DistributedSampler(dataset_val) if settings.local_rank != -1 else None loader_val = LTRLoader('val', dataset_val, training=False, batch_size=cfg.TRAIN.BATCH_SIZE, num_workers=cfg.TRAIN.NUM_WORKER, drop_last=True, stack_dim=1, sampler=val_sampler, epoch_interval=cfg.TRAIN.VAL_EPOCH_INTERVAL) return loader_train, loader_val def get_optimizer_scheduler(net, cfg, settings): tracker_name = settings.script_name # Visual Encoder param_dicts = [ {"params": [p for n, p in net.named_parameters() if "backbone" not in n and p.requires_grad]}, { "params": [p for n, p in net.named_parameters() if "backbone" in n and p.requires_grad], "lr": cfg.TRAIN.LR * cfg.TRAIN.BACKBONE_MULTIPLIER, }, ]
# datasets related def update_settings(settings, cfg): settings.print_interval = cfg.TRAIN.PRINT_INTERVAL settings.search_area_factor = {'template': cfg.DATA.TEMPLATE.FACTOR, 'search': cfg.DATA.SEARCH.FACTOR} settings.output_sz = {'template': cfg.DATA.TEMPLATE.SIZE, 'search': cfg.DATA.SEARCH.SIZE} settings.center_jitter_factor = {'template': cfg.DATA.TEMPLATE.CENTER_JITTER, 'search': cfg.DATA.SEARCH.CENTER_JITTER} settings.scale_jitter_factor = {'template': cfg.DATA.TEMPLATE.SCALE_JITTER, 'search': cfg.DATA.SEARCH.SCALE_JITTER} settings.grad_clip_norm = cfg.TRAIN.GRAD_CLIP_NORM settings.print_stats = None settings.batchsize = cfg.TRAIN.BATCH_SIZE settings.scheduler_type = cfg.TRAIN.SCHEDULER.TYPE def names2datasets(name_list: list, settings, image_loader): assert isinstance(name_list, list) datasets = [] for name in name_list: assert name in ["LASOT", "GOT10K_vottrain", "GOT10K_votval", "GOT10K_train_full", "GOT10K_official_val", "COCO17", "VID", "TRACKINGNET", ] # Tracking Task if name == "LASOT": if settings.use_lmdb: print("Building lasot dataset from lmdb") datasets.append(Lasot_lmdb(settings.env.lasot_lmdb_dir, split='train', image_loader=image_loader)) else: datasets.append(Lasot(settings.env.lasot_dir, split='train', image_loader=image_loader)) if name == "GOT10K_vottrain": if settings.use_lmdb: print("Building got10k from lmdb") datasets.append(Got10k_lmdb(settings.env.got10k_lmdb_dir, split='vottrain', image_loader=image_loader)) else: datasets.append(Got10k(settings.env.got10k_dir, split='vottrain', image_loader=image_loader)) if name == "GOT10K_train_full": if settings.use_lmdb: print("Building got10k_train_full from lmdb") datasets.append(Got10k_lmdb(settings.env.got10k_lmdb_dir, split='train_full', image_loader=image_loader)) else: datasets.append(Got10k(settings.env.got10k_dir, split='train_full', image_loader=image_loader)) if name == "GOT10K_votval": if settings.use_lmdb: print("Building got10k from lmdb") datasets.append(Got10k_lmdb(settings.env.got10k_lmdb_dir, split='votval', image_loader=image_loader)) else: datasets.append(Got10k(settings.env.got10k_dir, split='votval', image_loader=image_loader)) if name == "GOT10K_official_val": if settings.use_lmdb: raise ValueError("Not implement") else: datasets.append(Got10k(settings.env.got10k_val_dir, split=None, image_loader=image_loader)) if name == "COCO17": if settings.use_lmdb: print("Building COCO2017 from lmdb") datasets.append(MSCOCOSeq_lmdb(settings.env.coco_lmdb_dir, version="2017", image_loader=image_loader)) else: datasets.append(MSCOCOSeq(settings.env.coco_dir, version="2017", image_loader=image_loader)) if name == "VID": if settings.use_lmdb: print("Building VID from lmdb") datasets.append(ImagenetVID_lmdb(settings.env.imagenet_lmdb_dir, image_loader=image_loader)) else: datasets.append(ImagenetVID(settings.env.imagenet_dir, image_loader=image_loader)) if name == "TRACKINGNET": if settings.use_lmdb: print("Building TrackingNet from lmdb") datasets.append(TrackingNet_lmdb(settings.env.trackingnet_lmdb_dir, image_loader=image_loader)) else: # raise ValueError("NOW WE CAN ONLY USE TRACKINGNET FROM LMDB") datasets.append(TrackingNet(settings.env.trackingnet_dir, image_loader=image_loader)) return datasets def build_dataloaders(cfg, settings): # Data transform transform_joint = tfm.Transform(tfm.ToGrayscale(probability=0.05), tfm.RandomHorizontalFlip(probability=0.5)) transform_train = tfm.Transform(tfm.ToTensorAndJitter(0.2), tfm.RandomHorizontalFlip_Norm(probability=0.5), # tfm.RandomHorizontalFlip(probability=0.5), tfm.Normalize(mean=cfg.DATA.MEAN, std=cfg.DATA.STD)) transform_val = tfm.Transform(tfm.ToTensor(), tfm.Normalize(mean=cfg.DATA.MEAN, std=cfg.DATA.STD)) # The tracking pairs processing module output_sz = settings.output_sz search_area_factor = settings.search_area_factor data_processing_train = processing.STARKProcessing(search_area_factor=search_area_factor, output_sz=output_sz, center_jitter_factor=settings.center_jitter_factor, scale_jitter_factor=settings.scale_jitter_factor, mode='sequence', transform=transform_train, joint_transform=transform_joint, settings=settings) data_processing_val = processing.STARKProcessing(search_area_factor=search_area_factor, output_sz=output_sz, center_jitter_factor=settings.center_jitter_factor, scale_jitter_factor=settings.scale_jitter_factor, mode='sequence', transform=transform_val, joint_transform=transform_joint, settings=settings) # Train sampler and loader settings.num_template = getattr(cfg.DATA.TEMPLATE, "NUMBER", 1) settings.num_search = getattr(cfg.DATA.SEARCH, "NUMBER", 1) sampler_mode = getattr(cfg.DATA, "SAMPLER_MODE", "causal") train_cls = getattr(cfg.TRAIN, "TRAIN_CLS", False) print("sampler_mode: ", sampler_mode) dataset_train = sampler.TrackingSampler(datasets=names2datasets(cfg.DATA.TRAIN.DATASETS_NAME, settings, opencv_loader), p_datasets=cfg.DATA.TRAIN.DATASETS_RATIO, samples_per_epoch=cfg.DATA.TRAIN.SAMPLE_PER_EPOCH, max_gap=cfg.DATA.MAX_SAMPLE_INTERVAL, num_search_frames=settings.num_search, num_template_frames=settings.num_template, processing=data_processing_train, frame_sample_mode=sampler_mode, train_cls=train_cls) train_sampler = DistributedSampler(dataset_train) if settings.local_rank != -1 else None shuffle = False if settings.local_rank != -1 else True loader_train = LTRLoader('train', dataset_train, training=True, batch_size=cfg.TRAIN.BATCH_SIZE, shuffle=shuffle, num_workers=cfg.TRAIN.NUM_WORKER, drop_last=True, stack_dim=1, sampler=train_sampler) # Validation samplers and loaders dataset_val = sampler.TrackingSampler(datasets=names2datasets(cfg.DATA.VAL.DATASETS_NAME, settings, opencv_loader), p_datasets=cfg.DATA.VAL.DATASETS_RATIO, samples_per_epoch=cfg.DATA.VAL.SAMPLE_PER_EPOCH, max_gap=cfg.DATA.MAX_SAMPLE_INTERVAL, num_search_frames=settings.num_search, num_template_frames=settings.num_template, processing=data_processing_val, frame_sample_mode=sampler_mode, train_cls=train_cls) val_sampler = DistributedSampler(dataset_val) if settings.local_rank != -1 else None loader_val = LTRLoader('val', dataset_val, training=False, batch_size=cfg.TRAIN.BATCH_SIZE, num_workers=cfg.TRAIN.NUM_WORKER, drop_last=True, stack_dim=1, sampler=val_sampler, epoch_interval=cfg.TRAIN.VAL_EPOCH_INTERVAL) return loader_train, loader_val def get_optimizer_scheduler(net, cfg, settings): tracker_name = settings.script_name # Visual Encoder param_dicts = [ {"params": [p for n, p in net.named_parameters() if "backbone" not in n and p.requires_grad]}, { "params": [p for n, p in net.named_parameters() if "backbone" in n and p.requires_grad], "lr": cfg.TRAIN.LR * cfg.TRAIN.BACKBONE_MULTIPLIER, }, ]
if is_main_process():
14
2023-12-10 03:57:19+00:00
24k
lumina-test/lumina
lumina/e2e_test/test_gbn.py
[ { "identifier": "get_qp_info_list", "path": "lumina/analyzer/main.py", "snippet": "def get_qp_info_list(switch_msg_snapshot):\n \"\"\" Get the list of QP info from the switch message snapshot\n\n Args:\n switch_msg_snapshot (str): The path to the switch message snapshot\n\n Returns:\n list of dict: The list of queue pair (QP) information if successful or None otherwise.\n The list of QP information is in the following format:\n [{'psn_rcv': initial packet sequence number from the receiver qp,\n 'psn_snd': initial packet sequence number from the sender qp,\n 'qpn_rcv': receiver qp number,\n 'qpn_snd': sender qp number,\n 'ip_rcv' : receiver IP\n 'ip_snd' : sender IP}]\n \"\"\"\n try:\n with open(switch_msg_snapshot, 'r') as stream:\n qp_info_list = yaml.safe_load(stream)\n except:\n logging.error(\"Read switch message snapshot %s error.\" % switch_msg_snapshot)\n return None\n\n logging.info(\"Read switch message snapshot %s.\" % switch_msg_snapshot)\n return qp_info_list" }, { "identifier": "Orchestrator", "path": "lumina/orchestrator/main.py", "snippet": "class Orchestrator:\n \"\"\" Class to manage the experiment \"\"\"\n def __init__(self, config_file):\n \"\"\" Constructor for Orchestrator class\n\n Args:\n config_file (str): path to the yaml (config) file.\n The file contains configs for switch, requester, responder, traffic, etc.\n\n Returns:\n N/A\n \"\"\"\n with open(config_file, \"r\") as stream:\n conf = yaml.safe_load(stream)\n try:\n local_workspace = conf['local-workspace']\n result_path = conf['result-path']\n switch_conf = conf['switch']\n requester_conf = conf['requester']\n responder_conf = conf['responder']\n requester_mirror_conf = conf['requester-mirror']\n responder_mirror_conf = conf['responder-mirror']\n traffic_conf = conf['traffic']\n rewrite_udp_dst_port = conf['rewrite-udp-dst-port']\n num_repeats = conf['num-repeats']\n agg_pcap_filename = conf['aggregate-pcap-filename']\n except KeyError as e:\n print(\"Config file %s has a bad yaml format (key error: %s)\" % (config_file, e))\n sys.exit(-1)\n\n switch_conf['rewrite-udp-dst-port'] = rewrite_udp_dst_port\n requester_mirror_conf['pkt-dump-conf']['rewrite-udp-dst-port'] = rewrite_udp_dst_port\n responder_mirror_conf['pkt-dump-conf']['rewrite-udp-dst-port'] = rewrite_udp_dst_port\n\n self.local_workspace = local_workspace\n self.result_path = result_path\n self.traffic_conf = traffic_conf\n self.num_repeats = num_repeats\n self.switch = switch.Switch(switch_conf)\n self.requester = host.RDMAHost(requester_conf)\n self.responder = host.RDMAHost(responder_conf)\n self.requester_mirror = host.MirrorHost(requester_mirror_conf)\n self.responder_mirror = host.MirrorHost(responder_mirror_conf)\n self.aggregate_pcap_filename = agg_pcap_filename\n\n cmd = \"mkdir -p %s\" % self.result_path\n subprocess.call(cmd, shell = True)\n\n def rm_old_files(self):\n \"\"\" Remove result files left by previous experiments \"\"\"\n old_iter_id = 0\n old_iter_result_path = os.path.join(self.result_path, str(old_iter_id))\n\n while os.path.exists(old_iter_result_path) and not os.path.isfile(old_iter_result_path):\n cmd = \"rm -rf %s\" % (old_iter_result_path)\n subprocess.call(cmd, shell=True)\n\n old_iter_id += 1\n old_iter_result_path = os.path.join(self.result_path, str(old_iter_id))\n\n def get_requester_ip_list(self):\n \"\"\" Return the list of requester IP addresses (without prefix length info) \"\"\"\n return [x.split('/')[0] for x in self.requester.conf['nic']['ip-list']]\n\n def get_responder_ip_list(self):\n \"\"\" Return the list of responder IP addresses (without prefix length info) \"\"\"\n return [x.split('/')[0] for x in self.responder.conf['nic']['ip-list']]\n\n def get_num_repeats(self):\n \"\"\" Return the number of experiment repeats \"\"\"\n return self.num_repeats\n\n def sync_and_compile(self):\n \"\"\" Syncronize and compile the code on all the hosts\n\n Returns:\n bool: True if the code is synced and compiled successfully, False otherwise\n \"\"\"\n logging.info(\"Sync and compile the code\")\n\n ## Sync and compile the switch code\n ret = self.switch.sync_and_compile(self.local_workspace,\n switch.SWITCH_PROG_DIR_NAME,\n switch.SWITCH_PROG_FILE_NAME)\n if ret == False:\n logging.error(\"Failed to sync and compile the switch code\")\n return False\n\n ## Sync and compile the traffic generator code\n rdma_verb = self.traffic_conf['rdma-verb'].strip().lower()\n if rdma_verb not in host.VALID_IB_VERB_LIST_LOWER:\n logging.error(\"Invalid RDMA verb: %s\" % rdma_verb)\n return False\n\n ret = self.requester.sync_and_compile(local_workspace=self.local_workspace,\n prog_dir_name=self.requester.traffic_gen_dir_name(),\n prog_file_name=self.requester.traffic_gen_client_name(rdma_verb))\n if ret == False:\n logging.error(\"Failed to sync and compile the traffic generator code on requester\")\n return False\n\n ret = self.responder.sync_and_compile(local_workspace=self.local_workspace,\n prog_dir_name=self.requester.traffic_gen_dir_name(),\n prog_file_name=self.requester.traffic_gen_server_name(rdma_verb))\n if ret == False:\n logging.error(\"Failed to sync and compile the traffic generator code on responder\")\n return False\n\n ret = self.requester.sync(local_workspace=self.local_workspace,\n prog_dir_name=host.DUMP_COUNTER_DIR_NAME)\n if ret == False:\n logging.error(\"Failed to sync the dump counter code on requester\")\n return False\n\n ret = self.responder.sync(local_workspace=self.local_workspace,\n prog_dir_name=host.DUMP_COUNTER_DIR_NAME)\n if ret == False:\n logging.error(\"Failed to sync the dump counter code on responder\")\n return False\n\n ## Sync and compile the packet capture code\n ret = self.requester_mirror.sync_and_compile(local_workspace=self.local_workspace,\n prog_dir_name=host.PKT_CAPTURE_DIR_NAME,\n prog_file_name=host.PKT_CAPTURE_FILE_NAME)\n if ret == False:\n logging.error(\"Failed to sync and compile the packet capture code on requester_mirror\")\n return False\n\n ret = self.responder_mirror.sync_and_compile(local_workspace=self.local_workspace,\n prog_dir_name=host.PKT_CAPTURE_DIR_NAME,\n prog_file_name=host.PKT_CAPTURE_FILE_NAME)\n if ret == False:\n logging.error(\"Failed to sync and compile the packet capture code on responder_mirror\")\n return False\n\n return True\n\n def generate_switch_table_config(self):\n \"\"\" Generate the switch configuration, including:\n 1. Forward table\n 2. Mirror table\n 3. ARP table\n 4. Traffic table, including the events to inject\n\n Returns:\n bool: True if the switch configuration is generated successfully, False otherwise\n \"\"\"\n requester_nic_conf = self.requester.conf['nic']\n responder_nic_conf = self.responder.conf['nic']\n requester_mirror_nic_conf = self.requester_mirror.conf['nic']\n responder_mirror_nic_conf = self.responder_mirror.conf['nic']\n\n ## Set up forward table entries\n self.switch.conf['forward-table'] = []\n try:\n for nic_conf, host_type in zip([requester_nic_conf, responder_nic_conf, \\\n requester_mirror_nic_conf, responder_mirror_nic_conf],\n ['requester', 'responder', 'requester_mirror', 'responder_mirror']):\n forward_table_entry = {'dst-mac': nic_conf['mac'],\n 'eg-port': nic_conf['switch-port'],\n 'host': host_type}\n self.switch.conf['forward-table'].append(forward_table_entry)\n except:\n logging.error(\"Failed to set forward table\")\n return False\n\n ## Set up mirror table entries, use ingress_to_egress\n try:\n requester_mirror_entry = {'direction': 'ingress_to_egress',\n 'src-port': requester_nic_conf['switch-port'],\n 'dst-port': requester_mirror_nic_conf['switch-port']}\n\n responder_mirror_entry = {'direction': 'ingress_to_egress',\n 'src-port': responder_nic_conf['switch-port'],\n 'dst-port': responder_mirror_nic_conf['switch-port']}\n self.switch.conf['mirror-table'] = [requester_mirror_entry, responder_mirror_entry]\n except:\n logging.error(\"Failed to set mirror table\")\n return False\n\n requester_mac = requester_nic_conf['mac']\n responder_mac = responder_nic_conf['mac']\n requester_ip_list = requester_nic_conf['ip-list']\n responder_ip_list = responder_nic_conf['ip-list']\n ## Set up arp table entries\n arp_entries = []\n try:\n for dst_ip_list, dst_mac in zip([requester_ip_list, responder_ip_list],\n [requester_mac, responder_mac]):\n for dst_ip_subnet in dst_ip_list:\n dst_ip = dst_ip_subnet.split('/')[0]\n arp_entries.append({'dst-ip': dst_ip, 'dst-mac': dst_mac})\n self.switch.conf['arp-table'] = arp_entries\n except:\n logging.error(\"Failed to set ARP table\")\n return False\n\n ## Generate the events of each iteration for switch config\n per_iter_event_list = self.traffic_conf['data-pkt-events']\n msg_size = self.traffic_conf['message-size']\n mtu = self.traffic_conf['mtu']\n num_msgs_per_qp = self.traffic_conf['num-msgs-per-qp']\n num_pkts_per_msg = int(math.ceil(msg_size / mtu))\n self.switch.conf['traffic'] = {}\n self.switch.conf['traffic']['num-msgs-per-qp'] = num_msgs_per_qp\n self.switch.conf['traffic']['num-pkts-per-msg'] = num_pkts_per_msg\n self.switch.conf['traffic']['data-pkt-events'] = []\n\n if per_iter_event_list is None or len(per_iter_event_list) == 0:\n ## No events at all\n return True\n\n for i in range(num_msgs_per_qp):\n for per_iter_event in per_iter_event_list:\n global_event = copy.deepcopy(per_iter_event)\n\n ## This event is applied to all the packets of the message. We need to expand it!\n if str(global_event['psn']).lower() == 'all':\n for psn in range(num_pkts_per_msg):\n global_event['psn'] = psn + i * num_pkts_per_msg\n self.switch.conf['traffic']['data-pkt-events'].append(copy.deepcopy(global_event))\n else:\n global_event['psn'] += i * num_pkts_per_msg\n self.switch.conf['traffic']['data-pkt-events'].append(copy.deepcopy(global_event))\n\n return True\n\n def ping_mesh(self):\n \"\"\" Ping all the IP addresses between requester and responder to check the connectivity\n\n Returns:\n bool: True if all the IP addresses can be pinged successfully, False otherwise\n \"\"\"\n for requester_ip_subnet in self.requester.conf['nic']['ip-list']:\n requester_ip = requester_ip_subnet.split('/')[0]\n command = \"ping \" + requester_ip + \" -c 5 -i 0.2\"\n ret_val, err_info, exit_status = self.responder.execute_command(command)\n if exit_status != 0:\n logging.error(\"Failed to ping ip \" + requester_ip)\n logging.error(\"[Command return info]: %s %s\" % (', '.join(ret_val), ', '.join(err_info)))\n return False\n\n for responder_ip_subnet in self.responder.conf['nic']['ip-list']:\n responder_ip = responder_ip_subnet.split('/')[0]\n command = \"ping \" + responder_ip + \" -c 5 -i 0.2\"\n ret_val, err_info, exit_status = self.requester.execute_command(command)\n if exit_status != 0:\n logging.error(\"Failed to ping ip \" + responder_ip)\n logging.error(\"[Command return info]: %s %s\" % (ret_val, err_info))\n return False\n\n logging.info(\"Successfully pinged all the IP addresses between requester and responder\")\n return True\n\n def generate_switch_config_file(self):\n \"\"\" Generate the switch configuration file and copy it to the switch\n\n Returns:\n bool: True if the switch configuration file is generated and copied successfully, False otherwise\n \"\"\"\n ## Get the mac address for all the hosts\n self.requester.get_mac_address()\n self.responder.get_mac_address()\n self.requester_mirror.get_mac_address()\n self.responder_mirror.get_mac_address()\n\n ## Generate config for Match-Action table in switch\n if self.generate_switch_table_config() == False:\n logging.error(\"Failed to generate switch table configuration\")\n return False\n\n ## Dump the switch configuration into a file, and copy it to the switch\n if self.switch.dump_controller_config(self.local_workspace) == False:\n logging.error(\"Failed to dump switch config\")\n return False\n\n return True\n\n def __is_valid_traffc(self):\n \"\"\" Check if the traffic configuration is valid, including:\n 1. The tx-depth should be 1 or > 1\n 2. If tx-depth > 1, then we can only inject ECN marking events\n\n Returns:\n bool: True if the traffic configuration is valid, False otherwise\n \"\"\"\n try:\n data_pkt_events = self.traffic_conf['data-pkt-events']\n tx_depth = self.traffic_conf['tx-depth']\n\n if tx_depth == 1:\n return True\n elif tx_depth <= 0:\n return False\n\n for event in data_pkt_events:\n if event['type'] != 'ecn':\n logging.error(\"Cannot inject %s event when tx depth = %d\" % (event['type'], tx_depth))\n return False\n except:\n logging.error(\"Failed to parse traffic configuration\")\n return False\n\n return True\n\n def run_experiment(self):\n \"\"\" Run the experiment\n\n Returns:\n bool: True if the experiment is completed successfully, False otherwise\n \"\"\"\n\n ## Check if traffic configuration is valid\n if self.__is_valid_traffc() == False:\n logging.error(\"Invalid traffic configuration\")\n return False\n\n ## Run switch program\n if self.switch.run_switch() == False:\n logging.error(\"Failed to run switch\")\n return False\n\n ## Sleep for 1 second to make sure control plane is listenning (for client message)\n time.sleep(1)\n\n ## Configure the servers\n if self.requester.config_traffic_gen() == False:\n logging.error(\"Failed to config RDMA requester\")\n return False\n\n if self.responder.config_traffic_gen() == False:\n logging.error(\"Failed to config RDMA responder\")\n return False\n\n if self.requester_mirror.config_packet_capture() == False:\n logging.error(\"Failed to config packet capture on requester mirror\")\n return False\n\n if self.responder_mirror.config_packet_capture() == False:\n logging.error(\"Failed to config packet capture on responder mirror\")\n return False\n\n ## Check the connectivity through pingmesh (try 5 rounds)\n num_tries = 0\n pingmesh_ret = False\n\n while num_tries < 5:\n pingmesh_ret = self.ping_mesh()\n if pingmesh_ret == True:\n break\n num_tries += 1\n time.sleep(1)\n\n if pingmesh_ret == False:\n logging.error(\"Failed to ping all the IP addresses between requester and responder\")\n return False\n\n ## Launch packet capture for both side\n ## Prerequisite: config hugepage and igb_uio if needed\n if self.requester_mirror.run_packet_capture() == False:\n logging.error(\"Failed to run packet capture on requester mirror\")\n return False\n\n if self.responder_mirror.run_packet_capture() == False:\n logging.error(\"Failed to run packet capture on responder mirror\")\n return False\n\n time.sleep(3)\n\n ## Dump the counters before running\n if self.requester.dump_counters(host.REQ_START_COUNTER_FILE_NAME) == False:\n logging.error(\"Failed to dump counters on requester before running\")\n return False\n\n if self.responder.dump_counters(host.RSP_START_COUNTER_FILE_NAME) == False:\n logging.error(\"Failed to dump counters on responder before running\")\n return False\n\n ## Launch RDMA server first\n run_server_ret = self.responder.run_traffic_gen_server(self.traffic_conf)\n if run_server_ret == False:\n logging.error(\"Failed to run RDMA server\")\n return False\n\n time.sleep(2)\n\n ## Launch RDMA client\n try:\n destination_ip_subnet = self.responder.conf['nic']['ip-list'][0]\n destination_ip = destination_ip_subnet.split('/')[0]\n except:\n logging.error(\"Failed to get destination IP\")\n return False\n\n run_client_ret = self.requester.run_traffic_gen_client(traffic_conf=self.traffic_conf,\n destination_ip=destination_ip,\n controller_ip=self.switch.conf['control-ip'],\n controller_listen_port=self.switch.conf['listen-port'])\n if run_client_ret == False:\n logging.error(\"Failed to run RDMA client\")\n return False\n\n if self.switch.dump_results() == False:\n logging.error(\"Failed to dump results from switch\")\n return False\n\n if self.requester.dump_counters(host.REQ_FINISH_COUNTER_FILE_NAME) == False:\n logging.error(\"Failed to dump counters on requester after running\")\n return False\n\n if self.responder.dump_counters(host.RSP_FINISH_COUNTER_FILE_NAME) == False:\n logging.error(\"Failed to dump counters on responder after running\")\n return False\n\n logging.info(\"Experiment completed successfully\")\n return True\n\n def clean_up(self):\n \"\"\" Clean up the environment after the experiment\n\n Returns:\n bool: True if the clean up is completed successfully, False otherwise\n \"\"\"\n logging.info(\"Start cleaning up the environment\")\n\n if self.switch.clean_up() == False:\n logging.error(\"Failed to clean up switch\")\n return False\n\n if self.requester.clean_up() == False:\n logging.error(\"Failed to clean up requester\")\n return False\n\n if self.responder.clean_up() == False:\n logging.error(\"Failed to clean up responder\")\n return False\n\n if self.requester_mirror.clean_up() == False:\n logging.error(\"Failed to clean up requester mirror\")\n return False\n\n if self.responder_mirror.clean_up() == False:\n logging.error(\"Failed to clean up responder mirror\")\n return False\n\n return True\n\n def fetch_results(self, iter_id=0):\n \"\"\" Fetch the results of iteration 'iter_id', including:\n 1. Switch table entries and counters\n 2. Packet trace (pcap file)\n 3. Configs and end-to-end results from RDMA hosts\n\n Args:\n iter_id (int, optional): iteration ID, defaults to 0\n\n Returns:\n bool: True if the result collection is completed successfully, False otherwise\n \"\"\"\n ## Make the results dir if it does not exist\n iter_result_path = os.path.join(self.result_path, str(iter_id))\n cmd = \"mkdir -p %s\" % iter_result_path\n try:\n subprocess.call(cmd, shell=True)\n except:\n logging.error(\"Failed to create result directory %s\" % iter_result_path)\n return False\n\n if self.switch.fetch_results(iter_result_path) == False:\n logging.error(\"Failed to fetch results from switch\")\n return False\n\n if self.requester_mirror.fetch_results(iter_result_path) == False:\n logging.error(\"Failed to fetch results from requester mirror\")\n return False\n\n if self.responder_mirror.fetch_results(iter_result_path) == False:\n logging.error(\"Failed to fetch results from responder mirror\")\n return False\n\n if self.requester.fetch_results(iter_result_path) == False:\n logging.error(\"Failed to fetch results from requester\")\n return False\n\n if self.responder.fetch_results(iter_result_path) == False:\n logging.error(\"Failed to fetch results from responder\")\n return False\n\n logging.info(\"Finished fetching results for iteration %d\" % iter_id)\n return True\n\n def merge_traces(self, iter_id=0):\n iter_pcap_dir_path = os.path.join(self.result_path, str(iter_id), host.PCAP_RESULT_DIR)\n src_pcap_file_list = [os.path.join(iter_pcap_dir_path,\n self.requester_mirror.conf['pkt-dump-conf']['dump-filename']),\n os.path.join(iter_pcap_dir_path,\n self.responder_mirror.conf['pkt-dump-conf']['dump-filename'])]\n target_pcap_path = os.path.join(self.result_path,\n str(iter_id),\n host.PCAP_RESULT_DIR,\n self.aggregate_pcap_filename)\n packet_list = pcap_process.merge_pcaps(src_pcap_file_list)\n if packet_list is None:\n logging.error(\"Failed to merge pcap files for iteration %d\" % iter_id)\n return False\n\n if pcap_process.dump_pkts_to_pcap(target_pcap_path, packet_list) == False:\n logging.error(\"Failed to dump packets to pcap file %s\" % target_pcap_path)\n return False\n\n logging.info(\"Successfully merged pcap files for iteration %d\" % iter_id)\n\n def check_integrity(self, iter_id=0):\n ## Check if the collected packet trace passes integrity check\n pcap_path = os.path.join(self.result_path,\n str(iter_id),\n host.PCAP_RESULT_DIR,\n self.aggregate_pcap_filename)\n packet_list = get_packet_list(pcap_path)\n packet_list.sort(key=lambda x:x.get_switch_seqnum())\n logging.info(\"Packet trace sorted by switch sequence number.\")\n\n switch_state_snapshot = os.path.join(self.result_path,\n str(iter_id),\n switch.SWITCH_RESULT_DIR,\n switch.SWITCH_STATE_SNAPSHOT)\n port_map = {'requester': self.requester.conf['nic']['switch-port'],\n 'responder': self.responder.conf['nic']['switch-port'],\n 'requester-mirror': self.requester_mirror.conf['nic']['switch-port'],\n 'responder-mirror': self.responder_mirror.conf['nic']['switch-port']}\n switch_counter = SwitchCounter(switch_state_snapshot, port_map)\n\n integrity_checker = IntegrityCheck(packet_list=packet_list,\n switch_counter=switch_counter,\n requester_ip_list=self.get_requester_ip_list(),\n responder_ip_list=self.get_responder_ip_list())\n\n if integrity_checker.check() == True:\n logging.info(\"Integrity check passed\")\n return True\n else:\n logging.info(\"Integrity check failed\")\n return False" }, { "identifier": "SwitchCounter", "path": "lumina/analyzer/counter/switch_counter.py", "snippet": "class SwitchCounter:\n \"\"\" Class to parse switch counter files\n\n Attributes:\n _counter (dict of dict): the switch counters with the following format:\n {'requester': {'ingress': counter_value, 'egress': counter_value},\n 'responder': {'ingress': counter_value, 'egress': counter_value},\n 'requester-mirror': {'ingress': counter_value, 'egress': counter_value},\n 'responder-mirror': {'ingress': counter_value, 'egress': counter_value}}\n \"\"\"\n def __init__(self, snapshot_filename, port_map):\n \"\"\" Constructor\n\n Args:\n snapshot_filename (str): the file where switch dumps its counters\n port_map (dict): the mapping between port name and port number\n\n Returns:\n N/A\n \"\"\"\n with open(snapshot_filename, \"r\") as stream:\n conf = yaml.safe_load(stream)\n try:\n ingress_counters = conf['counter']['ingress']\n egress_counters = conf['counter']['egress']\n except:\n print(\"Bad yaml format in %s\" % snapshot_filename)\n sys.exit(-1)\n\n requester_port = port_map['requester']\n responder_port = port_map['responder']\n requester_mirror_port = port_map['requester-mirror']\n responder_mirror_port = port_map['responder-mirror']\n\n self._counter = {'requester' : {'ingress':0, 'egress': 0},\n 'responder' : {'ingress':0, 'egress': 0},\n 'requester-mirror' : {'ingress':0, 'egress': 0},\n 'responder-mirror' : {'ingress':0, 'egress': 0}}\n try:\n self._counter['requester']['ingress'] = ingress_counters[requester_port]\n self._counter['responder']['ingress'] = ingress_counters[responder_port]\n self._counter['requester-mirror']['ingress'] = ingress_counters[requester_mirror_port]\n self._counter['responder-mirror']['ingress'] = ingress_counters[responder_mirror_port]\n\n self._counter['requester']['egress'] = egress_counters[requester_port]\n self._counter['responder']['egress'] = egress_counters[responder_port]\n self._counter['requester-mirror']['egress'] = egress_counters[requester_mirror_port]\n self._counter['responder-mirror']['egress'] = egress_counters[responder_mirror_port]\n\n except:\n print(\"Port number not exist in the switch snapshot\")\n sys.exit(-1)\n\n def get_counter(self):\n \"\"\" Return the switch counters (dict of dict) \"\"\"\n return self._counter" }, { "identifier": "MLNXHostCounter", "path": "lumina/analyzer/counter/host_counter.py", "snippet": "class MLNXHostCounter(HostCounter):\n \"\"\" Class to parse MLNX host counter files \"\"\"\n def __init__(self, counter_start_filename, counter_finish_filename):\n \"\"\" Constructor\n\n Args:\n counter_start_filename (str): the file where host dumps its counters at the start phase\n counter_finish_filename (str): the file where host dumps its counters at the finish phase\n\n Returns:\n N/A\n \"\"\"\n super().__init__(counter_start_filename, counter_finish_filename)\n\n def get_port_rcv_packets(self):\n \"\"\" Return the number of received packets \"\"\"\n return self._counter['port-counters']['port_rcv_packets']\n\n def get_port_xmit_packets(self):\n \"\"\" Return the number of transmitted packets \"\"\"\n return self._counter['port-counters']['port_xmit_packets']\n\n def get_num_packet_seq_err(self):\n \"\"\" Return the number of received NAK sequence error packets \"\"\"\n return self._counter['hw-counters']['packet_seq_err']\n\n def get_num_out_of_sequence(self):\n \"\"\" Return the number of out-of-sequence packets received \"\"\"\n return self._counter['hw-counters']['out_of_sequence']\n\n def get_num_dup_requests(self):\n \"\"\" Return the number of duplicate requests \"\"\"\n return self._counter['hw-counters']['duplicate_request']\n\n def implied_nak_seq_err(self):\n \"\"\" Return the number of READ requests implying sequence errors \"\"\"\n return self._counter['hw-counters']['implied_nak_seq_err']\n\n def get_num_cnp_sent(self):\n \"\"\" Return the number of congestion notification packets sent by notification point \"\"\"\n return self._counter['hw-counters']['np_cnp_sent']\n\n def get_num_ecn_marked_packets(self):\n \"\"\" Return the number of ECN marked RoCEv2 packets received by notification point \"\"\"\n return self._counter['hw-counters']['np_ecn_marked_roce_packets']\n\n def get_num_cnp_handled(self):\n \"\"\" Return the number of congestion notification packets handled by reaction point \"\"\"\n return self._counter['hw-counters']['rp_cnp_handled']\n\n def get_num_icrc_errors(self):\n \"\"\" Return the number of RoCE packets with ICRC errors received \"\"\"\n return self._counter['hw-counters']['rx_icrc_encapsulated']\n\n def get_num_timeout_err(self):\n \"\"\" Return the number of times QP's ack timer expired for RC, XRC, DCT QPs at the sender side \"\"\"\n return self._counter['hw-counters']['local_ack_timeout_err']\n\n def get_num_discards_dict_tx(self):\n \"\"\" Return the number of TX discarded packets (dict)\"\"\"\n discards_dict_tx = {}\n for x in self._counter['ethtool-counters'].keys():\n if 'discard' in x and 'tx' in x:\n discards_dict_tx[x] = self._counter['ethtool-counters'][x]\n return discards_dict_tx\n\n def get_num_discards_dict_rx(self):\n \"\"\" Return the number of RX discarded packets (dict) \"\"\"\n discards_dict_rx = {}\n for x in self._counter['ethtool-counters'].keys():\n if 'discard' in x and 'rx' in x:\n discards_dict_rx[x] = self._counter['ethtool-counters'][x]\n return discards_dict_rx" }, { "identifier": "IntelHostCounter", "path": "lumina/analyzer/counter/host_counter.py", "snippet": "class IntelHostCounter(HostCounter):\n \"\"\" Class to parse Intel host counter files \"\"\"\n def __init__(self, counter_start_filename, counter_finish_filename):\n \"\"\" Constructor\n\n Args:\n counter_start_filename (str): the file where host dumps its counters at the start phase\n counter_finish_filename (str): the file where host dumps its counters at the finish phase\n\n Returns:\n N/A\n \"\"\"\n super().__init__(counter_start_filename, counter_finish_filename)\n\n def get_num_cnp_sent(self):\n \"\"\" Return the number of congestion notification packets sent by notification point \"\"\"\n return self._counter['hw-counters']['cnpSent']\n\n def get_num_ecn_marked_packets(self):\n \"\"\" Return the number of ECN marked RoCEv2 packets received by notification point \"\"\"\n return self._counter['hw-counters']['RxECNMrkd']\n\n def get_num_cnp_handled(self):\n \"\"\" Return the number of congestion notification packets handled by reaction point \"\"\"\n return self._counter['hw-counters']['cnpHandled']\n\n def get_num_discards_dict(self):\n \"\"\" Return the number of discarded packets (dict) \"\"\"\n discards_dict= {}\n for x in self._counter['hw-counters'].keys():\n if 'discard' in x:\n discards_dict[x] = self._counter['hw-counters'][x]\n return discards_dict" }, { "identifier": "get_packet_list", "path": "lumina/analyzer/pcap_processor/pcap_process.py", "snippet": "def get_packet_list(pcap_file):\n \"\"\" Read a pcap file and return a list of packets\n\n Args:\n pcap_file (str): The pcap file to read\n\n Returns:\n list: The list of packets if successful, empty list otherwise\n\n Raises:\n IOError: If the pcap file cannot be opened for reading\n Exception: If the pcap file cannot be read\n \"\"\"\n packet_list = []\n try:\n with open(pcap_file, 'rb') as file_read:\n pcap = dpkt.pcap.Reader(file_read)\n for packet in pcap:\n packet_list.append(roce_packet.RRoCEPacket(packet))\n except IOError:\n logging.error(\"Unable to open pcap file %s. Please check your filename.\" % pcap_file)\n raise IOError\n\n except:\n logging.error(\"Failed to read pcap file %s.\" % pcap_file)\n raise Exception\n\n logging.info(\"Successfully read %d packets from %s.\" % (len(packet_list), pcap_file))\n return packet_list" }, { "identifier": "LatencyMeasure", "path": "lumina/analyzer/measurer/latency_measure.py", "snippet": "class LatencyMeasure:\n \"\"\" Class to measure the latency between packets for some events,\n e.g., NACK latency, Retransmission latency, CNP latency\n\n Attributes:\n packet_list (list of RRoCEPacket objects): list of packets\n qp_info_list (list of dict): list of QP info with the following format:\n [{'psn_rcv': initial packet sequence number from the receiver qp,\n 'psn_snd': initial packet sequence number from the sender qp,\n 'qpn_rcv': receiver qp number,\n 'qpn_snd': sender qp number,\n 'ip_rcv' : receiver IP\n 'ip_snd' : sender IP}]\n is_read (bool): if the QPs use RDMA read verb\n \"\"\"\n def __init__(self, packet_list, qp_info_list, is_read=False):\n \"\"\" Constructor\n\n Args:\n packet_list (list of RRoCEPacket objects): list of packets\n qp_info_list (list of dict): list of QP info with the following format:\n [{'psn_rcv': initial packet sequence number from the receiver qp,\n 'psn_snd': initial packet sequence number from the sender qp,\n 'qpn_rcv': receiver qp number,\n 'qpn_snd': sender qp number,\n 'ip_rcv' : receiver IP\n 'ip_snd' : sender IP}]\n is_read (bool): if the QPs use RDMA read verb (default: False)\n\n Returns:\n N/A\n \"\"\"\n self.packet_list = packet_list\n self.qp_info_list = qp_info_list\n self.is_read = is_read\n\n def get_peer_qp_info(self, dest_qpn, dest_ip):\n \"\"\" Get the info of the peer QP (qpn, ip) of a given qp (qpn, ip)\n\n Args:\n dest_qpn (int): destination QP number\n dest_ip (str): destination IP\n\n Returns:\n int: peer QP number (None if not found)\n str: peer IP (None if not found)\n \"\"\"\n for qp_info in self.qp_info_list:\n if qp_info['qpn_snd'] == dest_qpn and qp_info['ip_snd'] == dest_ip:\n return qp_info['qpn_rcv'], qp_info['ip_rcv']\n elif qp_info['qpn_rcv'] == dest_qpn and qp_info['ip_rcv'] == dest_ip:\n return qp_info['qpn_snd'], qp_info['ip_snd']\n\n return None, None\n\n def get_bit_error_pkts(self, relative_dest_qpn=None):\n \"\"\" Get the packets marked with bit error flag\n\n Args:\n relative_dest_qpn (int): the relative destination QP number (None if not specified)\n\n Returns:\n list of RRoCEPacket objects: the list of packets marked with bit error flag\n \"\"\"\n error_pkt_list = []\n\n if relative_dest_qpn != None:\n dest_qpn = self.qp_info_list[relative_dest_qpn]['qpn_rcv']\n dest_ip = self.qp_info_list[relative_dest_qpn]['ip_rcv']\n\n for packet in self.packet_list:\n if packet.is_bit_error() == False:\n continue\n\n if relative_dest_qpn == None or \\\n (packet.get_roce_dest_qp() == dest_qpn and packet.get_dst_ip() == dest_ip):\n error_pkt_list.append(packet)\n\n return error_pkt_list\n\n def get_dropped_pkts(self, relative_dest_qpn=None):\n \"\"\" Get the packets marked with drop flag\n\n Args:\n relative_dest_qpn (int): the relative destination QP number (None if not specified)\n\n Returns:\n list of RRoCEPacket objects: the list of packets marked with drop flag\n \"\"\"\n dropped_pkt_list = []\n\n if relative_dest_qpn != None:\n dest_qpn = self.qp_info_list[relative_dest_qpn]['qpn_rcv']\n dest_ip = self.qp_info_list[relative_dest_qpn]['ip_rcv']\n\n for packet in self.packet_list:\n if packet.is_dropped() == False:\n continue\n\n if relative_dest_qpn == None or \\\n (packet.get_roce_dest_qp() == dest_qpn and packet.get_dst_ip() == dest_ip):\n dropped_pkt_list.append(packet)\n\n return dropped_pkt_list\n\n def get_ecn_pkts(self):\n \"\"\" Get the packets marked with ECN\n\n Returns:\n list of RRoCEPacket objects: the list of packets marked with ECN\n \"\"\"\n ecn_pkt_list = []\n\n for packet in self.packet_list:\n if packet.is_ecn():\n ecn_pkt_list.append(packet)\n\n return ecn_pkt_list\n\n def get_cnp_pkts(self):\n \"\"\" Get the congestion notification packets\n\n Returns:\n list of RRoCEPacket objects: the list of congestion notification packets\n \"\"\"\n cnp_pkt_list = []\n\n for packet in self.packet_list:\n if packet.is_cnp():\n cnp_pkt_list.append(packet)\n\n return cnp_pkt_list\n\n def get_undelivered_pkts(self, relative_dest_qpn = None):\n \"\"\" Get the undelivered packets (dropped or marked with bit error)\n\n Args:\n relative_dest_qpn (int): the relative destination QP number (None if not specified)\n\n Returns:\n list of RRoCEPacket objects: the list of undelivered packets\n \"\"\"\n undelivered_pkt_list = []\n\n if relative_dest_qpn != None:\n dest_qpn = self.qp_info_list[relative_dest_qpn]['qpn_rcv']\n dest_ip = self.qp_info_list[relative_dest_qpn]['ip_rcv']\n\n for packet in self.packet_list:\n if packet.is_delivered() == True:\n continue\n\n if relative_dest_qpn == None or \\\n (packet.get_roce_dest_qp() == dest_qpn and packet.get_dst_ip() == dest_ip):\n undelivered_pkt_list.append(packet)\n\n return undelivered_pkt_list\n\n def get_nack(self, undelivered_pkt):\n \"\"\" Given an undelivered packet, return the NACK packet that triggers its retransmission.\n If there's no NACK packet found for the undelivered packet, return None.\n Note that for RDMA READ, NACK is essentially a READ request packet that triggers retransmission\n\n Args:\n undelivered_pkt (RRoCEPacket object): the undelivered packet\n\n Returns:\n RRoCEPacket object: the NACK packet that triggers the retransmission of the undelivered packet\n (None if not found)\n \"\"\"\n undelivered_pkt_dest_qpn = undelivered_pkt.get_roce_dest_qp()\n undelivered_pkt_dst_ip = undelivered_pkt.get_dst_ip()\n undelivered_pkt_psn = undelivered_pkt.get_roce_pkt_seq()\n undelivered_pkt_switch_seqnum = undelivered_pkt.get_switch_seqnum()\n matched_dest_qpn, matched_dst_ip = self.get_peer_qp_info(undelivered_pkt_dest_qpn, undelivered_pkt_dst_ip)\n\n if matched_dest_qpn == None or matched_dst_ip == None:\n logging.error(\"QP info of the undelivered packet not found in qp_info_list dumped by switch\")\n return None\n\n for packet in self.packet_list:\n if self.is_same_roce_data_pkt(packet, undelivered_pkt) and \\\n packet.get_switch_seqnum() > undelivered_pkt_switch_seqnum:\n return None\n\n if ((self.is_read and packet.is_roce_read_req()) or packet.is_roce_nack()) and \\\n packet.get_dst_ip() == matched_dst_ip and \\\n packet.get_roce_dest_qp() == matched_dest_qpn and \\\n packet.get_roce_pkt_seq() == undelivered_pkt_psn and \\\n packet.get_switch_seqnum() > undelivered_pkt_switch_seqnum:\n ## We return the first packet appears after the undelivered packet and matches the undelivered packet\n return packet\n\n return None\n\n def get_qp_first_nack_before_retrans(self, undelivered_pkt):\n \"\"\" For an undelivered packet, return the first NACK packet on its QP between it and its retransmission.\n If there's no NACK packet found before the retransmission, return None.\n Note that for RDMA READ, NACK is essentially a READ request packet\n\n Args:\n undelivered_pkt (RRoCEPacket object): the undelivered packet\n\n Returns:\n RRoCEPacket object: the first NACK packet on the QP between the undelivered packet and its retransmission\n (None if not found)\n \"\"\"\n undelivered_pkt_dest_qpn = undelivered_pkt.get_roce_dest_qp()\n undelivered_pkt_dst_ip = undelivered_pkt.get_dst_ip()\n undelivered_pkt_psn = undelivered_pkt.get_roce_pkt_seq()\n undelivered_pkt_switch_seqnum = undelivered_pkt.get_switch_seqnum()\n matched_dest_qpn, matched_dst_ip = self.get_peer_qp_info(undelivered_pkt_dest_qpn, undelivered_pkt_dst_ip)\n\n if matched_dest_qpn == None or matched_dst_ip == None:\n logging.error(\"QP info of the undelivered packet not found in qp_info_list dumped by switch\")\n return None\n\n for packet in self.packet_list:\n if self.is_same_roce_data_pkt(packet, undelivered_pkt) and \\\n packet.get_switch_seqnum() > undelivered_pkt_switch_seqnum:\n return None\n\n if ((self.is_read and packet.is_roce_read_req()) or packet.is_roce_nack()) and \\\n packet.get_dst_ip() == matched_dst_ip and \\\n packet.get_roce_dest_qp() == matched_dest_qpn and \\\n packet.get_roce_pkt_seq() <= undelivered_pkt_psn and \\\n packet.get_switch_seqnum() > undelivered_pkt_switch_seqnum:\n return packet\n\n return None\n\n def get_qp_next_delivered_pkt(self, current_pkt):\n \"\"\" For a packet, return the next delivered packet on the same QP.\n\n Args:\n current_pkt (RRoCEPacket object): the current packet\n\n Returns:\n RRoCEPacket object: the next delivered packet on the same QP (None if not found)\n \"\"\"\n switch_seqnum = current_pkt.get_switch_seqnum()\n\n for packet in self.packet_list:\n if self.is_same_qp_roce_data_pkt(packet, current_pkt) and \\\n packet.get_switch_seqnum() > switch_seqnum and \\\n packet.is_delivered():\n return packet\n\n return None\n\n def get_retransmit_pkt(self, undelivered_pkt):\n \"\"\" Given an undelivered packet, return its retransmission packet.\n\n Args:\n undelivered_pkt (RRoCEPacket object): the undelivered packet\n\n Returns:\n RRoCEPacket object: the retransmission packet of the undelivered packet (None if not found)\n \"\"\"\n undelivered_pkt_switch_seqnum = undelivered_pkt.get_switch_seqnum()\n\n for packet in self.packet_list:\n if self.is_same_roce_data_pkt(packet, undelivered_pkt) and \\\n packet.get_switch_seqnum() > undelivered_pkt_switch_seqnum:\n ## We return the first packet appears after the undelivered packet and matches the undelivered packet\n return packet\n\n return None\n\n def get_latency_between_pkts(self, packet_alpha, packet_beta):\n \"\"\" Return the time of packet_beta - time of packet_alpha in seconds\n\n Args:\n packet_alpha (RRoCEPacket object): the first packet\n packet_beta (RRoCEPacket object): the second packet\n\n Returns:\n float: the time difference between two packets in seconds\n \"\"\"\n return packet_beta.get_switch_timestamp() - packet_alpha.get_switch_timestamp()\n\n def is_same_roce_data_pkt(self, packet_alpha, packet_beta):\n \"\"\" Return if two packets are the same RoCE data packet (same src ip, dst ip, dest qp, and psn)\n\n Args:\n packet_alpha (RRoCEPacket object): the first packet\n packet_beta (RRoCEPacket object): the second packet\n\n Returns:\n bool: True if two packets are the same RoCE data packet, False otherwise\n \"\"\"\n return packet_alpha.get_src_ip() == packet_beta.get_src_ip() and \\\n packet_alpha.get_dst_ip() == packet_beta.get_dst_ip() and \\\n packet_alpha.get_roce_dest_qp() == packet_beta.get_roce_dest_qp() and \\\n packet_alpha.get_roce_pkt_seq() == packet_beta.get_roce_pkt_seq()\n\n def is_same_qp_roce_data_pkt(self, packet_alpha, packet_beta):\n \"\"\" Return if two packets are RoCE data packets on the same QP (same src ip, dst ip, and dest qp)\n\n Args:\n packet_alpha (RRoCEPacket object): the first packet\n packet_beta (RRoCEPacket object): the second packet\n\n Returns:\n bool: True if two packets are RoCE data packets on the same QP, False otherwise\n \"\"\"\n return packet_alpha.get_src_ip() == packet_beta.get_src_ip() and \\\n packet_alpha.get_dst_ip() == packet_beta.get_dst_ip() and \\\n packet_alpha.get_roce_dest_qp() == packet_beta.get_roce_dest_qp()\n\n def get_qp_next_delivered_pkt_latency(self, pkt):\n \"\"\" Get the latency between 'pkt' and next 'delivered' packet on the same QP\n\n Args:\n pkt (RRoCEPacket object): the packet\n\n Returns:\n float: the latency between 'pkt' and next 'delivered' packet on the same QP\n (None if not found)\n \"\"\"\n\n next_pkt = self.get_qp_next_delivered_pkt(pkt)\n if next_pkt is None:\n return None\n\n return self.get_latency_between_pkts(pkt, next_pkt)\n\n def get_nack_gen_latency(self, undelivered_pkt):\n \"\"\" For an undelivered packet, return the NACK generation latency, i.e., the duration from the detection of\n the undelivered packet to the generation of the NACK packet that triggers its retransmission.\n\n Args:\n undelivered_pkt (RRoCEPacket object): the undelivered packet\n\n Returns:\n float: the NACK generation latency for the undelivered packet (None if not found)\n \"\"\"\n nack_pkt = self.get_nack(undelivered_pkt)\n if nack_pkt == None:\n return None\n\n # NACK should be triggered by the next delivered packet on the same QP\n next_delivered_pkt = self.get_qp_next_delivered_pkt(undelivered_pkt)\n if self.is_same_roce_data_pkt(next_delivered_pkt, undelivered_pkt):\n # We should never reach here\n return None\n\n nack_gen_latency = self.get_latency_between_pkts(next_delivered_pkt, nack_pkt)\n return nack_gen_latency\n\n def get_nack_resp_latency(self, undelivered_pkt):\n \"\"\" For an undelivered packet, return the NACK response latency, i.e., the duration from the generation of\n the NACK packet to the retransmission of this undelivered packet.\n\n Args:\n undelivered_pkt (RRoCEPacket object): the undelivered packet\n\n Returns:\n float: the NACK response latency for the undelivered packet (None if not found)\n \"\"\"\n nack_pkt = self.get_nack(undelivered_pkt)\n if nack_pkt == None:\n return None\n\n retransmit_pkt = self.get_retransmit_pkt(undelivered_pkt)\n if retransmit_pkt == None:\n return None\n\n nack_resp_latency = self.get_latency_between_pkts(nack_pkt, retransmit_pkt)\n return nack_resp_latency\n\n def get_retransmit_latency(self, undelivered_pkt):\n \"\"\" For an undelivered packet, return the retransmission latency, i.e., the duration from the packet\n to its retransmission.\n\n Args:\n undelivered_pkt (RRoCEPacket object): the undelivered packet\n\n Returns:\n float: the retransmission latency for the undelivered packet (None if not found)\n \"\"\"\n retransmit_pkt = self.get_retransmit_pkt(undelivered_pkt)\n if retransmit_pkt == None:\n return None\n\n retransmit_latency = self.get_latency_between_pkts(undelivered_pkt, retransmit_pkt)\n return retransmit_latency\n\n def get_nack_gen_latency_list(self, relative_dest_qpn=None):\n \"\"\" Return a list of NACK generation latency for all undelivered packets with relative_dest_qpn\n\n Args:\n relative_dest_qpn (int): the relative destination QP number (None if not specified)\n\n Returns:\n list of float: a list of NACK generation latency for all undelivered packets with relative_dest_qpn\n \"\"\"\n undelivered_pkts = self.get_undelivered_pkts(relative_dest_qpn)\n nack_latency_list = []\n\n for undelivered_pkt in undelivered_pkts:\n nack_pkt = self.get_nack(undelivered_pkt)\n if nack_pkt == None:\n nack_latency_list.append(None)\n else:\n nack_latency = self.get_latency_between_pkts(undelivered_pkt, nack_pkt)\n nack_latency_list.append(nack_latency)\n\n return nack_latency_list\n\n def get_retransmit_latency_list(self, relative_dest_qpn):\n \"\"\" Return a list of retransmission latency for all undelivered packets with relative_dest_qpn\n\n Args:\n relative_dest_qpn (int): the relative destination QP number (None if not specified)\n\n Returns:\n list of float: a list of retransmission latency for all undelivered packets with relative_dest_qpn\n \"\"\"\n undelivered_pkts = self.get_undelivered_pkts(relative_dest_qpn)\n retransmit_latency_list = []\n\n for undelivered_pkt in undelivered_pkts:\n retransmit_pkt = self.get_retransmit_pkt(undelivered_pkt)\n if retransmit_pkt == None:\n retransmit_latency_list.append(None)\n else:\n retransmit_latency = self.get_latency_between_pkts(undelivered_pkt, retransmit_pkt)\n retransmit_latency_list.append(retransmit_latency)\n\n return retransmit_latency_list" }, { "identifier": "config_stream_handler", "path": "lumina/utils/config_loggers.py", "snippet": "def config_stream_handler(logger):\n \"\"\" Configure stream handler\n\n Args:\n logger (logging.Logger): Logger object\n\n Returns:\n N/A\n \"\"\"\n logger.setLevel(logging.INFO)\n console = logging.StreamHandler()\n console.setLevel(logging.INFO)\n console.setFormatter(logging.Formatter('%(name)-18s: %(levelname)-8s %(message)s'))\n logger.addHandler(console)" }, { "identifier": "config_file_handler", "path": "lumina/utils/config_loggers.py", "snippet": "def config_file_handler(logger, log_file, no_format=False):\n \"\"\" Configure file handler\n\n Args:\n logger (logging.Logger): Logger object\n log_file (str): Log file path\n no_format (bool): If True, do not format log messages (default: False)\n\n Returns:\n N/A\n \"\"\"\n logger.setLevel(logging.INFO)\n file_handler = logging.FileHandler(log_file, mode=\"w\")\n if no_format == False:\n file_handler.setFormatter(logging.Formatter('%(name)-18s: %(levelname)-8s %(message)s'))\n file_handler.setLevel(logging.INFO)\n logger.addHandler(file_handler)" }, { "identifier": "TRIGGER_OOS", "path": "lumina/analyzer/packet_parser/roce_packet.py", "snippet": "TRIGGER_OOS = 1" }, { "identifier": "TRIGGER_TIMEOUT", "path": "lumina/analyzer/packet_parser/roce_packet.py", "snippet": "TRIGGER_TIMEOUT = 2" } ]
import argparse, os, math, glob, logging, time import lumina.analyzer.checker.integrity_check as integrity_check import lumina.analyzer.checker.host_check as host_check import lumina.analyzer.checker.gbn_check as gbn_check import lumina.analyzer.checker.read_gbn_check as read_gbn_check import lumina.orchestrator.host as host import lumina.orchestrator.switch as switch from lumina.analyzer.main import get_qp_info_list from lumina.orchestrator.main import Orchestrator from lumina.analyzer.counter.switch_counter import SwitchCounter from lumina.analyzer.counter.host_counter import MLNXHostCounter, IntelHostCounter from lumina.analyzer.pcap_processor.pcap_process import get_packet_list from lumina.analyzer.measurer.latency_measure import LatencyMeasure from lumina.utils.config_loggers import config_stream_handler, config_file_handler from lumina.analyzer.packet_parser.roce_packet import TRIGGER_OOS, TRIGGER_TIMEOUT
15,057
logger.info('\t\t Next delivered packet delay: %fus' % (next_delivered_pkt_delay * 1e6)) logger.info("\t\t NACK READ request generation latency: %fus" % (nack_gen_latency * 1e6)) logger.info('\t\t NACK READ request response latency: %fus' % (nack_resp_latency * 1e6)) elif trigger == TRIGGER_TIMEOUT: nack_resp_latency = latency_measurement.get_nack_resp_latency(pkt) logger.info("\t\t Timeout triggered retransmission") logger.info("\t\t Retransmission latency: %fus" % (retrans_latency * 1e6)) logger.info('\t\t NACK READ request response latency: %fus' % (nack_resp_latency * 1e6)) else: logger.error("\t\t NACK READ request should be triggered by either OOS or timeout") else: nack = latency_measurement.get_qp_first_nack_before_retrans(pkt) if nack is None: logger.error("\t\t Cannot find the NACK READ request to recover this lost packet") return trigger = nack.get_trigger() if trigger == TRIGGER_OOS: logger.info("\t\t Out of sequence (OOS) triggered retransmission") logger.info("\t\t But the NACK READ request indicates a loss (%d) before this packet (%d)" %\ (nack.get_roce_pkt_seq(), pkt.get_roce_pkt_seq())) logger.info("\t\t Retransmission latency: %fus" % (retrans_latency * 1e6)) elif trigger == TRIGGER_TIMEOUT: logger.info("\t\t Timeout triggered retransmission") logger.info("\t\t But the NACK READ request indicates a loss (%d) before this packet (%d)" %\ (nack.get_roce_pkt_seq(), pkt.get_roce_pkt_seq())) logger.info("\t\t Retransmission latency: %fus" % (retrans_latency * 1e6)) else: logger.error("\t\t NACK READ request should be triggered by either OOS or timeout") else: # For other verbs, we can only find a NACK in case of out of sequence arriving packets if latency_measurement.get_nack(pkt) != None: # Out of sequence/NACK triggered retransmission next_delivered_pkt_delay = latency_measurement.get_qp_next_delivered_pkt_latency(pkt) nack_gen_latency = latency_measurement.get_nack_gen_latency(pkt) nack_resp_latency = latency_measurement.get_nack_resp_latency(pkt) logger.info("\t\t Out of sequence (OOS) triggered retransmission") logger.info("\t\t Retransmission latency: %fus" % (retrans_latency * 1e6)) logger.info('\t\t Next delivered packet delay: %fus' % (next_delivered_pkt_delay * 1e6)) logger.info("\t\t NACK generation latency: %fus" % (nack_gen_latency * 1e6)) logger.info('\t\t NACK response latency: %fus' % (nack_resp_latency * 1e6)) elif latency_measurement.get_qp_first_nack_before_retrans(pkt) != None: logger.info("\t\t Out of sequence (OOS) triggered retransmission") logger.info("\t\t But the NACK indicates a loss (%d) before this packet (%d)") logger.info("\t\t Retransmission latency: %fus" % (retrans_latency * 1e6)) else: logger.info("\t\t Timeout triggered retransmission") logger.info("\t\t Retransmission latency: %fus" % (retrans_latency * 1e6)) def verify_results(orchestrator): """ Verify the experiment results Args: orchestrator (Orchestrator object): Orchestrator object that contains all the configurations Returns: N/A """ result_dir = orchestrator.result_path num_repeats = orchestrator.num_repeats mtu = orchestrator.traffic_conf['mtu'] msg_size = orchestrator.traffic_conf['message-size'] num_msgs_per_qp = orchestrator.traffic_conf['num-msgs-per-qp'] aggregate_pcap_filename = orchestrator.aggregate_pcap_filename port_map = {'requester': orchestrator.requester.conf['nic']['switch-port'], 'responder': orchestrator.responder.conf['nic']['switch-port'], 'requester-mirror': orchestrator.requester_mirror.conf['nic']['switch-port'], 'responder-mirror': orchestrator.responder_mirror.conf['nic']['switch-port']} requester_ip_list = orchestrator.get_requester_ip_list() responder_ip_list = orchestrator.get_responder_ip_list() for iter in range(num_repeats): iter = str(iter) result_logger = logging.getLogger('Analysis iter %s' % (iter)) result_logger.handlers.clear() config_file_handler(logger=result_logger, log_file=os.path.join(result_dir, iter, RESULT_FILENAME), no_format=True) result_logger.info("=" * 100) result_logger.info("Iteration %s" % iter) switch_msg_snapshot = os.path.join(result_dir, iter, switch.SWITCH_RESULT_DIR, switch.SWITCH_MESSAGE_SNAPSHOT) switch_state_snapshot = os.path.join(result_dir, iter, switch.SWITCH_RESULT_DIR, switch.SWITCH_STATE_SNAPSHOT) pcap_filename = os.path.join(result_dir, iter, host.PCAP_RESULT_DIR, aggregate_pcap_filename) requester_counter_start = os.path.join(result_dir, iter, host.RDMA_RESULT_DIR, host.REQ_START_COUNTER_FILE_NAME) requester_counter_finish = os.path.join(result_dir, iter, host.RDMA_RESULT_DIR, host.REQ_FINISH_COUNTER_FILE_NAME) responder_counter_start = os.path.join(result_dir, iter, host.RDMA_RESULT_DIR, host.RSP_START_COUNTER_FILE_NAME) responder_counter_finish = os.path.join(result_dir, iter, host.RDMA_RESULT_DIR, host.RSP_FINISH_COUNTER_FILE_NAME)
## All logs will be logged into file LOG_FILENAME LOG_FILENAME = "test_gbn.log" ## Results (checkers and measurements) will also be dumped into file RESULT_FILENAME RESULT_FILENAME = "result.log" ## Max # of retries for each experiment iteration MAX_NB_EXP_RETRIES = 3 def setup_root_logger(orchestrator): """ Setup the root logger for the test Args: orchestrator (Orchestrator object): Orchestrator object that contains all the configurations Returns: N/A """ root_logger = logging.getLogger() root_logger.handlers.clear() config_stream_handler(root_logger) config_file_handler(logger=root_logger, log_file=os.path.join(orchestrator.result_path, LOG_FILENAME), no_format=False) def run_traffic(orchestrator): """ Run the traffic and collect the results Args: orchestrator (Orchestrator object): Orchestrator object that contains all the configurations Returns: bool: True if the experiment is successful, False otherwise """ orchestrator.rm_old_files() if orchestrator.sync_and_compile() == False: logging.error("Failed to sync and compile the code") sys.exit(-1) logging.info("Sync and compile completed") if orchestrator.generate_switch_config_file() == False: logging.error("Failed to generate switch configuration file") sys.exit(-1) num_repeats = orchestrator.get_num_repeats() for i in range(num_repeats): logging.info("=" * 100) nb_retry = 0 iter_result = False while nb_retry < MAX_NB_EXP_RETRIES: if orchestrator.run_experiment() == False: logging.error("Iteration %d: Failed to complete experiment" % i) logging.error("Iteration %d: Rerun experiment (retry: %d)" % i, nb_retry) nb_retry += 1 orchestrator.clean_up() time.sleep(5) continue logging.info("Iteration %d: Completed experiment" % i) try: orchestrator.clean_up() orchestrator.fetch_results(i) logging.info("Iteration %d: Fetch experiment results" % i) orchestrator.merge_traces(i) logging.info("Iteration %d: Merge the pcap files" % i) except: logging.error("Iteration %d: Result collection failed" % (i)) logging.error("Iteration %d: Rerun experiment (retry: %d)" % (i, nb_retry)) nb_retry += 1 time.sleep(5) continue if orchestrator.check_integrity(i) == False: logging.error("Iteration %d: Integrity check failed" % (i)) logging.error("Iteration %d: Rerun experiment (retry: %d)" % (i, nb_retry)) nb_retry += 1 time.sleep(5) continue iter_result = True break if iter_result is False: logging.error("Iteration %d: Still failed after %d retries" % (i, nb_retry)) return False return True def analyze_retrans_latency(pkt, latency_measurement, is_read, logger): """ Analyze the retransmission latency breakdown for an undelivered packet Args: pkt (Packet object): The undelivered packet latency_measurement (LatencyMeasure object): A LatencyMeasure object that can compute latency breakdown is_read (bool): If we use RDMA READ in this experiment logger (logging.Logger): A logger object Returns: N/A """ # All the undelivered packets should be retransmitted in our test cases if latency_measurement.get_retransmit_pkt(pkt) == None: logger.error("\t\t No retransmit packet found for this packet") logger.error("\t\t It is possible that this undelivered packet is a redundant transmission") return retrans_latency = latency_measurement.get_retransmit_latency(pkt) if is_read == True: # For RDMA READ, we should always find a NACK READ request that triggers retransmission nack = latency_measurement.get_nack(pkt) if nack is not None: trigger = nack.get_trigger() if trigger == TRIGGER_OOS: next_delivered_pkt_delay = latency_measurement.get_qp_next_delivered_pkt_latency(pkt) nack_gen_latency = latency_measurement.get_nack_gen_latency(pkt) nack_resp_latency = latency_measurement.get_nack_resp_latency(pkt) logger.info("\t\t Out of sequence (OOS) triggered retransmission") logger.info("\t\t Retransmission latency: %fus" % (retrans_latency * 1e6)) logger.info('\t\t Next delivered packet delay: %fus' % (next_delivered_pkt_delay * 1e6)) logger.info("\t\t NACK READ request generation latency: %fus" % (nack_gen_latency * 1e6)) logger.info('\t\t NACK READ request response latency: %fus' % (nack_resp_latency * 1e6)) elif trigger == TRIGGER_TIMEOUT: nack_resp_latency = latency_measurement.get_nack_resp_latency(pkt) logger.info("\t\t Timeout triggered retransmission") logger.info("\t\t Retransmission latency: %fus" % (retrans_latency * 1e6)) logger.info('\t\t NACK READ request response latency: %fus' % (nack_resp_latency * 1e6)) else: logger.error("\t\t NACK READ request should be triggered by either OOS or timeout") else: nack = latency_measurement.get_qp_first_nack_before_retrans(pkt) if nack is None: logger.error("\t\t Cannot find the NACK READ request to recover this lost packet") return trigger = nack.get_trigger() if trigger == TRIGGER_OOS: logger.info("\t\t Out of sequence (OOS) triggered retransmission") logger.info("\t\t But the NACK READ request indicates a loss (%d) before this packet (%d)" %\ (nack.get_roce_pkt_seq(), pkt.get_roce_pkt_seq())) logger.info("\t\t Retransmission latency: %fus" % (retrans_latency * 1e6)) elif trigger == TRIGGER_TIMEOUT: logger.info("\t\t Timeout triggered retransmission") logger.info("\t\t But the NACK READ request indicates a loss (%d) before this packet (%d)" %\ (nack.get_roce_pkt_seq(), pkt.get_roce_pkt_seq())) logger.info("\t\t Retransmission latency: %fus" % (retrans_latency * 1e6)) else: logger.error("\t\t NACK READ request should be triggered by either OOS or timeout") else: # For other verbs, we can only find a NACK in case of out of sequence arriving packets if latency_measurement.get_nack(pkt) != None: # Out of sequence/NACK triggered retransmission next_delivered_pkt_delay = latency_measurement.get_qp_next_delivered_pkt_latency(pkt) nack_gen_latency = latency_measurement.get_nack_gen_latency(pkt) nack_resp_latency = latency_measurement.get_nack_resp_latency(pkt) logger.info("\t\t Out of sequence (OOS) triggered retransmission") logger.info("\t\t Retransmission latency: %fus" % (retrans_latency * 1e6)) logger.info('\t\t Next delivered packet delay: %fus' % (next_delivered_pkt_delay * 1e6)) logger.info("\t\t NACK generation latency: %fus" % (nack_gen_latency * 1e6)) logger.info('\t\t NACK response latency: %fus' % (nack_resp_latency * 1e6)) elif latency_measurement.get_qp_first_nack_before_retrans(pkt) != None: logger.info("\t\t Out of sequence (OOS) triggered retransmission") logger.info("\t\t But the NACK indicates a loss (%d) before this packet (%d)") logger.info("\t\t Retransmission latency: %fus" % (retrans_latency * 1e6)) else: logger.info("\t\t Timeout triggered retransmission") logger.info("\t\t Retransmission latency: %fus" % (retrans_latency * 1e6)) def verify_results(orchestrator): """ Verify the experiment results Args: orchestrator (Orchestrator object): Orchestrator object that contains all the configurations Returns: N/A """ result_dir = orchestrator.result_path num_repeats = orchestrator.num_repeats mtu = orchestrator.traffic_conf['mtu'] msg_size = orchestrator.traffic_conf['message-size'] num_msgs_per_qp = orchestrator.traffic_conf['num-msgs-per-qp'] aggregate_pcap_filename = orchestrator.aggregate_pcap_filename port_map = {'requester': orchestrator.requester.conf['nic']['switch-port'], 'responder': orchestrator.responder.conf['nic']['switch-port'], 'requester-mirror': orchestrator.requester_mirror.conf['nic']['switch-port'], 'responder-mirror': orchestrator.responder_mirror.conf['nic']['switch-port']} requester_ip_list = orchestrator.get_requester_ip_list() responder_ip_list = orchestrator.get_responder_ip_list() for iter in range(num_repeats): iter = str(iter) result_logger = logging.getLogger('Analysis iter %s' % (iter)) result_logger.handlers.clear() config_file_handler(logger=result_logger, log_file=os.path.join(result_dir, iter, RESULT_FILENAME), no_format=True) result_logger.info("=" * 100) result_logger.info("Iteration %s" % iter) switch_msg_snapshot = os.path.join(result_dir, iter, switch.SWITCH_RESULT_DIR, switch.SWITCH_MESSAGE_SNAPSHOT) switch_state_snapshot = os.path.join(result_dir, iter, switch.SWITCH_RESULT_DIR, switch.SWITCH_STATE_SNAPSHOT) pcap_filename = os.path.join(result_dir, iter, host.PCAP_RESULT_DIR, aggregate_pcap_filename) requester_counter_start = os.path.join(result_dir, iter, host.RDMA_RESULT_DIR, host.REQ_START_COUNTER_FILE_NAME) requester_counter_finish = os.path.join(result_dir, iter, host.RDMA_RESULT_DIR, host.REQ_FINISH_COUNTER_FILE_NAME) responder_counter_start = os.path.join(result_dir, iter, host.RDMA_RESULT_DIR, host.RSP_START_COUNTER_FILE_NAME) responder_counter_finish = os.path.join(result_dir, iter, host.RDMA_RESULT_DIR, host.RSP_FINISH_COUNTER_FILE_NAME)
switch_counter = SwitchCounter(switch_state_snapshot, port_map)
2
2023-12-09 08:21:14+00:00
24k
ebb-earl-co/tidal-wave
tidal_wave/main.py
[ { "identifier": "login", "path": "tidal_wave/login.py", "snippet": "def login(\n audio_format: AudioFormat,\n) -> Tuple[Optional[requests.Session], Optional[AudioFormat]]:\n \"\"\"Given a selected audio_format, either log in \"automatically\"\n via the Fire TV OAuth 2.0 flow, or ask for an Android-/Windows-/MacOS-\n gleaned API token; the latter to be able to access HiRes fLaC audio.\n Returns a tuple of a requests.Session object, if no error, and the\n AudioFormat instance passed in; or (None, \"\") in the event of error.\n \"\"\"\n android_formats: Set[AudioFormat] = {\n AudioFormat.sony_360_reality_audio,\n AudioFormat.hi_res,\n }\n fire_tv_formats: Set[AudioFormat] = {\n AudioFormat.dolby_atmos,\n AudioFormat.mqa,\n AudioFormat.lossless,\n AudioFormat.high,\n AudioFormat.low,\n }\n if audio_format in fire_tv_formats:\n return (login_fire_tv(), audio_format)\n elif audio_format in android_formats:\n options: set = {\"android\", \"a\", \"windows\", \"w\"}\n _input: str = \"\"\n while _input not in options:\n _input = typer.prompt(\n \"For which of Android [a] or Windows [w] would you like to provide an API token?\"\n ).lower()\n else:\n if _input in {\"android\", \"a\"}:\n return (login_android(), audio_format)\n elif _input in {\"windows\", \"w\"}:\n return (login_windows(), audio_format)\n else:\n logger.critical(\n \"Please provide one of the following: \"\n f\"{', '.join(e.value for e in AudioFormat)}\"\n )\n return (None, \"\")" }, { "identifier": "AudioFormat", "path": "tidal_wave/login.py", "snippet": "class AudioFormat(str, Enum):\n sony_360_reality_audio = \"360\"\n dolby_atmos = \"Atmos\"\n hi_res = \"HiRes\"\n mqa = \"MQA\"\n lossless = \"Lossless\"\n high = \"High\"\n low = \"Low\"" }, { "identifier": "LogLevel", "path": "tidal_wave/login.py", "snippet": "class LogLevel(str, Enum):\n debug = \"DEBUG\" # 10\n info = \"INFO\" # 20\n warning = \"WARNING\" # 30\n error = \"ERROR\" # 40\n critical = \"CRITICAL\" # 50" }, { "identifier": "Album", "path": "tidal_wave/album.py", "snippet": "class Album:\n album_id: int\n\n def __post_init__(self):\n self.album_dir: Optional[Path] = None\n self.album_cover_saved: bool = False\n\n def get_items(self, session: Session):\n \"\"\"This method populates self.tracks by requesting from\n TIDAL albums/items endpoint.\"\"\"\n album_items: AlbumsItemsResponseJSON = request_album_items(\n session=session, identifier=self.album_id\n )\n _items = album_items.items if album_items is not None else ()\n self.tracks = tuple(_item.item for _item in _items)\n\n def get_metadata(self, session: Session):\n \"\"\"This method populates self.metadata by requesting from\n TIDAL /albums endpoint\"\"\"\n self.metadata: AlbumsEndpointResponseJSON = request_albums(\n session=session, identifier=self.album_id\n )\n\n def get_review(self, session: Session):\n \"\"\"This method requests the review corresponding to self.album_id\n in TIDAL. If it exists, it is written to disk as AlbumReview.json\n in self.album_dir\"\"\"\n self.album_review: Optional[AlbumsReviewResponseJSON] = request_album_review(\n session=session, identifier=self.album_id\n )\n if self.album_review is not None:\n (self.album_dir / \"AlbumReview.json\").write_text(\n self.album_review.to_json()\n )\n\n def set_dir(self, out_dir: Path):\n \"\"\"This method populates self.album_dir as a sub-subdirectory of\n out_dir: its parent directory is the name of the (main) artist of\n the album\"\"\"\n artist_substring: str = self.metadata.artist.name.replace(\"..\", \"\")\n album_substring: str = (\n f\"{self.metadata.name.replace('..', '')} \"\n f\"[{self.metadata.id}] [{self.metadata.release_date.year}]\"\n )\n self.album_dir = out_dir / artist_substring / album_substring\n self.album_dir.mkdir(parents=True, exist_ok=True)\n\n if self.metadata.number_of_volumes > 1:\n for v in range(1, self.metadata.number_of_volumes + 1):\n volume_substring: str = f\"Volume {v}\"\n (out_dir / artist_substring / album_substring / volume_substring).mkdir(\n parents=True, exist_ok=True\n )\n\n def save_cover_image(self, session: Session, out_dir: Path):\n \"\"\"This method writes cover.jpg in self.album_dir via the\n utils.download_cover_image() function. If successful,\n then self.album_cover_saved takes the value True\"\"\"\n if self.album_dir is None:\n self.set_dir(out_dir=out_dir)\n self.cover_path: Path = self.album_dir / \"cover.jpg\"\n if not self.cover_path.exists():\n download_cover_image(\n session=session,\n cover_uuid=self.metadata.cover,\n output_dir=self.album_dir,\n )\n else:\n self.album_cover_saved = True\n\n def get_tracks(\n self, session: Session, audio_format: AudioFormat, out_dir: Path\n ) -> List[Optional[str]]:\n \"\"\"This method uses self.tracks to call track.Track.get() for each\n track in self.tracks. It uses the result of each of these calls to\n populate self.track_files\"\"\"\n track_files: List[str] = [None] * self.metadata.number_of_tracks\n for i, t in enumerate(self.tracks): # type(t) is TracksEndpointResponseJSON\n track: Track = Track(track_id=t.id)\n\n track_files_value: Optional[str] = track.get(\n session=session,\n audio_format=audio_format,\n out_dir=out_dir,\n metadata=t,\n album=self.metadata,\n )\n track_files[i] = {track.metadata.track_number: track_files_value}\n else:\n self.track_files = track_files\n\n def dumps(self):\n \"\"\"This method returns a JSON-like string of self.track_files\"\"\"\n return json.dumps(self.track_files)\n\n def dump(self, fp=sys.stdout):\n \"\"\"This method writes to (by default) STDOUT a\n JSON-like string of self.track_files\"\"\"\n json.dump(self.track_files, fp)\n\n def get(\n self,\n session: Session,\n audio_format: AudioFormat,\n out_dir: Path,\n metadata: Optional[AlbumsEndpointResponseJSON] = None,\n ):\n \"\"\"This method is the driver method of the class. It calls the\n other methods in order:\n 1. get_metadata()\n 2. get_items()\n 3. save_cover_image()\n 4. get_review()\n 5. get_tracks()\n \"\"\"\n if metadata is None:\n self.get_metadata(session)\n else:\n self.metadata = metadata\n \n if self.metadata is None:\n self.track_files = {}\n return\n\n self.get_items(session)\n self.save_cover_image(session, out_dir)\n self.get_review(session)\n self.get_tracks(session, audio_format, out_dir)" }, { "identifier": "Artist", "path": "tidal_wave/artist.py", "snippet": "class Artist:\n artist_id: int\n\n def set_metadata(self, session: Session):\n \"\"\"This function requests from TIDAL API endpoint /artists and\n stores the results in self.metadata\"\"\"\n self.metadata: Optional[ArtistsEndpointResponseJSON] = request_artists(\n session, self.artist_id\n )\n\n def save_artist_image(self, session: Session):\n \"\"\"This method writes the bytes of self.metadata.picture to\n the file cover.jpg in self.artist_dir\"\"\"\n artist_image: Path = self.artist_dir / \"cover.jpg\"\n if not artist_image.exists():\n download_cover_image(\n session, self.metadata.picture, self.artist_dir, dimension=750\n )\n\n def set_albums(self, session: Session):\n \"\"\"This method requests from TIDAL API endpoint /artists/albums and\n stores the results in self.albums\"\"\"\n self.albums: Optional[ArtistsAlbumsResponseJSON] = request_artists_albums(\n session, self.artist_id\n )\n\n def set_audio_works(self, session: Session):\n \"\"\"This method requests from TIDAL API endpoint\n /artists/albums?filter=EPSANDSINGLES and stores the results in self.albums\"\"\"\n self.albums: Optional[ArtistsAlbumsResponseJSON] = request_artists_audio_works(\n session, self.artist_id\n )\n\n def set_videos(self, session: Session):\n \"\"\"This method requests from TIDAL API endpoint /artists/videos and\n stores the results in self.albums\"\"\"\n self.videos: Optional[ArtistsVideosResponseJSON] = request_artists_videos(\n session, self.artist_id\n )\n\n def set_dir(self, out_dir: Path):\n \"\"\"This method sets self.artist_dir and creates the directory on the file system\n if it does not exist\"\"\"\n self.name: str = self.metadata.name.replace(\"..\", \"\")\n self.artist_dir = out_dir / self.name\n self.artist_dir.mkdir(parents=True, exist_ok=True)\n\n def get_albums(\n self,\n session: Session,\n audio_format: AudioFormat,\n out_dir: Path,\n include_eps_singles: bool = False,\n ) -> List[Optional[str]]:\n \"\"\"This method first fetches the total albums on TIDAL's service\n corresponding to the artist with ID self.artist_id. Then, each of\n the albums (and, optionally, EPs and singles) is requested and\n written to subdirectories of out_dir\"\"\"\n if include_eps_singles:\n self.set_audio_works(session)\n logger.info(\n f\"Starting attempt to get {self.albums.total_number_of_items} \"\n \"albums, EPs, and singles for artist with ID \"\n f\"{self.metadata.id}, '{self.name}'\"\n )\n else:\n self.set_albums(session)\n logger.info(\n f\"Starting attempt to get {self.albums.total_number_of_items} albums \"\n f\"for artist with ID {self.metadata.id}, '{self.name}'\"\n )\n\n for i, a in enumerate(self.albums.items):\n album: Album = Album(album_id=a.id)\n album.get(\n session=session,\n audio_format=audio_format,\n out_dir=out_dir,\n metadata=a,\n )\n\n def get_videos(\n self,\n session: Session,\n out_dir: Path,\n ) -> List[Optional[str]]:\n \"\"\"This method sets self.videos by calling self.set_videos()\n then, for each video, instantiates a Video object and executes\n video.get()\"\"\"\n self.set_videos(session)\n logger.info(\n f\"Starting attempt to get {self.videos.total_number_of_items} videos \"\n f\"for artist with ID {self.metadata.id}, '{self.name}'\"\n )\n for i, v in enumerate(self.videos.items):\n video: Video = Video(video_id=v.id)\n video.get(\n session=session,\n out_dir=out_dir,\n metadata=v,\n )\n\n def get(\n self,\n session: Session,\n audio_format: AudioFormat,\n out_dir: Path,\n include_eps_singles: bool,\n ):\n \"\"\"This is the driver method of the class. It executes the other\n methods in order:\n 1. set_metadata\n 2. set_dir\n 3. save_artist_image\n 4. get_videos\n 5. get_albums\n \"\"\"\n self.set_metadata(session)\n \n if self.metadata is None:\n return\n \n self.set_dir(out_dir)\n self.save_artist_image(session)\n self.get_videos(session, out_dir)\n if include_eps_singles:\n self.get_albums(session, audio_format, out_dir, include_eps_singles=True)\n self.get_albums(session, audio_format, out_dir, include_eps_singles=False)" }, { "identifier": "Mix", "path": "tidal_wave/mix.py", "snippet": "class Mix:\n mix_id: str\n\n def __post_init__(self):\n self.mix_dir: Optional[Path] = None\n self.mix_cover_saved: bool = False\n\n def get_metadata(self, session: Session):\n \"\"\"Request from TIDAL API /playlists endpoint\"\"\"\n self.metadata: Optional[PlaylistsEndpointResponseJSON] = request_mixes(\n session=session, mix_id=self.mix_id\n )\n \n if self.metadata is None:\n return\n \n self.name = (\n self.metadata.title.replace(\"/\", \"_\")\n .replace(\"|\", \"_\")\n .replace(\":\", \" -\")\n .replace('\"', \"\")\n .replace(\"..\", \"\")\n )\n\n def set_items(self, session: Session):\n \"\"\"Uses data from TIDAL API /mixes/items endpoint to\n populate self.items\"\"\"\n mix_items: Optional[MixesItemsResponseJSON] = get_mix(\n session=session, mix_id=self.mix_id\n )\n if mix_items is None:\n self.items = tuple()\n else:\n self.items: Tuple[Optional[MixItem]] = tuple(mix_items.items)\n\n def set_dir(self, out_dir: Path):\n \"\"\"Populates self.mix_dir based on self.name, self.mix_id\"\"\"\n mix_substring: str = f\"{self.name} [{self.mix_id}]\"\n self.mix_dir: Path = out_dir / \"Mixes\" / mix_substring\n self.mix_dir.mkdir(parents=True, exist_ok=True)\n\n def save_cover_image(self, session: Session, out_dir: Path):\n \"\"\"Requests self.metadata.image and attempts to write it to disk\"\"\"\n if self.mix_dir is None:\n self.set_dir(out_dir=out_dir)\n self.cover_path: Path = self.mix_dir / \"cover.jpg\"\n if not self.cover_path.exists():\n with session.get(\n url=self.metadata.image, params={k: None for k in session.params}\n ) as r:\n (self.mix_dir / \"cover.jpg\").write_bytes(r.content)\n\n self.mix_cover_saved = True\n else:\n self.mix_cover_saved = True\n\n def get_items(self, session: Session, audio_format: AudioFormat):\n \"\"\"Using either Track.get() or Video.get(), attempt to request\n the data for each track or video in self.items\"\"\"\n if len(self.items) == 0:\n return\n tracks_videos: list = [None] * len(self.items)\n for i, item in enumerate(self.items):\n if item is None:\n tracks_videos[i] = None\n continue\n elif isinstance(item, TracksEndpointResponseJSON):\n track: Track = Track(track_id=item.id)\n track.get(\n session=session,\n audio_format=audio_format,\n out_dir=self.mix_dir,\n metadata=item,\n )\n tracks_videos[i] = track\n elif isinstance(item, VideosEndpointResponseJSON):\n video: Video = Video(video_id=item.id)\n video.get(\n session=session,\n out_dir=self.mix_dir,\n metadata=item,\n )\n tracks_videos[i] = video\n else:\n tracks_videos[i] = None\n continue\n else:\n self.tracks_videos: Tuple[\n Tuple[int, Optional[Union[Track, Video]]]\n ] = tuple(tracks_videos)\n return tracks_videos\n\n def flatten_mix_dir(self):\n \"\"\"When self.get_items() is called, the tracks and/or videos in\n self.items are downloaded using their self-contained .get() logic;\n this means that they will be downloaded to albums. This function\n \"flattens\" self.mix_dir, meaning that it moves all downloaded\n audio and video files to self.mix_dir, and removes the various\n subdirectories created\"\"\"\n files: List[Dict[int, Optional[str]]] = [None] * len(self.tracks_videos)\n if len(self.tracks_videos) == 0:\n return\n subdirs: Set[Path] = set()\n\n for i, tv in enumerate(self.tracks_videos, 1):\n if getattr(tv, \"outfile\") is None:\n try:\n getattr(tv, \"album_dir\")\n except AttributeError:\n pass\n else:\n subdirs.add(tv.album_dir)\n subdirs.add(tv.album_dir.parent)\n files[i - 1] = {i: None}\n continue\n\n _path: Optional[Path] = Path(tv.outfile) if tv is not None else None\n # if the item never got turned into a track or video\n if _path is None:\n files[i - 1] = {i: None}\n continue\n\n # if the track or video didn't download\n if _path.exists():\n if _path.stat().st_size == 0:\n files[i - 1] = {i: None}\n continue\n else:\n files[i - 1] = {i: None}\n continue\n\n # otherwise, move files and clean up\n if isinstance(tv, Track):\n new_path: Path = self.mix_dir / f\"{i:03d} - {tv.trackname}\"\n new_path.write_bytes(_path.read_bytes())\n _path.unlink()\n files[i - 1] = {i: str(new_path.absolute())}\n elif isinstance(tv, Video):\n new_path: Path = self.mix_dir / f\"{i:03d} - {_path.name}\"\n new_path.write_bytes(_path.read_bytes())\n _path.unlink()\n files[i - 1] = {i: str(new_path.absolute())}\n else:\n self.files: List[Dict[int, Optional[str]]] = files\n\n # Find all subdirectories written to\n subdirs: Set[Path] = set()\n for tv in self.tracks_videos:\n if isinstance(tv, Track):\n try:\n getattr(tv, \"album_dir\")\n except AttributeError:\n pass\n else:\n subdirs.add(tv.album_dir)\n subdirs.add(tv.album_dir.parent)\n elif isinstance(tv, Video):\n subdirs.add(tv.artist_dir)\n\n # Copy all artist images, artist bio JSON files out\n # of subdirs\n artist_images: Set[Path] = set()\n for subdir in subdirs:\n for p in subdir.glob(\"*.jpg\"):\n if p.name == \"cover.jpg\":\n continue\n artist_images.add(p)\n else:\n for artist_image_path in artist_images:\n if artist_image_path.exists():\n shutil.copyfile(\n artist_image_path.absolute(),\n self.mix_dir / artist_image_path.name,\n )\n\n artist_bios: Set[Path] = set()\n for subdir in subdirs:\n for p in subdir.glob(\"*bio.json\"):\n artist_bios.add(p)\n else:\n for artist_bio_path in artist_bios:\n if artist_bio_path.exists():\n shutil.copyfile(\n artist_bio_path.absolute(),\n self.mix_dir / artist_bio_path.name,\n )\n\n # Remove all subdirs\n for subdir in subdirs:\n if subdir.exists():\n shutil.rmtree(subdir)\n else:\n return self.mix_dir\n\n def dumps(self):\n return json.dumps(self.files)\n\n def dump(self, fp=sys.stdout):\n json.dump(self.files, fp)\n\n def get(self, session: Session, audio_format: AudioFormat, out_dir: Path):\n \"\"\"The main method of this class, executing a number of other methods\n in a row:\n - self.get_metadata()\n - self.set_items()\n - self.set_dir()\n - self.save_cover_image()\n - self.get_items()\n - self.flatten_playlist_dir()\n \"\"\"\n self.get_metadata(session)\n \n if self.metadata is None:\n self.files = {}\n return\n \n self.set_items(session)\n self.set_dir(out_dir)\n self.save_cover_image(session, out_dir)\n try:\n self.save_description()\n except Exception:\n pass\n\n _get_items = self.get_items(session, audio_format)\n if _get_items is None:\n logger.critical(f\"Could not retrieve mix with ID '{self.mix_id}'\")\n return\n self.flatten_mix_dir()\n logger.info(f\"Mix files written to '{self.mix_dir}'\")" }, { "identifier": "Playlist", "path": "tidal_wave/playlist.py", "snippet": "class Playlist:\n playlist_id: str # UUID4\n\n def __post_init__(self):\n self.playlist_dir: Optional[Path] = None\n self.playlist_cover_saved: bool = False\n\n def get_metadata(self, session: Session):\n \"\"\"Request from TIDAL API /playlists endpoint\"\"\"\n self.metadata: Optional[PlaylistsEndpointResponseJSON] = request_playlists(\n session=session, identifier=self.playlist_id\n )\n \n if self.metadata is None:\n return\n \n self.name = (\n self.metadata.title.replace(\"/\", \"_\")\n .replace(\"|\", \"_\")\n .replace(\":\", \" -\")\n .replace('\"', \"\")\n .replace(\"..\", \"\")\n )\n\n def set_items(self, session: Session):\n \"\"\"Uses data from TIDAL API /playlists/items endpoint to\n populate self.items\"\"\"\n playlist_items: Optional[PlaylistsItemsResponseJSON] = get_playlist(\n session=session, playlist_id=self.playlist_id\n )\n if playlist_items is None:\n self.items = tuple()\n else:\n self.items: Tuple[Optional[PlaylistItem]] = tuple(playlist_items.items)\n\n def set_dir(self, out_dir: Path):\n \"\"\"Populates self.playlist_dir based on self.name, self.playlist_id\"\"\"\n playlist_substring: str = f\"{self.name} [{self.playlist_id}]\"\n self.playlist_dir: Path = out_dir / \"Playlists\" / playlist_substring\n self.playlist_dir.mkdir(parents=True, exist_ok=True)\n\n def save_cover_image(self, session: Session, out_dir: Path):\n \"\"\"Requests self.metadata.image and attempts to write it to disk\"\"\"\n if self.playlist_dir is None:\n self.set_dir(out_dir=out_dir)\n self.cover_path: Path = self.playlist_dir / \"cover.jpg\"\n if not self.cover_path.exists():\n download_cover_image(\n session=session,\n cover_uuid=self.metadata.square_image,\n output_dir=self.playlist_dir,\n dimension=1080,\n )\n else:\n self.playlist_cover_saved = True\n\n def save_description(self):\n \"\"\"Requests self.metadata.description and attempts to write it to disk\"\"\"\n description_path: Path = self.playlist_dir / \"PlaylistDescription.txt\"\n if self.metadata.description is not None and len(self.metadata.description) > 0:\n if not description_path.exists():\n description_path.write_text(f\"{self.metadata.description}\\n\")\n\n def get_items(self, session: Session, audio_format: AudioFormat):\n \"\"\"Using either Track.get() or Video.get(), attempt to request\n the data for each track or video in self.items\"\"\"\n if len(self.items) == 0:\n return\n tracks_videos: list = [None] * len(self.items)\n for i, item in enumerate(self.items):\n if item is None:\n tracks_videos[i] = None\n continue\n elif isinstance(item, TracksEndpointResponseJSON):\n track: Track = Track(track_id=item.id)\n track.get(\n session=session,\n audio_format=audio_format,\n out_dir=self.playlist_dir,\n metadata=item,\n )\n tracks_videos[i] = track\n elif isinstance(item, VideosEndpointResponseJSON):\n video: Video = Video(video_id=item.id)\n video.get(\n session=session,\n out_dir=self.playlist_dir,\n metadata=item,\n )\n tracks_videos[i] = video\n else:\n tracks_videos[i] = None\n continue\n else:\n self.tracks_videos: Tuple[\n Tuple[int, Optional[Union[Track, Video]]]\n ] = tuple(tracks_videos)\n return tracks_videos\n\n def flatten_playlist_dir(self):\n \"\"\"When self.get_items() is called, the tracks and/or videos in\n self.items are downloaded using their self-contained .get() logic;\n this means that they will be downloaded to albums. This function\n \"flattens\" self.playlist_dir, meaning that it moves all downloaded\n audio and video files to self.playlist_dir, and removes the various\n subdirectories created\"\"\"\n files: List[Dict[int, Optional[str]]] = [None] * len(self.tracks_videos)\n if len(self.tracks_videos) == 0:\n return\n subdirs: Set[Path] = set()\n\n for i, tv in enumerate(self.tracks_videos, 1):\n if getattr(tv, \"outfile\") is None:\n try:\n getattr(tv, \"album_dir\")\n except AttributeError:\n pass\n else:\n subdirs.add(tv.album_dir)\n subdirs.add(tv.album_dir.parent)\n files[i - 1] = {i: None}\n continue\n\n _path: Optional[Path] = Path(tv.outfile) if tv is not None else None\n # if the item never got turned into a track or video\n if _path is None:\n files[i - 1] = {i: None}\n continue\n\n # if the track or video didn't download\n if _path.exists():\n if _path.stat().st_size == 0:\n files[i - 1] = {i: None}\n continue\n else:\n files[i - 1] = {i: None}\n continue\n\n # otherwise, move files and clean up\n if isinstance(tv, Track):\n new_path: Path = self.playlist_dir / f\"{i:03d} - {tv.trackname}\"\n new_path.write_bytes(_path.read_bytes())\n _path.unlink()\n files[i - 1] = {i: str(new_path.absolute())}\n elif isinstance(tv, Video):\n new_path: Path = self.playlist_dir / f\"{i:03d} - {_path.name}\"\n new_path.write_bytes(_path.read_bytes())\n _path.unlink()\n files[i - 1] = {i: str(new_path.absolute())}\n else:\n self.files: List[Dict[int, Optional[str]]] = files\n\n # Find all subdirectories written to\n subdirs: Set[Path] = set()\n for tv in self.tracks_videos:\n if isinstance(tv, Track):\n try:\n getattr(tv, \"album_dir\")\n except AttributeError:\n pass\n else:\n subdirs.add(tv.album_dir)\n subdirs.add(tv.album_dir.parent)\n elif isinstance(tv, Video):\n subdirs.add(tv.artist_dir)\n\n # Copy all artist images, artist bio JSON files out\n # of subdirs\n artist_images: Set[Path] = set()\n for subdir in subdirs:\n for p in subdir.glob(\"*.jpg\"):\n if p.name == \"cover.jpg\":\n continue\n artist_images.add(p)\n else:\n for artist_image_path in artist_images:\n if artist_image_path.exists():\n shutil.copyfile(\n artist_image_path.absolute(),\n self.playlist_dir / artist_image_path.name,\n )\n\n artist_bios: Set[Path] = set()\n for subdir in subdirs:\n for p in subdir.glob(\"*bio.json\"):\n artist_bios.add(p)\n else:\n for artist_bio_path in artist_bios:\n if artist_bio_path.exists():\n shutil.copyfile(\n artist_bio_path.absolute(),\n self.playlist_dir / artist_bio_path.name,\n )\n\n # Remove all subdirs\n for subdir in subdirs:\n if subdir.exists():\n shutil.rmtree(subdir)\n else:\n return self.playlist_dir\n\n def craft_m3u8_text(self):\n \"\"\"This method creates a file called playlist.m3u8 in self.playlist_dir\n that is a standard M3U. Needs to be called after self.flatten_playlist_dir\n in order to be able to access self.files\n N.b. the already-written file is temporarily copied to a .mp4 version in a\n temporary directory because .m4a files cannot be read with mutagen.\"\"\"\n m3u_text: str = f\"#EXTM3U\\n#EXTENC:UTF-8\\n#EXTIMG:{str(self.cover_path.absolute())}\\n#PLAYLIST:{self.name}\\n\"\n\n logger.info(\n f\"Creating .m3u8 playlist file for Playlist with ID '{self.playlist_id}'\"\n )\n for d in self.files:\n file: str = next(iter(d.values()))\n if file is None:\n continue\n elif file.endswith(\".flac\"):\n m = mutagen.File(file)\n artist: str = m.get(\"artist\", [\"\"])[0]\n title: str = m.get(\"title\", [\"\"])[0]\n extinf: str = (\n f\"#EXTINF:{math.ceil(m.info.length)},\"\n f\"{artist} - {title}\\n{file}\\n\"\n )\n m3u_text += extinf\n elif file.endswith(\".mka\"):\n m = mutagen.File(file)\n artist: str = m.get(\"ARTI\", [\"\"])[0]\n title: str = m.get(\"TITL\", [\"\"])[0]\n extinf: str = (\n f\"#EXTINF:{math.ceil(m.info.length)},\"\n f\"{artist} - {title}\\n{file}\\n\"\n )\n m3u_text += extinf\n elif file.endswith(\".m4a\"):\n # Mutagen cannot read .m4a files, so make a copy with all\n # of the metadata tags as a .mp4 in a temporary directory\n with temporary_file(suffix=\".mp4\") as tf:\n ffmpeg.input(file, hide_banner=None, y=None).output(\n tf.name,\n acodec=\"copy\",\n vcodec=\"copy\",\n loglevel=\"quiet\",\n ).run()\n\n m = mutagen.File(tf.name)\n artist: str = m.get(\"\\xa9ART\", [\"\"])[0]\n title: str = m.get(\"\\xa9nam\", [\"\"])[0]\n extinf: str = (\n f\"#EXTINF:{math.ceil(m.info.length)},\"\n f\"{artist} - {title}\\n{file}\\n\"\n )\n m3u_text += extinf\n else:\n return m3u_text\n\n def dumps(self):\n return json.dumps(self.files)\n\n def dump(self, fp=sys.stdout):\n json.dump(self.files, fp)\n\n def get(self, session: Session, audio_format: AudioFormat, out_dir: Path):\n \"\"\"The main method of this class, executing a number of other methods\n in a row:\n - self.get_metadata()\n - self.set_items()\n - self.set_dir()\n - self.save_cover_image()\n - self.save_description()\n - self.get_items()\n - self.flatten_playlist_dir()\n \"\"\"\n self.get_metadata(session)\n \n if self.metadata is None:\n self.files = {}\n return\n \n self.set_items(session)\n self.set_dir(out_dir)\n self.save_cover_image(session, out_dir)\n try:\n self.save_description()\n except Exception:\n pass\n\n _get_items = self.get_items(session, audio_format)\n if _get_items is None:\n logger.critical(f\"Could not retrieve playlist with ID '{self.playlist_id}'\")\n return\n\n self.flatten_playlist_dir()\n\n try:\n m3u8_text: str = self.craft_m3u8_text()\n except Exception as e:\n logger.warning(\n \"Unable to create playlist.m3u8 file for \"\n f\"playlist with ID '{self.playlist_id}'\"\n )\n logger.debug(e)\n else:\n with open(self.playlist_dir / \"playlist.m3u8\", \"w\") as f:\n f.write(m3u8_text)\n\n logger.info(f\"Playlist files written to '{self.playlist_dir}'\")" }, { "identifier": "Track", "path": "tidal_wave/track.py", "snippet": "class Track:\n track_id: int\n\n def __post_init__(self):\n self._has_lyrics: Optional[bool] = None\n self.tags: dict = {}\n self.album_cover_saved: bool = False\n\n def get_metadata(self, session: Session):\n self.metadata: Optional[TracksEndpointResponseJSON] = request_tracks(\n session, self.track_id\n )\n\n def get_album(self, session: Session):\n self.album: Optional[AlbumsEndpointResponseJSON] = request_albums(\n session, self.metadata.album.id\n )\n\n def get_credits(self, session: Session):\n self.credits: Optional[TracksCreditsResponseJSON] = request_credits(\n session, self.track_id\n )\n\n def get_lyrics(self, session: Session):\n if self._has_lyrics is None:\n self.lyrics: Optional[TracksLyricsResponseJSON] = request_lyrics(\n session, self.track_id\n )\n if self.lyrics is None:\n self._has_lyrics = False\n else:\n self._has_lyrics = True\n else:\n return self.lyrics\n\n def get_stream(self, session: Session, audio_format: AudioFormat):\n \"\"\"Populates self.stream, self.manifest\"\"\"\n aq: Optional[str] = af_aq.get(audio_format)\n self.stream: Optional[TracksEndpointStreamResponseJSON] = request_stream(\n session, self.track_id, aq\n )\n\n def set_manifest(self):\n \"\"\"This method sets self.manifest and self.codec\"\"\"\n self.manifest: Manifest = manifester(self.stream)\n # https://dashif.org/codecs/audio/\n if self.manifest.codecs == \"flac\":\n self.codec = \"flac\"\n elif self.manifest.codecs == \"mqa\":\n self.codec = \"flac\"\n elif self.manifest.codecs == \"mha1\": # Sony 360 Reality Audio\n self.codec = \"mka\"\n elif self.manifest.codecs == \"mp4a.40.5\": # HE-AAC\n self.codec = \"m4a\"\n elif self.manifest.codecs == \"mp4a.40.29\": # HE-AAC v2\n self.codec = \"m4a\"\n elif self.manifest.codecs == \"mp4a.40.2\": # AAC-LC\n self.codec = \"m4a\"\n elif self.manifest.codecs == \"eac3\": # Enhanced AC-3\n self.codec = \"m4a\"\n elif self.manifest.codecs == \"mp4a.40.34\": # MP3\n self.codec = \"mp3\"\n\n def set_album_dir(self, out_dir: Path):\n \"\"\"This method sets self.album_dir, based on self.album and\n out_dir. In particular, self.album_dir is a subdirectory of out_dir\n based on the name of the album's artist\"\"\"\n artist_substring: str = self.album.artist.name.replace(\"..\", \"\")\n album_substring: str = (\n f\"{self.album.name} \" f\"[{self.album.id}] [{self.album.release_date.year}]\"\n )\n self.album_dir: Path = out_dir / artist_substring / album_substring\n self.album_dir.mkdir(parents=True, exist_ok=True)\n\n if self.album.number_of_volumes > 1:\n volume_substring: str = f\"Volume {self.metadata.volume_number}\"\n (self.album_dir / volume_substring).mkdir(parents=True, exist_ok=True)\n\n def set_filename(self, audio_format: AudioFormat):\n \"\"\"This method sets self.filename. It's based on self.metadata\n as well as audio_format. Additionally, if the available codecs in\n self.manifest don't match audio_format, warnings are logged\"\"\"\n _track_part: str = f\"{self.metadata.track_number:02d} - {self.metadata.name}\"\n if audio_format == AudioFormat.low:\n track_substring: str = f\"{_track_part} [L]\"\n elif audio_format == AudioFormat.high:\n track_substring: str = f\"{_track_part} [H]\"\n elif audio_format == AudioFormat.lossless:\n track_substring: str = f\"{_track_part} [CD]\"\n elif audio_format == AudioFormat.mqa:\n track_substring: str = f\"{_track_part} [Q]\"\n elif audio_format == AudioFormat.hi_res:\n track_substring: str = f\"{_track_part} [HiRes]\"\n elif audio_format == AudioFormat.dolby_atmos:\n track_substring: str = f\"{_track_part} [A]\"\n elif audio_format == AudioFormat.sony_360_reality_audio:\n track_substring: str = f\"{_track_part} [360]\"\n else:\n track_substring: str = _track_part\n\n # Check for MQA masquerading as HiRes here\n if audio_format == AudioFormat.hi_res:\n if self.manifest.codecs == \"mqa\":\n logger.warning(\n \"Even though HiRes audio format was requested, this track is only \"\n \"available in MQA format. TIDAL regards this as 'HiRes' even though \"\n \"it is probably only lossless; i.e. 16-bit 44.1 kHz quality. \"\n \"Downloading of track will continue, but it will be marked as MQA.\"\n )\n self.filename: Optional[str] = f\"{_track_part} [Q].{self.codec}\"\n elif (self.stream.bit_depth == 16) and (self.stream.sample_rate == 44100):\n logger.warning(\n \"Even though HiRes audio format was requested, and TIDAL responded to \"\n \"that request without error, this track is only available in lossless \"\n \"format; i.e. 16-bit 44.1 kHz quality. Downloading of track will \"\n \"continue, but it will be marked as Lossless ([CD]).\"\n )\n self.filename: Optional[str] = f\"{_track_part} [CD].{self.codec}\"\n else:\n self.filename: Optional[str] = f\"{track_substring}.{self.codec}\"\n else:\n self.filename: Optional[str] = f\"{track_substring}.{self.codec}\"\n\n # for use in playlist file ordering\n self.trackname: str = re.match(r\"(?:\\d{2,3} - )(.+?$)\", self.filename).groups()[\n 0\n ]\n\n def set_outfile(self):\n \"\"\"Uses self.album_dir and self.metadata and self.filename\n to craft the pathlib.Path object, self.outfile, that is a\n reference to where the track will be written on disk.\"\"\"\n if self.album.number_of_volumes > 1:\n self.outfile: Path = (\n self.album_dir / f\"Volume {self.metadata.volume_number}\" / self.filename\n )\n self.absolute_outfile = str(self.outfile.absolute())\n else:\n self.outfile: Path = self.album_dir / self.filename\n self.absolute_outfile = str(self.outfile.absolute())\n\n if (self.outfile.exists()) and (self.outfile.stat().st_size > 0):\n logger.info(\n f\"Track {self.absolute_outfile} already exists \"\n \"and therefore will not be overwritten\"\n )\n return\n else:\n return self.outfile\n\n def save_artist_image(self, session: Session):\n \"\"\"This method writes a JPEG file with the name of each of\n self.metadata.artists to self.album_dir\"\"\"\n for a in self.metadata.artists:\n track_artist_image: Path = (\n self.album_dir / f\"{a.name.replace('..', '')}.jpg\"\n )\n if not track_artist_image.exists():\n download_artist_image(session, a, self.album_dir)\n\n def save_artist_bio(self, session: Session):\n \"\"\"This method writes a JSON file with the name of each of\n self.metadata.artists to self.album_dir\"\"\"\n for a in self.metadata.artists:\n track_artist_bio_json: Path = self.album_dir / f\"{a.name}-bio.json\"\n if not track_artist_bio_json.exists():\n artist_bio: Optional[ArtistsBioResponseJSON] = request_artist_bio(\n session, a.id\n )\n if artist_bio is not None:\n logger.info(\n f\"Writing artist bio for artist {a.id} to \"\n f\"'{str(track_artist_bio_json.absolute())}\"\n )\n track_artist_bio_json.write_text(artist_bio.to_json())\n\n def save_album_cover(self, session: Session):\n \"\"\"This method saves cover.jpg to self.album_dir; the bytes for cover.jpg\n come from self.album.cover\"\"\"\n self.cover_path: Path = self.album_dir / \"cover.jpg\"\n if (not self.cover_path.exists()) or (not self.album_cover_saved):\n download_cover_image(\n session=session, cover_uuid=self.album.cover, output_dir=self.album_dir\n )\n else:\n self.album_cover_saved = True\n\n def set_urls(self, session: Session):\n \"\"\"This method sets self.urls based on self.manifest\"\"\"\n if isinstance(self.manifest, JSONDASHManifest):\n self.urls: List[str] = self.manifest.urls\n elif isinstance(self.manifest, XMLDASHManifest):\n self.urls: List[str] = self.manifest.build_urls(session=session)\n self.download_headers: Dict[str, str] = {\"Accept\": self.manifest.mime_type}\n if session.session_id is not None:\n self.download_headers[\"sessionId\"] = session.session_id\n self.download_params = {k: None for k in session.params}\n\n def download_url(self, session: Session, out_dir: Path) -> Optional[Path]:\n \"\"\"This method downloads self.urls[0], for use in situations when\n the manifest returned by TIDAL API contains one URL. It relies on\n byte range headers to incrementally get all content from a URL\"\"\"\n logger.info(f\"Writing track {self.track_id} to '{self.absolute_outfile}'\")\n\n with temporary_file() as ntf:\n # Implement HTTP range requests here to mimic official clients\n range_size: int = 1024 * 1024 # 1 MiB\n content_length: int = fetch_content_length(\n session=session, url=self.urls[0]\n )\n if content_length == 0:\n return\n\n range_headers: Iterable[str] = http_request_range_headers(\n content_length=content_length,\n range_size=range_size,\n return_tuple=False,\n )\n for rh in range_headers:\n with session.get(\n self.urls[0], params=self.download_params, headers={\"Range\": rh}\n ) as rr:\n if not rr.ok:\n logger.warning(f\"Could not download {self}\")\n return\n else:\n ntf.write(rr.content)\n else:\n ntf.seek(0)\n\n if self.codec == \"flac\":\n # Have to use FFMPEG to re-mux the audio bytes, otherwise\n # mutagen chokes on NoFlacHeaderError\n ffmpeg.input(ntf.name, hide_banner=None, y=None).output(\n self.absolute_outfile,\n acodec=\"copy\",\n loglevel=\"quiet\",\n ).run()\n elif self.codec == \"m4a\":\n shutil.copyfile(ntf.name, self.outfile)\n elif self.codec == \"mka\":\n shutil.copyfile(ntf.name, self.outfile)\n\n logger.info(\n f\"Track {self.track_id} written to '{str(self.outfile.absolute())}'\"\n )\n return self.outfile\n\n def download_urls(self, session: Session, out_dir: Path) -> Optional[Path]:\n \"\"\"This method writes the contents from self.urls to a temporary\n directory, then uses FFmpeg to re-mux the data to self.outfile\"\"\"\n logger.info(f\"Writing track {self.track_id} to '{self.absolute_outfile}'\")\n\n with temporary_file() as ntf:\n for u in self.urls:\n with session.get(\n url=u, headers=self.download_headers, params=self.download_params\n ) as resp:\n if not resp.ok:\n logger.warning(f\"Could not download {self}\")\n return\n else:\n ntf.write(resp.content)\n else:\n ntf.seek(0)\n\n if self.codec == \"flac\":\n # Have to use FFmpeg to re-mux the audio bytes, otherwise\n # mutagen chokes on NoFlacHeaderError\n ffmpeg.input(ntf.name, hide_banner=None, y=None).output(\n self.absolute_outfile, acodec=\"copy\", loglevel=\"quiet\"\n ).run()\n elif self.codec == \"m4a\":\n shutil.copyfile(ntf.name, self.outfile)\n elif self.codec == \"mka\":\n shutil.copyfile(ntf.name, self.outfile)\n\n logger.info(f\"Track {self.track_id} written to '{self.absolute_outfile}'\")\n return self.outfile\n\n def download(self, session: Session, out_dir: Path) -> Optional[Path]:\n \"\"\"This method GETs the data from self.urls and writes it\n to self.outfile.\"\"\"\n if len(self.urls) == 1:\n outfile: Optional[Path] = self.download_url(\n session=session, out_dir=out_dir\n )\n else:\n outfile: Optional[Path] = self.download_urls(\n session=session, out_dir=out_dir\n )\n\n return outfile\n\n def craft_tags(self):\n \"\"\"Using the TAG_MAPPING dictionary,\n write the correct values of various metadata tags to the file.\n E.g. for .flac files, the album's artist is 'ALBUMARTIST',\n but for .m4a files, the album's artist is 'aART'.\"\"\"\n tags = dict()\n if (self.codec == \"flac\") or (self.codec == \"mka\"):\n tag_map = {k: v[\"flac\"] for k, v in TAG_MAPPING.items()}\n elif self.codec == \"m4a\":\n tag_map = {k: v[\"m4a\"] for k, v in TAG_MAPPING.items()}\n\n tags[tag_map[\"album\"]] = self.album.title\n tags[tag_map[\"album_artist\"]] = \";\".join((a.name for a in self.album.artists))\n tags[tag_map[\"album_peak_amplitude\"]] = f\"{self.stream.album_peak_amplitude}\"\n tags[tag_map[\"album_replay_gain\"]] = f\"{self.stream.album_replay_gain}\"\n tags[tag_map[\"artist\"]] = \";\".join((a.name for a in self.metadata.artists))\n tags[tag_map[\"artists\"]] = [a.name for a in self.metadata.artists]\n tags[tag_map[\"barcode\"]] = self.album.upc\n tags[tag_map[\"comment\"]] = self.metadata.url\n tags[tag_map[\"copyright\"]] = self.metadata.copyright\n tags[tag_map[\"date\"]] = str(self.album.release_date)\n tags[tag_map[\"isrc\"]] = self.metadata.isrc\n tags[tag_map[\"title\"]] = self.metadata.name\n tags[tag_map[\"track_peak_amplitude\"]] = f\"{self.metadata.peak}\"\n tags[tag_map[\"track_replay_gain\"]] = f\"{self.metadata.replay_gain}\"\n # credits\n for tag in {\"composer\", \"engineer\", \"lyricist\", \"mixer\", \"producer\", \"remixer\"}:\n try:\n _credits_tag = \";\".join(getattr(self.credits, tag))\n except (TypeError, AttributeError): # NoneType problems\n continue\n else:\n tags[tag_map[tag]] = _credits_tag\n # lyrics\n try:\n _lyrics = self.lyrics.subtitles\n except (TypeError, AttributeError): # NoneType problems\n pass\n else:\n tags[tag_map[\"lyrics\"]] = _lyrics\n\n if self.codec == \"flac\":\n # track and disk\n tags[\"DISCTOTAL\"] = f\"{self.album.number_of_volumes}\"\n tags[\"DISC\"] = f\"{self.metadata.volume_number}\"\n tags[\"TRACKTOTAL\"] = f\"{self.album.number_of_tracks}\"\n tags[\"TRACKNUMBER\"] = f\"{self.metadata.track_number}\"\n # instrument-specific\n # piano\n try:\n piano_credits: List[str] = [\n f\"{pc} (piano)\" for pc in self.credits.piano\n ]\n except (TypeError, AttributeError): # NoneType problems\n pass\n else:\n tags[\"PERFORMER\"] = piano_credits\n\n elif self.codec == \"m4a\":\n # Have to convert to bytes the values of the tags starting with '----'\n for k, v in tags.copy().items():\n if k.startswith(\"----\"):\n if isinstance(v, str):\n tags[k]: bytes = v.encode(\"UTF-8\")\n elif isinstance(v, list):\n tags[k]: List[bytes] = [s.encode(\"UTF-8\") for s in v]\n\n tags[\"trkn\"] = [(self.metadata.track_number, self.album.number_of_tracks)]\n tags[\"disk\"] = [(self.metadata.volume_number, self.album.number_of_volumes)]\n\n self.tags: dict = {k: v for k, v in tags.items() if v is not None}\n\n def set_tags(self):\n \"\"\"Instantiate a mutagen.File instance, add self.tags to it, and\n save it to disk\"\"\"\n self.mutagen = mutagen.File(self.outfile)\n self.mutagen.clear()\n self.mutagen.update(**self.tags)\n # add album cover\n if self.codec == \"flac\":\n p = mutagen.flac.Picture()\n p.type = mutagen.id3.PictureType.COVER_FRONT\n p.desc = \"Album Cover\"\n p.width = p.height = 1280\n p.mime = \"image/jpeg\"\n p.data = self.cover_path.read_bytes()\n self.mutagen.add_picture(p)\n elif self.codec == \"m4a\":\n self.mutagen[\"covr\"] = [\n MP4Cover(self.cover_path.read_bytes(), imageformat=MP4Cover.FORMAT_JPEG)\n ]\n\n self.mutagen.save()\n # Make sure audio track comes first because of\n # less-sophisticated audio players that only\n # recognize the first stream\n if self.codec == \"flac\":\n with temporary_file(suffix=\".mka\") as tf:\n shutil.move(str(self.outfile.absolute()), tf.name)\n cmd: List[str] = shlex.split(\n f\"\"\"ffmpeg -hide_banner -loglevel quiet -y -i \"{tf.name}\"\n -map 0:a:0 -map 0:v:0 -c:a copy -c:v copy\n -metadata:s:v title='Album cover' -metadata:s:v comment='Cover (front)'\n -disposition:v attached_pic \"{self.absolute_outfile}\" \"\"\"\n )\n subprocess.run(cmd)\n elif self.codec == \"m4a\":\n with temporary_file(suffix=\".mka\") as tf:\n cmd: List[str] = shlex.split(\n f\"\"\"ffmpeg -hide_banner -loglevel quiet -y -i \"{self.absolute_outfile}\"\n -map 0:a:0 -map 0:v:0 -c:a copy -c:v copy \"{tf.name}\" \"\"\"\n )\n subprocess.run(cmd)\n shutil.copyfile(tf.name, self.absolute_outfile)\n\n def get(\n self,\n session: Session,\n audio_format: AudioFormat,\n out_dir: Path,\n metadata: Optional[TracksEndpointResponseJSON] = None,\n album: Optional[AlbumsEndpointResponseJSON] = None,\n ) -> Optional[str]:\n if metadata is None:\n self.get_metadata(session)\n else:\n self.metadata = metadata\n\n if self.metadata is None:\n self.outfile = None\n return\n\n if \"DOLBY_ATMOS\" in self.metadata.media_metadata.tags:\n if audio_format != AudioFormat.dolby_atmos:\n logger.warning(\n f\"Track {self.track_id} is only available in Dolby Atmos \"\n \"format. Downloading of track will not continue.\"\n )\n self.outfile = None\n return\n\n if audio_format == AudioFormat.dolby_atmos:\n if \"DOLBY_ATMOS\" not in self.metadata.media_metadata.tags:\n logger.warning(\n \"Dolby Atmos audio format was requested, but track \"\n f\"{self.track_id} is not available in Dolby Atmos \"\n \"format. Downloading of track will not continue.\"\n )\n self.outfile = None\n return\n elif audio_format == AudioFormat.sony_360_reality_audio:\n if \"SONY_360RA\" not in self.metadata.media_metadata.tags:\n logger.warning(\n \"Sony 360 Reality Audio audio format was requested, but track \"\n f\"{self.track_id} is not available in Sony 360 Reality Audio \"\n \"format. Downloading of track will not continue.\"\n )\n self.outfile = None\n return\n elif audio_format == AudioFormat.mqa:\n if \"MQA\" not in self.metadata.media_metadata.tags:\n logger.warning(\n \"MQA audio format was requested, but track \"\n f\"{self.track_id} is not available in MQA audio \"\n \"format. Downloading of track will not continue.\"\n )\n self.outfile = None\n return\n\n if album is None:\n self.get_album(session)\n else:\n self.album = album\n\n if self.album is None:\n self.outfile = None\n return\n\n self.get_credits(session)\n self.get_stream(session, audio_format)\n if self.stream is None:\n return\n self.set_manifest()\n self.set_album_dir(out_dir)\n self.set_filename(audio_format)\n outfile: Optional[Path] = self.set_outfile()\n if outfile is None:\n return\n\n try:\n self.get_lyrics(session)\n except Exception:\n pass\n\n self.save_album_cover(session)\n\n try:\n self.save_artist_image(session)\n except Exception:\n pass\n\n try:\n self.save_artist_bio(session)\n except Exception:\n pass\n\n self.set_urls(session)\n\n if self.download(session, out_dir) is None:\n return\n\n self.craft_tags()\n self.set_tags()\n\n return str(self.outfile.absolute())\n\n def dump(self, fp=sys.stdout):\n k: int = int(self.metadata.track_number)\n if self.outfile is None:\n v: Optional[str] = None\n elif not isinstance(self.outfile, Path):\n v: Optional[str] = None\n else:\n v: Optional[str] = str(self.outfile.absolute())\n json.dump({k: v}, fp)\n return None\n\n def dumps(self) -> str:\n k: int = int(self.metadata.track_number)\n if self.outfile is None:\n v: Optional[str] = None\n elif not isinstance(self.outfile, Path):\n v: Optional[str] = None\n else:\n v: Optional[str] = str(self.outfile.absolute())\n json.dumps({k: v})\n return None" }, { "identifier": "Video", "path": "tidal_wave/video.py", "snippet": "class Video:\n video_id: int\n\n def __post_init__(self):\n self.tags: dict = {}\n self.codec: str = \"mp4\"\n\n def get_metadata(self, session: Session):\n \"\"\"Request from TIDAL API /videos endpoint\"\"\"\n self.metadata: Optional[VideosEndpointResponseJSON] = request_videos(\n session, self.video_id\n )\n\n def get_contributors(self, session: Session):\n \"\"\"Request from TIDAL API /videos/contributors endpoint\"\"\"\n self.contributors: Optional[\n VideosContributorsResponseJSON\n ] = request_video_contributors(session, self.video_id)\n\n def get_stream(self, session: Session, video_format=VideoFormat.high):\n \"\"\"Populates self.stream by requesting from TIDAL API\n /videos/playbackinfopostpaywall endpoint\"\"\"\n self.stream: Optional[VideosEndpointStreamResponseJSON] = request_video_stream(\n session, self.video_id, video_format.value\n )\n\n def get_m3u8(self, session: Session):\n \"\"\"This method sets self.m3u8, an m3u8.M3U8 object\n following the HTTP Live Streaming specification; parsed from\n self.stream. I.e., self.get_stream() needs to have been executed\n before calling this method. N.b. self.m3u8 almost certainly will\n be a multivariant playlist, meaning further processing of its\n contents will be necessary.\"\"\"\n self.m3u8: m3u8.Playlist = playlister(session=session, vesrj=self.stream)\n\n def set_urls(self):\n \"\"\"This method uses self.m3u8, an m3u8.M3U8 object that is variant:\n (https://developer.apple.com/documentation/http-live-streaming/creating-a-multivariant-playlist)\n It retrieves the highest-quality .m3u8 in its .playlists attribute,\n and sets self.urls as the list of strings from that m3u8.Playlist\"\"\"\n # for now, just get the highest-bandwidth playlist\n playlist: m3u8.Playlist = variant_streams(self.m3u8)\n self.M3U8 = m3u8.load(playlist.uri)\n if self.M3U8 is None or len(self.M3U8.files) == 0:\n raise TidalM3U8Exception(\n f\"HLS media segments are not available for video {self.video_id}\"\n )\n self.urls: List[str] = self.M3U8.files\n\n def set_artist_dir(self, out_dir: Path):\n \"\"\"Set self.artist_dir, which is the subdirectory of `out_dir`\n with name `self.metadata.artist.name`\"\"\"\n self.artist_dir: Path = out_dir / self.metadata.artist.name\n self.artist_dir.mkdir(parents=True, exist_ok=True)\n\n def set_filename(self, out_dir: Path):\n \"\"\"Set self.filename, which is constructed from self.metadata.name\n and self.stream.video_quality\"\"\"\n self.filename: str = (\n f\"{self.metadata.name} [{self.stream.video_quality}].{self.codec}\"\n )\n\n def set_outfile(self):\n \"\"\"Uses self.artist_dir and self.metadata and self.filename\n to craft the pathlib.Path object, self.outfile, that is a\n reference to where the track will be written on disk.\"\"\"\n self.outfile: Path = self.artist_dir / self.filename\n\n if (self.outfile.exists()) and (self.outfile.stat().st_size > 0):\n logger.info(\n f\"Video {str(self.outfile.absolute())} already exists \"\n \"and therefore will not be overwritten\"\n )\n return\n else:\n return self.outfile\n\n def download(self, session: Session, out_dir: Path) -> Optional[Path]:\n \"\"\"Requests the HLS video files that constitute self.video_id.\n Writes HLS bytes to a temporary file, then uses FFmpeg to write the\n video data to self.outfile\"\"\"\n if session.session_id is not None:\n download_headers: Dict[str, str] = {\"sessionId\": session.session_id}\n else:\n download_headers: dict = dict()\n download_params: Dict[str, None] = {k: None for k in session.params}\n # self.outfile should already have been set by self.set_outfile()\n logger.info(\n f\"Writing video {self.video_id} to '{str(self.outfile.absolute())}'\"\n )\n\n with temporary_file() as ntf:\n for u in self.urls:\n with session.get(\n url=u, headers=download_headers, params=download_params\n ) as download_response:\n if not download_response.ok:\n logger.warning(f\"Could not download {self}\")\n else:\n ntf.write(download_response.content)\n else:\n ntf.seek(0)\n\n # will always be .mp4 because HLS\n ffmpeg.input(ntf.name, hide_banner=None, y=None).output(\n str(self.outfile.absolute()),\n vcodec=\"copy\",\n acodec=\"copy\",\n loglevel=\"quiet\",\n ).run()\n\n logger.info(\n f\"Video {self.video_id} written to '{str(self.outfile.absolute())}'\"\n )\n return self.outfile\n\n def craft_tags(self):\n \"\"\"Using the TAG_MAPPING dictionary, write the correct values of\n various metadata tags to the file. Videos are .mp4\"\"\"\n tags = dict()\n tag_map = {k: v[\"m4a\"] for k, v in TAG_MAPPING.items()}\n\n tags[tag_map[\"artist\"]] = \";\".join((a.name for a in self.metadata.artists))\n tags[tag_map[\"artists\"]] = [a.name for a in self.metadata.artists]\n tags[tag_map[\"comment\"]] = f\"https://tidal.com/browse/video/{self.video_id}\"\n tags[tag_map[\"date\"]] = str(self.metadata.release_date.date())\n tags[tag_map[\"title\"]] = self.metadata.title\n\n for tag in {\"composer\", \"director\", \"lyricist\", \"producer\"}:\n try:\n _credits_tag = \";\".join(getattr(self.contributors, tag))\n except (TypeError, AttributeError): # NoneType problems\n continue\n else:\n tags[tag_map[tag]] = _credits_tag\n\n # Have to convert to bytes the values of the tags starting with '----'\n for k, v in tags.copy().items():\n if k.startswith(\"----\"):\n if isinstance(v, str):\n tags[k]: bytes = v.encode(\"UTF-8\")\n elif isinstance(v, list):\n tags[k]: List[bytes] = [s.encode(\"UTF-8\") for s in v]\n\n self.tags: dict = {k: v for k, v in tags.items() if v is not None}\n\n def set_tags(self):\n \"\"\"Instantiate a mutagen.File instance, add self.tags to it, and\n save it to disk\"\"\"\n self.mutagen = mutagen.File(self.outfile)\n self.mutagen.clear()\n self.mutagen.update(**self.tags)\n self.mutagen.save()\n\n def get(\n self,\n session: Session,\n out_dir: Path,\n metadata: Optional[\"VideosEndpointResponseJSON\"] = None,\n ) -> Optional[str]:\n \"\"\"The main method of this class. Executes a number of other methods\n in a row:\n - self.get_metadata()\n - self.get_contributors()\n - self.get_stream()\n - self.get_m3u8()\n - self.set_urls()\n - self.set_artist_dir()\n - self.set_filename()\n - self.set_outfile()\n - self.download()\n - self.craft_tags()\n - self.set_tags()\n \"\"\"\n if metadata is None:\n self.get_metadata(session)\n else:\n self.metadata = metadata\n\n if self.metadata is None:\n return None\n\n self.get_contributors(session)\n self.get_stream(session)\n if self.stream is None:\n return None\n self.get_m3u8(session)\n self.set_urls()\n self.set_artist_dir(out_dir)\n self.set_filename(out_dir)\n outfile: Optional[Path] = self.set_outfile()\n if outfile is None:\n return None\n\n if self.download(session, out_dir) is None:\n return None\n\n self.craft_tags()\n self.set_tags()\n return str(self.outfile.absolute())\n\n def dump(self, fp=sys.stdout):\n json.dump({self.metadata.title: str(self.outfile.absolute())}, fp)\n\n def dumps(self) -> str:\n return json.dumps({self.metadata.title: str(self.outfile.absolute())})" }, { "identifier": "match_tidal_url", "path": "tidal_wave/models.py", "snippet": "def match_tidal_url(input_str: str) -> Optional[TidalResource]:\n \"\"\"Attempt to match the `input_str` to either the URL of a track or an\n album in the Tidal API service. Returns None if `input_str` matches\n neither, otherwise a subclass of TidalResource corresponding to the\n parsed input_str type\n \"\"\"\n resource_match: Optional[TidalResource] = None\n tidal_resources: Tuple[TidalResource] = (\n TidalTrack,\n TidalAlbum,\n TidalVideo,\n TidalPlaylist,\n TidalMix,\n TidalArtist,\n )\n for T in tidal_resources:\n try:\n resource_match = T(input_str)\n except ValueError as v:\n logger.debug(v)\n continue\n else:\n return resource_match" }, { "identifier": "TidalAlbum", "path": "tidal_wave/models.py", "snippet": "class TidalAlbum(TidalResource):\n \"\"\"Class representing a TIDAL album. Its main purpose is the\n __post_init__ checking process\"\"\"\n\n url: str\n\n def __post_init__(self):\n self.pattern: str = (\n r\"http(?:s)?://(?:listen\\.)?tidal\\.com/(?:browse/)?album/(\\d{5,9})(?:.*?)?\"\n )\n _id = self.match_url()\n\n if _id is None:\n raise ValueError(f\"'{self.url}' is not a valid TIDAL album URL\")\n else:\n self.tidal_id = int(_id)\n logger.info(f\"TIDAL album ID parsed from input: {self.tidal_id}\")" }, { "identifier": "TidalArtist", "path": "tidal_wave/models.py", "snippet": "class TidalArtist(TidalResource):\n \"\"\"Class representing a TIDAL artist. Its main purpose is the\n __post_init__ checking process\"\"\"\n\n url: str\n\n def __post_init__(self):\n self.pattern: str = (\n r\"http(?:s)?://(?:listen\\.)?tidal\\.com/(?:browse/)?artist/(\\d{7,9})(?:.*?)?\"\n )\n _id = self.match_url()\n\n if _id is None:\n raise ValueError(f\"'{self.url}' is not a valid TIDAL album URL\")\n else:\n self.tidal_id = int(_id)\n logger.info(f\"TIDAL album ID parsed from input: {self.tidal_id}\")" }, { "identifier": "TidalMix", "path": "tidal_wave/models.py", "snippet": "class TidalMix(TidalResource):\n url: str\n\n def __post_init__(self):\n self.pattern: str = (\n r\"http(?:s)?://(?:listen\\.)?tidal\\.com/(?:browse/)?mix/(\\w{30})(?:.*?)?\"\n )\n _id = self.match_url()\n\n if _id is None:\n raise ValueError(f\"'{self.url}' is not a valid TIDAL mix URL\")\n else:\n self.tidal_id = _id\n logger.info(f\"TIDAL mix ID parsed from input: {self.tidal_id}\")" }, { "identifier": "TidalPlaylist", "path": "tidal_wave/models.py", "snippet": "class TidalPlaylist(TidalResource):\n \"\"\"Class representing a TIDAL playlist. Its main purpose is the\n __post_init__ checking process\"\"\"\n\n url: str\n\n def __post_init__(self):\n self.pattern: str = (\n r\"http(?:s)?://(?:listen\\.)?tidal\\.com/(?:browse/)?playlist/\"\n r\"([0-9a-f]{8}\\-[0-9a-f]{4}\\-4[0-9a-f]{3}\\-[89ab][0-9a-f]{3}\\-[0-9a-f]{12})(?:.*?)?\"\n )\n\n _id = self.match_url()\n\n if _id is None:\n raise ValueError(f\"'{self.url}' is not a valid TIDAL playlist URL\")\n else:\n self.tidal_id = _id\n logger.info(f\"TIDAL playlist ID parsed from input: {self.tidal_id}\")" }, { "identifier": "TidalTrack", "path": "tidal_wave/models.py", "snippet": "class TidalTrack(TidalResource):\n \"\"\"Class representing a TIDAL track. Its main purpose is the\n __post_init__ checking process\"\"\"\n\n url: str\n\n def __post_init__(self):\n self.pattern: str = r\"http(?:s)?://(?:listen\\.)?tidal\\.com/(?:browse/)?(?:album/\\d{5,9}/)?track/(\\d{5,9})(?:.*?)?\"\n _id = self.match_url()\n\n if _id is None:\n raise ValueError(f\"'{self.url}' is not a valid TIDAL track URL\")\n else:\n self.tidal_id = int(_id)\n logger.info(f\"TIDAL track ID parsed from input: {self.tidal_id}\")" }, { "identifier": "TidalVideo", "path": "tidal_wave/models.py", "snippet": "class TidalVideo(TidalResource):\n \"\"\"Class representing a TIDAL video. Its main purpose is the\n __post_init__ checking process\"\"\"\n\n url: str\n\n def __post_init__(self):\n self.pattern: str = (\n r\"http(?:s)?://(?:listen\\.)?tidal\\.com/(?:browse/)?video/(\\d{7,9})(?:.*?)?\"\n )\n _id = self.match_url()\n\n if _id is None:\n raise ValueError(f\"'{self.url}' is not a valid TIDAL video URL\")\n else:\n self.tidal_id = int(_id)\n logger.info(f\"TIDAL video ID parsed from input: {self.tidal_id}\")" } ]
from contextlib import closing from pathlib import Path from typing import Optional, Union from .login import login, AudioFormat, LogLevel from .album import Album from .artist import Artist from .mix import Mix from .playlist import Playlist from .track import Track from .video import Video from .models import ( match_tidal_url, TidalAlbum, TidalArtist, TidalMix, TidalPlaylist, TidalTrack, TidalVideo, ) from platformdirs import user_music_path from typing_extensions import Annotated import logging import typer
17,086
app = typer.Typer() @app.command() def main( tidal_url: Annotated[ str, typer.Argument( help="The Tidal album or artist or mix or playlist or track or video to download" ), ], audio_format: Annotated[ AudioFormat, typer.Option(case_sensitive=False) ] = AudioFormat.lossless.value, output_directory: Annotated[ Path, typer.Argument( help="The parent directory under which directory(ies) of files will be written" ), ] = user_music_path(), loglevel: Annotated[ LogLevel, typer.Option(case_sensitive=False) ] = LogLevel.info.value, include_eps_singles: Annotated[ bool, typer.Option( "--include-eps-singles", help="No-op unless passing TIDAL artist. Whether to include artist's EPs and singles with albums", ), ] = False, ): logging.basicConfig( format="%(asctime)s,%(msecs)03d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s", datefmt="%Y-%m-%d:%H:%M:%S", level=logging.getLevelName(loglevel.value), ) logger = logging.getLogger(__name__) tidal_resource: Optional[
app = typer.Typer() @app.command() def main( tidal_url: Annotated[ str, typer.Argument( help="The Tidal album or artist or mix or playlist or track or video to download" ), ], audio_format: Annotated[ AudioFormat, typer.Option(case_sensitive=False) ] = AudioFormat.lossless.value, output_directory: Annotated[ Path, typer.Argument( help="The parent directory under which directory(ies) of files will be written" ), ] = user_music_path(), loglevel: Annotated[ LogLevel, typer.Option(case_sensitive=False) ] = LogLevel.info.value, include_eps_singles: Annotated[ bool, typer.Option( "--include-eps-singles", help="No-op unless passing TIDAL artist. Whether to include artist's EPs and singles with albums", ), ] = False, ): logging.basicConfig( format="%(asctime)s,%(msecs)03d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s", datefmt="%Y-%m-%d:%H:%M:%S", level=logging.getLevelName(loglevel.value), ) logger = logging.getLogger(__name__) tidal_resource: Optional[
Union[TidalAlbum, TidalMix, TidalPlaylist, TidalTrack, TidalVideo]
13
2023-12-12 21:50:25+00:00
24k
ZS-YANG/FemtoDet-v3
mmdet/models/utils/misc.py
[ { "identifier": "SampleList", "path": "mmdet/structures/det_data_sample.py", "snippet": "class DetDataSample(BaseDataElement):\n def proposals(self) -> InstanceData:\n def proposals(self, value: InstanceData):\n def proposals(self):\n def gt_instances(self) -> InstanceData:\n def gt_instances(self, value: InstanceData):\n def gt_instances(self):\n def pred_instances(self) -> InstanceData:\n def pred_instances(self, value: InstanceData):\n def pred_instances(self):\n def pred_track_instances(self) -> InstanceData:\n def pred_track_instances(self, value: InstanceData):\n def pred_track_instances(self):\n def ignored_instances(self) -> InstanceData:\n def ignored_instances(self, value: InstanceData):\n def ignored_instances(self):\n def gt_panoptic_seg(self) -> PixelData:\n def gt_panoptic_seg(self, value: PixelData):\n def gt_panoptic_seg(self):\n def pred_panoptic_seg(self) -> PixelData:\n def pred_panoptic_seg(self, value: PixelData):\n def pred_panoptic_seg(self):\n def gt_sem_seg(self) -> PixelData:\n def gt_sem_seg(self, value: PixelData):\n def gt_sem_seg(self):\n def pred_sem_seg(self) -> PixelData:\n def pred_sem_seg(self, value: PixelData):\n def pred_sem_seg(self):" }, { "identifier": "BaseBoxes", "path": "mmdet/structures/bbox/base_boxes.py", "snippet": "class BaseBoxes(metaclass=ABCMeta):\n \"\"\"The base class for 2D box types.\n\n The functions of ``BaseBoxes`` lie in three fields:\n\n - Verify the boxes shape.\n - Support tensor-like operations.\n - Define abstract functions for 2D boxes.\n\n In ``__init__`` , ``BaseBoxes`` verifies the validity of the data shape\n w.r.t ``box_dim``. The tensor with the dimension >= 2 and the length\n of the last dimension being ``box_dim`` will be regarded as valid.\n ``BaseBoxes`` will restore them at the field ``tensor``. It's necessary\n to override ``box_dim`` in subclass to guarantee the data shape is\n correct.\n\n There are many basic tensor-like functions implemented in ``BaseBoxes``.\n In most cases, users can operate ``BaseBoxes`` instance like a normal\n tensor. To protect the validity of data shape, All tensor-like functions\n cannot modify the last dimension of ``self.tensor``.\n\n When creating a new box type, users need to inherit from ``BaseBoxes``\n and override abstract methods and specify the ``box_dim``. Then, register\n the new box type by using the decorator ``register_box_type``.\n\n Args:\n data (Tensor or np.ndarray or Sequence): The box data with shape\n (..., box_dim).\n dtype (torch.dtype, Optional): data type of boxes. Defaults to None.\n device (str or torch.device, Optional): device of boxes.\n Default to None.\n clone (bool): Whether clone ``boxes`` or not. Defaults to True.\n \"\"\"\n\n # Used to verify the last dimension length\n # Should override it in subclass.\n box_dim: int = 0\n\n def __init__(self,\n data: Union[Tensor, np.ndarray, Sequence],\n dtype: Optional[torch.dtype] = None,\n device: Optional[DeviceType] = None,\n clone: bool = True) -> None:\n if isinstance(data, (np.ndarray, Tensor, Sequence)):\n data = torch.as_tensor(data)\n else:\n raise TypeError('boxes should be Tensor, ndarray, or Sequence, ',\n f'but got {type(data)}')\n\n if device is not None or dtype is not None:\n data = data.to(dtype=dtype, device=device)\n # Clone the data to avoid potential bugs\n if clone:\n data = data.clone()\n # handle the empty input like []\n if data.numel() == 0:\n data = data.reshape((-1, self.box_dim))\n\n assert data.dim() >= 2 and data.size(-1) == self.box_dim, \\\n ('The boxes dimension must >= 2 and the length of the last '\n f'dimension must be {self.box_dim}, but got boxes with '\n f'shape {data.shape}.')\n self.tensor = data\n\n def convert_to(self, dst_type: Union[str, type]) -> 'BaseBoxes':\n \"\"\"Convert self to another box type.\n\n Args:\n dst_type (str or type): destination box type.\n\n Returns:\n :obj:`BaseBoxes`: destination box type object .\n \"\"\"\n from .box_type import convert_box_type\n return convert_box_type(self, dst_type=dst_type)\n\n def empty_boxes(self: T,\n dtype: Optional[torch.dtype] = None,\n device: Optional[DeviceType] = None) -> T:\n \"\"\"Create empty box.\n\n Args:\n dtype (torch.dtype, Optional): data type of boxes.\n device (str or torch.device, Optional): device of boxes.\n\n Returns:\n T: empty boxes with shape of (0, box_dim).\n \"\"\"\n empty_box = self.tensor.new_zeros(\n 0, self.box_dim, dtype=dtype, device=device)\n return type(self)(empty_box, clone=False)\n\n def fake_boxes(self: T,\n sizes: Tuple[int],\n fill: float = 0,\n dtype: Optional[torch.dtype] = None,\n device: Optional[DeviceType] = None) -> T:\n \"\"\"Create fake boxes with specific sizes and fill values.\n\n Args:\n sizes (Tuple[int]): The size of fake boxes. The last value must\n be equal with ``self.box_dim``.\n fill (float): filling value. Defaults to 0.\n dtype (torch.dtype, Optional): data type of boxes.\n device (str or torch.device, Optional): device of boxes.\n\n Returns:\n T: Fake boxes with shape of ``sizes``.\n \"\"\"\n fake_boxes = self.tensor.new_full(\n sizes, fill, dtype=dtype, device=device)\n return type(self)(fake_boxes, clone=False)\n\n def __getitem__(self: T, index: IndexType) -> T:\n \"\"\"Rewrite getitem to protect the last dimension shape.\"\"\"\n boxes = self.tensor\n if isinstance(index, np.ndarray):\n index = torch.as_tensor(index, device=self.device)\n if isinstance(index, Tensor) and index.dtype == torch.bool:\n assert index.dim() < boxes.dim()\n elif isinstance(index, tuple):\n assert len(index) < boxes.dim()\n # `Ellipsis`(...) is commonly used in index like [None, ...].\n # When `Ellipsis` is in index, it must be the last item.\n if Ellipsis in index:\n assert index[-1] is Ellipsis\n\n boxes = boxes[index]\n if boxes.dim() == 1:\n boxes = boxes.reshape(1, -1)\n return type(self)(boxes, clone=False)\n\n def __setitem__(self: T, index: IndexType, values: Union[Tensor, T]) -> T:\n \"\"\"Rewrite setitem to protect the last dimension shape.\"\"\"\n assert type(values) is type(self), \\\n 'The value to be set must be the same box type as self'\n values = values.tensor\n\n if isinstance(index, np.ndarray):\n index = torch.as_tensor(index, device=self.device)\n if isinstance(index, Tensor) and index.dtype == torch.bool:\n assert index.dim() < self.tensor.dim()\n elif isinstance(index, tuple):\n assert len(index) < self.tensor.dim()\n # `Ellipsis`(...) is commonly used in index like [None, ...].\n # When `Ellipsis` is in index, it must be the last item.\n if Ellipsis in index:\n assert index[-1] is Ellipsis\n\n self.tensor[index] = values\n\n def __len__(self) -> int:\n \"\"\"Return the length of self.tensor first dimension.\"\"\"\n return self.tensor.size(0)\n\n def __deepcopy__(self, memo):\n \"\"\"Only clone the ``self.tensor`` when applying deepcopy.\"\"\"\n cls = self.__class__\n other = cls.__new__(cls)\n memo[id(self)] = other\n other.tensor = self.tensor.clone()\n return other\n\n def __repr__(self) -> str:\n \"\"\"Return a strings that describes the object.\"\"\"\n return self.__class__.__name__ + '(\\n' + str(self.tensor) + ')'\n\n def new_tensor(self, *args, **kwargs) -> Tensor:\n \"\"\"Reload ``new_tensor`` from self.tensor.\"\"\"\n return self.tensor.new_tensor(*args, **kwargs)\n\n def new_full(self, *args, **kwargs) -> Tensor:\n \"\"\"Reload ``new_full`` from self.tensor.\"\"\"\n return self.tensor.new_full(*args, **kwargs)\n\n def new_empty(self, *args, **kwargs) -> Tensor:\n \"\"\"Reload ``new_empty`` from self.tensor.\"\"\"\n return self.tensor.new_empty(*args, **kwargs)\n\n def new_ones(self, *args, **kwargs) -> Tensor:\n \"\"\"Reload ``new_ones`` from self.tensor.\"\"\"\n return self.tensor.new_ones(*args, **kwargs)\n\n def new_zeros(self, *args, **kwargs) -> Tensor:\n \"\"\"Reload ``new_zeros`` from self.tensor.\"\"\"\n return self.tensor.new_zeros(*args, **kwargs)\n\n def size(self, dim: Optional[int] = None) -> Union[int, torch.Size]:\n \"\"\"Reload new_zeros from self.tensor.\"\"\"\n # self.tensor.size(dim) cannot work when dim=None.\n return self.tensor.size() if dim is None else self.tensor.size(dim)\n\n def dim(self) -> int:\n \"\"\"Reload ``dim`` from self.tensor.\"\"\"\n return self.tensor.dim()\n\n @property\n def device(self) -> torch.device:\n \"\"\"Reload ``device`` from self.tensor.\"\"\"\n return self.tensor.device\n\n @property\n def dtype(self) -> torch.dtype:\n \"\"\"Reload ``dtype`` from self.tensor.\"\"\"\n return self.tensor.dtype\n\n @property\n def shape(self) -> torch.Size:\n return self.tensor.shape\n\n def numel(self) -> int:\n \"\"\"Reload ``numel`` from self.tensor.\"\"\"\n return self.tensor.numel()\n\n def numpy(self) -> np.ndarray:\n \"\"\"Reload ``numpy`` from self.tensor.\"\"\"\n return self.tensor.numpy()\n\n def to(self: T, *args, **kwargs) -> T:\n \"\"\"Reload ``to`` from self.tensor.\"\"\"\n return type(self)(self.tensor.to(*args, **kwargs), clone=False)\n\n def cpu(self: T) -> T:\n \"\"\"Reload ``cpu`` from self.tensor.\"\"\"\n return type(self)(self.tensor.cpu(), clone=False)\n\n def cuda(self: T, *args, **kwargs) -> T:\n \"\"\"Reload ``cuda`` from self.tensor.\"\"\"\n return type(self)(self.tensor.cuda(*args, **kwargs), clone=False)\n\n def clone(self: T) -> T:\n \"\"\"Reload ``clone`` from self.tensor.\"\"\"\n return type(self)(self.tensor)\n\n def detach(self: T) -> T:\n \"\"\"Reload ``detach`` from self.tensor.\"\"\"\n return type(self)(self.tensor.detach(), clone=False)\n\n def view(self: T, *shape: Tuple[int]) -> T:\n \"\"\"Reload ``view`` from self.tensor.\"\"\"\n return type(self)(self.tensor.view(shape), clone=False)\n\n def reshape(self: T, *shape: Tuple[int]) -> T:\n \"\"\"Reload ``reshape`` from self.tensor.\"\"\"\n return type(self)(self.tensor.reshape(shape), clone=False)\n\n def expand(self: T, *sizes: Tuple[int]) -> T:\n \"\"\"Reload ``expand`` from self.tensor.\"\"\"\n return type(self)(self.tensor.expand(sizes), clone=False)\n\n def repeat(self: T, *sizes: Tuple[int]) -> T:\n \"\"\"Reload ``repeat`` from self.tensor.\"\"\"\n return type(self)(self.tensor.repeat(sizes), clone=False)\n\n def transpose(self: T, dim0: int, dim1: int) -> T:\n \"\"\"Reload ``transpose`` from self.tensor.\"\"\"\n ndim = self.tensor.dim()\n assert dim0 != -1 and dim0 != ndim - 1\n assert dim1 != -1 and dim1 != ndim - 1\n return type(self)(self.tensor.transpose(dim0, dim1), clone=False)\n\n def permute(self: T, *dims: Tuple[int]) -> T:\n \"\"\"Reload ``permute`` from self.tensor.\"\"\"\n assert dims[-1] == -1 or dims[-1] == self.tensor.dim() - 1\n return type(self)(self.tensor.permute(dims), clone=False)\n\n def split(self: T,\n split_size_or_sections: Union[int, Sequence[int]],\n dim: int = 0) -> List[T]:\n \"\"\"Reload ``split`` from self.tensor.\"\"\"\n assert dim != -1 and dim != self.tensor.dim() - 1\n boxes_list = self.tensor.split(split_size_or_sections, dim=dim)\n return [type(self)(boxes, clone=False) for boxes in boxes_list]\n\n def chunk(self: T, chunks: int, dim: int = 0) -> List[T]:\n \"\"\"Reload ``chunk`` from self.tensor.\"\"\"\n assert dim != -1 and dim != self.tensor.dim() - 1\n boxes_list = self.tensor.chunk(chunks, dim=dim)\n return [type(self)(boxes, clone=False) for boxes in boxes_list]\n\n def unbind(self: T, dim: int = 0) -> T:\n \"\"\"Reload ``unbind`` from self.tensor.\"\"\"\n assert dim != -1 and dim != self.tensor.dim() - 1\n boxes_list = self.tensor.unbind(dim=dim)\n return [type(self)(boxes, clone=False) for boxes in boxes_list]\n\n def flatten(self: T, start_dim: int = 0, end_dim: int = -2) -> T:\n \"\"\"Reload ``flatten`` from self.tensor.\"\"\"\n assert end_dim != -1 and end_dim != self.tensor.dim() - 1\n return type(self)(self.tensor.flatten(start_dim, end_dim), clone=False)\n\n def squeeze(self: T, dim: Optional[int] = None) -> T:\n \"\"\"Reload ``squeeze`` from self.tensor.\"\"\"\n boxes = self.tensor.squeeze() if dim is None else \\\n self.tensor.squeeze(dim)\n return type(self)(boxes, clone=False)\n\n def unsqueeze(self: T, dim: int) -> T:\n \"\"\"Reload ``unsqueeze`` from self.tensor.\"\"\"\n assert dim != -1 and dim != self.tensor.dim()\n return type(self)(self.tensor.unsqueeze(dim), clone=False)\n\n @classmethod\n def cat(cls: Type[T], box_list: Sequence[T], dim: int = 0) -> T:\n \"\"\"Cancatenates a box instance list into one single box instance.\n Similar to ``torch.cat``.\n\n Args:\n box_list (Sequence[T]): A sequence of box instances.\n dim (int): The dimension over which the box are concatenated.\n Defaults to 0.\n\n Returns:\n T: Concatenated box instance.\n \"\"\"\n assert isinstance(box_list, Sequence)\n if len(box_list) == 0:\n raise ValueError('box_list should not be a empty list.')\n\n assert dim != -1 and dim != box_list[0].dim() - 1\n assert all(isinstance(boxes, cls) for boxes in box_list)\n\n th_box_list = [boxes.tensor for boxes in box_list]\n return cls(torch.cat(th_box_list, dim=dim), clone=False)\n\n @classmethod\n def stack(cls: Type[T], box_list: Sequence[T], dim: int = 0) -> T:\n \"\"\"Concatenates a sequence of tensors along a new dimension. Similar to\n ``torch.stack``.\n\n Args:\n box_list (Sequence[T]): A sequence of box instances.\n dim (int): Dimension to insert. Defaults to 0.\n\n Returns:\n T: Concatenated box instance.\n \"\"\"\n assert isinstance(box_list, Sequence)\n if len(box_list) == 0:\n raise ValueError('box_list should not be a empty list.')\n\n assert dim != -1 and dim != box_list[0].dim()\n assert all(isinstance(boxes, cls) for boxes in box_list)\n\n th_box_list = [boxes.tensor for boxes in box_list]\n return cls(torch.stack(th_box_list, dim=dim), clone=False)\n\n @abstractproperty\n def centers(self) -> Tensor:\n \"\"\"Return a tensor representing the centers of boxes.\"\"\"\n pass\n\n @abstractproperty\n def areas(self) -> Tensor:\n \"\"\"Return a tensor representing the areas of boxes.\"\"\"\n pass\n\n @abstractproperty\n def widths(self) -> Tensor:\n \"\"\"Return a tensor representing the widths of boxes.\"\"\"\n pass\n\n @abstractproperty\n def heights(self) -> Tensor:\n \"\"\"Return a tensor representing the heights of boxes.\"\"\"\n pass\n\n @abstractmethod\n def flip_(self,\n img_shape: Tuple[int, int],\n direction: str = 'horizontal') -> None:\n \"\"\"Flip boxes horizontally or vertically in-place.\n\n Args:\n img_shape (Tuple[int, int]): A tuple of image height and width.\n direction (str): Flip direction, options are \"horizontal\",\n \"vertical\" and \"diagonal\". Defaults to \"horizontal\"\n \"\"\"\n pass\n\n @abstractmethod\n def translate_(self, distances: Tuple[float, float]) -> None:\n \"\"\"Translate boxes in-place.\n\n Args:\n distances (Tuple[float, float]): translate distances. The first\n is horizontal distance and the second is vertical distance.\n \"\"\"\n pass\n\n @abstractmethod\n def clip_(self, img_shape: Tuple[int, int]) -> None:\n \"\"\"Clip boxes according to the image shape in-place.\n\n Args:\n img_shape (Tuple[int, int]): A tuple of image height and width.\n \"\"\"\n pass\n\n @abstractmethod\n def rotate_(self, center: Tuple[float, float], angle: float) -> None:\n \"\"\"Rotate all boxes in-place.\n\n Args:\n center (Tuple[float, float]): Rotation origin.\n angle (float): Rotation angle represented in degrees. Positive\n values mean clockwise rotation.\n \"\"\"\n pass\n\n @abstractmethod\n def project_(self, homography_matrix: Union[Tensor, np.ndarray]) -> None:\n \"\"\"Geometric transformat boxes in-place.\n\n Args:\n homography_matrix (Tensor or np.ndarray]):\n Shape (3, 3) for geometric transformation.\n \"\"\"\n pass\n\n @abstractmethod\n def rescale_(self, scale_factor: Tuple[float, float]) -> None:\n \"\"\"Rescale boxes w.r.t. rescale_factor in-place.\n\n Note:\n Both ``rescale_`` and ``resize_`` will enlarge or shrink boxes\n w.r.t ``scale_facotr``. The difference is that ``resize_`` only\n changes the width and the height of boxes, but ``rescale_`` also\n rescales the box centers simultaneously.\n\n Args:\n scale_factor (Tuple[float, float]): factors for scaling boxes.\n The length should be 2.\n \"\"\"\n pass\n\n @abstractmethod\n def resize_(self, scale_factor: Tuple[float, float]) -> None:\n \"\"\"Resize the box width and height w.r.t scale_factor in-place.\n\n Note:\n Both ``rescale_`` and ``resize_`` will enlarge or shrink boxes\n w.r.t ``scale_facotr``. The difference is that ``resize_`` only\n changes the width and the height of boxes, but ``rescale_`` also\n rescales the box centers simultaneously.\n\n Args:\n scale_factor (Tuple[float, float]): factors for scaling box\n shapes. The length should be 2.\n \"\"\"\n pass\n\n @abstractmethod\n def is_inside(self,\n img_shape: Tuple[int, int],\n all_inside: bool = False,\n allowed_border: int = 0) -> BoolTensor:\n \"\"\"Find boxes inside the image.\n\n Args:\n img_shape (Tuple[int, int]): A tuple of image height and width.\n all_inside (bool): Whether the boxes are all inside the image or\n part inside the image. Defaults to False.\n allowed_border (int): Boxes that extend beyond the image shape\n boundary by more than ``allowed_border`` are considered\n \"outside\" Defaults to 0.\n Returns:\n BoolTensor: A BoolTensor indicating whether the box is inside\n the image. Assuming the original boxes have shape (m, n, box_dim),\n the output has shape (m, n).\n \"\"\"\n pass\n\n @abstractmethod\n def find_inside_points(self,\n points: Tensor,\n is_aligned: bool = False) -> BoolTensor:\n \"\"\"Find inside box points. Boxes dimension must be 2.\n\n Args:\n points (Tensor): Points coordinates. Has shape of (m, 2).\n is_aligned (bool): Whether ``points`` has been aligned with boxes\n or not. If True, the length of boxes and ``points`` should be\n the same. Defaults to False.\n\n Returns:\n BoolTensor: A BoolTensor indicating whether a point is inside\n boxes. Assuming the boxes has shape of (n, box_dim), if\n ``is_aligned`` is False. The index has shape of (m, n). If\n ``is_aligned`` is True, m should be equal to n and the index has\n shape of (m, ).\n \"\"\"\n pass\n\n @abstractstaticmethod\n def overlaps(boxes1: 'BaseBoxes',\n boxes2: 'BaseBoxes',\n mode: str = 'iou',\n is_aligned: bool = False,\n eps: float = 1e-6) -> Tensor:\n \"\"\"Calculate overlap between two set of boxes with their types\n converted to the present box type.\n\n Args:\n boxes1 (:obj:`BaseBoxes`): BaseBoxes with shape of (m, box_dim)\n or empty.\n boxes2 (:obj:`BaseBoxes`): BaseBoxes with shape of (n, box_dim)\n or empty.\n mode (str): \"iou\" (intersection over union), \"iof\" (intersection\n over foreground). Defaults to \"iou\".\n is_aligned (bool): If True, then m and n must be equal. Defaults\n to False.\n eps (float): A value added to the denominator for numerical\n stability. Defaults to 1e-6.\n\n Returns:\n Tensor: shape (m, n) if ``is_aligned`` is False else shape (m,)\n \"\"\"\n pass\n\n @abstractstaticmethod\n def from_instance_masks(masks: MaskType) -> 'BaseBoxes':\n \"\"\"Create boxes from instance masks.\n\n Args:\n masks (:obj:`BitmapMasks` or :obj:`PolygonMasks`): BitmapMasks or\n PolygonMasks instance with length of n.\n\n Returns:\n :obj:`BaseBoxes`: Converted boxes with shape of (n, box_dim).\n \"\"\"\n pass" }, { "identifier": "get_box_type", "path": "mmdet/structures/bbox/box_type.py", "snippet": "def get_box_type(box_type: Union[str, type]) -> Tuple[str, type]:\n \"\"\"get both box type name and class.\n\n Args:\n box_type (str or type): Single box type name or class.\n\n Returns:\n Tuple[str, type]: A tuple of box type name and class.\n \"\"\"\n if isinstance(box_type, str):\n type_name = box_type.lower()\n assert type_name in box_types, \\\n f\"Box type {type_name} hasn't been registered in box_types.\"\n type_cls = box_types[type_name]\n elif issubclass(box_type, BaseBoxes):\n assert box_type in _box_type_to_name, \\\n f\"Box type {box_type} hasn't been registered in box_types.\"\n type_name = _box_type_to_name[box_type]\n type_cls = box_type\n else:\n raise KeyError('box_type must be a str or class inheriting from '\n f'BaseBoxes, but got {type(box_type)}.')\n return type_name, type_cls" }, { "identifier": "stack_boxes", "path": "mmdet/structures/bbox/transforms.py", "snippet": "def stack_boxes(data_list: List[Union[Tensor, BaseBoxes]],\n dim: int = 0) -> Union[Tensor, BaseBoxes]:\n \"\"\"Stack boxes with type of tensor or box type.\n\n Args:\n data_list (List[Union[Tensor, :obj:`BaseBoxes`]]): A list of tensors\n or box types need to be stacked.\n dim (int): The dimension over which the box are stacked.\n Defaults to 0.\n\n Returns:\n Union[Tensor, :obj`BaseBoxes`]: Stacked results.\n \"\"\"\n if data_list and isinstance(data_list[0], BaseBoxes):\n return data_list[0].stack(data_list, dim=dim)\n else:\n return torch.stack(data_list, dim=dim)" }, { "identifier": "BitmapMasks", "path": "mmdet/structures/mask/structures.py", "snippet": "class BitmapMasks(BaseInstanceMasks):\n \"\"\"This class represents masks in the form of bitmaps.\n\n Args:\n masks (ndarray): ndarray of masks in shape (N, H, W), where N is\n the number of objects.\n height (int): height of masks\n width (int): width of masks\n\n Example:\n >>> from mmdet.data_elements.mask.structures import * # NOQA\n >>> num_masks, H, W = 3, 32, 32\n >>> rng = np.random.RandomState(0)\n >>> masks = (rng.rand(num_masks, H, W) > 0.1).astype(np.int64)\n >>> self = BitmapMasks(masks, height=H, width=W)\n\n >>> # demo crop_and_resize\n >>> num_boxes = 5\n >>> bboxes = np.array([[0, 0, 30, 10.0]] * num_boxes)\n >>> out_shape = (14, 14)\n >>> inds = torch.randint(0, len(self), size=(num_boxes,))\n >>> device = 'cpu'\n >>> interpolation = 'bilinear'\n >>> new = self.crop_and_resize(\n ... bboxes, out_shape, inds, device, interpolation)\n >>> assert len(new) == num_boxes\n >>> assert new.height, new.width == out_shape\n \"\"\"\n\n def __init__(self, masks, height, width):\n self.height = height\n self.width = width\n if len(masks) == 0:\n self.masks = np.empty((0, self.height, self.width), dtype=np.uint8)\n else:\n assert isinstance(masks, (list, np.ndarray))\n if isinstance(masks, list):\n assert isinstance(masks[0], np.ndarray)\n assert masks[0].ndim == 2 # (H, W)\n else:\n assert masks.ndim == 3 # (N, H, W)\n\n self.masks = np.stack(masks).reshape(-1, height, width)\n assert self.masks.shape[1] == self.height\n assert self.masks.shape[2] == self.width\n\n def __getitem__(self, index):\n \"\"\"Index the BitmapMask.\n\n Args:\n index (int | ndarray): Indices in the format of integer or ndarray.\n\n Returns:\n :obj:`BitmapMasks`: Indexed bitmap masks.\n \"\"\"\n masks = self.masks[index].reshape(-1, self.height, self.width)\n return BitmapMasks(masks, self.height, self.width)\n\n def __iter__(self):\n return iter(self.masks)\n\n def __repr__(self):\n s = self.__class__.__name__ + '('\n s += f'num_masks={len(self.masks)}, '\n s += f'height={self.height}, '\n s += f'width={self.width})'\n return s\n\n def __len__(self):\n \"\"\"Number of masks.\"\"\"\n return len(self.masks)\n\n def rescale(self, scale, interpolation='nearest'):\n \"\"\"See :func:`BaseInstanceMasks.rescale`.\"\"\"\n if len(self.masks) == 0:\n new_w, new_h = mmcv.rescale_size((self.width, self.height), scale)\n rescaled_masks = np.empty((0, new_h, new_w), dtype=np.uint8)\n else:\n rescaled_masks = np.stack([\n mmcv.imrescale(mask, scale, interpolation=interpolation)\n for mask in self.masks\n ])\n height, width = rescaled_masks.shape[1:]\n return BitmapMasks(rescaled_masks, height, width)\n\n def resize(self, out_shape, interpolation='nearest'):\n \"\"\"See :func:`BaseInstanceMasks.resize`.\"\"\"\n if len(self.masks) == 0:\n resized_masks = np.empty((0, *out_shape), dtype=np.uint8)\n else:\n resized_masks = np.stack([\n mmcv.imresize(\n mask, out_shape[::-1], interpolation=interpolation)\n for mask in self.masks\n ])\n return BitmapMasks(resized_masks, *out_shape)\n\n def flip(self, flip_direction='horizontal'):\n \"\"\"See :func:`BaseInstanceMasks.flip`.\"\"\"\n assert flip_direction in ('horizontal', 'vertical', 'diagonal')\n\n if len(self.masks) == 0:\n flipped_masks = self.masks\n else:\n flipped_masks = np.stack([\n mmcv.imflip(mask, direction=flip_direction)\n for mask in self.masks\n ])\n return BitmapMasks(flipped_masks, self.height, self.width)\n\n def pad(self, out_shape, pad_val=0):\n \"\"\"See :func:`BaseInstanceMasks.pad`.\"\"\"\n if len(self.masks) == 0:\n padded_masks = np.empty((0, *out_shape), dtype=np.uint8)\n else:\n padded_masks = np.stack([\n mmcv.impad(mask, shape=out_shape, pad_val=pad_val)\n for mask in self.masks\n ])\n return BitmapMasks(padded_masks, *out_shape)\n\n def crop(self, bbox):\n \"\"\"See :func:`BaseInstanceMasks.crop`.\"\"\"\n assert isinstance(bbox, np.ndarray)\n assert bbox.ndim == 1\n\n # clip the boundary\n bbox = bbox.copy()\n bbox[0::2] = np.clip(bbox[0::2], 0, self.width)\n bbox[1::2] = np.clip(bbox[1::2], 0, self.height)\n x1, y1, x2, y2 = bbox\n w = np.maximum(x2 - x1, 1)\n h = np.maximum(y2 - y1, 1)\n\n if len(self.masks) == 0:\n cropped_masks = np.empty((0, h, w), dtype=np.uint8)\n else:\n cropped_masks = self.masks[:, y1:y1 + h, x1:x1 + w]\n return BitmapMasks(cropped_masks, h, w)\n\n def crop_and_resize(self,\n bboxes,\n out_shape,\n inds,\n device='cpu',\n interpolation='bilinear',\n binarize=True):\n \"\"\"See :func:`BaseInstanceMasks.crop_and_resize`.\"\"\"\n if len(self.masks) == 0:\n empty_masks = np.empty((0, *out_shape), dtype=np.uint8)\n return BitmapMasks(empty_masks, *out_shape)\n\n # convert bboxes to tensor\n if isinstance(bboxes, np.ndarray):\n bboxes = torch.from_numpy(bboxes).to(device=device)\n if isinstance(inds, np.ndarray):\n inds = torch.from_numpy(inds).to(device=device)\n\n num_bbox = bboxes.shape[0]\n fake_inds = torch.arange(\n num_bbox, device=device).to(dtype=bboxes.dtype)[:, None]\n rois = torch.cat([fake_inds, bboxes], dim=1) # Nx5\n rois = rois.to(device=device)\n if num_bbox > 0:\n gt_masks_th = torch.from_numpy(self.masks).to(device).index_select(\n 0, inds).to(dtype=rois.dtype)\n targets = roi_align(gt_masks_th[:, None, :, :], rois, out_shape,\n 1.0, 0, 'avg', True).squeeze(1)\n if binarize:\n resized_masks = (targets >= 0.5).cpu().numpy()\n else:\n resized_masks = targets.cpu().numpy()\n else:\n resized_masks = []\n return BitmapMasks(resized_masks, *out_shape)\n\n def expand(self, expanded_h, expanded_w, top, left):\n \"\"\"See :func:`BaseInstanceMasks.expand`.\"\"\"\n if len(self.masks) == 0:\n expanded_mask = np.empty((0, expanded_h, expanded_w),\n dtype=np.uint8)\n else:\n expanded_mask = np.zeros((len(self), expanded_h, expanded_w),\n dtype=np.uint8)\n expanded_mask[:, top:top + self.height,\n left:left + self.width] = self.masks\n return BitmapMasks(expanded_mask, expanded_h, expanded_w)\n\n def translate(self,\n out_shape,\n offset,\n direction='horizontal',\n border_value=0,\n interpolation='bilinear'):\n \"\"\"Translate the BitmapMasks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n offset (int | float): The offset for translate.\n direction (str): The translate direction, either \"horizontal\"\n or \"vertical\".\n border_value (int | float): Border value. Default 0 for masks.\n interpolation (str): Same as :func:`mmcv.imtranslate`.\n\n Returns:\n BitmapMasks: Translated BitmapMasks.\n\n Example:\n >>> from mmdet.data_elements.mask.structures import BitmapMasks\n >>> self = BitmapMasks.random(dtype=np.uint8)\n >>> out_shape = (32, 32)\n >>> offset = 4\n >>> direction = 'horizontal'\n >>> border_value = 0\n >>> interpolation = 'bilinear'\n >>> # Note, There seem to be issues when:\n >>> # * the mask dtype is not supported by cv2.AffineWarp\n >>> new = self.translate(out_shape, offset, direction,\n >>> border_value, interpolation)\n >>> assert len(new) == len(self)\n >>> assert new.height, new.width == out_shape\n \"\"\"\n if len(self.masks) == 0:\n translated_masks = np.empty((0, *out_shape), dtype=np.uint8)\n else:\n masks = self.masks\n if masks.shape[-2:] != out_shape:\n empty_masks = np.zeros((masks.shape[0], *out_shape),\n dtype=masks.dtype)\n min_h = min(out_shape[0], masks.shape[1])\n min_w = min(out_shape[1], masks.shape[2])\n empty_masks[:, :min_h, :min_w] = masks[:, :min_h, :min_w]\n masks = empty_masks\n translated_masks = mmcv.imtranslate(\n masks.transpose((1, 2, 0)),\n offset,\n direction,\n border_value=border_value,\n interpolation=interpolation)\n if translated_masks.ndim == 2:\n translated_masks = translated_masks[:, :, None]\n translated_masks = translated_masks.transpose(\n (2, 0, 1)).astype(self.masks.dtype)\n return BitmapMasks(translated_masks, *out_shape)\n\n def shear(self,\n out_shape,\n magnitude,\n direction='horizontal',\n border_value=0,\n interpolation='bilinear'):\n \"\"\"Shear the BitmapMasks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n magnitude (int | float): The magnitude used for shear.\n direction (str): The shear direction, either \"horizontal\"\n or \"vertical\".\n border_value (int | tuple[int]): Value used in case of a\n constant border.\n interpolation (str): Same as in :func:`mmcv.imshear`.\n\n Returns:\n BitmapMasks: The sheared masks.\n \"\"\"\n if len(self.masks) == 0:\n sheared_masks = np.empty((0, *out_shape), dtype=np.uint8)\n else:\n sheared_masks = mmcv.imshear(\n self.masks.transpose((1, 2, 0)),\n magnitude,\n direction,\n border_value=border_value,\n interpolation=interpolation)\n if sheared_masks.ndim == 2:\n sheared_masks = sheared_masks[:, :, None]\n sheared_masks = sheared_masks.transpose(\n (2, 0, 1)).astype(self.masks.dtype)\n return BitmapMasks(sheared_masks, *out_shape)\n\n def rotate(self,\n out_shape,\n angle,\n center=None,\n scale=1.0,\n border_value=0,\n interpolation='bilinear'):\n \"\"\"Rotate the BitmapMasks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n angle (int | float): Rotation angle in degrees. Positive values\n mean counter-clockwise rotation.\n center (tuple[float], optional): Center point (w, h) of the\n rotation in source image. If not specified, the center of\n the image will be used.\n scale (int | float): Isotropic scale factor.\n border_value (int | float): Border value. Default 0 for masks.\n interpolation (str): Same as in :func:`mmcv.imrotate`.\n\n Returns:\n BitmapMasks: Rotated BitmapMasks.\n \"\"\"\n if len(self.masks) == 0:\n rotated_masks = np.empty((0, *out_shape), dtype=self.masks.dtype)\n else:\n rotated_masks = mmcv.imrotate(\n self.masks.transpose((1, 2, 0)),\n angle,\n center=center,\n scale=scale,\n border_value=border_value,\n interpolation=interpolation)\n if rotated_masks.ndim == 2:\n # case when only one mask, (h, w)\n rotated_masks = rotated_masks[:, :, None] # (h, w, 1)\n rotated_masks = rotated_masks.transpose(\n (2, 0, 1)).astype(self.masks.dtype)\n return BitmapMasks(rotated_masks, *out_shape)\n\n @property\n def areas(self):\n \"\"\"See :py:attr:`BaseInstanceMasks.areas`.\"\"\"\n return self.masks.sum((1, 2))\n\n def to_ndarray(self):\n \"\"\"See :func:`BaseInstanceMasks.to_ndarray`.\"\"\"\n return self.masks\n\n def to_tensor(self, dtype, device):\n \"\"\"See :func:`BaseInstanceMasks.to_tensor`.\"\"\"\n return torch.tensor(self.masks, dtype=dtype, device=device)\n\n @classmethod\n def random(cls,\n num_masks=3,\n height=32,\n width=32,\n dtype=np.uint8,\n rng=None):\n \"\"\"Generate random bitmap masks for demo / testing purposes.\n\n Example:\n >>> from mmdet.data_elements.mask.structures import BitmapMasks\n >>> self = BitmapMasks.random()\n >>> print('self = {}'.format(self))\n self = BitmapMasks(num_masks=3, height=32, width=32)\n \"\"\"\n from mmdet.utils.util_random import ensure_rng\n rng = ensure_rng(rng)\n masks = (rng.rand(num_masks, height, width) > 0.1).astype(dtype)\n self = cls(masks, height=height, width=width)\n return self\n\n @classmethod\n def cat(cls: Type[T], masks: Sequence[T]) -> T:\n \"\"\"Concatenate a sequence of masks into one single mask instance.\n\n Args:\n masks (Sequence[BitmapMasks]): A sequence of mask instances.\n\n Returns:\n BitmapMasks: Concatenated mask instance.\n \"\"\"\n assert isinstance(masks, Sequence)\n if len(masks) == 0:\n raise ValueError('masks should not be an empty list.')\n assert all(isinstance(m, cls) for m in masks)\n\n mask_array = np.concatenate([m.masks for m in masks], axis=0)\n return cls(mask_array, *mask_array.shape[1:])" }, { "identifier": "PolygonMasks", "path": "mmdet/structures/mask/structures.py", "snippet": "class PolygonMasks(BaseInstanceMasks):\n \"\"\"This class represents masks in the form of polygons.\n\n Polygons is a list of three levels. The first level of the list\n corresponds to objects, the second level to the polys that compose the\n object, the third level to the poly coordinates\n\n Args:\n masks (list[list[ndarray]]): The first level of the list\n corresponds to objects, the second level to the polys that\n compose the object, the third level to the poly coordinates\n height (int): height of masks\n width (int): width of masks\n\n Example:\n >>> from mmdet.data_elements.mask.structures import * # NOQA\n >>> masks = [\n >>> [ np.array([0, 0, 10, 0, 10, 10., 0, 10, 0, 0]) ]\n >>> ]\n >>> height, width = 16, 16\n >>> self = PolygonMasks(masks, height, width)\n\n >>> # demo translate\n >>> new = self.translate((16, 16), 4., direction='horizontal')\n >>> assert np.all(new.masks[0][0][1::2] == masks[0][0][1::2])\n >>> assert np.all(new.masks[0][0][0::2] == masks[0][0][0::2] + 4)\n\n >>> # demo crop_and_resize\n >>> num_boxes = 3\n >>> bboxes = np.array([[0, 0, 30, 10.0]] * num_boxes)\n >>> out_shape = (16, 16)\n >>> inds = torch.randint(0, len(self), size=(num_boxes,))\n >>> device = 'cpu'\n >>> interpolation = 'bilinear'\n >>> new = self.crop_and_resize(\n ... bboxes, out_shape, inds, device, interpolation)\n >>> assert len(new) == num_boxes\n >>> assert new.height, new.width == out_shape\n \"\"\"\n\n def __init__(self, masks, height, width):\n assert isinstance(masks, list)\n if len(masks) > 0:\n assert isinstance(masks[0], list)\n assert isinstance(masks[0][0], np.ndarray)\n\n self.height = height\n self.width = width\n self.masks = masks\n\n def __getitem__(self, index):\n \"\"\"Index the polygon masks.\n\n Args:\n index (ndarray | List): The indices.\n\n Returns:\n :obj:`PolygonMasks`: The indexed polygon masks.\n \"\"\"\n if isinstance(index, np.ndarray):\n if index.dtype == bool:\n index = np.where(index)[0].tolist()\n else:\n index = index.tolist()\n if isinstance(index, list):\n masks = [self.masks[i] for i in index]\n else:\n try:\n masks = self.masks[index]\n except Exception:\n raise ValueError(\n f'Unsupported input of type {type(index)} for indexing!')\n if len(masks) and isinstance(masks[0], np.ndarray):\n masks = [masks] # ensure a list of three levels\n return PolygonMasks(masks, self.height, self.width)\n\n def __iter__(self):\n return iter(self.masks)\n\n def __repr__(self):\n s = self.__class__.__name__ + '('\n s += f'num_masks={len(self.masks)}, '\n s += f'height={self.height}, '\n s += f'width={self.width})'\n return s\n\n def __len__(self):\n \"\"\"Number of masks.\"\"\"\n return len(self.masks)\n\n def rescale(self, scale, interpolation=None):\n \"\"\"see :func:`BaseInstanceMasks.rescale`\"\"\"\n new_w, new_h = mmcv.rescale_size((self.width, self.height), scale)\n if len(self.masks) == 0:\n rescaled_masks = PolygonMasks([], new_h, new_w)\n else:\n rescaled_masks = self.resize((new_h, new_w))\n return rescaled_masks\n\n def resize(self, out_shape, interpolation=None):\n \"\"\"see :func:`BaseInstanceMasks.resize`\"\"\"\n if len(self.masks) == 0:\n resized_masks = PolygonMasks([], *out_shape)\n else:\n h_scale = out_shape[0] / self.height\n w_scale = out_shape[1] / self.width\n resized_masks = []\n for poly_per_obj in self.masks:\n resized_poly = []\n for p in poly_per_obj:\n p = p.copy()\n p[0::2] = p[0::2] * w_scale\n p[1::2] = p[1::2] * h_scale\n resized_poly.append(p)\n resized_masks.append(resized_poly)\n resized_masks = PolygonMasks(resized_masks, *out_shape)\n return resized_masks\n\n def flip(self, flip_direction='horizontal'):\n \"\"\"see :func:`BaseInstanceMasks.flip`\"\"\"\n assert flip_direction in ('horizontal', 'vertical', 'diagonal')\n if len(self.masks) == 0:\n flipped_masks = PolygonMasks([], self.height, self.width)\n else:\n flipped_masks = []\n for poly_per_obj in self.masks:\n flipped_poly_per_obj = []\n for p in poly_per_obj:\n p = p.copy()\n if flip_direction == 'horizontal':\n p[0::2] = self.width - p[0::2]\n elif flip_direction == 'vertical':\n p[1::2] = self.height - p[1::2]\n else:\n p[0::2] = self.width - p[0::2]\n p[1::2] = self.height - p[1::2]\n flipped_poly_per_obj.append(p)\n flipped_masks.append(flipped_poly_per_obj)\n flipped_masks = PolygonMasks(flipped_masks, self.height,\n self.width)\n return flipped_masks\n\n def crop(self, bbox):\n \"\"\"see :func:`BaseInstanceMasks.crop`\"\"\"\n assert isinstance(bbox, np.ndarray)\n assert bbox.ndim == 1\n\n # clip the boundary\n bbox = bbox.copy()\n bbox[0::2] = np.clip(bbox[0::2], 0, self.width)\n bbox[1::2] = np.clip(bbox[1::2], 0, self.height)\n x1, y1, x2, y2 = bbox\n w = np.maximum(x2 - x1, 1)\n h = np.maximum(y2 - y1, 1)\n\n if len(self.masks) == 0:\n cropped_masks = PolygonMasks([], h, w)\n else:\n # reference: https://github.com/facebookresearch/fvcore/blob/main/fvcore/transforms/transform.py # noqa\n crop_box = geometry.box(x1, y1, x2, y2).buffer(0.0)\n cropped_masks = []\n # suppress shapely warnings util it incorporates GEOS>=3.11.2\n # reference: https://github.com/shapely/shapely/issues/1345\n initial_settings = np.seterr()\n np.seterr(invalid='ignore')\n for poly_per_obj in self.masks:\n cropped_poly_per_obj = []\n for p in poly_per_obj:\n p = p.copy()\n p = geometry.Polygon(p.reshape(-1, 2)).buffer(0.0)\n # polygon must be valid to perform intersection.\n if not p.is_valid:\n continue\n cropped = p.intersection(crop_box)\n if cropped.is_empty:\n continue\n if isinstance(cropped,\n geometry.collection.BaseMultipartGeometry):\n cropped = cropped.geoms\n else:\n cropped = [cropped]\n # one polygon may be cropped to multiple ones\n for poly in cropped:\n # ignore lines or points\n if not isinstance(\n poly, geometry.Polygon) or not poly.is_valid:\n continue\n coords = np.asarray(poly.exterior.coords)\n # remove an extra identical vertex at the end\n coords = coords[:-1]\n coords[:, 0] -= x1\n coords[:, 1] -= y1\n cropped_poly_per_obj.append(coords.reshape(-1))\n # a dummy polygon to avoid misalignment between masks and boxes\n if len(cropped_poly_per_obj) == 0:\n cropped_poly_per_obj = [np.array([0, 0, 0, 0, 0, 0])]\n cropped_masks.append(cropped_poly_per_obj)\n np.seterr(**initial_settings)\n cropped_masks = PolygonMasks(cropped_masks, h, w)\n return cropped_masks\n\n def pad(self, out_shape, pad_val=0):\n \"\"\"padding has no effect on polygons`\"\"\"\n return PolygonMasks(self.masks, *out_shape)\n\n def expand(self, *args, **kwargs):\n \"\"\"TODO: Add expand for polygon\"\"\"\n raise NotImplementedError\n\n def crop_and_resize(self,\n bboxes,\n out_shape,\n inds,\n device='cpu',\n interpolation='bilinear',\n binarize=True):\n \"\"\"see :func:`BaseInstanceMasks.crop_and_resize`\"\"\"\n out_h, out_w = out_shape\n if len(self.masks) == 0:\n return PolygonMasks([], out_h, out_w)\n\n if not binarize:\n raise ValueError('Polygons are always binary, '\n 'setting binarize=False is unsupported')\n\n resized_masks = []\n for i in range(len(bboxes)):\n mask = self.masks[inds[i]]\n bbox = bboxes[i, :]\n x1, y1, x2, y2 = bbox\n w = np.maximum(x2 - x1, 1)\n h = np.maximum(y2 - y1, 1)\n h_scale = out_h / max(h, 0.1) # avoid too large scale\n w_scale = out_w / max(w, 0.1)\n\n resized_mask = []\n for p in mask:\n p = p.copy()\n # crop\n # pycocotools will clip the boundary\n p[0::2] = p[0::2] - bbox[0]\n p[1::2] = p[1::2] - bbox[1]\n\n # resize\n p[0::2] = p[0::2] * w_scale\n p[1::2] = p[1::2] * h_scale\n resized_mask.append(p)\n resized_masks.append(resized_mask)\n return PolygonMasks(resized_masks, *out_shape)\n\n def translate(self,\n out_shape,\n offset,\n direction='horizontal',\n border_value=None,\n interpolation=None):\n \"\"\"Translate the PolygonMasks.\n\n Example:\n >>> self = PolygonMasks.random(dtype=np.int64)\n >>> out_shape = (self.height, self.width)\n >>> new = self.translate(out_shape, 4., direction='horizontal')\n >>> assert np.all(new.masks[0][0][1::2] == self.masks[0][0][1::2])\n >>> assert np.all(new.masks[0][0][0::2] == self.masks[0][0][0::2] + 4) # noqa: E501\n \"\"\"\n assert border_value is None or border_value == 0, \\\n 'Here border_value is not '\\\n f'used, and defaultly should be None or 0. got {border_value}.'\n if len(self.masks) == 0:\n translated_masks = PolygonMasks([], *out_shape)\n else:\n translated_masks = []\n for poly_per_obj in self.masks:\n translated_poly_per_obj = []\n for p in poly_per_obj:\n p = p.copy()\n if direction == 'horizontal':\n p[0::2] = np.clip(p[0::2] + offset, 0, out_shape[1])\n elif direction == 'vertical':\n p[1::2] = np.clip(p[1::2] + offset, 0, out_shape[0])\n translated_poly_per_obj.append(p)\n translated_masks.append(translated_poly_per_obj)\n translated_masks = PolygonMasks(translated_masks, *out_shape)\n return translated_masks\n\n def shear(self,\n out_shape,\n magnitude,\n direction='horizontal',\n border_value=0,\n interpolation='bilinear'):\n \"\"\"See :func:`BaseInstanceMasks.shear`.\"\"\"\n if len(self.masks) == 0:\n sheared_masks = PolygonMasks([], *out_shape)\n else:\n sheared_masks = []\n if direction == 'horizontal':\n shear_matrix = np.stack([[1, magnitude],\n [0, 1]]).astype(np.float32)\n elif direction == 'vertical':\n shear_matrix = np.stack([[1, 0], [magnitude,\n 1]]).astype(np.float32)\n for poly_per_obj in self.masks:\n sheared_poly = []\n for p in poly_per_obj:\n p = np.stack([p[0::2], p[1::2]], axis=0) # [2, n]\n new_coords = np.matmul(shear_matrix, p) # [2, n]\n new_coords[0, :] = np.clip(new_coords[0, :], 0,\n out_shape[1])\n new_coords[1, :] = np.clip(new_coords[1, :], 0,\n out_shape[0])\n sheared_poly.append(\n new_coords.transpose((1, 0)).reshape(-1))\n sheared_masks.append(sheared_poly)\n sheared_masks = PolygonMasks(sheared_masks, *out_shape)\n return sheared_masks\n\n def rotate(self,\n out_shape,\n angle,\n center=None,\n scale=1.0,\n border_value=0,\n interpolation='bilinear'):\n \"\"\"See :func:`BaseInstanceMasks.rotate`.\"\"\"\n if len(self.masks) == 0:\n rotated_masks = PolygonMasks([], *out_shape)\n else:\n rotated_masks = []\n rotate_matrix = cv2.getRotationMatrix2D(center, -angle, scale)\n for poly_per_obj in self.masks:\n rotated_poly = []\n for p in poly_per_obj:\n p = p.copy()\n coords = np.stack([p[0::2], p[1::2]], axis=1) # [n, 2]\n # pad 1 to convert from format [x, y] to homogeneous\n # coordinates format [x, y, 1]\n coords = np.concatenate(\n (coords, np.ones((coords.shape[0], 1), coords.dtype)),\n axis=1) # [n, 3]\n rotated_coords = np.matmul(\n rotate_matrix[None, :, :],\n coords[:, :, None])[..., 0] # [n, 2, 1] -> [n, 2]\n rotated_coords[:, 0] = np.clip(rotated_coords[:, 0], 0,\n out_shape[1])\n rotated_coords[:, 1] = np.clip(rotated_coords[:, 1], 0,\n out_shape[0])\n rotated_poly.append(rotated_coords.reshape(-1))\n rotated_masks.append(rotated_poly)\n rotated_masks = PolygonMasks(rotated_masks, *out_shape)\n return rotated_masks\n\n def to_bitmap(self):\n \"\"\"convert polygon masks to bitmap masks.\"\"\"\n bitmap_masks = self.to_ndarray()\n return BitmapMasks(bitmap_masks, self.height, self.width)\n\n @property\n def areas(self):\n \"\"\"Compute areas of masks.\n\n This func is modified from `detectron2\n <https://github.com/facebookresearch/detectron2/blob/ffff8acc35ea88ad1cb1806ab0f00b4c1c5dbfd9/detectron2/structures/masks.py#L387>`_.\n The function only works with Polygons using the shoelace formula.\n\n Return:\n ndarray: areas of each instance\n \"\"\" # noqa: W501\n area = []\n for polygons_per_obj in self.masks:\n area_per_obj = 0\n for p in polygons_per_obj:\n area_per_obj += self._polygon_area(p[0::2], p[1::2])\n area.append(area_per_obj)\n return np.asarray(area)\n\n def _polygon_area(self, x, y):\n \"\"\"Compute the area of a component of a polygon.\n\n Using the shoelace formula:\n https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates\n\n Args:\n x (ndarray): x coordinates of the component\n y (ndarray): y coordinates of the component\n\n Return:\n float: the are of the component\n \"\"\" # noqa: 501\n return 0.5 * np.abs(\n np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))\n\n def to_ndarray(self):\n \"\"\"Convert masks to the format of ndarray.\"\"\"\n if len(self.masks) == 0:\n return np.empty((0, self.height, self.width), dtype=np.uint8)\n bitmap_masks = []\n for poly_per_obj in self.masks:\n bitmap_masks.append(\n polygon_to_bitmap(poly_per_obj, self.height, self.width))\n return np.stack(bitmap_masks)\n\n def to_tensor(self, dtype, device):\n \"\"\"See :func:`BaseInstanceMasks.to_tensor`.\"\"\"\n if len(self.masks) == 0:\n return torch.empty((0, self.height, self.width),\n dtype=dtype,\n device=device)\n ndarray_masks = self.to_ndarray()\n return torch.tensor(ndarray_masks, dtype=dtype, device=device)\n\n @classmethod\n def random(cls,\n num_masks=3,\n height=32,\n width=32,\n n_verts=5,\n dtype=np.float32,\n rng=None):\n \"\"\"Generate random polygon masks for demo / testing purposes.\n\n Adapted from [1]_\n\n References:\n .. [1] https://gitlab.kitware.com/computer-vision/kwimage/-/blob/928cae35ca8/kwimage/structs/polygon.py#L379 # noqa: E501\n\n Example:\n >>> from mmdet.data_elements.mask.structures import PolygonMasks\n >>> self = PolygonMasks.random()\n >>> print('self = {}'.format(self))\n \"\"\"\n from mmdet.utils.util_random import ensure_rng\n rng = ensure_rng(rng)\n\n def _gen_polygon(n, irregularity, spikeyness):\n \"\"\"Creates the polygon by sampling points on a circle around the\n centre. Random noise is added by varying the angular spacing\n between sequential points, and by varying the radial distance of\n each point from the centre.\n\n Based on original code by Mike Ounsworth\n\n Args:\n n (int): number of vertices\n irregularity (float): [0,1] indicating how much variance there\n is in the angular spacing of vertices. [0,1] will map to\n [0, 2pi/numberOfVerts]\n spikeyness (float): [0,1] indicating how much variance there is\n in each vertex from the circle of radius aveRadius. [0,1]\n will map to [0, aveRadius]\n\n Returns:\n a list of vertices, in CCW order.\n \"\"\"\n from scipy.stats import truncnorm\n\n # Generate around the unit circle\n cx, cy = (0.0, 0.0)\n radius = 1\n\n tau = np.pi * 2\n\n irregularity = np.clip(irregularity, 0, 1) * 2 * np.pi / n\n spikeyness = np.clip(spikeyness, 1e-9, 1)\n\n # generate n angle steps\n lower = (tau / n) - irregularity\n upper = (tau / n) + irregularity\n angle_steps = rng.uniform(lower, upper, n)\n\n # normalize the steps so that point 0 and point n+1 are the same\n k = angle_steps.sum() / (2 * np.pi)\n angles = (angle_steps / k).cumsum() + rng.uniform(0, tau)\n\n # Convert high and low values to be wrt the standard normal range\n # https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.truncnorm.html\n low = 0\n high = 2 * radius\n mean = radius\n std = spikeyness\n a = (low - mean) / std\n b = (high - mean) / std\n tnorm = truncnorm(a=a, b=b, loc=mean, scale=std)\n\n # now generate the points\n radii = tnorm.rvs(n, random_state=rng)\n x_pts = cx + radii * np.cos(angles)\n y_pts = cy + radii * np.sin(angles)\n\n points = np.hstack([x_pts[:, None], y_pts[:, None]])\n\n # Scale to 0-1 space\n points = points - points.min(axis=0)\n points = points / points.max(axis=0)\n\n # Randomly place within 0-1 space\n points = points * (rng.rand() * .8 + .2)\n min_pt = points.min(axis=0)\n max_pt = points.max(axis=0)\n\n high = (1 - max_pt)\n low = (0 - min_pt)\n offset = (rng.rand(2) * (high - low)) + low\n points = points + offset\n return points\n\n def _order_vertices(verts):\n \"\"\"\n References:\n https://stackoverflow.com/questions/1709283/how-can-i-sort-a-coordinate-list-for-a-rectangle-counterclockwise\n \"\"\"\n mlat = verts.T[0].sum() / len(verts)\n mlng = verts.T[1].sum() / len(verts)\n\n tau = np.pi * 2\n angle = (np.arctan2(mlat - verts.T[0], verts.T[1] - mlng) +\n tau) % tau\n sortx = angle.argsort()\n verts = verts.take(sortx, axis=0)\n return verts\n\n # Generate a random exterior for each requested mask\n masks = []\n for _ in range(num_masks):\n exterior = _order_vertices(_gen_polygon(n_verts, 0.9, 0.9))\n exterior = (exterior * [(width, height)]).astype(dtype)\n masks.append([exterior.ravel()])\n\n self = cls(masks, height, width)\n return self\n\n @classmethod\n def cat(cls: Type[T], masks: Sequence[T]) -> T:\n \"\"\"Concatenate a sequence of masks into one single mask instance.\n\n Args:\n masks (Sequence[PolygonMasks]): A sequence of mask instances.\n\n Returns:\n PolygonMasks: Concatenated mask instance.\n \"\"\"\n assert isinstance(masks, Sequence)\n if len(masks) == 0:\n raise ValueError('masks should not be an empty list.')\n assert all(isinstance(m, cls) for m in masks)\n\n mask_list = list(itertools.chain(*[m.masks for m in masks]))\n return cls(mask_list, masks[0].height, masks[0].width)" }, { "identifier": "OptInstanceList", "path": "mmdet/utils/typing_utils.py", "snippet": "" } ]
from functools import partial from typing import List, Optional, Sequence, Tuple, Union from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional as F from mmdet.structures import SampleList from mmdet.structures.bbox import BaseBoxes, get_box_type, stack_boxes from mmdet.structures.mask import BitmapMasks, PolygonMasks from mmdet.utils import OptInstanceList import numpy as np import torch
18,160
(num_bboxes_filtered, ). - filtered_results (dict or list or Tensor, Optional): \ The filtered results. The shape of each item is \ (num_bboxes_filtered, N). """ valid_mask = scores > score_thr scores = scores[valid_mask] valid_idxs = torch.nonzero(valid_mask) num_topk = min(topk, valid_idxs.size(0)) # torch.sort is actually faster than .topk (at least on GPUs) scores, idxs = scores.sort(descending=True) scores = scores[:num_topk] topk_idxs = valid_idxs[idxs[:num_topk]] keep_idxs, labels = topk_idxs.unbind(dim=1) filtered_results = None if results is not None: if isinstance(results, dict): filtered_results = {k: v[keep_idxs] for k, v in results.items()} elif isinstance(results, list): filtered_results = [result[keep_idxs] for result in results] elif isinstance(results, torch.Tensor): filtered_results = results[keep_idxs] else: raise NotImplementedError(f'Only supports dict or list or Tensor, ' f'but get {type(results)}.') return scores, labels, keep_idxs, filtered_results def center_of_mass(mask, esp=1e-6): """Calculate the centroid coordinates of the mask. Args: mask (Tensor): The mask to be calculated, shape (h, w). esp (float): Avoid dividing by zero. Default: 1e-6. Returns: tuple[Tensor]: the coordinates of the center point of the mask. - center_h (Tensor): the center point of the height. - center_w (Tensor): the center point of the width. """ h, w = mask.shape grid_h = torch.arange(h, device=mask.device)[:, None] grid_w = torch.arange(w, device=mask.device) normalizer = mask.sum().float().clamp(min=esp) center_h = (mask * grid_h).sum() / normalizer center_w = (mask * grid_w).sum() / normalizer return center_h, center_w def generate_coordinate(featmap_sizes, device='cuda'): """Generate the coordinate. Args: featmap_sizes (tuple): The feature to be calculated, of shape (N, C, W, H). device (str): The device where the feature will be put on. Returns: coord_feat (Tensor): The coordinate feature, of shape (N, 2, W, H). """ x_range = torch.linspace(-1, 1, featmap_sizes[-1], device=device) y_range = torch.linspace(-1, 1, featmap_sizes[-2], device=device) y, x = torch.meshgrid(y_range, x_range) y = y.expand([featmap_sizes[0], 1, -1, -1]) x = x.expand([featmap_sizes[0], 1, -1, -1]) coord_feat = torch.cat([x, y], 1) return coord_feat def levels_to_images(mlvl_tensor: List[torch.Tensor]) -> List[torch.Tensor]: """Concat multi-level feature maps by image. [feature_level0, feature_level1...] -> [feature_image0, feature_image1...] Convert the shape of each element in mlvl_tensor from (N, C, H, W) to (N, H*W , C), then split the element to N elements with shape (H*W, C), and concat elements in same image of all level along first dimension. Args: mlvl_tensor (list[Tensor]): list of Tensor which collect from corresponding level. Each element is of shape (N, C, H, W) Returns: list[Tensor]: A list that contains N tensors and each tensor is of shape (num_elements, C) """ batch_size = mlvl_tensor[0].size(0) batch_list = [[] for _ in range(batch_size)] channels = mlvl_tensor[0].size(1) for t in mlvl_tensor: t = t.permute(0, 2, 3, 1) t = t.view(batch_size, -1, channels).contiguous() for img in range(batch_size): batch_list[img].append(t[img]) return [torch.cat(item, 0) for item in batch_list] def images_to_levels(target, num_levels): """Convert targets by image to targets by feature level. [target_img0, target_img1] -> [target_level0, target_level1, ...] """ target = stack_boxes(target, 0) level_targets = [] start = 0 for n in num_levels: end = start + n # level_targets.append(target[:, start:end].squeeze(0)) level_targets.append(target[:, start:end]) start = end return level_targets def samplelist_boxtype2tensor(batch_data_samples: SampleList) -> SampleList: for data_samples in batch_data_samples: if 'gt_instances' in data_samples: bboxes = data_samples.gt_instances.get('bboxes', None)
# Copyright (c) OpenMMLab. All rights reserved. class SigmoidGeometricMean(Function): """Forward and backward function of geometric mean of two sigmoid functions. This implementation with analytical gradient function substitutes the autograd function of (x.sigmoid() * y.sigmoid()).sqrt(). The original implementation incurs none during gradient backprapagation if both x and y are very small values. """ @staticmethod def forward(ctx, x, y): x_sigmoid = x.sigmoid() y_sigmoid = y.sigmoid() z = (x_sigmoid * y_sigmoid).sqrt() ctx.save_for_backward(x_sigmoid, y_sigmoid, z) return z @staticmethod def backward(ctx, grad_output): x_sigmoid, y_sigmoid, z = ctx.saved_tensors grad_x = grad_output * z * (1 - x_sigmoid) / 2 grad_y = grad_output * z * (1 - y_sigmoid) / 2 return grad_x, grad_y sigmoid_geometric_mean = SigmoidGeometricMean.apply def interpolate_as(source, target, mode='bilinear', align_corners=False): """Interpolate the `source` to the shape of the `target`. The `source` must be a Tensor, but the `target` can be a Tensor or a np.ndarray with the shape (..., target_h, target_w). Args: source (Tensor): A 3D/4D Tensor with the shape (N, H, W) or (N, C, H, W). target (Tensor | np.ndarray): The interpolation target with the shape (..., target_h, target_w). mode (str): Algorithm used for interpolation. The options are the same as those in F.interpolate(). Default: ``'bilinear'``. align_corners (bool): The same as the argument in F.interpolate(). Returns: Tensor: The interpolated source Tensor. """ assert len(target.shape) >= 2 def _interpolate_as(source, target, mode='bilinear', align_corners=False): """Interpolate the `source` (4D) to the shape of the `target`.""" target_h, target_w = target.shape[-2:] source_h, source_w = source.shape[-2:] if target_h != source_h or target_w != source_w: source = F.interpolate( source, size=(target_h, target_w), mode=mode, align_corners=align_corners) return source if len(source.shape) == 3: source = source[:, None, :, :] source = _interpolate_as(source, target, mode, align_corners) return source[:, 0, :, :] else: return _interpolate_as(source, target, mode, align_corners) def unpack_gt_instances(batch_data_samples: SampleList) -> tuple: """Unpack ``gt_instances``, ``gt_instances_ignore`` and ``img_metas`` based on ``batch_data_samples`` Args: batch_data_samples (List[:obj:`DetDataSample`]): The Data Samples. It usually includes information such as `gt_instance`, `gt_panoptic_seg` and `gt_sem_seg`. Returns: tuple: - batch_gt_instances (list[:obj:`InstanceData`]): Batch of gt_instance. It usually includes ``bboxes`` and ``labels`` attributes. - batch_gt_instances_ignore (list[:obj:`InstanceData`]): Batch of gt_instances_ignore. It includes ``bboxes`` attribute data that is ignored during training and testing. Defaults to None. - batch_img_metas (list[dict]): Meta information of each image, e.g., image size, scaling factor, etc. """ batch_gt_instances = [] batch_gt_instances_ignore = [] batch_img_metas = [] for data_sample in batch_data_samples: batch_img_metas.append(data_sample.metainfo) batch_gt_instances.append(data_sample.gt_instances) if 'ignored_instances' in data_sample: batch_gt_instances_ignore.append(data_sample.ignored_instances) else: batch_gt_instances_ignore.append(None) return batch_gt_instances, batch_gt_instances_ignore, batch_img_metas def empty_instances(batch_img_metas: List[dict], device: torch.device, task_type: str, instance_results: OptInstanceList = None, mask_thr_binary: Union[int, float] = 0, box_type: Union[str, type] = 'hbox', use_box_type: bool = False, num_classes: int = 80, score_per_cls: bool = False) -> List[InstanceData]: """Handle predicted instances when RoI is empty. Note: If ``instance_results`` is not None, it will be modified in place internally, and then return ``instance_results`` Args: batch_img_metas (list[dict]): List of image information. device (torch.device): Device of tensor. task_type (str): Expected returned task type. it currently supports bbox and mask. instance_results (list[:obj:`InstanceData`]): List of instance results. mask_thr_binary (int, float): mask binarization threshold. Defaults to 0. box_type (str or type): The empty box type. Defaults to `hbox`. use_box_type (bool): Whether to warp boxes with the box type. Defaults to False. num_classes (int): num_classes of bbox_head. Defaults to 80. score_per_cls (bool): Whether to generate classwise score for the empty instance. ``score_per_cls`` will be True when the model needs to produce raw results without nms. Defaults to False. Returns: list[:obj:`InstanceData`]: Detection results of each image """ assert task_type in ('bbox', 'mask'), 'Only support bbox and mask,' \ f' but got {task_type}' if instance_results is not None: assert len(instance_results) == len(batch_img_metas) results_list = [] for img_id in range(len(batch_img_metas)): if instance_results is not None: results = instance_results[img_id] assert isinstance(results, InstanceData) else: results = InstanceData() if task_type == 'bbox': _, box_type = get_box_type(box_type) bboxes = torch.zeros(0, box_type.box_dim, device=device) if use_box_type: bboxes = box_type(bboxes, clone=False) results.bboxes = bboxes score_shape = (0, num_classes + 1) if score_per_cls else (0, ) results.scores = torch.zeros(score_shape, device=device) results.labels = torch.zeros((0, ), device=device, dtype=torch.long) else: # TODO: Handle the case where rescale is false img_h, img_w = batch_img_metas[img_id]['ori_shape'][:2] # the type of `im_mask` will be torch.bool or torch.uint8, # where uint8 if for visualization and debugging. im_mask = torch.zeros( 0, img_h, img_w, device=device, dtype=torch.bool if mask_thr_binary >= 0 else torch.uint8) results.masks = im_mask results_list.append(results) return results_list def multi_apply(func, *args, **kwargs): """Apply function to a list of arguments. Note: This function applies the ``func`` to multiple inputs and map the multiple outputs of the ``func`` into different list. Each list contains the same type of outputs corresponding to different inputs. Args: func (Function): A function that will be applied to a list of arguments Returns: tuple(list): A tuple containing multiple list, each list contains \ a kind of returned results by the function """ pfunc = partial(func, **kwargs) if kwargs else func map_results = map(pfunc, *args) return tuple(map(list, zip(*map_results))) def unmap(data, count, inds, fill=0): """Unmap a subset of item (data) back to the original set of items (of size count)""" if data.dim() == 1: ret = data.new_full((count, ), fill) ret[inds.type(torch.bool)] = data else: new_size = (count, ) + data.size()[1:] ret = data.new_full(new_size, fill) ret[inds.type(torch.bool), :] = data return ret def mask2ndarray(mask): """Convert Mask to ndarray.. Args: mask (:obj:`BitmapMasks` or :obj:`PolygonMasks` or torch.Tensor or np.ndarray): The mask to be converted. Returns: np.ndarray: Ndarray mask of shape (n, h, w) that has been converted """ if isinstance(mask, (BitmapMasks, PolygonMasks)): mask = mask.to_ndarray() elif isinstance(mask, torch.Tensor): mask = mask.detach().cpu().numpy() elif not isinstance(mask, np.ndarray): raise TypeError(f'Unsupported {type(mask)} data type') return mask def flip_tensor(src_tensor, flip_direction): """flip tensor base on flip_direction. Args: src_tensor (Tensor): input feature map, shape (B, C, H, W). flip_direction (str): The flipping direction. Options are 'horizontal', 'vertical', 'diagonal'. Returns: out_tensor (Tensor): Flipped tensor. """ assert src_tensor.ndim == 4 valid_directions = ['horizontal', 'vertical', 'diagonal'] assert flip_direction in valid_directions if flip_direction == 'horizontal': out_tensor = torch.flip(src_tensor, [3]) elif flip_direction == 'vertical': out_tensor = torch.flip(src_tensor, [2]) else: out_tensor = torch.flip(src_tensor, [2, 3]) return out_tensor def select_single_mlvl(mlvl_tensors, batch_id, detach=True): """Extract a multi-scale single image tensor from a multi-scale batch tensor based on batch index. Note: The default value of detach is True, because the proposal gradient needs to be detached during the training of the two-stage model. E.g Cascade Mask R-CNN. Args: mlvl_tensors (list[Tensor]): Batch tensor for all scale levels, each is a 4D-tensor. batch_id (int): Batch index. detach (bool): Whether detach gradient. Default True. Returns: list[Tensor]: Multi-scale single image tensor. """ assert isinstance(mlvl_tensors, (list, tuple)) num_levels = len(mlvl_tensors) if detach: mlvl_tensor_list = [ mlvl_tensors[i][batch_id].detach() for i in range(num_levels) ] else: mlvl_tensor_list = [ mlvl_tensors[i][batch_id] for i in range(num_levels) ] return mlvl_tensor_list def filter_scores_and_topk(scores, score_thr, topk, results=None): """Filter results using score threshold and topk candidates. Args: scores (Tensor): The scores, shape (num_bboxes, K). score_thr (float): The score filter threshold. topk (int): The number of topk candidates. results (dict or list or Tensor, Optional): The results to which the filtering rule is to be applied. The shape of each item is (num_bboxes, N). Returns: tuple: Filtered results - scores (Tensor): The scores after being filtered, \ shape (num_bboxes_filtered, ). - labels (Tensor): The class labels, shape \ (num_bboxes_filtered, ). - anchor_idxs (Tensor): The anchor indexes, shape \ (num_bboxes_filtered, ). - filtered_results (dict or list or Tensor, Optional): \ The filtered results. The shape of each item is \ (num_bboxes_filtered, N). """ valid_mask = scores > score_thr scores = scores[valid_mask] valid_idxs = torch.nonzero(valid_mask) num_topk = min(topk, valid_idxs.size(0)) # torch.sort is actually faster than .topk (at least on GPUs) scores, idxs = scores.sort(descending=True) scores = scores[:num_topk] topk_idxs = valid_idxs[idxs[:num_topk]] keep_idxs, labels = topk_idxs.unbind(dim=1) filtered_results = None if results is not None: if isinstance(results, dict): filtered_results = {k: v[keep_idxs] for k, v in results.items()} elif isinstance(results, list): filtered_results = [result[keep_idxs] for result in results] elif isinstance(results, torch.Tensor): filtered_results = results[keep_idxs] else: raise NotImplementedError(f'Only supports dict or list or Tensor, ' f'but get {type(results)}.') return scores, labels, keep_idxs, filtered_results def center_of_mass(mask, esp=1e-6): """Calculate the centroid coordinates of the mask. Args: mask (Tensor): The mask to be calculated, shape (h, w). esp (float): Avoid dividing by zero. Default: 1e-6. Returns: tuple[Tensor]: the coordinates of the center point of the mask. - center_h (Tensor): the center point of the height. - center_w (Tensor): the center point of the width. """ h, w = mask.shape grid_h = torch.arange(h, device=mask.device)[:, None] grid_w = torch.arange(w, device=mask.device) normalizer = mask.sum().float().clamp(min=esp) center_h = (mask * grid_h).sum() / normalizer center_w = (mask * grid_w).sum() / normalizer return center_h, center_w def generate_coordinate(featmap_sizes, device='cuda'): """Generate the coordinate. Args: featmap_sizes (tuple): The feature to be calculated, of shape (N, C, W, H). device (str): The device where the feature will be put on. Returns: coord_feat (Tensor): The coordinate feature, of shape (N, 2, W, H). """ x_range = torch.linspace(-1, 1, featmap_sizes[-1], device=device) y_range = torch.linspace(-1, 1, featmap_sizes[-2], device=device) y, x = torch.meshgrid(y_range, x_range) y = y.expand([featmap_sizes[0], 1, -1, -1]) x = x.expand([featmap_sizes[0], 1, -1, -1]) coord_feat = torch.cat([x, y], 1) return coord_feat def levels_to_images(mlvl_tensor: List[torch.Tensor]) -> List[torch.Tensor]: """Concat multi-level feature maps by image. [feature_level0, feature_level1...] -> [feature_image0, feature_image1...] Convert the shape of each element in mlvl_tensor from (N, C, H, W) to (N, H*W , C), then split the element to N elements with shape (H*W, C), and concat elements in same image of all level along first dimension. Args: mlvl_tensor (list[Tensor]): list of Tensor which collect from corresponding level. Each element is of shape (N, C, H, W) Returns: list[Tensor]: A list that contains N tensors and each tensor is of shape (num_elements, C) """ batch_size = mlvl_tensor[0].size(0) batch_list = [[] for _ in range(batch_size)] channels = mlvl_tensor[0].size(1) for t in mlvl_tensor: t = t.permute(0, 2, 3, 1) t = t.view(batch_size, -1, channels).contiguous() for img in range(batch_size): batch_list[img].append(t[img]) return [torch.cat(item, 0) for item in batch_list] def images_to_levels(target, num_levels): """Convert targets by image to targets by feature level. [target_img0, target_img1] -> [target_level0, target_level1, ...] """ target = stack_boxes(target, 0) level_targets = [] start = 0 for n in num_levels: end = start + n # level_targets.append(target[:, start:end].squeeze(0)) level_targets.append(target[:, start:end]) start = end return level_targets def samplelist_boxtype2tensor(batch_data_samples: SampleList) -> SampleList: for data_samples in batch_data_samples: if 'gt_instances' in data_samples: bboxes = data_samples.gt_instances.get('bboxes', None)
if isinstance(bboxes, BaseBoxes):
1
2023-12-11 15:23:03+00:00
24k
chinhsuanwu/ifusion
model/zero123.py
[ { "identifier": "inject_trainable_lora_extended", "path": "ldm/lora.py", "snippet": "def inject_trainable_lora_extended(\n model: nn.Module,\n target_replace_module: Set[str] = UNET_EXTENDED_TARGET_REPLACE,\n r: int = 4,\n loras=None, # path to lora .pt\n eval=True,\n):\n \"\"\"\n inject lora into model, and returns lora parameter groups.\n \"\"\"\n\n require_grad_params = []\n names = []\n\n if loras != None:\n loras = torch.load(loras, map_location=model.device)\n\n for _module, name, _child_module in _find_modules(\n model, target_replace_module, search_class=[nn.Linear, nn.Conv2d]\n ):\n if _child_module.__class__ == nn.Linear:\n weight = _child_module.weight\n bias = _child_module.bias\n _tmp = LoraInjectedLinear(\n _child_module.in_features,\n _child_module.out_features,\n _child_module.bias is not None,\n r=r,\n )\n _tmp.linear.weight = weight\n if bias is not None:\n _tmp.linear.bias = bias\n elif _child_module.__class__ == nn.Conv2d:\n weight = _child_module.weight\n bias = _child_module.bias\n _tmp = LoraInjectedConv2d(\n _child_module.in_channels,\n _child_module.out_channels,\n _child_module.kernel_size,\n _child_module.stride,\n _child_module.padding,\n _child_module.dilation,\n _child_module.groups,\n _child_module.bias is not None,\n r=r,\n )\n\n _tmp.conv.weight = weight\n if bias is not None:\n _tmp.conv.bias = bias\n\n # switch the module\n _tmp.to(_child_module.weight.device).to(_child_module.weight.dtype)\n if bias is not None:\n _tmp.to(_child_module.bias.device).to(_child_module.bias.dtype)\n\n _module._modules[name] = _tmp\n\n require_grad_params.append(_module._modules[name].lora_up.parameters())\n require_grad_params.append(_module._modules[name].lora_down.parameters())\n\n if loras != None:\n _module._modules[name].lora_up.weight = nn.Parameter(loras.pop(0).to(model.dtype))\n _module._modules[name].lora_down.weight = nn.Parameter(loras.pop(0).to(model.dtype))\n\n _module._modules[name].lora_up.weight.requires_grad = True if not eval else False\n _module._modules[name].lora_down.weight.requires_grad = True if not eval else False\n names.append(name)\n\n return require_grad_params, names" }, { "identifier": "monkeypatch_remove_lora", "path": "ldm/lora.py", "snippet": "def monkeypatch_remove_lora(model):\n for _module, name, _child_module in _find_modules(\n model, search_class=[LoraInjectedLinear, LoraInjectedConv2d]\n ):\n if isinstance(_child_module, LoraInjectedLinear):\n _source = _child_module.linear\n weight, bias = _source.weight, _source.bias\n\n _tmp = nn.Linear(\n _source.in_features, _source.out_features, bias is not None\n )\n\n _tmp.weight = weight\n if bias is not None:\n _tmp.bias = bias\n\n else:\n _source = _child_module.conv\n weight, bias = _source.weight, _source.bias\n\n _tmp = nn.Conv2d(\n in_channels=_source.in_channels,\n out_channels=_source.out_channels,\n kernel_size=_source.kernel_size,\n stride=_source.stride,\n padding=_source.padding,\n dilation=_source.dilation,\n groups=_source.groups,\n bias=bias is not None,\n )\n\n _tmp.weight = weight\n if bias is not None:\n _tmp.bias = bias\n\n _module._modules[name] = _tmp" }, { "identifier": "save_lora_weight", "path": "ldm/lora.py", "snippet": "def save_lora_weight(\n model,\n path=\"./lora.pt\",\n target_replace_module=DEFAULT_TARGET_REPLACE,\n):\n weights = []\n for _up, _down in extract_lora_ups_down(\n model, target_replace_module=target_replace_module\n ):\n weights.append(_up.weight.to(\"cpu\").to(torch.float16))\n weights.append(_down.weight.to(\"cpu\").to(torch.float16))\n\n torch.save(weights, path)" }, { "identifier": "LatentDiffusion", "path": "ldm/models/diffusion/ddpm.py", "snippet": "class LatentDiffusion(DDPM):\n \"\"\"main class\"\"\"\n\n def __init__(\n self,\n first_stage_config,\n cond_stage_config,\n num_timesteps_cond=None,\n cond_stage_key=\"image_cond\",\n cond_stage_trainable=False,\n concat_mode=True,\n cond_stage_forward=None,\n conditioning_key=None,\n scale_factor=1.0,\n scale_by_std=False,\n unet_trainable=True,\n *args,\n **kwargs,\n ):\n self.num_timesteps_cond = default(num_timesteps_cond, 1)\n self.scale_by_std = scale_by_std\n assert self.num_timesteps_cond <= kwargs[\"timesteps\"]\n # for backwards compatibility after implementation of DiffusionWrapper\n if conditioning_key is None:\n conditioning_key = \"concat\" if concat_mode else \"crossattn\"\n if cond_stage_config == \"__is_unconditional__\":\n conditioning_key = None\n ckpt_path = kwargs.pop(\"ckpt_path\", None)\n ignore_keys = kwargs.pop(\"ignore_keys\", [])\n super().__init__(conditioning_key=conditioning_key, *args, **kwargs)\n self.concat_mode = concat_mode\n self.cond_stage_trainable = cond_stage_trainable\n self.unet_trainable = unet_trainable\n self.cond_stage_key = cond_stage_key\n try:\n self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1\n except:\n self.num_downs = 0\n if not scale_by_std:\n self.scale_factor = scale_factor\n else:\n self.register_buffer(\"scale_factor\", torch.tensor(scale_factor))\n self.instantiate_first_stage(first_stage_config)\n self.instantiate_cond_stage(cond_stage_config)\n self.cond_stage_forward = cond_stage_forward\n\n # construct linear projection layer for concatenating image CLIP embedding and RT\n self.cc_projection = nn.Linear(772, 768)\n nn.init.eye_(list(self.cc_projection.parameters())[0][:768, :768])\n nn.init.zeros_(list(self.cc_projection.parameters())[1])\n self.cc_projection.requires_grad_(True)\n\n self.clip_denoised = False\n self.bbox_tokenizer = None\n\n self.restarted_from_ckpt = False\n if ckpt_path is not None:\n self.init_from_ckpt(ckpt_path, ignore_keys)\n self.restarted_from_ckpt = True\n\n def make_cond_schedule(\n self,\n ):\n self.cond_ids = torch.full(\n size=(self.num_timesteps,),\n fill_value=self.num_timesteps - 1,\n dtype=torch.long,\n )\n ids = torch.round(\n torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)\n ).long()\n self.cond_ids[: self.num_timesteps_cond] = ids\n\n @rank_zero_only\n @torch.no_grad()\n def on_train_batch_start(self, batch, batch_idx, dataloader_idx):\n # only for very first batch\n if (\n self.scale_by_std\n and self.current_epoch == 0\n and self.global_step == 0\n and batch_idx == 0\n and not self.restarted_from_ckpt\n ):\n assert (\n self.scale_factor == 1.0\n ), \"rather not use custom rescaling and std-rescaling simultaneously\"\n # set rescale weight to 1./std of encodings\n print(\"### USING STD-RESCALING ###\")\n x = super().get_input(batch, self.first_stage_key)\n x = x.to(self.device)\n encoder_posterior = self.encode_first_stage(x)\n z = self.get_first_stage_encoding(encoder_posterior).detach()\n del self.scale_factor\n self.register_buffer(\"scale_factor\", 1.0 / z.flatten().std())\n print(f\"setting self.scale_factor to {self.scale_factor}\")\n print(\"### USING STD-RESCALING ###\")\n\n def register_schedule(\n self,\n given_betas=None,\n beta_schedule=\"linear\",\n timesteps=1000,\n linear_start=1e-4,\n linear_end=2e-2,\n cosine_s=8e-3,\n ):\n super().register_schedule(\n given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s\n )\n\n self.shorten_cond_schedule = self.num_timesteps_cond > 1\n if self.shorten_cond_schedule:\n self.make_cond_schedule()\n\n def instantiate_first_stage(self, config):\n model = instantiate_from_config(config)\n self.first_stage_model = model.eval()\n self.first_stage_model.train = disabled_train\n for param in self.first_stage_model.parameters():\n param.requires_grad = False\n\n def instantiate_cond_stage(self, config):\n if not self.cond_stage_trainable:\n if config == \"__is_first_stage__\":\n print(\"Using first stage also as cond stage.\")\n self.cond_stage_model = self.first_stage_model\n elif config == \"__is_unconditional__\":\n print(f\"Training {self.__class__.__name__} as an unconditional model.\")\n self.cond_stage_model = None\n # self.be_unconditional = True\n else:\n model = instantiate_from_config(config)\n self.cond_stage_model = model.eval()\n self.cond_stage_model.train = disabled_train\n for param in self.cond_stage_model.parameters():\n param.requires_grad = False\n else:\n assert config != \"__is_first_stage__\"\n assert config != \"__is_unconditional__\"\n model = instantiate_from_config(config)\n self.cond_stage_model = model\n\n def _get_denoise_row_from_list(\n self, samples, desc=\"\", force_no_decoder_quantization=False\n ):\n denoise_row = []\n for zd in tqdm(samples, desc=desc):\n denoise_row.append(\n self.decode_first_stage(\n zd.to(self.device), force_not_quantize=force_no_decoder_quantization\n )\n )\n n_imgs_per_row = len(denoise_row)\n denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W\n denoise_grid = rearrange(denoise_row, \"n b c h w -> b n c h w\")\n denoise_grid = rearrange(denoise_grid, \"b n c h w -> (b n) c h w\")\n denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)\n return denoise_grid\n\n def get_first_stage_encoding(self, encoder_posterior):\n if isinstance(encoder_posterior, DiagonalGaussianDistribution):\n z = encoder_posterior.sample()\n elif isinstance(encoder_posterior, torch.Tensor):\n z = encoder_posterior\n else:\n raise NotImplementedError(\n f\"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented\"\n )\n return self.scale_factor * z\n\n def get_learned_conditioning(self, c):\n if self.cond_stage_forward is None:\n if hasattr(self.cond_stage_model, \"encode\") and callable(\n self.cond_stage_model.encode\n ):\n c = self.cond_stage_model.encode(c)\n if isinstance(c, DiagonalGaussianDistribution):\n c = c.mode()\n else:\n c = self.cond_stage_model(c)\n else:\n assert hasattr(self.cond_stage_model, self.cond_stage_forward)\n c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)\n return c\n\n def meshgrid(self, h, w):\n y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)\n x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)\n\n arr = torch.cat([y, x], dim=-1)\n return arr\n\n def delta_border(self, h, w):\n \"\"\"\n :param h: height\n :param w: width\n :return: normalized distance to image border,\n wtith min distance = 0 at border and max dist = 0.5 at image center\n \"\"\"\n lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)\n arr = self.meshgrid(h, w) / lower_right_corner\n dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]\n dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]\n edge_dist = torch.min(\n torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1\n )[0]\n return edge_dist\n\n def get_weighting(self, h, w, Ly, Lx, device):\n weighting = self.delta_border(h, w)\n weighting = torch.clip(\n weighting,\n self.split_input_params[\"clip_min_weight\"],\n self.split_input_params[\"clip_max_weight\"],\n )\n weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)\n\n if self.split_input_params[\"tie_braker\"]:\n L_weighting = self.delta_border(Ly, Lx)\n L_weighting = torch.clip(\n L_weighting,\n self.split_input_params[\"clip_min_tie_weight\"],\n self.split_input_params[\"clip_max_tie_weight\"],\n )\n\n L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)\n weighting = weighting * L_weighting\n return weighting\n\n def get_fold_unfold(\n self, x, kernel_size, stride, uf=1, df=1\n ): # todo load once not every time, shorten code\n \"\"\"\n :param x: img of size (bs, c, h, w)\n :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])\n \"\"\"\n bs, nc, h, w = x.shape\n\n # number of crops in image\n Ly = (h - kernel_size[0]) // stride[0] + 1\n Lx = (w - kernel_size[1]) // stride[1] + 1\n\n if uf == 1 and df == 1:\n fold_params = dict(\n kernel_size=kernel_size, dilation=1, padding=0, stride=stride\n )\n unfold = torch.nn.Unfold(**fold_params)\n\n fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)\n\n weighting = self.get_weighting(\n kernel_size[0], kernel_size[1], Ly, Lx, x.device\n ).to(x.dtype)\n normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap\n weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))\n\n elif uf > 1 and df == 1:\n fold_params = dict(\n kernel_size=kernel_size, dilation=1, padding=0, stride=stride\n )\n unfold = torch.nn.Unfold(**fold_params)\n\n fold_params2 = dict(\n kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),\n dilation=1,\n padding=0,\n stride=(stride[0] * uf, stride[1] * uf),\n )\n fold = torch.nn.Fold(\n output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2\n )\n\n weighting = self.get_weighting(\n kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device\n ).to(x.dtype)\n normalization = fold(weighting).view(\n 1, 1, h * uf, w * uf\n ) # normalizes the overlap\n weighting = weighting.view(\n (1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx)\n )\n\n elif df > 1 and uf == 1:\n fold_params = dict(\n kernel_size=kernel_size, dilation=1, padding=0, stride=stride\n )\n unfold = torch.nn.Unfold(**fold_params)\n\n fold_params2 = dict(\n kernel_size=(kernel_size[0] // df, kernel_size[0] // df),\n dilation=1,\n padding=0,\n stride=(stride[0] // df, stride[1] // df),\n )\n fold = torch.nn.Fold(\n output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2\n )\n\n weighting = self.get_weighting(\n kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device\n ).to(x.dtype)\n normalization = fold(weighting).view(\n 1, 1, h // df, w // df\n ) # normalizes the overlap\n weighting = weighting.view(\n (1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx)\n )\n\n else:\n raise NotImplementedError\n\n return fold, unfold, normalization, weighting\n\n @torch.no_grad()\n def get_input(\n self,\n batch,\n k,\n return_first_stage_outputs=False,\n force_c_encode=False,\n cond_key=None,\n return_original_cond=False,\n bs=None,\n uncond=0.05,\n ):\n x = super().get_input(batch, k)\n T = batch[\"T\"].to(memory_format=torch.contiguous_format).float()\n\n if bs is not None:\n x = x[:bs]\n T = T[:bs].to(self.device)\n\n x = x.to(self.device)\n encoder_posterior = self.encode_first_stage(x)\n z = self.get_first_stage_encoding(encoder_posterior).detach()\n cond_key = cond_key or self.cond_stage_key\n xc = super().get_input(batch, cond_key).to(self.device)\n if bs is not None:\n xc = xc[:bs]\n cond = {}\n\n # To support classifier-free guidance, randomly drop out only text conditioning 5%, only image conditioning 5%, and both 5%.\n random = torch.rand(x.size(0), device=x.device)\n prompt_mask = rearrange(random < 2 * uncond, \"n -> n 1 1\")\n input_mask = 1 - rearrange(\n (random >= uncond).float() * (random < 3 * uncond).float(), \"n -> n 1 1 1\"\n )\n null_prompt = self.get_learned_conditioning([\"\"])\n\n # z.shape: [8, 4, 64, 64]; c.shape: [8, 1, 768]\n # print('=========== xc shape ===========', xc.shape)\n with torch.enable_grad():\n clip_emb = self.get_learned_conditioning(xc).detach()\n null_prompt = self.get_learned_conditioning([\"\"]).detach()\n cond[\"c_crossattn\"] = [\n self.cc_projection(\n torch.cat(\n [\n torch.where(prompt_mask, null_prompt, clip_emb),\n T[:, None, :],\n ],\n dim=-1,\n )\n )\n ]\n cond[\"c_concat\"] = [\n input_mask * self.encode_first_stage((xc.to(self.device))).mode().detach()\n ]\n out = [z, cond]\n if return_first_stage_outputs:\n xrec = self.decode_first_stage(z)\n out.extend([x, xrec])\n if return_original_cond:\n out.append(xc)\n return out\n\n # @torch.no_grad()\n def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):\n if predict_cids:\n if z.dim() == 4:\n z = torch.argmax(z.exp(), dim=1).long()\n z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)\n z = rearrange(z, \"b h w c -> b c h w\").contiguous()\n\n z = 1.0 / self.scale_factor * z\n\n if hasattr(self, \"split_input_params\"):\n if self.split_input_params[\"patch_distributed_vq\"]:\n ks = self.split_input_params[\"ks\"] # eg. (128, 128)\n stride = self.split_input_params[\"stride\"] # eg. (64, 64)\n uf = self.split_input_params[\"vqf\"]\n bs, nc, h, w = z.shape\n if ks[0] > h or ks[1] > w:\n ks = (min(ks[0], h), min(ks[1], w))\n print(\"reducing Kernel\")\n\n if stride[0] > h or stride[1] > w:\n stride = (min(stride[0], h), min(stride[1], w))\n print(\"reducing stride\")\n\n fold, unfold, normalization, weighting = self.get_fold_unfold(\n z, ks, stride, uf=uf\n )\n\n z = unfold(z) # (bn, nc * prod(**ks), L)\n # 1. Reshape to img shape\n z = z.view(\n (z.shape[0], -1, ks[0], ks[1], z.shape[-1])\n ) # (bn, nc, ks[0], ks[1], L )\n\n # 2. apply model loop over last dim\n if isinstance(self.first_stage_model, VQModelInterface):\n output_list = [\n self.first_stage_model.decode(\n z[:, :, :, :, i],\n force_not_quantize=predict_cids or force_not_quantize,\n )\n for i in range(z.shape[-1])\n ]\n else:\n output_list = [\n self.first_stage_model.decode(z[:, :, :, :, i])\n for i in range(z.shape[-1])\n ]\n\n o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)\n o = o * weighting\n # Reverse 1. reshape to img shape\n o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)\n # stitch crops together\n decoded = fold(o)\n decoded = decoded / normalization # norm is shape (1, 1, h, w)\n return decoded\n else:\n if isinstance(self.first_stage_model, VQModelInterface):\n return self.first_stage_model.decode(\n z, force_not_quantize=predict_cids or force_not_quantize\n )\n else:\n return self.first_stage_model.decode(z)\n\n else:\n if isinstance(self.first_stage_model, VQModelInterface):\n return self.first_stage_model.decode(\n z, force_not_quantize=predict_cids or force_not_quantize\n )\n else:\n return self.first_stage_model.decode(z)\n\n @torch.no_grad()\n def encode_first_stage(self, x):\n if hasattr(self, \"split_input_params\"):\n if self.split_input_params[\"patch_distributed_vq\"]:\n ks = self.split_input_params[\"ks\"] # eg. (128, 128)\n stride = self.split_input_params[\"stride\"] # eg. (64, 64)\n df = self.split_input_params[\"vqf\"]\n self.split_input_params[\"original_image_size\"] = x.shape[-2:]\n bs, nc, h, w = x.shape\n if ks[0] > h or ks[1] > w:\n ks = (min(ks[0], h), min(ks[1], w))\n print(\"reducing Kernel\")\n\n if stride[0] > h or stride[1] > w:\n stride = (min(stride[0], h), min(stride[1], w))\n print(\"reducing stride\")\n\n fold, unfold, normalization, weighting = self.get_fold_unfold(\n x, ks, stride, df=df\n )\n z = unfold(x) # (bn, nc * prod(**ks), L)\n # Reshape to img shape\n z = z.view(\n (z.shape[0], -1, ks[0], ks[1], z.shape[-1])\n ) # (bn, nc, ks[0], ks[1], L )\n\n output_list = [\n self.first_stage_model.encode(z[:, :, :, :, i])\n for i in range(z.shape[-1])\n ]\n\n o = torch.stack(output_list, axis=-1)\n o = o * weighting\n\n # Reverse reshape to img shape\n o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)\n # stitch crops together\n decoded = fold(o)\n decoded = decoded / normalization\n return decoded\n\n else:\n return self.first_stage_model.encode(x)\n else:\n return self.first_stage_model.encode(x)\n\n def shared_step(self, batch, step_ratio=None, **kwargs):\n x, c = self.get_input(batch, self.first_stage_key)\n loss = self(x, c, step_ratio=step_ratio)\n return loss\n\n def forward(self, x, c, step_ratio=None, *args, **kwargs):\n if step_ratio is not None:\n t = np.round((1 - step_ratio) * self.num_timesteps).clip(0, self.num_timesteps - 1)\n t = torch.full((x.shape[0],), t, dtype=torch.long, device=self.device)\n else:\n t = torch.randint(\n 0, self.num_timesteps, (x.shape[0],), device=self.device\n ).long()\n if self.model.conditioning_key is not None:\n assert c is not None\n # if self.cond_stage_trainable:\n # c = self.get_learned_conditioning(c)\n if self.shorten_cond_schedule: # TODO: drop this option\n tc = self.cond_ids[t].to(self.device)\n c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))\n return self.p_losses(x, c, t, *args, **kwargs)\n\n def _rescale_annotations(self, bboxes, crop_coordinates): # TODO: move to dataset\n def rescale_bbox(bbox):\n x0 = clamp((bbox[0] - crop_coordinates[0]) / crop_coordinates[2])\n y0 = clamp((bbox[1] - crop_coordinates[1]) / crop_coordinates[3])\n w = min(bbox[2] / crop_coordinates[2], 1 - x0)\n h = min(bbox[3] / crop_coordinates[3], 1 - y0)\n return x0, y0, w, h\n\n return [rescale_bbox(b) for b in bboxes]\n\n def apply_model(self, x_noisy, t, cond, return_ids=False):\n if isinstance(cond, dict):\n # hybrid case, cond is exptected to be a dict\n pass\n else:\n if not isinstance(cond, list):\n cond = [cond]\n key = (\n \"c_concat\" if self.model.conditioning_key == \"concat\" else \"c_crossattn\"\n )\n cond = {key: cond}\n\n if hasattr(self, \"split_input_params\"):\n assert len(cond) == 1 # todo can only deal with one conditioning atm\n assert not return_ids\n ks = self.split_input_params[\"ks\"] # eg. (128, 128)\n stride = self.split_input_params[\"stride\"] # eg. (64, 64)\n\n h, w = x_noisy.shape[-2:]\n\n fold, unfold, normalization, weighting = self.get_fold_unfold(\n x_noisy, ks, stride\n )\n\n z = unfold(x_noisy) # (bn, nc * prod(**ks), L)\n # Reshape to img shape\n z = z.view(\n (z.shape[0], -1, ks[0], ks[1], z.shape[-1])\n ) # (bn, nc, ks[0], ks[1], L )\n z_list = [z[:, :, :, :, i] for i in range(z.shape[-1])]\n\n if (\n self.cond_stage_key in [\"image\", \"LR_image\", \"segmentation\", \"bbox_img\"]\n and self.model.conditioning_key\n ): # todo check for completeness\n c_key = next(iter(cond.keys())) # get key\n c = next(iter(cond.values())) # get value\n assert len(c) == 1 # todo extend to list with more than one elem\n c = c[0] # get element\n\n c = unfold(c)\n c = c.view(\n (c.shape[0], -1, ks[0], ks[1], c.shape[-1])\n ) # (bn, nc, ks[0], ks[1], L )\n\n cond_list = [{c_key: [c[:, :, :, :, i]]} for i in range(c.shape[-1])]\n\n elif self.cond_stage_key == \"coordinates_bbox\":\n assert (\n \"original_image_size\" in self.split_input_params\n ), \"BoudingBoxRescaling is missing original_image_size\"\n\n # assuming padding of unfold is always 0 and its dilation is always 1\n n_patches_per_row = int((w - ks[0]) / stride[0] + 1)\n full_img_h, full_img_w = self.split_input_params[\"original_image_size\"]\n # as we are operating on latents, we need the factor from the original image size to the\n # spatial latent size to properly rescale the crops for regenerating the bbox annotations\n num_downs = self.first_stage_model.encoder.num_resolutions - 1\n rescale_latent = 2 ** (num_downs)\n\n # get top left postions of patches as conforming for the bbbox tokenizer, therefore we\n # need to rescale the tl patch coordinates to be in between (0,1)\n tl_patch_coordinates = [\n (\n rescale_latent\n * stride[0]\n * (patch_nr % n_patches_per_row)\n / full_img_w,\n rescale_latent\n * stride[1]\n * (patch_nr // n_patches_per_row)\n / full_img_h,\n )\n for patch_nr in range(z.shape[-1])\n ]\n\n # patch_limits are tl_coord, width and height coordinates as (x_tl, y_tl, h, w)\n patch_limits = [\n (\n x_tl,\n y_tl,\n rescale_latent * ks[0] / full_img_w,\n rescale_latent * ks[1] / full_img_h,\n )\n for x_tl, y_tl in tl_patch_coordinates\n ]\n # patch_values = [(np.arange(x_tl,min(x_tl+ks, 1.)),np.arange(y_tl,min(y_tl+ks, 1.))) for x_tl, y_tl in tl_patch_coordinates]\n\n # tokenize crop coordinates for the bounding boxes of the respective patches\n patch_limits_tknzd = [\n torch.LongTensor(self.bbox_tokenizer._crop_encoder(bbox))[None].to(\n self.device\n )\n for bbox in patch_limits\n ] # list of length l with tensors of shape (1, 2)\n # cut tknzd crop position from conditioning\n assert isinstance(cond, dict), \"cond must be dict to be fed into model\"\n cut_cond = cond[\"c_crossattn\"][0][..., :-2].to(self.device)\n\n adapted_cond = torch.stack(\n [torch.cat([cut_cond, p], dim=1) for p in patch_limits_tknzd]\n )\n adapted_cond = rearrange(adapted_cond, \"l b n -> (l b) n\")\n adapted_cond = self.get_learned_conditioning(adapted_cond)\n adapted_cond = rearrange(\n adapted_cond, \"(l b) n d -> l b n d\", l=z.shape[-1]\n )\n\n cond_list = [{\"c_crossattn\": [e]} for e in adapted_cond]\n\n else:\n cond_list = [\n cond for i in range(z.shape[-1])\n ] # Todo make this more efficient\n\n # apply model by loop over crops\n output_list = [\n self.model(z_list[i], t, **cond_list[i]) for i in range(z.shape[-1])\n ]\n assert not isinstance(\n output_list[0], tuple\n ) # todo cant deal with multiple model outputs check this never happens\n\n o = torch.stack(output_list, axis=-1)\n o = o * weighting\n # Reverse reshape to img shape\n o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)\n # stitch crops together\n x_recon = fold(o) / normalization\n\n else:\n x_recon = self.model(x_noisy, t, **cond)\n\n if isinstance(x_recon, tuple) and not return_ids:\n return x_recon[0]\n else:\n return x_recon\n\n def _predict_eps_from_xstart(self, x_t, t, pred_xstart):\n return (\n extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t\n - pred_xstart\n ) / extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)\n\n def _prior_bpd(self, x_start):\n \"\"\"\n Get the prior KL term for the variational lower-bound, measured in\n bits-per-dim.\n This term can't be optimized, as it only depends on the encoder.\n :param x_start: the [N x C x ...] tensor of inputs.\n :return: a batch of [N] KL values (in bits), one per batch element.\n \"\"\"\n batch_size = x_start.shape[0]\n t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)\n qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)\n kl_prior = normal_kl(\n mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0\n )\n return mean_flat(kl_prior) / np.log(2.0)\n\n def p_losses(self, x_start, cond, t, noise=None):\n noise = default(noise, lambda: torch.randn_like(x_start))\n x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)\n model_output = self.apply_model(x_noisy, t, cond)\n\n loss_dict = {}\n prefix = \"train\" if self.training else \"val\"\n\n if self.parameterization == \"x0\":\n target = x_start\n elif self.parameterization == \"eps\":\n target = noise\n else:\n raise NotImplementedError()\n\n loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])\n loss_dict.update({f\"{prefix}/loss_simple\": loss_simple.mean()})\n\n if self.logvar.device != self.device:\n self.logvar = self.logvar.to(self.device)\n\n logvar_t = self.logvar[t].to(self.device)\n loss = loss_simple / torch.exp(logvar_t) + logvar_t\n # loss = loss_simple / torch.exp(self.logvar) + self.logvar\n if self.learn_logvar:\n loss_dict.update({f\"{prefix}/loss_gamma\": loss.mean()})\n loss_dict.update({\"logvar\": self.logvar.data.mean()})\n\n loss = self.l_simple_weight * loss.mean()\n\n loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))\n loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()\n loss_dict.update({f\"{prefix}/loss_vlb\": loss_vlb})\n loss += self.original_elbo_weight * loss_vlb\n loss_dict.update({f\"{prefix}/loss\": loss})\n\n return loss, loss_dict\n\n def p_mean_variance(\n self,\n x,\n c,\n t,\n clip_denoised: bool,\n return_codebook_ids=False,\n quantize_denoised=False,\n return_x0=False,\n score_corrector=None,\n corrector_kwargs=None,\n ):\n t_in = t\n model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)\n\n if score_corrector is not None:\n assert self.parameterization == \"eps\"\n model_out = score_corrector.modify_score(\n self, model_out, x, t, c, **corrector_kwargs\n )\n\n if return_codebook_ids:\n model_out, logits = model_out\n\n if self.parameterization == \"eps\":\n x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)\n elif self.parameterization == \"x0\":\n x_recon = model_out\n else:\n raise NotImplementedError()\n\n if clip_denoised:\n x_recon.clamp_(-1.0, 1.0)\n if quantize_denoised:\n x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)\n model_mean, posterior_variance, posterior_log_variance = self.q_posterior(\n x_start=x_recon, x_t=x, t=t\n )\n if return_codebook_ids:\n return model_mean, posterior_variance, posterior_log_variance, logits\n elif return_x0:\n return model_mean, posterior_variance, posterior_log_variance, x_recon\n else:\n return model_mean, posterior_variance, posterior_log_variance\n\n @torch.no_grad()\n def p_sample(\n self,\n x,\n c,\n t,\n clip_denoised=False,\n repeat_noise=False,\n return_codebook_ids=False,\n quantize_denoised=False,\n return_x0=False,\n temperature=1.0,\n noise_dropout=0.0,\n score_corrector=None,\n corrector_kwargs=None,\n ):\n b, *_, device = *x.shape, x.device\n outputs = self.p_mean_variance(\n x=x,\n c=c,\n t=t,\n clip_denoised=clip_denoised,\n return_codebook_ids=return_codebook_ids,\n quantize_denoised=quantize_denoised,\n return_x0=return_x0,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n )\n if return_codebook_ids:\n raise DeprecationWarning(\"Support dropped.\")\n model_mean, _, model_log_variance, logits = outputs\n elif return_x0:\n model_mean, _, model_log_variance, x0 = outputs\n else:\n model_mean, _, model_log_variance = outputs\n\n noise = noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.0:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n # no noise when t == 0\n nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))\n\n if return_codebook_ids:\n return model_mean + nonzero_mask * (\n 0.5 * model_log_variance\n ).exp() * noise, logits.argmax(dim=1)\n if return_x0:\n return (\n model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise,\n x0,\n )\n else:\n return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise\n\n @torch.no_grad()\n def progressive_denoising(\n self,\n cond,\n shape,\n verbose=True,\n callback=None,\n quantize_denoised=False,\n img_callback=None,\n mask=None,\n x0=None,\n temperature=1.0,\n noise_dropout=0.0,\n score_corrector=None,\n corrector_kwargs=None,\n batch_size=None,\n x_T=None,\n start_T=None,\n log_every_t=None,\n ):\n if not log_every_t:\n log_every_t = self.log_every_t\n timesteps = self.num_timesteps\n if batch_size is not None:\n b = batch_size if batch_size is not None else shape[0]\n shape = [batch_size] + list(shape)\n else:\n b = batch_size = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=self.device)\n else:\n img = x_T\n intermediates = []\n if cond is not None:\n if isinstance(cond, dict):\n cond = {\n key: cond[key][:batch_size]\n if not isinstance(cond[key], list)\n else list(map(lambda x: x[:batch_size], cond[key]))\n for key in cond\n }\n else:\n cond = (\n [c[:batch_size] for c in cond]\n if isinstance(cond, list)\n else cond[:batch_size]\n )\n\n if start_T is not None:\n timesteps = min(timesteps, start_T)\n iterator = (\n tqdm(\n reversed(range(0, timesteps)),\n desc=\"Progressive Generation\",\n total=timesteps,\n )\n if verbose\n else reversed(range(0, timesteps))\n )\n if type(temperature) == float:\n temperature = [temperature] * timesteps\n\n for i in iterator:\n ts = torch.full((b,), i, device=self.device, dtype=torch.long)\n if self.shorten_cond_schedule:\n assert self.model.conditioning_key != \"hybrid\"\n tc = self.cond_ids[ts].to(cond.device)\n cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))\n\n img, x0_partial = self.p_sample(\n img,\n cond,\n ts,\n clip_denoised=self.clip_denoised,\n quantize_denoised=quantize_denoised,\n return_x0=True,\n temperature=temperature[i],\n noise_dropout=noise_dropout,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n )\n if mask is not None:\n assert x0 is not None\n img_orig = self.q_sample(x0, ts)\n img = img_orig * mask + (1.0 - mask) * img\n\n if i % log_every_t == 0 or i == timesteps - 1:\n intermediates.append(x0_partial)\n if callback:\n callback(i)\n if img_callback:\n img_callback(img, i)\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_loop(\n self,\n cond,\n shape,\n return_intermediates=False,\n x_T=None,\n verbose=True,\n callback=None,\n timesteps=None,\n quantize_denoised=False,\n mask=None,\n x0=None,\n img_callback=None,\n start_T=None,\n log_every_t=None,\n ):\n if not log_every_t:\n log_every_t = self.log_every_t\n device = self.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n intermediates = [img]\n if timesteps is None:\n timesteps = self.num_timesteps\n\n if start_T is not None:\n timesteps = min(timesteps, start_T)\n iterator = (\n tqdm(reversed(range(0, timesteps)), desc=\"Sampling t\", total=timesteps)\n if verbose\n else reversed(range(0, timesteps))\n )\n\n if mask is not None:\n assert x0 is not None\n assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match\n\n for i in iterator:\n ts = torch.full((b,), i, device=device, dtype=torch.long)\n if self.shorten_cond_schedule:\n assert self.model.conditioning_key != \"hybrid\"\n tc = self.cond_ids[ts].to(cond.device)\n cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))\n\n img = self.p_sample(\n img,\n cond,\n ts,\n clip_denoised=self.clip_denoised,\n quantize_denoised=quantize_denoised,\n )\n if mask is not None:\n img_orig = self.q_sample(x0, ts)\n img = img_orig * mask + (1.0 - mask) * img\n\n if i % log_every_t == 0 or i == timesteps - 1:\n intermediates.append(img)\n if callback:\n callback(i)\n if img_callback:\n img_callback(img, i)\n\n if return_intermediates:\n return img, intermediates\n return img\n\n @torch.no_grad()\n def sample(\n self,\n cond,\n batch_size=16,\n return_intermediates=False,\n x_T=None,\n verbose=True,\n timesteps=None,\n quantize_denoised=False,\n mask=None,\n x0=None,\n shape=None,\n **kwargs,\n ):\n if shape is None:\n shape = (batch_size, self.channels, self.image_size, self.image_size)\n if cond is not None:\n if isinstance(cond, dict):\n cond = {\n key: cond[key][:batch_size]\n if not isinstance(cond[key], list)\n else list(map(lambda x: x[:batch_size], cond[key]))\n for key in cond\n }\n else:\n cond = (\n [c[:batch_size] for c in cond]\n if isinstance(cond, list)\n else cond[:batch_size]\n )\n return self.p_sample_loop(\n cond,\n shape,\n return_intermediates=return_intermediates,\n x_T=x_T,\n verbose=verbose,\n timesteps=timesteps,\n quantize_denoised=quantize_denoised,\n mask=mask,\n x0=x0,\n )\n\n @torch.no_grad()\n def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):\n if ddim:\n ddim_sampler = DDIMSampler(self)\n shape = (self.channels, self.image_size, self.image_size)\n samples, intermediates = ddim_sampler.sample(\n ddim_steps, batch_size, shape, cond, verbose=False, **kwargs\n )\n\n else:\n samples, intermediates = self.sample(\n cond=cond, batch_size=batch_size, return_intermediates=True, **kwargs\n )\n\n return samples, intermediates\n\n @torch.no_grad()\n def get_unconditional_conditioning(\n self, batch_size, null_label=None, image_size=512\n ):\n if null_label is not None:\n xc = null_label\n if isinstance(xc, ListConfig):\n xc = list(xc)\n if isinstance(xc, dict) or isinstance(xc, list):\n c = self.get_learned_conditioning(xc)\n else:\n if hasattr(xc, \"to\"):\n xc = xc.to(self.device)\n c = self.get_learned_conditioning(xc)\n else:\n # todo: get null label from cond_stage_model\n raise NotImplementedError()\n c = repeat(c, \"1 ... -> b ...\", b=batch_size).to(self.device)\n cond = {}\n cond[\"c_crossattn\"] = [c]\n cond[\"c_concat\"] = [\n torch.zeros([batch_size, 4, image_size // 8, image_size // 8]).to(\n self.device\n )\n ]\n return cond\n\n @torch.no_grad()\n def log_images(\n self,\n batch,\n N=8,\n n_row=4,\n sample=True,\n ddim_steps=200,\n ddim_eta=1.0,\n return_keys=None,\n quantize_denoised=True,\n inpaint=True,\n plot_denoise_rows=False,\n plot_progressive_rows=True,\n plot_diffusion_rows=True,\n unconditional_guidance_scale=1.0,\n unconditional_guidance_label=None,\n use_ema_scope=True,\n **kwargs,\n ):\n ema_scope = self.ema_scope if use_ema_scope else nullcontext\n use_ddim = ddim_steps is not None\n\n log = dict()\n z, c, x, xrec, xc = self.get_input(\n batch,\n self.first_stage_key,\n return_first_stage_outputs=True,\n force_c_encode=True,\n return_original_cond=True,\n bs=N,\n )\n N = min(x.shape[0], N)\n n_row = min(x.shape[0], n_row)\n log[\"inputs\"] = x\n log[\"reconstruction\"] = xrec\n if self.model.conditioning_key is not None:\n if hasattr(self.cond_stage_model, \"decode\"):\n xc = self.cond_stage_model.decode(c)\n log[\"conditioning\"] = xc\n elif self.cond_stage_key in [\"caption\", \"txt\"]:\n xc = log_txt_as_img(\n (x.shape[2], x.shape[3]),\n batch[self.cond_stage_key],\n size=x.shape[2] // 25,\n )\n log[\"conditioning\"] = xc\n elif self.cond_stage_key == \"class_label\":\n xc = log_txt_as_img(\n (x.shape[2], x.shape[3]),\n batch[\"human_label\"],\n size=x.shape[2] // 25,\n )\n log[\"conditioning\"] = xc\n elif isimage(xc):\n log[\"conditioning\"] = xc\n if ismap(xc):\n log[\"original_conditioning\"] = self.to_rgb(xc)\n\n if plot_diffusion_rows:\n # get diffusion row\n diffusion_row = list()\n z_start = z[:n_row]\n for t in range(self.num_timesteps):\n if t % self.log_every_t == 0 or t == self.num_timesteps - 1:\n t = repeat(torch.tensor([t]), \"1 -> b\", b=n_row)\n t = t.to(self.device).long()\n noise = torch.randn_like(z_start)\n z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)\n diffusion_row.append(self.decode_first_stage(z_noisy))\n\n diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W\n diffusion_grid = rearrange(diffusion_row, \"n b c h w -> b n c h w\")\n diffusion_grid = rearrange(diffusion_grid, \"b n c h w -> (b n) c h w\")\n diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])\n log[\"diffusion_row\"] = diffusion_grid\n\n if sample:\n # get denoise row\n with ema_scope(\"Sampling\"):\n samples, z_denoise_row = self.sample_log(\n cond=c,\n batch_size=N,\n ddim=use_ddim,\n ddim_steps=ddim_steps,\n eta=ddim_eta,\n )\n # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)\n x_samples = self.decode_first_stage(samples)\n log[\"samples\"] = x_samples\n if plot_denoise_rows:\n denoise_grid = self._get_denoise_row_from_list(z_denoise_row)\n log[\"denoise_row\"] = denoise_grid\n\n if (\n quantize_denoised\n and not isinstance(self.first_stage_model, AutoencoderKL)\n and not isinstance(self.first_stage_model, IdentityFirstStage)\n ):\n # also display when quantizing x0 while sampling\n with ema_scope(\"Plotting Quantized Denoised\"):\n samples, z_denoise_row = self.sample_log(\n cond=c,\n batch_size=N,\n ddim=use_ddim,\n ddim_steps=ddim_steps,\n eta=ddim_eta,\n quantize_denoised=True,\n )\n # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,\n # quantize_denoised=True)\n x_samples = self.decode_first_stage(samples.to(self.device))\n log[\"samples_x0_quantized\"] = x_samples\n\n if unconditional_guidance_scale > 1.0:\n uc = self.get_unconditional_conditioning(\n N, unconditional_guidance_label, image_size=x.shape[-1]\n )\n # uc = torch.zeros_like(c)\n with ema_scope(\"Sampling with classifier-free guidance\"):\n samples_cfg, _ = self.sample_log(\n cond=c,\n batch_size=N,\n ddim=use_ddim,\n ddim_steps=ddim_steps,\n eta=ddim_eta,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=uc,\n )\n x_samples_cfg = self.decode_first_stage(samples_cfg)\n log[\n f\"samples_cfg_scale_{unconditional_guidance_scale:.2f}\"\n ] = x_samples_cfg\n\n if inpaint:\n # make a simple center square\n b, h, w = z.shape[0], z.shape[2], z.shape[3]\n mask = torch.ones(N, h, w).to(self.device)\n # zeros will be filled in\n mask[:, h // 4 : 3 * h // 4, w // 4 : 3 * w // 4] = 0.0\n mask = mask[:, None, ...]\n with ema_scope(\"Plotting Inpaint\"):\n samples, _ = self.sample_log(\n cond=c,\n batch_size=N,\n ddim=use_ddim,\n eta=ddim_eta,\n ddim_steps=ddim_steps,\n x0=z[:N],\n mask=mask,\n )\n x_samples = self.decode_first_stage(samples.to(self.device))\n log[\"samples_inpainting\"] = x_samples\n log[\"mask\"] = mask\n\n # outpaint\n mask = 1.0 - mask\n with ema_scope(\"Plotting Outpaint\"):\n samples, _ = self.sample_log(\n cond=c,\n batch_size=N,\n ddim=use_ddim,\n eta=ddim_eta,\n ddim_steps=ddim_steps,\n x0=z[:N],\n mask=mask,\n )\n x_samples = self.decode_first_stage(samples.to(self.device))\n log[\"samples_outpainting\"] = x_samples\n\n if plot_progressive_rows:\n with ema_scope(\"Plotting Progressives\"):\n img, progressives = self.progressive_denoising(\n c,\n shape=(self.channels, self.image_size, self.image_size),\n batch_size=N,\n )\n prog_row = self._get_denoise_row_from_list(\n progressives, desc=\"Progressive Generation\"\n )\n log[\"progressive_row\"] = prog_row\n\n if return_keys:\n if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:\n return log\n else:\n return {key: log[key] for key in return_keys}\n return log\n\n def configure_optimizers(self):\n lr = self.learning_rate\n params = []\n if self.unet_trainable == \"attn\":\n print(\"Training only unet attention layers\")\n for n, m in self.model.named_modules():\n if isinstance(m, CrossAttention) and n.endswith(\"attn2\"):\n params.extend(m.parameters())\n if self.unet_trainable == \"conv_in\":\n print(\"Training only unet input conv layers\")\n params = list(self.model.diffusion_model.input_blocks[0][0].parameters())\n elif self.unet_trainable is True or self.unet_trainable == \"all\":\n print(\"Training the full unet\")\n params = list(self.model.parameters())\n else:\n raise ValueError(\n f\"Unrecognised setting for unet_trainable: {self.unet_trainable}\"\n )\n\n if self.cond_stage_trainable:\n print(f\"{self.__class__.__name__}: Also optimizing conditioner params!\")\n params = params + list(self.cond_stage_model.parameters())\n if self.learn_logvar:\n print(\"Diffusion model optimizing logvar\")\n params.append(self.logvar)\n\n if self.cc_projection is not None:\n params = params + list(self.cc_projection.parameters())\n print(\"========== optimizing for cc projection weight ==========\")\n\n opt = torch.optim.AdamW(\n [\n {\"params\": self.model.parameters(), \"lr\": lr},\n {\"params\": self.cc_projection.parameters(), \"lr\": 10.0 * lr},\n ],\n lr=lr,\n )\n if self.use_scheduler:\n assert \"target\" in self.scheduler_config\n scheduler = instantiate_from_config(self.scheduler_config)\n\n print(\"Setting up LambdaLR scheduler...\")\n scheduler = [\n {\n \"scheduler\": LambdaLR(opt, lr_lambda=scheduler.schedule),\n \"interval\": \"step\",\n \"frequency\": 1,\n }\n ]\n return [opt], scheduler\n return opt\n\n @torch.no_grad()\n def to_rgb(self, x):\n x = x.float()\n if not hasattr(self, \"colorize\"):\n self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)\n x = nn.functional.conv2d(x, weight=self.colorize)\n x = 2.0 * (x - x.min()) / (x.max() - x.min()) - 1.0\n return x" }, { "identifier": "load_model_from_config", "path": "ldm/util.py", "snippet": "def load_model_from_config(config, ckpt, device, vram_O=False, verbose=False):\n print(f\"[INFO] Loading model from {ckpt}\")\n pl_sd = torch.load(ckpt, map_location=\"cpu\")\n\n if \"global_step\" in pl_sd and verbose:\n print(f'[INFO] Global Step: {pl_sd[\"global_step\"]}')\n\n sd = pl_sd[\"state_dict\"]\n\n model = instantiate_from_config(config.model)\n m, u = model.load_state_dict(sd, strict=False)\n\n if len(m) > 0 and verbose:\n print(\"[INFO] Missing keys: \\n\", m)\n if len(u) > 0 and verbose:\n print(\"[INFO] Unexpected keys: \\n\", u)\n\n # manually load ema and delete it to save GPU memory\n if model.use_ema:\n if verbose:\n print(\"[INFO] Loading EMA\")\n model.model_ema.copy_to(model.model)\n del model.model_ema\n\n if vram_O:\n # we don't need decoder\n del model.first_stage_model.decoder\n\n torch.cuda.empty_cache()\n model.eval().to(device)\n\n return model" }, { "identifier": "make_T", "path": "util/pose.py", "snippet": "def make_T(theta, azimuth, distance, in_deg=False):\n if in_deg:\n theta, azimuth = theta.deg2rad(), azimuth.deg2rad()\n return torch.stack(\n (\n theta,\n torch.sin(azimuth),\n torch.cos(azimuth),\n distance,\n )\n )" }, { "identifier": "default", "path": "util/util.py", "snippet": "def default(val, d):\n if exists(val):\n return val\n return d() if isfunction(d) else d" } ]
import itertools import torch import torch.nn as nn from dataclasses import dataclass from diffusers import DDIMScheduler from einops import rearrange from omegaconf import OmegaConf from ldm.lora import ( inject_trainable_lora_extended, monkeypatch_remove_lora, save_lora_weight, ) from ldm.models.diffusion.ddpm import LatentDiffusion from ldm.util import load_model_from_config from util.pose import make_T from util.typing import * from util.util import default
14,862
class Zero123(nn.Module): @dataclass class Config: pretrained_model_name_or_path: str = "ldm/ckpt/zero123-xl.ckpt" pretrained_config: str = "ldm/ckpt/sd-objaverse-finetune-c_concat-256.yaml" vram_O: bool = False min_step_percent: float = 0.02 max_step_percent: float = 0.98 config: Config def __init__(self, **kwargs) -> None: super().__init__() self.config = OmegaConf.structured(self.Config(**kwargs)) self.device = "cuda" self.require_grad_params = [] self.configure() def configure(self) -> None: print("[INFO] Loading Zero123...") self.pretrained_config = OmegaConf.load(self.config.pretrained_config) self.weights_dtype = torch.float32
class Zero123(nn.Module): @dataclass class Config: pretrained_model_name_or_path: str = "ldm/ckpt/zero123-xl.ckpt" pretrained_config: str = "ldm/ckpt/sd-objaverse-finetune-c_concat-256.yaml" vram_O: bool = False min_step_percent: float = 0.02 max_step_percent: float = 0.98 config: Config def __init__(self, **kwargs) -> None: super().__init__() self.config = OmegaConf.structured(self.Config(**kwargs)) self.device = "cuda" self.require_grad_params = [] self.configure() def configure(self) -> None: print("[INFO] Loading Zero123...") self.pretrained_config = OmegaConf.load(self.config.pretrained_config) self.weights_dtype = torch.float32
self.model: LatentDiffusion = load_model_from_config(
4
2023-12-17 12:45:38+00:00
24k
penghao-wu/vstar
VisualSearch/utils/dataset.py
[ { "identifier": "conversation", "path": "VisualSearch/model/llava/conversation.py", "snippet": "class SeparatorStyle(Enum):\nclass Conversation:\n SINGLE = auto()\n TWO = auto()\n MPT = auto()\n PLAIN = auto()\n LLAMA_2 = auto()\n W, H = image.size\n H, W = longest_edge, shortest_edge\n H, W = shortest_edge, longest_edge\n W, H = image.size\n H, W = longest_edge, shortest_edge\n H, W = shortest_edge, longest_edge\n def get_prompt(self):\n def append_message(self, role, message):\n def get_images(self, return_pil=False):\n def expand2square(pil_img, background_color=(122, 116, 104)):\n def to_gradio_chatbot(self):\n def copy(self):\n def dict(self):" }, { "identifier": "DEFAULT_IMAGE_TOKEN", "path": "VisualSearch/model/llava/constants.py", "snippet": "DEFAULT_IMAGE_TOKEN = \"<image>\"" }, { "identifier": "IGNORE_INDEX", "path": "VisualSearch/model/llava/constants.py", "snippet": "IGNORE_INDEX = -100" }, { "identifier": "IMAGE_TOKEN_INDEX", "path": "VisualSearch/model/llava/constants.py", "snippet": "IMAGE_TOKEN_INDEX = -200" }, { "identifier": "tokenizer_image_token", "path": "VisualSearch/model/llava/mm_utils.py", "snippet": "def tokenizer_image_token(\n prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None\n):\n prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split(\"<image>\")]\n\n def insert_separator(X, sep):\n return [ele for sublist in zip(X, [sep] * len(X)) for ele in sublist][:-1]\n\n input_ids = []\n offset = 0\n if (\n len(prompt_chunks) > 0\n and len(prompt_chunks[0]) > 0\n and prompt_chunks[0][0] == tokenizer.bos_token_id\n ):\n offset = 1\n input_ids.append(prompt_chunks[0][0])\n\n for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):\n input_ids.extend(x[offset:])\n\n if return_tensors is not None:\n if return_tensors == \"pt\":\n return torch.tensor(input_ids, dtype=torch.long)\n raise ValueError(f\"Unsupported tensor type: {return_tensors}\")\n return input_ids" }, { "identifier": "get_mask_from_json", "path": "VisualSearch/utils/data_processing.py", "snippet": "def get_mask_from_json(json_path, img):\n try:\n with open(json_path, \"r\") as r:\n anno = json.loads(r.read())\n except:\n with open(json_path, \"r\", encoding=\"cp1252\") as r:\n anno = json.loads(r.read())\n\n inform = anno[\"shapes\"]\n comments = anno[\"text\"]\n is_sentence = anno[\"is_sentence\"]\n\n height, width = img.shape[:2]\n\n ### sort polies by area\n area_list = []\n valid_poly_list = []\n for i in inform:\n label_id = i[\"label\"]\n points = i[\"points\"]\n if \"flag\" == label_id.lower(): ## meaningless deprecated annotations\n continue\n\n tmp_mask = np.zeros((height, width), dtype=np.uint8)\n cv2.polylines(tmp_mask, np.array([points], dtype=np.int32), True, 1, 1)\n cv2.fillPoly(tmp_mask, np.array([points], dtype=np.int32), 1)\n tmp_area = tmp_mask.sum()\n\n area_list.append(tmp_area)\n valid_poly_list.append(i)\n\n ### ground-truth mask\n sort_index = np.argsort(area_list)[::-1].astype(np.int32)\n sort_index = list(sort_index)\n sort_inform = []\n for s_idx in sort_index:\n sort_inform.append(valid_poly_list[s_idx])\n\n mask = np.zeros((height, width), dtype=np.uint8)\n for i in sort_inform:\n label_id = i[\"label\"]\n points = i[\"points\"]\n\n if \"ignore\" in label_id.lower():\n label_value = 255 # ignored during evaluation\n else:\n label_value = 1 # target\n\n cv2.polylines(mask, np.array([points], dtype=np.int32), True, label_value, 1)\n cv2.fillPoly(mask, np.array([points], dtype=np.int32), label_value)\n\n return mask, comments, is_sentence" }, { "identifier": "REFER", "path": "VisualSearch/utils/refer.py", "snippet": "class REFER:\n def __init__(self, data_root, dataset=\"refcoco\", splitBy=\"unc\"):\n # provide data_root folder which contains refclef, refcoco, refcoco+ and refcocog\n # also provide dataset name and splitBy information\n # e.g., dataset = 'refcoco', splitBy = 'unc'\n print(\"loading dataset %s into memory...\" % dataset)\n self.ROOT_DIR = osp.abspath(osp.dirname(__file__))\n self.DATA_DIR = osp.join(data_root, dataset)\n if dataset in [\"refcoco\", \"refcoco+\", \"refcocog\"]:\n self.IMAGE_DIR = osp.join(data_root, \"images/mscoco/images/train2014\")\n elif dataset == \"refclef\":\n self.IMAGE_DIR = osp.join(data_root, \"images/saiapr_tc-12\")\n else:\n print(\"No refer dataset is called [%s]\" % dataset)\n sys.exit()\n\n self.dataset = dataset\n\n # load refs from data/dataset/refs(dataset).json\n tic = time.time()\n\n ref_file = osp.join(self.DATA_DIR, \"refs(\" + splitBy + \").p\")\n print(\"ref_file: \", ref_file)\n self.data = {}\n self.data[\"dataset\"] = dataset\n self.data[\"refs\"] = pickle.load(open(ref_file, \"rb\"))\n\n # load annotations from data/dataset/instances.json\n instances_file = osp.join(self.DATA_DIR, \"instances.json\")\n instances = json.load(open(instances_file, \"rb\"))\n self.data[\"images\"] = instances[\"images\"]\n self.data[\"annotations\"] = instances[\"annotations\"]\n self.data[\"categories\"] = instances[\"categories\"]\n\n # create index\n self.createIndex()\n print(\"DONE (t=%.2fs)\" % (time.time() - tic))\n\n def createIndex(self):\n # create sets of mapping\n # 1) Refs: \t \t{ref_id: ref}\n # 2) Anns: \t \t{ann_id: ann}\n # 3) Imgs:\t\t \t{image_id: image}\n # 4) Cats: \t \t{category_id: category_name}\n # 5) Sents: \t{sent_id: sent}\n # 6) imgToRefs: \t{image_id: refs}\n # 7) imgToAnns: \t{image_id: anns}\n # 8) refToAnn: \t{ref_id: ann}\n # 9) annToRef: \t{ann_id: ref}\n # 10) catToRefs: \t{category_id: refs}\n # 11) sentToRef: \t{sent_id: ref}\n # 12) sentToTokens: {sent_id: tokens}\n print(\"creating index...\")\n # fetch info from instances\n Anns, Imgs, Cats, imgToAnns = {}, {}, {}, {}\n for ann in self.data[\"annotations\"]:\n Anns[ann[\"id\"]] = ann\n imgToAnns[ann[\"image_id\"]] = imgToAnns.get(ann[\"image_id\"], []) + [ann]\n for img in self.data[\"images\"]:\n Imgs[img[\"id\"]] = img\n for cat in self.data[\"categories\"]:\n Cats[cat[\"id\"]] = cat[\"name\"]\n\n # fetch info from refs\n Refs, imgToRefs, refToAnn, annToRef, catToRefs = {}, {}, {}, {}, {}\n Sents, sentToRef, sentToTokens = {}, {}, {}\n for ref in self.data[\"refs\"]:\n # ids\n ref_id = ref[\"ref_id\"]\n ann_id = ref[\"ann_id\"]\n category_id = ref[\"category_id\"]\n image_id = ref[\"image_id\"]\n\n # add mapping related to ref\n Refs[ref_id] = ref\n imgToRefs[image_id] = imgToRefs.get(image_id, []) + [ref]\n catToRefs[category_id] = catToRefs.get(category_id, []) + [ref]\n refToAnn[ref_id] = Anns[ann_id]\n annToRef[ann_id] = ref\n\n # add mapping of sent\n for sent in ref[\"sentences\"]:\n Sents[sent[\"sent_id\"]] = sent\n sentToRef[sent[\"sent_id\"]] = ref\n sentToTokens[sent[\"sent_id\"]] = sent[\"tokens\"]\n\n # create class members\n self.Refs = Refs\n self.Anns = Anns\n self.Imgs = Imgs\n self.Cats = Cats\n self.Sents = Sents\n self.imgToRefs = imgToRefs\n self.imgToAnns = imgToAnns\n self.refToAnn = refToAnn\n self.annToRef = annToRef\n self.catToRefs = catToRefs\n self.sentToRef = sentToRef\n self.sentToTokens = sentToTokens\n print(\"index created.\")\n\n def getRefIds(self, image_ids=[], cat_ids=[], ref_ids=[], split=\"\"):\n image_ids = image_ids if type(image_ids) == list else [image_ids]\n cat_ids = cat_ids if type(cat_ids) == list else [cat_ids]\n ref_ids = ref_ids if type(ref_ids) == list else [ref_ids]\n\n if len(image_ids) == len(cat_ids) == len(ref_ids) == len(split) == 0:\n refs = self.data[\"refs\"]\n else:\n if not len(image_ids) == 0:\n refs = [self.imgToRefs[image_id] for image_id in image_ids]\n else:\n refs = self.data[\"refs\"]\n if not len(cat_ids) == 0:\n refs = [ref for ref in refs if ref[\"category_id\"] in cat_ids]\n if not len(ref_ids) == 0:\n refs = [ref for ref in refs if ref[\"ref_id\"] in ref_ids]\n if not len(split) == 0:\n if split in [\"testA\", \"testB\", \"testC\"]:\n refs = [\n ref for ref in refs if split[-1] in ref[\"split\"]\n ] # we also consider testAB, testBC, ...\n elif split in [\"testAB\", \"testBC\", \"testAC\"]:\n refs = [\n ref for ref in refs if ref[\"split\"] == split\n ] # rarely used I guess...\n elif split == \"test\":\n refs = [ref for ref in refs if \"test\" in ref[\"split\"]]\n elif split == \"train\" or split == \"val\":\n refs = [ref for ref in refs if ref[\"split\"] == split]\n else:\n print(\"No such split [%s]\" % split)\n sys.exit()\n ref_ids = [ref[\"ref_id\"] for ref in refs]\n return ref_ids\n\n def getAnnIds(self, image_ids=[], cat_ids=[], ref_ids=[]):\n image_ids = image_ids if type(image_ids) == list else [image_ids]\n cat_ids = cat_ids if type(cat_ids) == list else [cat_ids]\n ref_ids = ref_ids if type(ref_ids) == list else [ref_ids]\n\n if len(image_ids) == len(cat_ids) == len(ref_ids) == 0:\n ann_ids = [ann[\"id\"] for ann in self.data[\"annotations\"]]\n else:\n if not len(image_ids) == 0:\n lists = [\n self.imgToAnns[image_id]\n for image_id in image_ids\n if image_id in self.imgToAnns\n ] # list of [anns]\n anns = list(itertools.chain.from_iterable(lists))\n else:\n anns = self.data[\"annotations\"]\n if not len(cat_ids) == 0:\n anns = [ann for ann in anns if ann[\"category_id\"] in cat_ids]\n ann_ids = [ann[\"id\"] for ann in anns]\n if not len(ref_ids) == 0:\n ids = set(ann_ids).intersection(\n set([self.Refs[ref_id][\"ann_id\"] for ref_id in ref_ids])\n )\n return ann_ids\n\n def getImgIds(self, ref_ids=[]):\n ref_ids = ref_ids if type(ref_ids) == list else [ref_ids]\n\n if not len(ref_ids) == 0:\n image_ids = list(set([self.Refs[ref_id][\"image_id\"] for ref_id in ref_ids]))\n else:\n image_ids = self.Imgs.keys()\n return image_ids\n\n def getCatIds(self):\n return self.Cats.keys()\n\n def loadRefs(self, ref_ids=[]):\n if type(ref_ids) == list:\n return [self.Refs[ref_id] for ref_id in ref_ids]\n elif type(ref_ids) == int:\n return [self.Refs[ref_ids]]\n\n def loadAnns(self, ann_ids=[]):\n if type(ann_ids) == list:\n return [self.Anns[ann_id] for ann_id in ann_ids]\n elif type(ann_ids) == int or type(ann_ids) == unicode:\n return [self.Anns[ann_ids]]\n\n def loadImgs(self, image_ids=[]):\n if type(image_ids) == list:\n return [self.Imgs[image_id] for image_id in image_ids]\n elif type(image_ids) == int:\n return [self.Imgs[image_ids]]\n\n def loadCats(self, cat_ids=[]):\n if type(cat_ids) == list:\n return [self.Cats[cat_id] for cat_id in cat_ids]\n elif type(cat_ids) == int:\n return [self.Cats[cat_ids]]\n\n def getRefBox(self, ref_id):\n ref = self.Refs[ref_id]\n ann = self.refToAnn[ref_id]\n return ann[\"bbox\"] # [x, y, w, h]\n\n def showRef(self, ref, seg_box=\"seg\"):\n ax = plt.gca()\n # show image\n image = self.Imgs[ref[\"image_id\"]]\n I = io.imread(osp.join(self.IMAGE_DIR, image[\"file_name\"]))\n ax.imshow(I)\n # show refer expression\n for sid, sent in enumerate(ref[\"sentences\"]):\n print(\"%s. %s\" % (sid + 1, sent[\"sent\"]))\n # show segmentations\n if seg_box == \"seg\":\n ann_id = ref[\"ann_id\"]\n ann = self.Anns[ann_id]\n polygons = []\n color = []\n c = \"none\"\n if type(ann[\"segmentation\"][0]) == list:\n # polygon used for refcoco*\n for seg in ann[\"segmentation\"]:\n poly = np.array(seg).reshape((len(seg) / 2, 2))\n polygons.append(Polygon(poly, True, alpha=0.4))\n color.append(c)\n p = PatchCollection(\n polygons,\n facecolors=color,\n edgecolors=(1, 1, 0, 0),\n linewidths=3,\n alpha=1,\n )\n ax.add_collection(p) # thick yellow polygon\n p = PatchCollection(\n polygons,\n facecolors=color,\n edgecolors=(1, 0, 0, 0),\n linewidths=1,\n alpha=1,\n )\n ax.add_collection(p) # thin red polygon\n else:\n # mask used for refclef\n rle = ann[\"segmentation\"]\n m = mask.decode(rle)\n img = np.ones((m.shape[0], m.shape[1], 3))\n color_mask = np.array([2.0, 166.0, 101.0]) / 255\n for i in range(3):\n img[:, :, i] = color_mask[i]\n ax.imshow(np.dstack((img, m * 0.5)))\n # show bounding-box\n elif seg_box == \"box\":\n ann_id = ref[\"ann_id\"]\n ann = self.Anns[ann_id]\n bbox = self.getRefBox(ref[\"ref_id\"])\n box_plot = Rectangle(\n (bbox[0], bbox[1]),\n bbox[2],\n bbox[3],\n fill=False,\n edgecolor=\"green\",\n linewidth=3,\n )\n ax.add_patch(box_plot)\n\n def getMask(self, ref):\n # return mask, area and mask-center\n ann = self.refToAnn[ref[\"ref_id\"]]\n image = self.Imgs[ref[\"image_id\"]]\n if type(ann[\"segmentation\"][0]) == list: # polygon\n rle = mask.frPyObjects(ann[\"segmentation\"], image[\"height\"], image[\"width\"])\n else:\n rle = ann[\"segmentation\"]\n m = mask.decode(rle)\n m = np.sum(\n m, axis=2\n ) # sometimes there are multiple binary map (corresponding to multiple segs)\n m = m.astype(np.uint8) # convert to np.uint8\n # compute area\n area = sum(mask.area(rle)) # should be close to ann['area']\n return {\"mask\": m, \"area\": area}\n # # position\n # position_x = np.mean(np.where(m==1)[1]) # [1] means columns (matlab style) -> x (c style)\n # position_y = np.mean(np.where(m==1)[0]) # [0] means rows (matlab style) -> y (c style)\n # # mass position (if there were multiple regions, we use the largest one.)\n # label_m = label(m, connectivity=m.ndim)\n # regions = regionprops(label_m)\n # if len(regions) > 0:\n # \tlargest_id = np.argmax(np.array([props.filled_area for props in regions]))\n # \tlargest_props = regions[largest_id]\n # \tmass_y, mass_x = largest_props.centroid\n # else:\n # \tmass_x, mass_y = position_x, position_y\n # # if centroid is not in mask, we find the closest point to it from mask\n # if m[mass_y, mass_x] != 1:\n # \tprint('Finding closes mask point ...')\n # \tkernel = np.ones((10, 10),np.uint8)\n # \tme = cv2.erode(m, kernel, iterations = 1)\n # \tpoints = zip(np.where(me == 1)[0].tolist(), np.where(me == 1)[1].tolist()) # row, col style\n # \tpoints = np.array(points)\n # \tdist = np.sum((points - (mass_y, mass_x))**2, axis=1)\n # \tid = np.argsort(dist)[0]\n # \tmass_y, mass_x = points[id]\n # \t# return\n # return {'mask': m, 'area': area, 'position_x': position_x, 'position_y': position_y, 'mass_x': mass_x, 'mass_y': mass_y}\n # # show image and mask\n # I = io.imread(osp.join(self.IMAGE_DIR, image['file_name']))\n # plt.figure()\n # plt.imshow(I)\n # ax = plt.gca()\n # img = np.ones( (m.shape[0], m.shape[1], 3) )\n # color_mask = np.array([2.0,166.0,101.0])/255\n # for i in range(3):\n # img[:,:,i] = color_mask[i]\n # ax.imshow(np.dstack( (img, m*0.5) ))\n # plt.show()\n\n def showMask(self, ref):\n M = self.getMask(ref)\n msk = M[\"mask\"]\n ax = plt.gca()\n ax.imshow(msk)" }, { "identifier": "ReferSegDataset", "path": "VisualSearch/utils/refer_seg_dataset.py", "snippet": "class ReferSegDataset(torch.utils.data.Dataset):\n pixel_mean = torch.Tensor([123.675, 116.28, 103.53]).view(-1, 1, 1)\n pixel_std = torch.Tensor([58.395, 57.12, 57.375]).view(-1, 1, 1)\n img_size = 1024\n ignore_label = 255\n\n def __init__(\n self,\n base_dir,\n tokenizer,\n vision_tower,\n samples_per_epoch=500 * 8 * 2 * 10,\n precision: str = \"fp32\",\n num_classes_per_sample: int = 3,\n exclude_val=False,\n refer_seg_data=\"refclef||refcoco||refcoco+||refcocog\",\n ):\n self.exclude_val = exclude_val\n self.samples_per_epoch = samples_per_epoch\n self.num_classes_per_sample = num_classes_per_sample\n\n self.base_dir = base_dir\n self.tokenizer = tokenizer\n self.precision = precision\n self.transform = OwlViTProcessor.from_pretrained(\"google/owlvit-base-patch16\")\n self.clip_image_processor = CLIPImageProcessor.from_pretrained(vision_tower)\n\n self.short_question_list = SHORT_QUESTION_LIST\n self.answer_list = ANSWER_LIST\n\n DATA_DIR = os.path.join(base_dir, \"refer_seg\")\n self.refer_seg_ds_list = refer_seg_data.split(\n \"||\"\n ) # ['refclef', 'refcoco', 'refcoco+', 'refcocog']\n self.refer_seg_data = {}\n for ds in self.refer_seg_ds_list:\n if ds == \"refcocog\":\n splitBy = \"umd\"\n else:\n splitBy = \"unc\"\n\n if ds == \"grefcoco\":\n refer_api = G_REFER(DATA_DIR, ds, splitBy)\n else:\n refer_api = REFER(DATA_DIR, ds, splitBy)\n ref_ids_train = refer_api.getRefIds(split=\"train\")\n images_ids_train = refer_api.getImgIds(ref_ids=ref_ids_train)\n refs_train = refer_api.loadRefs(ref_ids=ref_ids_train)\n\n refer_seg_ds = {}\n refer_seg_ds[\"images\"] = []\n loaded_images = refer_api.loadImgs(image_ids=images_ids_train)\n\n for item in loaded_images:\n item = item.copy()\n if ds == \"refclef\":\n item[\"file_name\"] = os.path.join(\n DATA_DIR, \"images/saiapr_tc-12\", item[\"file_name\"]\n )\n else:\n item[\"file_name\"] = os.path.join(\n DATA_DIR, \"images/mscoco/images/train2014\", item[\"file_name\"]\n )\n refer_seg_ds[\"images\"].append(item)\n refer_seg_ds[\"annotations\"] = refer_api.Anns # anns_train\n\n print(\n \"dataset {} (refs {}) (train split) has {} images and {} annotations.\".format(\n ds,\n splitBy,\n len(refer_seg_ds[\"images\"]),\n len(refer_seg_ds[\"annotations\"]),\n )\n )\n\n img2refs = {}\n for ref in refs_train:\n image_id = ref[\"image_id\"]\n img2refs[image_id] = img2refs.get(image_id, []) + [\n ref,\n ]\n refer_seg_ds[\"img2refs\"] = img2refs\n self.refer_seg_data[ds] = refer_seg_ds\n\n def __len__(self):\n return self.samples_per_epoch\n\n def preprocess(self, x: torch.Tensor) -> torch.Tensor:\n \"\"\"Normalize pixel values and pad to a square input.\"\"\"\n # Normalize colors\n x = (x - self.pixel_mean) / self.pixel_std\n\n # Pad\n h, w = x.shape[-2:]\n padh = self.img_size - h\n padw = self.img_size - w\n x = F.pad(x, (0, padw, 0, padh))\n return x\n\n def __getitem__(self, idx):\n ds = random.randint(0, len(self.refer_seg_ds_list) - 1)\n ds = self.refer_seg_ds_list[ds]\n refer_seg_ds = self.refer_seg_data[ds]\n images = refer_seg_ds[\"images\"]\n annotations = refer_seg_ds[\"annotations\"]\n img2refs = refer_seg_ds[\"img2refs\"]\n idx = random.randint(0, len(images) - 1)\n image_info = images[idx]\n image_path = image_info[\"file_name\"]\n image_id = image_info[\"id\"]\n refs = img2refs[image_id]\n if len(refs) == 0:\n return self.__getitem__(0)\n\n sents = []\n ann_ids = []\n for ref in refs:\n for sent in ref[\"sentences\"]:\n text = sent[\"sent\"]\n sents.append(text)\n ann_ids.append(ref[\"ann_id\"])\n if len(sents) >= self.num_classes_per_sample:\n sampled_inds = np.random.choice(\n list(range(len(sents))), size=self.num_classes_per_sample, replace=False\n )\n else:\n sampled_inds = list(range(len(sents)))\n sampled_sents = np.vectorize(sents.__getitem__)(sampled_inds).tolist()\n # sampled_ann_ids = np.vectorize(ann_ids.__getitem__)(sampled_inds).tolist()\n sampled_ann_ids = [ann_ids[ind] for ind in sampled_inds]\n sampled_classes = sampled_sents\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n # preprocess image for clip\n image_clip = self.clip_image_processor.preprocess(\n expand2square(Image.open(image_path).convert('RGB'), tuple(int(x*255) for x in self.clip_image_processor.image_mean)), return_tensors=\"pt\")[\"pixel_values\"][0]\n original_size = image.shape[:2]\n image = self.transform(images=image, return_tensors=\"pt\")['pixel_values'][0]\n resize = image.shape[:2]\n\n questions = []\n answers = []\n for text in sampled_classes:\n text = text.strip()\n assert len(text.split(\"||\")) == 1\n question_template = random.choice(self.short_question_list)\n questions.append(question_template.format(class_name=text.lower()))\n answers.append(random.choice(self.answer_list))\n\n conversations = []\n conv = conversation_lib.default_conversation.copy()\n\n i = 0\n while i < len(questions):\n conv.messages = []\n conv.append_message(conv.roles[0], questions[i])\n conv.append_message(conv.roles[1], answers[i])\n conversations.append(conv.get_prompt())\n i += 1\n\n flag = False\n masks = []\n bboxes_labels = []\n for ann_id in sampled_ann_ids:\n if isinstance(ann_id, list):\n assert False\n flag = True\n if -1 in ann_id:\n assert len(ann_id) == 1\n m = np.zeros((image_info[\"height\"], image_info[\"width\"])).astype(\n np.uint8\n )\n else:\n m_final = np.zeros(\n (image_info[\"height\"], image_info[\"width\"])\n ).astype(np.uint8)\n for ann_id_i in ann_id:\n ann = annotations[ann_id_i]\n\n if len(ann[\"segmentation\"]) == 0:\n m = np.zeros(\n (image_info[\"height\"], image_info[\"width\"])\n ).astype(np.uint8)\n else:\n if type(ann[\"segmentation\"][0]) == list: # polygon\n rle = mask.frPyObjects(\n ann[\"segmentation\"],\n image_info[\"height\"],\n image_info[\"width\"],\n )\n else:\n rle = ann[\"segmentation\"]\n for i in range(len(rle)):\n if not isinstance(rle[i][\"counts\"], bytes):\n rle[i][\"counts\"] = rle[i][\"counts\"].encode()\n m = mask.decode(rle)\n m = np.sum(\n m, axis=2\n ) # sometimes there are multiple binary map (corresponding to multiple segs)\n m = m.astype(np.uint8) # convert to np.uint8\n m_final = m_final | m\n m = m_final\n masks.append(m)\n continue\n \n ann = annotations[ann_id]\n cur_bboxes = [ann['bbox']]\n cur_bboxes = torch.tensor(cur_bboxes).view(-1, 4)\n # xywh to x1y1x2y2\n cur_bboxes[:, 2:] += cur_bboxes[:, :2]\n cur_bboxes[:, 0::2].clamp_(min=0, max=original_size[1])\n cur_bboxes[:, 1::2].clamp_(min=0, max=original_size[0])\n keep = (cur_bboxes[:, 3] > cur_bboxes[:, 1]) & (cur_bboxes[:, 2] > cur_bboxes[:, 0])\n cur_bboxes = cur_bboxes[keep]\n cur_bboxes = box_xyxy_to_cxcywh(cur_bboxes)\n cur_bboxes = cur_bboxes / torch.tensor([original_size[1], original_size[0], original_size[1], original_size[0]], dtype=torch.float32)\n if len(cur_bboxes) == 0:\n return self.__getitem__(0)\n bboxes_labels.append(cur_bboxes)\n \n if len(ann[\"segmentation\"]) == 0:\n m = np.zeros((image_info[\"height\"], image_info[\"width\"])).astype(\n np.uint8\n )\n masks.append(m)\n continue\n\n if type(ann[\"segmentation\"][0]) == list: # polygon\n rle = mask.frPyObjects(\n ann[\"segmentation\"], image_info[\"height\"], image_info[\"width\"]\n )\n else:\n rle = ann[\"segmentation\"]\n for i in range(len(rle)):\n if not isinstance(rle[i][\"counts\"], bytes):\n rle[i][\"counts\"] = rle[i][\"counts\"].encode()\n m = mask.decode(rle)\n m = np.sum(\n m, axis=2\n ) # sometimes there are multiple binary map (corresponding to multiple segs)\n m = m.astype(np.uint8) # convert to np.uint8\n masks.append(m)\n bboxes_valid = [1]*len(bboxes_labels)\n masks_valid = [1]*len(bboxes_labels)\n masks = np.stack(masks, axis=0)\n\n\n masks = torch.from_numpy(masks)\n label = torch.ones(masks.shape[1], masks.shape[2]) * self.ignore_label\n\n return (\n image_path,\n image,\n image_clip,\n conversations,\n masks,\n label,\n bboxes_labels,\n bboxes_valid,\n masks_valid,\n resize,\n questions,\n sampled_classes,\n )" }, { "identifier": "SegDetDataset", "path": "VisualSearch/utils/general_segdet_dataset.py", "snippet": "class SegDetDataset(torch.utils.data.Dataset):\n pixel_mean = torch.Tensor([123.675, 116.28, 103.53]).view(-1, 1, 1)\n pixel_std = torch.Tensor([58.395, 57.12, 57.375]).view(-1, 1, 1)\n img_size = 1024\n ignore_label = 255\n\n def __init__(\n self,\n base_dir,\n tokenizer,\n vision_tower,\n samples_per_epoch=500 * 8 * 2 * 10,\n precision: str = \"fp32\",\n num_classes_per_sample: int = 3,\n exclude_val=False,\n general_segdet_data=\"objects365||cocostuff||paco_lvis\",\n general_segdet_sample_rate=[2,1,1]\n ):\n self.exclude_val = exclude_val\n self.samples_per_epoch = samples_per_epoch\n self.num_classes_per_sample = num_classes_per_sample\n\n self.base_dir = base_dir\n self.tokenizer = tokenizer\n self.precision = precision\n self.transform = OwlViTProcessor.from_pretrained(\"google/owlvit-base-patch16\")\n self.clip_image_processor = CLIPImageProcessor.from_pretrained(vision_tower)\n\n self.short_question_list = SHORT_QUESTION_LIST\n self.answer_list = ANSWER_LIST\n\n self.data2list = {}\n self.data2classes = {}\n\n self.general_segdet_datas = general_segdet_data.split(\"||\")\n num_images = []\n for ds in self.general_segdet_datas:\n if ds == \"cocostuff\":\n classes, images, labels, bboxes = eval(\"init_{}\".format(ds))(base_dir)\n self.data2list[ds] = (images, labels, bboxes)\n elif ds == \"objects365\":\n classes, images, bboxes = eval(\"init_{}\".format(ds))(base_dir)\n self.data2list[ds] = (images, bboxes)\n else:\n classes, images, labels = eval(\"init_{}\".format(ds))(base_dir)\n self.data2list[ds] = (images, labels)\n self.data2classes[ds] = classes\n num_images.append(len(images))\n sample_rate = np.array(general_segdet_sample_rate)\n self.sample_rate = sample_rate / sample_rate.sum()\n\n if \"cocostuff\" in self.general_segdet_datas:\n self.cocostuff_class2index = {\n c: i for i, c in enumerate(self.data2classes[\"cocostuff\"])\n }\n\n def __len__(self):\n return self.samples_per_epoch\n\n def preprocess(self, x: torch.Tensor) -> torch.Tensor:\n \"\"\"Normalize pixel values and pad to a square input.\"\"\"\n # Normalize colors\n x = (x - self.pixel_mean) / self.pixel_std\n\n # Pad\n h, w = x.shape[-2:]\n padh = self.img_size - h\n padw = self.img_size - w\n x = F.pad(x, (0, padw, 0, padh))\n return x\n\n def __getitem__(self, idx):\n ds = np.random.choice(list(range(len(self.general_segdet_datas))), p=self.sample_rate)\n ds = self.general_segdet_datas[ds]\n\n if ds in [\"paco_lvis\"]:\n class_map = self.data2classes[ds]\n img_ids, coco_api = self.data2list[ds]\n idx = random.randint(0, len(img_ids) - 1)\n img_id = img_ids[idx]\n image_info = coco_api.loadImgs([img_id])[0]\n file_name = image_info[\"file_name\"]\n if ds == \"pascal_part\":\n file_name = os.path.join(\n \"VOCdevkit\", \"VOC2010\", \"JPEGImages\", file_name\n )\n image_path = os.path.join(self.base_dir, \"vlpart\", ds, file_name)\n elif ds == \"paco_lvis\":\n image_path = os.path.join(self.base_dir, \"coco2017\", file_name)\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n # preprocess image for clip\n image_clip = self.clip_image_processor.preprocess(\n expand2square(Image.open(image_path).convert('RGB'), tuple(int(x*255) for x in self.clip_image_processor.image_mean)), return_tensors=\"pt\"\n )[\"pixel_values\"][0]\n original_size = image.shape[:2]\n image = self.transform(images=image, return_tensors=\"pt\")['pixel_values'][0]\n resize = image.shape[:2]\n annIds = coco_api.getAnnIds(imgIds=image_info[\"id\"])\n anns = coco_api.loadAnns(annIds)\n anns_category2instances = dict()\n for ann in anns:\n category_id = ann['category_id']\n if category_id not in anns_category2instances:\n anns_category2instances[category_id] = []\n anns_category2instances[category_id].append(ann)\n if len(anns_category2instances) == 0:\n return self.__getitem__(0)\n if len(anns_category2instances) >= self.num_classes_per_sample:\n sampled_anns = np.random.choice(\n list(anns_category2instances.keys()), size=self.num_classes_per_sample, replace=False\n ).tolist()\n else:\n sampled_anns = list(anns_category2instances.keys())\n sampled_classes = []\n for category_id in sampled_anns:\n sampled_cls = class_map[category_id]\n if isinstance(sampled_cls, tuple):\n obj, part = sampled_cls\n if random.random() < 0.5:\n name = obj + \" \" + part\n else:\n name = \"the {} of the {}\".format(part, obj)\n else:\n name = sampled_cls\n name = name.replace('_', ' ')\n sampled_classes.append(name)\n\n elif ds in [\"cocostuff\"]:\n image, labels, bboxes_all = self.data2list[ds]\n idx = random.randint(0, len(image) - 1)\n image_path = image[idx]\n label_path = labels[idx]\n bboxes = bboxes_all[idx]\n label = Image.open(label_path)\n label = np.array(label)\n if ds == \"ade20k\":\n label[label == 0] = 255\n label -= 1\n label[label == 254] = 255\n elif ds == \"cocostuff\":\n for c, i in self.cocostuff_class2index.items():\n if \"-\" in c:\n label[label == i] = 255\n img = cv2.imread(image_path)\n image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n # preprocess image for clip\n image_clip = self.clip_image_processor.preprocess(\n expand2square(Image.open(image_path).convert('RGB'), tuple(int(x*255) for x in self.clip_image_processor.image_mean)), return_tensors=\"pt\"\n )[\"pixel_values\"][0]\n original_size = image.shape[:2]\n image = self.transform(images=image, return_tensors=\"pt\")['pixel_values'][0]\n resize = image.shape[:2]\n unique_label = np.unique(label).tolist()\n if 255 in unique_label:\n unique_label.remove(255)\n if len(unique_label) == 0:\n return self.__getitem__(0)\n\n classes = [self.data2classes[ds][class_id] for class_id in unique_label]\n if len(classes) >= self.num_classes_per_sample:\n sampled_classes = np.random.choice(\n classes, size=self.num_classes_per_sample, replace=False\n ).tolist()\n else:\n sampled_classes = classes\n\n elif ds in ['objects365']:\n image, bboxes_all = self.data2list[ds]\n idx = random.randint(0, len(image) - 1)\n image_path = image[idx]\n bboxes = bboxes_all[idx]\n img = cv2.imread(image_path)\n image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n # preprocess image for clip\n image_clip = self.clip_image_processor.preprocess(\n expand2square(Image.open(image_path).convert('RGB'), tuple(int(x*255) for x in self.clip_image_processor.image_mean)), return_tensors=\"pt\"\n )[\"pixel_values\"][0]\n original_size = image.shape[:2]\n image = self.transform(images=image, return_tensors=\"pt\")['pixel_values'][0]\n resize = image.shape[:2]\n unique_label = set()\n for bbox_info in bboxes:\n unique_label.add(bbox_info['category_id'])\n unique_label = list(unique_label)\n if len(unique_label) == 0:\n return self.__getitem__(0)\n\n classes = [self.data2classes[ds][class_id] for class_id in unique_label]\n if len(classes) >= self.num_classes_per_sample:\n sampled_classes = np.random.choice(\n classes, size=self.num_classes_per_sample, replace=False\n ).tolist()\n else:\n sampled_classes = classes\n\n\n questions = []\n answers = []\n class_ids = []\n bboxes_labels = []\n for i, sampled_cls in enumerate(sampled_classes):\n text = sampled_cls\n if ds in ['objects365']:\n text = random.sample(text.split('/'), 1)[0]\n \n assert len(text.split(\"||\")) == 1\n question_template = random.choice(self.short_question_list)\n questions.append(question_template.format(class_name=text.lower()))\n\n answers.append(random.choice(self.answer_list))\n\n if ds in [\"paco_lvis\", \"pascal_part\"]:\n category_id = sampled_anns[i]\n cur_bboxes = [instance['bbox'] for instance in anns_category2instances[category_id]]\n cur_bboxes = torch.tensor(cur_bboxes).view(-1, 4)\n # xywh to x1y1x2y2\n cur_bboxes[:, 2:] += cur_bboxes[:, :2]\n cur_bboxes[:, 0::2].clamp_(min=0, max=original_size[1])\n cur_bboxes[:, 1::2].clamp_(min=0, max=original_size[0])\n keep = (cur_bboxes[:, 3] > cur_bboxes[:, 1]) & (cur_bboxes[:, 2] > cur_bboxes[:, 0])\n cur_bboxes = cur_bboxes[keep]\n cur_bboxes = box_xyxy_to_cxcywh(cur_bboxes)\n cur_bboxes = cur_bboxes / torch.tensor([original_size[1], original_size[0], original_size[1], original_size[0]], dtype=torch.float32)\n if len(cur_bboxes) == 0:\n return self.__getitem__(0)\n bboxes_labels.append(cur_bboxes)\n continue\n\n class_id = self.data2classes[ds].tolist().index(sampled_cls)\n class_ids.append(class_id)\n if ds in ['objects365']:\n cur_bboxes = [bbox['bbox'] for bbox in bboxes if bbox['category_id'] == class_id]\n else:\n cur_bboxes = [bbox['bbox'] for bbox in bboxes if bbox['category_id']-1 == class_id]\n cur_bboxes = cur_bboxes[:100]\n assert len(cur_bboxes) > 0\n cur_bboxes = torch.tensor(cur_bboxes).view(-1, 4)\n # xywh to x1y1x2y2\n cur_bboxes[:, 2:] += cur_bboxes[:, :2]\n cur_bboxes[:, 0::2].clamp_(min=0, max=original_size[1])\n cur_bboxes[:, 1::2].clamp_(min=0, max=original_size[0])\n keep = (cur_bboxes[:, 3] > cur_bboxes[:, 1]) & (cur_bboxes[:, 2] > cur_bboxes[:, 0])\n cur_bboxes = cur_bboxes[keep]\n cur_bboxes = box_xyxy_to_cxcywh(cur_bboxes)\n cur_bboxes = cur_bboxes / torch.tensor([original_size[1], original_size[0], original_size[1], original_size[0]], dtype=torch.float32)\n if len(cur_bboxes) == 0:\n return self.__getitem__(0)\n bboxes_labels.append(cur_bboxes)\n bboxes_valid = [1]*len(bboxes_labels)\n masks_valid = [1]*len(bboxes_labels)\n conversations = []\n conv = conversation_lib.default_conversation.copy()\n\n i = 0\n while i < len(questions):\n conv.messages = []\n conv.append_message(conv.roles[0], questions[i])\n conv.append_message(conv.roles[1], answers[i])\n conversations.append(conv.get_prompt())\n i += 1\n\n if ds in [\"paco_lvis\", \"pascal_part\"]:\n masks = []\n for category_id in sampled_anns:\n try:\n cur_anns = anns_category2instances[category_id]\n cur_mask = None\n for ann in cur_anns:\n if cur_mask is None:\n cur_mask = coco_api.annToMask(ann)\n else:\n cur_mask = cur_mask | coco_api.annToMask(ann)\n assert cur_mask is not None\n masks.append(cur_mask)\n except Exception as e:\n print(e)\n return self.__getitem__(0)\n\n masks = np.stack(masks, axis=0)\n masks = torch.from_numpy(masks)\n label = torch.ones(masks.shape[1], masks.shape[2]) * self.ignore_label\n elif ds in ['objects365']:\n masks = torch.rand(len(bboxes_labels), *original_size)\n label = torch.ones(original_size) * self.ignore_label\n masks_valid = [0]*len(bboxes_labels)\n else:\n label = torch.from_numpy(label).long()\n masks = []\n for class_id in class_ids:\n masks.append(label == class_id)\n masks = torch.stack(masks, dim=0)\n return (\n image_path,\n image,\n image_clip,\n conversations,\n masks,\n label,\n bboxes_labels,\n bboxes_valid,\n masks_valid,\n resize,\n questions,\n sampled_classes,\n )" }, { "identifier": "MixedGroundingDataset", "path": "VisualSearch/utils/mixed_grounding_dataset.py", "snippet": "class MixedGroundingDataset(torch.utils.data.Dataset):\n pixel_mean = torch.Tensor([123.675, 116.28, 103.53]).view(-1, 1, 1)\n pixel_std = torch.Tensor([58.395, 57.12, 57.375]).view(-1, 1, 1)\n img_size = 1024\n ignore_label = 255\n\n def __init__(\n self,\n base_dir,\n tokenizer,\n vision_tower,\n samples_per_epoch=500 * 8 * 2 * 10,\n precision: str = \"fp32\",\n num_classes_per_sample: int = 3,\n exclude_val=False,\n ):\n self.samples_per_epoch = samples_per_epoch\n self.num_classes_per_sample = num_classes_per_sample\n\n self.base_dir = base_dir\n self.tokenizer = tokenizer\n self.precision = precision\n self.transform = OwlViTProcessor.from_pretrained(\"google/owlvit-base-patch16\")\n self.clip_image_processor = CLIPImageProcessor.from_pretrained(vision_tower)\n\n self.short_question_list = SHORT_QUESTION_LIST\n self.answer_list = ANSWER_LIST\n\n with open(os.path.join(base_dir, 'MixedGrounding', 'goldG_train.json')) as f:\n self.images = json.load(f)\n\n def __len__(self):\n return self.samples_per_epoch\n\n def preprocess(self, x: torch.Tensor) -> torch.Tensor:\n \"\"\"Normalize pixel values and pad to a square input.\"\"\"\n # Normalize colors\n x = (x - self.pixel_mean) / self.pixel_std\n\n # Pad\n h, w = x.shape[-2:]\n padh = self.img_size - h\n padw = self.img_size - w\n x = F.pad(x, (0, padw, 0, padh))\n return x\n\n def __getitem__(self, idx):\n\n idx = random.randint(0, len(self.images) - 1)\n image_info = self.images[idx]\n image_data_source = image_info['data_source']\n file_name = image_info[\"file_name\"]\n assert image_data_source in ['coco', 'vg', 'flickr']\n if image_data_source == 'coco':\n image_path = os.path.join(self.base_dir, 'coco2014/train2014', file_name)\n elif image_data_source == 'vg':\n image_path = os.path.join(self.base_dir, 'MixedGrounding/GQA/images', file_name)\n else:\n image_path = os.path.join(self.base_dir, 'MixedGrounding/flickr30k-images', file_name)\n caption = image_info['caption']\n instances = image_info['instances']\n if len(instances) == 0:\n return self.__getitem__(0)\n\n if len(instances) >= self.num_classes_per_sample:\n sampled_inds = np.random.choice(\n list(range(len(instances))), size=self.num_classes_per_sample, replace=False\n )\n else:\n sampled_inds = list(range(len(instances)))\n\n sampled_classes = sampled_inds\n \n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n # preprocess image for clip\n image_clip = self.clip_image_processor.preprocess(\n expand2square(Image.open(image_path).convert('RGB'), tuple(int(x*255) for x in self.clip_image_processor.image_mean)), return_tensors=\"pt\")[\"pixel_values\"][0]\n original_size = image.shape[:2]\n image = self.transform(images=image, return_tensors=\"pt\")['pixel_values'][0]\n resize = image.shape[:2]\n\n questions = []\n answers = []\n bboxes_labels = []\n for sample_ind in sampled_inds:\n text = []\n tokens_positive = instances[sample_ind]['tokens_positive']\n for token in tokens_positive:\n text.append(caption[token[0]:token[1]])\n text = \" \".join(text)\n text = text.strip()\n question_template = random.choice(self.short_question_list)\n questions.append(question_template.format(class_name=text.lower()))\n answers.append(random.choice(self.answer_list))\n\n cur_bboxes = [instances[sample_ind]['bbox']]\n cur_bboxes = torch.tensor(cur_bboxes).view(-1, 4)\n # xywh to x1y1x2y2\n cur_bboxes[:, 2:] += cur_bboxes[:, :2]\n cur_bboxes[:, 0::2].clamp_(min=0, max=original_size[1])\n cur_bboxes[:, 1::2].clamp_(min=0, max=original_size[0])\n keep = (cur_bboxes[:, 3] > cur_bboxes[:, 1]) & (cur_bboxes[:, 2] > cur_bboxes[:, 0])\n cur_bboxes = cur_bboxes[keep]\n cur_bboxes = box_xyxy_to_cxcywh(cur_bboxes)\n cur_bboxes = cur_bboxes / torch.tensor([original_size[1], original_size[0], original_size[1], original_size[0]], dtype=torch.float32)\n if len(cur_bboxes) == 0:\n return self.__getitem__(0)\n bboxes_labels.append(cur_bboxes)\n\n conversations = []\n conv = conversation_lib.default_conversation.copy()\n\n i = 0\n while i < len(questions):\n conv.messages = []\n conv.append_message(conv.roles[0], questions[i])\n conv.append_message(conv.roles[1], answers[i])\n conversations.append(conv.get_prompt())\n i += 1\n \n bboxes_valid = [1]*len(bboxes_labels)\n masks_valid = [0]*len(bboxes_labels)\n masks = torch.rand(len(bboxes_labels), *original_size)\n label = torch.ones(original_size) * self.ignore_label\n\n return (\n image_path,\n image,\n image_clip,\n conversations,\n masks,\n label,\n bboxes_labels,\n bboxes_valid,\n masks_valid,\n resize,\n questions,\n sampled_classes,\n )" }, { "identifier": "VQADataset", "path": "VisualSearch/utils/vqa_dataset.py", "snippet": "class VQADataset(torch.utils.data.Dataset):\n pixel_mean = torch.Tensor([123.675, 116.28, 103.53]).view(-1, 1, 1)\n pixel_std = torch.Tensor([58.395, 57.12, 57.375]).view(-1, 1, 1)\n img_size = 1024\n ignore_label = 255\n\n def __init__(\n self,\n base_image_dir,\n tokenizer,\n vision_tower,\n samples_per_epoch=500 * 8 * 2 * 10,\n precision: str = \"fp32\",\n num_classes_per_sample: int = 3,\n exclude_val=False,\n vqa_data=\"possible_locations_conv_86k||llava_instruct_150k\",\n vqa_sample_rate=[2,1],\n ):\n self.exclude_val = exclude_val\n self.samples_per_epoch = samples_per_epoch\n self.num_classes_per_sample = num_classes_per_sample\n\n self.base_image_dir = base_image_dir\n self.tokenizer = tokenizer\n self.precision = precision\n self.transform = OwlViTProcessor.from_pretrained(\"google/owlvit-base-patch16\")\n self.clip_image_processor = CLIPImageProcessor.from_pretrained(vision_tower)\n\n DATA_DIR = os.path.join(base_image_dir, \"vsm_vqa_data\")\n self.vqa_image_root = os.path.join(base_image_dir, \"coco2017/train2017\")\n vqa_datas = vqa_data.split(\"||\")\n self.vqa_datas = []\n for data in vqa_datas:\n with open(os.path.join(DATA_DIR, \"{}.json\".format(data))) as f:\n data = json.load(f)\n self.vqa_datas.append(data)\n sample_rate = np.array(vqa_sample_rate)\n self.sample_rate = sample_rate / sample_rate.sum()\n\n def __len__(self):\n return self.samples_per_epoch\n\n def preprocess(self, x: torch.Tensor) -> torch.Tensor:\n \"\"\"Normalize pixel values and pad to a square input.\"\"\"\n # Normalize colors\n x = (x - self.pixel_mean) / self.pixel_std\n\n # Pad\n h, w = x.shape[-2:]\n padh = self.img_size - h\n padw = self.img_size - w\n x = F.pad(x, (0, padw, 0, padh))\n return x\n\n def __getitem__(self, idx):\n ds = np.random.choice(list(range(len(self.vqa_datas))), p=self.sample_rate)\n ds = self.vqa_datas[ds]\n idx = random.randint(0, len(ds) - 1)\n item = ds[idx]\n image_path = os.path.join(self.vqa_image_root, item[\"image\"])\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n ori_size = image.shape[:2]\n image_clip = self.clip_image_processor.preprocess(\n expand2square(Image.open(image_path).convert('RGB'), tuple(int(x*255) for x in self.clip_image_processor.image_mean)), return_tensors=\"pt\")[\"pixel_values\"][0]\n\n image = self.transform(images=image, return_tensors=\"pt\")['pixel_values'][0]\n resize = image.shape[:2]\n\n conv = conversation_lib.default_conversation.copy()\n source = item[\"conversations\"]\n source = preprocess_multimodal(\n copy.deepcopy(source),\n mm_use_im_start_end=conv.sep_style == conversation_lib.SeparatorStyle.TWO,\n )\n roles = {\"human\": conv.roles[0], \"gpt\": conv.roles[1]}\n conversations = []\n if roles[source[0][\"from\"]] != conv.roles[0]:\n # Skip the first one if it is not from human\n source = source[1:]\n conv.messages = []\n for j, sentence in enumerate(source):\n role = roles[sentence[\"from\"]]\n assert role == conv.roles[j % 2], f\"{j}\"\n conv.append_message(role, sentence[\"value\"])\n conversations.append(conv.get_prompt())\n\n questions = conversations\n sampled_classes = conversations\n\n masks = torch.rand(1, *ori_size)\n label = torch.ones(ori_size) * self.ignore_label\n bboxes_labels = [torch.tensor([[0.5,0.5,1.0,1.0]])]\n bboxes_valid = [0]\n masks_valid = [0]\n\n return (\n image_path,\n image,\n image_clip,\n conversations,\n masks,\n label,\n bboxes_labels,\n bboxes_valid,\n masks_valid,\n resize,\n questions,\n sampled_classes,\n )" }, { "identifier": "DEFAULT_IM_END_TOKEN", "path": "VisualSearch/utils/utils.py", "snippet": "DEFAULT_IM_END_TOKEN = \"<im_end>\"" }, { "identifier": "DEFAULT_IM_START_TOKEN", "path": "VisualSearch/utils/utils.py", "snippet": "DEFAULT_IM_START_TOKEN = \"<im_start>\"" }, { "identifier": "DEFAULT_IMAGE_TOKEN", "path": "VisualSearch/utils/utils.py", "snippet": "DEFAULT_IMAGE_TOKEN = \"<image>\"" }, { "identifier": "box_xyxy_to_cxcywh", "path": "VisualSearch/utils/utils.py", "snippet": "def box_xyxy_to_cxcywh(x):\n x0, y0, x1, y1 = x.unbind(-1)\n b = [(x0 + x1) / 2, (y0 + y1) / 2,\n (x1 - x0), (y1 - y0)]\n return torch.stack(b, dim=-1)" }, { "identifier": "expand2square", "path": "VisualSearch/utils/utils.py", "snippet": "def expand2square(pil_img, background_color):\n width, height = pil_img.size\n if width == height:\n return pil_img\n elif width > height:\n result = Image.new(pil_img.mode, (width, width), background_color)\n result.paste(pil_img, (0, 0))\n return result\n else:\n result = Image.new(pil_img.mode, (height, height), background_color)\n result.paste(pil_img, (0, 0))\n return result" } ]
import glob import os import random import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image from pycocotools import mask from transformers import CLIPImageProcessor from transformers import OwlViTProcessor from VisualSearch.model.llava import conversation as conversation_lib from VisualSearch.model.llava.constants import (DEFAULT_IMAGE_TOKEN, IGNORE_INDEX, IMAGE_TOKEN_INDEX) from VisualSearch.model.llava.mm_utils import tokenizer_image_token from VisualSearch.utils.data_processing import get_mask_from_json from VisualSearch.utils.refer import REFER from VisualSearch.utils.refer_seg_dataset import ReferSegDataset from VisualSearch.utils.general_segdet_dataset import SegDetDataset from VisualSearch.utils.mixed_grounding_dataset import MixedGroundingDataset from VisualSearch.utils.vqa_dataset import VQADataset from VisualSearch.utils.utils import (DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IMAGE_TOKEN) from VisualSearch.utils.utils import box_xyxy_to_cxcywh, expand2square
14,596
cv2.setNumThreads(1) def collate_fn( batch, tokenizer=None, conv_type="llava_v1", use_mm_start_end=True, local_rank=-1 ): image_path_list = [] images_list = [] images_clip_list = [] conversation_list = [] masks_list = [] label_list = [] bboxes_labels_list = [] bboxes_valid_list = [] masks_valid_list = [] resize_list = [] questions_list = [] sampled_classes_list = [] offset_list = [0] cnt = 0 inferences = [] for ( image_path, images, images_clip, conversations, masks, label, bboxes_labels, bboxes_valid, masks_valid, resize, questions, sampled_classes, inference, ) in batch: image_path_list.append(image_path) images_list.append(images) images_clip_list.append(images_clip) conversation_list.extend(conversations) label_list.append(label) masks_list.append(masks.float()) bboxes_labels_list.extend(bboxes_labels) bboxes_valid_list.extend(bboxes_valid) masks_valid_list.append(torch.tensor(masks_valid)) resize_list.append(resize) questions_list.append(questions) sampled_classes_list.append(sampled_classes) cnt += len(conversations) offset_list.append(cnt) inferences.append(inference) if use_mm_start_end: # replace <image> token for i in range(len(conversation_list)): replace_token = DEFAULT_IMAGE_TOKEN replace_token = ( DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN ) conversation_list[i] = conversation_list[i].replace( DEFAULT_IMAGE_TOKEN, replace_token ) input_ids = [ tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversation_list ] input_ids = torch.nn.utils.rnn.pad_sequence( input_ids, batch_first=True, padding_value=tokenizer.pad_token_id ) attention_masks = input_ids.ne(tokenizer.pad_token_id) for i in range(len(bboxes_valid_list)): bboxes_valid = bboxes_valid_list[i] attention_mask = attention_masks[i] if not bboxes_valid: attention_mask = attention_mask & input_ids[i].ne(tokenizer("[LOC]", add_special_tokens=False).input_ids[0]) attention_masks[i] = attention_mask conv = conversation_lib.default_conversation.copy() targets = input_ids.clone() if conv_type == "llava_v1": sep = conv.sep + conv.roles[1] + ": " else: sep = "[/INST] " for conversation, target in zip(conversation_list, targets): total_len = int(target.ne(tokenizer.pad_token_id).sum()) rounds = conversation.split(conv.sep2) cur_len = 1
cv2.setNumThreads(1) def collate_fn( batch, tokenizer=None, conv_type="llava_v1", use_mm_start_end=True, local_rank=-1 ): image_path_list = [] images_list = [] images_clip_list = [] conversation_list = [] masks_list = [] label_list = [] bboxes_labels_list = [] bboxes_valid_list = [] masks_valid_list = [] resize_list = [] questions_list = [] sampled_classes_list = [] offset_list = [0] cnt = 0 inferences = [] for ( image_path, images, images_clip, conversations, masks, label, bboxes_labels, bboxes_valid, masks_valid, resize, questions, sampled_classes, inference, ) in batch: image_path_list.append(image_path) images_list.append(images) images_clip_list.append(images_clip) conversation_list.extend(conversations) label_list.append(label) masks_list.append(masks.float()) bboxes_labels_list.extend(bboxes_labels) bboxes_valid_list.extend(bboxes_valid) masks_valid_list.append(torch.tensor(masks_valid)) resize_list.append(resize) questions_list.append(questions) sampled_classes_list.append(sampled_classes) cnt += len(conversations) offset_list.append(cnt) inferences.append(inference) if use_mm_start_end: # replace <image> token for i in range(len(conversation_list)): replace_token = DEFAULT_IMAGE_TOKEN replace_token = ( DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN ) conversation_list[i] = conversation_list[i].replace( DEFAULT_IMAGE_TOKEN, replace_token ) input_ids = [ tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversation_list ] input_ids = torch.nn.utils.rnn.pad_sequence( input_ids, batch_first=True, padding_value=tokenizer.pad_token_id ) attention_masks = input_ids.ne(tokenizer.pad_token_id) for i in range(len(bboxes_valid_list)): bboxes_valid = bboxes_valid_list[i] attention_mask = attention_masks[i] if not bboxes_valid: attention_mask = attention_mask & input_ids[i].ne(tokenizer("[LOC]", add_special_tokens=False).input_ids[0]) attention_masks[i] = attention_mask conv = conversation_lib.default_conversation.copy() targets = input_ids.clone() if conv_type == "llava_v1": sep = conv.sep + conv.roles[1] + ": " else: sep = "[/INST] " for conversation, target in zip(conversation_list, targets): total_len = int(target.ne(tokenizer.pad_token_id).sum()) rounds = conversation.split(conv.sep2) cur_len = 1
target[:cur_len] = IGNORE_INDEX
2
2023-12-15 14:58:24+00:00
24k
sinoyou/nelf-pro
nerfstudio/viewer/server/viewer_utils.py
[ { "identifier": "Cameras", "path": "nerfstudio/cameras/cameras.py", "snippet": "class Cameras(TensorDataclass):\n \"\"\"Dataparser outputs for the image dataset and the ray generator.\n\n Note: currently only supports cameras with the same principal points and types. The reason we type\n the focal lengths, principal points, and image sizes as tensors is to allow for batched cameras\n down the line in cases where your batches of camera data don't come from the same cameras.\n\n If a single value is provided, it is broadcasted to all cameras.\n\n Args:\n camera_to_worlds: Camera to world matrices. Tensor of per-image c2w matrices, in [R | t] format\n fx: Focal length x\n fy: Focal length y\n cx: Principal point x\n cy: Principal point y\n width: Image width\n height: Image height\n distortion_params: OpenCV 6 radial distortion coefficients\n camera_type: Type of camera model. This will be an int corresponding to the CameraType enum.\n times: Timestamps for each camera\n probe_config: dict config containing the generated probe information (core and basis)\n \"\"\"\n\n camera_to_worlds: TensorType[\"num_cameras\":..., 3, 4]\n fx: TensorType[\"num_cameras\":..., 1]\n fy: TensorType[\"num_cameras\":..., 1]\n cx: TensorType[\"num_cameras\":..., 1]\n cy: TensorType[\"num_cameras\":..., 1]\n width: TensorType[\"num_cameras\":..., 1]\n height: TensorType[\"num_cameras\":..., 1]\n distortion_params: Optional[TensorType[\"num_cameras\":..., 6]]\n camera_type: TensorType[\"num_cameras\":..., 1]\n times: Optional[TensorType[\"num_cameras\":..., 1]]\n image_filenames: Optional[List[str]]\n probe_config: Optional[list]\n\n def __init__(\n self,\n camera_to_worlds: TensorType[\"batch_c2ws\":..., 3, 4],\n fx: Union[TensorType[\"batch_fxs\":..., 1], float],\n fy: Union[TensorType[\"batch_fys\":..., 1], float],\n cx: Union[TensorType[\"batch_cxs\":..., 1], float],\n cy: Union[TensorType[\"batch_cys\":..., 1], float],\n width: Optional[Union[TensorType[\"batch_ws\":..., 1], int]] = None,\n height: Optional[Union[TensorType[\"batch_hs\":..., 1], int]] = None,\n distortion_params: Optional[TensorType[\"batch_dist_params\":..., 6]] = None,\n camera_type: Optional[\n Union[\n TensorType[\"batch_cam_types\":..., 1],\n int,\n List[CameraType],\n CameraType,\n ]\n ] = CameraType.PERSPECTIVE,\n times: Optional[TensorType[\"num_cameras\"]] = None,\n image_filenames: Optional[List[str]] = None,\n probe_config: Optional[list] = None\n ):\n \"\"\"Initializes the Cameras object.\n\n Note on Input Tensor Dimensions: All of these tensors have items of dimensions TensorType[3, 4]\n (in the case of the c2w matrices), TensorType[6] (in the case of distortion params), or\n TensorType[1] (in the case of the rest of the elements). The dimensions before that are\n considered the batch dimension of that tensor (batch_c2ws, batch_fxs, etc.). We will broadcast\n all the tensors to be the same batch dimension. This means you can use any combination of the\n input types in the function signature and it won't break. Your batch size for all tensors\n must be broadcastable to the same size, and the resulting number of batch dimensions will be\n the batch dimension with the largest number of dimensions.\n \"\"\"\n\n # This will notify the tensordataclass that we have a field with more than 1 dimension\n self._field_custom_dimensions = {\"camera_to_worlds\": 2}\n\n self.camera_to_worlds = camera_to_worlds\n\n # fx fy calculation\n self.fx = self._init_get_fc_xy(fx, \"fx\") # @dataclass's post_init will take care of broadcasting\n self.fy = self._init_get_fc_xy(fy, \"fy\") # @dataclass's post_init will take care of broadcasting\n\n # cx cy calculation\n self.cx = self._init_get_fc_xy(cx, \"cx\") # @dataclass's post_init will take care of broadcasting\n self.cy = self._init_get_fc_xy(cy, \"cy\") # @dataclass's post_init will take care of broadcasting\n\n # Distortion Params Calculation:\n self.distortion_params = distortion_params # @dataclass's post_init will take care of broadcasting\n\n # @dataclass's post_init will take care of broadcasting\n self.height = self._init_get_height_width(height, self.cy)\n self.width = self._init_get_height_width(width, self.cx)\n self.camera_type = self._init_get_camera_type(camera_type)\n self.times = self._init_get_times(times)\n \n self.image_filenames = image_filenames\n self.probe_config = probe_config\n if self.probe_config is not None:\n self.probe = Probes(self.camera_to_worlds, self.probe_config)\n else:\n self.probe = None\n \n self.__post_init__() # This will do the dataclass post_init and broadcast all the tensors\n\n def _init_get_fc_xy(self, fc_xy, name):\n \"\"\"\n Parses the input focal length / principle point x or y and returns a tensor of the correct shape\n\n Only needs to make sure that we a 1 in the last dimension if it is a tensor. If it is a float, we\n just need to make it into a tensor and it will be broadcasted later in the __post_init__ function.\n\n Args:\n fc_xy: The focal length / principle point x or y\n name: The name of the variable. Used for error messages\n \"\"\"\n if isinstance(fc_xy, float):\n fc_xy = torch.Tensor([fc_xy], device=self.device)\n elif isinstance(fc_xy, torch.Tensor):\n if fc_xy.ndim == 0 or fc_xy.shape[-1] != 1:\n fc_xy = fc_xy.unsqueeze(-1)\n fc_xy = fc_xy.to(self.device)\n else:\n raise ValueError(f\"{name} must be a float or tensor, got {type(fc_xy)}\")\n return fc_xy\n\n def _init_get_camera_type(\n self,\n camera_type: Union[\n TensorType[\"batch_cam_types\":..., 1], TensorType[\"batch_cam_types\":...], int, List[CameraType], CameraType\n ],\n ) -> TensorType[\"num_cameras\":..., 1]:\n \"\"\"\n Parses the __init__() argument camera_type\n\n Camera Type Calculation:\n If CameraType, convert to int and then to tensor, then broadcast to all cameras\n If List of CameraTypes, convert to ints and then to tensor, then broadcast to all cameras\n If int, first go to tensor and then broadcast to all cameras\n If tensor, broadcast to all cameras\n\n Args:\n camera_type: camera_type argument from __init__()\n \"\"\"\n if isinstance(camera_type, CameraType):\n camera_type = torch.tensor([camera_type.value], device=self.device)\n elif isinstance(camera_type, List) and isinstance(camera_type[0], CameraType):\n camera_type = torch.tensor([[c.value] for c in camera_type], device=self.device)\n elif isinstance(camera_type, int):\n camera_type = torch.tensor([camera_type], device=self.device)\n elif isinstance(camera_type, torch.Tensor):\n assert not torch.is_floating_point(\n camera_type\n ), f\"camera_type tensor must be of type int, not: {camera_type.dtype}\"\n camera_type = camera_type.to(self.device)\n if camera_type.ndim == 0 or camera_type.shape[-1] != 1:\n camera_type = camera_type.unsqueeze(-1)\n # assert torch.all(\n # camera_type.view(-1)[0] == camera_type\n # ), \"Batched cameras of different camera_types will be allowed in the future.\"\n else:\n raise ValueError(\n 'Invalid camera_type. Must be CameraType, List[CameraType], int, or torch.Tensor[\"num_cameras\"]. \\\n Received: '\n + str(type(camera_type))\n )\n return camera_type\n\n def _init_get_height_width(\n self,\n h_w: Union[TensorType[\"batch_hws\":..., 1], TensorType[\"batch_hws\":...], int, None],\n c_x_y: TensorType[\"batch_cxys\":...],\n ) -> TensorType[\"num_cameras\":..., 1]:\n \"\"\"\n Parses the __init__() argument for height or width\n\n Height/Width Calculation:\n If int, first go to tensor and then broadcast to all cameras\n If tensor, broadcast to all cameras\n If none, use cx or cy * 2\n Else raise error\n\n Args:\n h_w: height or width argument from __init__()\n c_x_y: cx or cy for when h_w == None\n \"\"\"\n if isinstance(h_w, int):\n h_w = torch.Tensor([h_w]).to(torch.int64).to(self.device)\n elif isinstance(h_w, torch.Tensor):\n assert not torch.is_floating_point(h_w), f\"height and width tensor must be of type int, not: {h_w.dtype}\"\n h_w = h_w.to(torch.int64).to(self.device)\n if h_w.ndim == 0 or h_w.shape[-1] != 1:\n h_w = h_w.unsqueeze(-1)\n # assert torch.all(h_w == h_w.view(-1)[0]), \"Batched cameras of different h, w will be allowed in the future.\"\n elif h_w is None:\n h_w = torch.Tensor((c_x_y * 2).to(torch.int64).to(self.device))\n else:\n raise ValueError(\"Height must be an int, tensor, or None, received: \" + str(type(h_w)))\n return h_w\n\n def _init_get_times(self, times):\n if times is None:\n times = None\n elif isinstance(times, torch.Tensor):\n if times.ndim == 0 or times.shape[-1] != 1:\n times = times.unsqueeze(-1).to(self.device)\n else:\n raise ValueError(f\"times must be None or a tensor, got {type(times)}\")\n\n return times\n\n @property\n def device(self):\n \"\"\"Returns the device that the camera is on.\"\"\"\n return self.camera_to_worlds.device\n\n @property\n def image_height(self) -> TensorType[\"num_cameras\":..., 1]:\n \"\"\"Returns the height of the images.\"\"\"\n return self.height\n\n @property\n def image_width(self) -> TensorType[\"num_cameras\":..., 1]:\n \"\"\"Returns the height of the images.\"\"\"\n return self.width\n\n @property\n def is_jagged(self):\n \"\"\"\n Returns whether or not the cameras are \"jagged\" (i.e. the height and widths are different, meaning that\n you cannot concatenate the image coordinate maps together)\n \"\"\"\n h_jagged = not torch.all(self.height == self.height.view(-1)[0])\n w_jagged = not torch.all(self.width == self.width.view(-1)[0])\n return h_jagged or w_jagged\n\n def get_image_coords(\n self, pixel_offset: float = 0.5, index: Optional[Tuple] = None\n ) -> TensorType[\"height\", \"width\", 2]:\n \"\"\"This gets the image coordinates of one of the cameras in this object.\n\n If no index is specified, it will return the maximum possible sized height / width image coordinate map,\n by looking at the maximum height and width of all the cameras in this object.\n\n Args:\n pixel_offset: Offset for each pixel. Defaults to center of pixel (0.5)\n index: Tuple of indices into the batch dimensions of the camera. Defaults to None, which returns the 0th\n flattened camera\n\n Returns:\n Grid of image coordinates.\n \"\"\"\n if index is None:\n image_height = torch.max(self.image_height.view(-1))\n image_width = torch.max(self.image_width.view(-1))\n image_coords = torch.meshgrid(torch.arange(image_height), torch.arange(image_width), indexing=\"ij\")\n image_coords = torch.stack(image_coords, dim=-1) + pixel_offset # stored as (y, x) coordinates\n else:\n image_height = self.image_height[index].item()\n image_width = self.image_width[index].item()\n image_coords = torch.meshgrid(torch.arange(image_height), torch.arange(image_width), indexing=\"ij\")\n image_coords = torch.stack(image_coords, dim=-1) + pixel_offset # stored as (y, x) coordinates\n return image_coords\n\n def generate_rays( # pylint: disable=too-many-statements\n self,\n camera_indices: Union[TensorType[\"num_rays\":..., \"num_cameras_batch_dims\"], int],\n coords: Optional[TensorType[\"num_rays\":..., 2]] = None,\n camera_opt_to_camera: Optional[TensorType[\"num_rays\":..., 3, 4]] = None,\n distortion_params_delta: Optional[TensorType[\"num_rays\":..., 6]] = None,\n keep_shape: Optional[bool] = None,\n disable_distortion: bool = False,\n ) -> RayBundle:\n \"\"\"Generates rays for the given camera indices.\n\n This function will standardize the input arguments and then call the _generate_rays_from_coords function\n to generate the rays. Our goal is to parse the arguments and then get them into the right shape:\n - camera_indices: (num_rays:..., num_cameras_batch_dims)\n - coords: (num_rays:..., 2)\n - camera_opt_to_camera: (num_rays:..., 3, 4) or None\n - distortion_params_delta: (num_rays:..., 6) or None\n\n Read the docstring for _generate_rays_from_coords for more information on how we generate the rays\n after we have standardized the arguments.\n\n We are only concerned about different combinations of camera_indices and coords matrices, and the following\n are the 4 cases we have to deal with:\n 1. isinstance(camera_indices, int) and coords == None\n - In this case we broadcast our camera_indices / coords shape (h, w, 1 / 2 respectively)\n 2. isinstance(camera_indices, int) and coords != None\n - In this case, we broadcast camera_indices to the same batch dim as coords\n 3. not isinstance(camera_indices, int) and coords == None\n - In this case, we will need to set coords so that it is of shape (h, w, num_rays, 2), and broadcast\n all our other args to match the new definition of num_rays := (h, w) + num_rays\n 4. not isinstance(camera_indices, int) and coords != None\n - In this case, we have nothing to do, only check that the arguments are of the correct shape\n\n There is one more edge case we need to be careful with: when we have \"jagged cameras\" (ie: different heights\n and widths for each camera). This isn't problematic when we specify coords, since coords is already a tensor.\n When coords == None (ie: when we render out the whole image associated with this camera), we run into problems\n since there's no way to stack each coordinate map as all coordinate maps are all different shapes. In this case,\n we will need to flatten each individual coordinate map and concatenate them, giving us only one batch dimension,\n regaurdless of the number of prepended extra batch dimensions in the camera_indices tensor.\n\n\n Args:\n camera_indices: Camera indices of the flattened cameras object to generate rays for.\n coords: Coordinates of the pixels to generate rays for. If None, the full image will be rendered.\n camera_opt_to_camera: Optional transform for the camera to world matrices.\n distortion_params_delta: Optional delta for the distortion parameters.\n keep_shape: If None, then we default to the regular behavior of flattening if cameras is jagged, otherwise\n keeping dimensions. If False, we flatten at the end. If True, then we keep the shape of the\n camera_indices and coords tensors (if we can).\n disable_distortion: If True, disables distortion.\n\n Returns:\n Rays for the given camera indices and coords.\n \"\"\"\n # Check the argument types to make sure they're valid and all shaped correctly\n assert isinstance(camera_indices, (torch.Tensor, int)), \"camera_indices must be a tensor or int\"\n assert coords is None or isinstance(coords, torch.Tensor), \"coords must be a tensor or None\"\n assert camera_opt_to_camera is None or isinstance(camera_opt_to_camera, torch.Tensor)\n assert distortion_params_delta is None or isinstance(distortion_params_delta, torch.Tensor)\n if isinstance(camera_indices, torch.Tensor) and isinstance(coords, torch.Tensor):\n num_rays_shape = camera_indices.shape[:-1]\n errormsg = \"Batch dims of inputs must match when inputs are all tensors\"\n assert coords.shape[:-1] == num_rays_shape, errormsg\n assert camera_opt_to_camera is None or camera_opt_to_camera.shape[:-2] == num_rays_shape, errormsg\n assert distortion_params_delta is None or distortion_params_delta.shape[:-1] == num_rays_shape, errormsg\n\n # If zero dimensional, we need to unsqueeze to get a batch dimension and then squeeze later\n if not self.shape:\n cameras = self.reshape((1,))\n assert torch.all(\n torch.tensor(camera_indices == 0) if isinstance(camera_indices, int) else camera_indices == 0\n ), \"Can only index into single camera with no batch dimensions if index is zero\"\n else:\n cameras = self\n\n # If the camera indices are an int, then we need to make sure that the camera batch is 1D\n if isinstance(camera_indices, int):\n assert (\n len(cameras.shape) == 1\n ), \"camera_indices must be a tensor if cameras are batched with more than 1 batch dimension\"\n camera_indices = torch.tensor([camera_indices], device=cameras.device)\n\n assert camera_indices.shape[-1] == len(\n cameras.shape\n ), \"camera_indices must have shape (num_rays:..., num_cameras_batch_dims)\"\n\n # If keep_shape is True, then we need to make sure that the camera indices in question\n # are all the same height and width and can actually be batched while maintaining the image\n # shape\n if keep_shape is True:\n assert torch.all(cameras.height[camera_indices] == cameras.height[camera_indices[0]]) and torch.all(\n cameras.width[camera_indices] == cameras.width[camera_indices[0]]\n ), \"Can only keep shape if all cameras have the same height and width\"\n\n # If the cameras don't all have same height / width, if coords is not none, we will need to generate\n # a flat list of coords for each camera and then concatenate otherwise our rays will be jagged.\n # Camera indices, camera_opt, and distortion will also need to be broadcasted accordingly which is non-trivial\n if cameras.is_jagged and coords is None and (keep_shape is None or keep_shape is False):\n index_dim = camera_indices.shape[-1]\n camera_indices = camera_indices.reshape(-1, index_dim)\n _coords = [cameras.get_image_coords(index=tuple(index)).reshape(-1, 2) for index in camera_indices]\n camera_indices = torch.cat(\n [index.unsqueeze(0).repeat(coords.shape[0], 1) for index, coords in zip(camera_indices, _coords)],\n )\n coords = torch.cat(_coords, dim=0)\n assert coords.shape[0] == camera_indices.shape[0]\n # Need to get the coords of each indexed camera and flatten all coordinate maps and concatenate them\n\n # The case where we aren't jagged && keep_shape (since otherwise coords is already set) and coords\n # is None. In this case we append (h, w) to the num_rays dimensions for all tensors. In this case,\n # each image in camera_indices has to have the same shape since otherwise we would have error'd when\n # we checked keep_shape is valid or we aren't jagged.\n if coords is None:\n index_dim = camera_indices.shape[-1]\n index = camera_indices.reshape(-1, index_dim)[0]\n coords: torch.Tensor = cameras.get_image_coords(index=tuple(index)) # (h, w, 2)\n coords = coords.reshape(coords.shape[:2] + (1,) * len(camera_indices.shape[:-1]) + (2,)) # (h, w, 1..., 2)\n coords = coords.expand(coords.shape[:2] + camera_indices.shape[:-1] + (2,)) # (h, w, num_rays, 2)\n camera_opt_to_camera = ( # (h, w, num_rays, 3, 4) or None\n camera_opt_to_camera.broadcast_to(coords.shape[:-1] + (3, 4))\n if camera_opt_to_camera is not None\n else None\n )\n distortion_params_delta = ( # (h, w, num_rays, 6) or None\n distortion_params_delta.broadcast_to(coords.shape[:-1] + (6,))\n if distortion_params_delta is not None\n else None\n )\n\n # If camera indices was an int or coords was none, we need to broadcast our indices along batch dims\n camera_indices = camera_indices.broadcast_to(coords.shape[:-1] + (len(cameras.shape),)).to(torch.long)\n\n # Checking our tensors have been standardized\n assert isinstance(coords, torch.Tensor) and isinstance(camera_indices, torch.Tensor)\n assert camera_indices.shape[-1] == len(cameras.shape)\n assert camera_opt_to_camera is None or camera_opt_to_camera.shape[:-2] == coords.shape[:-1]\n assert distortion_params_delta is None or distortion_params_delta.shape[:-1] == coords.shape[:-1]\n\n # This will do the actual work of generating the rays now that we have standardized the inputs\n # raybundle.shape == (num_rays) when done\n # pylint: disable=protected-access\n raybundle = cameras._generate_rays_from_coords(\n camera_indices, coords, camera_opt_to_camera, distortion_params_delta, disable_distortion=disable_distortion\n )\n\n # If we have mandated that we don't keep the shape, then we flatten\n if keep_shape is False:\n raybundle = raybundle.flatten()\n\n # TODO: We should have to squeeze the last dimension here if we started with zero batch dims, but never have to,\n # so there might be a rogue squeeze happening somewhere, and this may cause some unintended behaviour\n # that we haven't caught yet with tests\n return raybundle\n\n # pylint: disable=too-many-statements\n def _generate_rays_from_coords(\n self,\n camera_indices: TensorType[\"num_rays\":..., \"num_cameras_batch_dims\"],\n coords: TensorType[\"num_rays\":..., 2],\n camera_opt_to_camera: Optional[TensorType[\"num_rays\":..., 3, 4]] = None,\n distortion_params_delta: Optional[TensorType[\"num_rays\":..., 6]] = None,\n disable_distortion: bool = False,\n ) -> RayBundle:\n \"\"\"Generates rays for the given camera indices and coords where self isn't jagged\n\n This is a fairly complex function, so let's break this down slowly.\n\n Shapes involved:\n - num_rays: This is your output raybundle shape. It dictates the number and shape of the rays generated\n - num_cameras_batch_dims: This is the number of dimensions of our camera\n\n Args:\n camera_indices: Camera indices of the flattened cameras object to generate rays for.\n The shape of this is such that indexing into camera_indices[\"num_rays\":...] will return the\n index into each batch dimension of the camera in order to get the correct camera specified by\n \"num_rays\".\n Example:\n >>> cameras = Cameras(...)\n >>> cameras.shape\n (2, 3, 4)\n >>> camera_indices = torch.tensor([0, 0, 0]) # We need an axis of length 3 since cameras.ndim == 3\n >>> camera_indices.shape\n (3,)\n >>> coords = torch.tensor([1,1])\n >>> coords.shape\n (2,)\n >>> out_rays = cameras.generate_rays(camera_indices=camera_indices, coords = coords)\n # This will generate a RayBundle with a single ray for the\n # camera at cameras[0,0,0] at image coordinates (1,1), so out_rays.shape == ()\n >>> out_rays.shape\n ()\n >>> camera_indices = torch.tensor([[0,0,0]])\n >>> camera_indices.shape\n (1, 3)\n >>> coords = torch.tensor([[1,1]])\n >>> coords.shape\n (1, 2)\n >>> out_rays = cameras.generate_rays(camera_indices=camera_indices, coords = coords)\n # This will generate a RayBundle with a single ray for the\n # camera at cameras[0,0,0] at point (1,1), so out_rays.shape == (1,)\n # since we added an extra dimension in front of camera_indices\n >>> out_rays.shape\n (1,)\n\n If you want more examples, check tests/cameras/test_cameras and the function check_generate_rays_shape\n\n The bottom line is that for camera_indices: (num_rays:..., num_cameras_batch_dims), num_rays is the\n output shape and if you index into the output RayBundle with some indices [i:...], if you index into\n camera_indices with camera_indices[i:...] as well, you will get a 1D tensor containing the batch\n indices into the original cameras object corresponding to that ray (ie: you will get the camera\n from our batched cameras corresponding to the ray at RayBundle[i:...]).\n\n coords: Coordinates of the pixels to generate rays for. If None, the full image will be rendered, meaning\n height and width get prepended to the num_rays dimensions. Indexing into coords with [i:...] will\n get you the image coordinates [x, y] of that specific ray located at output RayBundle[i:...].\n\n camera_opt_to_camera: Optional transform for the camera to world matrices.\n In terms of shape, it follows the same rules as coords, but indexing into it with [i:...] gets you\n the 2D camera to world transform matrix for the camera optimization at RayBundle[i:...].\n\n distortion_params_delta: Optional delta for the distortion parameters.\n In terms of shape, it follows the same rules as coords, but indexing into it with [i:...] gets you\n the 1D tensor with the 6 distortion parameters for the camera optimization at RayBundle[i:...].\n\n disable_distortion: If True, disables distortion.\n\n Returns:\n Rays for the given camera indices and coords. RayBundle.shape == num_rays\n \"\"\"\n # Make sure we're on the right devices\n camera_indices = camera_indices.to(self.device)\n coords = coords.to(self.device)\n\n # Checking to make sure everything is of the right shape and type\n num_rays_shape = camera_indices.shape[:-1]\n assert camera_indices.shape == num_rays_shape + (self.ndim,)\n assert coords.shape == num_rays_shape + (2,)\n assert coords.shape[-1] == 2\n assert camera_opt_to_camera is None or camera_opt_to_camera.shape == num_rays_shape + (3, 4)\n assert distortion_params_delta is None or distortion_params_delta.shape == num_rays_shape + (6,)\n\n # Here, we've broken our indices down along the num_cameras_batch_dims dimension allowing us to index by all\n # of our output rays at each dimension of our cameras object\n true_indices = [camera_indices[..., i] for i in range(camera_indices.shape[-1])]\n\n # Get all our focal lengths, principal points and make sure they are the right shapes\n y = coords[..., 0] # (num_rays,) get rid of the last dimension\n x = coords[..., 1] # (num_rays,) get rid of the last dimension\n fx, fy = self.fx[true_indices].squeeze(-1), self.fy[true_indices].squeeze(-1) # (num_rays,)\n cx, cy = self.cx[true_indices].squeeze(-1), self.cy[true_indices].squeeze(-1) # (num_rays,)\n assert (\n y.shape == num_rays_shape\n and x.shape == num_rays_shape\n and fx.shape == num_rays_shape\n and fy.shape == num_rays_shape\n and cx.shape == num_rays_shape\n and cy.shape == num_rays_shape\n ), (\n str(num_rays_shape)\n + str(y.shape)\n + str(x.shape)\n + str(fx.shape)\n + str(fy.shape)\n + str(cx.shape)\n + str(cy.shape)\n )\n\n # Get our image coordinates and image coordinates offset by 1 (offsets used for dx, dy calculations)\n # Also make sure the shapes are correct\n coord = torch.stack([(x - cx) / fx, -(y - cy) / fy], -1) # (num_rays, 2)\n coord_x_offset = torch.stack([(x - cx + 1) / fx, -(y - cy) / fy], -1) # (num_rays, 2)\n coord_y_offset = torch.stack([(x - cx) / fx, -(y - cy + 1) / fy], -1) # (num_rays, 2)\n assert (\n coord.shape == num_rays_shape + (2,)\n and coord_x_offset.shape == num_rays_shape + (2,)\n and coord_y_offset.shape == num_rays_shape + (2,)\n )\n\n # Stack image coordinates and image coordinates offset by 1, check shapes too\n coord_stack = torch.stack([coord, coord_x_offset, coord_y_offset], dim=0) # (3, num_rays, 2)\n assert coord_stack.shape == (3,) + num_rays_shape + (2,)\n\n # Undistorts our images according to our distortion parameters\n if not disable_distortion:\n distortion_params = None\n if self.distortion_params is not None:\n distortion_params = self.distortion_params[true_indices]\n if distortion_params_delta is not None:\n distortion_params = distortion_params + distortion_params_delta\n elif distortion_params_delta is not None:\n distortion_params = distortion_params_delta\n\n # Do not apply distortion for equirectangular images\n if distortion_params is not None:\n mask = (self.camera_type[true_indices] != CameraType.EQUIRECTANGULAR.value).squeeze(-1) # (num_rays)\n coord_mask = torch.stack([mask, mask, mask], dim=0)\n if mask.any():\n coord_stack[coord_mask, :] = camera_utils.radial_and_tangential_undistort(\n coord_stack[coord_mask, :].reshape(3, -1, 2),\n distortion_params[mask, :],\n ).reshape(-1, 2)\n\n # Make sure after we have undistorted our images, the shapes are still correct\n assert coord_stack.shape == (3,) + num_rays_shape + (2,)\n\n # Gets our directions for all our rays in camera coordinates and checks shapes at the end\n # Here, directions_stack is of shape (3, num_rays, 3)\n # directions_stack[0] is the direction for ray in camera coordinates\n # directions_stack[1] is the direction for ray in camera coordinates offset by 1 in x\n # directions_stack[2] is the direction for ray in camera coordinates offset by 1 in y\n cam_types = torch.unique(self.camera_type, sorted=False)\n directions_stack = torch.empty((3,) + num_rays_shape + (3,), device=self.device)\n if CameraType.PERSPECTIVE.value in cam_types:\n mask = (self.camera_type[true_indices] == CameraType.PERSPECTIVE.value).squeeze(-1) # (num_rays)\n mask = torch.stack([mask, mask, mask], dim=0)\n directions_stack[..., 0][mask] = torch.masked_select(coord_stack[..., 0], mask).float()\n directions_stack[..., 1][mask] = torch.masked_select(coord_stack[..., 1], mask).float()\n directions_stack[..., 2][mask] = -1.0\n\n if CameraType.FISHEYE.value in cam_types:\n mask = (self.camera_type[true_indices] == CameraType.FISHEYE.value).squeeze(-1) # (num_rays)\n mask = torch.stack([mask, mask, mask], dim=0)\n\n theta = torch.sqrt(torch.sum(coord_stack**2, dim=-1))\n theta = torch.clip(theta, 0.0, math.pi)\n\n sin_theta = torch.sin(theta)\n\n directions_stack[..., 0][mask] = torch.masked_select(coord_stack[..., 0] * sin_theta / theta, mask).float()\n directions_stack[..., 1][mask] = torch.masked_select(coord_stack[..., 1] * sin_theta / theta, mask).float()\n directions_stack[..., 2][mask] = -torch.masked_select(torch.cos(theta), mask)\n\n if CameraType.EQUIRECTANGULAR.value in cam_types:\n mask = (self.camera_type[true_indices] == CameraType.EQUIRECTANGULAR.value).squeeze(-1) # (num_rays)\n mask = torch.stack([mask, mask, mask], dim=0)\n\n # For equirect, fx = fy = height = width/2\n # Then coord[..., 0] goes from -1 to 1 and coord[..., 1] goes from -1/2 to 1/2\n theta = -torch.pi * coord_stack[..., 0] # minus sign for right-handed\n phi = torch.pi * (0.5 - coord_stack[..., 1])\n # use spherical in local camera coordinates (+y up, x=0 and z<0 is theta=0)\n directions_stack[..., 0][mask] = torch.masked_select(-torch.sin(theta) * torch.sin(phi), mask).float()\n directions_stack[..., 1][mask] = torch.masked_select(torch.cos(phi), mask).float()\n directions_stack[..., 2][mask] = torch.masked_select(-torch.cos(theta) * torch.sin(phi), mask).float()\n\n for value in cam_types:\n if value not in [CameraType.PERSPECTIVE.value, CameraType.FISHEYE.value, CameraType.EQUIRECTANGULAR.value]:\n raise ValueError(f\"Camera type {value} not supported.\")\n\n assert directions_stack.shape == (3,) + num_rays_shape + (3,)\n\n c2w = self.camera_to_worlds[true_indices]\n assert c2w.shape == num_rays_shape + (3, 4)\n\n if camera_opt_to_camera is not None:\n c2w = pose_utils.multiply(c2w, camera_opt_to_camera)\n rotation = c2w[..., :3, :3] # (..., 3, 3)\n assert rotation.shape == num_rays_shape + (3, 3)\n\n directions_stack = torch.sum(\n directions_stack[..., None, :] * rotation, dim=-1\n ) # (..., 1, 3) * (..., 3, 3) -> (..., 3)\n\n directions_norm = torch.norm(directions_stack, dim=-1, keepdim=True)\n directions_norm = directions_norm[0]\n\n directions_stack = normalize(directions_stack, dim=-1)\n assert directions_stack.shape == (3,) + num_rays_shape + (3,)\n\n origins = c2w[..., :3, 3] # (..., 3)\n assert origins.shape == num_rays_shape + (3,)\n\n directions = directions_stack[0]\n assert directions.shape == num_rays_shape + (3,)\n\n # norms of the vector going between adjacent coords, giving us dx and dy per output ray\n dx = torch.sqrt(torch.sum((directions - directions_stack[1]) ** 2, dim=-1)) # (\"num_rays\":...,)\n dy = torch.sqrt(torch.sum((directions - directions_stack[2]) ** 2, dim=-1)) # (\"num_rays\":...,)\n assert dx.shape == num_rays_shape and dy.shape == num_rays_shape\n\n pixel_area = (dx * dy)[..., None] # (\"num_rays\":..., 1)\n assert pixel_area.shape == num_rays_shape + (1,)\n\n times = self.times[camera_indices, 0] if self.times is not None else None\n\n\n return RayBundle(\n origins=origins,\n directions=directions,\n pixel_area=pixel_area,\n camera_indices=camera_indices,\n directions_norm=directions_norm,\n times=times,\n probes=self.probe,\n )\n\n def to_json(\n self, camera_idx: int, image: Optional[TensorType[\"height\", \"width\", 2]] = None, max_size: Optional[int] = None\n ) -> Dict:\n \"\"\"Convert a camera to a json dictionary.\n\n Args:\n camera_idx: Index of the camera to convert.\n image: An image in range [0, 1] that is encoded to a base64 string.\n max_size: Max size to resize the image to if present.\n\n Returns:\n A JSON representation of the camera\n \"\"\"\n flattened = self.flatten()\n json_ = {\n \"type\": \"PinholeCamera\",\n \"cx\": flattened[camera_idx].cx.item(),\n \"cy\": flattened[camera_idx].cy.item(),\n \"fx\": flattened[camera_idx].fx.item(),\n \"fy\": flattened[camera_idx].fy.item(),\n \"camera_to_world\": self.camera_to_worlds[camera_idx].tolist(),\n \"camera_index\": camera_idx,\n \"times\": flattened[camera_idx].times.item() if self.times is not None else None,\n }\n if image is not None:\n image_uint8 = (image * 255).detach().type(torch.uint8)\n if max_size is not None:\n image_uint8 = image_uint8.permute(2, 0, 1)\n image_uint8 = torchvision.transforms.functional.resize(image_uint8, max_size) # type: ignore\n image_uint8 = image_uint8.permute(1, 2, 0)\n image_uint8 = image_uint8.cpu().numpy()\n data = cv2.imencode(\".jpg\", image_uint8)[1].tobytes()\n json_[\"image\"] = str(\"data:image/jpeg;base64,\" + base64.b64encode(data).decode(\"ascii\"))\n return json_\n\n def get_intrinsics_matrices(self) -> TensorType[\"num_cameras\":..., 3, 3]:\n \"\"\"Returns the intrinsic matrices for each camera.\n\n Returns:\n Pinhole camera intrinsics matrices\n \"\"\"\n K = torch.zeros((*self.shape, 3, 3), dtype=torch.float32)\n K[..., 0, 0] = self.fx.squeeze(-1)\n K[..., 1, 1] = self.fy.squeeze(-1)\n K[..., 0, 2] = self.cx.squeeze(-1)\n K[..., 1, 2] = self.cy.squeeze(-1)\n K[..., 2, 2] = 1.0\n return K\n\n def rescale_output_resolution(\n self,\n scaling_factor: Union[TensorType[\"num_cameras\":...], TensorType[\"num_cameras\":..., 1], float, int],\n round_hw=False,\n ) -> None:\n \"\"\"Rescale the output resolution of the cameras.\n\n Args:\n scaling_factor: Scaling factor to apply to the output resolution.\n round_hw: Whether to round the height and width to the nearest integer.\n \"\"\"\n if isinstance(scaling_factor, (float, int)):\n scaling_factor = torch.tensor([scaling_factor]).to(self.device).broadcast_to((self.cx.shape))\n elif isinstance(scaling_factor, torch.Tensor) and scaling_factor.shape == self.shape:\n scaling_factor = scaling_factor.unsqueeze(-1)\n elif isinstance(scaling_factor, torch.Tensor) and scaling_factor.shape == (*self.shape, 1):\n pass\n else:\n raise ValueError(\n f\"Scaling factor must be a float, int, or a tensor of shape {self.shape} or {(*self.shape, 1)}.\"\n )\n\n self.fx = self.fx * scaling_factor\n self.fy = self.fy * scaling_factor\n self.cx = self.cx * scaling_factor\n self.cy = self.cy * scaling_factor\n if not round_hw:\n self.height = (self.height * scaling_factor).to(torch.int64)\n self.width = (self.width * scaling_factor).to(torch.int64)\n else:\n self.height = torch.floor(self.height * scaling_factor + 0.5).to(torch.int64)\n self.width = torch.floor(self.width * scaling_factor + 0.5).to(torch.int64)\n\n def get_plotly(self, camera_group):\n\n # define local necssary coordinates for plotting\n num_cameras = self.camera_to_worlds.shape[0]\n _cam_center_c = np.array([[.0, .0, .0]]).repeat(num_cameras, axis=0)\n _cam_forward_c = np.array([[.0, .0, -1.0]]).repeat(num_cameras, axis=0)\n _cam_up_c = np.array([[.0, 1.0, .0]]).repeat(num_cameras, axis=0)\n _cam_right_c = np.array([[1.0, .0, .0]]).repeat(num_cameras, axis=0)\n\n _pyramid_width = self.width.cpu().numpy() / self.fx.cpu().numpy()\n _pyramid_height = self.height.cpu().numpy() / self.fy.cpu().numpy()\n\n _cam_pyramid_ur = np.concatenate([_pyramid_width/2, _pyramid_height/2, -np.ones_like(_pyramid_width)], axis=-1)\n _cam_pyramid_dr = np.concatenate([_pyramid_width/2, -_pyramid_height/2, -np.ones_like(_pyramid_width)], axis=-1)\n _cam_pyramid_ul = np.concatenate([-_pyramid_width/2, _pyramid_height/2, -np.ones_like(_pyramid_width)], axis=-1)\n _cam_pyramid_dl = np.concatenate([-_pyramid_width/2, -_pyramid_height/2, -np.ones_like(_pyramid_width)], axis=-1)\n\n _local_coordinates = {\n 'center': _cam_center_c, \n 'forward': _cam_forward_c, \n 'up': _cam_up_c, \n 'right': _cam_right_c, \n 'pyramid_ur': _cam_pyramid_ur, \n 'pyramid_dr': _cam_pyramid_dr, \n 'pyramid_ul': _cam_pyramid_ul, \n 'pyramid_dl': _cam_pyramid_dl, \n }\n\n # transform it into world coordinates\n data = {}\n for k in _local_coordinates.keys():\n _local_coor_homo = np.concatenate([_local_coordinates[k].reshape(-1, 3) * plotly_camera_scale, np.ones((num_cameras, 1))], axis=-1) # num_cam, 4\n _cw = self.camera_to_worlds.cpu().numpy() # num_cam, 3, 4\n\n _homo = np.einsum('ijk,ik->ij', _cw, _local_coor_homo) # num_cam, 3\n data[k] = _homo[:, :3]\n\n plot_data = plot_camera_components(data, image_list=self.image_filenames, camera_group=camera_group)\n \n if isinstance(plot_data, list):\n return plot_data\n else:\n return [plot_data]" }, { "identifier": "RayBundle", "path": "nerfstudio/cameras/rays.py", "snippet": "class RayBundle(TensorDataclass):\n \"\"\"A bundle of ray parameters.\"\"\"\n\n # TODO(ethan): make sure the sizes with ... are correct\n origins: TensorType[..., 3]\n \"\"\"Ray origins (XYZ)\"\"\"\n directions: TensorType[..., 3]\n \"\"\"Unit ray direction vector\"\"\"\n pixel_area: TensorType[..., 1]\n \"\"\"Projected area of pixel a distance 1 away from origin\"\"\"\n directions_norm: Optional[TensorType[..., 1]] = None\n \"\"\"Norm of ray direction vector before normalization\"\"\"\n camera_indices: Optional[TensorType[..., 1]] = None\n \"\"\"Camera indices\"\"\"\n nears: Optional[TensorType[..., 1]] = None\n \"\"\"Distance along ray to start sampling\"\"\"\n fars: Optional[TensorType[..., 1]] = None\n \"\"\"Rays Distance along ray to stop sampling\"\"\"\n metadata: Optional[Dict[str, TensorType[\"num_rays\", \"latent_dims\"]]] = None\n \"\"\"Additional metadata or data needed for interpolation, will mimic shape of rays\"\"\"\n times: Optional[TensorType[..., 1]] = None\n \"\"\"Times at which rays are sampled\"\"\"\n probes: Optional[Probes] = None\n \"\"\"Probe Cameras Object. This object doesn't follow the same shape pattern as the other fields. \n Lazy broadcasting is used for preventing CUDA memory overflow. \"\"\"\n\n def set_camera_indices(self, camera_index: int) -> None:\n \"\"\"Sets all of the the camera indices to a specific camera index.\n\n Args:\n camera_index: Camera index.\n \"\"\"\n self.camera_indices = torch.ones_like(self.origins[..., 0:1]).long() * camera_index\n\n def __len__(self):\n num_rays = torch.numel(self.origins) // self.origins.shape[-1]\n return num_rays\n\n def sample(self, num_rays: int) -> \"RayBundle\":\n \"\"\"Returns a RayBundle as a subset of rays.\n\n Args:\n num_rays: Number of rays in output RayBundle\n\n Returns:\n RayBundle with subset of rays.\n \"\"\"\n assert num_rays <= len(self)\n indices = random.sample(range(len(self)), k=num_rays)\n return self[indices]\n\n def get_row_major_sliced_ray_bundle(self, start_idx: int, end_idx: int) -> \"RayBundle\":\n \"\"\"Flattens RayBundle and extracts chunk given start and end indicies.\n\n Args:\n start_idx: Start index of RayBundle chunk.\n end_idx: End index of RayBundle chunk.\n\n Returns:\n Flattened RayBundle with end_idx-start_idx rays.\n\n \"\"\"\n return self.flatten()[start_idx:end_idx]\n\n def get_ray_samples(\n self,\n bin_starts: TensorType[\"bs\":..., \"num_samples\", 1],\n bin_ends: TensorType[\"bs\":..., \"num_samples\", 1],\n spacing_starts: Optional[TensorType[\"bs\":..., \"num_samples\", 1]] = None,\n spacing_ends: Optional[TensorType[\"bs\":..., \"num_samples\", 1]] = None,\n spacing_to_euclidean_fn: Optional[Callable] = None,\n ) -> RaySamples:\n \"\"\"Produces samples for each ray by projection points along the ray direction. Currently samples uniformly.\n\n Args:\n bin_starts: Distance from origin to start of bin. (in Euclidean space)\n bin_ends: Distance from origin to end of bin. (in Euclidean space)\n spacing_starts: start point in normalized space. [0, 1]\n spacing_ends: end point in normalized space. [0, 1]\n\n Returns:\n Samples projected along ray.\n \"\"\"\n deltas = bin_ends - bin_starts\n if self.camera_indices is not None:\n camera_indices = self.camera_indices[..., None]\n else:\n camera_indices = None\n\n shaped_raybundle_fields = self[..., None]\n\n frustums = Frustums(\n origins=shaped_raybundle_fields.origins, # [..., 1, 3]\n directions=shaped_raybundle_fields.directions, # [..., 1, 3]\n starts=bin_starts, # [..., num_samples, 1]\n ends=bin_ends, # [..., num_samples, 1]\n pixel_area=shaped_raybundle_fields.pixel_area, # [..., 1, 1]\n )\n\n ray_samples = RaySamples(\n frustums=frustums,\n camera_indices=camera_indices, # [..., 1, 1]\n deltas=deltas, # [..., num_samples, 1]\n spacing_starts=spacing_starts, # [..., num_samples, 1]\n spacing_ends=spacing_ends, # [..., num_samples, 1]\n spacing_to_euclidean_fn=spacing_to_euclidean_fn,\n metadata=shaped_raybundle_fields.metadata,\n times=None if self.times is None else self.times[..., None], # [..., 1, 1]\n probes=self.probes, # special class, not following the same shape pattern\n )\n\n return ray_samples" }, { "identifier": "base_config", "path": "nerfstudio/configs/base_config.py", "snippet": "CONSOLE = Console(width=120)\nclass PrintableConfig: # pylint: disable=too-few-public-methods\nclass InstantiateConfig(PrintableConfig): # pylint: disable=too-few-public-methods\nclass MachineConfig(PrintableConfig):\nclass LocalWriterConfig(InstantiateConfig):\nclass LoggingConfig(PrintableConfig):\nclass TrainerConfig(PrintableConfig):\nclass ViewerConfig(PrintableConfig):\nclass Config(PrintableConfig):\n def __str__(self):\n def setup(self, **kwargs) -> Any:\n def setup(self, banner_messages: Optional[List[str]] = None, **kwargs) -> Any:\n def is_viewer_enabled(self) -> bool:\n def is_wandb_enabled(self) -> bool:\n def is_tensorboard_enabled(self) -> bool:\n def set_timestamp(self) -> None:\n def set_experiment_name(self) -> None:\n def get_base_dir(self) -> Path:\n def get_checkpoint_dir(self) -> Path:\n def print_to_terminal(self) -> None:\n def save_config(self) -> None:" }, { "identifier": "InputDataset", "path": "nerfstudio/data/datasets/base_dataset.py", "snippet": "class InputDataset(Dataset):\n \"\"\"Dataset that returns images.\n\n Args:\n dataparser_outputs: description of where and how to read input images.\n scale_factor: The scaling factor for the dataparser outputs\n \"\"\"\n\n def __init__(self, dataparser_outputs: DataparserOutputs, scale_factor: float = 1.0):\n super().__init__()\n self._dataparser_outputs = dataparser_outputs\n self.has_masks = dataparser_outputs.mask_filenames is not None\n self.scale_factor = scale_factor\n self.scene_box = deepcopy(dataparser_outputs.scene_box)\n self.metadata = deepcopy(dataparser_outputs.metadata)\n self.cameras = deepcopy(dataparser_outputs.cameras)\n self.cameras.rescale_output_resolution(scaling_factor=scale_factor)\n self.image_cache = {}\n\n def __len__(self):\n return len(self._dataparser_outputs.image_filenames)\n\n def get_numpy_image(self, image_idx: int) -> npt.NDArray[np.uint8]:\n \"\"\"Returns the image of shape (H, W, 3 or 4).\n\n Args:\n image_idx: The image index in the dataset.\n \"\"\"\n image_filename = self._dataparser_outputs.image_filenames[image_idx]\n pil_image = Image.open(image_filename)\n if self.scale_factor != 1.0:\n width, height = pil_image.size\n newsize = (int(width * self.scale_factor), int(height * self.scale_factor))\n pil_image = pil_image.resize(newsize, resample=Image.BILINEAR)\n image = np.array(pil_image, dtype=\"uint8\") # shape is (h, w, 3 or 4)\n # mask_filename = str(image_filename).replace(\"dense/images\", \"masks\").replace(\".jpg\", \".npy\")\n # mask = np.load(mask_filename)\n # image = image * mask[..., None]\n\n assert len(image.shape) == 3\n assert image.dtype == np.uint8\n assert image.shape[2] in [3, 4], f\"Image shape of {image.shape} is in correct.\"\n return image\n\n def get_image(self, image_idx: int) -> TensorType[\"image_height\", \"image_width\", \"num_channels\"]:\n \"\"\"Returns a 3 channel image.\n\n Args:\n image_idx: The image index in the dataset.\n \"\"\"\n image = torch.from_numpy(self.get_numpy_image(image_idx).astype(\"float32\") / 255.0)\n if self._dataparser_outputs.alpha_color is not None and image.shape[-1] == 4:\n assert image.shape[-1] == 4\n image = image[:, :, :3] * image[:, :, -1:] + self._dataparser_outputs.alpha_color * (1.0 - image[:, :, -1:])\n else:\n image = image[:, :, :3]\n return image\n\n def get_data(self, image_idx: int) -> Dict:\n \"\"\"Returns the ImageDataset data as a dictionary.\n\n Args:\n image_idx: The image index in the dataset.\n \"\"\"\n if image_idx in self.image_cache:\n image = self.image_cache[image_idx]\n else:\n image = self.get_image(image_idx)\n self.image_cache[image_idx] = image\n\n data = {\"image_idx\": image_idx, 'image_filename': self._dataparser_outputs.image_filenames[image_idx].name}\n data[\"image\"] = image\n for _, data_func_dict in self._dataparser_outputs.additional_inputs.items():\n assert \"func\" in data_func_dict, \"Missing function to process data: specify `func` in `additional_inputs`\"\n func = data_func_dict[\"func\"]\n assert \"kwargs\" in data_func_dict, \"No data to process: specify `kwargs` in `additional_inputs`\"\n data.update(func(image_idx, **data_func_dict[\"kwargs\"]))\n if self.has_masks:\n mask_filepath = self._dataparser_outputs.mask_filenames[image_idx]\n data[\"mask\"] = get_image_mask_tensor_from_path(filepath=mask_filepath, scale_factor=self.scale_factor)\n metadata = self.get_metadata(data)\n data.update(metadata)\n return data\n\n # pylint: disable=no-self-use\n def get_metadata(self, data: Dict) -> Dict:\n \"\"\"Method that can be used to process any additional metadata that may be part of the model inputs.\n\n Args:\n image_idx: The image index in the dataset.\n \"\"\"\n del data\n return {}\n\n def __getitem__(self, image_idx: int) -> Dict:\n data = self.get_data(image_idx)\n return data" }, { "identifier": "Model", "path": "nerfstudio/models/base_model.py", "snippet": "class Model(nn.Module):\n \"\"\"Model class\n Where everything (Fields, Optimizers, Samplers, Visualization, etc) is linked together. This should be\n subclassed for custom NeRF model.\n\n Args:\n config: configuration for instantiating model\n scene_box: dataset scene box\n \"\"\"\n\n config: ModelConfig\n\n def __init__(\n self,\n config: ModelConfig,\n scene_box: SceneBox,\n num_train_data: int,\n world_size: int = 1,\n local_rank: int = 0,\n load_step: int = None, \n **kwargs,\n ) -> None:\n super().__init__()\n self.config = config\n self.scene_box = scene_box\n self.num_train_data = num_train_data\n self.kwargs = kwargs\n self.collider = None\n self.world_size = world_size\n self.local_rank = local_rank\n self.load_step = load_step\n\n self.populate_modules() # populate the modules\n self.callbacks = None\n # to keep track of which device the nn.Module is on\n self.device_indicator_param = nn.Parameter(torch.empty(0))\n\n @property\n def device(self):\n \"\"\"Returns the device that the model is on.\"\"\"\n return self.device_indicator_param.device\n\n def get_training_callbacks( # pylint:disable=no-self-use\n self, training_callback_attributes: TrainingCallbackAttributes # pylint: disable=unused-argument\n ) -> List[TrainingCallback]:\n \"\"\"Returns a list of callbacks that run functions at the specified training iterations.\"\"\"\n return []\n\n def populate_modules(self):\n \"\"\"Set the necessary modules to get the network working.\"\"\"\n # default instantiates optional modules that are common among many networks\n # NOTE: call `super().populate_modules()` in subclasses\n\n if self.config.enable_collider:\n self.collider = NearFarCollider(\n near_plane=self.config.collider_params[\"near_plane\"], far_plane=self.config.collider_params[\"far_plane\"]\n )\n\n @abstractmethod\n def get_param_groups(self) -> Dict[str, List[Parameter]]:\n \"\"\"Obtain the parameter groups for the optimizers\n\n Returns:\n Mapping of different parameter groups\n \"\"\"\n\n @abstractmethod\n def get_outputs(self, ray_bundle: RayBundle) -> Dict[str, torch.Tensor]:\n \"\"\"Takes in a Ray Bundle and returns a dictionary of outputs.\n\n Args:\n ray_bundle: Input bundle of rays. This raybundle should have all the\n needed information to compute the outputs.\n\n Returns:\n Outputs of model. (ie. rendered colors)\n \"\"\"\n\n def forward(self, ray_bundle: RayBundle) -> Dict[str, torch.Tensor]:\n \"\"\"Run forward starting with a ray bundle. This outputs different things depending on the configuration\n of the model and whether or not the batch is provided (whether or not we are training basically)\n\n Args:\n ray_bundle: containing all the information needed to render that ray latents included\n \"\"\"\n\n if self.collider is not None:\n ray_bundle = self.collider(ray_bundle)\n\n return self.get_outputs(ray_bundle)\n\n def get_metrics_dict(self, outputs, batch) -> Dict[str, torch.Tensor]:\n \"\"\"Compute and returns metrics.\n\n Args:\n outputs: the output to compute loss dict to\n batch: ground truth batch corresponding to outputs\n \"\"\"\n # pylint: disable=unused-argument\n # pylint: disable=no-self-use\n return {}\n \n\n @abstractmethod\n def get_loss_dict(self, outputs, batch, metrics_dict=None) -> Dict[str, torch.Tensor]:\n \"\"\"Computes and returns the losses dict.\n\n Args:\n outputs: the output to compute loss dict to\n batch: ground truth batch corresponding to outputs\n metrics_dict: dictionary of metrics, some of which we can use for loss\n \"\"\"\n \n def n_parameters(self):\n return -1.0\n\n @torch.no_grad()\n def get_outputs_for_camera_ray_bundle(self, camera_ray_bundle: RayBundle) -> Dict[str, torch.Tensor]:\n \"\"\"Takes in camera parameters and computes the output of the model.\n\n Args:\n camera_ray_bundle: ray bundle to calculate outputs over\n \"\"\"\n num_rays_per_chunk = self.config.eval_num_rays_per_chunk\n image_height, image_width = camera_ray_bundle.origins.shape[:2]\n num_rays = len(camera_ray_bundle)\n outputs_lists = defaultdict(list)\n for i in range(0, num_rays, num_rays_per_chunk):\n start_idx = i\n end_idx = i + num_rays_per_chunk\n ray_bundle = camera_ray_bundle.get_row_major_sliced_ray_bundle(start_idx, end_idx)\n outputs = self.forward(ray_bundle=ray_bundle)\n for output_name, output in outputs.items(): # type: ignore\n outputs_lists[output_name].append(output)\n outputs = {}\n for output_name, outputs_list in outputs_lists.items():\n if not torch.is_tensor(outputs_list[0]):\n # TODO: handle lists of tensors as well\n continue\n outputs[output_name] = torch.cat(outputs_list).view(image_height, image_width, -1) # type: ignore\n return outputs\n\n @abstractmethod\n def get_image_metrics_and_images(\n self, outputs: Dict[str, torch.Tensor], batch: Dict[str, torch.Tensor]\n ) -> Tuple[Dict[str, float], Dict[str, torch.Tensor]]:\n \"\"\"Writes the test image outputs.\n TODO: This shouldn't return a loss\n\n Args:\n image_idx: Index of the image.\n step: Current step.\n batch: Batch of data.\n outputs: Outputs of the model.\n\n Returns:\n A dictionary of metrics.\n \"\"\"\n\n def load_model(self, loaded_state: Dict[str, Any]) -> None:\n \"\"\"Load the checkpoint from the given path\n\n Args:\n loaded_state: dictionary of pre-trained model states\n \"\"\"\n state = {key.replace(\"module.\", \"\"): value for key, value in loaded_state[\"model\"].items()}\n self.load_state_dict(state) # type: ignore\n \n def customized_save(self, step: int, checkpoint_dir) -> None:\n \"\"\"Call the model's customized save function.\n\n Args:\n step: Current step.\n checkpoint_dir: directory of checkpoint\n \"\"\"\n pass\n\n def customized_load(self, load_step: int, checkpoint_dir) -> None:\n \"\"\"Call the model's customized load function.\n\n Args:\n checkpoint_dir: directory of checkpoint\n \"\"\"\n pass" }, { "identifier": "colormaps", "path": "nerfstudio/utils/colormaps.py", "snippet": "def apply_colormap(image: TensorType[\"bs\":..., 1], cmap=\"viridis\") -> TensorType[\"bs\":..., \"rgb\":3]:\ndef apply_depth_colormap(\n depth: TensorType[\"bs\":..., 1],\n accumulation: Optional[TensorType[\"bs\":..., 1]] = None,\n near_plane: Optional[float] = None,\n far_plane: Optional[float] = None,\n cmap=\"turbo\",\n) -> TensorType[\"bs\":..., \"rgb\":3]:\ndef apply_boolean_colormap(\n image: TensorType[\"bs\":..., 1, bool],\n true_color: TensorType[\"bs\":..., \"rgb\":3] = colors.WHITE,\n false_color: TensorType[\"bs\":..., \"rgb\":3] = colors.BLACK,\n) -> TensorType[\"bs\":..., \"rgb\":3]:" }, { "identifier": "profiler", "path": "nerfstudio/utils/profiler.py", "snippet": "CONSOLE = Console(width=120)\nPROFILER = []\ndef time_function(func: Callable) -> Callable:\n def wrapper(*args, **kwargs):\ndef flush_profiler(config: cfg.LoggingConfig):\ndef setup_profiler(config: cfg.LoggingConfig):\n def __init__(self, config: cfg.LoggingConfig):\n def update_time(self, func_name: str, start_time: float, end_time: float):\n def print_profile(self):\nclass Profiler:" }, { "identifier": "writer", "path": "nerfstudio/utils/writer.py", "snippet": "CONSOLE = Console(width=120)\nEVENT_WRITERS = []\nEVENT_STORAGE = []\nGLOBAL_BUFFER = {}\n ITER_TRAIN_TIME = \"Train Iter (time)\"\n TOTAL_TRAIN_TIME = \"Train Total (time)\"\n ITER_VIS_TIME = \"Viewer Rendering (time)\"\n ETA = \"ETA (time)\"\n TRAIN_RAYS_PER_SEC = \"Train Rays / Sec\"\n TEST_RAYS_PER_SEC = \"Test Rays / Sec\"\n VIS_RAYS_PER_SEC = \"Vis Rays / Sec\"\n CURR_TEST_PSNR = \"Test PSNR\"\n IMAGE = \"write_image\"\n PLOTLY = \"write_plotly\"\n SCALAR = \"write_scalar\"\n DICT = \"write_scalar_dict\"\n CONFIG = \"write_config\"\nclass EventName(enum.Enum):\nclass EventType(enum.Enum):\nclass Writer:\nclass TimeWriter:\nclass WandbWriter(Writer):\nclass TensorboardWriter(Writer):\nclass LocalWriter:\ndef put_image(name, image: TensorType[\"H\", \"W\", \"C\"], step: int):\ndef put_plotly(name: str, figure: Any, step: int = 0):\ndef put_scalar(name: str, scalar: Any, step: int):\ndef put_dict(name: str, scalar_dict: Dict[str, Any], step: int):\ndef put_config(name: str, config_dict: Dict[str, Any], step: int):\ndef put_time(name: str, duration: float, step: int, avg_over_steps: bool = True, update_eta: bool = False):\ndef write_out_storage():\ndef setup_local_writer(config: cfg.LoggingConfig, max_iter: int, banner_messages: Optional[List[str]] = None) -> None:\ndef setup_event_writer(config: cfg.Config, log_dir: Path) -> None:\n def write_image(self, name: str, image: TensorType[\"H\", \"W\", \"C\"], step: int) -> None:\n def write_plotly(self, name: str, figure: Any, step: int) -> None:\n def write_scalar(self, name: str, scalar: Union[float, torch.Tensor], step: int) -> None:\n def write_scalar_dict(self, name: str, scalar_dict: Dict[str, Any], step: int) -> None:\n def __init__(self, writer, name, step=None, write=True):\n def __enter__(self):\n def __exit__(self, *args):\n def __init__(self, log_dir: Path, experiment_name: str):\n def write_image(self, name: str, image: TensorType[\"H\", \"W\", \"C\"], step: int) -> None:\n def write_plotly(self, name: str, figure: Any, step: int) -> None:\n def write_scalar(self, name: str, scalar: Union[float, torch.Tensor], step: int) -> None:\n def write_config(self, name: str, config_dict: Dict[str, Any], step: int):\n def __init__(self, log_dir: Path):\n def write_image(self, name: str, image: TensorType[\"H\", \"W\", \"C\"], step: int) -> None:\n def write_plotly(self, name: str, figure: Any, step: int) -> None:\n def write_scalar(self, name: str, scalar: Union[float, torch.Tensor], step: int) -> None:\n def write_config(self, name: str, config_dict: Dict[str, Any], step: int): # pylint: disable=unused-argument\ndef _cursorup(x: int):\ndef _format_time(seconds):\n def __init__(self, config: cfg.LocalWriterConfig, banner_messages: Optional[List[str]] = None):\n def write_stats_log(self, step: int) -> None:\n def write_config(self, name: str, config_dict: Dict[str, Any], step: int):\n def _consolidate_events(self):\n def _update_header(self, latest_map, new_key):\n def _print_stats(self, latest_map, padding=\" \"):" }, { "identifier": "check_main_thread", "path": "nerfstudio/utils/decorators.py", "snippet": "def check_main_thread(func: Callable) -> Callable:\n \"\"\"Decorator: check if you are on main thread\"\"\"\n\n def wrapper(*args, **kwargs):\n ret = None\n if comms.is_main_process():\n ret = func(*args, **kwargs)\n return ret\n\n return wrapper" }, { "identifier": "decorate_all", "path": "nerfstudio/utils/decorators.py", "snippet": "def decorate_all(decorators: List[Callable]) -> Callable:\n \"\"\"A decorator to decorate all member functions of a class\n\n Args:\n decorators: list of decorators to add to all functions in the class\n \"\"\"\n\n def decorate(cls):\n for attr in cls.__dict__:\n if callable(getattr(cls, attr)) and attr != \"__init__\":\n for decorator in decorators:\n setattr(cls, attr, decorator(getattr(cls, attr)))\n return cls\n\n return decorate" }, { "identifier": "BasicImages", "path": "nerfstudio/utils/images.py", "snippet": "class BasicImages:\n \"\"\"This is a very primitive struct for holding images, especially for when these images\n are of different heights / widths.\n\n The purpose of this is to have a special struct wrapping around a list so that the\n nerfstudio_collate fn and other parts of the code recognise this as a struct to leave alone\n instead of reshaping or concatenating into a single tensor (since this will likely be used\n for cases where we have images of different sizes and shapes).\n\n This only has one batch dimension and will likely be replaced down the line with some\n TensorDataclass alternative that supports arbitrary batches.\n \"\"\"\n\n def __init__(self, images: List):\n assert isinstance(images, List)\n assert not images or isinstance(\n images[0], torch.Tensor\n ), f\"Input should be a list of tensors, not {type(images[0]) if isinstance(images, List) else type(images)}\"\n self.images = images\n\n def to(self, device):\n \"\"\"Move the images to the given device.\"\"\"\n assert isinstance(device, torch.device)\n return BasicImages([image.to(device) for image in self.images])" }, { "identifier": "load_from_json", "path": "nerfstudio/utils/io.py", "snippet": "def load_from_json(filename: Path):\n \"\"\"Load a dictionary from a JSON filename.\n\n Args:\n filename: The filename to load from.\n \"\"\"\n assert filename.suffix == \".json\"\n with open(filename, encoding=\"UTF-8\") as file:\n return json.load(file)" }, { "identifier": "write_to_json", "path": "nerfstudio/utils/io.py", "snippet": "def write_to_json(filename: Path, content: dict):\n \"\"\"Write data to a JSON file.\n\n Args:\n filename: The filename to write to.\n content: The dictionary data to write.\n \"\"\"\n assert filename.suffix == \".json\", \"Filename must have .json extension but got {}\".format(filename)\n with open(filename, \"w\", encoding=\"UTF-8\") as file:\n json.dump(content, file)" }, { "identifier": "GLOBAL_BUFFER", "path": "nerfstudio/utils/writer.py", "snippet": "GLOBAL_BUFFER = {}" }, { "identifier": "EventName", "path": "nerfstudio/utils/writer.py", "snippet": "class EventName(enum.Enum):\n \"\"\"Names of possible events that can be logged via Local Writer for convenience.\n see config/logging/default_logging.yaml\"\"\"\n\n ITER_TRAIN_TIME = \"Train Iter (time)\"\n TOTAL_TRAIN_TIME = \"Train Total (time)\"\n ITER_VIS_TIME = \"Viewer Rendering (time)\"\n ETA = \"ETA (time)\"\n TRAIN_RAYS_PER_SEC = \"Train Rays / Sec\"\n TEST_RAYS_PER_SEC = \"Test Rays / Sec\"\n VIS_RAYS_PER_SEC = \"Vis Rays / Sec\"\n CURR_TEST_PSNR = \"Test PSNR\"" }, { "identifier": "TimeWriter", "path": "nerfstudio/utils/writer.py", "snippet": "class TimeWriter:\n \"\"\"Timer context manager that calculates duration around wrapped functions\"\"\"\n\n def __init__(self, writer, name, step=None, write=True):\n self.writer = writer\n self.name = name\n self.step = step\n self.write = write\n\n self.start: float = 0.0\n self.duration: float = 0.0\n\n def __enter__(self):\n torch.cuda.synchronize()\n self.start = time()\n return self\n\n def __exit__(self, *args):\n torch.cuda.synchronize()\n self.duration = time() - self.start\n update_step = self.step is not None\n if self.write:\n self.writer.put_time(\n name=self.name,\n duration=self.duration,\n step=self.step if update_step else GLOBAL_BUFFER[\"max_iter\"],\n avg_over_steps=update_step,\n update_eta=self.name == EventName.ITER_TRAIN_TIME,\n )" }, { "identifier": "run_viewer_bridge_server_as_subprocess", "path": "nerfstudio/viewer/server/subprocess.py", "snippet": "def run_viewer_bridge_server_as_subprocess(\n websocket_port: int,\n zmq_port: Optional[int] = None,\n ip_address: str = \"127.0.0.1\",\n log_filename: Union[str, None] = None,\n):\n \"\"\"Runs the viewer bridge server as a subprocess.\n\n Args:\n zmq_port: Port to use for the ZMQ server.\n websocket_port: Port to use for the websocket server.\n ip_address: host to connect to\n log_filename: Filename to use for the log file. If None, no log file is created.\n\n Returns:\n None\n \"\"\"\n args = [sys.executable, \"-u\", \"-m\", server.__name__]\n\n # find an available port for zmq\n if zmq_port is None:\n sock = socket.socket()\n sock.bind((\"\", 0))\n zmq_port = sock.getsockname()[1]\n string = f\"Using ZMQ port: {zmq_port}\"\n CONSOLE.print(f\"[bold yellow]{string}\")\n\n args.append(\"--zmq-port\")\n args.append(str(zmq_port))\n args.append(\"--websocket-port\")\n args.append(str(websocket_port))\n args.append(\"--ip-address\")\n args.append(str(ip_address))\n # supress output if no log filename is specified\n logfile = open( # pylint: disable=consider-using-with\n log_filename if log_filename else os.devnull, \"w\", encoding=\"utf8\"\n )\n process = subprocess.Popen( # pylint: disable=consider-using-with\n args, stdout=logfile, stderr=logfile, start_new_session=True\n )\n\n def cleanup(process):\n process.kill()\n process.wait()\n\n def poll_process():\n \"\"\"\n Continually check to see if the viewer bridge server process is still running and has not failed.\n If it fails, alert the user and exit the entire program.\n \"\"\"\n while process.poll() is None:\n time.sleep(0.5)\n string = f\"\\nThe viewer bridge server subprocess failed. Please check the log file {log_filename}.\\n\"\n string += (\n \"You likely have to modify --viewer.zmq-port and/or --viewer.websocket-port in the \"\n \"config to avoid conflicting ports.\\n\"\n )\n string += \"Try modifying --viewer.websocket-port 7007\\n\"\n CONSOLE.print(f\"[bold red]{string}\")\n cleanup(process)\n # This exists the entire program. sys.exit() will only kill the thread that this runs in.\n os.kill(os.getpid(), signal.SIGKILL)\n\n # continually check to see if the process stopped\n t1 = threading.Thread(target=poll_process)\n t1.daemon = True\n t1.start()\n atexit.register(cleanup, process)\n return zmq_port" }, { "identifier": "get_intrinsics_matrix_and_camera_to_world_h", "path": "nerfstudio/viewer/server/utils.py", "snippet": "def get_intrinsics_matrix_and_camera_to_world_h(\n camera_object: Dict[str, Any], image_height: int\n) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Returns the camera intrinsics matrix and the camera to world homogeneous matrix.\n\n Args:\n camera_object: a Camera object.\n image_size: the size of the image (height, width)\n \"\"\"\n # intrinsics\n fov = camera_object[\"fov\"]\n aspect = camera_object[\"aspect\"]\n image_width = aspect * image_height\n pp_w = image_width / 2.0\n pp_h = image_height / 2.0\n focal_length = three_js_perspective_camera_focal_length(fov, image_height)\n intrinsics_matrix = torch.tensor([[focal_length, 0, pp_w], [0, focal_length, pp_h], [0, 0, 1]]).float()\n\n # extrinsics\n camera_to_world_h = torch.tensor(get_chunks(camera_object[\"matrix\"], size_of_chunk=4)).T.float()\n camera_to_world_h = torch.stack(\n [\n camera_to_world_h[0, :],\n camera_to_world_h[2, :],\n camera_to_world_h[1, :],\n camera_to_world_h[3, :],\n ],\n dim=0,\n )\n\n return intrinsics_matrix, camera_to_world_h" }, { "identifier": "Viewer", "path": "nerfstudio/viewer/server/visualizer.py", "snippet": "class Viewer:\n \"\"\"Viewer class for connecting to the bridge server.\n\n Args:\n zmq_port: Where to connect with ZMQ.\n window: An already existing ViewerWindow.\n ip_address: The ip address of the bridge server.\n \"\"\"\n\n def __init__(\n self, zmq_port: Optional[int] = None, window: Optional[ViewerWindow] = None, ip_address: str = \"127.0.0.1\"\n ):\n if zmq_port is None and window is None:\n raise ValueError(\"Must specify either zmq_port or window.\")\n if window is None:\n self.window = ViewerWindow(zmq_port=zmq_port, ip_address=ip_address)\n else:\n self.window = window\n self.path = Path(())\n\n @staticmethod\n def view_into(window: ViewerWindow, path: Path):\n \"\"\"Returns a new Viewer but keeping the same ViewerWindow.\"\"\"\n vis = Viewer(window=window)\n vis.path = path\n return vis\n\n def __getitem__(self, path):\n return Viewer.view_into(self.window, self.path.append(path))\n\n def __repr__(self):\n return f\"<Viewer using: {self.window} at path: {self.path}>\"\n\n def write(self, data: Union[Dict, str, None] = None):\n \"\"\"Write data.\"\"\"\n path = self.path.lower()\n return self.window.send({\"type\": \"write\", \"path\": path, \"data\": data})\n\n def read(self):\n \"\"\"Read data.\"\"\"\n path = self.path.lower()\n return self.window.send({\"type\": \"read\", \"path\": path})\n\n def delete(self):\n \"\"\"Delete data.\"\"\"\n return self.write(data=None)" } ]
import base64 import enum import os import sys import threading import time import warnings import cv2 import numpy as np import torch from pathlib import Path from typing import Any, Dict, Optional, Tuple from cryptography.utils import CryptographyDeprecationWarning from rich.console import Console from nerfstudio.cameras.cameras import Cameras from nerfstudio.cameras.rays import RayBundle from nerfstudio.configs import base_config as cfg from nerfstudio.data.datasets.base_dataset import InputDataset from nerfstudio.models.base_model import Model from nerfstudio.utils import colormaps, profiler, writer from nerfstudio.utils.decorators import check_main_thread, decorate_all from nerfstudio.utils.images import BasicImages from nerfstudio.utils.io import load_from_json, write_to_json from nerfstudio.utils.writer import GLOBAL_BUFFER, EventName, TimeWriter from nerfstudio.viewer.server.subprocess import run_viewer_bridge_server_as_subprocess from nerfstudio.viewer.server.utils import get_intrinsics_matrix_and_camera_to_world_h from nerfstudio.viewer.server.visualizer import Viewer
19,284
# Copyright 2022 The Nerfstudio Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Code to interface with the `vis/` (the JS viewer). """ from __future__ import annotations warnings.filterwarnings("ignore", category=CryptographyDeprecationWarning) CONSOLE = Console(width=120) def get_viewer_version() -> str: """Get the version of the viewer.""" json_filename = os.path.join(os.path.dirname(__file__), "../app/package.json") version = load_from_json(Path(json_filename))["version"] return version @check_main_thread def setup_viewer(config: cfg.ViewerConfig, log_filename: Path): """Sets up the viewer if enabled Args: config: the configuration to instantiate viewer """ viewer_state = ViewerState(config, log_filename=log_filename) banner_messages = [f"Viewer at: {viewer_state.viewer_url}"] return viewer_state, banner_messages class OutputTypes(str, enum.Enum): """Noncomprehsnive list of output render types""" INIT = "init" RGB = "rgb" RGB_FINE = "rgb_fine" ACCUMULATION = "accumulation" ACCUMULATION_FINE = "accumulation_fine" class ColormapTypes(str, enum.Enum): """Noncomprehsnive list of colormap render types""" INIT = "init" DEFAULT = "default" TURBO = "turbo" DEPTH = "depth" SEMANTIC = "semantic" BOOLEAN = "boolean" class IOChangeException(Exception): """Basic camera exception to interrupt viewer""" class SetTrace: """Basic trace function""" def __init__(self, func): self.func = func def __enter__(self): sys.settrace(self.func) return self def __exit__(self, ext_type, exc_value, traceback): sys.settrace(None) class RenderThread(threading.Thread): """Thread that does all the rendering calls while listening for interrupts Args: state: current viewer state object graph: current checkpoint of model camera_ray_bundle: input rays to pass through the graph to render out """
# Copyright 2022 The Nerfstudio Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Code to interface with the `vis/` (the JS viewer). """ from __future__ import annotations warnings.filterwarnings("ignore", category=CryptographyDeprecationWarning) CONSOLE = Console(width=120) def get_viewer_version() -> str: """Get the version of the viewer.""" json_filename = os.path.join(os.path.dirname(__file__), "../app/package.json") version = load_from_json(Path(json_filename))["version"] return version @check_main_thread def setup_viewer(config: cfg.ViewerConfig, log_filename: Path): """Sets up the viewer if enabled Args: config: the configuration to instantiate viewer """ viewer_state = ViewerState(config, log_filename=log_filename) banner_messages = [f"Viewer at: {viewer_state.viewer_url}"] return viewer_state, banner_messages class OutputTypes(str, enum.Enum): """Noncomprehsnive list of output render types""" INIT = "init" RGB = "rgb" RGB_FINE = "rgb_fine" ACCUMULATION = "accumulation" ACCUMULATION_FINE = "accumulation_fine" class ColormapTypes(str, enum.Enum): """Noncomprehsnive list of colormap render types""" INIT = "init" DEFAULT = "default" TURBO = "turbo" DEPTH = "depth" SEMANTIC = "semantic" BOOLEAN = "boolean" class IOChangeException(Exception): """Basic camera exception to interrupt viewer""" class SetTrace: """Basic trace function""" def __init__(self, func): self.func = func def __enter__(self): sys.settrace(self.func) return self def __exit__(self, ext_type, exc_value, traceback): sys.settrace(None) class RenderThread(threading.Thread): """Thread that does all the rendering calls while listening for interrupts Args: state: current viewer state object graph: current checkpoint of model camera_ray_bundle: input rays to pass through the graph to render out """
def __init__(self, state: "ViewerState", graph: Model, camera_ray_bundle: RayBundle):
4
2023-12-15 20:07:22+00:00
24k
amazon-science/c2f-seg
data/dataloader_transformer.py
[ { "identifier": "FishBowl", "path": "data/dataloader_Fishbowl.py", "snippet": "class FishBowl(object):\n def __init__(self, config, mode, subtest=None):\n self.datatype = mode\n data_dir = config.root_path\n\n self.img_path = os.path.join(data_dir, self.datatype+\"_data\", self.datatype+\"_frames\")\n self.mode = mode\n self.dtype = torch.float32\n self.test_set = subtest\n \n self.data_summary = pickle.load(open(os.path.join(data_dir, self.datatype+\"_data\", self.datatype+\"_data.pkl\"), \"rb\"))\n self.obj_lists = list(self.data_summary.keys())\n self.device = \"cpu\"\n\n self.seq_len = 32 if self.mode == \"test\" else config.train_seq_len\n\n self.cur_vid = None\n self.video_frames = None\n self.patch_h = config.patch_H\n self.patch_w = config.patch_W\n self.enlarge_coef = config.enlarge_coef\n\n def decode2binarymask(self, masks):\n mask = mask_utils.decode(masks)\n binary_masks = mask.astype('bool') # (Image_W,Image_H,128)\n binary_masks = binary_masks.transpose(2,0,1) #(128, Image_W, Image_H)\n return binary_masks\n\n def __len__(self):\n return len(self.obj_lists)\n\n def __getitem__(self, idx):\n v_id, obj_id = self.obj_lists[idx].split(\"_\")\n if v_id != self.cur_vid:\n self.cur_vid = v_id\n fm_crop = []\n fm_no_crop = []\n vm_crop = []\n vm_no_crop = []\n img_crop = []\n \n obj_position = []\n\n counts = []\n loss_mask_weight = []\n\n # for evaluation \n video_ids = []\n object_ids = []\n frame_ids = []\n\n obj_dict = self.data_summary[self.obj_lists[idx]]\n timesteps = list(obj_dict.keys())\n assert np.all(np.diff(sorted(timesteps))==1)\n start_t, end_t = min(timesteps), max(timesteps)\n # print(start_t, end_t)\n if self.mode != \"test\" and end_t - start_t > self.seq_len - 1:\n start_t = np.random.randint(start_t, end_t-(self.seq_len-2))\n end_t = start_t + self.seq_len - 1\n\n if self.mode == \"test\":\n if start_t + self.seq_len-1<=end_t:\n end_t = start_t + self.seq_len-1\n\n for t_step in range(start_t, end_t):\n image_path = os.path.join(self.img_path, v_id, str(t_step).zfill(5)+'.png')\n img = cv2.imread(image_path)[:,:,::-1]\n # get visible mask and full mask\n vm = self.decode2binarymask(obj_dict[t_step][\"VM\"])[0]\n fm = self.decode2binarymask(obj_dict[t_step][\"FM\"])[0] # 320, 480\n vx_min, vx_max, vy_min, vy_max = obj_dict[t_step][\"VM_bx\"]\n x_center = (vx_min + vx_max) // 2\n y_center = (vy_min + vy_max) // 2\n x_len = int((vx_max - vx_min) * self.enlarge_coef)\n y_len = int((vy_max - vy_min) * self.enlarge_coef)\n vx_min = max(0, x_center - x_len // 2)\n vx_max = min(320, x_center + x_len // 2)\n vy_min = max(0, y_center - y_len // 2)\n vy_max = min(480, y_center + y_len // 2)\n\n obj_position.append([vx_min, vx_max, vy_min, vy_max])\n vm_crop.append(vm[vx_min:vx_max+1, vy_min:vy_max+1])\n fm_crop.append(fm[vx_min:vx_max+1, vy_min:vy_max+1])\n img_crop.append(img[vx_min:vx_max+1, vy_min:vy_max+1])\n\n vm_no_crop.append(vm)\n fm_no_crop.append(fm)\n # get loss mask\n loss_mask_weight.append(self.decode2binarymask(obj_dict[t_step][\"loss_mask_weight\"])[0])\n\n # for evaluation\n video_ids.append(int(v_id))\n object_ids.append(int(obj_id))\n frame_ids.append(t_step)\n counts.append(1)\n \n if True:\n num_pad = self.seq_len - (end_t - start_t)\n for _ in range(num_pad):\n obj_position.append(copy.deepcopy(obj_position[-1]))\n\n fm_crop.append(copy.deepcopy(fm_crop[-1]))\n fm_no_crop.append(copy.deepcopy(fm_no_crop[-1]))\n vm_crop.append(copy.deepcopy(vm_crop[-1]))\n vm_no_crop.append(copy.deepcopy(vm_no_crop[-1]))\n img_crop.append(copy.deepcopy(img_crop[-1]))\n\n loss_mask_weight.append(copy.deepcopy(loss_mask_weight[-1]))\n \n video_ids.append(video_ids[-1])\n object_ids.append(object_ids[-1])\n frame_ids.append(frame_ids[-1] + 1)\n counts.append(0)\n \n vm_crop, vm_crop_gt, fm_crop, img_crop, vm_pad, vm_scale = self.crop_and_rescale(vm_crop, fm_crop, img_crop)\n\n vm_crop = np.stack(vm_crop, axis=0) # Seq_len * h * w\n vm_crop_gt = np.stack(vm_crop_gt, axis=0) # Seq_len * h * w\n vm_no_crop = np.stack(vm_no_crop, axis=0) # Seq_len * H * W\n fm_crop = np.stack(fm_crop, axis=0) # Seq_len * h * w\n fm_no_crop = np.stack(fm_no_crop, axis=0) # Seq_len * H * W\n\n vm_crop = torch.from_numpy(np.array(vm_crop)).to(self.dtype).to(self.device)\n vm_crop_gt = torch.from_numpy(np.array(vm_crop_gt)).to(self.dtype).to(self.device)\n vm_no_crop = torch.from_numpy(np.array(vm_no_crop)).to(self.dtype).to(self.device)\n fm_crop = torch.from_numpy(np.array(fm_crop)).to(self.dtype).to(self.device)\n fm_no_crop = torch.from_numpy(np.array(fm_no_crop)).to(self.dtype).to(self.device)\n img_crop = torch.from_numpy(np.array(img_crop)).to(self.dtype).to(self.device)\n\n vm_pad = torch.from_numpy(np.array(vm_pad)).to(self.dtype).to(self.device)\n vm_scale = torch.from_numpy(np.array(vm_scale)).to(self.dtype).to(self.device)\n\n video_ids = torch.from_numpy(np.array(video_ids)).to(self.dtype).to(self.device)\n object_ids = torch.from_numpy(np.array(object_ids)).to(self.dtype).to(self.device)\n frame_ids = torch.from_numpy(np.array(frame_ids)).to(self.dtype).to(self.device)\n counts = torch.from_numpy(np.array(counts)).to(self.dtype).to(self.device)\n loss_mask_weight = torch.from_numpy(np.array(loss_mask_weight)).to(self.dtype).to(self.device) \n obj_position = torch.from_numpy(np.array(obj_position)).to(self.dtype).to(self.device)\n\n obj_data = {\n \"vm_crop\": vm_crop,\n \"vm_crop_gt\": vm_crop_gt,\n \"vm_no_crop\": vm_no_crop,\n \"fm_crop\": fm_crop,\n \"fm_no_crop\": fm_no_crop,\n \"img_crop\": img_crop,\n \"vm_pad\": vm_pad,\n \"vm_scale\": vm_scale,\n \"video_ids\": video_ids,\n \"object_ids\": object_ids,\n \"frame_ids\": frame_ids,\n \"counts\": counts,\n \"loss_mask\": loss_mask_weight, \n \"obj_position\": obj_position,\n }\n\n return obj_data\n\n def crop_and_rescale(self, vm_crop, fm_crop_vm=None, img_crop=None):\n h, w = np.array([m.shape for m in vm_crop]).max(axis=0)\n vm_pad = []\n vm_scale = []\n vm_crop_gt = []\n\n for i, m in enumerate(vm_crop):\n m = transform.rescale(m, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n vm_pad.append(np.array([max(self.patch_h-cur_h, 0), max(self.patch_w-cur_w, 0)]))\n vm_scale.append(np.array([self.patch_h/h, self.patch_w/w]))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w]\n if self.mode==\"train\":\n vm_crop[i] = self.data_augmentation(m)\n vm_crop_gt.append(m)\n else:\n vm_crop[i] = m\n vm_crop_gt.append(m)\n\n for i, m in enumerate(fm_crop_vm):\n m = transform.rescale(m, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w]\n fm_crop_vm[i] = m\n\n for i, img_ in enumerate(img_crop):\n img_ = transform.rescale(img_, (self.patch_h/h, self.patch_w/w, 1))\n cur_h, cur_w = img_.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)), (0, 0))\n img_ = np.pad(img_, to_pad)[:self.patch_h, :self.patch_w, :3]\n img_crop[i] = img_\n\n vm_pad = np.stack(vm_pad)\n vm_scale = np.stack(vm_scale)\n return vm_crop, vm_crop_gt, fm_crop_vm, img_crop, vm_pad, vm_scale\n \n def getImg(self, v_id):\n imgs = []\n imgs_list = os.listdir(os.path.join(self.img_path, v_id))\n imgs_list.sort()\n for sub_path in imgs_list:\n img_path = os.path.join(self.img_path, v_id, sub_path)\n img_tmp = plt.imread(img_path)\n imgs.append(img_tmp)\n assert len(imgs) == 128\n return imgs\n\n def create_iterator(self, batch_size):\n while True:\n sample_loader = DataLoader(\n dataset=self,\n batch_size=batch_size,\n drop_last=True,\n collate_fn=self.collate_fn\n )\n for item in sample_loader:\n yield item\n \n @staticmethod\n def collate_fn(batch):\n keys = batch[0].keys()\n res = {}\n for k in keys:\n temp_ = []\n for b in batch:\n if b[k] is not None:\n temp_.append(b[k])\n if len(temp_) > 0:\n res[k] = default_collate(temp_)\n else:\n res[k] = None\n return res\n \n def data_augmentation(self, mask):\n mask = mask.astype(np.float)\n rdv = random.random()\n n_repeat = random.randint(1, 4)\n if rdv <= 0.1:\n mask = cv2.GaussianBlur(mask, (35,35), 11)\n elif rdv > 0.1 and rdv < 0.6:\n rdv_1 = random.random()\n rdv_2 = random.random()\n for i in range(n_repeat):\n w = random.randint(5, 13)\n h = random.randint(5, 13)\n kernel = np.ones((w, h), dtype=np.uint8)\n if rdv_1 <= 0.5:\n mask = cv2.dilate(mask, kernel, 1)\n elif rdv_1 > 0.5 and rdv_1 <= 1.0:\n mask = cv2.erode(mask, kernel, 1)\n if rdv_2 <= 0.1:\n mask = cv2.GaussianBlur(mask, (35,35), 11)\n else:\n mask = mask\n return (mask>0.5)" }, { "identifier": "MOViD_A", "path": "data/dataloader_MOViD_A.py", "snippet": "class MOViD_A(object):\n def __init__(self, config, mode):\n super(MOViD_A, self).__init__()\n self.mode = mode\n self.dtype = torch.float32\n self.device = \"cpu\"\n root_path = config.root_path\n self.data_dir = os.path.join(root_path, mode)\n \n self.instance_list = np.genfromtxt(\n os.path.join(root_path, \"{}_instance.txt\".format(mode)),\n dtype=np.str,\n encoding='utf-8'\n )\n\n self.train_seq_len = 24\n self.cur_vid = None\n self.patch_h = config.patch_H\n self.patch_w = config.patch_W\n self.enlarge_coef = config.enlarge_coef\n\n def __len__(self):\n return len(self.instance_list)\n\n def __getitem__(self, idx, specified_V_O_id=None):\n # whether choose a specific instance to load\n if specified_V_O_id is None:\n v_id, obj_id, value = self.instance_list[idx].split(\"_\")\n else:\n v_id, obj_id, value = specified_V_O_id.split(\"_\")\n v_id, obj_id, value = int(v_id), int(obj_id), int(value)\n if v_id != self.cur_vid:\n self.cur_vid = v_id\n self.video_path = os.path.join(self.data_dir, str(v_id))\n metadata = self.read_json(os.path.join(self.video_path, 'metadata.json'))\n\n self.num_frames = metadata[\"metadata\"][\"num_frames\"]\n self.height = metadata['metadata']['height']\n self.width = metadata['metadata']['width']\n self.instances = [self.format_instance_information(obj) for obj in metadata[\"instances\"]]\n\n vis_mask_paths = [os.path.join(self.video_path, \"segmentation_full_{}.png\".format(str(f).zfill(5))) for f in range(self.num_frames)]\n vis_mask = [np.array(Image.open(frame_path)) for frame_path in vis_mask_paths] #[t,h,w]\n\n full_mask_paths = [os.path.join(self.video_path, \"segmentation_{}_{}.png\".format(obj_id, str(f).zfill(5))) for f in range(self.num_frames)]\n full_mask = [np.array(Image.open(frame_path)) for frame_path in full_mask_paths] #[t,h,w]\n \n rgb_img_path = [os.path.join(self.video_path, \"rgba_full_{}.png\".format(str(f).zfill(5))) for f in range(self.num_frames)]\n rgb_img = [np.array(Image.open(frame_path))[...,:3] for frame_path in rgb_img_path]\n \n counts = []\n obj_position = []\n\n vm_crop = []\n vm_no_crop = []\n fm_crop = []\n fm_no_crop = []\n loss_mask_weight = []\n img_crop = []\n # for evaluation \n video_ids = []\n object_ids = []\n frame_ids = []\n\n timesteps = self.instances[obj_id]['bbox_frames']\n start_t, end_t = 0, 23\n if self.mode != \"test\" and end_t - start_t > self.train_seq_len - 1:\n start_t = np.random.randint(start_t, end_t-(self.train_seq_len-2))\n end_t = start_t + self.train_seq_len - 1\n\n for t_step in range(start_t, end_t+1):\n Image_H, Image_W = self.height, self.width\n # some objects will move out the field of view in some frames\n if t_step in timesteps:\n index = self.instances[obj_id][\"bbox_frames\"].index(t_step)\n xmin, ymin, xmax, ymax = self.instances[obj_id][\"bboxes\"][index]\n vx_min, vy_min, vx_max, vy_max = int(Image_H*xmin), int(Image_W*ymin), int(Image_H*xmax), int(Image_W*ymax)\n counts.append(1)\n else:\n bboxs = mask_find_bboxs(full_mask[t_step].astype(np.uint8))\n \n if bboxs.size==0:\n vx_min, vy_min, vx_max, vy_max = 0, 0, 256, 256\n else:\n b = bboxs[-1][:4]\n vx_min, vy_min, vx_max, vy_max = b[1], b[0], b[1]+b[3], b[0]+b[2]\n counts.append(0)\n\n # enlarge the bbox\n x_center = (vx_min + vx_max) // 2\n y_center = (vy_min + vy_max) // 2\n x_len = int((vx_max - vx_min) * self.enlarge_coef)\n y_len = int((vy_max - vy_min) * self.enlarge_coef)\n vx_min = max(0, x_center - x_len // 2)\n vx_max = min(Image_H, x_center + x_len // 2)\n vy_min = max(0, y_center - y_len // 2)\n vy_max = min(Image_W, y_center + y_len // 2)\n\n obj_position.append([vx_min, vx_max, vy_min, vy_max])\n\n # get mask\n vm = vis_mask[t_step]\n vm_crop.append(vm[vx_min:vx_max+1, vy_min:vy_max+1]==value)\n vm_no_crop.append(vm==value)\n\n fm = full_mask[t_step]\n fm_crop.append(fm[vx_min:vx_max+1, vy_min:vy_max+1]==value)\n fm_no_crop.append(fm==value)\n \n # get image\n image = rgb_img[t_step]\n img_crop.append(image[vx_min:vx_max+1, vy_min:vy_max+1])\n\n # get loss mask\n fore_ground = vm == 0\n obj_ground = vm==value\n loss_mask = np.logical_or(fore_ground, obj_ground)\n\n loss_mask_weight.append(loss_mask)\n\n # for evaluation\n video_ids.append(v_id)\n object_ids.append(obj_id)\n frame_ids.append(t_step)\n\n obj_position = torch.from_numpy(np.array(obj_position)).to(self.dtype).to(self.device)\n \n vm_crop, fm_crop, vm_pad, vm_scale, vm_crop_gt, img_crop = self.crop_and_rescale(vm_crop, fm_crop, img_crop)\n\n vm_crop = np.stack(vm_crop, axis=0) # Seq_len * h * w\n vm_no_crop = np.stack(vm_no_crop, axis=0) # Seq_len * H * W\n # fm_crop = np.stack(fm_crop, axis=0) # Seq_len * h * w\n fm_crop = np.stack(fm_crop, axis=0) # Seq_len * h * w\n fm_no_crop = np.stack(fm_no_crop, axis=0) # Seq_len * H * W\n img_crop = np.stack(img_crop, axis=0) # Sqe_len * H * W\n\n vm_crop = torch.from_numpy(np.array(vm_crop)).to(self.dtype).to(self.device)\n vm_no_crop = torch.from_numpy(np.array(vm_no_crop)).to(self.dtype).to(self.device)\n fm_crop = torch.from_numpy(np.array(fm_crop)).to(self.dtype).to(self.device)\n fm_no_crop = torch.from_numpy(np.array(fm_no_crop)).to(self.dtype).to(self.device)\n\n img_crop = torch.from_numpy(np.array(img_crop)).to(self.dtype).to(self.device)\n\n vm_pad = torch.from_numpy(np.array(vm_pad)).to(self.dtype).to(self.device)\n vm_scale = torch.from_numpy(np.array(vm_scale)).to(self.dtype).to(self.device)\n\n video_ids = torch.from_numpy(np.array(video_ids)).to(self.dtype).to(self.device)\n object_ids = torch.from_numpy(np.array(object_ids)).to(self.dtype).to(self.device)\n frame_ids = torch.from_numpy(np.array(frame_ids)).to(self.dtype).to(self.device)\n counts = torch.from_numpy(np.array(counts)).to(self.dtype).to(self.device)\n loss_mask_weight = torch.from_numpy(np.array(loss_mask_weight)).to(self.dtype).to(self.device) \n obj_position = torch.from_numpy(np.array(obj_position)).to(self.dtype).to(self.device)\n\n obj_data = {\n \"vm_crop\": vm_crop,\n \"vm_no_crop\": vm_no_crop,\n \"vm_pad\": vm_pad,\n \"vm_scale\": vm_scale,\n\n \"img_crop\": img_crop,\n \n \"fm_crop\": fm_crop,\n \"fm_no_crop\": fm_no_crop,\n\n \"obj_position\": obj_position, \n \"loss_mask\": loss_mask_weight, \n \"counts\": counts,\n \"video_ids\": video_ids,\n \"object_ids\": object_ids,\n \"frame_ids\": frame_ids,\n }\n\n return obj_data\n\n def crop_and_rescale(self, vm_crop, fm_crop=None,img_crop=None):\n h, w = np.array([m.shape for m in vm_crop]).max(axis=0)\n vm_pad = []\n vm_crop_gt = []\n vm_scale = []\n for i, img in enumerate(img_crop):\n img = transform.rescale(img, (self.patch_h/h, self.patch_w/w, 1))\n cur_h, cur_w = img.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)), (0, 0))\n img = np.pad(img, to_pad)[:self.patch_h, :self.patch_w, :3]\n img_crop[i] = img\n\n for i, m in enumerate(vm_crop):\n m = transform.rescale(m, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w]\n if self.mode==\"train\":\n vm_crop[i] = self.data_augmentation(m)\n else:\n vm_crop[i] = m\n vm_crop_gt.append(m)\n vm_pad.append(np.array([max(self.patch_h-cur_h, 0), max(self.patch_w-cur_w, 0)]))\n vm_scale.append(np.array([self.patch_h/h, self.patch_w/w]))\n\n for i, m in enumerate(fm_crop):\n m = transform.rescale(m, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w]\n fm_crop[i] = m\n\n vm_pad = np.stack(vm_pad)\n vm_scale = np.stack(vm_scale)\n return vm_crop, fm_crop, vm_pad, vm_scale, vm_crop_gt,img_crop\n \n def read_json(self,dir_):\n with open(dir_) as f:\n data = json.load(f)\n return data\n\n def format_instance_information(self, obj):\n return {\n \"bboxes\": obj[\"bboxes\"],\n \"bbox_frames\": obj[\"bbox_frames\"],\n }\n\n def create_iterator(self, batch_size):\n while True:\n sample_loader = DataLoader(\n dataset=self,\n batch_size=batch_size,\n drop_last=True,\n collate_fn=self.collate_fn\n )\n\n for item in sample_loader:\n yield item\n\n @staticmethod\n def collate_fn(batch):\n keys = batch[0].keys()\n res = {}\n for k in keys:\n temp_ = []\n for b in batch:\n if b[k] is not None:\n temp_.append(b[k])\n if len(temp_) > 0:\n res[k] = default_collate(temp_)\n else:\n res[k] = None\n return res\n \n def data_augmentation(self, mask):\n mask = mask.astype(np.float)\n rdv = random.random()\n n_repeat = random.randint(1, 4)\n if rdv <= 0.1:\n mask = cv2.GaussianBlur(mask, (35,35), 11)\n elif rdv > 0.1 and rdv < 0.6:\n rdv_1 = random.random()\n rdv_2 = random.random()\n for i in range(n_repeat):\n w = random.randint(5, 13)\n h = random.randint(5, 13)\n kernel = np.ones((w, h), dtype=np.uint8)\n if rdv_1 <= 0.5:\n mask = cv2.dilate(mask, kernel, 1)\n elif rdv_1 > 0.5 and rdv_1 <= 1.0:\n mask = cv2.erode(mask, kernel, 1)\n if rdv_2 <= 0.1:\n mask = cv2.GaussianBlur(mask, (35,35), 11)\n else:\n mask = mask\n return (mask>0.5)" }, { "identifier": "Kins_Fusion_dataset", "path": "data/dataloader_KINS.py", "snippet": "class Kins_Fusion_dataset(torch.utils.data.Dataset):\n def __init__(self, config, mode):\n super(Kins_Fusion_dataset, self).__init__()\n self.config = config\n self.mode = mode\n self.root_path = config.root_path\n \n # Load Fusion dataset\n self.data_info = pickle.load(open(os.path.join(self.root_path, \"fusion_{}.pkl\".format(self.mode)), \"rb\"))\n self.label_info = np.genfromtxt(os.path.join(self.root_path, \"c2f_seg_{}_list.txt\".format(self.mode)), dtype=np.str, encoding='utf-8')\n self.img_root_path = os.path.join(self.root_path, \"{}ing\".format(mode),\"image_2\")\n \n # Load the GT of AISFormer\n if mode==\"train\":\n aisformer_gt = cvb.load(os.path.join(self.root_path, \"instances_train.json\"))\n else:\n aisformer_gt = cvb.load(os.path.join(self.root_path, \"instances_val_upate.json\"))\n annotations = aisformer_gt[\"annotations\"]\n images = aisformer_gt[\"images\"]\n self.images, self.annotations = self.make_json_dict(images, annotations)\n \n # Load the GT of vanilla KINS\n self.base_img_path = os.path.join(self.root_path, \"{}ing\".format(mode), \"image_2\")\n self.base_ann_path= os.path.join(self.root_path, \"update_{}_2020.json\".format(mode))\n annotations = cvb.load(self.base_ann_path)\n imgs_info = annotations['images']\n anns_info = annotations[\"annotations\"]\n self.imgs_dict, self.anns_dict = self.make_json_dict(imgs_info, anns_info)\n\n # dataloader setting\n self.dtype = torch.float32\n self.enlarge_coef = 2\n self.patch_h = 256\n self.patch_w = 256\n self.device = \"cpu\"\n\n def __len__(self):\n return self.label_info.shape[0]\n\n def __getitem__(self, index):\n return self.load_item(index)\n \n def load_item(self, index):\n # load aisformer predicted visible masks\n if \"aisformer\" in self.label_info[index]:\n dataset_name, image_id, anno_id = self.label_info[index].split(\",\")\n image_id, anno_id = int(image_id), int(anno_id)\n # add image information\n img_name = self.images[image_id]\n img_path = os.path.join(self.img_root_path, img_name)\n # img_path = os.path.join(self.img_root_path, str(image_id).zfill(6)+ \".png\")\n img = np.array(Image.open(img_path))\n instances = self.data_info['{}_{}'.format(dataset_name, image_id)][anno_id]\n segmentation = instances[\"pred_visible_mask\"]\n height, width = segmentation[\"size\"]\n vm_no_crop = mask_utils.decode([segmentation]).astype(bool)\n vm_no_crop_gt = mask_utils.decode([instances[\"gt_visible_mask\"]]).astype(bool)\n rles = mask_utils.frPyObjects(instances[\"gt_full_mask\"], height, width)\n fm_no_crop = mask_utils.decode(mask_utils.merge(rles)).astype(bool)\n fm_no_crop = fm_no_crop[..., np.newaxis]\n\n bbox = instances[\"pred_visible_mask_bbox\"]\n y_min, x_min, w, h = bbox\n y_max, x_max = y_min + w, x_min + h\n x_center = (x_min + x_max) // 2\n y_center = (y_min + y_max) // 2\n x_len = int((x_max - x_min) * self.enlarge_coef)\n y_len = int((y_max - y_min) * self.enlarge_coef)\n x_min = max(0, x_center - x_len // 2)\n x_max = min(height, x_center + x_len // 2)\n y_min = max(0, y_center - y_len // 2)\n y_max = min(width, y_center + y_len // 2)\n x_min, x_max, y_min, y_max = int(x_min), int(x_max), int(y_min), int(y_max)\n \n vm_crop = vm_no_crop[x_min:x_max+1, y_min:y_max+1, 0].astype(bool)\n vm_crop_gt = vm_no_crop_gt[x_min:x_max+1, y_min:y_max+1, 0].astype(bool)\n fm_crop = fm_no_crop[x_min:x_max+1, y_min:y_max+1, 0].astype(bool)\n img_crop = img[x_min:x_max+1, y_min:y_max+1]\n \n h, w = vm_crop.shape[:2]\n m = transform.rescale(vm_crop, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w]\n vm_crop = m[np.newaxis, ...]\n\n img_ = transform.rescale(img_crop, (self.patch_h/h, self.patch_w/w, 1))\n cur_h, cur_w = img_.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)), (0, 0))\n img_ = np.pad(img_, to_pad)[:self.patch_h, :self.patch_w, :3]\n img_crop = img_\n\n # data augmentation\n vm_crop_aug = self.data_augmentation(vm_crop[0])[np.newaxis, ...]\n\n h, w = vm_crop_gt.shape[:2]\n m = transform.rescale(vm_crop_gt, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w]\n vm_crop_gt = m[np.newaxis, ...]\n\n m = transform.rescale(fm_crop, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w] \n fm_crop = m[np.newaxis, ...]\n\n loss_mask = fm_no_crop.astype(int)-vm_no_crop_gt.astype(int)\n loss_mask[loss_mask==255]=0\n loss_mask = 1-loss_mask.astype(bool)\n\n vm_no_crop = vm_no_crop[np.newaxis, ...]\n fm_no_crop = fm_no_crop[np.newaxis, ...]\n\n obj_position = np.array([x_min, x_max, y_min, y_max])\n vm_pad = np.array([max(self.patch_h-cur_h, 0), max(self.patch_w-cur_w, 0)])\n vm_scale = np.array([self.patch_h/h, self.patch_w/w])\n counts = np.array([1])\n \n counts = torch.from_numpy(counts).to(self.dtype).to(self.device)\n\n obj_position = torch.from_numpy(obj_position).to(self.dtype).to(self.device)\n vm_pad = torch.from_numpy(vm_pad).to(self.dtype).to(self.device)\n vm_scale = torch.from_numpy(vm_scale).to(self.dtype).to(self.device)\n\n fm_crop = torch.from_numpy(fm_crop).to(self.dtype).to(self.device)\n fm_no_crop = torch.from_numpy(np.array(fm_no_crop)).to(self.dtype).to(self.device)\n vm_crop_aug = torch.from_numpy(vm_crop_aug).to(self.dtype).to(self.device)\n vm_crop_gt = torch.from_numpy(vm_crop_gt).to(self.dtype).to(self.device)\n vm_no_crop = torch.from_numpy(np.array(vm_no_crop)).to(self.dtype).to(self.device)\n vm_no_crop_gt = torch.from_numpy(np.array(vm_no_crop_gt)).to(self.dtype).to(self.device)\n\n img_crop = torch.from_numpy(np.array(img_crop)).to(self.dtype).to(self.device)\n\n loss_mask = torch.from_numpy(np.array(loss_mask)).to(self.dtype).to(self.device)\n \n image_id = torch.from_numpy(np.array(image_id)).to(self.dtype).to(self.device)\n anno_id = torch.from_numpy(np.array(anno_id)).to(self.dtype).to(self.device)\n \n if self.mode==\"train\":\n meta = {\n # \"vm_no_crop\": vm_no_crop,\n \"vm_crop\": vm_crop_aug,\n \"vm_crop_gt\": vm_crop_gt,\n # \"fm_no_crop\": fm_no_crop,\n \"fm_crop\": fm_crop,\n \"img_crop\": img_crop,\n # \"loss_mask\": loss_mask,\n \"obj_position\": obj_position,\n \"vm_pad\": vm_pad,\n \"vm_scale\": vm_scale,\n \"counts\":counts,\n \"img_id\": image_id,\n \"anno_id\": anno_id,\n }\n elif self.mode==\"test\":\n meta = {\n \"vm_no_crop\": vm_no_crop,\n \"vm_no_crop_gt\": vm_no_crop_gt,\n \"vm_crop\": vm_crop,\n \"vm_crop_gt\": vm_crop_gt,\n \"fm_no_crop\": fm_no_crop,\n \"fm_crop\": fm_crop,\n \"img_crop\": img_crop,\n \"loss_mask\": loss_mask,\n \"obj_position\": obj_position,\n \"vm_pad\": vm_pad,\n \"vm_scale\": vm_scale,\n \"counts\":counts,\n \"img_id\": image_id,\n \"anno_id\": anno_id,\n }\n return meta\n else:\n img_id, anno_id, category_id = self.label_info[index].split(\"_\")\n img_id, anno_id, category_id = int(img_id), int(anno_id), int(category_id)\n\n img_name = self.imgs_dict[img_id]\n img_path = os.path.join(self.base_img_path, img_name)\n \n img = cv2.imread(img_path, cv2.IMREAD_COLOR)\n height, width, _ = img.shape\n \n ann = self.anns_dict[img_id][anno_id]\n fm_no_crop = self.polys_to_mask(ann[\"a_segm\"], height, width)\n vm_no_crop = self.polys_to_mask(ann[\"i_segm\"], height, width)\n if np.sum(vm_no_crop)==0:\n counts = np.array([0])\n else:\n counts = np.array([1])\n y_min, x_min, w, h = ann[\"i_bbox\"]\n\n y_max, x_max = y_min + w, x_min + h\n x_center = (x_min + x_max) // 2\n y_center = (y_min + y_max) // 2\n x_len = int((x_max - x_min) * self.enlarge_coef)\n y_len = int((y_max - y_min) * self.enlarge_coef)\n x_min = max(0, x_center - x_len // 2)\n x_max = min(height, x_center + x_len // 2)\n y_min = max(0, y_center - y_len // 2)\n y_max = min(width, y_center + y_len // 2)\n \n fm_crop = fm_no_crop[x_min:x_max+1, y_min:y_max+1].astype(bool)\n vm_crop = vm_no_crop[x_min:x_max+1, y_min:y_max+1].astype(bool)\n img_crop = img[x_min:x_max+1, y_min:y_max+1]\n\n h, w = vm_crop.shape[:2]\n m = transform.rescale(vm_crop, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w]\n vm_crop = m[np.newaxis, ...]\n\n img_ = transform.rescale(img_crop, (self.patch_h/h, self.patch_w/w, 1))\n cur_h, cur_w = img_.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)), (0, 0))\n img_ = np.pad(img_, to_pad)[:self.patch_h, :self.patch_w, :3]\n img_crop = img_\n\n m = transform.rescale(fm_crop, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w] \n fm_crop = m[np.newaxis, ...]\n\n obj_position = np.array([x_min, x_max, y_min, y_max])\n vm_pad = np.array([max(self.patch_h-cur_h, 0), max(self.patch_w-cur_w, 0)])\n vm_scale = np.array([self.patch_h/h, self.patch_w/w])\n\n vm_no_crop = vm_no_crop[np.newaxis, ...]\n fm_no_crop = fm_no_crop[np.newaxis, ...]\n\n loss_mask = fm_no_crop-vm_no_crop\n loss_mask[loss_mask==255]=0\n loss_mask = 1-loss_mask.astype(bool)\n # data augmentation\n vm_crop_aug = self.data_augmentation(vm_crop[0])[np.newaxis, ...]\n counts = torch.from_numpy(counts).to(self.dtype).to(self.device)\n\n obj_position = torch.from_numpy(obj_position).to(self.dtype).to(self.device)\n vm_pad = torch.from_numpy(vm_pad).to(self.dtype).to(self.device)\n vm_scale = torch.from_numpy(vm_scale).to(self.dtype).to(self.device)\n\n fm_crop = torch.from_numpy(fm_crop).to(self.dtype).to(self.device)\n fm_no_crop = torch.from_numpy(np.array(fm_no_crop)).to(self.dtype).to(self.device)\n # vm_crop here is the GT\n vm_crop = torch.from_numpy(vm_crop).to(self.dtype).to(self.device)\n vm_crop_aug = torch.from_numpy(vm_crop_aug).to(self.dtype).to(self.device)\n vm_no_crop = torch.from_numpy(np.array(vm_no_crop)).to(self.dtype).to(self.device)\n img_crop = torch.from_numpy(np.array(img_crop)).to(self.dtype).to(self.device)\n loss_mask = torch.from_numpy(np.array(loss_mask)).to(self.dtype).to(self.device)\n \n img_id = torch.from_numpy(np.array(img_id)).to(self.dtype).to(self.device)\n anno_id = torch.from_numpy(np.array(anno_id)).to(self.dtype).to(self.device)\n # category_id = torch.from_numpy(np.array(category_id)).to(self.dtype).to(self.device)\n if self.mode==\"train\":\n meta = {\n # \"vm_no_crop\": vm_no_crop,\n \"vm_crop\": vm_crop_aug,\n \"vm_crop_gt\": vm_crop,\n # \"fm_no_crop\": fm_no_crop,\n \"fm_crop\": fm_crop,\n \"img_crop\": img_crop,\n # \"loss_mask\": loss_mask,\n \"obj_position\": obj_position,\n \"vm_pad\": vm_pad,\n \"vm_scale\": vm_scale,\n \"counts\":counts,\n \"img_id\": img_id,\n \"anno_id\": anno_id,\n # for vq\n # \"mask_crop\": fm_crop\n }\n elif self.mode==\"test\":\n meta = {\n \"vm_no_crop\": vm_no_crop,\n \"vm_crop\": vm_crop,\n \"vm_crop_gt\": vm_crop,\n \"fm_no_crop\": fm_no_crop,\n \"vm_no_crop_gt\": vm_no_crop,\n \"fm_crop\": fm_crop,\n \"img_crop\": img_crop,\n \"loss_mask\": loss_mask,\n \"obj_position\": obj_position,\n \"vm_pad\": vm_pad,\n \"vm_scale\": vm_scale,\n \"counts\":counts,\n \"img_id\": img_id,\n \"anno_id\": anno_id,\n # for vq\n # \"mask_crop\": fm_crop\n }\n return meta\n\n def data_augmentation(self, mask):\n mask = mask.astype(np.float)\n rdv = random.random()\n n_repeat = random.randint(1, 4)\n if rdv <= 0.2:\n mask = cv2.GaussianBlur(mask, (35,35), 11)\n elif rdv > 0.2 and rdv <0.6:\n rdv_1 = random.random()\n rdv_2 = random.random()\n for i in range(n_repeat):\n w = random.randint(5, 13)\n h = random.randint(5, 13)\n kernel = np.ones((w, h), dtype=np.uint8)\n if rdv_1 <= 0.55:\n mask = cv2.dilate(mask, kernel, 1)\n elif rdv_1 > 0.55 and rdv_1 <= 1.0:\n mask = cv2.erode(mask, kernel, 1)\n if rdv_2 <= 0.1:\n mask = cv2.GaussianBlur(mask, (35,35), 11)\n else:\n mask = mask\n return (mask>0.5)\n \n @staticmethod\n def collate_fn(batch):\n keys = batch[0].keys()\n res = {}\n for k in keys:\n temp_ = []\n for b in batch:\n if b[k] is not None:\n temp_.append(b[k])\n if len(temp_) > 0:\n res[k] = default_collate(temp_)\n else:\n res[k] = None\n\n return res\n\n def create_iterator(self, batch_size):\n while True:\n sample_loader = DataLoader(\n dataset=self,\n batch_size=batch_size,\n drop_last=True,\n collate_fn=self.collate_fn\n )\n\n for item in sample_loader:\n yield item\n\n def make_json_dict(self, imgs, anns):\n imgs_dict = {}\n anns_dict = {}\n for ann in anns:\n image_id = ann[\"image_id\"]\n if not image_id in anns_dict:\n anns_dict[image_id] = []\n anns_dict[image_id].append(ann)\n else:\n anns_dict[image_id].append(ann)\n \n for img in imgs:\n image_id = img['id']\n imgs_dict[image_id] = img['file_name']\n\n return imgs_dict, anns_dict\n\n def polys_to_mask(self, polygons, height, width):\n rles = mask_utils.frPyObjects(polygons, height, width)\n rle = mask_utils.merge(rles)\n mask = mask_utils.decode(rle)\n return mask" }, { "identifier": "KINS_Aisformer_VRSP_Intersection", "path": "data/dataloader_KINS.py", "snippet": "class KINS_Aisformer_VRSP_Intersection(torch.utils.data.Dataset):\n def __init__(self, config, mode):\n super(KINS_Aisformer_VRSP_Intersection, self).__init__()\n self.config = config\n self.mode = mode\n self.root_path = config.root_path\n \n # Load Intersection dataset\n self.data_info = pickle.load(open(os.path.join(self.root_path, \"kins_intersection.pkl\"), \"rb\"))\n self.label_info = np.genfromtxt(os.path.join(self.root_path, \"kins_intersection_list.txt\"), dtype=np.str, encoding='utf-8')\n if mode==\"train\":\n aisformer_gt = cvb.load(os.path.join(self.root_path, \"instances_train.json\"))\n else:\n aisformer_gt = cvb.load(os.path.join(self.root_path, \"instances_val_upate.json\"))\n annotations = aisformer_gt[\"annotations\"]\n images = aisformer_gt[\"images\"]\n self.images, self.annotations = self.make_json_dict(images, annotations)\n self.img_root_path = os.path.join(self.root_path, \"{}ing\".format(mode), \"image_2\")\n self.dtype = torch.float32\n self.enlarge_coef = 2\n self.patch_h = 256\n self.patch_w = 256\n self.device = \"cpu\"\n \n def __len__(self):\n return self.label_info.shape[0]\n\n def __getitem__(self, index):\n return self.load_item(index)\n \n def mask_find_bboxs(self, mask):\n retval, labels, stats, centroids = cv2.connectedComponentsWithStats(mask, connectivity=8)\n stats = stats[stats[:,4].argsort()]\n return stats\n \n def generate_heatmap(self, mask, kernel, sigma):\n heatmap = cv2.GaussianBlur(mask, kernel, sigma)\n am = np.amax(heatmap)\n heatmap /= am / 1\n return heatmap\n \n def load_item(self, index):\n image_id, anno_id = self.label_info[index].split(\"_\")\n image_id, anno_id = int(image_id), int(anno_id)\n instances = self.data_info[image_id][anno_id]\n\n segmentation = instances[\"pred_visible_mask\"]\n height, width = segmentation[\"size\"]\n # add image information\n img_name = self.images[image_id]\n img_path = os.path.join(self.img_root_path, img_name)\n # img_path = os.path.join(self.img_root_path, str(image_id).zfill(6)+ \".png\")\n img = Image.open(img_path)\n img = img.resize((width,height), Image.ANTIALIAS)\n img = np.array(img)\n \n vm_no_crop = mask_utils.decode([segmentation]).astype(bool)\n vm_no_crop_gt = mask_utils.decode([instances[\"gt_visible_mask\"]]).astype(bool)\n # fm_no_crop = mask_utils.decode([instances[\"gt_full_mask\"]]).astype(bool)\n rles = mask_utils.frPyObjects(instances[\"gt_full_mask\"], height, width)\n fm_no_crop = mask_utils.decode(mask_utils.merge(rles)).astype(bool)\n \n bbox = instances[\"pred_visible_mask_bbox\"]\n y_min, x_min, w, h = bbox\n y_max, x_max = y_min + w, x_min + h\n x_center = (x_min + x_max) // 2\n y_center = (y_min + y_max) // 2\n x_len = int((x_max - x_min) * self.enlarge_coef)\n y_len = int((y_max - y_min) * self.enlarge_coef)\n x_min = max(0, x_center - x_len // 2)\n x_max = min(height, x_center + x_len // 2)\n y_min = max(0, y_center - y_len // 2)\n y_max = min(width, y_center + y_len // 2)\n x_min, x_max, y_min, y_max = int(x_min), int(x_max), int(y_min), int(y_max)\n\n x_center_crop = x_center - x_min\n y_center_crop = y_center - y_min\n \n fm_no_crop = fm_no_crop[..., np.newaxis]\n vm_crop = vm_no_crop[x_min:x_max+1, y_min:y_max+1, 0].astype(bool)\n fm_crop = fm_no_crop[x_min:x_max+1, y_min:y_max+1, 0].astype(bool)\n img_crop = img[x_min:x_max+1, y_min:y_max+1]\n vm_crop_gt = vm_no_crop_gt[x_min:x_max+1, y_min:y_max+1, 0].astype(bool)\n\n h, w = vm_crop.shape[:2]\n m = transform.rescale(vm_crop, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w]\n vm_crop = m[np.newaxis, ...]\n \n center_crop = np.zeros_like(vm_crop[0])\n x_center_crop = int(x_center_crop*self.patch_h/h)\n y_center_crop = int(y_center_crop*self.patch_w/w)\n center_crop[x_center_crop: x_center_crop+1, y_center_crop: y_center_crop+1]=1\n center_crop = self.generate_heatmap(center_crop.astype(np.float), (35, 35), 9)\n center_crop = center_crop[np.newaxis, ...]\n\n img_ = transform.rescale(img_crop, (self.patch_h/h, self.patch_w/w, 1))\n cur_h, cur_w = img_.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)), (0, 0))\n img_ = np.pad(img_, to_pad)[:self.patch_h, :self.patch_w, :3]\n img_crop = img_\n\n h, w = vm_crop_gt.shape[:2]\n m = transform.rescale(vm_crop_gt, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w]\n vm_crop_gt = m[np.newaxis, ...]\n\n m = transform.rescale(fm_crop, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w] \n fm_crop = m[np.newaxis, ...]\n\n refine_loss_mask = 1 - (vm_crop_gt==vm_crop).astype(bool)\n loss_mask = fm_no_crop.astype(int)-vm_no_crop_gt.astype(int)\n # import pdb;pdb.set_trace()\n loss_mask[loss_mask==255]=0\n loss_mask = 1-loss_mask.astype(bool)\n\n vm_no_crop = vm_no_crop[np.newaxis, ...]\n fm_no_crop = fm_no_crop[np.newaxis, ...]\n\n obj_position = np.array([x_min, x_max, y_min, y_max])\n vm_pad = np.array([max(self.patch_h-cur_h, 0), max(self.patch_w-cur_w, 0)])\n vm_scale = np.array([self.patch_h/h, self.patch_w/w])\n counts = np.array([1])\n\n counts = torch.from_numpy(counts).to(self.dtype).to(self.device)\n\n obj_position = torch.from_numpy(obj_position).to(self.dtype).to(self.device)\n vm_pad = torch.from_numpy(vm_pad).to(self.dtype).to(self.device)\n vm_scale = torch.from_numpy(vm_scale).to(self.dtype).to(self.device)\n\n fm_crop = torch.from_numpy(fm_crop).to(self.dtype).to(self.device)\n fm_no_crop = torch.from_numpy(np.array(fm_no_crop)).to(self.dtype).to(self.device)\n vm_crop = torch.from_numpy(vm_crop).to(self.dtype).to(self.device)\n vm_crop_gt = torch.from_numpy(vm_crop_gt).to(self.dtype).to(self.device)\n vm_no_crop_gt = torch.from_numpy(vm_no_crop_gt).to(self.dtype).to(self.device)\n vm_no_crop = torch.from_numpy(np.array(vm_no_crop)).to(self.dtype).to(self.device)\n refine_loss_mask = torch.from_numpy(np.array(refine_loss_mask)).to(self.dtype).to(self.device)\n center_crop = torch.from_numpy(np.array(center_crop)).to(self.dtype).to(self.device)\n \n img_crop = torch.from_numpy(np.array(img_crop)).to(self.dtype).to(self.device)\n img = torch.from_numpy(np.array(img)).to(self.dtype).to(self.device)\n\n loss_mask = torch.from_numpy(np.array(loss_mask)).to(self.dtype).to(self.device)\n \n image_id = torch.from_numpy(np.array(image_id)).to(self.dtype).to(self.device)\n anno_id = torch.from_numpy(np.array(anno_id)).to(self.dtype).to(self.device)\n \n if self.mode==\"train\":\n meta = {\n # \"vm_no_crop\": vm_no_crop,\n \"vm_crop\": vm_crop,\n # \"vm_crop_gt\": vm_crop_gt,\n # \"fm_no_crop\": fm_no_crop,\n \"fm_crop\": fm_crop,\n \"img_crop\": img_crop,\n \"center_crop\": center_crop,\n # \"loss_mask\": loss_mask,\n \"obj_position\": obj_position,\n \"vm_pad\": vm_pad,\n \"vm_scale\": vm_scale,\n \"counts\":counts,\n \"img_id\": image_id,\n \"anno_id\": anno_id,\n # for vq\n # \"mask_crop\": fm_crop\n }\n # elif self.mode==\"test\":\n # meta = {\n # # \"vm_no_crop\": vm_no_crop,\n # \"vm_crop\": vm_crop,\n # \"vm_crop_gt\": vm_crop_gt,\n # # \"vm_no_crop_gt\": vm_no_crop_gt,\n # # \"refine_loss_mask\": refine_loss_mask,\n # # \"fm_no_crop\": fm_no_crop,\n # \"fm_crop\": fm_crop,\n # \"img_crop\": img_crop,\n # # \"loss_mask\": loss_mask,\n # # \"obj_position\": obj_position,\n # # \"vm_pad\": vm_pad,\n # # \"vm_scale\": vm_scale,\n # # \"counts\":counts,\n # # \"img_id\": image_id,\n # # \"anno_id\": anno_id,\n # # # for vq\n # # # \"mask_crop\": fm_crop\n # # # \"img\":img,\n # }\n elif self.mode==\"test\":\n meta = {\n \"vm_no_crop\": vm_no_crop,\n \"vm_crop\": vm_crop,\n \"vm_crop_gt\": vm_crop_gt,\n \"vm_no_crop_gt\": vm_no_crop_gt,\n \"fm_no_crop\": fm_no_crop,\n \"fm_crop\": fm_crop,\n \"img_crop\": img_crop,\n \"center_crop\": center_crop,\n \"loss_mask\": loss_mask,\n \"obj_position\": obj_position,\n \"vm_pad\": vm_pad,\n \"vm_scale\": vm_scale,\n \"counts\":counts,\n \"img_id\": image_id,\n \"anno_id\": anno_id,\n # for vq\n # \"mask_crop\": fm_crop\n \"img\":img,\n }\n return meta\n\n @staticmethod\n def collate_fn(batch):\n keys = batch[0].keys()\n res = {}\n for k in keys:\n temp_ = []\n for b in batch:\n if b[k] is not None:\n temp_.append(b[k])\n if len(temp_) > 0:\n res[k] = default_collate(temp_)\n else:\n res[k] = None\n\n return res\n\n def create_iterator(self, batch_size):\n while True:\n sample_loader = DataLoader(\n dataset=self,\n batch_size=batch_size,\n drop_last=True,\n collate_fn=self.collate_fn\n )\n\n for item in sample_loader:\n yield item\n\n def polys_to_mask(self, polygons, height, width):\n rles = mask_utils.frPyObjects(polygons, height, width)\n rle = mask_utils.merge(rles)\n mask = mask_utils.decode(rle)\n return mask\n \n def make_json_dict(self, imgs, anns):\n imgs_dict = {}\n anns_dict = {}\n for ann in anns:\n image_id = ann[\"image_id\"]\n if not image_id in anns_dict:\n anns_dict[image_id] = []\n anns_dict[image_id].append(ann)\n else:\n anns_dict[image_id].append(ann)\n \n for img in imgs:\n image_id = img['id']\n imgs_dict[image_id] = img['file_name']\n\n return imgs_dict, anns_dict" }, { "identifier": "COCOA_Fusion_dataset", "path": "data/dataloader_COCOA.py", "snippet": "class COCOA_Fusion_dataset(torch.utils.data.Dataset):\n def __init__(self, config, mode):\n super(COCOA_Fusion_dataset, self).__init__()\n self.config = config\n self.mode = mode\n self.root_path = config.root_path\n \n # Load Fusion dataset \n self.data_info = pickle.load(open(os.path.join(self.root_path, \"fusion_{}.pkl\".format(self.mode)), \"rb\"))\n self.label_info = np.genfromtxt(os.path.join(self.root_path, \"c2f_seg_{}_list.txt\".format(self.mode)), dtype=np.str, encoding='utf-8')\n \n if mode==\"train\":\n train_label = cvb.load(os.path.join(self.root_path, \"COCO_amodal_train2014_with_classes.json\"))\n self.anns_dict = train_label[\"annotations\"]\n self.img_root_path = os.path.join(self.root_path, \"train2014\")\n elif mode==\"test\":\n val_label = cvb.load(os.path.join(self.root_path, \"COCO_amodal_val2014_with_classes.json\"))\n self.anns_dict = val_label[\"annotations\"]\n self.img_root_path = os.path.join(self.root_path, \"val2014\")\n \n self.dtype = torch.float32\n self.enlarge_coef = 2\n self.patch_h = 256\n self.patch_w = 256\n self.device = \"cpu\"\n\n \n def __len__(self):\n return self.label_info.shape[0]\n\n def __getitem__(self, index):\n return self.load_item(index)\n \n def load_item(self, index):\n # predicted vm\n if len(self.label_info[index].split(\",\"))==3:\n dataset_name, image_id, anno_id = self.label_info[index].split(\",\")\n image_id, anno_id = int(image_id), int(anno_id)\n if self.mode==\"train\":\n img_path = os.path.join(self.img_root_path, \"COCO_{}2014_{}.jpg\".format(self.mode, str(image_id).zfill(12)))\n elif self.mode==\"test\":\n img_path = os.path.join(self.img_root_path, \"COCO_val2014_{}.jpg\".format(str(image_id).zfill(12)))\n img = np.array(Image.open(img_path))\n if len(img.shape)==2:\n img = np.repeat(img[:, :, np.newaxis], 3, axis=2)\n instances = self.data_info[\"{}_{}\".format(dataset_name, image_id)][anno_id]\n segmentation = instances[\"pred_visible_mask\"]\n height, weight = segmentation[\"size\"]\n # occlude_rate = instances[\"occlude_rate\"]\n vm_no_crop = mask_utils.decode([segmentation]).astype(bool)\n fm_no_crop = mask_utils.decode([instances[\"gt_full_mask\"]]).astype(bool)\n vm_no_crop_gt = mask_utils.decode([instances[\"gt_visible_mask\"]]).astype(bool)\n\n bbox = instances[\"pred_visible_mask_bbox\"]\n y_min, x_min, w, h = bbox\n y_max, x_max = y_min + w, x_min + h\n x_center = (x_min + x_max) // 2\n y_center = (y_min + y_max) // 2\n x_len = int((x_max - x_min) * self.enlarge_coef)\n y_len = int((y_max - y_min) * self.enlarge_coef)\n x_min = max(0, x_center - x_len // 2)\n x_max = min(height, x_center + x_len // 2)\n y_min = max(0, y_center - y_len // 2)\n y_max = min(weight, y_center + y_len // 2)\n x_min, x_max, y_min, y_max = int(x_min), int(x_max), int(y_min), int(y_max)\n # import pdb;pdb.set_trace()\n vm_crop = vm_no_crop[x_min:x_max+1, y_min:y_max+1, 0].astype(bool)\n fm_crop = fm_no_crop[x_min:x_max+1, y_min:y_max+1, 0].astype(bool)\n img_crop = img[x_min:x_max+1, y_min:y_max+1]\n vm_crop_gt = vm_no_crop_gt[x_min:x_max+1, y_min:y_max+1, 0].astype(bool)\n\n h, w = vm_crop.shape[:2]\n m = transform.rescale(vm_crop, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w]\n vm_crop = m[np.newaxis, ...]\n\n img_ = transform.rescale(img_crop, (self.patch_h/h, self.patch_w/w, 1))\n cur_h, cur_w = img_.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)), (0, 0))\n img_ = np.pad(img_, to_pad)[:self.patch_h, :self.patch_w, :3]\n img_crop = img_\n\n h, w = vm_crop_gt.shape[:2]\n m = transform.rescale(vm_crop_gt, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w]\n vm_crop_gt = m[np.newaxis, ...]\n\n # data augmentation\n vm_crop_aug = self.data_augmentation(vm_crop[0])[np.newaxis, ...]\n\n m = transform.rescale(fm_crop, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w] \n fm_crop = m[np.newaxis, ...]\n # if self.mode==\"test\":\n # loss_mask = mask_utils.decode([instances[\"loss_mask\"]]).astype(bool)[...,0]\n # else:\n loss_mask = fm_no_crop.astype(int)-vm_no_crop_gt.astype(int)\n loss_mask[loss_mask==255]=0\n loss_mask = 1-loss_mask.astype(bool)\n\n vm_no_crop = vm_no_crop[np.newaxis, ...]\n fm_no_crop = fm_no_crop[np.newaxis, ...]\n\n obj_position = np.array([x_min, x_max, y_min, y_max])\n vm_pad = np.array([max(self.patch_h-cur_h, 0), max(self.patch_w-cur_w, 0)])\n vm_scale = np.array([self.patch_h/h, self.patch_w/w])\n counts = np.array([1])\n counts = torch.from_numpy(counts).to(self.dtype).to(self.device)\n\n obj_position = torch.from_numpy(obj_position).to(self.dtype).to(self.device)\n vm_pad = torch.from_numpy(vm_pad).to(self.dtype).to(self.device)\n vm_scale = torch.from_numpy(vm_scale).to(self.dtype).to(self.device)\n\n fm_crop = torch.from_numpy(fm_crop).to(self.dtype).to(self.device)\n fm_no_crop = torch.from_numpy(np.array(fm_no_crop)).to(self.dtype).to(self.device)\n vm_crop = torch.from_numpy(vm_crop).to(self.dtype).to(self.device)\n vm_crop_gt = torch.from_numpy(vm_crop_gt).to(self.dtype).to(self.device)\n vm_crop_aug = torch.from_numpy(vm_crop_aug).to(self.dtype).to(self.device)\n vm_no_crop = torch.from_numpy(np.array(vm_no_crop)).to(self.dtype).to(self.device)\n\n img_crop = torch.from_numpy(np.array(img_crop)).to(self.dtype).to(self.device)\n img = torch.from_numpy(np.array(img)).to(self.dtype).to(self.device)\n loss_mask = torch.from_numpy(np.array(loss_mask)).to(self.dtype).to(self.device)\n \n image_id = torch.from_numpy(np.array(image_id)).to(self.dtype).to(self.device)\n anno_id = torch.from_numpy(np.array(anno_id)).to(self.dtype).to(self.device)\n # occlude_rate = torch.from_numpy(np.array(occlude_rate)).to(self.dtype).to(self.device)\n \n if self.mode==\"train\":\n meta = {\n # \"vm_no_crop\": vm_no_crop,\n # \"vm_crop\": vm_crop,\n \"vm_crop\": vm_crop_aug,\n \"vm_crop_gt\": vm_crop_gt,\n # \"vm_crop_gt\": vm_crop_gt,\n # \"fm_no_crop\": fm_no_crop,\n \"fm_crop\": fm_crop,\n \"img_crop\": img_crop,\n # \"loss_mask\": loss_mask,\n \"obj_position\": obj_position,\n \"vm_pad\": vm_pad,\n \"vm_scale\": vm_scale,\n \"counts\":counts,\n \"img_id\": image_id,\n \"anno_id\": anno_id,\n # for vq\n # \"mask_crop\": fm_crop\n # \"img_no_crop\": img,\n }\n elif self.mode==\"test\":\n meta = {\n \"vm_no_crop\": vm_no_crop,\n \"vm_crop\": vm_crop,\n \"img_crop\": img_crop,\n \"vm_crop_gt\": vm_crop_gt,\n \"fm_no_crop\": fm_no_crop,\n \"fm_crop\": fm_crop,\n \"loss_mask\": loss_mask,\n \"obj_position\": obj_position,\n \"vm_pad\": vm_pad,\n \"vm_scale\": vm_scale,\n \"counts\":counts,\n \"img_id\": image_id,\n \"anno_id\": anno_id,\n # \"occlude_rate\":occlude_rate\n # for vq\n # \"mask_crop\": fm_crop\n # \"img_no_crop\": img,\n }\n return meta\n # gt vm\n elif len(self.label_info[index].split(\",\"))==2:\n anno_id, img_path = self.label_info[index].split(\",\")\n anno_id = int(anno_id)\n img = cv2.imread(img_path, cv2.IMREAD_COLOR)\n height, width, _ = img.shape\n\n ann = self.anns_dict[anno_id]\n img_id = ann[\"image_id\"]\n # category_id = ann[\"category_id\"]\n\n full_mask = ann[\"segmentation\"]\n fm_no_crop = mask_utils.decode(full_mask)[...,np.newaxis]\n\n visible_mask = ann[\"visible_mask\"]\n vm_no_crop = mask_utils.decode(visible_mask)[...,np.newaxis]\n\n if np.sum(vm_no_crop)==0:\n counts = np.array([0])\n else:\n counts = np.array([1])\n y_min, x_min, w, h = ann[\"bbox\"]\n y_max, x_max = y_min + w, x_min + h\n y_min, x_min, y_max, x_max = int(y_min), int(x_min), int(y_max), int(x_max) \n\n x_center = (x_min + x_max) // 2\n y_center = (y_min + y_max) // 2\n x_len = int((x_max - x_min) * self.enlarge_coef)\n y_len = int((y_max - y_min) * self.enlarge_coef)\n x_min = max(0, x_center - x_len // 2)\n x_max = min(height, x_center + x_len // 2)\n y_min = max(0, y_center - y_len // 2)\n y_max = min(width, y_center + y_len // 2)\n \n fm_crop = fm_no_crop[x_min:x_max+1, y_min:y_max+1, 0].astype(bool)\n vm_crop = vm_no_crop[x_min:x_max+1, y_min:y_max+1, 0].astype(bool)\n img_crop = img[x_min:x_max+1, y_min:y_max+1]\n\n h, w = vm_crop.shape[:2]\n m = transform.rescale(vm_crop, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w]\n vm_crop = m[np.newaxis, ...]\n\n img_ = transform.rescale(img_crop, (self.patch_h/h, self.patch_w/w, 1))\n cur_h, cur_w = img_.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)), (0, 0))\n img_ = np.pad(img_, to_pad)[:self.patch_h, :self.patch_w, :3]\n img_crop = img_\n\n m = transform.rescale(fm_crop, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w] \n fm_crop = m[np.newaxis, ...]\n\n obj_position = np.array([x_min, x_max, y_min, y_max])\n vm_pad = np.array([max(self.patch_h-cur_h, 0), max(self.patch_w-cur_w, 0)])\n vm_scale = np.array([self.patch_h/h, self.patch_w/w])\n\n # full_pad = ((0, max(375-height, 0)), (0, max(1242-width, 0)))\n # vm_no_crop = np.pad(vm_no_crop, full_pad)[:375, :1242]\n # fm_no_crop = np.pad(fm_no_crop, full_pad)[:375, :1242]\n vm_no_crop = vm_no_crop[np.newaxis, ...]\n fm_no_crop = fm_no_crop[np.newaxis, ...]\n\n loss_mask = fm_no_crop-vm_no_crop\n loss_mask[loss_mask==255]=0\n loss_mask = 1-loss_mask.astype(bool)\n # data augmentation\n vm_crop_aug = self.data_augmentation(vm_crop[0])[np.newaxis, ...]\n \n counts = torch.from_numpy(counts).to(self.dtype).to(self.device)\n\n obj_position = torch.from_numpy(obj_position).to(self.dtype).to(self.device)\n vm_pad = torch.from_numpy(vm_pad).to(self.dtype).to(self.device)\n vm_scale = torch.from_numpy(vm_scale).to(self.dtype).to(self.device)\n\n fm_crop = torch.from_numpy(fm_crop).to(self.dtype).to(self.device)\n fm_no_crop = torch.from_numpy(np.array(fm_no_crop)).to(self.dtype).to(self.device)\n vm_crop = torch.from_numpy(vm_crop).to(self.dtype).to(self.device)\n vm_crop_aug = torch.from_numpy(vm_crop_aug).to(self.dtype).to(self.device)\n img_crop = torch.from_numpy(img_crop).to(self.dtype).to(self.device)\n img = torch.from_numpy(img).to(self.dtype).to(self.device)\n vm_no_crop = torch.from_numpy(np.array(vm_no_crop)).to(self.dtype).to(self.device)\n \n loss_mask = torch.from_numpy(np.array(loss_mask)).to(self.dtype).to(self.device)\n \n img_id = torch.from_numpy(np.array(img_id)).to(self.dtype).to(self.device)\n anno_id = torch.from_numpy(np.array(anno_id)).to(self.dtype).to(self.device)\n # category_id = torch.from_numpy(np.array(category_id)).to(self.dtype).to(self.device)\n if self.mode==\"train\":\n meta = {\n # \"vm_no_crop\": vm_no_crop,\n \"vm_crop\": vm_crop_aug,\n \"vm_crop_gt\": vm_crop,\n # \"fm_no_crop\": fm_no_crop,\n \"fm_crop\": fm_crop,\n \"img_crop\": img_crop,\n # \"loss_mask\": loss_mask,\n \"obj_position\": obj_position,\n \"vm_pad\": vm_pad,\n \"vm_scale\": vm_scale,\n \"counts\": counts,\n \"img_id\": img_id,\n \"anno_id\": anno_id,\n # \"category_id\": category_id,\n # for vq\n # \"mask_crop\": fm_crop\n # \"img_no_crop\": img\n }\n elif self.mode==\"test\":\n meta = {\n \"vm_no_crop\": vm_no_crop,\n \"vm_no_crop_gt\": vm_no_crop,\n \"vm_crop\": vm_crop,\n \"vm_crop_gt\": vm_crop,\n \"fm_no_crop\": fm_no_crop,\n \"fm_crop\": fm_crop,\n \"img_crop\": img_crop,\n \"loss_mask\": loss_mask,\n \"obj_position\": obj_position,\n \"vm_pad\": vm_pad,\n \"vm_scale\": vm_scale,\n \"counts\":counts,\n \"img_id\": img_id,\n \"anno_id\": anno_id,\n # \"category_id\": category_id,\n # for vq\n # \"mask_crop\": fm_crop\n \"img_no_crop\": img,\n }\n return meta\n \n @staticmethod\n def collate_fn(batch):\n keys = batch[0].keys()\n res = {}\n for k in keys:\n temp_ = []\n for b in batch:\n if b[k] is not None:\n temp_.append(b[k])\n if len(temp_) > 0:\n res[k] = default_collate(temp_)\n else:\n res[k] = None\n\n return res\n\n def create_iterator(self, batch_size):\n while True:\n sample_loader = DataLoader(\n dataset=self,\n batch_size=batch_size,\n drop_last=True,\n collate_fn=self.collate_fn\n )\n\n for item in sample_loader:\n yield item\n\n def polys_to_mask(self, polygons, height, width):\n rles = mask_utils.frPyObjects(polygons, height, width)\n rle = mask_utils.merge(rles)\n mask = mask_utils.decode(rle)\n return mask\n\n # def data_augmentation(self, mask):\n # return mask\n \n def data_augmentation(self, mask):\n mask = mask.astype(np.float)\n rdv = random.random()\n n_repeat = random.randint(1, 4)\n if rdv <= 0.2:\n mask = cv2.GaussianBlur(mask, (35,35), 11)\n elif rdv > 0.2 and rdv <0.9:\n rdv_1 = random.random()\n rdv_2 = random.random()\n for i in range(n_repeat):\n w = random.randint(5, 13)\n h = random.randint(5, 13)\n kernel = np.ones((w, h), dtype=np.uint8)\n if rdv_1 <= 0.6:\n mask = cv2.dilate(mask, kernel, 1)\n elif rdv_1 > 0.6 and rdv_1 <= 1.0:\n mask = cv2.erode(mask, kernel, 1)\n if rdv_2 <= 0.2:\n mask = cv2.GaussianBlur(mask, (35,35), 11)\n else:\n mask = mask\n return (mask>0.5)\n \n def make_json_dict(self, imgs, anns):\n imgs_dict = {}\n anns_dict = {}\n for ann in anns:\n image_id = ann[\"image_id\"]\n if not image_id in anns_dict:\n anns_dict[image_id] = []\n anns_dict[image_id].append(ann)\n else:\n anns_dict[image_id].append(ann)\n \n for img in imgs:\n image_id = img['id']\n imgs_dict[image_id] = img['file_name']\n\n return imgs_dict, anns_dict" }, { "identifier": "COCOA_VRSP", "path": "data/dataloader_COCOA.py", "snippet": "class COCOA_VRSP(torch.utils.data.Dataset):\n def __init__(self, config, mode):\n super(COCOA_VRSP, self).__init__()\n self.config = config\n self.mode = mode\n self.data_info = pickle.load(open(os.path.join(self.root_path, \"fusion_{}.pkl\".format(self.mode)), \"rb\"))\n self.label_info = np.genfromtxt(os.path.join(self.root_path, \"c2f_seg_{}_list.txt\".format(self.mode)), dtype=np.str, encoding='utf-8')\n \n if self.mode==\"train\":\n self.img_root_path = os.path.join(self.root_path, \"train2014\")\n elif self.mode==\"test\":\n self.img_root_path = os.path.join(self.root_path, \"val2014\")\n\n self.dtype = torch.float32\n self.enlarge_coef = 2\n self.patch_h = 256\n self.patch_w = 256\n self.device = \"cpu\"\n\n \n def __len__(self):\n return self.label_info.shape[0]\n\n def __getitem__(self, index):\n return self.load_item(index)\n \n def generate_heatmap(self, mask, kernel, sigma):\n heatmap = cv2.GaussianBlur(mask, kernel, sigma)\n am = np.amax(heatmap)\n heatmap /= am / 1\n return heatmap\n \n def load_item(self, index):\n image_id, anno_id = self.label_info[index].split(\"_\")\n image_id, anno_id = int(image_id), int(anno_id)\n if self.mode==\"train\":\n img_path = os.path.join(self.img_root_path, \"COCO_{}2014_{}.jpg\".format(self.mode, str(image_id).zfill(12)))\n elif self.mode==\"test\":\n img_path = os.path.join(self.img_root_path, \"COCO_val2014_{}.jpg\".format(str(image_id).zfill(12)))\n img = np.array(Image.open(img_path))\n if len(img.shape)==2:\n img = np.repeat(img[:, :, np.newaxis], 3, axis=2)\n instances = self.data_info[image_id][anno_id]\n segmentation = instances[\"pred_visible_mask\"]\n height, weight = segmentation[\"size\"]\n occlude_rate = instances[\"occlude_rate\"]\n vm_no_crop = mask_utils.decode([segmentation]).astype(bool)\n fm_no_crop = mask_utils.decode([instances[\"gt_full_mask\"]]).astype(bool)\n vm_no_crop_gt = mask_utils.decode([instances[\"gt_visible_mask\"]]).astype(bool)\n\n bbox = instances[\"pred_visible_mask_bbox\"]\n y_min, x_min, w, h = bbox\n y_max, x_max = y_min + w, x_min + h\n x_center = (x_min + x_max) // 2\n y_center = (y_min + y_max) // 2\n x_len = int((x_max - x_min) * self.enlarge_coef)\n y_len = int((y_max - y_min) * self.enlarge_coef)\n x_min = max(0, x_center - x_len // 2)\n x_max = min(height, x_center + x_len // 2)\n y_min = max(0, y_center - y_len // 2)\n y_max = min(weight, y_center + y_len // 2)\n x_min, x_max, y_min, y_max = int(x_min), int(x_max), int(y_min), int(y_max)\n \n x_center_crop = x_center - x_min\n y_center_crop = y_center - y_min\n\n vm_crop = vm_no_crop[x_min:x_max+1, y_min:y_max+1, 0].astype(bool)\n fm_crop = fm_no_crop[x_min:x_max+1, y_min:y_max+1, 0].astype(bool)\n img_crop = img[x_min:x_max+1, y_min:y_max+1]\n vm_crop_gt = vm_no_crop_gt[x_min:x_max+1, y_min:y_max+1, 0].astype(bool)\n\n h, w = vm_crop.shape[:2]\n m = transform.rescale(vm_crop, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w]\n vm_crop = m[np.newaxis, ...]\n\n center_crop = np.zeros_like(vm_crop[0])\n x_center_crop = int(x_center_crop*self.patch_h/h)\n y_center_crop = int(y_center_crop*self.patch_w/w)\n center_crop[x_center_crop: x_center_crop+1, y_center_crop: y_center_crop+1]=1\n center_crop = self.generate_heatmap(center_crop.astype(np.float), (35, 35), 9)\n center_crop = center_crop[np.newaxis, ...]\n\n img_ = transform.rescale(img_crop, (self.patch_h/h, self.patch_w/w, 1))\n cur_h, cur_w = img_.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)), (0, 0))\n img_ = np.pad(img_, to_pad)[:self.patch_h, :self.patch_w, :3]\n img_crop = img_\n\n h, w = vm_crop_gt.shape[:2]\n m = transform.rescale(vm_crop_gt, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w]\n vm_crop_gt = m[np.newaxis, ...]\n\n m = transform.rescale(fm_crop, (self.patch_h/h, self.patch_w/w))\n cur_h, cur_w = m.shape[:2]\n to_pad = ((0, max(self.patch_h-cur_h, 0)), (0, max(self.patch_w-cur_w, 0)))\n m = np.pad(m, to_pad)[:self.patch_h, :self.patch_w] \n fm_crop = m[np.newaxis, ...]\n\n loss_mask = fm_no_crop.astype(int)-vm_no_crop_gt.astype(int)\n loss_mask[loss_mask==255]=0\n loss_mask = 1-loss_mask.astype(bool)\n\n vm_no_crop = vm_no_crop[np.newaxis, ...]\n fm_no_crop = fm_no_crop[np.newaxis, ...]\n\n obj_position = np.array([x_min, x_max, y_min, y_max])\n vm_pad = np.array([max(self.patch_h-cur_h, 0), max(self.patch_w-cur_w, 0)])\n vm_scale = np.array([self.patch_h/h, self.patch_w/w])\n counts = np.array([1])\n\n counts = torch.from_numpy(counts).to(self.dtype).to(self.device)\n\n obj_position = torch.from_numpy(obj_position).to(self.dtype).to(self.device)\n vm_pad = torch.from_numpy(vm_pad).to(self.dtype).to(self.device)\n vm_scale = torch.from_numpy(vm_scale).to(self.dtype).to(self.device)\n\n fm_crop = torch.from_numpy(fm_crop).to(self.dtype).to(self.device)\n fm_no_crop = torch.from_numpy(np.array(fm_no_crop)).to(self.dtype).to(self.device)\n vm_crop = torch.from_numpy(vm_crop).to(self.dtype).to(self.device)\n vm_crop_gt = torch.from_numpy(vm_crop_gt).to(self.dtype).to(self.device)\n vm_no_crop = torch.from_numpy(np.array(vm_no_crop)).to(self.dtype).to(self.device)\n center_crop = torch.from_numpy(np.array(center_crop)).to(self.dtype).to(self.device)\n \n img_crop = torch.from_numpy(np.array(img_crop)).to(self.dtype).to(self.device)\n img = torch.from_numpy(np.array(img)).to(self.dtype).to(self.device)\n\n loss_mask = torch.from_numpy(np.array(loss_mask)).to(self.dtype).to(self.device)\n \n image_id = torch.from_numpy(np.array(image_id)).to(self.dtype).to(self.device)\n anno_id = torch.from_numpy(np.array(anno_id)).to(self.dtype).to(self.device)\n occlude_rate = torch.from_numpy(np.array(occlude_rate)).to(self.dtype).to(self.device)\n \n if self.mode==\"train\":\n meta = {\n # \"vm_no_crop\": vm_no_crop,\n \"vm_crop\": vm_crop,\n # \"vm_crop_gt\": vm_crop_gt,\n # \"fm_no_crop\": fm_no_crop,\n \"fm_crop\": fm_crop,\n \"img_crop\": img_crop,\n \"center_crop\": center_crop,\n # \"loss_mask\": loss_mask,\n \"obj_position\": obj_position,\n \"vm_pad\": vm_pad,\n \"vm_scale\": vm_scale,\n \"counts\":counts,\n \"img_id\": image_id,\n \"anno_id\": anno_id,\n \"img_no_crop\": img,\n }\n elif self.mode==\"test\":\n meta = {\n \"vm_no_crop\": vm_no_crop,\n \"vm_no_crop_gt\": vm_no_crop_gt,\n \"vm_crop\": vm_crop,\n \"vm_crop_gt\": vm_crop_gt,\n \"fm_no_crop\": fm_no_crop,\n \"fm_crop\": fm_crop,\n \"img_crop\": img_crop,\n \"center_crop\": center_crop,\n \"loss_mask\": loss_mask,\n \"obj_position\": obj_position,\n \"vm_pad\": vm_pad,\n \"vm_scale\": vm_scale,\n \"counts\":counts,\n \"img_id\": image_id,\n \"anno_id\": anno_id,\n \"occlude_rate\":occlude_rate,\n # # for vq\n # \"mask_crop\": fm_crop,\n \"img\": img,\n }\n return meta\n\n @staticmethod\n def collate_fn(batch):\n keys = batch[0].keys()\n res = {}\n for k in keys:\n temp_ = []\n for b in batch:\n if b[k] is not None:\n temp_.append(b[k])\n if len(temp_) > 0:\n res[k] = default_collate(temp_)\n else:\n res[k] = None\n\n return res\n\n def create_iterator(self, batch_size):\n while True:\n sample_loader = DataLoader(\n dataset=self,\n batch_size=batch_size,\n drop_last=True,\n collate_fn=self.collate_fn\n )\n\n for item in sample_loader:\n yield item\n\n def polys_to_mask(self, polygons, height, width):\n rles = mask_utils.frPyObjects(polygons, height, width)\n rle = mask_utils.merge(rles)\n mask = mask_utils.decode(rle)\n return mask" } ]
from data.dataloader_Fishbowl import FishBowl from data.dataloader_MOViD_A import MOViD_A from data.dataloader_KINS import Kins_Fusion_dataset, KINS_Aisformer_VRSP_Intersection from data.dataloader_COCOA import COCOA_Fusion_dataset, COCOA_VRSP
21,229
def load_dataset(config, args, mode): if mode=="train": if args.dataset=="KINS": train_dataset = Kins_Fusion_dataset(config, mode='train') test_dataset = Kins_Fusion_dataset(config, mode='test') elif args.dataset=="COCOA": train_dataset = COCOA_Fusion_dataset(config, mode='train') test_dataset = COCOA_Fusion_dataset(config, mode='test') elif args.dataset=="Fishbowl":
def load_dataset(config, args, mode): if mode=="train": if args.dataset=="KINS": train_dataset = Kins_Fusion_dataset(config, mode='train') test_dataset = Kins_Fusion_dataset(config, mode='test') elif args.dataset=="COCOA": train_dataset = COCOA_Fusion_dataset(config, mode='train') test_dataset = COCOA_Fusion_dataset(config, mode='test') elif args.dataset=="Fishbowl":
train_dataset = FishBowl(config, mode='train')
0
2023-12-21 04:25:47+00:00
24k
alipay/PainlessInferenceAcceleration
pia/lookahead/models/baichuan/modeling_baichuan.py
[ { "identifier": "LookaheadPreTrainedModel", "path": "pia/lookahead/common/pretrained_model.py", "snippet": "class LookaheadPreTrainedModel(PreTrainedModel):\n _batch_generation = False\n _stream_generation = False\n\n def __init__(self, config):\n super().__init__(config=config)\n\n def _get_generation_mode(\n self, generation_config: GenerationConfig, assistant_model: Optional[\"PreTrainedModel\"]\n ) -> GenerationMode:\n \"\"\"\n Returns the generation mode triggered by a [`GenerationConfig`] instance.\n \"\"\"\n if generation_config.constraints is not None or generation_config.force_words_ids is not None:\n generation_mode = GenerationMode.CONSTRAINED_BEAM_SEARCH\n elif generation_config.num_beams == 1:\n if generation_config.do_sample is False:\n if (\n generation_config.top_k is not None\n and generation_config.top_k > 1\n and generation_config.penalty_alpha is not None\n and generation_config.penalty_alpha > 0\n ):\n generation_mode = GenerationMode.CONTRASTIVE_SEARCH\n elif generation_config.use_cache \\\n and hasattr(generation_config, 'decoding_kwargs') \\\n and generation_config.decoding_kwargs.get('use_lookahead', False) \\\n and generation_config.decoding_kwargs.get('decoding_length', 64) > 1 \\\n and generation_config.decoding_kwargs.get('branch_length', 12) > 0:\n generation_mode = GenerationMode.LOOKAHEAD_GENERATION\n else:\n generation_mode = GenerationMode.GREEDY_SEARCH\n else:\n if generation_config.use_cache \\\n and hasattr(generation_config, 'decoding_kwargs') \\\n and generation_config.decoding_kwargs.get('use_lookahead', False) \\\n and generation_config.decoding_kwargs.get('decoding_length', 64) > 1 \\\n and generation_config.decoding_kwargs.get('branch_length', 12) > 0:\n generation_mode = GenerationMode.LOOKAHEAD_GENERATION\n else:\n generation_mode = GenerationMode.SAMPLE\n else:\n if generation_config.num_beam_groups > 1:\n generation_mode = GenerationMode.GROUP_BEAM_SEARCH\n elif generation_config.do_sample is True:\n generation_mode = GenerationMode.BEAM_SAMPLE\n else:\n generation_mode = GenerationMode.BEAM_SEARCH\n\n # Assisted generation may extend some generation modes\n if assistant_model is not None:\n if generation_mode in (\"greedy_search\", \"sample\"):\n generation_mode = GenerationMode.ASSISTED_GENERATION\n else:\n raise ValueError(\n \"You've set `assistant_model`, which triggers assisted generate. Currently, assisted generate \"\n \"is only supported with Greedy Search and Sample.\"\n )\n return generation_mode\n\n @torch.no_grad()\n def generate(\n self,\n inputs: Optional[torch.Tensor] = None,\n generation_config: Optional[GenerationConfig] = None,\n logits_processor: Optional[LogitsProcessorList] = None,\n stopping_criteria: Optional[StoppingCriteriaList] = None,\n prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,\n synced_gpus: Optional[bool] = None,\n assistant_model: Optional[\"PreTrainedModel\"] = None,\n streamer: Optional[\"BaseStreamer\"] = None,\n **kwargs,\n ) -> Union[GenerateOutput, torch.LongTensor]:\n r\"\"\"\n\n Generates sequences of token ids for models with a language modeling head.\n\n <Tip warning={true}>\n\n Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the\n model's default generation configuration. You can override any `generation_config` by passing the corresponding\n parameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`.\n\n For an overview of generation strategies and code examples, check out the [following\n guide](../generation_strategies).\n\n </Tip>\n\n Parameters:\n inputs (`torch.Tensor` of varying shape depending on the modality, *optional*):\n The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the\n method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs`\n should of in the format of `input_ids`. For encoder-decoder models *inputs* can represent any of\n `input_ids`, `input_values`, `input_features`, or `pixel_values`.\n generation_config (`~generation.GenerationConfig`, *optional*):\n The generation configuration to be used as base parametrization for the generation call. `**kwargs`\n passed to generate matching the attributes of `generation_config` will override them. If\n `generation_config` is not provided, the default will be used, which had the following loading\n priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model\n configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s\n default values, whose documentation should be checked to parameterize generation.\n logits_processor (`LogitsProcessorList`, *optional*):\n Custom logits processors that complement the default logits processors built from arguments and\n generation config. If a logit processor is passed that is already created with the arguments or a\n generation config an error is thrown. This feature is intended for advanced users.\n stopping_criteria (`StoppingCriteriaList`, *optional*):\n Custom stopping criteria that complement the default stopping criteria built from arguments and a\n generation config. If a stopping criteria is passed that is already created with the arguments or a\n generation config an error is thrown. This feature is intended for advanced users.\n prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`, *optional*):\n If provided, this function constraints the beam search to allowed tokens only at each step. If not\n provided no constraint is applied. This function takes 2 arguments: the batch ID `batch_id` and\n `input_ids`. It has to return a list with the allowed tokens for the next generation step conditioned\n on the batch ID `batch_id` and the previously generated tokens `inputs_ids`. This argument is useful\n for constrained generation conditioned on the prefix, as described in [Autoregressive Entity\n Retrieval](https://arxiv.org/abs/2010.00904).\n synced_gpus (`bool`, *optional*):\n Whether to continue running the while loop until max_length. Unless overridden this flag will be set to\n `True` under DeepSpeed ZeRO Stage 3 multiple GPUs environment to avoid hanging if one GPU finished\n generating before other GPUs. Otherwise it'll be set to `False`.\n assistant_model (`PreTrainedModel`, *optional*):\n An assistant model that can be used to accelerate generation. The assistant model must have the exact\n same tokenizer. The acceleration is achieved when forecasting candidate tokens with the assistent model\n is much faster than running generation with the model you're calling generate from. As such, the\n assistant model should be much smaller.\n streamer (`BaseStreamer`, *optional*):\n Streamer object that will be used to stream the generated sequences. Generated tokens are passed\n through `streamer.put(token_ids)` and the streamer is responsible for any further processing.\n kwargs (`Dict[str, Any]`, *optional*):\n Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be\n forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder\n specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.\n\n Return:\n [`~utils.ModelOutput`] or `torch.LongTensor`: A [`~utils.ModelOutput`] (if `return_dict_in_generate=True`\n or when `config.return_dict_in_generate=True`) or a `torch.FloatTensor`.\n\n If the model is *not* an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible\n [`~utils.ModelOutput`] types are:\n\n - [`~generation.GreedySearchDecoderOnlyOutput`],\n - [`~generation.SampleDecoderOnlyOutput`],\n - [`~generation.BeamSearchDecoderOnlyOutput`],\n - [`~generation.BeamSampleDecoderOnlyOutput`]\n\n If the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible\n [`~utils.ModelOutput`] types are:\n\n - [`~generation.GreedySearchEncoderDecoderOutput`],\n - [`~generation.SampleEncoderDecoderOutput`],\n - [`~generation.BeamSearchEncoderDecoderOutput`],\n - [`~generation.BeamSampleEncoderDecoderOutput`]\n \"\"\"\n\n if synced_gpus is None:\n # if is_deepspeed_zero3_enabled() and dist.get_world_size() > 1:\n # synced_gpus = True\n # else:\n # synced_gpus = False\n synced_gpus = False\n\n # 1. Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call\n self._validate_model_class()\n\n # priority: `generation_config` argument > `model.generation_config` (the default generation config)\n if generation_config is None:\n # legacy: users may modify the model configuration to control generation -- update the generation config\n # model attribute accordingly, if it was created from the model config\n if self.generation_config._from_model_config:\n new_generation_config = GenerationConfig.from_model_config(self.config)\n if new_generation_config != self.generation_config:\n # warnings.warn(\n # \"You have modified the pretrained model configuration to control generation. This is a\"\n # \" deprecated strategy to control generation and will be removed soon, in a future version.\"\n # \" Please use a generation configuration file (see\"\n # \" https://huggingface.co/docs/transformers/main_classes/text_generation )\"\n # )\n self.generation_config = new_generation_config\n generation_config = self.generation_config\n\n generation_config = copy.deepcopy(generation_config)\n model_kwargs = generation_config.update(**kwargs) # All unused kwargs must be model kwargs\n generation_config.validate()\n self._validate_model_kwargs(model_kwargs.copy())\n if not hasattr(generation_config, 'decoding_kwargs'):\n generation_config.decoding_kwargs = model_kwargs.get('decoding_kwargs', {})\n\n # 2. Set generation parameters if not already defined\n logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()\n stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()\n\n if generation_config.pad_token_id is None and generation_config.eos_token_id is not None:\n if model_kwargs.get(\"attention_mask\", None) is None:\n logger.warning(\n \"The attention mask and the pad token id were not set. As a consequence, you may observe \"\n \"unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results.\"\n )\n eos_token_id = generation_config.eos_token_id\n if isinstance(eos_token_id, list):\n eos_token_id = eos_token_id[0]\n logger.warning(f\"Setting `pad_token_id` to `eos_token_id`:{eos_token_id} for open-end generation.\")\n generation_config.pad_token_id = eos_token_id\n\n # 3. Define model inputs\n # inputs_tensor has to be defined\n # model_input_name is defined if model-specific keyword input is passed\n # otherwise model_input_name is None\n # all model-specific keyword inputs are removed from `model_kwargs`\n inputs_tensor, model_input_name, model_kwargs = self._prepare_model_inputs(\n inputs, generation_config.bos_token_id, model_kwargs\n )\n batch_size = inputs_tensor.shape[0]\n\n # 4. Define other model kwargs\n model_kwargs[\"output_attentions\"] = generation_config.output_attentions\n model_kwargs[\"output_hidden_states\"] = generation_config.output_hidden_states\n # decoder-only models with inputs_embeds forwarding must use caching (otherwise we can't detect whether we are\n # generating the first new token or not, and we only want to use the embeddings for the first new token)\n if not self.config.is_encoder_decoder and model_input_name == \"inputs_embeds\":\n model_kwargs[\"use_cache\"] = True\n else:\n model_kwargs[\"use_cache\"] = generation_config.use_cache\n\n accepts_attention_mask = \"attention_mask\" in set(inspect.signature(self.forward).parameters.keys())\n requires_attention_mask = \"encoder_outputs\" not in model_kwargs\n\n if model_kwargs.get(\"attention_mask\", None) is None and requires_attention_mask and accepts_attention_mask:\n model_kwargs[\"attention_mask\"] = self._prepare_attention_mask_for_generation(\n inputs_tensor, generation_config.pad_token_id, generation_config.eos_token_id\n )\n\n # decoder-only models should use left-padding for generation\n if not self.config.is_encoder_decoder:\n # If `input_ids` was given, check if the last id in any sequence is `pad_token_id`\n # Note: If using, `inputs_embeds` this check does not work, because we want to be more hands-off.\n if (\n generation_config.pad_token_id is not None\n and len(inputs_tensor.shape) == 2\n and torch.sum(inputs_tensor[:, -1] == generation_config.pad_token_id) > 0\n ):\n logger.warning(\n \"A decoder-only architecture is being used, but right-padding was detected! For correct \"\n \"generation results, please set `padding_side='left'` when initializing the tokenizer.\"\n )\n\n if self.config.is_encoder_decoder and \"encoder_outputs\" not in model_kwargs:\n # if model is encoder decoder encoder_outputs are created\n # and added to `model_kwargs`\n model_kwargs = self._prepare_encoder_decoder_kwargs_for_generation(\n inputs_tensor, model_kwargs, model_input_name\n )\n\n # 5. Prepare `input_ids` which will be used for auto-regressive generation\n if self.config.is_encoder_decoder:\n input_ids, model_kwargs = self._prepare_decoder_input_ids_for_generation(\n batch_size=batch_size,\n model_input_name=model_input_name,\n model_kwargs=model_kwargs,\n decoder_start_token_id=generation_config.decoder_start_token_id,\n bos_token_id=generation_config.bos_token_id,\n device=inputs_tensor.device,\n )\n else:\n input_ids = inputs_tensor if model_input_name == \"input_ids\" else model_kwargs.pop(\"input_ids\")\n\n if streamer is not None:\n streamer.put(input_ids.cpu())\n\n # 6. Prepare `max_length` depending on other stopping criteria.\n input_ids_length = input_ids.shape[-1]\n has_default_max_length = kwargs.get(\"max_length\") is None and generation_config.max_length is not None\n if generation_config.max_new_tokens is not None:\n if not has_default_max_length:\n logger.warning(\n f\"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(=\"\n f\"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. \"\n \"Please refer to the documentation for more information. \"\n \"(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)\"\n )\n generation_config.max_length = generation_config.max_new_tokens + input_ids_length\n\n # 7. determine generation mode\n generation_mode = self._get_generation_mode(generation_config, assistant_model)\n\n if streamer is not None and (generation_config.num_beams > 1):\n raise ValueError(\n \"`streamer` cannot be used with beam search (yet!). Make sure that `num_beams` is set to 1.\"\n )\n\n if self.device.type != input_ids.device.type:\n warnings.warn(\n \"You are calling .generate() with the `input_ids` being on a device type different\"\n f\" than your model's device. `input_ids` is on {input_ids.device.type}, whereas the model\"\n f\" is on {self.device.type}. You may experience unexpected behaviors or slower generation.\"\n \" Please make sure that you have put `input_ids` to the\"\n f\" correct device by calling for example input_ids = input_ids.to('{self.device.type}') before\"\n \" running `.generate()`.\",\n UserWarning,\n )\n\n # 8. prepare distribution pre_processing samplers\n logits_processor = self._get_logits_processor(\n generation_config=generation_config,\n input_ids_seq_length=input_ids_length,\n encoder_input_ids=inputs_tensor,\n prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,\n logits_processor=logits_processor,\n )\n\n # 9. prepare stopping criteria\n stopping_criteria = self._get_stopping_criteria(\n generation_config=generation_config, stopping_criteria=stopping_criteria\n )\n\n decoding_kwargs = generation_config.decoding_kwargs if hasattr(generation_config, 'decoding_kwargs') else {}\n decoding_kwargs['generation_mode'] = generation_mode\n decoding_kwargs['do_sample'] = generation_config.do_sample\n decoding_kwargs['inputs_embeds_position'] = generation_config.inputs_embeds_position if hasattr(generation_config, 'inputs_embeds_position') else 0\n decoding_kwargs['max_length'] = generation_config.max_length\n if generation_mode == GenerationMode.LOOKAHEAD_GENERATION:\n decoding_length = decoding_kwargs.get('decoding_length', 64)\n decoding_kwargs['decoding_max_length'] = generation_config.max_length + decoding_length + 1\n else:\n decoding_kwargs['decoding_max_length'] = generation_config.max_length\n model_kwargs['decoding_kwargs'] = decoding_kwargs\n\n # 10. go into different generation modes\n if generation_mode == GenerationMode.ASSISTED_GENERATION:\n if generation_config.num_return_sequences > 1:\n raise ValueError(\n \"num_return_sequences has to be 1 when doing assisted generate, \"\n f\"but is {generation_config.num_return_sequences}.\"\n )\n if batch_size > 1:\n raise ValueError(\"assisted generate is only supported for batch_size = 1\")\n if not model_kwargs[\"use_cache\"]:\n raise ValueError(\"assisted generate requires `use_cache=True`\")\n\n # 11. If the assistant model is an encoder-decoder, prepare its encoder outputs\n if assistant_model.config.is_encoder_decoder:\n assistant_model_kwargs = copy.deepcopy(model_kwargs)\n inputs_tensor, model_input_name, assistant_model_kwargs = assistant_model._prepare_model_inputs(\n inputs_tensor, assistant_model.generation_config.bos_token_id, assistant_model_kwargs\n )\n assistant_model_kwargs = assistant_model._prepare_encoder_decoder_kwargs_for_generation(\n inputs_tensor, assistant_model_kwargs, model_input_name\n )\n model_kwargs[\"assistant_encoder_outputs\"] = assistant_model_kwargs[\"encoder_outputs\"]\n\n # 12. run assisted generate\n return self.assisted_decoding(\n input_ids,\n assistant_model=assistant_model,\n do_sample=generation_config.do_sample,\n logits_processor=logits_processor,\n logits_warper=self._get_logits_warper(generation_config) if generation_config.do_sample else None,\n stopping_criteria=stopping_criteria,\n pad_token_id=generation_config.pad_token_id,\n eos_token_id=generation_config.eos_token_id,\n output_scores=generation_config.output_scores,\n return_dict_in_generate=generation_config.return_dict_in_generate,\n synced_gpus=synced_gpus,\n streamer=streamer,\n **model_kwargs,\n )\n if generation_mode == GenerationMode.GREEDY_SEARCH:\n # 11. run greedy search\n return self.greedy_search(\n input_ids,\n logits_processor=logits_processor,\n stopping_criteria=stopping_criteria,\n pad_token_id=generation_config.pad_token_id,\n eos_token_id=generation_config.eos_token_id,\n output_scores=generation_config.output_scores,\n return_dict_in_generate=generation_config.return_dict_in_generate,\n synced_gpus=synced_gpus,\n streamer=streamer,\n **model_kwargs,\n )\n\n elif generation_mode == GenerationMode.LOOKAHEAD_GENERATION:\n # 11. run greedy search\n return self.lookahead_generation(\n input_ids,\n logits_processor=logits_processor,\n stopping_criteria=stopping_criteria,\n pad_token_id=generation_config.pad_token_id,\n eos_token_id=generation_config.eos_token_id,\n output_scores=generation_config.output_scores,\n return_dict_in_generate=generation_config.return_dict_in_generate,\n synced_gpus=synced_gpus,\n streamer=streamer,\n **model_kwargs,\n )\n\n elif generation_mode == GenerationMode.CONTRASTIVE_SEARCH:\n if not model_kwargs[\"use_cache\"]:\n raise ValueError(\"Contrastive search requires `use_cache=True`\")\n\n return self.contrastive_search(\n input_ids,\n top_k=generation_config.top_k,\n penalty_alpha=generation_config.penalty_alpha,\n logits_processor=logits_processor,\n stopping_criteria=stopping_criteria,\n pad_token_id=generation_config.pad_token_id,\n eos_token_id=generation_config.eos_token_id,\n output_scores=generation_config.output_scores,\n return_dict_in_generate=generation_config.return_dict_in_generate,\n synced_gpus=synced_gpus,\n streamer=streamer,\n sequential=generation_config.low_memory,\n **model_kwargs,\n )\n\n elif generation_mode == GenerationMode.SAMPLE:\n # 11. prepare logits warper\n logits_warper = self._get_logits_warper(generation_config)\n\n # 12. expand input_ids with `num_return_sequences` additional sequences per batch\n input_ids, model_kwargs = self._expand_inputs_for_generation(\n input_ids=input_ids,\n expand_size=generation_config.num_return_sequences,\n is_encoder_decoder=self.config.is_encoder_decoder,\n **model_kwargs,\n )\n\n # 13. run sample\n return self.sample(\n input_ids,\n logits_processor=logits_processor,\n logits_warper=logits_warper,\n stopping_criteria=stopping_criteria,\n pad_token_id=generation_config.pad_token_id,\n eos_token_id=generation_config.eos_token_id,\n output_scores=generation_config.output_scores,\n return_dict_in_generate=generation_config.return_dict_in_generate,\n synced_gpus=synced_gpus,\n streamer=streamer,\n **model_kwargs,\n )\n\n elif generation_mode == GenerationMode.BEAM_SEARCH:\n # 11. prepare beam search scorer\n beam_scorer = BeamSearchScorer(\n batch_size=batch_size,\n num_beams=generation_config.num_beams,\n device=inputs_tensor.device,\n length_penalty=generation_config.length_penalty,\n do_early_stopping=generation_config.early_stopping,\n num_beam_hyps_to_keep=generation_config.num_return_sequences,\n max_length=generation_config.max_length,\n )\n # 12. interleave input_ids with `num_beams` additional sequences per batch\n input_ids, model_kwargs = self._expand_inputs_for_generation(\n input_ids=input_ids,\n expand_size=generation_config.num_beams,\n is_encoder_decoder=self.config.is_encoder_decoder,\n **model_kwargs,\n )\n # 13. run beam search\n return self.beam_search(\n input_ids,\n beam_scorer,\n logits_processor=logits_processor,\n stopping_criteria=stopping_criteria,\n pad_token_id=generation_config.pad_token_id,\n eos_token_id=generation_config.eos_token_id,\n output_scores=generation_config.output_scores,\n return_dict_in_generate=generation_config.return_dict_in_generate,\n synced_gpus=synced_gpus,\n **model_kwargs,\n )\n\n elif generation_mode == GenerationMode.BEAM_SAMPLE:\n # 11. prepare logits warper\n logits_warper = self._get_logits_warper(generation_config)\n\n # 12. prepare beam search scorer\n beam_scorer = BeamSearchScorer(\n batch_size=batch_size,\n num_beams=generation_config.num_beams,\n device=inputs_tensor.device,\n length_penalty=generation_config.length_penalty,\n do_early_stopping=generation_config.early_stopping,\n num_beam_hyps_to_keep=generation_config.num_return_sequences,\n max_length=generation_config.max_length,\n )\n\n # 13. interleave input_ids with `num_beams` additional sequences per batch\n input_ids, model_kwargs = self._expand_inputs_for_generation(\n input_ids=input_ids,\n expand_size=generation_config.num_beams,\n is_encoder_decoder=self.config.is_encoder_decoder,\n **model_kwargs,\n )\n\n # 14. run beam sample\n return self.beam_sample(\n input_ids,\n beam_scorer,\n logits_processor=logits_processor,\n logits_warper=logits_warper,\n stopping_criteria=stopping_criteria,\n pad_token_id=generation_config.pad_token_id,\n eos_token_id=generation_config.eos_token_id,\n output_scores=generation_config.output_scores,\n return_dict_in_generate=generation_config.return_dict_in_generate,\n synced_gpus=synced_gpus,\n **model_kwargs,\n )\n\n elif generation_mode == GenerationMode.GROUP_BEAM_SEARCH:\n # 11. prepare beam search scorer\n beam_scorer = BeamSearchScorer(\n batch_size=batch_size,\n num_beams=generation_config.num_beams,\n device=inputs_tensor.device,\n length_penalty=generation_config.length_penalty,\n do_early_stopping=generation_config.early_stopping,\n num_beam_hyps_to_keep=generation_config.num_return_sequences,\n num_beam_groups=generation_config.num_beam_groups,\n max_length=generation_config.max_length,\n )\n # 12. interleave input_ids with `num_beams` additional sequences per batch\n input_ids, model_kwargs = self._expand_inputs_for_generation(\n input_ids=input_ids,\n expand_size=generation_config.num_beams,\n is_encoder_decoder=self.config.is_encoder_decoder,\n **model_kwargs,\n )\n # 13. run beam search\n return self.group_beam_search(\n input_ids,\n beam_scorer,\n logits_processor=logits_processor,\n stopping_criteria=stopping_criteria,\n pad_token_id=generation_config.pad_token_id,\n eos_token_id=generation_config.eos_token_id,\n output_scores=generation_config.output_scores,\n return_dict_in_generate=generation_config.return_dict_in_generate,\n synced_gpus=synced_gpus,\n **model_kwargs,\n )\n\n elif generation_mode == GenerationMode.CONSTRAINED_BEAM_SEARCH:\n final_constraints = []\n if generation_config.constraints is not None:\n final_constraints = generation_config.constraints\n\n if generation_config.force_words_ids is not None:\n\n def typeerror():\n raise ValueError(\n \"`force_words_ids` has to either be a `List[List[List[int]]]` or `List[List[int]]`\"\n f\"of positive integers, but is {generation_config.force_words_ids}.\"\n )\n\n if (\n not isinstance(generation_config.force_words_ids, list)\n or len(generation_config.force_words_ids) == 0\n ):\n typeerror()\n\n for word_ids in generation_config.force_words_ids:\n if isinstance(word_ids[0], list):\n if not isinstance(word_ids, list) or len(word_ids) == 0:\n typeerror()\n if any(not isinstance(token_ids, list) for token_ids in word_ids):\n typeerror()\n if any(\n any((not isinstance(token_id, int) or token_id < 0) for token_id in token_ids)\n for token_ids in word_ids\n ):\n typeerror()\n\n constraint = DisjunctiveConstraint(word_ids)\n else:\n if not isinstance(word_ids, list) or len(word_ids) == 0:\n typeerror()\n if any((not isinstance(token_id, int) or token_id < 0) for token_id in word_ids):\n typeerror()\n\n constraint = PhrasalConstraint(word_ids)\n final_constraints.append(constraint)\n\n # 11. prepare beam search scorer\n constrained_beam_scorer = ConstrainedBeamSearchScorer(\n constraints=final_constraints,\n batch_size=batch_size,\n num_beams=generation_config.num_beams,\n device=inputs_tensor.device,\n length_penalty=generation_config.length_penalty,\n do_early_stopping=generation_config.early_stopping,\n num_beam_hyps_to_keep=generation_config.num_return_sequences,\n max_length=generation_config.max_length,\n )\n # 12. interleave input_ids with `num_beams` additional sequences per batch\n input_ids, model_kwargs = self._expand_inputs_for_generation(\n input_ids=input_ids,\n expand_size=generation_config.num_beams,\n is_encoder_decoder=self.config.is_encoder_decoder,\n **model_kwargs,\n )\n # 13. run beam search\n return self.constrained_beam_search(\n input_ids,\n constrained_beam_scorer=constrained_beam_scorer,\n logits_processor=logits_processor,\n stopping_criteria=stopping_criteria,\n pad_token_id=generation_config.pad_token_id,\n eos_token_id=generation_config.eos_token_id,\n output_scores=generation_config.output_scores,\n return_dict_in_generate=generation_config.return_dict_in_generate,\n synced_gpus=synced_gpus,\n **model_kwargs,\n )\n\n def lookahead_prepare_inputs_for_generation(self,\n input_ids,\n past_key_values=None,\n attention_mask=None,\n inputs_embeds=None,\n **kwargs):\n position_ids = kwargs.get(\"position_ids\", None)\n\n decoding_kwargs = kwargs.get('decoding_kwargs', {})\n decoding_length = decoding_kwargs.get('decoding_length', 64)\n branch_length = decoding_kwargs.get('branch_length', 12)\n decoding_mode = decoding_kwargs.get('decoding_mode', 'hier')\n max_length = decoding_kwargs.get('max_length', 2048)\n update_branch_length = min(branch_length, max_length - input_ids.size(-1))\n assert update_branch_length > 0, f'{branch_length=} {max_length=} {input_ids.size(-1)=} {update_branch_length=}'\n\n if past_key_values is None:\n if inputs_embeds is not None and input_ids is not None:\n model_inputs = {\"inputs_embeds\": inputs_embeds, \"input_ids\": input_ids}\n length = input_ids.size(1)\n elif input_ids is not None:\n model_inputs = {\"input_ids\": input_ids}\n length = input_ids.size(1)\n elif inputs_embeds is not None:\n model_inputs = {\"inputs_embeds\": inputs_embeds}\n length = input_ids.size(1)\n else:\n raise ValueError('either input_ids or inputs_embeds is not None')\n update_attention_mask = attention_mask[:, :, :length, :length]\n\n model_inputs.update(\n {\"past_key_values\": past_key_values,\n \"use_cache\": kwargs.get(\"use_cache\"),\n \"attention_mask\": update_attention_mask,\n \"decoding_kwargs\": decoding_kwargs\n })\n\n if position_ids is not None:\n model_inputs[\"position_ids\"] = self._get_position_ids(position_ids, encoding=True, length=length)\n\n else:\n decoding_qids = input_ids[0, -2:].tolist()\n # decoding_qids = decoding_kwargs['input_id_list'][0][-2:]\n min_input_size = 0\n min_output_size = max(decoding_length // 2, 1)\n\n if decoding_mode in ('hier', 'par', 'one'):\n decoding_mode = decoding_mode + '_mix'\n fmt, mode = decoding_mode.split('_')\n method_name = fmt + '_get'\n\n decoding_ids, decoding_masks, sizes = getattr(self.lookahead_cache, method_name)(decoding_qids,\n decoding_length=decoding_length,\n branch_length=update_branch_length,\n min_input_size=min_input_size,\n min_output_size=min_output_size,\n mode=mode,\n idx=0)\n\n decoding_input_ids = torch.tensor([decoding_ids], dtype=torch.long, device=input_ids.device)\n prefix_length = input_ids.size(-1) - 1\n fresh_length = len(decoding_ids)\n ppl = prefix_length + fresh_length\n assert ppl <= attention_mask.size(2), \\\n f'{max_length=} {update_branch_length=} {prefix_length=} {fresh_length=} {attention_mask.shape=}'\n prefix_mask_tensor = attention_mask[:, :, prefix_length:ppl, :prefix_length]\n decoding_mask_tensor = torch.from_numpy(decoding_masks[None, None]).to(\n dtype=attention_mask.dtype, device=attention_mask.device)\n decoding_attention_mask = torch.cat([prefix_mask_tensor, decoding_mask_tensor], dim=3)\n\n decoding_kwargs.update({'decoding_qids': decoding_qids,\n 'decoding_ids': decoding_ids,\n 'decoding_masks': decoding_masks,\n 'sizes': sizes,\n })\n model_inputs = {'decoding_kwargs': decoding_kwargs}\n\n model_inputs.update(\n {\n \"input_ids\": decoding_input_ids,\n \"past_key_values\": past_key_values,\n \"use_cache\": kwargs.get(\"use_cache\"),\n \"attention_mask\": decoding_attention_mask\n }\n )\n if position_ids is not None:\n indices = torch.sum(decoding_attention_mask, dim=3).squeeze(1)[0]\n model_inputs[\"position_ids\"] = self._get_position_ids(position_ids, indices=indices, encoding=False)\n\n return model_inputs\n\n def _get_position_ids(self, full_position_ids, indices=None, length=None, encoding=True):\n if encoding:\n return full_position_ids[..., :length]\n else:\n return full_position_ids[..., indices]\n\n def _lookahead_update_model_kwargs_for_generation(\n self,\n outputs: ModelOutput,\n model_kwargs: Dict[str, Any],\n is_encoder_decoder: bool = False,\n standardize_cache_format: bool = False,\n logits_processor: Optional[LogitsProcessorList] = None,\n input_ids: Optional[torch.Tensor] = None,\n ) -> Dict[str, Any]:\n # update past_key_values\n model_kwargs[\"past_key_values\"] = self._extract_past_from_model_output(\n outputs, standardize_cache_format=standardize_cache_format\n )\n\n decoding_kwargs = model_kwargs['decoding_kwargs']\n decoding_ids = decoding_kwargs.get('decoding_ids', [])\n if len(decoding_ids) <= 1:\n next_token_logits = outputs.logits[:, -1:, :]\n # pre-process distribution\n # next_tokens_scores = logits_processor(input_ids, next_token_logits)\n bs, nt, nv = next_token_logits.shape\n next_tokens_scores = logits_processor(input_ids, next_token_logits.squeeze(1)).unsqueeze(1)\n\n if decoding_kwargs.get('do_sample', False):\n probs = nn.functional.softmax(next_tokens_scores, dim=-1)\n next_tokens = torch.multinomial(probs.view(bs * nt, nv), num_samples=1).view(bs, nt)\n else:\n next_tokens = torch.argmax(next_tokens_scores, dim=-1, keepdim=False).long()\n model_kwargs['next_tokens'] = next_tokens\n model_kwargs['next_tokens_scores'] = next_tokens_scores\n next_token_list = next_tokens.tolist()\n model_kwargs['next_token_list'] = next_token_list\n decoding_kwargs['input_id_list'][0].extend(next_token_list[0])\n decoding_kwargs['dls'].append(1)\n decoding_kwargs['edls'].append(1)\n if decoding_kwargs.get('debug_lookahead', False):\n decoding_qids = decoding_kwargs.get('decoding_qids', [])\n print(f'size:0 query:{decoding_qids} next_token:{next_token_list[0]}')\n else:\n # TODO: accurate logit_processor\n # next_tokens_scores = logits_processor(input_ids, outputs.logits)\n bs, nt, nv = outputs.logits.shape\n next_tokens_scores = logits_processor(input_ids.repeat(1, nt).view(bs * nt, -1),\n outputs.logits.view(bs * nt, -1)).view(bs, nt, -1)\n\n if decoding_kwargs.get('do_sample', False):\n probs = nn.functional.softmax(next_tokens_scores, dim=-1)\n bs, nt, nv = probs.shape\n next_tokens = torch.multinomial(probs.view(bs * nt, nv), num_samples=1).view(bs, nt)\n else:\n next_tokens = torch.argmax(next_tokens_scores, dim=-1, keepdim=False).long()\n\n next_token_list = next_tokens.tolist()[0]\n decoding_ids = decoding_kwargs['decoding_ids'][1:]\n decoding_mask = decoding_kwargs['decoding_masks']\n sizes = decoding_kwargs['sizes']\n\n max_match_index = 0\n max_match_count = 0\n max_decoding_ids_slice = None\n max_next_token_slice = None\n \n for i in range(len(decoding_ids)):\n mask_indices = np.nonzero(decoding_mask[i + 1, 1:])[0]\n decoding_ids_slice = [decoding_ids[j] for j in mask_indices] \n next_token_slice = [next_token_list[0]] + [next_token_list[j + 1] for j in mask_indices]\n \n c = len(decoding_ids_slice)\n for j, p in enumerate(decoding_ids_slice):\n if next_token_slice[j] != p:\n c = j\n break\n if c > max_match_count:\n max_match_count = c\n max_match_index = i\n if c >= max_match_count:\n max_decoding_ids_slice = decoding_ids_slice\n max_next_token_slice = next_token_slice\n # if decoding_kwargs['eos'] in decoding_ids:\n # max_match_count = 0\n\n prefix_plus_count = input_ids.size(-1)\n match_idx = np.nonzero(decoding_mask[max_match_index + 1, 1:])[0][:max_match_count]\n if len(decoding_ids) != max_match_count:\n past = model_kwargs[\"past_key_values\"]\n device = past[0][0].device\n kv_idx = torch.tensor(match_idx + prefix_plus_count, dtype=torch.long, device=device)\n model_kwargs[\"past_key_values\"] = self._update_cache(past,\n kv_idx,\n prefix_and_next_count=prefix_plus_count,\n max_match_count=max_match_count,\n max_match_index=max_match_index)\n\n next_token_list = [next_token_list[0:1] + [next_token_list[x + 1] for x in match_idx]]\n next_tokens = torch.tensor(next_token_list, dtype=torch.long, device=input_ids.device)\n model_kwargs['next_tokens'] = next_tokens\n model_kwargs['next_token_list'] = next_token_list\n decoding_kwargs['input_id_list'][0].extend(next_token_list[0])\n decoding_kwargs['dls'].append(len(decoding_ids))\n decoding_kwargs['edls'].append(max_match_count + 1)\n if decoding_kwargs.get('debug_lookahead', False):\n lengths = np.sum(decoding_mask, axis=1) - 1\n l = np.concatenate([lengths[:-1][(lengths[1:] - lengths[:-1]) <= 0], lengths[-1:]], axis=0)\n ls = ','.join(l.astype(np.str_))\n decoding_qids = decoding_kwargs['decoding_qids']\n size_str = ','.join([str(x) for x in sizes])\n print(\n f'decoding_length:{len(decoding_ids)+1} accept_length:{max_match_count+1} '\n f'query:{decoding_qids} source:{size_str} lengths:{ls} index:{max_match_index} '\n f'branch_token:{max_decoding_ids_slice} next_token:{max_next_token_slice}')\n\n return model_kwargs\n\n def _update_cache(self, past_key_values, kv_idx, prefix_and_next_count=None, max_match_count=None,\n max_match_index=None):\n update_past_key_values = []\n for k, v in past_key_values:\n if max_match_index + 1 == max_match_count:\n k = k[:, :, :prefix_and_next_count + max_match_count]\n v = v[:, :, :prefix_and_next_count + max_match_count]\n else:\n k = torch.concat([k[:, :, :prefix_and_next_count], k[:, :, kv_idx]], 2)\n v = torch.concat([v[:, :, :prefix_and_next_count], v[:, :, kv_idx]], 2)\n update_past_key_values.append((k, v))\n return tuple(update_past_key_values)\n\n def lookahead_generation(\n self,\n input_ids: torch.LongTensor,\n logits_processor: Optional[LogitsProcessorList] = None,\n stopping_criteria: Optional[StoppingCriteriaList] = None,\n max_length: Optional[int] = None,\n pad_token_id: Optional[int] = None,\n eos_token_id: Optional[Union[int, List[int]]] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n output_scores: Optional[bool] = None,\n return_dict_in_generate: Optional[bool] = None,\n synced_gpus: bool = False,\n streamer: Optional[\"BaseStreamer\"] = None,\n **model_kwargs,\n ) -> Union[GreedySearchOutput, torch.LongTensor]:\n r\"\"\"\n Generates sequences of token ids for models with a language modeling head using **greedy decoding** and can be\n used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.\n\n <Tip warning={true}>\n\n In most cases, you do not need to call [`~generation.GenerationMixin.greedy_search`] directly. Use generate()\n instead. For an overview of generation strategies and code examples, check the [following\n guide](../generation_strategies).\n\n </Tip>\n\n\n Parameters:\n input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n The sequence used as a prompt for the generation.\n logits_processor (`LogitsProcessorList`, *optional*):\n An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]\n used to modify the prediction scores of the language modeling head applied at each generation step.\n stopping_criteria (`StoppingCriteriaList`, *optional*):\n An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]\n used to tell if the generation loop should stop.\n\n max_length (`int`, *optional*, defaults to 20):\n **DEPRECATED**. Use `logits_processor` or `stopping_criteria` directly to cap the number of generated\n tokens. The maximum length of the sequence to be generated.\n pad_token_id (`int`, *optional*):\n The id of the *padding* token.\n eos_token_id (`Union[int, List[int]]`, *optional*):\n The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.\n output_attentions (`bool`, *optional*, defaults to `False`):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n returned tensors for more details.\n output_hidden_states (`bool`, *optional*, defaults to `False`):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors\n for more details.\n output_scores (`bool`, *optional*, defaults to `False`):\n Whether or not to return the prediction scores. See `scores` under returned tensors for more details.\n return_dict_in_generate (`bool`, *optional*, defaults to `False`):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n synced_gpus (`bool`, *optional*, defaults to `False`):\n Whether to continue running the while loop until max_length (needed for ZeRO stage 3)\n streamer (`BaseStreamer`, *optional*):\n Streamer object that will be used to stream the generated sequences. Generated tokens are passed\n through `streamer.put(token_ids)` and the streamer is responsible for any further processing.\n model_kwargs:\n Additional model specific keyword arguments will be forwarded to the `forward` function of the model.\n If model is an encoder-decoder model the kwargs should include `encoder_outputs`.\n\n Return:\n [`~generation.GreedySearchDecoderOnlyOutput`], [`~generation.GreedySearchEncoderDecoderOutput`] or\n `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a\n [`~generation.GreedySearchDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and\n `return_dict_in_generate=True` or a [`~generation.GreedySearchEncoderDecoderOutput`] if\n `model.config.is_encoder_decoder=True`.\n\n Examples:\n\n ```python\n >>> from transformers import (\n ... AutoTokenizer,\n ... AutoModelForCausalLM,\n ... LogitsProcessorList,\n ... MinLengthLogitsProcessor,\n ... StoppingCriteriaList,\n ... MaxLengthCriteria,\n ... )\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"gpt2\")\n >>> model = AutoModelForCausalLM.from_pretrained(\"gpt2\")\n\n >>> # set pad_token_id to eos_token_id because GPT2 does not have a PAD token\n >>> model.generation_config.pad_token_id = model.generation_config.eos_token_id\n\n >>> input_prompt = \"It might be possible to\"\n >>> input_ids = tokenizer(input_prompt, return_tensors=\"pt\").input_ids\n\n >>> # instantiate logits processors\n >>> logits_processor = LogitsProcessorList(\n ... [\n ... MinLengthLogitsProcessor(10, eos_token_id=model.generation_config.eos_token_id),\n ... ]\n ... )\n >>> stopping_criteria = StoppingCriteriaList([MaxLengthCriteria(max_length=20)])\n\n >>> outputs = model.greedy_search(\n ... input_ids, logits_processor=logits_processor, stopping_criteria=stopping_criteria\n ... )\n\n >>> tokenizer.batch_decode(outputs, skip_special_tokens=True)\n [\"It might be possible to get a better understanding of the nature of the problem, but it's not\"]\n ```\"\"\"\n # init values\n\n if not hasattr(self, 'lookahead_cache'):\n self.lookahead_cache = LookaheadCache()\n\n logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()\n stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()\n if max_length is not None:\n warnings.warn(\n \"`max_length` is deprecated in this function, use\"\n \" `stopping_criteria=StoppingCriteriaList([MaxLengthCriteria(max_length=max_length)])` instead.\",\n UserWarning,\n )\n stopping_criteria = validate_stopping_criteria(stopping_criteria, max_length)\n pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id\n eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id\n if isinstance(eos_token_id, int):\n eos_token_id = [eos_token_id]\n eos_token_id_tensor = torch.tensor(eos_token_id, device=input_ids.device) if eos_token_id is not None else None\n output_scores = output_scores if output_scores is not None else self.generation_config.output_scores\n output_attentions = (\n output_attentions if output_attentions is not None else self.generation_config.output_attentions\n )\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states\n )\n return_dict_in_generate = (\n return_dict_in_generate\n if return_dict_in_generate is not None\n else self.generation_config.return_dict_in_generate\n )\n\n # init attention / hidden states / scores tuples\n scores = () if (return_dict_in_generate and output_scores) else None\n decoder_attentions = () if (return_dict_in_generate and output_attentions) else None\n cross_attentions = () if (return_dict_in_generate and output_attentions) else None\n decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None\n\n # if model is an encoder-decoder, retrieve encoder attention weights and hidden states\n if return_dict_in_generate and self.config.is_encoder_decoder:\n encoder_attentions = model_kwargs[\"encoder_outputs\"].get(\"attentions\") if output_attentions else None\n encoder_hidden_states = (\n model_kwargs[\"encoder_outputs\"].get(\"hidden_states\") if output_hidden_states else None\n )\n\n decoding_kwargs = model_kwargs['decoding_kwargs']\n decoding_kwargs.update({\n 'eos': eos_token_id[0] if eos_token_id is not None else 2,\n 'edls': [],\n 'dls': [],\n 'fts': []\n })\n\n decoding_length = decoding_kwargs.get('decoding_length', 64)\n stop_max_length = stopping_criteria.max_length\n decoding_max_length = stop_max_length + decoding_length + 1\n attention_mask = model_kwargs.get('attention_mask', None)\n input_device = input_ids.device\n if attention_mask is None:\n bs = input_ids.size(0)\n full_attention_mask = torch.tril(\n torch.ones((bs, 1, decoding_max_length, decoding_max_length), dtype=torch.long, device=input_device),\n 0)\n elif len(attention_mask.shape) == 2:\n # from [bs, src_len] to [bs,1,max_len,max_len]\n bs, src_len = attention_mask.shape\n pad_len = decoding_max_length - src_len\n attention_mask = attention_mask.long()\n if pad_len > 0:\n pad_mask = torch.ones((bs, pad_len), dtype=torch.long, device=attention_mask.device)\n attention_mask = torch.cat([attention_mask, pad_mask], 1)\n full_attention_mask = torch.tril(attention_mask[:, None, None].expand(-1, -1, decoding_max_length, -1), 0)\n elif len(attention_mask.shape) == 4:\n bs, _, src_len, tgt_len = attention_mask.shape\n attention_mask = attention_mask.long()\n if src_len < decoding_max_length or tgt_len < decoding_max_length:\n full_attention_mask = torch.tril(\n torch.ones((bs, 1, decoding_max_length, decoding_max_length), dtype=torch.long,\n device=input_device),\n 0)\n full_attention_mask[:, :, :src_len, :tgt_len] = attention_mask\n else:\n full_attention_mask = attention_mask\n else:\n raise ValueError(f'unsupport attention_mask.shape:{attention_mask.shape}')\n model_kwargs['attention_mask'] = full_attention_mask\n decoding_kwargs['max_length'] = stop_max_length\n decoding_kwargs['decoding_max_length'] = decoding_max_length\n\n # keep track of which sequences are already finished\n unfinished_sequences = torch.ones(input_ids.shape[0], dtype=torch.long, device=input_ids.device)\n\n assert input_ids.size(0) == 1\n input_id_list = input_ids[0].tolist()\n decoding_kwargs['input_id_list'] = [input_id_list]\n branch_length = decoding_kwargs.get('branch_length', 12)\n self.lookahead_cache.put(input_id_list[1:], branch_length=branch_length + 1, mode='input', idx=0)\n ts = time.time()\n\n this_peer_finished = False # used by synced_gpus only\n while True:\n if synced_gpus:\n # Under synced_gpus the `forward` call must continue until all gpus complete their sequence.\n # The following logic allows an early break if all peers finished generating their sequence\n this_peer_finished_flag = torch.tensor(0.0 if this_peer_finished else 1.0).to(input_ids.device)\n # send 0.0 if we finished, 1.0 otherwise\n dist.all_reduce(this_peer_finished_flag, op=dist.ReduceOp.SUM)\n # did all peers finish? the reduced sum will be 0.0 then\n if this_peer_finished_flag.item() == 0.0:\n break\n\n # prepare model inputs\n model_inputs = self.lookahead_prepare_inputs_for_generation(input_ids, **model_kwargs)\n decoding_kwargs = model_inputs.pop('decoding_kwargs', {})\n\n # forward pass to get next token\n outputs = self(\n **model_inputs,\n return_dict=True,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n )\n\n if synced_gpus and this_peer_finished:\n continue # don't waste resources running the code we don't need\n\n model_kwargs['decoding_kwargs'] = decoding_kwargs\n model_kwargs = self._lookahead_update_model_kwargs_for_generation(\n outputs,\n model_kwargs,\n is_encoder_decoder=self.config.is_encoder_decoder,\n input_ids=input_ids,\n logits_processor=logits_processor\n )\n\n next_tokens = model_kwargs['next_tokens']\n next_tokens_scores = model_kwargs['next_tokens_scores']\n next_token_list = model_kwargs['next_token_list']\n\n # finished sentences should have their next token be a padding token\n if eos_token_id is not None:\n if pad_token_id is None:\n raise ValueError(\"If `eos_token_id` is defined, make sure that `pad_token_id` is defined.\")\n next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)\n\n # update generated ids, model inputs, and length for next step\n input_ids = torch.cat([input_ids, next_tokens], dim=-1)\n if streamer is not None:\n streamer.put(next_token_list)\n\n self.lookahead_cache.stream_put(next_token_list[0], branch_length=branch_length + 1, final=False,\n mode='output', idx=0)\n\n # Store scores, attentions and hidden_states when required\n if return_dict_in_generate:\n if output_scores:\n scores += (next_tokens_scores,)\n if output_attentions:\n decoder_attentions += (\n (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)\n )\n if self.config.is_encoder_decoder:\n cross_attentions += (outputs.cross_attentions,)\n\n if output_hidden_states:\n decoder_hidden_states += (\n (outputs.decoder_hidden_states,)\n if self.config.is_encoder_decoder\n else (outputs.hidden_states,)\n )\n\n # if eos_token was found in one sentence, set sentence to finished\n if eos_token_id_tensor is not None:\n # unfinished_sequences = unfinished_sequences.mul(\n # next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0)\n # )\n unfinished_sequences = unfinished_sequences.mul(\n next_tokens[:, :, None].ne(eos_token_id_tensor).prod(dim=2).prod(dim=1))\n\n # stop when each sentence is finished\n if unfinished_sequences.max() == 0:\n this_peer_finished = True\n\n # stop if we exceed the maximum length\n if stopping_criteria(input_ids, scores):\n this_peer_finished = True\n\n te = time.time()\n model_kwargs['decoding_kwargs']['fts'].append(te - ts)\n ts = te\n if this_peer_finished and not synced_gpus:\n self.lookahead_cache.stream_put([], branch_length=branch_length + 1, final=True,\n mode='output', idx=0)\n break\n\n if streamer is not None:\n streamer.end()\n\n if return_dict_in_generate:\n if self.config.is_encoder_decoder:\n return GreedySearchEncoderDecoderOutput(\n sequences=input_ids,\n scores=scores,\n encoder_attentions=encoder_attentions,\n encoder_hidden_states=encoder_hidden_states,\n decoder_attentions=decoder_attentions,\n cross_attentions=cross_attentions,\n decoder_hidden_states=decoder_hidden_states,\n )\n else:\n kwargs = {'dls': model_kwargs['decoding_kwargs']['dls'],\n 'edls': model_kwargs['decoding_kwargs']['edls'],\n 'fts': model_kwargs['decoding_kwargs']['fts']}\n return LookaheadDecoderOnlyOutput(\n sequences=input_ids,\n scores=scores,\n attentions=decoder_attentions,\n hidden_states=decoder_hidden_states,\n kwargs=kwargs\n )\n else:\n return input_ids\n\n def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]):\n \"\"\"Validates model kwargs for generation. Generate argument typos will also be caught here.\"\"\"\n # Excludes arguments that are handled before calling any model function\n if self.config.is_encoder_decoder:\n for key in [\"decoder_input_ids\"]:\n model_kwargs.pop(key, None)\n\n unused_model_args = []\n model_args = set(inspect.signature(self.prepare_inputs_for_generation).parameters)\n # `kwargs`/`model_kwargs` is often used to handle optional forward pass inputs like `attention_mask`. If\n # `prepare_inputs_for_generation` doesn't accept them, then a stricter check can be made ;)\n if \"kwargs\" in model_args or \"model_kwargs\" in model_args:\n model_args |= set(inspect.signature(self.forward).parameters)\n\n # Encoder-Decoder models may also need Encoder arguments from `model_kwargs`\n if self.config.is_encoder_decoder:\n base_model = getattr(self, self.base_model_prefix, None)\n\n # allow encoder kwargs\n encoder = getattr(self, \"encoder\", None)\n # `MusicgenForConditionalGeneration` has `text_encoder` and `audio_encoder`.\n # Also, it has `base_model_prefix = \"encoder_decoder\"` but there is no `self.encoder_decoder`\n # TODO: A better way to handle this.\n if encoder is None and base_model is not None:\n encoder = getattr(base_model, \"encoder\", None)\n\n if encoder is not None:\n encoder_model_args = set(inspect.signature(encoder.forward).parameters)\n model_args |= encoder_model_args\n\n # allow decoder kwargs\n decoder = getattr(self, \"decoder\", None)\n if decoder is None and base_model is not None:\n decoder = getattr(base_model, \"decoder\", None)\n\n if decoder is not None:\n decoder_model_args = set(inspect.signature(decoder.forward).parameters)\n model_args |= {f\"decoder_{x}\" for x in decoder_model_args}\n\n decoding_kwargs = ['decoding_kwargs','stop_words_ids']\n for key, value in model_kwargs.items():\n if value is not None and key not in model_args and key not in decoding_kwargs:\n unused_model_args.append(key)\n\n if unused_model_args:\n raise ValueError(\n f\"The following `model_kwargs` are not used by the model: {unused_model_args} (note: typos in the\"\n \" generate arguments will also show up in this list)\"\n )" }, { "identifier": "BaichuanConfig", "path": "pia/lookahead/models/baichuan/configuration_baichuan.py", "snippet": "class BaichuanConfig(PretrainedConfig):\n model_type = \"baichuan\"\n keys_to_ignore_at_inference = [\"past_key_values\"]\n\n def __init__(\n self,\n vocab_size=125696,\n hidden_size=4096,\n intermediate_size=11008,\n num_hidden_layers=32,\n num_attention_heads=32,\n hidden_act=\"silu\",\n max_position_embeddings=4096,\n initializer_range=0.02,\n rms_norm_eps=1e-6,\n use_cache=True,\n pad_token_id=0,\n bos_token_id=1,\n eos_token_id=2,\n tie_word_embeddings=False,\n z_loss_weight=0,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.rms_norm_eps = rms_norm_eps\n self.use_cache = use_cache\n self.z_loss_weight = z_loss_weight\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n tie_word_embeddings=tie_word_embeddings,\n **kwargs,\n )" }, { "identifier": "build_chat_input", "path": "pia/lookahead/models/baichuan/generation_utils.py", "snippet": "def build_chat_input(model, tokenizer, messages: List[dict], max_new_tokens: int = 0):\n def _parse_messages(messages, split_role=\"user\"):\n system, rounds = \"\", []\n round = []\n for i, message in enumerate(messages):\n if message[\"role\"] == \"system\":\n assert i == 0\n system = message[\"content\"]\n continue\n if message[\"role\"] == split_role and round:\n rounds.append(round)\n round = []\n round.append(message)\n if round:\n rounds.append(round)\n return system, rounds\n\n max_new_tokens = max_new_tokens or model.generation_config.max_new_tokens\n max_input_tokens = model.config.model_max_length - max_new_tokens\n system, rounds = _parse_messages(messages, split_role=\"user\")\n system_tokens = tokenizer.encode(system)\n max_history_tokens = max_input_tokens - len(system_tokens)\n\n history_tokens = []\n for round in rounds[::-1]:\n round_tokens = []\n for message in round:\n if message[\"role\"] == \"user\":\n round_tokens.append(model.generation_config.user_token_id)\n else:\n round_tokens.append(model.generation_config.assistant_token_id)\n round_tokens.extend(tokenizer.encode(message[\"content\"]))\n if len(history_tokens) == 0 or len(history_tokens) + len(round_tokens) <= max_history_tokens:\n history_tokens = round_tokens + history_tokens # concat left\n if len(history_tokens) < max_history_tokens:\n continue\n break\n\n input_tokens = system_tokens + history_tokens\n if messages[-1][\"role\"] != \"assistant\":\n input_tokens.append(model.generation_config.assistant_token_id)\n input_tokens = input_tokens[-max_input_tokens:] # truncate left\n return torch.LongTensor([input_tokens]).to(model.device)" }, { "identifier": "TextIterStreamer", "path": "pia/lookahead/models/baichuan/generation_utils.py", "snippet": "class TextIterStreamer:\n def __init__(self, tokenizer, skip_prompt=False, skip_special_tokens=False):\n self.tokenizer = tokenizer\n self.skip_prompt = skip_prompt\n self.skip_special_tokens = skip_special_tokens\n self.tokens = []\n self.text_queue = Queue()\n self.next_tokens_are_prompt = True\n\n def put(self, value):\n if self.skip_prompt and self.next_tokens_are_prompt:\n self.next_tokens_are_prompt = False\n else:\n if len(value.shape) > 1:\n value = value[0]\n self.tokens.extend(value.tolist())\n self.text_queue.put(\n self.tokenizer.decode(self.tokens, skip_special_tokens=self.skip_special_tokens))\n\n def end(self):\n self.text_queue.put(None)\n\n def __iter__(self):\n return self\n\n def __next__(self):\n value = self.text_queue.get()\n if value is None:\n raise StopIteration()\n else:\n return value" } ]
import math import os import torch import torch.utils.checkpoint from contextlib import contextmanager from threading import Thread from typing import List, Optional, Tuple, Union from torch import nn from torch.nn import CrossEntropyLoss from torch.nn import functional as F from transformers import PretrainedConfig from transformers.activations import ACT2FN from transformers.generation.utils import GenerationConfig from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast from transformers.utils import logging, ContextManagers from pia.lookahead.common.pretrained_model import LookaheadPreTrainedModel from pia.lookahead.models.baichuan.configuration_baichuan import BaichuanConfig from pia.lookahead.models.baichuan.generation_utils import build_chat_input, TextIterStreamer from xformers import ops as xops from .quantizer import quantize_offline, init_model_weight_int4 from .quantizer import init_model_weight_int4 from accelerate import init_empty_weights, dispatch_model, infer_auto_device_map from accelerate.utils import CustomDtype from accelerate.utils import get_balanced_memory from .quantizer import quantize_online
17,578
return model return super(BaichuanForCausalLM, cls).from_pretrained(pretrained_model_name_or_path, *model_args, config=config, cache_dir=cache_dir, ignore_mismatched_sizes=ignore_mismatched_sizes, force_download=force_download, local_files_only=local_files_only, token=token, revision=revision, use_safetensors=use_safetensors, **kwargs) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, CausalLMOutputWithPast]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = outputs[0] logits = self.lm_head(hidden_states) loss = None if labels is not None: # Shift so that tokens < n predict n shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() # Flatten the tokens loss_fct = CrossEntropyLoss() shift_logits = shift_logits.view(-1, self.config.vocab_size) shift_labels = shift_labels.view(-1) softmax_normalizer = shift_logits.max(-1).values ** 2 z_loss = self.config.z_loss_weight * softmax_normalizer.mean() # Enable model parallelism shift_labels = shift_labels.to(shift_logits.device) loss = loss_fct(shift_logits, shift_labels) + z_loss if not return_dict: output = (logits,) + outputs[1:] return (loss,) + output if loss is not None else output return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs ): if past_key_values: input_ids = input_ids[:, -1:] position_ids = kwargs.get("position_ids", None) if attention_mask is not None and position_ids is None: # create position_ids on the fly for batch generation position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) if past_key_values: position_ids = position_ids[:, -1].unsqueeze(-1) # if `inputs_embeds` are passed, we only want to use them in the 1st generation step if inputs_embeds is not None and past_key_values is None: model_inputs = {"inputs_embeds": inputs_embeds} else: model_inputs = {"input_ids": input_ids} model_inputs.update( { "position_ids": position_ids, "past_key_values": past_key_values, "use_cache": kwargs.get("use_cache"), "attention_mask": attention_mask, } ) return model_inputs @staticmethod def _reorder_cache(past_key_values, beam_idx): reordered_past = () for layer_past in past_key_values: reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),) return reordered_past def quantize(self, bits: int): try: except ImportError: raise ImportError(f"Needs QLinear to run quantize.") return quantize_online(self, bits) def chat(self, tokenizer, messages: List[dict], stream=False, generation_config: Optional[GenerationConfig] = None): generation_config = generation_config or self.generation_config input_ids = build_chat_input(self, tokenizer, messages, generation_config.max_new_tokens) if stream:
# Copyright 2023 Baichuan Inc. All Rights Reserved. # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differences compared # to GPT-NeoX and OPT used by the Meta AI team that trained the model. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. logger = logging.get_logger(__name__) try: except ImportError: xops = None logger.warning( "Xformers is not installed correctly. If you want to use memory_efficient_attention to accelerate training use the following command to install Xformers\npip install xformers." ) # Copied from transformers.models.bart.modeling_bart._make_causal_mask def _make_causal_mask( input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0 ): """ Make causal mask used for bi-directional self-attention. """ bsz, tgt_len = input_ids_shape mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device) mask_cond = torch.arange(mask.size(-1), device=device) mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) mask = mask.to(dtype) if past_key_values_length > 0: mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1) return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length) def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): """ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. """ if len(mask.size()) == 3: bsz, src_len, _ = mask.size() tgt_len = tgt_len if tgt_len is not None else src_len expanded_mask = mask[:, None, :, :].expand(bsz, 1, tgt_len, src_len).to(dtype) else: bsz, src_len = mask.size() tgt_len = tgt_len if tgt_len is not None else src_len expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) inverted_mask = 1.0 - expanded_mask return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min) class RMSNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ RMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) # convert into half-precision if necessary if self.weight.dtype in [torch.float16, torch.bfloat16]: hidden_states = hidden_states.to(self.weight.dtype) return self.weight * hidden_states class RotaryEmbedding(torch.nn.Module): def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None): super().__init__() self.inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim)) self.max_seq_len_cached = max_position_embeddings t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=torch.float32) freqs = torch.outer(t, self.inv_freq) emb = torch.cat((freqs, freqs), dim=-1) self.cos_cached = emb.cos()[None, None, :, :].to(torch.float32) self.sin_cached = emb.sin()[None, None, :, :].to(torch.float32) def forward(self, x, seq_len=None): # x: [bs, num_attention_heads, seq_len, head_size] # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case. if seq_len > self.max_seq_len_cached: self.max_seq_len_cached = seq_len t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=torch.float32) freqs = torch.outer(t, self.inv_freq) emb = torch.cat((freqs, freqs), dim=-1) self.cos_cached = emb.cos()[None, None, :, :].to(torch.float32).to(x.device) self.sin_cached = emb.sin()[None, None, :, :].to(torch.float32).to(x.device) elif self.cos_cached.device != x.device: self.cos_cached = self.cos_cached.to(x.device) self.sin_cached = self.sin_cached.to(x.device) return ( self.cos_cached[:, :, :seq_len, ...], self.sin_cached[:, :, :seq_len, ...], ) def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2:] return torch.cat((-x2, x1), dim=-1) def apply_rotary_pos_emb(q, k, cos_, sin_, position_ids): cos = cos_.squeeze(1).squeeze(0) # [seq_len, dim] sin = sin_.squeeze(1).squeeze(0) # [seq_len, dim] cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim] sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim] q_embed = (q.float() * cos) + (rotate_half(q.float()) * sin) k_embed = (k.float() * cos) + (rotate_half(k.float()) * sin) return q_embed.to(q.dtype), k_embed.to(k.dtype) class MLP(nn.Module): def __init__( self, hidden_size: int, intermediate_size: int, hidden_act: str, ): super().__init__() self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False) self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False) self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False) self.act_fn = ACT2FN[hidden_act] def forward(self, x): return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) class Attention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: BaichuanConfig): super().__init__() self.config = config self.hidden_size = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = self.hidden_size // self.num_heads self.max_position_embeddings = config.max_position_embeddings if (self.head_dim * self.num_heads) != self.hidden_size: raise ValueError( f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}" f" and `num_heads`: {self.num_heads})." ) self.W_pack = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=False) self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False) self.rotary_emb = RotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings) def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: bool = False, use_cache: bool = False, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: bsz, q_len, _ = hidden_states.size() proj = self.W_pack(hidden_states) proj = proj.unflatten(-1, (3, self.hidden_size)).unsqueeze(0).transpose(0, -2).squeeze(-2) query_states = proj[0].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) key_states = proj[1].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) value_states = proj[2].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) kv_seq_len = key_states.shape[-2] if past_key_value is not None: kv_seq_len += past_key_value[0].shape[-2] cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) # [bsz, nh, t, hd] if past_key_value is not None: # reuse k, v, self_attention key_states = torch.cat([past_key_value[0], key_states], dim=2) value_states = torch.cat([past_key_value[1], value_states], dim=2) past_key_value = (key_states, value_states) if use_cache else None if xops is not None and self.training: attn_weights = None query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2) attn_output = xops.memory_efficient_attention( query_states, key_states, value_states, attn_bias=xops.LowerTriangularMask() ) else: with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=True): attn_output = F.scaled_dot_product_attention(query_states, key_states, value_states, attn_mask=attention_mask) attn_output = attn_output.transpose(1, 2) attn_output = attn_output.reshape(bsz, q_len, self.hidden_size) attn_output = self.o_proj(attn_output) if not output_attentions: attn_weights = None return attn_output, attn_weights, past_key_value class DecoderLayer(nn.Module): def __init__(self, config: BaichuanConfig): super().__init__() self.hidden_size = config.hidden_size self.self_attn = Attention(config=config) self.mlp = MLP( hidden_size=self.hidden_size, intermediate_size=config.intermediate_size, hidden_act=config.hidden_act, ) self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: Optional[bool] = False, use_cache: Optional[bool] = False, ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: residual = hidden_states hidden_states = self.input_layernorm(hidden_states) # Self Attention hidden_states, self_attn_weights, present_key_value = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, output_attentions=output_attentions, use_cache=use_cache, ) hidden_states = residual + hidden_states # Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states outputs = (hidden_states,) if output_attentions: outputs += (self_attn_weights,) if use_cache: outputs += (present_key_value,) return outputs class BaichuanPreTrainedModel(LookaheadPreTrainedModel): config_class = BaichuanConfig base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["DecoderLayer"] _keys_to_ignore_on_load_unexpected = [r"decoder\.version"] def _init_weights(self, module): std = self.config.initializer_range if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() def _set_gradient_checkpointing(self, module, value=False): if isinstance(module, BaichuanModel): module.gradient_checkpointing = value class BaichuanModel(BaichuanPreTrainedModel): def __init__(self, config: BaichuanConfig): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.layers = nn.ModuleList([DecoderLayer(config) for _ in range(config.num_hidden_layers)]) self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.embed_tokens def set_input_embeddings(self, value): self.embed_tokens = value # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length): # create causal mask # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] combined_attention_mask = None if input_shape[-1] > 1: combined_attention_mask = _make_causal_mask( input_shape, inputs_embeds.dtype, device=inputs_embeds.device, past_key_values_length=past_key_values_length, ) if attention_mask is not None: # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to( inputs_embeds.device ) combined_attention_mask = ( expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask ) return combined_attention_mask def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutputWithPast]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = return_dict if return_dict is not None else self.config.use_return_dict # retrieve input_ids and inputs_embeds if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") elif input_ids is not None: batch_size, seq_length = input_ids.shape elif inputs_embeds is not None: batch_size, seq_length, _ = inputs_embeds.shape else: raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") seq_length_with_past = seq_length past_key_values_length = 0 if past_key_values is not None: past_key_values_length = past_key_values[0][0].shape[2] seq_length_with_past = seq_length_with_past + past_key_values_length if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) # embed positions # Note: adapt for lookahead if attention_mask is not None and len(attention_mask.shape) == 4: # lookahead # attention_mask: [bs, 1, src_len, tgt_len] position_ids = torch.sum(attention_mask, dim=-1).squeeze(1) - 1 attention_mask = (1.0-attention_mask.to(inputs_embeds.dtype)) * torch.finfo(inputs_embeds.dtype).min else: # non-lookahead if attention_mask is None: attention_mask = torch.ones( (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device ) attention_mask = self._prepare_decoder_attention_mask( attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length ) if position_ids is None: device = input_ids.device if input_ids is not None else inputs_embeds.device position_ids = torch.arange( past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device ) position_ids = position_ids.unsqueeze(0).view(-1, seq_length) else: position_ids = position_ids.view(-1, seq_length).long() hidden_states = inputs_embeds if self.gradient_checkpointing and self.training: if use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." ) use_cache = False # decoder layers all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None next_decoder_cache = () if use_cache else None for idx, decoder_layer in enumerate(self.layers): if output_hidden_states: all_hidden_states += (hidden_states,) past_key_value = past_key_values[idx] if past_key_values is not None else None if self.gradient_checkpointing and self.training: def create_custom_forward(module): def custom_forward(*inputs): # None for past_key_value return module(*inputs, output_attentions, None) return custom_forward layer_outputs = torch.utils.checkpoint.checkpoint( create_custom_forward(decoder_layer), hidden_states, attention_mask, position_ids, None, ) else: layer_outputs = decoder_layer( hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, output_attentions=output_attentions, use_cache=use_cache, ) hidden_states = layer_outputs[0] if use_cache: next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) if output_attentions: all_self_attns += (layer_outputs[1],) hidden_states = self.norm(hidden_states) # add hidden states from the last decoder layer if output_hidden_states: all_hidden_states += (hidden_states,) next_cache = next_decoder_cache if use_cache else None if not return_dict: return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=next_cache, hidden_states=all_hidden_states, attentions=all_self_attns, ) class NormHead(nn.Module): def __init__(self, hidden_size, vocab_size, bias=False): super().__init__() self.weight = nn.Parameter(torch.empty((vocab_size, hidden_size))) nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) self.first_flag = True def forward(self, hidden_states): if self.training: norm_weight = nn.functional.normalize(self.weight) elif self.first_flag: self.first_flag = False self.weight = nn.Parameter(nn.functional.normalize(self.weight)) norm_weight = self.weight else: norm_weight = self.weight return nn.functional.linear(hidden_states, norm_weight) _init_weights = True @contextmanager def no_init_weights(_enable=True): global _init_weights old_init_weights = _init_weights if _enable: _init_weights = False try: yield finally: _init_weights = old_init_weights class BaichuanForCausalLM(BaichuanPreTrainedModel): def __init__(self, config, *model_args, **model_kwargs): super().__init__(config) self.model = BaichuanModel(config) self.lm_head = NormHead(config.hidden_size, config.vocab_size, bias=False) if hasattr(config, "quantization_config") and config.quantization_config['load_in_4bit']: try: except ImportError: raise ImportError(f"Needs QLinear to run quantize.") quantize_offline(self, 4) # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.model.embed_tokens def set_input_embeddings(self, value): self.model.embed_tokens = value def get_output_embeddings(self): return self.lm_head def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings def set_decoder(self, decoder): self.model = decoder def get_decoder(self): return self.model @classmethod def from_pretrained( cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *model_args, config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None, cache_dir: Optional[Union[str, os.PathLike]] = None, ignore_mismatched_sizes: bool = False, force_download: bool = False, local_files_only: bool = False, token: Optional[Union[str, bool]] = None, revision: str = "main", use_safetensors: bool = None, **kwargs, ): # Load config if we don't provide a configuration if not isinstance(config, PretrainedConfig): config_path = config if config is not None else pretrained_model_name_or_path config, model_kwargs = cls.config_class.from_pretrained( config_path, cache_dir=cache_dir, return_unused_kwargs=True, force_download=force_download, resume_download=False, proxies=None, local_files_only=local_files_only, token=token, revision=revision, subfolder="", _from_auto=False, _from_pipeline=None, **kwargs, ) else: model_kwargs = kwargs if hasattr(config, "quantization_config") and config.quantization_config['load_in_4bit']: try: except ImportError: raise ImportError(f"Needs import model weight init func to run quantize.") # Instantiate model. init_contexts = [no_init_weights(_enable=True)] init_contexts.append(init_empty_weights()) with ContextManagers(init_contexts): model = cls(config) model_file = os.path.join(pretrained_model_name_or_path, 'pytorch_model.bin') state_dict = torch.load(model_file, map_location="cpu") model.is_quantized = True device_map = kwargs.pop("device_map", None) torch_dtype = kwargs.pop("torch_dtype", None) kwargs = {"no_split_module_classes": model._no_split_modules} target_dtype = CustomDtype.INT4 max_memory = get_balanced_memory( model, dtype=target_dtype, low_zero=(device_map == "balanced_low_0"), max_memory=None, **kwargs, ) kwargs["max_memory"] = max_memory device_map = infer_auto_device_map(model, dtype=target_dtype, **kwargs) model = init_model_weight_int4(config, model, state_dict) # Set model in evaluation mode to deactivate DropOut modules by default model.eval() # If it is a model with generation capabilities, attempt to load the generation config if model.can_generate(): try: model.generation_config = GenerationConfig.from_pretrained( pretrained_model_name_or_path, cache_dir=cache_dir, force_download=force_download, resume_download=False, proxies=None, local_files_only=local_files_only, token=token, revision=revision, subfolder="", _from_auto=False, _from_pipeline=None, **kwargs, ) except (OSError, TypeError): logger.info( "Generation config file not found, using a generation config created from the model config." ) pass if device_map is not None: dispatch_model(model, device_map=device_map) return model return super(BaichuanForCausalLM, cls).from_pretrained(pretrained_model_name_or_path, *model_args, config=config, cache_dir=cache_dir, ignore_mismatched_sizes=ignore_mismatched_sizes, force_download=force_download, local_files_only=local_files_only, token=token, revision=revision, use_safetensors=use_safetensors, **kwargs) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, CausalLMOutputWithPast]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = outputs[0] logits = self.lm_head(hidden_states) loss = None if labels is not None: # Shift so that tokens < n predict n shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() # Flatten the tokens loss_fct = CrossEntropyLoss() shift_logits = shift_logits.view(-1, self.config.vocab_size) shift_labels = shift_labels.view(-1) softmax_normalizer = shift_logits.max(-1).values ** 2 z_loss = self.config.z_loss_weight * softmax_normalizer.mean() # Enable model parallelism shift_labels = shift_labels.to(shift_logits.device) loss = loss_fct(shift_logits, shift_labels) + z_loss if not return_dict: output = (logits,) + outputs[1:] return (loss,) + output if loss is not None else output return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs ): if past_key_values: input_ids = input_ids[:, -1:] position_ids = kwargs.get("position_ids", None) if attention_mask is not None and position_ids is None: # create position_ids on the fly for batch generation position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) if past_key_values: position_ids = position_ids[:, -1].unsqueeze(-1) # if `inputs_embeds` are passed, we only want to use them in the 1st generation step if inputs_embeds is not None and past_key_values is None: model_inputs = {"inputs_embeds": inputs_embeds} else: model_inputs = {"input_ids": input_ids} model_inputs.update( { "position_ids": position_ids, "past_key_values": past_key_values, "use_cache": kwargs.get("use_cache"), "attention_mask": attention_mask, } ) return model_inputs @staticmethod def _reorder_cache(past_key_values, beam_idx): reordered_past = () for layer_past in past_key_values: reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),) return reordered_past def quantize(self, bits: int): try: except ImportError: raise ImportError(f"Needs QLinear to run quantize.") return quantize_online(self, bits) def chat(self, tokenizer, messages: List[dict], stream=False, generation_config: Optional[GenerationConfig] = None): generation_config = generation_config or self.generation_config input_ids = build_chat_input(self, tokenizer, messages, generation_config.max_new_tokens) if stream:
streamer = TextIterStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
3
2023-12-19 13:11:38+00:00
24k
MingtaoGuo/AnimateAnyone_unofficial
aldm/aldm.py
[ { "identifier": "conv_nd", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def conv_nd(dims, *args, **kwargs):\n \"\"\"\n Create a 1D, 2D, or 3D convolution module.\n \"\"\"\n if dims == 1:\n return nn.Conv1d(*args, **kwargs)\n elif dims == 2:\n return nn.Conv2d(*args, **kwargs)\n elif dims == 3:\n return nn.Conv3d(*args, **kwargs)\n raise ValueError(f\"unsupported dimensions: {dims}\")" }, { "identifier": "linear", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def linear(*args, **kwargs):\n \"\"\"\n Create a linear module.\n \"\"\"\n return nn.Linear(*args, **kwargs)" }, { "identifier": "zero_module", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def zero_module(module):\n \"\"\"\n Zero out the parameters of a module and return it.\n \"\"\"\n for p in module.parameters():\n p.detach().zero_()\n return module" }, { "identifier": "timestep_embedding", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):\n \"\"\"\n Create sinusoidal timestep embeddings.\n :param timesteps: a 1-D Tensor of N indices, one per batch element.\n These may be fractional.\n :param dim: the dimension of the output.\n :param max_period: controls the minimum frequency of the embeddings.\n :return: an [N x dim] Tensor of positional embeddings.\n \"\"\"\n if not repeat_only:\n half = dim // 2\n freqs = torch.exp(\n -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half\n ).to(device=timesteps.device)\n args = timesteps[:, None].float() * freqs[None]\n embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)\n if dim % 2:\n embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)\n else:\n embedding = repeat(timesteps, 'b -> b d', d=dim)\n return embedding" }, { "identifier": "SpatialTransformer", "path": "ldm/modules/attention.py", "snippet": "class SpatialTransformer(nn.Module):\n \"\"\"\n Transformer block for image-like data.\n First, project the input (aka embedding)\n and reshape to b, t, d.\n Then apply standard transformer action.\n Finally, reshape to image\n NEW: use_linear for more efficiency instead of the 1x1 convs\n \"\"\"\n def __init__(self, in_channels, n_heads, d_head,\n depth=1, dropout=0., context_dim=None,\n disable_self_attn=False, use_linear=False,\n use_checkpoint=True):\n super().__init__()\n if exists(context_dim) and not isinstance(context_dim, list):\n context_dim = [context_dim]\n self.in_channels = in_channels\n inner_dim = n_heads * d_head\n self.norm = Normalize(in_channels)\n if not use_linear:\n self.proj_in = nn.Conv2d(in_channels,\n inner_dim,\n kernel_size=1,\n stride=1,\n padding=0)\n else:\n self.proj_in = nn.Linear(in_channels, inner_dim)\n\n self.transformer_blocks = nn.ModuleList(\n [BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim[d],\n disable_self_attn=disable_self_attn, checkpoint=use_checkpoint)\n for d in range(depth)]\n )\n if not use_linear:\n self.proj_out = zero_module(nn.Conv2d(inner_dim,\n in_channels,\n kernel_size=1,\n stride=1,\n padding=0))\n else:\n self.proj_out = zero_module(nn.Linear(in_channels, inner_dim))\n self.use_linear = use_linear\n\n def forward(self, x, context=None):\n # note: if no context is given, cross-attention defaults to self-attention\n if not isinstance(context, list):\n context = [context]\n b, c, h, w = x.shape\n x_in = x\n x = self.norm(x)\n if not self.use_linear:\n x = self.proj_in(x)\n x = rearrange(x, 'b c h w -> b (h w) c').contiguous()\n if self.use_linear:\n x = self.proj_in(x)\n for i, block in enumerate(self.transformer_blocks):\n x = block(x, context=context[i])\n if self.use_linear:\n x = self.proj_out(x)\n x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()\n if not self.use_linear:\n x = self.proj_out(x)\n return x + x_in" }, { "identifier": "SpatialTransformerPlus", "path": "ldm/modules/attention.py", "snippet": "class SpatialTransformerPlus(nn.Module):\n \"\"\"\n Transformer block for image-like data.\n First, project the input (aka embedding)\n and reshape to b, t, d.\n Then apply standard transformer action.\n Finally, reshape to image\n NEW: use_linear for more efficiency instead of the 1x1 convs\n \"\"\"\n def __init__(self, in_channels, n_heads, d_head,\n depth=1, dropout=0., context_dim=None,\n disable_self_attn=False, use_linear=False,\n use_checkpoint=True, use_temporal_attention=False):\n super().__init__()\n if exists(context_dim) and not isinstance(context_dim, list):\n context_dim = [context_dim]\n self.in_channels = in_channels\n inner_dim = n_heads * d_head\n self.norm = Normalize(in_channels)\n if not use_linear:\n self.proj_in = nn.Conv2d(in_channels,\n inner_dim,\n kernel_size=1,\n stride=1,\n padding=0)\n else:\n self.proj_in = nn.Linear(in_channels, inner_dim)\n\n self.transformer_blocks = nn.ModuleList(\n [BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim[d],\n disable_self_attn=disable_self_attn, checkpoint=use_checkpoint)\n for d in range(depth)]\n )\n if not use_linear:\n self.proj_out = zero_module(nn.Conv2d(inner_dim,\n in_channels,\n kernel_size=1,\n stride=1,\n padding=0))\n else:\n self.proj_out = zero_module(nn.Linear(in_channels, inner_dim))\n self.use_linear = use_linear\n self.spatial_attn = SpatialSelfAttention(in_channels)\n if use_temporal_attention:\n self.temporal_attn = TemporalTransformer(in_channels)\n\n def forward(self, x, context=None, ref=None):\n x = torch.cat([x, ref], dim=-1)\n x = self.spatial_attn(x)\n x = x[..., :ref.shape[-1]]\n # note: if no context is given, cross-attention defaults to self-attention\n if not isinstance(context, list):\n context = [context]\n b, c, h, w = x.shape\n x_in = x\n x = self.norm(x)\n if not self.use_linear:\n x = self.proj_in(x)\n x = rearrange(x, 'b c h w -> b (h w) c').contiguous()\n if self.use_linear:\n x = self.proj_in(x)\n for i, block in enumerate(self.transformer_blocks):\n x = block(x, context=context[i])\n if self.use_linear:\n x = self.proj_out(x)\n x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()\n if not self.use_linear:\n x = self.proj_out(x)\n return x + x_in" }, { "identifier": "ResBlock", "path": "ldm/modules/diffusionmodules/openaimodel.py", "snippet": "def convert_module_to_f16(x):\ndef convert_module_to_f32(x):\n def __init__(\n self,\n spacial_dim: int,\n embed_dim: int,\n num_heads_channels: int,\n output_dim: int = None,\n ):\n def forward(self, x):\n def forward(self, x, emb):\n def forward(self, x, emb, context=None):\n def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):\n def forward(self, x):\n def __init__(self, channels, out_channels=None, ks=5):\n def forward(self,x):\n def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1):\n def forward(self, x):\n def __init__(\n self,\n channels,\n emb_channels,\n dropout,\n out_channels=None,\n use_conv=False,\n use_scale_shift_norm=False,\n dims=2,\n use_checkpoint=False,\n up=False,\n down=False,\n ):\n def forward(self, x, emb):\n def _forward(self, x, emb):\n def __init__(\n self,\n channels,\n dropout,\n out_channels=None,\n use_conv=False,\n dims=2,\n use_checkpoint=False,\n up=False,\n down=False,\n ):\n def forward(self, x):\n def _forward(self, x):\n def __init__(\n self,\n channels,\n num_heads=1,\n num_head_channels=-1,\n use_checkpoint=False,\n use_new_attention_order=False,\n ):\n def forward(self, x):\n def _forward(self, x):\ndef count_flops_attn(model, _x, y):\n def __init__(self, n_heads):\n def forward(self, qkv):\n def count_flops(model, _x, y):\n def __init__(self, n_heads):\n def forward(self, qkv):\n def count_flops(model, _x, y):\n def __init__(\n self,\n image_size,\n in_channels,\n model_channels,\n out_channels,\n num_res_blocks,\n attention_resolutions,\n dropout=0,\n channel_mult=(1, 2, 4, 8),\n conv_resample=True,\n dims=2,\n num_classes=None,\n use_checkpoint=False,\n use_fp16=False,\n num_heads=-1,\n num_head_channels=-1,\n num_heads_upsample=-1,\n use_scale_shift_norm=False,\n resblock_updown=False,\n use_new_attention_order=False,\n use_spatial_transformer=False, # custom transformer support\n transformer_depth=1, # custom transformer support\n context_dim=None, # custom transformer support\n n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model\n legacy=True,\n disable_self_attentions=None,\n num_attention_blocks=None,\n disable_middle_self_attn=False,\n use_linear_in_transformer=False,\n ):\n def convert_to_fp16(self):\n def convert_to_fp32(self):\n def forward(self, x, timesteps=None, context=None, y=None,**kwargs):\nclass AttentionPool2d(nn.Module):\nclass TimestepBlock(nn.Module):\nclass TimestepEmbedSequential(nn.Sequential, TimestepBlock):\nclass Upsample(nn.Module):\nclass TransposedUpsample(nn.Module):\nclass Downsample(nn.Module):\nclass ResBlock(TimestepBlock):\nclass ResBlockNoTime(TimestepBlock):\nclass AttentionBlock(nn.Module):\nclass QKVAttentionLegacy(nn.Module):\nclass QKVAttention(nn.Module):\nclass UNetModel(nn.Module):" }, { "identifier": "LatentDiffusion", "path": "ldm/models/diffusion/ddpm.py", "snippet": "class LatentDiffusion(DDPM):\n \"\"\"main class\"\"\"\n\n def __init__(self,\n first_stage_config,\n cond_stage_config,\n num_timesteps_cond=None,\n cond_stage_key=\"image\",\n cond_stage_trainable=False,\n concat_mode=True,\n cond_stage_forward=None,\n conditioning_key=None,\n scale_factor=1.0,\n scale_by_std=False,\n force_null_conditioning=False,\n *args, **kwargs):\n self.force_null_conditioning = force_null_conditioning\n self.num_timesteps_cond = default(num_timesteps_cond, 1)\n self.scale_by_std = scale_by_std\n assert self.num_timesteps_cond <= kwargs['timesteps']\n # for backwards compatibility after implementation of DiffusionWrapper\n if conditioning_key is None:\n conditioning_key = 'concat' if concat_mode else 'crossattn'\n if cond_stage_config == '__is_unconditional__' and not self.force_null_conditioning:\n conditioning_key = None\n ckpt_path = kwargs.pop(\"ckpt_path\", None)\n reset_ema = kwargs.pop(\"reset_ema\", False)\n reset_num_ema_updates = kwargs.pop(\"reset_num_ema_updates\", False)\n ignore_keys = kwargs.pop(\"ignore_keys\", [])\n super().__init__(conditioning_key=conditioning_key, *args, **kwargs)\n self.concat_mode = concat_mode\n self.cond_stage_trainable = cond_stage_trainable\n self.cond_stage_key = cond_stage_key\n try:\n self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1\n except:\n self.num_downs = 0\n if not scale_by_std:\n self.scale_factor = scale_factor\n else:\n self.register_buffer('scale_factor', torch.tensor(scale_factor))\n self.instantiate_first_stage(first_stage_config)\n self.instantiate_cond_stage(cond_stage_config)\n self.cond_stage_forward = cond_stage_forward\n self.clip_denoised = False\n self.bbox_tokenizer = None\n\n self.restarted_from_ckpt = False\n if ckpt_path is not None:\n self.init_from_ckpt(ckpt_path, ignore_keys)\n self.restarted_from_ckpt = True\n if reset_ema:\n assert self.use_ema\n print(\n f\"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.\")\n self.model_ema = LitEma(self.model)\n if reset_num_ema_updates:\n print(\" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ \")\n assert self.use_ema\n self.model_ema.reset_num_updates()\n\n def make_cond_schedule(self, ):\n self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)\n ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()\n self.cond_ids[:self.num_timesteps_cond] = ids\n\n @rank_zero_only\n @torch.no_grad()\n def on_train_batch_start(self, batch, batch_idx, dataloader_idx):\n # only for very first batch\n if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt:\n assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'\n # set rescale weight to 1./std of encodings\n print(\"### USING STD-RESCALING ###\")\n x = super().get_input(batch, self.first_stage_key)\n x = x.to(self.device)\n encoder_posterior = self.encode_first_stage(x)\n z = self.get_first_stage_encoding(encoder_posterior).detach()\n del self.scale_factor\n self.register_buffer('scale_factor', 1. / z.flatten().std())\n print(f\"setting self.scale_factor to {self.scale_factor}\")\n print(\"### USING STD-RESCALING ###\")\n\n def register_schedule(self,\n given_betas=None, beta_schedule=\"linear\", timesteps=1000,\n linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):\n super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)\n\n self.shorten_cond_schedule = self.num_timesteps_cond > 1\n if self.shorten_cond_schedule:\n self.make_cond_schedule()\n\n def instantiate_first_stage(self, config):\n model = instantiate_from_config(config)\n self.first_stage_model = model.eval()\n self.first_stage_model.train = disabled_train\n for param in self.first_stage_model.parameters():\n param.requires_grad = False\n\n def instantiate_cond_stage(self, config):\n if not self.cond_stage_trainable:\n if config == \"__is_first_stage__\":\n print(\"Using first stage also as cond stage.\")\n self.cond_stage_model = self.first_stage_model\n elif config == \"__is_unconditional__\":\n print(f\"Training {self.__class__.__name__} as an unconditional model.\")\n self.cond_stage_model = None\n # self.be_unconditional = True\n else:\n model = instantiate_from_config(config)\n self.cond_stage_model = model.eval()\n self.cond_stage_model.train = disabled_train\n for param in self.cond_stage_model.parameters():\n param.requires_grad = False\n else:\n assert config != '__is_first_stage__'\n assert config != '__is_unconditional__'\n model = instantiate_from_config(config)\n self.cond_stage_model = model\n\n def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):\n denoise_row = []\n for zd in tqdm(samples, desc=desc):\n denoise_row.append(self.decode_first_stage(zd.to(self.device),\n force_not_quantize=force_no_decoder_quantization))\n n_imgs_per_row = len(denoise_row)\n denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W\n denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')\n denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')\n denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)\n return denoise_grid\n\n def get_first_stage_encoding(self, encoder_posterior):\n if isinstance(encoder_posterior, DiagonalGaussianDistribution):\n z = encoder_posterior.sample()\n elif isinstance(encoder_posterior, torch.Tensor):\n z = encoder_posterior\n else:\n raise NotImplementedError(f\"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented\")\n return self.scale_factor * z\n\n def get_learned_conditioning(self, c):\n if self.cond_stage_forward is None:\n if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):\n c = self.cond_stage_model.encode(c)\n if isinstance(c, DiagonalGaussianDistribution):\n c = c.mode()\n else:\n c = self.cond_stage_model(c)\n else:\n assert hasattr(self.cond_stage_model, self.cond_stage_forward)\n c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)\n return c\n\n def meshgrid(self, h, w):\n y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)\n x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)\n\n arr = torch.cat([y, x], dim=-1)\n return arr\n\n def delta_border(self, h, w):\n \"\"\"\n :param h: height\n :param w: width\n :return: normalized distance to image border,\n wtith min distance = 0 at border and max dist = 0.5 at image center\n \"\"\"\n lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)\n arr = self.meshgrid(h, w) / lower_right_corner\n dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]\n dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]\n edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]\n return edge_dist\n\n def get_weighting(self, h, w, Ly, Lx, device):\n weighting = self.delta_border(h, w)\n weighting = torch.clip(weighting, self.split_input_params[\"clip_min_weight\"],\n self.split_input_params[\"clip_max_weight\"], )\n weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)\n\n if self.split_input_params[\"tie_braker\"]:\n L_weighting = self.delta_border(Ly, Lx)\n L_weighting = torch.clip(L_weighting,\n self.split_input_params[\"clip_min_tie_weight\"],\n self.split_input_params[\"clip_max_tie_weight\"])\n\n L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)\n weighting = weighting * L_weighting\n return weighting\n\n def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code\n \"\"\"\n :param x: img of size (bs, c, h, w)\n :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])\n \"\"\"\n bs, nc, h, w = x.shape\n\n # number of crops in image\n Ly = (h - kernel_size[0]) // stride[0] + 1\n Lx = (w - kernel_size[1]) // stride[1] + 1\n\n if uf == 1 and df == 1:\n fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)\n unfold = torch.nn.Unfold(**fold_params)\n\n fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)\n\n weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)\n normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap\n weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))\n\n elif uf > 1 and df == 1:\n fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)\n unfold = torch.nn.Unfold(**fold_params)\n\n fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),\n dilation=1, padding=0,\n stride=(stride[0] * uf, stride[1] * uf))\n fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)\n\n weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)\n normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap\n weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))\n\n elif df > 1 and uf == 1:\n fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)\n unfold = torch.nn.Unfold(**fold_params)\n\n fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),\n dilation=1, padding=0,\n stride=(stride[0] // df, stride[1] // df))\n fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)\n\n weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)\n normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap\n weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))\n\n else:\n raise NotImplementedError\n\n return fold, unfold, normalization, weighting\n\n @torch.no_grad()\n def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,\n cond_key=None, return_original_cond=False, bs=None, return_x=False):\n x = super().get_input(batch, k)\n if bs is not None:\n x = x[:bs]\n x = x.to(self.device)\n encoder_posterior = self.encode_first_stage(x)\n z = self.get_first_stage_encoding(encoder_posterior).detach()\n\n if self.model.conditioning_key is not None and not self.force_null_conditioning:\n if cond_key is None:\n cond_key = self.cond_stage_key\n if cond_key != self.first_stage_key:\n if cond_key in ['caption', 'coordinates_bbox', 'txt', 'vision']:\n xc = batch[cond_key]\n xc = rearrange(xc, 'b h w c -> b c h w')\n elif cond_key in ['class_label', 'cls']:\n xc = batch\n else:\n xc = super().get_input(batch, cond_key).to(self.device)\n else:\n xc = x\n if not self.cond_stage_trainable or force_c_encode:\n if isinstance(xc, dict) or isinstance(xc, list):\n c = self.get_learned_conditioning(xc)\n else:\n c = self.get_learned_conditioning(xc.to(self.device))\n else:\n c = xc\n if bs is not None:\n c = c[:bs]\n\n if self.use_positional_encodings:\n pos_x, pos_y = self.compute_latent_shifts(batch)\n ckey = __conditioning_keys__[self.model.conditioning_key]\n c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y}\n\n else:\n c = None\n xc = None\n if self.use_positional_encodings:\n pos_x, pos_y = self.compute_latent_shifts(batch)\n c = {'pos_x': pos_x, 'pos_y': pos_y}\n out = [z, c]\n if return_first_stage_outputs:\n xrec = self.decode_first_stage(z)\n out.extend([x, xrec])\n if return_x:\n out.extend([x])\n if return_original_cond:\n out.append(xc)\n return out\n\n @torch.no_grad()\n def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):\n if predict_cids:\n if z.dim() == 4:\n z = torch.argmax(z.exp(), dim=1).long()\n z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)\n z = rearrange(z, 'b h w c -> b c h w').contiguous()\n\n z = 1. / self.scale_factor * z\n return self.first_stage_model.decode(z)\n\n @torch.no_grad()\n def encode_first_stage(self, x):\n return self.first_stage_model.encode(x)\n\n def shared_step(self, batch, **kwargs):\n x, c = self.get_input(batch, self.first_stage_key)\n loss = self(x, c)\n return loss\n\n def forward(self, x, c, *args, **kwargs):\n t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()\n if self.model.conditioning_key is not None:\n assert c is not None\n if self.cond_stage_trainable:\n c = self.get_learned_conditioning(c)\n if self.shorten_cond_schedule: # TODO: drop this option\n tc = self.cond_ids[t].to(self.device)\n c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))\n return self.p_losses(x, c, t, *args, **kwargs)\n\n def apply_model(self, x_noisy, t, cond, return_ids=False):\n if isinstance(cond, dict):\n # hybrid case, cond is expected to be a dict\n pass\n else:\n if not isinstance(cond, list):\n cond = [cond]\n key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'\n cond = {key: cond}\n\n x_recon = self.model(x_noisy, t, **cond)\n\n if isinstance(x_recon, tuple) and not return_ids:\n return x_recon[0]\n else:\n return x_recon\n\n def _predict_eps_from_xstart(self, x_t, t, pred_xstart):\n return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \\\n extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)\n\n def _prior_bpd(self, x_start):\n \"\"\"\n Get the prior KL term for the variational lower-bound, measured in\n bits-per-dim.\n This term can't be optimized, as it only depends on the encoder.\n :param x_start: the [N x C x ...] tensor of inputs.\n :return: a batch of [N] KL values (in bits), one per batch element.\n \"\"\"\n batch_size = x_start.shape[0]\n t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)\n qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)\n kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)\n return mean_flat(kl_prior) / np.log(2.0)\n\n def p_losses(self, x_start, cond, t, noise=None):\n noise = default(noise, lambda: torch.randn_like(x_start))\n x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)\n model_output = self.apply_model(x_noisy, t, cond)\n \n loss_dict = {}\n prefix = 'train' if self.training else 'val'\n\n if self.parameterization == \"x0\":\n target = x_start\n elif self.parameterization == \"eps\":\n target = noise\n elif self.parameterization == \"v\":\n target = self.get_v(x_start, noise, t)\n else:\n raise NotImplementedError()\n\n loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])\n loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})\n\n logvar_t = self.logvar[t].to(self.device)\n loss = loss_simple / torch.exp(logvar_t) + logvar_t\n # loss = loss_simple / torch.exp(self.logvar) + self.logvar\n if self.learn_logvar:\n loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})\n loss_dict.update({'logvar': self.logvar.data.mean()})\n\n loss = self.l_simple_weight * loss.mean()\n\n loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))\n loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()\n loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})\n loss += (self.original_elbo_weight * loss_vlb)\n loss_dict.update({f'{prefix}/loss': loss})\n return loss, loss_dict\n\n def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,\n return_x0=False, score_corrector=None, corrector_kwargs=None):\n t_in = t\n model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)\n\n if score_corrector is not None:\n assert self.parameterization == \"eps\"\n model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)\n\n if return_codebook_ids:\n model_out, logits = model_out\n\n if self.parameterization == \"eps\":\n x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)\n elif self.parameterization == \"x0\":\n x_recon = model_out\n else:\n raise NotImplementedError()\n\n if clip_denoised:\n x_recon.clamp_(-1., 1.)\n if quantize_denoised:\n x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)\n model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)\n if return_codebook_ids:\n return model_mean, posterior_variance, posterior_log_variance, logits\n elif return_x0:\n return model_mean, posterior_variance, posterior_log_variance, x_recon\n else:\n return model_mean, posterior_variance, posterior_log_variance\n\n @torch.no_grad()\n def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,\n return_codebook_ids=False, quantize_denoised=False, return_x0=False,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):\n b, *_, device = *x.shape, x.device\n outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,\n return_codebook_ids=return_codebook_ids,\n quantize_denoised=quantize_denoised,\n return_x0=return_x0,\n score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)\n if return_codebook_ids:\n raise DeprecationWarning(\"Support dropped.\")\n model_mean, _, model_log_variance, logits = outputs\n elif return_x0:\n model_mean, _, model_log_variance, x0 = outputs\n else:\n model_mean, _, model_log_variance = outputs\n\n noise = noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n # no noise when t == 0\n nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))\n\n if return_codebook_ids:\n return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)\n if return_x0:\n return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0\n else:\n return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise\n\n @torch.no_grad()\n def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,\n img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,\n score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,\n log_every_t=None):\n if not log_every_t:\n log_every_t = self.log_every_t\n timesteps = self.num_timesteps\n if batch_size is not None:\n b = batch_size if batch_size is not None else shape[0]\n shape = [batch_size] + list(shape)\n else:\n b = batch_size = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=self.device)\n else:\n img = x_T\n intermediates = []\n if cond is not None:\n if isinstance(cond, dict):\n cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else\n list(map(lambda x: x[:batch_size], cond[key])) for key in cond}\n else:\n cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]\n\n if start_T is not None:\n timesteps = min(timesteps, start_T)\n iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',\n total=timesteps) if verbose else reversed(\n range(0, timesteps))\n if type(temperature) == float:\n temperature = [temperature] * timesteps\n\n for i in iterator:\n ts = torch.full((b,), i, device=self.device, dtype=torch.long)\n if self.shorten_cond_schedule:\n assert self.model.conditioning_key != 'hybrid'\n tc = self.cond_ids[ts].to(cond.device)\n cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))\n\n img, x0_partial = self.p_sample(img, cond, ts,\n clip_denoised=self.clip_denoised,\n quantize_denoised=quantize_denoised, return_x0=True,\n temperature=temperature[i], noise_dropout=noise_dropout,\n score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)\n if mask is not None:\n assert x0 is not None\n img_orig = self.q_sample(x0, ts)\n img = img_orig * mask + (1. - mask) * img\n\n if i % log_every_t == 0 or i == timesteps - 1:\n intermediates.append(x0_partial)\n if callback: callback(i)\n if img_callback: img_callback(img, i)\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_loop(self, cond, shape, return_intermediates=False,\n x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, img_callback=None, start_T=None,\n log_every_t=None):\n\n if not log_every_t:\n log_every_t = self.log_every_t\n device = self.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n intermediates = [img]\n if timesteps is None:\n timesteps = self.num_timesteps\n\n if start_T is not None:\n timesteps = min(timesteps, start_T)\n iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(\n range(0, timesteps))\n\n if mask is not None:\n assert x0 is not None\n assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match\n\n for i in iterator:\n ts = torch.full((b,), i, device=device, dtype=torch.long)\n if self.shorten_cond_schedule:\n assert self.model.conditioning_key != 'hybrid'\n tc = self.cond_ids[ts].to(cond.device)\n cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))\n\n img = self.p_sample(img, cond, ts,\n clip_denoised=self.clip_denoised,\n quantize_denoised=quantize_denoised)\n if mask is not None:\n img_orig = self.q_sample(x0, ts)\n img = img_orig * mask + (1. - mask) * img\n\n if i % log_every_t == 0 or i == timesteps - 1:\n intermediates.append(img)\n if callback: callback(i)\n if img_callback: img_callback(img, i)\n\n if return_intermediates:\n return img, intermediates\n return img\n\n @torch.no_grad()\n def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,\n verbose=True, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, shape=None, **kwargs):\n if shape is None:\n shape = (batch_size, self.channels, self.image_size, self.image_size)\n if cond is not None:\n if isinstance(cond, dict):\n cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else\n list(map(lambda x: x[:batch_size], cond[key])) for key in cond}\n else:\n cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]\n return self.p_sample_loop(cond,\n shape,\n return_intermediates=return_intermediates, x_T=x_T,\n verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,\n mask=mask, x0=x0)\n\n @torch.no_grad()\n def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):\n if ddim:\n ddim_sampler = DDIMSampler(self)\n shape = (self.channels, self.image_size, self.image_size)\n samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size,\n shape, cond, verbose=False, **kwargs)\n\n else:\n samples, intermediates = self.sample(cond=cond, batch_size=batch_size,\n return_intermediates=True, **kwargs)\n\n return samples, intermediates\n\n @torch.no_grad()\n def get_unconditional_conditioning(self, batch_size, null_label=None):\n if null_label is not None:\n xc = null_label\n if isinstance(xc, ListConfig):\n xc = list(xc)\n if isinstance(xc, dict) or isinstance(xc, list):\n c = self.get_learned_conditioning(xc)\n else:\n if hasattr(xc, \"to\"):\n xc = xc.to(self.device)\n c = self.get_learned_conditioning(xc)\n else:\n if self.cond_stage_key in [\"class_label\", \"cls\"]:\n xc = self.cond_stage_model.get_unconditional_conditioning(batch_size, device=self.device)\n return self.get_learned_conditioning(xc)\n else:\n raise NotImplementedError(\"todo\")\n if isinstance(c, list): # in case the encoder gives us a list\n for i in range(len(c)):\n c[i] = repeat(c[i], '1 ... -> b ...', b=batch_size).to(self.device)\n else:\n c = repeat(c, '1 ... -> b ...', b=batch_size).to(self.device)\n return c\n\n @torch.no_grad()\n def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=50, ddim_eta=0., return_keys=None,\n quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,\n plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None,\n use_ema_scope=True,\n **kwargs):\n ema_scope = self.ema_scope if use_ema_scope else nullcontext\n use_ddim = ddim_steps is not None\n\n log = dict()\n z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,\n return_first_stage_outputs=True,\n force_c_encode=True,\n return_original_cond=True,\n bs=N)\n N = min(x.shape[0], N)\n n_row = min(x.shape[0], n_row)\n log[\"inputs\"] = x\n log[\"reconstruction\"] = xrec\n if self.model.conditioning_key is not None:\n if hasattr(self.cond_stage_model, \"decode\"):\n xc = self.cond_stage_model.decode(c)\n log[\"conditioning\"] = xc\n elif self.cond_stage_key in [\"caption\", \"txt\"]:\n xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)\n log[\"conditioning\"] = xc\n elif self.cond_stage_key in ['class_label', \"cls\"]:\n try:\n xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[\"human_label\"], size=x.shape[2] // 25)\n log['conditioning'] = xc\n except KeyError:\n # probably no \"human_label\" in batch\n pass\n elif isimage(xc):\n log[\"conditioning\"] = xc\n if ismap(xc):\n log[\"original_conditioning\"] = self.to_rgb(xc)\n\n if plot_diffusion_rows:\n # get diffusion row\n diffusion_row = list()\n z_start = z[:n_row]\n for t in range(self.num_timesteps):\n if t % self.log_every_t == 0 or t == self.num_timesteps - 1:\n t = repeat(torch.tensor([t]), '1 -> b', b=n_row)\n t = t.to(self.device).long()\n noise = torch.randn_like(z_start)\n z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)\n diffusion_row.append(self.decode_first_stage(z_noisy))\n\n diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W\n diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')\n diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')\n diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])\n log[\"diffusion_row\"] = diffusion_grid\n\n if sample:\n # get denoise row\n with ema_scope(\"Sampling\"):\n samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,\n ddim_steps=ddim_steps, eta=ddim_eta)\n # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)\n x_samples = self.decode_first_stage(samples)\n log[\"samples\"] = x_samples\n if plot_denoise_rows:\n denoise_grid = self._get_denoise_row_from_list(z_denoise_row)\n log[\"denoise_row\"] = denoise_grid\n\n if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(\n self.first_stage_model, IdentityFirstStage):\n # also display when quantizing x0 while sampling\n with ema_scope(\"Plotting Quantized Denoised\"):\n samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,\n ddim_steps=ddim_steps, eta=ddim_eta,\n quantize_denoised=True)\n # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,\n # quantize_denoised=True)\n x_samples = self.decode_first_stage(samples.to(self.device))\n log[\"samples_x0_quantized\"] = x_samples\n\n if unconditional_guidance_scale > 1.0:\n uc = self.get_unconditional_conditioning(N, unconditional_guidance_label)\n if self.model.conditioning_key == \"crossattn-adm\":\n uc = {\"c_crossattn\": [uc], \"c_adm\": c[\"c_adm\"]}\n with ema_scope(\"Sampling with classifier-free guidance\"):\n samples_cfg, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,\n ddim_steps=ddim_steps, eta=ddim_eta,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=uc,\n )\n x_samples_cfg = self.decode_first_stage(samples_cfg)\n log[f\"samples_cfg_scale_{unconditional_guidance_scale:.2f}\"] = x_samples_cfg\n\n if inpaint:\n # make a simple center square\n b, h, w = z.shape[0], z.shape[2], z.shape[3]\n mask = torch.ones(N, h, w).to(self.device)\n # zeros will be filled in\n mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.\n mask = mask[:, None, ...]\n with ema_scope(\"Plotting Inpaint\"):\n samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta,\n ddim_steps=ddim_steps, x0=z[:N], mask=mask)\n x_samples = self.decode_first_stage(samples.to(self.device))\n log[\"samples_inpainting\"] = x_samples\n log[\"mask\"] = mask\n\n # outpaint\n mask = 1. - mask\n with ema_scope(\"Plotting Outpaint\"):\n samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta,\n ddim_steps=ddim_steps, x0=z[:N], mask=mask)\n x_samples = self.decode_first_stage(samples.to(self.device))\n log[\"samples_outpainting\"] = x_samples\n\n if plot_progressive_rows:\n with ema_scope(\"Plotting Progressives\"):\n img, progressives = self.progressive_denoising(c,\n shape=(self.channels, self.image_size, self.image_size),\n batch_size=N)\n prog_row = self._get_denoise_row_from_list(progressives, desc=\"Progressive Generation\")\n log[\"progressive_row\"] = prog_row\n\n if return_keys:\n if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:\n return log\n else:\n return {key: log[key] for key in return_keys}\n return log\n\n def configure_optimizers(self):\n lr = self.learning_rate\n params = list(self.model.parameters())\n if self.cond_stage_trainable:\n print(f\"{self.__class__.__name__}: Also optimizing conditioner params!\")\n params = params + list(self.cond_stage_model.parameters())\n if self.learn_logvar:\n print('Diffusion model optimizing logvar')\n params.append(self.logvar)\n opt = torch.optim.AdamW(params, lr=lr)\n if self.use_scheduler:\n assert 'target' in self.scheduler_config\n scheduler = instantiate_from_config(self.scheduler_config)\n\n print(\"Setting up LambdaLR scheduler...\")\n scheduler = [\n {\n 'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),\n 'interval': 'step',\n 'frequency': 1\n }]\n return [opt], scheduler\n return opt\n\n @torch.no_grad()\n def to_rgb(self, x):\n x = x.float()\n if not hasattr(self, \"colorize\"):\n self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)\n x = nn.functional.conv2d(x, weight=self.colorize)\n x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.\n return x" }, { "identifier": "log_txt_as_img", "path": "ldm/util.py", "snippet": "def log_txt_as_img(wh, xc, size=10):\n # wh a tuple of (width, height)\n # xc a list of captions to plot\n b = len(xc)\n txts = list()\n for bi in range(b):\n txt = Image.new(\"RGB\", wh, color=\"white\")\n draw = ImageDraw.Draw(txt)\n font = ImageFont.truetype('font/DejaVuSans.ttf', size=size)\n nc = int(40 * (wh[0] / 256))\n lines = \"\\n\".join(xc[bi][start:start + nc] for start in range(0, len(xc[bi]), nc))\n\n try:\n draw.text((0, 0), lines, fill=\"black\", font=font)\n except UnicodeEncodeError:\n print(\"Cant encode string for logging. Skipping.\")\n\n txt = np.array(txt).transpose(2, 0, 1) / 127.5 - 1.0\n txts.append(txt)\n txts = np.stack(txts)\n txts = torch.tensor(txts)\n return txts" }, { "identifier": "exists", "path": "ldm/util.py", "snippet": "def exists(x):\n return x is not None" }, { "identifier": "instantiate_from_config", "path": "ldm/util.py", "snippet": "def instantiate_from_config(config):\n if not \"target\" in config:\n if config == '__is_first_stage__':\n return None\n elif config == \"__is_unconditional__\":\n return None\n raise KeyError(\"Expected key `target` to instantiate.\")\n return get_obj_from_str(config[\"target\"])(**config.get(\"params\", dict()))" }, { "identifier": "DDIMSampler", "path": "ldm/models/diffusion/ddim.py", "snippet": "class DDIMSampler(object):\n def __init__(self, model, schedule=\"linear\", **kwargs):\n super().__init__()\n self.model = model\n self.ddpm_num_timesteps = model.num_timesteps\n self.schedule = schedule\n\n def register_buffer(self, name, attr):\n if type(attr) == torch.Tensor:\n if attr.device != torch.device(\"cuda\"):\n attr = attr.to(torch.device(\"cuda\"))\n setattr(self, name, attr)\n\n def make_schedule(self, ddim_num_steps, ddim_discretize=\"uniform\", ddim_eta=0., verbose=True):\n self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,\n num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)\n alphas_cumprod = self.model.alphas_cumprod\n assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'\n to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)\n\n self.register_buffer('betas', to_torch(self.model.betas))\n self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))\n self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))\n\n # calculations for diffusion q(x_t | x_{t-1}) and others\n self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))\n self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))\n self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))\n\n # ddim sampling parameters\n ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),\n ddim_timesteps=self.ddim_timesteps,\n eta=ddim_eta,verbose=verbose)\n self.register_buffer('ddim_sigmas', ddim_sigmas)\n self.register_buffer('ddim_alphas', ddim_alphas)\n self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)\n self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))\n sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(\n (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (\n 1 - self.alphas_cumprod / self.alphas_cumprod_prev))\n self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)\n\n @torch.no_grad()\n def sample(self,\n S,\n batch_size,\n shape,\n conditioning=None,\n callback=None,\n normals_sequence=None,\n img_callback=None,\n quantize_x0=False,\n eta=0.,\n mask=None,\n x0=None,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n verbose=True,\n x_T=None,\n log_every_t=100,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...\n dynamic_threshold=None,\n ucg_schedule=None,\n **kwargs\n ):\n if conditioning is not None:\n if isinstance(conditioning, dict):\n ctmp = conditioning[list(conditioning.keys())[0]]\n while isinstance(ctmp, list): ctmp = ctmp[0]\n cbs = ctmp.shape[0]\n if cbs != batch_size:\n print(f\"Warning: Got {cbs} conditionings but batch-size is {batch_size}\")\n\n elif isinstance(conditioning, list):\n for ctmp in conditioning:\n if ctmp.shape[0] != batch_size:\n print(f\"Warning: Got {cbs} conditionings but batch-size is {batch_size}\")\n\n else:\n if conditioning.shape[0] != batch_size:\n print(f\"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}\")\n\n self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)\n # sampling\n C, H, W = shape\n size = (batch_size, C, H, W)\n print(f'Data shape for DDIM sampling is {size}, eta {eta}')\n\n samples, intermediates = self.ddim_sampling(conditioning, size,\n callback=callback,\n img_callback=img_callback,\n quantize_denoised=quantize_x0,\n mask=mask, x0=x0,\n ddim_use_original_steps=False,\n noise_dropout=noise_dropout,\n temperature=temperature,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n x_T=x_T,\n log_every_t=log_every_t,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n dynamic_threshold=dynamic_threshold,\n ucg_schedule=ucg_schedule\n )\n return samples, intermediates\n\n @torch.no_grad()\n def ddim_sampling(self, cond, shape,\n x_T=None, ddim_use_original_steps=False,\n callback=None, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, img_callback=None, log_every_t=100,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None, dynamic_threshold=None,\n ucg_schedule=None):\n device = self.model.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n if timesteps is None:\n timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps\n elif timesteps is not None and not ddim_use_original_steps:\n subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1\n timesteps = self.ddim_timesteps[:subset_end]\n\n intermediates = {'x_inter': [img], 'pred_x0': [img]}\n time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)\n total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]\n print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)\n\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((b,), step, device=device, dtype=torch.long)\n\n if mask is not None:\n assert x0 is not None\n img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?\n img = img_orig * mask + (1. - mask) * img\n\n if ucg_schedule is not None:\n assert len(ucg_schedule) == len(time_range)\n unconditional_guidance_scale = ucg_schedule[i]\n\n outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,\n quantize_denoised=quantize_denoised, temperature=temperature,\n noise_dropout=noise_dropout, score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n dynamic_threshold=dynamic_threshold)\n img, pred_x0 = outs\n if callback: callback(i)\n if img_callback: img_callback(pred_x0, i)\n\n if index % log_every_t == 0 or index == total_steps - 1:\n intermediates['x_inter'].append(img)\n intermediates['pred_x0'].append(pred_x0)\n\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None,\n dynamic_threshold=None):\n b, *_, device = *x.shape, x.device\n\n if unconditional_conditioning is None or unconditional_guidance_scale == 1.:\n model_output = self.model.apply_model(x, t, c)\n else:\n x_in = torch.cat([x] * 2)\n t_in = torch.cat([t] * 2)\n if isinstance(c, dict):\n assert isinstance(unconditional_conditioning, dict)\n c_in = dict()\n for k in c:\n if isinstance(c[k], list):\n c_in[k] = [torch.cat([\n unconditional_conditioning[k][i],\n c[k][i]]) for i in range(len(c[k]))]\n else:\n c_in[k] = torch.cat([\n unconditional_conditioning[k],\n c[k]])\n elif isinstance(c, list):\n c_in = list()\n assert isinstance(unconditional_conditioning, list)\n for i in range(len(c)):\n c_in.append(torch.cat([unconditional_conditioning[i], c[i]]))\n else:\n c_in = torch.cat([unconditional_conditioning, c])\n model_uncond, model_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)\n model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond)\n\n if self.model.parameterization == \"v\":\n e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)\n else:\n e_t = model_output\n\n if score_corrector is not None:\n assert self.model.parameterization == \"eps\", 'not implemented'\n e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)\n\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n # select parameters corresponding to the currently considered timestep\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)\n sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)\n\n # current prediction for x_0\n if self.model.parameterization != \"v\":\n pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n else:\n pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)\n\n if quantize_denoised:\n pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n\n if dynamic_threshold is not None:\n raise NotImplementedError()\n\n # direction pointing to x_t\n dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t\n noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n return x_prev, pred_x0\n\n @torch.no_grad()\n def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None,\n unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None):\n num_reference_steps = self.ddpm_num_timesteps if use_original_steps else self.ddim_timesteps.shape[0]\n\n assert t_enc <= num_reference_steps\n num_steps = t_enc\n\n if use_original_steps:\n alphas_next = self.alphas_cumprod[:num_steps]\n alphas = self.alphas_cumprod_prev[:num_steps]\n else:\n alphas_next = self.ddim_alphas[:num_steps]\n alphas = torch.tensor(self.ddim_alphas_prev[:num_steps])\n\n x_next = x0\n intermediates = []\n inter_steps = []\n for i in tqdm(range(num_steps), desc='Encoding Image'):\n t = torch.full((x0.shape[0],), i, device=self.model.device, dtype=torch.long)\n if unconditional_guidance_scale == 1.:\n noise_pred = self.model.apply_model(x_next, t, c)\n else:\n assert unconditional_conditioning is not None\n e_t_uncond, noise_pred = torch.chunk(\n self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)),\n torch.cat((unconditional_conditioning, c))), 2)\n noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond)\n\n xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next\n weighted_noise_pred = alphas_next[i].sqrt() * (\n (1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred\n x_next = xt_weighted + weighted_noise_pred\n if return_intermediates and i % (\n num_steps // return_intermediates) == 0 and i < num_steps - 1:\n intermediates.append(x_next)\n inter_steps.append(i)\n elif return_intermediates and i >= num_steps - 2:\n intermediates.append(x_next)\n inter_steps.append(i)\n if callback: callback(i)\n\n out = {'x_encoded': x_next, 'intermediate_steps': inter_steps}\n if return_intermediates:\n out.update({'intermediates': intermediates})\n return x_next, out\n\n @torch.no_grad()\n def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):\n # fast, but does not allow for exact reconstruction\n # t serves as an index to gather the correct alphas\n if use_original_steps:\n sqrt_alphas_cumprod = self.sqrt_alphas_cumprod\n sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod\n else:\n sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)\n sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas\n\n if noise is None:\n noise = torch.randn_like(x0)\n return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +\n extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)\n\n @torch.no_grad()\n def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,\n use_original_steps=False, callback=None):\n\n timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps\n timesteps = timesteps[:t_start]\n\n time_range = np.flip(timesteps)\n total_steps = timesteps.shape[0]\n print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n iterator = tqdm(time_range, desc='Decoding image', total=total_steps)\n x_dec = x_latent\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)\n x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning)\n if callback: callback(i)\n return x_dec" } ]
import einops import torch import torch as th import torch.nn as nn from ldm.modules.diffusionmodules.util import ( conv_nd, linear, zero_module, timestep_embedding, ) from einops import rearrange, repeat from torchvision.utils import make_grid from ldm.modules.attention import SpatialTransformer, SpatialTransformerPlus from ldm.modules.diffusionmodules.openaimodel import ResBlock, TimestepEmbedSequential, Downsample, AttentionBlock, Upsample, normalization, checkpoint, convert_module_to_f16, convert_module_to_f32 from ldm.models.diffusion.ddpm import LatentDiffusion from ldm.util import log_txt_as_img, exists, instantiate_from_config from ldm.models.diffusion.ddim import DDIMSampler from omegaconf.listconfig import ListConfig from omegaconf.listconfig import ListConfig
19,720
""" Convert the torso of the model to float32. """ self.conv1.apply(convert_module_to_f32) self.conv2.apply(convert_module_to_f32) self.conv3.apply(convert_module_to_f32) self.conv4.apply(convert_module_to_f32) self.proj.apply(convert_module_to_f32) def forward(self, x): x = self.conv1(x) x = self.conv2(x) x = self.conv3(x) x = self.conv4(x) x = self.proj(x) return x class AnimateLDM(LatentDiffusion): def __init__(self, reference_stage_config, pose_guider_config, target_key, reference_key, skeleton_key, *args, **kwargs): super().__init__(*args, **kwargs) self.reference_model = instantiate_from_config(reference_stage_config) self.pose_model = instantiate_from_config(pose_guider_config) self.target_key = target_key self.reference_key = reference_key self.skeleton_key = skeleton_key self.animate_scales = [1.0] * 13 @torch.no_grad() def get_input(self, batch, k, bs=None, *args, **kwargs): x, _ = super().get_input(batch, self.target_key, *args, **kwargs) ref_x, ref_c = super().get_input(batch, self.reference_key, *args, **kwargs) reference = batch[self.reference_key] skeleton = batch[self.skeleton_key] if bs is not None: reference = reference[:bs] skeleton = skeleton[:bs] reference = reference.to(self.device) skeleton = skeleton.to(self.device) reference = einops.rearrange(reference, 'b h w c -> b c h w') skeleton = einops.rearrange(skeleton, 'b h w c -> b c h w') reference = reference.to(memory_format=torch.contiguous_format).float() skeleton = skeleton.to(memory_format=torch.contiguous_format).float() return x, dict(c_crossattn=[ref_c], c_concat=None, img_skeleton=skeleton, img_reference=reference, latent_reference=ref_x) def apply_model(self, x_noisy, t, cond, *args, **kwargs): assert isinstance(cond, dict) diffusion_model = self.model.diffusion_model cond_img = cond['c_crossattn'] refs = self.reference_model(x=cond['latent_reference'], timesteps=t, context=cond_img) pose = self.pose_model(x=cond['img_skeleton']) # control = [c * scale for c, scale in zip(control, self.control_scales)] eps = diffusion_model(x=x_noisy + pose, timesteps=t, context=cond_img, refs=refs) return eps @torch.no_grad() def get_unconditional_conditioning(self, N): return self.get_learned_conditioning([""] * N) @torch.no_grad() def log_images(self, batch, N=4, n_row=2, sample=False, ddim_steps=50, ddim_eta=0.0, return_keys=None, quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=False, unconditional_guidance_scale=9.0, unconditional_guidance_label=None, use_ema_scope=True, **kwargs): use_ddim = ddim_steps is not None log = dict() z, cond = self.get_input(batch, self.target_key, bs=N) N = min(z.shape[0], N) n_row = min(z.shape[0], n_row) log["reconstruction"] = self.decode_first_stage(z) log["reference"] = cond["img_reference"] log["skeleton"] = cond["img_skeleton"] * 2.0 - 1.0 if plot_diffusion_rows: # get diffusion row diffusion_row = list() z_start = z[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), '1 -> b', b=n_row) t = t.to(self.device).long() noise = torch.randn_like(z_start) z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise) diffusion_row.append(self.decode_first_stage(z_noisy)) diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w') diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w') diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0]) log["diffusion_row"] = diffusion_grid if sample: # get denoise row # cond={"c_concat": [c_cat], "c_crossattn": [c_txt], "c_reference": [ref_x], "c_skeleton": [c_skt]} samples, z_denoise_row = self.sample_log(cond=cond, batch_size=N, ddim=use_ddim, ddim_steps=ddim_steps, eta=ddim_eta) x_samples = self.decode_first_stage(samples) log["samples"] = x_samples if plot_denoise_rows: denoise_grid = self._get_denoise_row_from_list(z_denoise_row) log["denoise_row"] = denoise_grid if unconditional_guidance_scale > 1.0: samples_cfg, _ = self.sample_log(cond=cond, batch_size=N, ddim=use_ddim, ddim_steps=ddim_steps, eta=ddim_eta, unconditional_guidance_scale=unconditional_guidance_scale, ) x_samples_cfg = self.decode_first_stage(samples_cfg) log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg return log @torch.no_grad() def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):
class ReferenceNet(nn.Module): """ The full UNet model with attention and timestep embedding. :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, num_res_blocks, attention_resolutions, dropout=0, channel_mult=(1, 2, 4, 8), conv_resample=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=False, resblock_updown=False, use_new_attention_order=False, use_spatial_transformer=False, # custom transformer support transformer_depth=1, # custom transformer support context_dim=None, # custom transformer support n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model legacy=True, disable_self_attentions=None, num_attention_blocks=None, disable_middle_self_attn=False, use_linear_in_transformer=False, ): super().__init__() if use_spatial_transformer: assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...' if context_dim is not None: assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...' if type(context_dim) == ListConfig: context_dim = list(context_dim) if num_heads_upsample == -1: num_heads_upsample = num_heads if num_heads == -1: assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set' if num_head_channels == -1: assert num_heads != -1, 'Either num_heads or num_head_channels has to be set' self.image_size = image_size self.in_channels = in_channels self.model_channels = model_channels if isinstance(num_res_blocks, int): self.num_res_blocks = len(channel_mult) * [num_res_blocks] else: if len(num_res_blocks) != len(channel_mult): raise ValueError("provide num_res_blocks either as an int (globally constant) or " "as a list/tuple (per-level) with the same length as channel_mult") self.num_res_blocks = num_res_blocks if disable_self_attentions is not None: # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not assert len(disable_self_attentions) == len(channel_mult) if num_attention_blocks is not None: assert len(num_attention_blocks) == len(self.num_res_blocks) assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks)))) print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. " f"This option has LESS priority than attention_resolutions {attention_resolutions}, " f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, " f"attention will still not be set.") 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.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.predict_codebook_ids = n_embed is not 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), ) self.input_blocks = nn.ModuleList( [ TimestepEmbedSequential( conv_nd(dims, in_channels, model_channels, 3, padding=1) ) ] ) self._feature_size = model_channels input_block_chans = [model_channels] ch = model_channels ds = 1 for level, mult in enumerate(channel_mult): for nr in range(self.num_res_blocks[level]): layers = [ ResBlock( ch, time_embed_dim, dropout, out_channels=mult * model_channels, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ) ] ch = mult * model_channels if ds in attention_resolutions: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels if exists(disable_self_attentions): disabled_sa = disable_self_attentions[level] else: disabled_sa = False if not exists(num_attention_blocks) or nr < num_attention_blocks[level]: layers.append( AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads, num_head_channels=dim_head, use_new_attention_order=use_new_attention_order, ) if not use_spatial_transformer else SpatialTransformer( ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer, use_checkpoint=use_checkpoint ) ) 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, 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 if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels self.middle_block = TimestepEmbedSequential( ResBlock( ch, time_embed_dim, dropout, out_channels=ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ), AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads, num_head_channels=dim_head, use_new_attention_order=use_new_attention_order, ) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer, use_checkpoint=use_checkpoint ), ResBlock( ch, time_embed_dim, dropout, out_channels=ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ), ) self._feature_size += ch self.output_blocks = nn.ModuleList([]) for level, mult in list(enumerate(channel_mult))[::-1]: for i in range(self.num_res_blocks[level] + 1): ich = input_block_chans.pop() layers = [ ResBlock( ch + ich, time_embed_dim, dropout, out_channels=model_channels * mult, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ) ] ch = model_channels * mult if ds in attention_resolutions: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels if exists(disable_self_attentions): disabled_sa = disable_self_attentions[level] else: disabled_sa = False if not exists(num_attention_blocks) or i < num_attention_blocks[level]: layers.append( AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads_upsample, num_head_channels=dim_head, use_new_attention_order=use_new_attention_order, ) if not use_spatial_transformer else SpatialTransformer( ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer, use_checkpoint=use_checkpoint ) ) if level and i == self.num_res_blocks[level]: out_ch = ch layers.append( ResBlock( ch, time_embed_dim, dropout, out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, up=True, ) if resblock_updown else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch) ) ds //= 2 self.output_blocks.append(TimestepEmbedSequential(*layers)) self._feature_size += ch 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) 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) def forward(self, x, timesteps=None, context=None, y=None,**kwargs): """ 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 context: conditioning plugged in via crossattn :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" refs = [] hs = [] t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False) emb = self.time_embed(t_emb) h = x.type(self.dtype) # --------- input_block --------- for module in self.input_blocks: for sub_m in module: if isinstance(sub_m, ResBlock): h = sub_m(h, emb) elif isinstance(sub_m, SpatialTransformer): refs.append(h) # push features into refs before cross attention module h = sub_m(h, context) else: h = sub_m(h) hs.append(h) # --------- middle_block --------- for sub_m in self.middle_block: if isinstance(sub_m, ResBlock): h = sub_m(h, emb) elif isinstance(sub_m, SpatialTransformer): refs.append(h) # push features into refs before cross attention module h = sub_m(h, context) else: h = sub_m(h) # --------- output_block --------- for module in self.output_blocks: h = th.cat([h, hs.pop()], dim=1) for sub_m in module: if isinstance(sub_m, ResBlock): h = sub_m(h, emb) elif isinstance(sub_m, SpatialTransformer): refs.append(h) # push features into refs before cross attention module h = sub_m(h, context) else: h = sub_m(h) return refs class ReferenceUNetModel(nn.Module): """ The full UNet model with attention and timestep embedding. :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, channel_mult=(1, 2, 4, 8), conv_resample=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=False, resblock_updown=False, use_new_attention_order=False, use_temporal_attention=False, use_spatial_transformer=False, # custom transformer support transformer_depth=1, # custom transformer support context_dim=None, # custom transformer support n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model legacy=True, disable_self_attentions=None, num_attention_blocks=None, disable_middle_self_attn=False, use_linear_in_transformer=False, frames=24, # temporal length ): super().__init__() if use_spatial_transformer: assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...' if context_dim is not None: assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...' if type(context_dim) == ListConfig: context_dim = list(context_dim) if num_heads_upsample == -1: num_heads_upsample = num_heads if num_heads == -1: assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set' if num_head_channels == -1: assert num_heads != -1, 'Either num_heads or num_head_channels has to be set' self.image_size = image_size self.in_channels = in_channels self.model_channels = model_channels self.out_channels = out_channels if isinstance(num_res_blocks, int): self.num_res_blocks = len(channel_mult) * [num_res_blocks] else: if len(num_res_blocks) != len(channel_mult): raise ValueError("provide num_res_blocks either as an int (globally constant) or " "as a list/tuple (per-level) with the same length as channel_mult") self.num_res_blocks = num_res_blocks if disable_self_attentions is not None: # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not assert len(disable_self_attentions) == len(channel_mult) if num_attention_blocks is not None: assert len(num_attention_blocks) == len(self.num_res_blocks) assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks)))) print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. " f"This option has LESS priority than attention_resolutions {attention_resolutions}, " f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, " f"attention will still not be set.") 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.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.predict_codebook_ids = n_embed is not 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.num_classes is not None: if isinstance(self.num_classes, int): self.label_emb = nn.Embedding(num_classes, time_embed_dim) elif self.num_classes == "continuous": print("setting up linear c_adm embedding layer") self.label_emb = nn.Linear(1, time_embed_dim) else: raise ValueError() self.input_blocks = nn.ModuleList( [ TimestepEmbedSequential( conv_nd(dims, in_channels, model_channels, 3, padding=1) ) ] ) self._feature_size = model_channels input_block_chans = [model_channels] ch = model_channels ds = 1 for level, mult in enumerate(channel_mult): for nr in range(self.num_res_blocks[level]): layers = [ ResBlock( ch, time_embed_dim, dropout, out_channels=mult * model_channels, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ) ] ch = mult * model_channels if ds in attention_resolutions: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels if exists(disable_self_attentions): disabled_sa = disable_self_attentions[level] else: disabled_sa = False if not exists(num_attention_blocks) or nr < num_attention_blocks[level]: layers.append( AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads, num_head_channels=dim_head, use_new_attention_order=use_new_attention_order, ) if not use_spatial_transformer else SpatialTransformerPlus( ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer, use_checkpoint=use_checkpoint, use_temporal_attention=use_temporal_attention ) ) 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, 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 if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels self.middle_block = TimestepEmbedSequential( ResBlock( ch, time_embed_dim, dropout, out_channels=ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ), AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads, num_head_channels=dim_head, use_new_attention_order=use_new_attention_order, ) if not use_spatial_transformer else SpatialTransformerPlus( # always uses a self-attn ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer, use_checkpoint=use_checkpoint, use_temporal_attention=use_temporal_attention ), ResBlock( ch, time_embed_dim, dropout, out_channels=ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ), ) self._feature_size += ch self.output_blocks = nn.ModuleList([]) for level, mult in list(enumerate(channel_mult))[::-1]: for i in range(self.num_res_blocks[level] + 1): ich = input_block_chans.pop() layers = [ ResBlock( ch + ich, time_embed_dim, dropout, out_channels=model_channels * mult, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ) ] ch = model_channels * mult if ds in attention_resolutions: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels if exists(disable_self_attentions): disabled_sa = disable_self_attentions[level] else: disabled_sa = False if not exists(num_attention_blocks) or i < num_attention_blocks[level]: layers.append( AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads_upsample, num_head_channels=dim_head, use_new_attention_order=use_new_attention_order, ) if not use_spatial_transformer else SpatialTransformerPlus( ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer, use_checkpoint=use_checkpoint, use_temporal_attention=use_temporal_attention ) ) if level and i == self.num_res_blocks[level]: out_ch = ch layers.append( ResBlock( ch, time_embed_dim, dropout, out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, up=True, ) if resblock_updown else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch) ) 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, model_channels, out_channels, 3, padding=1)), ) if self.predict_codebook_ids: self.id_predictor = nn.Sequential( normalization(ch), conv_nd(dims, model_channels, n_embed, 1), #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits ) 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) 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) def forward(self, x, timesteps=None, context=None, refs=None, y=None, **kwargs): """ 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 context: conditioning plugged in via crossattn :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" hs = [] t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False) emb = self.time_embed(t_emb) if self.num_classes is not None: assert y.shape[0] == x.shape[0] emb = emb + self.label_emb(y) # -------- input_block ----------- h = x.type(self.dtype) for module in self.input_blocks: for sub_m in module: if isinstance(sub_m, ResBlock): h = sub_m(h, emb) elif isinstance(sub_m, SpatialTransformerPlus): # push features into refs before cross attention module h = sub_m(h, context, refs.pop(0)) else: h = sub_m(h) hs.append(h) # -------- middle_block ---------- for sub_m in self.middle_block: if isinstance(sub_m, ResBlock): h = sub_m(h, emb) elif isinstance(sub_m, SpatialTransformerPlus): # push features into refs before cross attention module h = sub_m(h, context, refs.pop(0)) else: h = sub_m(h) # -------- output_block ---------- for module in self.output_blocks: h = th.cat([h, hs.pop()], dim=1) for sub_m in module: if isinstance(sub_m, ResBlock): h = sub_m(h, emb) elif isinstance(sub_m, SpatialTransformerPlus): # push features into refs before cross attention module h = sub_m(h, context, refs.pop(0)) else: h = sub_m(h) h = h.type(x.dtype) if self.predict_codebook_ids: return self.id_predictor(h) else: return self.out(h) class PoseGuider(nn.Module): def __init__(self, in_channels=3, out_channels=4, kernel_size=4, model_channels=[16, 32, 64, 128]): super().__init__() self.conv1 = nn.Sequential(nn.Conv2d(in_channels, model_channels[0], kernel_size, 2, padding=1), nn.GroupNorm(16, model_channels[0]), nn.SiLU()) self.conv2 = nn.Sequential(nn.Conv2d(model_channels[0], model_channels[1], kernel_size, 2, padding=1), nn.GroupNorm(16, model_channels[1]), nn.SiLU()) self.conv3 = nn.Sequential(nn.Conv2d(model_channels[1], model_channels[2], kernel_size, 2, padding=1), nn.GroupNorm(16, model_channels[2]), nn.SiLU()) self.conv4 = nn.Sequential(nn.Conv2d(model_channels[2], model_channels[3], kernel_size, 1, padding=1), nn.GroupNorm(16, model_channels[3]), nn.SiLU()) self.proj = zero_module(nn.Conv2d(model_channels[3], out_channels, kernel_size, 1, padding=1)) def convert_to_fp16(self): """ Convert the torso of the model to float16. """ self.conv1.apply(convert_module_to_f16) self.conv2.apply(convert_module_to_f16) self.conv3.apply(convert_module_to_f16) self.conv4.apply(convert_module_to_f16) self.proj.apply(convert_module_to_f16) def convert_to_fp32(self): """ Convert the torso of the model to float32. """ self.conv1.apply(convert_module_to_f32) self.conv2.apply(convert_module_to_f32) self.conv3.apply(convert_module_to_f32) self.conv4.apply(convert_module_to_f32) self.proj.apply(convert_module_to_f32) def forward(self, x): x = self.conv1(x) x = self.conv2(x) x = self.conv3(x) x = self.conv4(x) x = self.proj(x) return x class AnimateLDM(LatentDiffusion): def __init__(self, reference_stage_config, pose_guider_config, target_key, reference_key, skeleton_key, *args, **kwargs): super().__init__(*args, **kwargs) self.reference_model = instantiate_from_config(reference_stage_config) self.pose_model = instantiate_from_config(pose_guider_config) self.target_key = target_key self.reference_key = reference_key self.skeleton_key = skeleton_key self.animate_scales = [1.0] * 13 @torch.no_grad() def get_input(self, batch, k, bs=None, *args, **kwargs): x, _ = super().get_input(batch, self.target_key, *args, **kwargs) ref_x, ref_c = super().get_input(batch, self.reference_key, *args, **kwargs) reference = batch[self.reference_key] skeleton = batch[self.skeleton_key] if bs is not None: reference = reference[:bs] skeleton = skeleton[:bs] reference = reference.to(self.device) skeleton = skeleton.to(self.device) reference = einops.rearrange(reference, 'b h w c -> b c h w') skeleton = einops.rearrange(skeleton, 'b h w c -> b c h w') reference = reference.to(memory_format=torch.contiguous_format).float() skeleton = skeleton.to(memory_format=torch.contiguous_format).float() return x, dict(c_crossattn=[ref_c], c_concat=None, img_skeleton=skeleton, img_reference=reference, latent_reference=ref_x) def apply_model(self, x_noisy, t, cond, *args, **kwargs): assert isinstance(cond, dict) diffusion_model = self.model.diffusion_model cond_img = cond['c_crossattn'] refs = self.reference_model(x=cond['latent_reference'], timesteps=t, context=cond_img) pose = self.pose_model(x=cond['img_skeleton']) # control = [c * scale for c, scale in zip(control, self.control_scales)] eps = diffusion_model(x=x_noisy + pose, timesteps=t, context=cond_img, refs=refs) return eps @torch.no_grad() def get_unconditional_conditioning(self, N): return self.get_learned_conditioning([""] * N) @torch.no_grad() def log_images(self, batch, N=4, n_row=2, sample=False, ddim_steps=50, ddim_eta=0.0, return_keys=None, quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=False, unconditional_guidance_scale=9.0, unconditional_guidance_label=None, use_ema_scope=True, **kwargs): use_ddim = ddim_steps is not None log = dict() z, cond = self.get_input(batch, self.target_key, bs=N) N = min(z.shape[0], N) n_row = min(z.shape[0], n_row) log["reconstruction"] = self.decode_first_stage(z) log["reference"] = cond["img_reference"] log["skeleton"] = cond["img_skeleton"] * 2.0 - 1.0 if plot_diffusion_rows: # get diffusion row diffusion_row = list() z_start = z[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), '1 -> b', b=n_row) t = t.to(self.device).long() noise = torch.randn_like(z_start) z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise) diffusion_row.append(self.decode_first_stage(z_noisy)) diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w') diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w') diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0]) log["diffusion_row"] = diffusion_grid if sample: # get denoise row # cond={"c_concat": [c_cat], "c_crossattn": [c_txt], "c_reference": [ref_x], "c_skeleton": [c_skt]} samples, z_denoise_row = self.sample_log(cond=cond, batch_size=N, ddim=use_ddim, ddim_steps=ddim_steps, eta=ddim_eta) x_samples = self.decode_first_stage(samples) log["samples"] = x_samples if plot_denoise_rows: denoise_grid = self._get_denoise_row_from_list(z_denoise_row) log["denoise_row"] = denoise_grid if unconditional_guidance_scale > 1.0: samples_cfg, _ = self.sample_log(cond=cond, batch_size=N, ddim=use_ddim, ddim_steps=ddim_steps, eta=ddim_eta, unconditional_guidance_scale=unconditional_guidance_scale, ) x_samples_cfg = self.decode_first_stage(samples_cfg) log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg return log @torch.no_grad() def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):
ddim_sampler = DDIMSampler(self)
11
2023-12-16 03:31:33+00:00
24k
yasserben/CLOUDS
train_net.py
[ { "identifier": "add_maskformer2_config", "path": "clouds/config.py", "snippet": "def add_maskformer2_config(cfg):\n \"\"\"\n Add config for MASK_FORMER.\n \"\"\"\n # NOTE: configs from original maskformer\n # data config\n # select the dataset mapper\n cfg.INPUT.DATASET_MAPPER_NAME = \"mask_former_semantic\"\n # Color augmentation\n cfg.INPUT.COLOR_AUG_SSD = False\n # We retry random cropping until no single category in semantic segmentation GT occupies more\n # than `SINGLE_CATEGORY_MAX_AREA` part of the crop.\n cfg.INPUT.CROP.SINGLE_CATEGORY_MAX_AREA = 1.0\n # Pad image and segmentation GT in dataset mapper.\n cfg.INPUT.SIZE_DIVISIBILITY = -1\n\n # solver config\n # weight decay on embedding\n cfg.SOLVER.WEIGHT_DECAY_EMBED = 0.0\n # optimizer\n cfg.SOLVER.OPTIMIZER = \"ADAMW\"\n cfg.SOLVER.BACKBONE_MULTIPLIER = 0.1\n\n # mask_former model config\n cfg.MODEL.MASK_FORMER = CN()\n\n # loss\n cfg.MODEL.MASK_FORMER.DEEP_SUPERVISION = True\n cfg.MODEL.MASK_FORMER.NO_OBJECT_WEIGHT = 0.1\n cfg.MODEL.MASK_FORMER.CLASS_WEIGHT = 1.0\n cfg.MODEL.MASK_FORMER.DICE_WEIGHT = 1.0\n cfg.MODEL.MASK_FORMER.MASK_WEIGHT = 20.0\n\n # transformer config\n cfg.MODEL.MASK_FORMER.NHEADS = 8\n cfg.MODEL.MASK_FORMER.DROPOUT = 0.1\n cfg.MODEL.MASK_FORMER.DIM_FEEDFORWARD = 2048\n cfg.MODEL.MASK_FORMER.ENC_LAYERS = 0\n cfg.MODEL.MASK_FORMER.DEC_LAYERS = 6\n cfg.MODEL.MASK_FORMER.PRE_NORM = False\n\n cfg.MODEL.MASK_FORMER.HIDDEN_DIM = 256\n cfg.MODEL.MASK_FORMER.NUM_OBJECT_QUERIES = 100\n\n cfg.MODEL.MASK_FORMER.TRANSFORMER_IN_FEATURE = \"res5\"\n cfg.MODEL.MASK_FORMER.ENFORCE_INPUT_PROJ = False\n\n # mask_former inference config\n cfg.MODEL.MASK_FORMER.TEST = CN()\n cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON = True\n cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON = False\n cfg.MODEL.MASK_FORMER.TEST.PANOPTIC_ON = False\n cfg.MODEL.MASK_FORMER.TEST.OBJECT_MASK_THRESHOLD = 0.0\n cfg.MODEL.MASK_FORMER.TEST.OVERLAP_THRESHOLD = 0.0\n cfg.MODEL.MASK_FORMER.TEST.SEM_SEG_POSTPROCESSING_BEFORE_INFERENCE = False\n\n # Sometimes `backbone.size_divisibility` is set to 0 for some backbone (e.g. ResNet)\n # you can use this config to override\n cfg.MODEL.MASK_FORMER.SIZE_DIVISIBILITY = 32\n\n # pixel decoder config\n cfg.MODEL.SEM_SEG_HEAD.MASK_DIM = 256\n # adding transformer in pixel decoder\n cfg.MODEL.SEM_SEG_HEAD.TRANSFORMER_ENC_LAYERS = 0\n # pixel decoder\n cfg.MODEL.SEM_SEG_HEAD.PIXEL_DECODER_NAME = \"BasePixelDecoder\"\n\n # swin transformer backbone\n cfg.MODEL.SWIN = CN()\n cfg.MODEL.SWIN.PRETRAIN_IMG_SIZE = 224\n cfg.MODEL.SWIN.PATCH_SIZE = 4\n cfg.MODEL.SWIN.EMBED_DIM = 96\n cfg.MODEL.SWIN.DEPTHS = [2, 2, 6, 2]\n cfg.MODEL.SWIN.NUM_HEADS = [3, 6, 12, 24]\n cfg.MODEL.SWIN.WINDOW_SIZE = 7\n cfg.MODEL.SWIN.MLP_RATIO = 4.0\n cfg.MODEL.SWIN.QKV_BIAS = True\n cfg.MODEL.SWIN.QK_SCALE = None\n cfg.MODEL.SWIN.DROP_RATE = 0.0\n cfg.MODEL.SWIN.ATTN_DROP_RATE = 0.0\n cfg.MODEL.SWIN.DROP_PATH_RATE = 0.3\n cfg.MODEL.SWIN.APE = False\n cfg.MODEL.SWIN.PATCH_NORM = True\n cfg.MODEL.SWIN.OUT_FEATURES = [\"res2\", \"res3\", \"res4\", \"res5\"]\n cfg.MODEL.SWIN.USE_CHECKPOINT = False\n\n # NOTE: maskformer2 extra configs\n # transformer module\n cfg.MODEL.MASK_FORMER.TRANSFORMER_DECODER_NAME = (\n \"MultiScaleMaskedTransformerDecoder\"\n )\n\n # LSJ aug\n cfg.INPUT.IMAGE_SIZE = 1024\n cfg.INPUT.MIN_SCALE = 0.1\n cfg.INPUT.MAX_SCALE = 2.0\n\n # MSDeformAttn encoder configs\n cfg.MODEL.SEM_SEG_HEAD.DEFORMABLE_TRANSFORMER_ENCODER_IN_FEATURES = [\n \"res3\",\n \"res4\",\n \"res5\",\n ]\n cfg.MODEL.SEM_SEG_HEAD.DEFORMABLE_TRANSFORMER_ENCODER_N_POINTS = 4\n cfg.MODEL.SEM_SEG_HEAD.DEFORMABLE_TRANSFORMER_ENCODER_N_HEADS = 8\n\n # point loss configs\n # Number of points sampled during training for a mask point head.\n cfg.MODEL.MASK_FORMER.TRAIN_NUM_POINTS = 112 * 112\n # Oversampling parameter for PointRend point sampling during training. Parameter `k` in the\n # original paper.\n cfg.MODEL.MASK_FORMER.OVERSAMPLE_RATIO = 3.0\n # Importance sampling parameter for PointRend point sampling during training. Parametr `beta` in\n # the original paper.\n cfg.MODEL.MASK_FORMER.IMPORTANCE_SAMPLE_RATIO = 0.75\n\n # Resizing disabled for Synthia\n cfg.INPUT.RESIZE = CN()\n cfg.INPUT.RESIZE.ENABLED = True\n cfg.INPUT.RESIZE.SIZE_TRAIN = (1280, 720)\n\n # Saving Pseudo Labels during test time\n cfg.MODEL.SAVE_PSEUDO_LABELS = False\n\n # for the Dataset repeat factor\n # cfg.DATASETS.TRAIN_REPEAT_FACTOR = [(\"sd_v99\",5.0), (\"cityscapes_train\",1.0)]" }, { "identifier": "add_clouds_config", "path": "clouds/config.py", "snippet": "def add_clouds_config(cfg):\n # CLOUDS model config\n cfg.MODEL.CLOUDS = CN()\n cfg.MODEL.CLOUDS.CLIP_MODEL_NAME = \"convnext_large_d_320\"\n cfg.MODEL.CLOUDS.CLIP_PRETRAINED_WEIGHTS = \"laion2b_s29b_b131k_ft_soup\"\n cfg.MODEL.CLOUDS.EMBED_DIM = 768\n cfg.MODEL.CLOUDS.GEOMETRIC_ENSEMBLE_ALPHA = 0.4\n cfg.MODEL.CLOUDS.GEOMETRIC_ENSEMBLE_BETA = 0.8\n cfg.MODEL.CLOUDS.ENSEMBLE_ON_VALID_MASK = False\n cfg.MODEL.CLOUDS.GEOMETRIC_ENSEMBLE = False\n cfg.MODEL.CLOUDS.GEOMETRIC_ENSEMBLE_EMA = False\n cfg.MODEL.CLOUDS.SAM = CN()\n cfg.MODEL.CLOUDS.SAM.ENABLED = False\n cfg.MODEL.CLOUDS.SAM.MOBILE = True\n cfg.MODEL.CLOUDS.SAM.MINIBATCH = False\n cfg.MODEL.CLOUDS.SAM.SIZE_THRESHOLD = 5000\n cfg.MODEL.CLOUDS.SAM.EROSION = False\n cfg.MODEL.CLOUDS.SAM.EROSION_SIZE = 3\n cfg.MODEL.CLOUDS.SAM.NUM_POINTS = 5\n cfg.MODEL.CLOUDS.SAM.SELECTION_MODE = \"random\"\n cfg.MODEL.CLOUDS.SAM.RM_INTERSECTION = True\n cfg.MODEL.CLOUDS.SAM.REFINEMENT = False\n cfg.MODEL.CLOUDS.SAM.ALPHA_EMA = 0.999\n cfg.MODEL.CLOUDS.OVERWRITING = True\n cfg.MODEL.CLOUDS.ITERATION_UPDATE = 100" }, { "identifier": "add_wandb_config", "path": "clouds/config.py", "snippet": "def add_wandb_config(cfg):\n # Wandb\n cfg.WANDB = CN()\n cfg.WANDB.PROJECT = \"clouds\"\n cfg.WANDB.NAME = None\n # use flash attention\n cfg.MODEL.FLASH = False" }, { "identifier": "add_prerocessing_training_set_config", "path": "clouds/config.py", "snippet": "def add_prerocessing_training_set_config(cfg):\n cfg.INPUT.FLIP = True\n cfg.INPUT.INITIAL_HEIGHT = 1052\n cfg.INPUT.INITIAL_WIDTH = 1914\n cfg.INPUT.RESIZE_HEIGHT = 720\n cfg.INPUT.RESIZE_WIDTH = 1280\n cfg.INPUT.PL_THRESHOLD = 0.0\n\n cfg.DATASETS.SOURCE_FACTOR = 1.0\n cfg.DATASETS.TARGET_FACTOR = 1.0" }, { "identifier": "add_repeat_factors", "path": "clouds/config.py", "snippet": "def add_repeat_factors(cfg):\n # for the Dataset repeat factor\n if (\n len(cfg.DATASETS.TRAIN) == 2\n and cfg.DATALOADER.SAMPLER_TRAIN == \"WeightedTrainingSampler\"\n ):\n if \"sd\" in cfg.DATASETS.TRAIN[0]:\n target_dataset = cfg.DATASETS.TRAIN[0]\n source_dataset = cfg.DATASETS.TRAIN[1]\n else:\n target_dataset = cfg.DATASETS.TRAIN[1]\n source_dataset = cfg.DATASETS.TRAIN[0]\n\n TRAIN_REPEAT_FACTOR = [\n (target_dataset, cfg.DATASETS.TARGET_FACTOR),\n (source_dataset, cfg.DATASETS.SOURCE_FACTOR),\n ]\n cfg.DATASETS.TRAIN_REPEAT_FACTOR = TRAIN_REPEAT_FACTOR\n return cfg\n else:\n return cfg" }, { "identifier": "MapperTrain", "path": "clouds/data/dataset_mappers/mapper_train.py", "snippet": "class MapperTrain:\n \"\"\"\n A callable which takes a dataset dict in Detectron2 Dataset format,\n and map it into a format used by MaskFormer for semantic segmentation.\n\n The callable currently does the following:\n\n 1. Read the image from \"file_name\"\n 2. Applies geometric transforms to the image and annotation\n 3. Find and applies suitable cropping to the image and annotation\n 4. Prepare image and annotation to Tensors\n \"\"\"\n\n @configurable\n def __init__(\n self,\n is_train=True,\n *,\n augmentations_src,\n augmentations_sd,\n augmentations_photo,\n image_format,\n ignore_label,\n size_divisibility,\n ):\n \"\"\"\n NOTE: this interface is experimental.\n Args:\n is_train: for training or inference\n augmentations: a list of augmentations or deterministic transforms to apply\n image_format: an image format supported by :func:`detection_utils.read_image`.\n ignore_label: the label that is ignored to evaluation\n size_divisibility: pad image size to be divisible by this value\n \"\"\"\n self.is_train = is_train\n self.tfm_gens_src = augmentations_src\n self.tfm_gens_sd = augmentations_sd\n self.tfm_gens_photometric = augmentations_photo\n self.img_format = image_format\n self.ignore_label = ignore_label\n self.size_divisibility = size_divisibility\n\n logger = logging.getLogger(__name__)\n mode = \"training\" if is_train else \"inference\"\n logger.info(\n f\"[{self.__class__.__name__}] Augmentations used in {mode}: {augmentations_src}\"\n )\n\n @classmethod\n def from_config(cls, cfg, is_train=True):\n augs_src = []\n augs_sd = []\n augs_photometric = []\n # Build augmentation\n if cfg.INPUT.RESIZE.ENABLED:\n augs_src.append(\n T.ResizeScale(\n min_scale=0.5,\n max_scale=2.0,\n target_height=cfg.INPUT.INITIAL_HEIGHT,\n target_width=cfg.INPUT.INITIAL_WIDTH,\n interp=Image.BILINEAR,\n )\n )\n if cfg.INPUT.CROP.ENABLED:\n augs_src.append(\n T.FixedSizeCrop(\n (768, 768),\n pad=True,\n seg_pad_value=255,\n pad_value=0,\n )\n )\n if cfg.INPUT.COLOR_AUG_SSD:\n augs_src.append(ColorAugSSDTransform(img_format=cfg.INPUT.FORMAT))\n augs_photometric.append(ColorAugSSDTransform(img_format=cfg.INPUT.FORMAT))\n if cfg.INPUT.FLIP:\n augs_src.append(T.RandomFlip())\n augs_sd.append(T.RandomFlip())\n\n # Assume always applies to the training set.\n dataset_names = cfg.DATASETS.TRAIN\n meta = MetadataCatalog.get(dataset_names[0])\n ignore_label = meta.ignore_label\n\n ret = {\n \"is_train\": is_train,\n \"augmentations_src\": augs_src,\n \"augmentations_sd\": augs_sd,\n \"augmentations_photo\": augs_photometric,\n \"image_format\": cfg.INPUT.FORMAT,\n \"ignore_label\": ignore_label,\n \"size_divisibility\": cfg.INPUT.SIZE_DIVISIBILITY,\n }\n return ret\n\n def __call__(self, dataset_dict):\n \"\"\"\n Args:\n dataset_dict (dict): Metadata of one image, in Detectron2 Dataset format.\n\n Returns:\n dict: a format that builtin models in detectron2 accept\n \"\"\"\n assert (\n self.is_train\n ), \"MaskFormerSemanticDatasetMapper should only be used for training!\"\n\n dataset_dict = copy.deepcopy(dataset_dict) # it will be modified by code below\n image = utils.read_image(dataset_dict[\"file_name\"], format=self.img_format)\n utils.check_image_size(dataset_dict, image)\n\n if \"sem_seg_file_name\" in dataset_dict:\n # PyTorch transformation not implemented for uint16, so converting it to double first\n sem_seg_gt = utils.read_image(dataset_dict.pop(\"sem_seg_file_name\")).astype(\n \"double\"\n )\n else:\n sem_seg_gt = np.full(\n (dataset_dict[\"height\"], dataset_dict[\"width\"]), self.ignore_label\n ).astype(\"double\")\n\n if sem_seg_gt is None:\n raise ValueError(\n \"Cannot find 'sem_seg_file_name' for semantic segmentation dataset {}.\".format(\n dataset_dict[\"file_name\"]\n )\n )\n\n aug_input = T.AugInput(image, sem_seg=sem_seg_gt)\n if not (\"generated\" in str(dataset_dict[\"image_id\"])):\n aug_input, transforms = T.apply_transform_gens(self.tfm_gens_src, aug_input)\n image = aug_input.image\n sem_seg_gt = aug_input.sem_seg\n else:\n aug_input, transforms = T.apply_transform_gens(self.tfm_gens_sd, aug_input)\n image = aug_input.image\n sem_seg_gt = aug_input.sem_seg\n aug_input_photo, transforms = T.apply_transform_gens(\n self.tfm_gens_photometric, aug_input\n )\n image_aug = aug_input_photo.image\n\n # Pad image and segmentation label here!\n image = torch.as_tensor(np.ascontiguousarray(image.transpose(2, 0, 1)))\n if \"generated\" in str(dataset_dict[\"image_id\"]):\n image_aug = torch.as_tensor(\n np.ascontiguousarray(image_aug.transpose(2, 0, 1))\n )\n if sem_seg_gt is not None:\n sem_seg_gt = torch.as_tensor(sem_seg_gt.astype(\"long\"))\n\n if self.size_divisibility > 0:\n image_size = (image.shape[-2], image.shape[-1])\n padding_size = [\n 0,\n self.size_divisibility - image_size[1],\n 0,\n self.size_divisibility - image_size[0],\n ]\n image = F.pad(image, padding_size, value=128).contiguous()\n if \"generated\" in str(dataset_dict[\"image_id\"]):\n image_aug = F.pad(image_aug, padding_size, value=128).contiguous()\n if sem_seg_gt is not None:\n sem_seg_gt = F.pad(\n sem_seg_gt, padding_size, value=self.ignore_label\n ).contiguous()\n\n image_shape = (image.shape[-2], image.shape[-1]) # h, w\n\n # Pytorch's dataloader is efficient on torch.Tensor due to shared-memory,\n # but not efficient on large generic data structures due to the use of pickle & mp.Queue.\n # Therefore it's important to use torch.Tensor.\n dataset_dict[\"image\"] = image\n if \"generated\" in str(dataset_dict[\"image_id\"]):\n dataset_dict[\"image_aug\"] = image_aug\n\n if sem_seg_gt is not None:\n dataset_dict[\"sem_seg\"] = sem_seg_gt.long()\n\n if \"annotations\" in dataset_dict:\n raise ValueError(\n \"Semantic segmentation dataset should not have 'annotations'.\"\n )\n\n # Prepare per-category binary masks\n if sem_seg_gt is not None:\n sem_seg_gt = sem_seg_gt.numpy()\n instances = Instances(image_shape)\n classes = np.unique(sem_seg_gt)\n # remove ignored region\n classes = classes[classes != self.ignore_label]\n instances.gt_classes = torch.tensor(classes, dtype=torch.int64)\n\n masks = []\n for class_id in classes:\n masks.append(sem_seg_gt == class_id)\n\n if len(masks) == 0:\n # Some image does not have annotation (all ignored)\n instances.gt_masks = torch.zeros(\n (0, sem_seg_gt.shape[-2], sem_seg_gt.shape[-1])\n )\n else:\n masks = BitMasks(\n torch.stack(\n [\n torch.from_numpy(np.ascontiguousarray(x.copy()))\n for x in masks\n ]\n )\n )\n instances.gt_masks = masks.tensor\n\n dataset_dict[\"instances\"] = instances\n\n return dataset_dict" }, { "identifier": "MapperTest", "path": "clouds/data/dataset_mappers/mapper_test.py", "snippet": "class MapperTest:\n \"\"\"\n A callable which takes a dataset dict in Detectron2 Dataset format,\n and map it into a format used by the model.\n\n This is the default callable to be used to map your dataset dict into training data.\n You may need to follow it to implement your own one for customized logic,\n such as a different way to read or transform images.\n See :doc:`/tutorials/data_loading` for details.\n\n The callable currently does the following:\n\n 1. Read the image from \"file_name\"\n 2. Applies cropping/geometric transforms to the image and annotations\n 3. Prepare data and annotations to Tensor and :class:`Instances`\n \"\"\"\n\n @configurable\n def __init__(\n self,\n is_train: bool,\n *,\n augmentations: List[Union[T.Augmentation, T.Transform]],\n image_format: str,\n\n ):\n \"\"\"\n NOTE: this interface is experimental.\n\n Args:\n is_train: whether it's used in training or inference\n augmentations: a list of augmentations or deterministic transforms to apply\n image_format: an image format supported by :func:`detection_utils.read_image`.\n \"\"\"\n # if recompute_boxes:\n # assert use_instance_mask, \"recompute_boxes requires instance masks\"\n # fmt: off\n self.is_train = is_train\n self.augmentations = augmentations\n self.image_format = image_format\n logger = logging.getLogger(__name__)\n mode = \"training\" if is_train else \"inference\"\n logger.info(f\"[DatasetMapper] Augmentations used in {mode}: {augmentations}\")\n\n @classmethod\n def from_config(cls, cfg, is_train: bool = True):\n augs = [T.ResizeShortestEdge(short_edge_length=[1024], sample_style=\"choice\")]\n\n ret = {\n \"is_train\": is_train,\n \"augmentations\": augs,\n \"image_format\": cfg.INPUT.FORMAT,\n }\n\n\n return ret\n\n def __call__(self, dataset_dict):\n \"\"\"\n Args:\n dataset_dict (dict): Metadata of one image, in Detectron2 Dataset format.\n\n Returns:\n dict: a format that builtin models in detectron2 accept\n \"\"\"\n dataset_dict = copy.deepcopy(dataset_dict) # it will be modified by code below\n # USER: Write your own image loading if it's not from a file\n image = utils.read_image(dataset_dict[\"file_name\"], format=self.image_format)\n utils.check_image_size(dataset_dict, image)\n\n # USER: Remove if you don't do semantic/panoptic segmentation.\n if \"sem_seg_file_name\" in dataset_dict:\n sem_seg_gt = utils.read_image(dataset_dict.pop(\"sem_seg_file_name\"), \"L\").squeeze(2)\n else:\n sem_seg_gt = None\n\n aug_input = T.AugInput(image, sem_seg=sem_seg_gt)\n aug_input, transformation = T.apply_transform_gens(self.augmentations, aug_input)\n image, sem_seg_gt = aug_input.image, aug_input.sem_seg\n\n # Pytorch's dataloader is efficient on torch.Tensor due to shared-memory,\n # but not efficient on large generic data structures due to the use of pickle & mp.Queue.\n # Therefore it's important to use torch.Tensor.\n dataset_dict[\"image\"] = torch.as_tensor(np.ascontiguousarray(image.transpose(2, 0, 1)))\n\n if sem_seg_gt is not None:\n dataset_dict[\"sem_seg\"] = torch.as_tensor(sem_seg_gt.astype(\"long\"))\n\n dataset_dict['height'] = dataset_dict[\"image\"].shape[1]\n dataset_dict['width'] = dataset_dict[\"image\"].shape[2]\n if not self.is_train:\n # USER: Modify this if you want to keep them for some reason.\n dataset_dict.pop(\"sem_seg_file_name\", None)\n return dataset_dict\n\n return dataset_dict" }, { "identifier": "CityscapesSemSegEvaluator", "path": "clouds/evaluation/cityscapes_evaluation.py", "snippet": "class CityscapesSemSegEvaluator(CityscapesEvaluator):\n \"\"\"\n Evaluate semantic segmentation results on cityscapes dataset using cityscapes API.\n\n Note:\n * It does not work in multi-machine distributed training.\n * It contains a synchronization, therefore has to be used on all ranks.\n * Only the main process runs evaluation.\n \"\"\"\n\n def process(self, inputs, outputs):\n from cityscapesscripts.helpers.labels import trainId2label\n for input, output in zip(inputs, outputs):\n file_name = input[\"file_name\"]\n basename = os.path.splitext(os.path.basename(file_name))[0]\n pred_filename = os.path.join(self._temp_dir, basename + \"_pred.png\")\n\n output = output[\"sem_seg\"].argmax(dim=0).to(self._cpu_device).numpy()\n pred = 255 * np.ones(output.shape, dtype=np.uint8)\n for train_id, label in trainId2label.items():\n if label.ignoreInEval:\n continue\n pred[output == train_id] = label.id\n Image.fromarray(pred).save(pred_filename)\n\n\n def evaluate(self):\n comm.synchronize()\n if comm.get_rank() > 0:\n return\n # Load the Cityscapes eval script *after* setting the required env var,\n # since the script reads CITYSCAPES_DATASET into global variables at load time.\n import cityscapesscripts.evaluation.evalPixelLevelSemanticLabeling as cityscapes_eval\n\n self._logger.info(\"Evaluating results under {} ...\".format(self._temp_dir))\n\n # set some global states in cityscapes evaluation API, before evaluating\n cityscapes_eval.args.predictionPath = os.path.abspath(self._temp_dir)\n cityscapes_eval.args.predictionWalk = None\n cityscapes_eval.args.JSONOutput = False\n cityscapes_eval.args.colorized = False\n\n # These lines are adopted from\n # https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/evaluation/evalPixelLevelSemanticLabeling.py # noqa\n gt_dir = PathManager.get_local_path(self._metadata.gt_dir)\n groundTruthImgList = glob.glob(\n os.path.join(gt_dir, \"*\", \"*_gtFine_labelIds.png\")\n )\n assert len(\n groundTruthImgList\n ), \"Cannot find any ground truth images to use for evaluation. Searched for: {}\".format(\n cityscapes_eval.args.groundTruthSearch\n )\n predictionImgList = []\n for gt in groundTruthImgList:\n predictionImgList.append(\n cityscapes_eval.getPrediction(cityscapes_eval.args, gt)\n )\n results = cityscapes_eval.evaluateImgLists(\n predictionImgList, groundTruthImgList, cityscapes_eval.args\n )\n ret = OrderedDict()\n ret[\"sem_seg\"] = {\n \"mIoU\": 100.0 * results[\"averageScoreClasses\"],\n \"IoU.road\": 100.0 * results[\"classScores\"][\"road\"],\n \"IoU.sidewalk\": 100.0 * results[\"classScores\"][\"sidewalk\"],\n \"IoU.building\": 100.0 * results[\"classScores\"][\"building\"],\n \"IoU.wall\": 100.0 * results[\"classScores\"][\"wall\"],\n \"IoU.fence\": 100.0 * results[\"classScores\"][\"fence\"],\n \"IoU.pole\": 100.0 * results[\"classScores\"][\"pole\"],\n \"IoU.traffic light\": 100.0 * results[\"classScores\"][\"traffic light\"],\n \"IoU.traffic sign\": 100.0 * results[\"classScores\"][\"traffic sign\"],\n \"IoU.vegetation\": 100.0 * results[\"classScores\"][\"vegetation\"],\n \"IoU.terrain\": 100.0 * results[\"classScores\"][\"terrain\"],\n \"IoU.sky\": 100.0 * results[\"classScores\"][\"sky\"],\n \"IoU.person\": 100.0 * results[\"classScores\"][\"person\"],\n \"IoU.rider\": 100.0 * results[\"classScores\"][\"rider\"],\n \"IoU.car\": 100.0 * results[\"classScores\"][\"car\"],\n \"IoU.truck\": 100.0 * results[\"classScores\"][\"truck\"],\n \"IoU.bus\": 100.0 * results[\"classScores\"][\"bus\"],\n \"IoU.train\": 100.0 * results[\"classScores\"][\"train\"],\n \"IoU.motorcycle\": 100.0 * results[\"classScores\"][\"motorcycle\"],\n \"IoU.bicycle\": 100.0 * results[\"classScores\"][\"bicycle\"],\n }\n if not self._save_pl:\n self._working_dir.cleanup()\n return ret" }, { "identifier": "ClassicalSemSegEvaluator", "path": "clouds/evaluation/semantic_evaluation.py", "snippet": "class ClassicalSemSegEvaluator(DatasetEvaluator):\n \"\"\"\n Evaluate semantic segmentation metrics.\n \"\"\"\n\n def __init__(\n self,\n dataset_name,\n distributed=True,\n output_dir=None,\n *,\n sem_seg_loading_fn=load_image_into_numpy_array,\n num_classes=None,\n ignore_label=None,\n save_pl=False,\n ):\n \"\"\"\n Args:\n dataset_name (str): name of the dataset to be evaluated.\n distributed (bool): if True, will collect results from all ranks for evaluation.\n Otherwise, will evaluate the results in the current process.\n output_dir (str): an output directory to dump results.\n sem_seg_loading_fn: function to read sem seg file and load into numpy array.\n Default provided, but projects can customize.\n num_classes, ignore_label: deprecated argument\n \"\"\"\n self._logger = logging.getLogger(__name__)\n if num_classes is not None:\n self._logger.warn(\n \"SemSegEvaluator(num_classes) is deprecated! It should be obtained from metadata.\"\n )\n if ignore_label is not None:\n self._logger.warn(\n \"SemSegEvaluator(ignore_label) is deprecated! It should be obtained from metadata.\"\n )\n self._dataset_name = dataset_name\n self._distributed = distributed\n self._output_dir = output_dir\n\n self._cpu_device = torch.device(\"cpu\")\n\n self.input_file_to_gt_file = {\n dataset_record[\"file_name\"]: dataset_record[\"sem_seg_file_name\"]\n for dataset_record in DatasetCatalog.get(dataset_name)\n }\n\n meta = MetadataCatalog.get(dataset_name)\n # Dict that maps contiguous training ids to COCO category ids\n try:\n c2d = meta.stuff_dataset_id_to_contiguous_id\n self._contiguous_id_to_dataset_id = {v: k for k, v in c2d.items()}\n except AttributeError:\n self._contiguous_id_to_dataset_id = None\n self._class_names = meta.stuff_classes\n self.sem_seg_loading_fn = sem_seg_loading_fn\n self._num_classes = len(meta.stuff_classes)\n if num_classes is not None:\n assert (\n self._num_classes == num_classes\n ), f\"{self._num_classes} != {num_classes}\"\n self._ignore_label = (\n ignore_label if ignore_label is not None else meta.ignore_label\n )\n\n # This is because cv2.erode did not work for int datatype. Only works for uint8.\n self._compute_boundary_iou = True\n if not _CV2_IMPORTED:\n self._compute_boundary_iou = False\n self._logger.warn(\n \"\"\"Boundary IoU calculation requires OpenCV. B-IoU metrics are\n not going to be computed because OpenCV is not available to import.\"\"\"\n )\n if self._num_classes >= np.iinfo(np.uint8).max:\n self._compute_boundary_iou = False\n self._logger.warn(\n f\"\"\"SemSegEvaluator(num_classes) is more than supported value for Boundary IoU calculation!\n B-IoU metrics are not going to be computed. Max allowed value (exclusive)\n for num_classes for calculating Boundary IoU is {np.iinfo(np.uint8).max}.\n The number of classes of dataset {self._dataset_name} is {self._num_classes}\"\"\"\n )\n self._save_pl = save_pl\n\n def reset(self):\n self._conf_matrix = np.zeros(\n (self._num_classes + 1, self._num_classes + 1), dtype=np.int64\n )\n self._b_conf_matrix = np.zeros(\n (self._num_classes + 1, self._num_classes + 1), dtype=np.int64\n )\n self._predictions = []\n\n def process(self, inputs, outputs):\n \"\"\"\n Args:\n inputs: the inputs to a model.\n It is a list of dicts. Each dict corresponds to an image and\n contains keys like \"height\", \"width\", \"file_name\".\n outputs: the outputs of a model. It is either list of semantic segmentation predictions\n (Tensor [H, W]) or list of dicts with key \"sem_seg\" that contains semantic\n segmentation prediction in the same format.\n \"\"\"\n for input, output in zip(inputs, outputs):\n output = output[\"sem_seg\"].argmax(dim=0).to(self._cpu_device)\n pred = np.array(output, dtype=int)\n gt = input[\"sem_seg\"].numpy()\n\n gt[gt == self._ignore_label] = self._num_classes\n\n self._conf_matrix += np.bincount(\n (self._num_classes + 1) * pred.reshape(-1) + gt.reshape(-1),\n minlength=self._conf_matrix.size,\n ).reshape(self._conf_matrix.shape)\n\n if self._compute_boundary_iou:\n b_gt = self._mask_to_boundary(gt.astype(np.uint8))\n b_pred = self._mask_to_boundary(pred.astype(np.uint8))\n\n self._b_conf_matrix += np.bincount(\n (self._num_classes + 1) * b_pred.reshape(-1) + b_gt.reshape(-1),\n minlength=self._conf_matrix.size,\n ).reshape(self._conf_matrix.shape)\n\n if self._save_pl:\n self._predictions.extend(\n [dict(file_name=input[\"file_name\"], pred=pred)]\n )\n else:\n self._predictions.extend(\n self.encode_json_sem_seg(pred, input[\"file_name\"])\n )\n\n def evaluate(self):\n \"\"\"\n Evaluates standard semantic segmentation metrics (http://cocodataset.org/#stuff-eval):\n\n * Mean intersection-over-union averaged across classes (mIoU)\n * Frequency Weighted IoU (fwIoU)\n * Mean pixel accuracy averaged across classes (mACC)\n * Pixel Accuracy (pACC)\n \"\"\"\n if self._distributed:\n synchronize()\n conf_matrix_list = all_gather(self._conf_matrix)\n b_conf_matrix_list = all_gather(self._b_conf_matrix)\n self._predictions = all_gather(self._predictions)\n self._predictions = list(itertools.chain(*self._predictions))\n if not is_main_process():\n return\n\n self._conf_matrix = np.zeros_like(self._conf_matrix)\n for conf_matrix in conf_matrix_list:\n self._conf_matrix += conf_matrix\n\n self._b_conf_matrix = np.zeros_like(self._b_conf_matrix)\n for b_conf_matrix in b_conf_matrix_list:\n self._b_conf_matrix += b_conf_matrix\n\n if self._output_dir:\n first_elem = self._predictions[0]\n if \"bdd\" in first_elem[\"file_name\"]:\n self._output_dir = os.path.join(self._output_dir, \"bdd_eval_pl\")\n elif \"mapillary\" in first_elem[\"file_name\"]:\n self._output_dir = os.path.join(self._output_dir, \"mapillary_eval_pl\")\n PathManager.mkdirs(self._output_dir)\n if self._save_pl:\n # A function that will iterate over the list of dictionnaries and write the corresponding image\n # in the output directory\n def write_image_from_dict(dict):\n filename = os.path.join(\n self._output_dir,\n dict[\"file_name\"].split(\"/\")[-1].split(\".\")[0] + \"_pred.png\",\n )\n pred = dict[\"pred\"]\n pred = get_rgb_from_semantic_map_maxed(pred)\n # pred = Image.fromarray(pred)\n pred.save(filename)\n\n # We apply the function to the list of dictionnaries\n list(map(write_image_from_dict, self._predictions))\n\n else:\n file_path = os.path.join(self._output_dir, \"sem_seg_predictions.json\")\n with PathManager.open(file_path, \"w\") as f:\n f.write(json.dumps(self._predictions))\n\n acc = np.full(self._num_classes, np.nan, dtype=float)\n iou = np.full(self._num_classes, np.nan, dtype=float)\n tp = self._conf_matrix.diagonal()[:-1].astype(float)\n pos_gt = np.sum(self._conf_matrix[:-1, :-1], axis=0).astype(float)\n class_weights = pos_gt / np.sum(pos_gt)\n pos_pred = np.sum(self._conf_matrix[:-1, :-1], axis=1).astype(float)\n acc_valid = pos_gt > 0\n acc[acc_valid] = tp[acc_valid] / pos_gt[acc_valid]\n union = pos_gt + pos_pred - tp\n iou_valid = np.logical_and(acc_valid, union > 0)\n iou[iou_valid] = tp[iou_valid] / union[iou_valid]\n macc = np.sum(acc[acc_valid]) / np.sum(acc_valid)\n miou = np.sum(iou[iou_valid]) / np.sum(iou_valid)\n fiou = np.sum(iou[iou_valid] * class_weights[iou_valid])\n pacc = np.sum(tp) / np.sum(pos_gt)\n\n if self._compute_boundary_iou:\n b_iou = np.full(self._num_classes, np.nan, dtype=float)\n b_tp = self._b_conf_matrix.diagonal()[:-1].astype(float)\n b_pos_gt = np.sum(self._b_conf_matrix[:-1, :-1], axis=0).astype(float)\n b_pos_pred = np.sum(self._b_conf_matrix[:-1, :-1], axis=1).astype(float)\n b_union = b_pos_gt + b_pos_pred - b_tp\n b_iou_valid = b_union > 0\n b_iou[b_iou_valid] = b_tp[b_iou_valid] / b_union[b_iou_valid]\n\n res = {}\n res[\"mIoU\"] = 100 * miou\n res[\"fwIoU\"] = 100 * fiou\n for i, name in enumerate(self._class_names):\n res[f\"IoU-{name}\"] = 100 * iou[i]\n if self._compute_boundary_iou:\n res[f\"BoundaryIoU-{name}\"] = 100 * b_iou[i]\n res[f\"min(IoU, B-Iou)-{name}\"] = 100 * min(iou[i], b_iou[i])\n res[\"mACC\"] = 100 * macc\n res[\"pACC\"] = 100 * pacc\n for i, name in enumerate(self._class_names):\n res[f\"ACC-{name}\"] = 100 * acc[i]\n\n if self._output_dir:\n file_path = os.path.join(self._output_dir, \"sem_seg_evaluation.pth\")\n with PathManager.open(file_path, \"wb\") as f:\n torch.save(res, f)\n results = OrderedDict({\"sem_seg\": res})\n self._logger.info(results)\n\n def get_miou_value_from_dict(dict, subkey):\n for key, value in dict.items():\n if subkey in key and \"IoU\" in key:\n if np.isnan(value):\n return 0\n else:\n return value\n\n ret = OrderedDict()\n ret[\"sem_seg\"] = {\n \"mIoU\": results[\"sem_seg\"][\"mIoU\"],\n \"IoU.road\": get_miou_value_from_dict(results[\"sem_seg\"], \"road\"),\n \"IoU.sidewalk\": get_miou_value_from_dict(results[\"sem_seg\"], \"sidewalk\"),\n \"IoU.building\": get_miou_value_from_dict(results[\"sem_seg\"], \"building\"),\n \"IoU.wall\": get_miou_value_from_dict(results[\"sem_seg\"], \"wall\"),\n \"IoU.fence\": get_miou_value_from_dict(results[\"sem_seg\"], \"fence\"),\n \"IoU.pole\": get_miou_value_from_dict(results[\"sem_seg\"], \"pole\"),\n \"IoU.traffic light\": get_miou_value_from_dict(\n results[\"sem_seg\"], \"traffic light\"\n ),\n \"IoU.traffic sign\": get_miou_value_from_dict(\n results[\"sem_seg\"], \"traffic sign\"\n ),\n \"IoU.vegetation\": get_miou_value_from_dict(\n results[\"sem_seg\"], \"vegetation\"\n ),\n \"IoU.terrain\": get_miou_value_from_dict(results[\"sem_seg\"], \"terrain\"),\n \"IoU.sky\": get_miou_value_from_dict(results[\"sem_seg\"], \"sky\"),\n \"IoU.person\": get_miou_value_from_dict(results[\"sem_seg\"], \"person\"),\n \"IoU.rider\": get_miou_value_from_dict(results[\"sem_seg\"], \"rider\"),\n \"IoU.car\": get_miou_value_from_dict(results[\"sem_seg\"], \"car\"),\n \"IoU.truck\": get_miou_value_from_dict(results[\"sem_seg\"], \"truck\"),\n \"IoU.bus\": get_miou_value_from_dict(results[\"sem_seg\"], \"bus\"),\n \"IoU.train\": get_miou_value_from_dict(results[\"sem_seg\"], \"train\"),\n \"IoU.motorcycle\": get_miou_value_from_dict(\n results[\"sem_seg\"], \"motorcycle\"\n ),\n \"IoU.bicycle\": get_miou_value_from_dict(results[\"sem_seg\"], \"bicycle\"),\n }\n return ret\n\n def encode_json_sem_seg(self, sem_seg, input_file_name):\n \"\"\"\n Convert semantic segmentation to COCO stuff format with segments encoded as RLEs.\n See http://cocodataset.org/#format-results\n \"\"\"\n json_list = []\n for label in np.unique(sem_seg):\n if self._contiguous_id_to_dataset_id is not None:\n assert (\n label in self._contiguous_id_to_dataset_id\n ), \"Label {} is not in the metadata info for {}\".format(\n label, self._dataset_name\n )\n dataset_id = self._contiguous_id_to_dataset_id[label]\n else:\n dataset_id = int(label)\n mask = (sem_seg == label).astype(np.uint8)\n mask_rle = mask_util.encode(np.array(mask[:, :, None], order=\"F\"))[0]\n mask_rle[\"counts\"] = mask_rle[\"counts\"].decode(\"utf-8\")\n json_list.append(\n {\n \"file_name\": input_file_name,\n \"category_id\": dataset_id,\n \"segmentation\": mask_rle,\n }\n )\n return json_list\n\n def _mask_to_boundary(self, mask: np.ndarray, dilation_ratio=0.02):\n assert mask.ndim == 2, \"mask_to_boundary expects a 2-dimensional image\"\n h, w = mask.shape\n diag_len = np.sqrt(h ** 2 + w ** 2)\n dilation = max(1, int(round(dilation_ratio * diag_len)))\n kernel = np.ones((3, 3), dtype=np.uint8)\n\n padded_mask = cv2.copyMakeBorder(mask, 1, 1, 1, 1, cv2.BORDER_CONSTANT, value=0)\n eroded_mask_with_padding = cv2.erode(padded_mask, kernel, iterations=dilation)\n eroded_mask = eroded_mask_with_padding[1:-1, 1:-1]\n boundary = mask - eroded_mask\n return boundary" }, { "identifier": "PersoEvalHook", "path": "clouds/engine/hooks.py", "snippet": "class PersoEvalHook(HookBase):\n \"\"\"\n Run an evaluation function periodically, and at the end of training.\n\n It is executed every ``eval_period`` iterations and after the last iteration.\n \"\"\"\n\n def __init__(self, eval_period, eval_function, eval_after_train=True):\n \"\"\"\n Args:\n eval_period (int): the period to run `eval_function`. Set to 0 to\n not evaluate periodically (but still evaluate after the last iteration\n if `eval_after_train` is True).\n eval_function (callable): a function which takes no arguments, and\n returns a nested dict of evaluation metrics.\n eval_after_train (bool): whether to evaluate after the last iteration\n\n Note:\n This hook must be enabled in all or none workers.\n If you would like only certain workers to perform evaluation,\n give other workers a no-op function (`eval_function=lambda: None`).\n \"\"\"\n self._period = eval_period\n self._func = eval_function\n self._eval_after_train = eval_after_train\n\n def _do_eval(self):\n results = self._func()\n\n if results:\n assert isinstance(\n results, dict\n ), \"Eval function must return a dict. Got {} instead.\".format(results)\n\n flattened_results = flatten_results_dict(results)\n for k, v in flattened_results.items():\n try:\n v = float(v)\n except Exception as e:\n raise ValueError(\n \"[EvalHook] eval_function should return a nested dict of float. \"\n \"Got '{}: {}' instead.\".format(k, v)\n ) from e\n self.trainer.storage.put_scalars(**flattened_results, smoothing_hint=False)\n\n # Evaluation may take different time among workers.\n # A barrier make them start the next iteration together.\n comm.synchronize()\n\n def before_train(self):\n \"\"\"\n Called before the first iteration.\n \"\"\"\n if \"debug\" in self.trainer.cfg.OUTPUT_DIR:\n pass\n else:\n results = self._func()\n\n if results:\n assert isinstance(\n results, dict\n ), \"Eval function must return a dict. Got {} instead.\".format(results)\n\n flattened_results = flatten_results_dict(results)\n for k, v in flattened_results.items():\n try:\n v = float(v)\n except Exception as e:\n raise ValueError(\n \"[EvalHook] eval_function should return a nested dict of float. \"\n \"Got '{}: {}' instead.\".format(k, v)\n ) from e\n self.trainer.storage.put_scalars(\n **flattened_results, smoothing_hint=False\n )\n\n def after_step(self):\n next_iter = self.trainer.iter + 1\n if self._period > 0 and next_iter % self._period == 0:\n # do the last eval in after_train\n if next_iter != self.trainer.max_iter:\n self._do_eval()\n\n def after_train(self):\n # This condition is to prevent the eval from running after a failed training\n if self._eval_after_train and self.trainer.iter + 1 >= self.trainer.max_iter:\n self._do_eval()\n # func is likely a closure that holds reference to the trainer\n # therefore we clean it to avoid circular reference in the end\n del self._func" }, { "identifier": "WandbWriter", "path": "clouds/utils/events.py", "snippet": "class WandbWriter(EventWriter):\n \"\"\"\n Write all scalars to a tensorboard file.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Args:\n log_dir (str): the directory to save the output events\n kwargs: other arguments passed to `torch.utils.tensorboard.SummaryWriter(...)`\n \"\"\"\n self._last_write = -1\n self._group_rules = [\n (IsIn(\"/\"), BaseRule()),\n (IsIn(\"loss\"), Prefix(\"train\")),\n # (IsIn(\"sem_seg\"), Prefix(\"val\")),\n (\n IsInList([\"lr\", \"time\", \"eta_seconds\", \"rank_data_time\", \"data_time\"]),\n Prefix(\"stats\"),\n ),\n ]\n\n def write(self):\n storage = get_event_storage()\n\n def _group_name(scalar_name):\n for rule, op in self._group_rules:\n if rule(scalar_name):\n return op(scalar_name)\n return scalar_name\n\n stats = {\n _group_name(name): scalars[0]\n for name, scalars in storage.latest().items()\n if scalars[1] > self._last_write\n }\n if len(stats) > 0:\n self._last_write = max([v[1] for k, v in storage.latest().items()])\n\n # storage.put_{image,histogram} is only meant to be used by\n # tensorboard writer. So we access its internal fields directly from here.\n if len(storage._vis_data) >= 1:\n stats[\"image\"] = [\n wandb.Image(img, caption=img_name)\n for img_name, img, step_num in storage._vis_data\n ]\n # Storage stores all image data and rely on this writer to clear them.\n # As a result it assumes only one writer will use its image data.\n # An alternative design is to let storage store limited recent\n # data (e.g. only the most recent image) that all writers can access.\n # In that case a writer may not see all image data if its period is long.\n storage.clear_images()\n\n if len(storage._histograms) >= 1:\n\n def create_bar(tag, bucket_limits, bucket_counts, **kwargs):\n data = [\n [label, val] for (label, val) in zip(bucket_limits, bucket_counts)\n ]\n table = wandb.Table(data=data, columns=[\"label\", \"value\"])\n return wandb.plot.bar(table, \"label\", \"value\", title=tag)\n\n stats[\"hist\"] = [create_bar(**params) for params in storage._histograms]\n\n storage.clear_histograms()\n\n if len(stats) == 0:\n return\n wandb.log(stats, step=storage.iter)\n\n def close(self):\n wandb.finish()" }, { "identifier": "setup_wandb", "path": "clouds/utils/events.py", "snippet": "def setup_wandb(cfg, args):\n if comm.is_main_process():\n init_args = {\n k.lower(): v\n for k, v in cfg.WANDB.items()\n if isinstance(k, str) and k not in [\"config\", \"name\"]\n }\n if \"config_exclude_keys\" in init_args:\n init_args[\"config\"] = cfg\n init_args[\"config\"][\"cfg_file\"] = args.config_file\n else:\n init_args[\"config\"] = {\n \"output_dir\": cfg.OUTPUT_DIR,\n \"train\": extract_dataset_from_string(cfg.DATASETS.TRAIN),\n \"test\": extract_dataset_from_string(cfg.DATASETS.TEST),\n \"iter\": cfg.SOLVER.MAX_ITER,\n \"lr\": cfg.SOLVER.BASE_LR,\n \"batch_size\": cfg.SOLVER.IMS_PER_BATCH,\n \"cfg_file\": args.config_file,\n }\n\n init_args[\"group\"] = get_base_name(cfg)\n if cfg.WANDB.NAME is not None:\n init_args[\"name\"] = cfg.WANDB.NAME\n else:\n init_args[\"name\"] = get_full_name_xp(init_args[\"group\"], cfg)\n if \"debug\" in cfg.OUTPUT_DIR:\n init_args[\"project\"] = \"debug\"\n wandb.init(**init_args)" } ]
from shapely.errors import ShapelyDeprecationWarning from collections import OrderedDict from typing import Any, Dict, List, Set from detectron2.checkpoint import DetectionCheckpointer from detectron2.config import get_cfg from detectron2.data import ( MetadataCatalog, build_detection_train_loader, build_detection_test_loader, ) from detectron2.engine import ( DefaultTrainer, default_argument_parser, default_setup, launch, ) from detectron2.modeling import build_model from detectron2.evaluation import ( CityscapesInstanceEvaluator, CityscapesSemSegEvaluator, COCOEvaluator, COCOPanopticEvaluator, DatasetEvaluators, LVISEvaluator, SemSegEvaluator, verify_results, inference_on_dataset, print_csv_format, DatasetEvaluator, ) from detectron2.projects.deeplab import add_deeplab_config, build_lr_scheduler from detectron2.solver.build import maybe_add_gradient_clipping from detectron2.utils.logger import setup_logger from detectron2.engine import hooks from fvcore.nn.precise_bn import get_bn_modules from clouds import ( CityscapesSemSegEvaluator, ClassicalSemSegEvaluator, MapperTrain, MapperTest, add_maskformer2_config, add_clouds_config, add_wandb_config, add_prerocessing_training_set_config, PersoEvalHook, add_repeat_factors, ) from clouds.utils import setup_wandb, WandbWriter import warnings import copy import itertools import logging import os import ast import torch import detectron2.utils.comm as comm
14,515
return FullModelGradientClippingOptimizer if enable else optim optimizer_type = cfg.SOLVER.OPTIMIZER if optimizer_type == "SGD": optimizer = maybe_add_full_model_gradient_clipping(torch.optim.SGD)( params, cfg.SOLVER.BASE_LR, momentum=cfg.SOLVER.MOMENTUM ) elif optimizer_type == "ADAMW": optimizer = maybe_add_full_model_gradient_clipping(torch.optim.AdamW)( params, cfg.SOLVER.BASE_LR ) else: raise NotImplementedError(f"no optimizer type {optimizer_type}") if not cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE == "full_model": optimizer = maybe_add_gradient_clipping(cfg, optimizer) return optimizer @classmethod def test(cls, cfg, model, output_folder=None, evaluators=None): """ Evaluate the given model. The given model is expected to already contain weights to evaluate. Args: cfg (CfgNode): model (nn.Module): evaluators (list[DatasetEvaluator] or None): if None, will call :meth:`build_evaluator`. Otherwise, must have the same length as ``cfg.DATASETS.TEST``. Returns: dict: a dict of result metrics """ logger = logging.getLogger(__name__) if isinstance(evaluators, DatasetEvaluator): evaluators = [evaluators] if evaluators is not None: assert len(cfg.DATASETS.TEST) == len(evaluators), "{} != {}".format( len(cfg.DATASETS.TEST), len(evaluators) ) results = OrderedDict() for idx, dataset_name in enumerate(cfg.DATASETS.TEST): data_loader = cls.build_test_loader(cfg, dataset_name) # When evaluators are passed in as arguments, # implicitly assume that evaluators can be created before data_loader. if evaluators is not None: evaluator = evaluators[idx] else: try: evaluator = cls.build_evaluator( cfg, dataset_name, output_folder=output_folder ) except NotImplementedError: logger.warn( "No evaluator found. Use `DefaultTrainer.test(evaluators=)`, " "or implement its `build_evaluator` method." ) results[dataset_name] = {} continue results_i = inference_on_dataset(model, data_loader, evaluator) results[dataset_name] = results_i if comm.is_main_process(): assert isinstance( results_i, dict ), "Evaluator must return a dict on the main process. Got {} instead.".format( results_i ) logger.info( "Evaluation results for {} in csv format:".format(dataset_name) ) print_csv_format(results_i) if len(results) == 1: results = list(results.values())[0] return results def build_hooks(self): """ Build a list of default hooks, including timing, evaluation, checkpointing, lr scheduling, precise BN, writing events. Returns: list[HookBase]: """ cfg = self.cfg.clone() cfg.defrost() cfg.DATALOADER.NUM_WORKERS = 0 # save some memory and time for PreciseBN ret = [ hooks.IterationTimer(), hooks.LRScheduler(), hooks.PreciseBN( # Run at the same freq as (but before) evaluation. cfg.TEST.EVAL_PERIOD, self.model, # Build a new data loader to not affect training self.build_train_loader(cfg), cfg.TEST.PRECISE_BN.NUM_ITER, ) if cfg.TEST.PRECISE_BN.ENABLED and get_bn_modules(self.model) else None, ] # Do PreciseBN before checkpointer, because it updates the model and need to # be saved by checkpointer. # This is not always the best: if checkpointing has a different frequency, # some checkpoints may have more precise statistics than others. if comm.is_main_process(): ret.append( hooks.PeriodicCheckpointer(self.checkpointer, cfg.TEST.EVAL_PERIOD * 5) ) def test_and_save_results(): self._last_eval_results = self.test(self.cfg, self.model) return self._last_eval_results # Do evaluation after checkpointer, because then if it fails, # we can use the saved checkpoint to debug. # ret.append(hooks.EvalHook(cfg.TEST.EVAL_PERIOD, test_and_save_results))
""" Copyright 2023 Telecom Paris, Yasser BENIGMIM. All rights reserved. Licensed under the Apache License, Version 2.0 Reference: https://github.com/facebookresearch/Mask2Former/blob/main/train_net.py CLOUDS Training Script. This script is a simplified version of the training script in detectron2/tools. """ try: # ignore ShapelyDeprecationWarning from fvcore warnings.filterwarnings("ignore", category=ShapelyDeprecationWarning) except: pass class Trainer(DefaultTrainer): """ Extension of the Trainer class adapted to CLOUDS. """ def build_writers(self): writers = super().build_writers() # use wandb writer instead. writers[-1] = WandbWriter() return writers @classmethod def build_model(cls, cfg): """ Returns: torch.nn.Module: It now calls :func:`detectron2.modeling.build_model`. Overwrite it if you'd like a different model. """ model = build_model(cfg) # logger = logging.getLogger(__name__) # logger.info("Model:\n{}".format(model)) return model # @classmethod # def build_model(cls, cfg): # """ # Returns: # torch.nn.Module: # # It now calls :func:`detectron2.modeling.build_model`. # Overwrite it if you'd like a different model. # """ # model = build_model(cfg) # # logger = logging.getLogger(__name__) # # logger.info("Model:\n{}".format(model)) # return model @classmethod def build_evaluator(cls, cfg, dataset_name, output_folder=None): """ Create evaluator(s) for a given dataset. This uses the special metadata "evaluator_type" associated with each builtin dataset. For your own dataset, you can simply create an evaluator manually in your script and do not have to worry about the hacky if-else logic here. """ if output_folder is None: output_folder = os.path.join(cfg.OUTPUT_DIR, "inference") else: output_folder = os.path.join(cfg.OUTPUT_DIR, output_folder, "inference") evaluator_list = [] evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type # semantic segmentation if ( evaluator_type == "bdd_sem_seg" or evaluator_type == "mapillary_sem_seg" or evaluator_type == "acdc_sem_seg" ): evaluator_list.append( ClassicalSemSegEvaluator( dataset_name, distributed=True, output_dir=output_folder, save_pl=cfg.MODEL.SAVE_PSEUDO_LABELS, ) ) # Cityscapes if evaluator_type == "cityscapes_sem_seg": assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." # return CityscapesSemSegEvaluator(dataset_name) if cfg.MODEL.SAVE_PSEUDO_LABELS: return CityscapesSemSegEvaluator( dataset_name, save_pl=True, output_dir=output_folder ) else: return CityscapesSemSegEvaluator(dataset_name) if len(evaluator_list) == 0: raise NotImplementedError( "no Evaluator for the dataset {} with the type {}".format( dataset_name, evaluator_type ) ) elif len(evaluator_list) == 1: return evaluator_list[0] return DatasetEvaluators(evaluator_list) @classmethod def build_train_loader(cls, cfg): # Semantic segmentation dataset mapper mapper = MapperTrain(cfg, True) return build_detection_train_loader(cfg, mapper=mapper) @classmethod def build_test_loader(cls, cfg, dataset_name): mapper = MapperTest(cfg, False) return build_detection_test_loader( cfg, dataset_name, batch_size=1, mapper=mapper ) @classmethod def build_lr_scheduler(cls, cfg, optimizer): """ It now calls :func:`detectron2.solver.build_lr_scheduler`. Overwrite it if you'd like a different scheduler. """ return build_lr_scheduler(cfg, optimizer) @classmethod def build_optimizer(cls, cfg, model): weight_decay_norm = cfg.SOLVER.WEIGHT_DECAY_NORM weight_decay_embed = cfg.SOLVER.WEIGHT_DECAY_EMBED defaults = {} defaults["lr"] = cfg.SOLVER.BASE_LR defaults["weight_decay"] = cfg.SOLVER.WEIGHT_DECAY norm_module_types = ( torch.nn.BatchNorm1d, torch.nn.BatchNorm2d, torch.nn.BatchNorm3d, torch.nn.SyncBatchNorm, # NaiveSyncBatchNorm inherits from BatchNorm2d torch.nn.GroupNorm, torch.nn.InstanceNorm1d, torch.nn.InstanceNorm2d, torch.nn.InstanceNorm3d, torch.nn.LayerNorm, torch.nn.LocalResponseNorm, ) params: List[Dict[str, Any]] = [] memo: Set[torch.nn.parameter.Parameter] = set() for module_name, module in model.named_modules(): for module_param_name, value in module.named_parameters(recurse=False): if not value.requires_grad: continue if cfg.MODEL.CLOUDS.OVERWRITING: if any( ignored_module in module_name for ignored_module in ["sem_seg_head_ema.", "sam.sam."] ): continue # Avoid duplicating parameters if value in memo: continue memo.add(value) hyperparams = copy.copy(defaults) if "backbone" in module_name: hyperparams["lr"] = ( hyperparams["lr"] * cfg.SOLVER.BACKBONE_MULTIPLIER ) if ( "relative_position_bias_table" in module_param_name or "absolute_pos_embed" in module_param_name ): print(module_param_name) hyperparams["weight_decay"] = 0.0 if isinstance(module, norm_module_types): hyperparams["weight_decay"] = weight_decay_norm if isinstance(module, torch.nn.Embedding): hyperparams["weight_decay"] = weight_decay_embed params.append({"params": [value], **hyperparams}) def maybe_add_full_model_gradient_clipping(optim): # detectron2 doesn't have full model gradient clipping now clip_norm_val = cfg.SOLVER.CLIP_GRADIENTS.CLIP_VALUE enable = ( cfg.SOLVER.CLIP_GRADIENTS.ENABLED and cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE == "full_model" and clip_norm_val > 0.0 ) class FullModelGradientClippingOptimizer(optim): def step(self, closure=None): all_params = itertools.chain( *[x["params"] for x in self.param_groups] ) torch.nn.utils.clip_grad_norm_(all_params, clip_norm_val) super().step(closure=closure) return FullModelGradientClippingOptimizer if enable else optim optimizer_type = cfg.SOLVER.OPTIMIZER if optimizer_type == "SGD": optimizer = maybe_add_full_model_gradient_clipping(torch.optim.SGD)( params, cfg.SOLVER.BASE_LR, momentum=cfg.SOLVER.MOMENTUM ) elif optimizer_type == "ADAMW": optimizer = maybe_add_full_model_gradient_clipping(torch.optim.AdamW)( params, cfg.SOLVER.BASE_LR ) else: raise NotImplementedError(f"no optimizer type {optimizer_type}") if not cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE == "full_model": optimizer = maybe_add_gradient_clipping(cfg, optimizer) return optimizer @classmethod def test(cls, cfg, model, output_folder=None, evaluators=None): """ Evaluate the given model. The given model is expected to already contain weights to evaluate. Args: cfg (CfgNode): model (nn.Module): evaluators (list[DatasetEvaluator] or None): if None, will call :meth:`build_evaluator`. Otherwise, must have the same length as ``cfg.DATASETS.TEST``. Returns: dict: a dict of result metrics """ logger = logging.getLogger(__name__) if isinstance(evaluators, DatasetEvaluator): evaluators = [evaluators] if evaluators is not None: assert len(cfg.DATASETS.TEST) == len(evaluators), "{} != {}".format( len(cfg.DATASETS.TEST), len(evaluators) ) results = OrderedDict() for idx, dataset_name in enumerate(cfg.DATASETS.TEST): data_loader = cls.build_test_loader(cfg, dataset_name) # When evaluators are passed in as arguments, # implicitly assume that evaluators can be created before data_loader. if evaluators is not None: evaluator = evaluators[idx] else: try: evaluator = cls.build_evaluator( cfg, dataset_name, output_folder=output_folder ) except NotImplementedError: logger.warn( "No evaluator found. Use `DefaultTrainer.test(evaluators=)`, " "or implement its `build_evaluator` method." ) results[dataset_name] = {} continue results_i = inference_on_dataset(model, data_loader, evaluator) results[dataset_name] = results_i if comm.is_main_process(): assert isinstance( results_i, dict ), "Evaluator must return a dict on the main process. Got {} instead.".format( results_i ) logger.info( "Evaluation results for {} in csv format:".format(dataset_name) ) print_csv_format(results_i) if len(results) == 1: results = list(results.values())[0] return results def build_hooks(self): """ Build a list of default hooks, including timing, evaluation, checkpointing, lr scheduling, precise BN, writing events. Returns: list[HookBase]: """ cfg = self.cfg.clone() cfg.defrost() cfg.DATALOADER.NUM_WORKERS = 0 # save some memory and time for PreciseBN ret = [ hooks.IterationTimer(), hooks.LRScheduler(), hooks.PreciseBN( # Run at the same freq as (but before) evaluation. cfg.TEST.EVAL_PERIOD, self.model, # Build a new data loader to not affect training self.build_train_loader(cfg), cfg.TEST.PRECISE_BN.NUM_ITER, ) if cfg.TEST.PRECISE_BN.ENABLED and get_bn_modules(self.model) else None, ] # Do PreciseBN before checkpointer, because it updates the model and need to # be saved by checkpointer. # This is not always the best: if checkpointing has a different frequency, # some checkpoints may have more precise statistics than others. if comm.is_main_process(): ret.append( hooks.PeriodicCheckpointer(self.checkpointer, cfg.TEST.EVAL_PERIOD * 5) ) def test_and_save_results(): self._last_eval_results = self.test(self.cfg, self.model) return self._last_eval_results # Do evaluation after checkpointer, because then if it fails, # we can use the saved checkpoint to debug. # ret.append(hooks.EvalHook(cfg.TEST.EVAL_PERIOD, test_and_save_results))
ret.append(PersoEvalHook(cfg.TEST.EVAL_PERIOD, test_and_save_results))
9
2023-12-15 15:40:58+00:00
24k
Ruiyuan-Zhang/CCS
multi_part_assembly/utils/wx_transformer_utilities/transformer_layer.py
[ { "identifier": "LayerNorm", "path": "multi_part_assembly/utils/wx_transformer_utilities/layer_norm.py", "snippet": "def LayerNorm(normalized_shape, eps=1e-5, elementwise_affine=True, export=False):\n if not export and torch.cuda.is_available() and has_fused_layernorm:\n return FusedLayerNorm(normalized_shape, eps, elementwise_affine)\n return torch.nn.LayerNorm(normalized_shape, eps, elementwise_affine)" }, { "identifier": "MultiheadAttention", "path": "multi_part_assembly/utils/wx_transformer_utilities/multihead_attention.py", "snippet": "class MultiheadAttention(nn.Module):\n \"\"\"Multi-headed attention.\n\n See \"Attention Is All You Need\" for more details.\n \"\"\"\n\n def __init__(\n self,\n embed_dim,\n num_heads,\n kdim=None,\n vdim=None,\n dropout=0.0,\n bias=True,\n add_bias_kv=False,\n add_zero_attn=False,\n self_attention=False,\n encoder_decoder_attention=False,\n q_noise=0.0,\n qn_block_size=8,\n nblocks=1,\n top_k_ratio=None,\n use_value_competition=True,\n shared_memory_attention = False,\n use_topk = False,\n topk = 3,\n num_steps = 5,\n mem_slots = 4,\n null_attention = False,\n regressive = False\n ):\n super().__init__()\n self.embed_dim = embed_dim\n self.kdim = kdim if kdim is not None else embed_dim\n self.vdim = vdim if vdim is not None else embed_dim\n self.qkv_same_dim = self.kdim == embed_dim and self.vdim == embed_dim\n\n self.num_heads = num_heads\n self.dropout_module = FairseqDropout(\n dropout, module_name=self.__class__.__name__\n )\n\n self.head_dim = embed_dim // num_heads\n self.shared_memory_attention = shared_memory_attention\n\n print('total heads', self.num_heads)\n print('head dim', self.head_dim)\n\n self.use_topk = use_topk\n self.topk = topk\n\n print('use topk?' + str(self.use_topk))\n print('topk:'+str(self.topk))\n\n assert (\n self.head_dim * num_heads == self.embed_dim\n ), \"embed_dim must be divisible by num_heads\"\n self.scaling = self.head_dim ** -0.5\n\n self.self_attention = self_attention\n self.encoder_decoder_attention = encoder_decoder_attention\n\n assert not self.self_attention or self.qkv_same_dim, (\n \"Self-attention requires query, key and \" \"value to be of the same size\"\n )\n if not self.shared_memory_attention: # 这里的共享memory_attention是什么内容呢?表示的是不在不同的layer之间共享memory吗?\n self.k_proj = quant_noise(GroupLinearLayer(self.kdim//nblocks, embed_dim//nblocks, nblocks, bias=bias), q_noise, qn_block_size)\n self.v_proj = quant_noise(GroupLinearLayer(self.vdim//nblocks, embed_dim//nblocks, nblocks, bias=bias), q_noise, qn_block_size)\n self.q_proj = quant_noise(GroupLinearLayer(embed_dim//nblocks, embed_dim//nblocks, nblocks, bias=bias), q_noise, qn_block_size)\n self.out_proj = quant_noise(GroupLinearLayer(embed_dim//nblocks, embed_dim//nblocks, nblocks, bias=bias), q_noise, qn_block_size)\n\n if add_bias_kv:\n self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim))\n self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim))\n if self.shared_memory_attention:\n self.bias_k_memory = Parameter(torch.Tensor(1, 1, embed_dim))\n self.bias_v_memory = Parameter(torch.Tensor(1, 1, embed_dim))\n else:\n self.bias_k = self.bias_v = None\n self.bias_k_memory = self.bias_v_memory = None\n\n self.add_zero_attn = add_zero_attn\n\n self.reset_parameters()\n\n self.onnx_trace = False\n self.tpu = False\n\n # 这里表示,如果共享memory_attention的话\n if self.shared_memory_attention:\n print('MEM SLOTS:' + str(mem_slots))\n print('Null attention:' + str(null_attention))\n print('USING SHARED MEMORY ATTENTION +++++++++')\n #self.num_heads = 1\n self.regressive = regressive\n if not regressive: \n self.relational_memory = RelationalMemory(\n mem_slots=mem_slots,\n head_size=self.head_dim , #128\n input_size=embed_dim,\n output_size=embed_dim,\n num_heads=self.num_heads, #1\n num_blocks=1,\n forget_bias=1,\n input_bias=0,\n gate_style=\"unit\",\n attention_mlp_layers=1,\n key_size=32,\n return_all_outputs=False,\n use_topk = self.use_topk,\n topk = self.topk,\n num_steps = num_steps, \n null_attention = null_attention\n )\n else:\n print('USING AUTO REGRESSIVE')\n self.relational_memory = RelationalMemoryRegressive(\n mem_slots=mem_slots,\n head_size=self.head_dim ,\n input_size=embed_dim,\n output_size=embed_dim,\n num_heads=self.num_heads,\n num_blocks=1,\n forget_bias=1,\n input_bias=0,\n gate_style=\"unit\",\n attention_mlp_layers=4,\n key_size=32,\n return_all_outputs=False,\n use_topk = self.use_topk,\n topk = self.topk,\n num_steps = num_steps,\n null_attention = False\n )\n self.memory_size = 128 #self.head_dim * self.num_heads\n '''\n self.mem_att = MHAMemory(\n n_head=4,\n d_model_read=embed_dim,\n d_model_write=self.memory_size,\n d_model_out=embed_dim,\n d_k=32,\n d_v=32,\n grad_sparse=False,\n )\n '''\n self.memory = None # 因为要共享self.memory,所以这里是为了占个位置\n\n def prepare_for_onnx_export_(self):\n self.onnx_trace = True\n\n def prepare_for_tpu_(self, **kwargs):\n self.tpu = True\n\n def reset_parameters(self):\n if self.qkv_same_dim:\n # Empirically observed the convergence to be much better with\n # the scaled initialization\n nn.init.xavier_uniform_(self.k_proj.weight, gain=1 / math.sqrt(2))\n nn.init.xavier_uniform_(self.v_proj.weight, gain=1 / math.sqrt(2))\n nn.init.xavier_uniform_(self.q_proj.weight, gain=1 / math.sqrt(2))\n if self.shared_memory_attention:\n nn.init.xavier_uniform_(self.k_proj_memory.weight, gain=1 / math.sqrt(2))\n nn.init.xavier_uniform_(self.v_proj_memory.weight, gain=1 / math.sqrt(2))\n nn.init.xavier_uniform_(self.q_proj_memory.weight, gain=1 / math.sqrt(2))\n\n else:\n nn.init.xavier_uniform_(self.k_proj.weight)\n nn.init.xavier_uniform_(self.v_proj.weight)\n nn.init.xavier_uniform_(self.q_proj.weight)\n\n #if self.shared_memory_attention:\n # nn.init.xavier_uniform_(self.k_proj_memory.weight)\n # nn.init.xavier_uniform_(self.v_proj_memory.weight)\n # nn.init.xavier_uniform_(self.q_proj_memory.weight)\n\n nn.init.xavier_uniform_(self.out_proj.weight)\n #if self.shared_memory_attention:\n # nn.init.xavier_uniform_(self.out_proj_memory.weight)\n \n if self.out_proj.bias is not None:\n nn.init.constant_(self.out_proj.bias, 0.)\n\n #if self.shared_memory_attention and self.out_proj_memory.bias is not None:\n # nn.init.constant_(self.out_proj.bias, 0.)\n \n if self.bias_k is not None:\n nn.init.xavier_normal_(self.bias_k)\n if self.bias_v is not None:\n nn.init.xavier_normal_(self.bias_v)\n\n #if self.shared_memory_attention:\n # if self.bias_k is not None:\n # nn.init.xavier_normal_(self.bias_k_memory)\n # if self.bias_v is not None:\n # nn.init.xavier_normal_(self.bias_v_memory)\n\n\n def forward(\n self,\n query,\n key: Optional[Tensor],\n value: Optional[Tensor],\n key_padding_mask: Optional[Tensor] = None,\n incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,\n need_weights: bool = True,\n static_kv: bool = False,\n attn_mask: Optional[Tensor] = None,\n before_softmax: bool = False,\n need_head_weights: bool = False,\n comp = None,\n memory = None\n ) -> Tuple[Tensor, Optional[Tensor]]:\n \"\"\"Input shape: Time x Batch x Channel\n\n Args:\n key_padding_mask (ByteTensor, optional): mask to exclude\n keys that are pads, of shape `(batch, src_len)`, where\n padding elements are indicated by 1s.\n need_weights (bool, optional): return the attention weights,\n averaged over heads (default: False).\n attn_mask (ByteTensor, optional): typically used to\n implement causal attention, where the mask prevents the\n attention from looking forward in time (default: None).\n before_softmax (bool, optional): return the raw attention\n weights and values before the attention softmax.\n need_head_weights (bool, optional): return the attention\n weights for each head. Implies *need_weights*. Default:\n return the average attention weights over all heads.\n \"\"\"\n if need_head_weights:\n need_weights = True\n\n tgt_len, bsz, embed_dim = query.size()\n assert embed_dim == self.embed_dim\n assert list(query.size()) == [tgt_len, bsz, embed_dim]\n\n if (\n not self.onnx_trace\n and not self.tpu # don't use PyTorch version on TPUs\n and incremental_state is None\n and not static_kv\n # A workaround for quantization to work. Otherwise JIT compilation\n # treats bias in linear module as method.\n and not torch.jit.is_scripting()\n and False\n ):\n assert key is not None and value is not None\n if self.shared_memory_attention:\n memory,_ = F.multi_head_attention_forward(\n memory,\n key,\n value,\n self.embed_dim,\n self.num_heads,\n torch.empty([0]),\n torch.cat((self.q_proj_memory.bias, self.k_proj.bias, self.v_proj.bias)),\n self.bias_k,\n self.bias_v,\n self.add_zero_attn,\n self.dropout_module.p,\n self.out_proj_memory.weight,\n self.out_proj_memory.bias,\n self.training or self.dropout_module.apply_during_inference,\n key_padding_mask,\n need_weights,\n attn_mask,\n use_separate_proj_weight=True,\n q_proj_weight=self.q_proj_memory.weight,\n k_proj_weight=self.k_proj.weight,\n v_proj_weight=self.v_proj.weight,\n )\n out,weights = F.multi_head_attention_forward(\n query,\n memory,\n memory,\n self.embed_dim,\n self.num_heads,\n torch.empty([0]),\n torch.cat((self.q_proj.bias, self.k_proj_memory.bias, self.v_proj_memory.bias)),\n self.bias_k_memory,\n self.bias_v_memory,\n self.add_zero_attn,\n self.dropout_module.p,\n self.out_proj.weight,\n self.out_proj.bias,\n self.training or self.dropout_module.apply_during_inference,\n key_padding_mask,\n need_weights,\n attn_mask,\n use_separate_proj_weight=True,\n q_proj_weight=self.q_proj.weight,\n k_proj_weight=self.k_proj_memory.weight,\n v_proj_weight=self.v_proj_memory.weight,\n )\n else:\n out, weights = F.multi_head_attention_forward(\n query,\n key,\n value,\n self.embed_dim,\n self.num_heads,\n torch.empty([0]),\n torch.cat((self.q_proj.bias, self.k_proj.bias, self.v_proj.bias)),\n self.bias_k,\n self.bias_v,\n self.add_zero_attn,\n self.dropout_module.p,\n self.out_proj.weight,\n self.out_proj.bias,\n self.training or self.dropout_module.apply_during_inference,\n key_padding_mask,\n need_weights,\n attn_mask,\n use_separate_proj_weight=True,\n q_proj_weight=self.q_proj.weight,\n k_proj_weight=self.k_proj.weight,\n v_proj_weight=self.v_proj.weight,\n\n ) \n\n return out, memory, weights\n\n if incremental_state is not None:\n saved_state = self._get_input_buffer(incremental_state)\n if saved_state is not None and \"prev_key\" in saved_state:\n # previous time steps are cached - no need to recompute\n # key and value if they are static\n if static_kv:\n assert self.encoder_decoder_attention and not self.self_attention\n key = value = None\n else:\n saved_state = None\n\n # 如果不共享memory attention\n if not self.shared_memory_attention:\n\n t1 = time.time()\n\n if self.self_attention:\n q = self.q_proj(query)\n k = self.k_proj(query)\n v = self.v_proj(query)\n elif self.encoder_decoder_attention:\n # encoder-decoder attention\n q = self.q_proj(query)\n if key is None:\n assert value is None\n k = v = None\n else:\n k = self.k_proj(key)\n v = self.v_proj(key)\n\n else:\n assert key is not None and value is not None\n \n q = self.q_proj(query)\n k = self.k_proj(key)\n v = self.v_proj(value)\n\n if comp is not None:\n v = v * comp\n #v_memory = v_memory * comp\n q *= self.scaling\n #q_memory *= self.scaling\n\n if self.bias_k is not None:\n assert self.bias_v is not None\n k = torch.cat([k, self.bias_k.repeat(1, bsz, 1)])\n v = torch.cat([v, self.bias_v.repeat(1, bsz, 1)])\n if attn_mask is not None:\n attn_mask = torch.cat(\n [attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1\n )\n if key_padding_mask is not None:\n key_padding_mask = torch.cat(\n [\n key_padding_mask,\n key_padding_mask.new_zeros(key_padding_mask.size(0), 1),\n ],\n dim=1,\n )\n\n q = (\n q.contiguous()\n .view(tgt_len, bsz * self.num_heads, self.head_dim)\n .transpose(0, 1)\n )\n if k is not None:\n k = (\n k.contiguous()\n .view(-1, bsz * self.num_heads, self.head_dim)\n .transpose(0, 1)\n )\n if v is not None:\n v = (\n v.contiguous()\n .view(-1, bsz * self.num_heads, self.head_dim)\n .transpose(0, 1)\n )\n\n \n if saved_state is not None:\n # saved states are stored with shape (bsz, num_heads, seq_len, head_dim)\n if \"prev_key\" in saved_state:\n _prev_key = saved_state[\"prev_key\"]\n assert _prev_key is not None\n prev_key = _prev_key.view(bsz * self.num_heads, -1, self.head_dim)\n if static_kv:\n k = prev_key\n else:\n assert k is not None\n k = torch.cat([prev_key, k], dim=1)\n if \"prev_value\" in saved_state:\n _prev_value = saved_state[\"prev_value\"]\n assert _prev_value is not None\n prev_value = _prev_value.view(bsz * self.num_heads, -1, self.head_dim)\n if static_kv:\n v = prev_value\n else:\n assert v is not None\n v = torch.cat([prev_value, v], dim=1)\n prev_key_padding_mask: Optional[Tensor] = None\n if \"prev_key_padding_mask\" in saved_state:\n prev_key_padding_mask = saved_state[\"prev_key_padding_mask\"]\n assert k is not None and v is not None\n key_padding_mask = MultiheadAttention._append_prev_key_padding_mask(\n key_padding_mask=key_padding_mask,\n prev_key_padding_mask=prev_key_padding_mask,\n batch_size=bsz,\n src_len=k.size(1),\n static_kv=static_kv,\n )\n\n saved_state[\"prev_key\"] = k.view(bsz, self.num_heads, -1, self.head_dim)\n saved_state[\"prev_value\"] = v.view(bsz, self.num_heads, -1, self.head_dim)\n saved_state[\"prev_key_padding_mask\"] = key_padding_mask\n # In this branch incremental_state is never None\n assert incremental_state is not None\n incremental_state = self._set_input_buffer(incremental_state, saved_state)\n assert k is not None\n src_len = k.size(1)\n\n # This is part of a workaround to get around fork/join parallelism\n # not supporting Optional types.\n if key_padding_mask is not None and key_padding_mask.dim() == 0:\n key_padding_mask = None\n\n if key_padding_mask is not None:\n assert key_padding_mask.size(0) == bsz\n assert key_padding_mask.size(1) == src_len\n\n if self.add_zero_attn:\n assert v is not None\n src_len += 1\n k = torch.cat([k, k.new_zeros((k.size(0), 1) + k.size()[2:])], dim=1)\n v = torch.cat([v, v.new_zeros((v.size(0), 1) + v.size()[2:])], dim=1)\n if attn_mask is not None:\n attn_mask = torch.cat(\n [attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1\n )\n if key_padding_mask is not None:\n key_padding_mask = torch.cat(\n [\n key_padding_mask,\n torch.zeros(key_padding_mask.size(0), 1).type_as(\n key_padding_mask\n ),\n ],\n dim=1,\n )\n\n attn_weights = torch.bmm(q, k.transpose(1, 2))\n attn_weights = MultiheadAttention.apply_sparse_mask(attn_weights, tgt_len, src_len, bsz)\n\n assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len]\n\n if attn_mask is not None:\n attn_mask = attn_mask.unsqueeze(0)\n if self.onnx_trace:\n attn_mask = attn_mask.repeat(attn_weights.size(0), 1, 1)\n attn_weights += attn_mask\n\n if key_padding_mask is not None:\n # don't attend to padding symbols\n attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)\n if not self.tpu:\n attn_weights = attn_weights.masked_fill(\n key_padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool),\n float(\"-inf\")\n )\n else:\n attn_weights = attn_weights.transpose(0, 2)\n attn_weights = attn_weights.masked_fill(key_padding_mask, float('-inf'))\n attn_weights = attn_weights.transpose(0, 2)\n attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)\n\n if before_softmax:\n return attn_weights, v\n \n # 是这个\n attn_weights_float = utils.softmax(\n attn_weights, dim=-1, onnx_trace=self.onnx_trace\n )\n attn_weights = attn_weights_float.type_as(attn_weights)\n attn_probs = self.dropout_module(attn_weights)\n\n assert v is not None\n if self.use_topk:\n k = torch.topk(attn_probs, dim = 2, k = self.topk)\n mask = torch.zeros(attn_probs.size()).to(attn_probs.device)\n mask.scatter_(2, k.indices, 1)\n attn_probs = attn_probs * mask\n attn = torch.bmm(attn_probs, v)\n assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.head_dim]\n if self.onnx_trace and attn.size(1) == 1:\n # when ONNX tracing a single decoder step (sequence length == 1)\n # the transpose is a no-op copy before view, thus unnecessary\n attn = attn.contiguous().view(tgt_len, bsz, embed_dim)\n else:\n attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)\n attn = self.out_proj(attn)\n attn_weights: Optional[Tensor] = None\n if need_weights:\n attn_weights = attn_weights_float.view(\n bsz, self.num_heads, tgt_len, src_len\n ).transpose(1, 0)\n if not need_head_weights:\n # average attention weights over heads\n attn_weights = attn_weights.mean(dim=0)\n #print('time taken by default mha:' + str(time.time() - t1))\n return attn, None, attn_weights\n \n else: # 共享注意力机制 memory\n t1 = time.time()\n\n # 这个是共享memory的时候\n if self.memory is None:\n self.memory = self.relational_memory.initial_state(query.size(1), query.size(0)).to(query.device)\n\n self.memory = self.memory.to(query.device)\n\n #print(self.memory.size())\n \n \n key = key.transpose(1, 0)\n\n #print(key.size())\n #memory = self.memory[:key.size(0)]\n #print(self.memory.size())\n\n t2 = time.time()\n\n #print(self.memory)\n\n # self.memory只是一个memory更新的方式,它并不是workspace吧!!! lm-workspace这篇代码是不是搞错了\n # 那这个 self.memory \n # 这里是对memory进行更新\n # 利用relational_memory 来对 workspace中的memory进行更新\n _,_, self.memory, out_hx_mem_new = self.relational_memory(\n inputs=key,\n memory=self.memory#.cuda(),\n )\n #print('time taken by relational:' + str(time.time() - t2))\n\n\n\n #query = query.transpose(1, 0)\n #if self.regressive:\n # B, T, D = query.size()\n # query = query.reshape(B * T, -1).unsqueeze(1)\n #out_hx_mem_new, _, _ = self.mem_att(\n # query,#.reshape((bsz, self.num_blocks_out, self.block_size_out)),\n # self.memory,\n # self.memory,\n # )\n\n #z = torch.zeros(self.memory.size(0) - memory.size(0), memory.size(1), memory.size(2)).to(memory.device)\n #memory = torch.cat((memory, z), dim = 0)\n #self.memory = self.memory + memory\n #print('time taken by shared mha:' + str(time.time() - t1))\n #if self.regressive:\n # out_hx_mem_new = out_hx_mem_new.squeeze(1)\n # out_hx_mem_new = out_hx_mem_new.reshape(B, T, -1)\n\n # 这里的memory实际上没啥用处了,emmm 我觉得\n return out_hx_mem_new.transpose(0, 1), memory, None\n \"\"\"\n\n tgt_len = memory.size(0)\n src_len = key.size(0)\n q_memory = self.q_proj_memory(memory)\n k = self.k_proj(key)\n v = self.v_proj(value)\n\n q_memory = (\n q_memory.contiguous()\n .view(memory.size(0), bsz * self.num_heads, self.head_dim)\n .transpose(0, 1)\n )\n\n k = (\n k.contiguous()\n .view(-1, bsz * self.num_heads, self.head_dim)\n .transpose(0, 1)\n )\n\n v = (\n v.contiguous()\n .view(-1, bsz * self.num_heads, self.head_dim)\n .transpose(0, 1)\n )\n\n \n\n attn_weights_1 = torch.bmm(q_memory, k.transpose(1, 2))\n\n if key_padding_mask is not None:\n # don't attend to padding symbols\n attn_weights_1 = attn_weights_1.view(bsz, self.num_heads, tgt_len, src_len)\n attn_weights_1 = attn_weights_1.masked_fill(\n key_padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool),\n float(\"-inf\")\n )\n\n attn_weights_float_1 = utils.softmax(\n attn_weights_1, dim=-1, onnx_trace=self.onnx_trace\n )\n attn_weights_1 = attn_weights_float_1.type_as(attn_weights_1)\n attn_probs_1 = self.dropout_module(attn_weights_1)\n\n assert v is not None\n memory = torch.bmm(attn_probs_1, v)\n\n memory = memory.permute(1, 0, 2)\n memory = memory.reshape(memory.size(0), bsz, self.num_heads, -1)\n memory = memory.reshape(memory.size(0), bsz, -1)\n\n\n\n q = self.q_proj(query)\n \n k_memory = self.k_proj_memory(memory)\n v_memory = self.v_proj_memory(memory)\n\n q = (\n q.contiguous()\n .view(src_len, bsz * self.num_heads, self.head_dim)\n .transpose(0, 1)\n )\n\n k_memory = (\n k.contiguous()\n .view(-1, bsz * self.num_heads, self.head_dim)\n .transpose(0, 1)\n )\n\n v_memory = (\n v.contiguous()\n .view(-1, bsz * self.num_heads, self.head_dim)\n .transpose(0, 1)\n )\n\n attn_weights_2 = torch.bmm(q, k_memory.transpose(1, 2))\n \n attn_weights_float_2 = utils.softmax(\n attn_weights_2, dim=-1, onnx_trace=self.onnx_trace\n )\n \n attn_weights_2 = attn_weights_float_2.type_as(attn_weights_2)\n attn_probs_2 = self.dropout_module(attn_weights_2)\n\n out = torch.bmm(attn_probs_2, v)\n out = out.transpose(0, 1).contiguous().view(src_len, bsz, embed_dim)\n return out, memory, None\n \"\"\"\n \n # 共享参数的时候,或者是共享memory attn的时候,\n def init_memory(self, bs, ts = None, device = None):\n if not self.regressive:\n self.memory = self.relational_memory.initial_state(bs).to(device)\n else:\n self.memory = self.relational_memory.initial_state(bs, ts).to(device)\n\n\n @staticmethod\n def _append_prev_key_padding_mask(\n key_padding_mask: Optional[Tensor],\n prev_key_padding_mask: Optional[Tensor],\n batch_size: int,\n src_len: int,\n static_kv: bool,\n ) -> Optional[Tensor]:\n # saved key padding masks have shape (bsz, seq_len)\n if prev_key_padding_mask is not None and static_kv:\n new_key_padding_mask = prev_key_padding_mask\n elif prev_key_padding_mask is not None and key_padding_mask is not None:\n new_key_padding_mask = torch.cat(\n [prev_key_padding_mask.float(), key_padding_mask.float()], dim=1\n )\n # During incremental decoding, as the padding token enters and\n # leaves the frame, there will be a time when prev or current\n # is None\n elif prev_key_padding_mask is not None:\n filler = torch.zeros(\n (batch_size, src_len - prev_key_padding_mask.size(1)),\n device=prev_key_padding_mask.device,\n )\n new_key_padding_mask = torch.cat(\n [prev_key_padding_mask.float(), filler.float()], dim=1\n )\n elif key_padding_mask is not None:\n filler = torch.zeros(\n (batch_size, src_len - key_padding_mask.size(1)),\n device=key_padding_mask.device,\n )\n new_key_padding_mask = torch.cat(\n [filler.float(), key_padding_mask.float()], dim=1\n )\n else:\n new_key_padding_mask = prev_key_padding_mask\n return new_key_padding_mask\n\n @torch.jit.export\n def reorder_incremental_state(\n self, incremental_state: Dict[str, Dict[str, Optional[Tensor]]], new_order: Tensor\n ):\n \"\"\"Reorder buffered internal state (for incremental generation).\"\"\"\n input_buffer = self._get_input_buffer(incremental_state)\n if input_buffer is not None:\n for k in input_buffer.keys():\n input_buffer_k = input_buffer[k]\n if input_buffer_k is not None:\n if self.encoder_decoder_attention and input_buffer_k.size(0) == new_order.size(0):\n break\n input_buffer[k] = input_buffer_k.index_select(0, new_order)\n incremental_state = self._set_input_buffer(incremental_state, input_buffer)\n return incremental_state\n\n def _get_input_buffer(\n self, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]]\n ) -> Dict[str, Optional[Tensor]]:\n result = self.get_incremental_state(incremental_state, \"attn_state\")\n if result is not None:\n return result\n else:\n empty_result: Dict[str, Optional[Tensor]] = {}\n return empty_result\n\n def _set_input_buffer(\n self,\n incremental_state: Dict[str, Dict[str, Optional[Tensor]]],\n buffer: Dict[str, Optional[Tensor]],\n ):\n return self.set_incremental_state(incremental_state, \"attn_state\", buffer)\n\n def apply_sparse_mask(attn_weights, tgt_len: int, src_len: int, bsz: int):\n return attn_weights\n\n def upgrade_state_dict_named(self, state_dict, name):\n prefix = name + \".\" if name != \"\" else \"\"\n items_to_add = {}\n keys_to_remove = []\n for k in state_dict.keys():\n if k.endswith(prefix + \"in_proj_weight\"):\n # in_proj_weight used to be q + k + v with same dimensions\n dim = int(state_dict[k].shape[0] / 3)\n items_to_add[prefix + \"q_proj.weight\"] = state_dict[k][:dim]\n items_to_add[prefix + \"k_proj.weight\"] = state_dict[k][dim : 2 * dim]\n items_to_add[prefix + \"v_proj.weight\"] = state_dict[k][2 * dim :]\n\n keys_to_remove.append(k)\n\n k_bias = prefix + \"in_proj_bias\"\n if k_bias in state_dict.keys():\n dim = int(state_dict[k].shape[0] / 3)\n items_to_add[prefix + \"q_proj.bias\"] = state_dict[k_bias][:dim]\n items_to_add[prefix + \"k_proj.bias\"] = state_dict[k_bias][\n dim : 2 * dim\n ]\n items_to_add[prefix + \"v_proj.bias\"] = state_dict[k_bias][2 * dim :]\n\n keys_to_remove.append(prefix + \"in_proj_bias\")\n\n for k in keys_to_remove:\n del state_dict[k]\n\n for key, value in items_to_add.items():\n state_dict[key] = value" }, { "identifier": "RelationalMemory", "path": "multi_part_assembly/utils/wx_transformer_utilities/relational_memory.py", "snippet": "class RelationalMemory(nn.Module):\n \"\"\"\n Constructs a `RelationalMemory` object.\n This class is same as the RMC from relational_rnn_models.py, but without language modeling-specific variables.\n Args:\n mem_slots: The total number of memory slots to use.\n head_size: The size of an attention head.\n input_size: The size of input per step. i.e. the dimension of each input vector\n num_heads: The number of attention heads to use. Defaults to 1.\n num_blocks: Number of times to compute attention per time step. Defaults\n to 1.\n forget_bias: Bias to use for the forget gate, assuming we are using\n some form of gating. Defaults to 1.\n input_bias: Bias to use for the input gate, assuming we are using\n some form of gating. Defaults to 0.\n gate_style: Whether to use per-element gating ('unit'),\n per-memory slot gating ('memory'), or no gating at all (None).\n Defaults to `unit`.\n attention_mlp_layers: Number of layers to use in the post-attention\n MLP. Defaults to 2.\n key_size: Size of vector to use for key & query vectors in the attention\n computation. Defaults to None, in which case we use `head_size`.\n name: Name of the module.\n\n # NEW flag for this class\n return_all_outputs: Whether the model returns outputs for each step (like seq2seq) or only the final output.\n Raises:\n ValueError: gate_style not one of [None, 'memory', 'unit'].\n ValueError: num_blocks is < 1.\n ValueError: attention_mlp_layers is < 1.\n \"\"\"\n\n def __init__(self, mem_slots, head_size, input_size, output_size, num_heads=1, num_blocks=1, forget_bias=1., input_bias=0.,\n gate_style='unit', attention_mlp_layers=2, key_size=None, return_all_outputs=False, use_topk = False, topk = 3, num_steps = 5,\n null_attention = False):\n super(RelationalMemory, self).__init__()\n\n ########## generic parameters for RMC ##########\n self.mem_slots = mem_slots\n self.head_size = head_size\n self.num_heads = num_heads\n self.mem_size = self.head_size * self.num_heads\n self.use_topk = use_topk\n self.topk = topk\n self.attn_log = None\n\n # a new fixed params needed for pytorch port of RMC\n # +1 is the concatenated input per time step : we do self-attention with the concatenated memory & input\n # so if the mem_slots = 1, this value is 2\n self.mem_slots_plus_input = self.mem_slots + 1\n\n if num_blocks < 1:\n raise ValueError('num_blocks must be >=1. Got: {}.'.format(num_blocks))\n self.num_blocks = num_blocks\n\n if gate_style not in ['unit', 'memory', None]:\n raise ValueError(\n 'gate_style must be one of [\\'unit\\', \\'memory\\', None]. got: '\n '{}.'.format(gate_style))\n self.gate_style = gate_style\n\n if attention_mlp_layers < 1:\n raise ValueError('attention_mlp_layers must be >= 1. Got: {}.'.format(\n attention_mlp_layers))\n self.attention_mlp_layers = attention_mlp_layers\n\n self.key_size = key_size if key_size else self.head_size\n\n ########## parameters for multihead attention ##########\n # value_size is same as head_size\n self.value_size = self.head_size\n # total size for query-key-value\n self.qkv_size = 2 * self.key_size + self.value_size\n self.total_qkv_size = self.qkv_size * self.num_heads # denoted as F\n\n self.query_proj = nn.Linear(self.mem_size, self.key_size * self.num_heads)\n self.key_proj = nn.Linear(self.mem_size, self.key_size * self.num_heads)\n self.value_proj = nn.Linear(self.mem_size, self.value_size * self.num_heads)\n\n\n # each head has qkv_sized linear projector\n # just using one big param is more efficient, rather than this line\n # self.qkv_projector = [nn.Parameter(torch.randn((self.qkv_size, self.qkv_size))) for _ in range(self.num_heads)]\n self.qkv_projector = nn.Linear(self.mem_size, self.total_qkv_size)\n self.qkv_layernorm = nn.LayerNorm(self.total_qkv_size)\n\n # used for attend_over_memory function\n self.attention_mlp = nn.ModuleList([nn.Linear(self.mem_size, self.mem_size)] * self.attention_mlp_layers)\n self.attended_memory_layernorm = nn.LayerNorm( self.mem_size)\n self.attended_memory_layernorm2 = nn.LayerNorm(self.mem_size)\n\n ########## parameters for initial embedded input projection ##########\n self.input_size = input_size\n self.input_projector = nn.Linear(self.input_size, self.mem_size)\n\n self.output_projector = nn.Linear(self.output_size, self.input_size)\n\n ########## parameters for gating ##########\n self.num_gates = 2 * self.calculate_gate_size()\n print('input projector:'+str(self.mem_size))\n self.input_gate_projector = nn.Linear(self.mem_size * num_steps, self.num_gates)\n self.memory_gate_projector = nn.Linear(self.mem_size, self.num_gates)\n # trainable scalar gate bias tensors\n self.forget_bias = nn.Parameter(torch.tensor(forget_bias, dtype=torch.float32))\n self.input_bias = nn.Parameter(torch.tensor(input_bias, dtype=torch.float32))\n\n ########## number of outputs returned #####\n self.return_all_outputs = return_all_outputs\n\n self.null_attention = null_attention\n\n self.competition_mlp = nn.Sequential(nn.Linear(self.mem_slots * self.mem_size + self.mem_size, 256),\n nn.ReLU(),\n nn.Linear(256, 256),\n nn.ReLU(),\n nn.Linear(256, 256),\n nn.ReLU(),\n nn.Linear(256, 2))\n\n def repackage_hidden(self, h):\n \"\"\"Wraps hidden states in new Tensors, to detach them from their history.\"\"\"\n # needed for truncated BPTT, called at every batch forward pass\n if isinstance(h, torch.Tensor):\n return h.detach()\n else:\n return tuple(self.repackage_hidden(v) for v in h)\n\n def initial_state(self, batch_size, trainable=False):\n \"\"\"\n Creates the initial memory.\n We should ensure each row of the memory is initialized to be unique,\n so initialize the matrix to be the identity. We then pad or truncate\n as necessary so that init_state is of size\n (batch_size, self.mem_slots, self.mem_size).\n Args:\n batch_size: The size of the batch.\n trainable: Whether the initial state is trainable. This is always True.\n Returns:\n init_state: A truncated or padded matrix of size\n (batch_size, self.mem_slots, self.mem_size).\n \"\"\"\n init_state = torch.stack([torch.eye(self.mem_slots) for _ in range(batch_size)])\n\n # pad the matrix with zeros\n if self.mem_size > self.mem_slots:\n difference = self.mem_size - self.mem_slots\n pad = torch.zeros((batch_size, self.mem_slots, difference))\n init_state = torch.cat([init_state, pad], -1)\n\n # truncation. take the first 'self.mem_size' components\n elif self.mem_size < self.mem_slots:\n init_state = init_state[:, :, :self.mem_size]\n\n return init_state\n\n def multihead_attention(self, input, memory):\n \"\"\"\n Perform multi-head attention from 'Attention is All You Need'.\n Implementation of the attention mechanism from\n https://arxiv.org/abs/1706.03762.\n Args:\n memory: Memory tensor to perform attention on.\n Returns:\n new_memory: New memory tensor.\n \"\"\"\n\n q = self.query_proj(memory)\n k = self.key_proj(input)\n v = self.value_proj(input)\n\n q = q.reshape(q.size(0), q.size(1), self.num_heads, -1).permute(0, 2, 1, 3)\n k = k.reshape(k.size(0), k.size(1), self.num_heads, -1).permute(0, 2, 1, 3)\n v = v.reshape(v.size(0), v.size(1), self.num_heads, -1).permute(0, 2, 1, 3)\n scores = torch.matmul(q, k.transpose(2, 3))\n\n scores = torch.softmax(scores, dim = -1)\n self.attn_log = scores[0]\n if not self.null_attention:\n if self.use_topk:\n topk = torch.topk(scores, dim = -1, k = self.topk)\n mask = torch.zeros(scores.size()).to(scores.device)\n mask.scatter_(3, topk.indices, 1)\n scores = scores * mask\n else:\n memory_flat = memory.reshape(memory.size(0), -1).unsqueeze(1)\n memory_flat = memory_flat.repeat(1, input.shape[1], 1)\n\n N = torch.cat((input, memory_flat), dim = 2)\n N = self.competition_mlp(N)\n\n N = torch.nn.functional.gumbel_softmax(N, dim = 2, hard = True, tau = 0.5)\n\n N = N[:, :, 0]\n\n scores = scores * N.unsqueeze(1).unsqueeze(1)\n\n\n output = torch.matmul(scores, v)\n\n \"\"\"#print(memory.size())\n # First, a simple linear projection is used to construct queries\n qkv = self.qkv_projector(memory)\n # apply layernorm for every dim except the batch dim\n qkv = self.qkv_layernorm(qkv)\n\n # mem_slots needs to be dynamically computed since mem_slots got concatenated with inputs\n # example: self.mem_slots=10 and seq_length is 3, and then mem_slots is 10 + 1 = 11 for each 3 step forward pass\n # this is the same as self.mem_slots_plus_input, but defined to keep the sonnet implementation code style\n mem_slots = memory.shape[1] # denoted as N\n\n # split the qkv to multiple heads H\n # [B, N, F] => [B, N, H, F/H]\n qkv_reshape = qkv.view(qkv.shape[0], mem_slots, self.num_heads, self.qkv_size)\n\n # [B, N, H, F/H] => [B, H, N, F/H]\n qkv_transpose = qkv_reshape.permute(0, 2, 1, 3)\n\n # [B, H, N, key_size], [B, H, N, key_size], [B, H, N, value_size]\n q, k, v = torch.split(qkv_transpose, [self.key_size, self.key_size, self.value_size], -1)\n\n # scale q with d_k, the dimensionality of the key vectors\n q *= (self.key_size ** -0.5)\n\n # make it [B, H, N, N]\n dot_product = torch.matmul(q, k.permute(0, 1, 3, 2))\n weights = F.softmax(dot_product, dim=-1)\n\n if self.use_topk:\n topk = torch.topk(weights, dim = -1, k = self.topk)\n mask = torch.zeros(weights.size()).to(weights.device)\n mask.scatter_(3, topk.indices, 1)\n weights = weights * mask\n\n # output is [B, H, N, V]\n output = torch.matmul(weights, v)\"\"\"\n\n # [B, H, N, V] => [B, N, H, V] => [B, N, H*V]\n output_transpose = output.permute(0, 2, 1, 3).contiguous()\n new_memory = output_transpose.view((output_transpose.shape[0], output_transpose.shape[1], -1))\n\n return new_memory\n\n\n @property\n def state_size(self):\n return [self.mem_slots, self.mem_size]\n\n @property\n def output_size(self):\n return self.mem_slots * self.mem_size\n\n def calculate_gate_size(self):\n \"\"\"\n Calculate the gate size from the gate_style.\n Returns:\n The per sample, per head parameter size of each gate.\n \"\"\"\n if self.gate_style == 'unit':\n return self.mem_size\n elif self.gate_style == 'memory':\n return 1\n else: # self.gate_style == None\n return 0\n\n def print_log(self):\n print(self.attn_log)\n\n def create_gates(self, inputs, memory):\n \"\"\"\n Create input and forget gates for this step using `inputs` and `memory`.\n Args:\n inputs: Tensor input.\n memory: The current state of memory.\n Returns:\n input_gate: A LSTM-like insert gate.\n forget_gate: A LSTM-like forget gate.\n \"\"\"\n # We'll create the input and forget gates at once. Hence, calculate double\n # the gate size.\n\n # equation 8: since there is no output gate, h is just a tanh'ed m\n memory = torch.tanh(memory)\n\n # TODO: check this input flattening is correct\n # sonnet uses this, but i think it assumes time step of 1 for all cases\n # if inputs is (B, T, features) where T > 1, this gets incorrect\n # inputs = inputs.view(inputs.shape[0], -1)\n\n # fixed implementation\n if len(inputs.shape) == 3:\n #if inputs.shape[1] > 1:\n # raise ValueError(\n # \"input seq length is larger than 1. create_gate function is meant to be called for each step, with input seq length of 1\")\n inputs = inputs.view(inputs.shape[0], -1)\n # matmul for equation 4 and 5\n # there is no output gate, so equation 6 is not implemented\n gate_inputs = self.input_gate_projector(inputs)\n gate_inputs = gate_inputs.unsqueeze(dim=1)\n gate_memory = self.memory_gate_projector(memory)\n else:\n raise ValueError(\"input shape of create_gate function is 2, expects 3\")\n\n # this completes the equation 4 and 5\n #print(gate_inputs.size())\n #print(gate_memory.size())\n gates = gate_memory + gate_inputs\n gates = torch.split(gates, split_size_or_sections=int(gates.shape[2] / 2), dim=2)\n input_gate, forget_gate = gates\n assert input_gate.shape[2] == forget_gate.shape[2]\n\n # to be used for equation 7\n input_gate = torch.sigmoid(input_gate + self.input_bias)\n forget_gate = torch.sigmoid(forget_gate + self.forget_bias)\n\n return input_gate, forget_gate\n\n def attend_over_memory(self, inputs, memory):\n \"\"\"\n Perform multiheaded attention over `memory`.\n Args:\n memory: Current relational memory.\n Returns:\n The attended-over memory.\n \"\"\"\n for _ in range(self.num_blocks):\n attended_memory = self.multihead_attention(inputs, memory)\n\n # Add a skip connection to the multiheaded attention's input.\n memory = self.attended_memory_layernorm(memory + attended_memory)\n\n # add a skip connection to the attention_mlp's input.\n attention_mlp = memory\n for i, l in enumerate(self.attention_mlp):\n attention_mlp = self.attention_mlp[i](attention_mlp)\n attention_mlp = F.relu(attention_mlp)\n memory = self.multihead_attention(memory, memory, use_topk_ = False, store_log = False)\n memory = self.attended_memory_layernorm2(memory + attention_mlp)\n\n return memory\n\n def forward_step(self, inputs, memory, treat_input_as_matrix=False):\n \"\"\"\n Forward step of the relational memory core.\n Args:\n inputs: Tensor input.\n memory: Memory output from the previous time step.\n treat_input_as_matrix: Optional, whether to treat `input` as a sequence\n of matrices. Default to False, in which case the input is flattened\n into a vector.\n Returns:\n output: This time step's output.\n next_memory: The next version of memory to use.\n \"\"\"\n\n if treat_input_as_matrix:\n # keep (Batch, Seq, ...) dim (0, 1), flatten starting from dim 2\n inputs = inputs.view(inputs.shape[0], inputs.shape[1], -1)\n # apply linear layer for dim 2\n inputs_reshape = self.input_projector(inputs)\n else:\n # keep (Batch, ...) dim (0), flatten starting from dim 1\n inputs = inputs.view(inputs.shape[0], -1)\n # apply linear layer for dim 1\n inputs = self.input_projector(inputs)\n # unsqueeze the time step to dim 1\n inputs_reshape = inputs.unsqueeze(dim=1)\n\n #memory_plus_input = torch.cat([memory, inputs_reshape], dim=1)\n #print(memory_plus_input.size())\n next_memory = self.attend_over_memory(inputs_reshape, memory)\n\n # cut out the concatenated input vectors from the original memory slots\n #n = inputs_reshape.shape[1]\n #next_memory = next_memory[:, :-n, :]\n\n if self.gate_style == 'unit' or self.gate_style == 'memory':\n # these gates are sigmoid-applied ones for equation 7\n input_gate, forget_gate = self.create_gates(inputs_reshape, memory)\n # equation 7 calculation\n next_memory = input_gate * torch.tanh(next_memory)\n next_memory += forget_gate * memory\n\n\n output = next_memory.view(next_memory.shape[0], -1)\n return output, next_memory\n\n def forward(self, inputs, memory, parallel = True):\n # Starting each batch, we detach the hidden state from how it was previously produced.\n # If we didn't, the model would try backpropagating all the way to start of the dataset.\n # memory = self.repackage_hidden(memory)\n\n # for loop implementation of (entire) recurrent forward pass of the model\n # inputs is batch first [batch, seq], and output logit per step is [batch, vocab]\n # so the concatenated logits are [seq * batch, vocab]\n\n # targets are flattened [seq, batch] => [seq * batch], so the dimension is correct\n\n logits = []\n #print(inputs.size())\n #print(memory.size())\n #memory = self.repackage_hidden(memory)\n # shape[1] is seq_lenth T\n if not parallel:\n for idx_step in range(inputs.shape[1]):\n logit, memory = self.forward_step(inputs[:, idx_step], memory)\n logits.append(logit)\n logits = torch.cat(logits)\n else:\n logits, memory = self.forward_step(inputs, memory, treat_input_as_matrix = True)\n \n memory_out = self.output_projector(memory.view(memory.shape[0], -1))\n\n #print(inputs.size())\n #print(memory_out.size())\n #print('------')\n if self.return_all_outputs:\n return logits, memory_out , memory\n else:\n return logits, memory_out, memory" }, { "identifier": "GroupLinearLayer", "path": "multi_part_assembly/utils/wx_transformer_utilities/group_linear_layer.py", "snippet": "class GroupLinearLayer(nn.Module):\n\n def __init__(self, din, dout, num_blocks, bias=True, a = None):\n super(GroupLinearLayer, self).__init__()\n self.nb = num_blocks\n self.dout = dout\n\n if a is None:\n a = 1. / math.sqrt(dout * num_blocks)\n\n #gain = 1.0 / math.sqrt(2)\n #a = gain * math.sqrt(6.0 / (din + dout))\n\n self.weight = nn.Parameter(torch.FloatTensor(num_blocks,din,dout).uniform_(-a,a))\n\n self.bias = bias\n\n if bias is True:\n self.bias = nn.Parameter(torch.FloatTensor(num_blocks,dout).uniform_(-a,a))\n #self.bias = nn.Parameter(torch.zeros(dout*num_blocks))\n else:\n self.bias = None\n\n def forward(self,x):\n\n\t#input: ts x bs x blocks*nhid\n\t#ts*bs , blocks, nhid\n\t#blocks, ts*bs, nhid\n ts,bs,m = x.shape\t\n\n x = x.reshape((ts*bs, self.nb, m//self.nb))\n x = x.permute(1,0,2)\n x = torch.bmm(x,self.weight)\n x = x.permute(1,0,2)\n \n if not self.bias is None:\n x = x + self.bias\n\n x = x.reshape((ts, bs, self.dout*self.nb))\n \n #if not self.bias is None:\n # x += self.bias\n\n return x" }, { "identifier": "MemoryAttention", "path": "multi_part_assembly/utils/wx_transformer_utilities/basic_mha.py", "snippet": "class MemoryAttention(nn.Module):\n def __init__(self, n_blocks_query, n_blocks_val, dim_query, dim_val, n_heads=8):\n super(MemoryAttention, self).__init__()\n\n self.n_heads = n_heads\n self.n_blocks_val = n_blocks_val\n self.dim_val = dim_val\n self.block_dim_val = dim_val // self.n_blocks_val\n\n self.n_blocks_query = n_blocks_query\n self.dim_query = dim_query\n self.block_dim_query = dim_query // self.n_blocks_query\n\n self.head_dim = 64\n self.scale = self.head_dim ** -0.5\n\n #self.n_blocks_val * self.block_dim_val\n\n self.query_net = GroupLinearLayer(self.block_dim_query, self.head_dim * self.n_heads, n_blocks_query)\n self.key_net = GroupLinearLayer(self.block_dim_val, self.head_dim * self.n_heads, n_blocks_val)\n self.value_net = GroupLinearLayer(self.block_dim_val, self.head_dim * self.n_heads, n_blocks_val)\n self.final = GroupLinearLayer(self.head_dim * self.n_heads, self.block_dim_query, n_blocks_query)\n\n def forward(self, q, kv):\n\n #comes in as: bs, pos*emb.\n #positions_attend x T*bs x emb\n\n\n #q = q.permute(1,0,2)\n #kv = kv.permute(1,0,2)\n\n #print('kv shape after permute', kv.shape)\n\n seq_len_q,bsz,_ = q.shape\n seq_len_v,bsz,_ = kv.shape\n\n q = q.reshape((seq_len_q, bsz, self.n_blocks_query * self.block_dim_query))\n\n kv = kv.reshape((seq_len_v, bsz, self.n_blocks_val * self.block_dim_val))\n\n q = self.query_net(q).view(seq_len_q, bsz, self.n_blocks_query, self.n_heads, self.head_dim)\n k = self.key_net(kv).view(seq_len_v, bsz, self.n_blocks_val, self.n_heads, self.head_dim)\n v = self.value_net(kv).view(seq_len_v, bsz, self.n_blocks_val, self.n_heads, self.head_dim)\n\n q = q.transpose(2,3) * self.scale\n k = k.transpose(2,3)\n v = v.transpose(2,3)\n score = torch.matmul(q, k.transpose(3,4))\n #print('score shape', score.shape)\n score = F.softmax(score, dim=-1)\n out = torch.matmul(score, v).transpose(2,3)\n #print('out shape', out.shape)\n score = score.mean(dim=2)\n\n out = out.reshape(seq_len_q, bsz, self.n_blocks_query * self.head_dim * self.n_heads)\n out = self.final(out)\n out = out.view(seq_len_q, bsz, self.dim_query)\n\n\n return out, score" }, { "identifier": "quant_noise", "path": "multi_part_assembly/utils/wx_transformer_utilities/quant_noise.py", "snippet": "def quant_noise(module, p, block_size):\n \"\"\"\n Wraps modules and applies quantization noise to the weights for\n subsequent quantization with Iterative Product Quantization as\n described in \"Training with Quantization Noise for Extreme Model Compression\"\n\n Args:\n - module: nn.Module\n - p: amount of Quantization Noise\n - block_size: size of the blocks for subsequent quantization with iPQ\n\n Remarks:\n - Module weights must have the right sizes wrt the block size\n - Only Linear, Embedding and Conv2d modules are supported for the moment\n - For more detail on how to quantize by blocks with convolutional weights,\n see \"And the Bit Goes Down: Revisiting the Quantization of Neural Networks\"\n - We implement the simplest form of noise here as stated in the paper\n which consists in randomly dropping blocks\n \"\"\"\n\n # if no quantization noise, don't register hook\n if p <= 0:\n return module\n\n # supported modules\n assert isinstance(module, (nn.Linear, nn.Embedding, nn.Conv2d))\n\n # test whether module.weight has the right sizes wrt block_size\n is_conv = module.weight.ndim == 4\n\n # 2D matrix\n if not is_conv:\n assert module.weight.size(1) % block_size == 0, \"Input features must be a multiple of block sizes\"\n\n # 4D matrix\n else:\n # 1x1 convolutions\n if module.kernel_size == (1, 1):\n assert module.in_channels % block_size == 0, \"Input channels must be a multiple of block sizes\"\n # regular convolutions\n else:\n k = module.kernel_size[0] * module.kernel_size[1]\n assert k % block_size == 0, \"Kernel size must be a multiple of block size\"\n\n def _forward_pre_hook(mod, input):\n # no noise for evaluation\n if mod.training:\n if not is_conv:\n # gather weight and sizes\n weight = mod.weight\n in_features = weight.size(1)\n out_features = weight.size(0)\n\n # split weight matrix into blocks and randomly drop selected blocks\n mask = torch.zeros(in_features // block_size * out_features, device=weight.device)\n mask.bernoulli_(p)\n mask = mask.repeat_interleave(block_size, -1).view(-1, in_features)\n\n else:\n # gather weight and sizes\n weight = mod.weight\n in_channels = mod.in_channels\n out_channels = mod.out_channels\n\n # split weight matrix into blocks and randomly drop selected blocks\n if mod.kernel_size == (1, 1):\n mask = torch.zeros(int(in_channels // block_size * out_channels), device=weight.device)\n mask.bernoulli_(p)\n mask = mask.repeat_interleave(block_size, -1).view(-1, in_channels)\n else:\n mask = torch.zeros(weight.size(0), weight.size(1), device=weight.device)\n mask.bernoulli_(p)\n mask = mask.unsqueeze(2).unsqueeze(3).repeat(1, 1, mod.kernel_size[0], mod.kernel_size[1])\n\n # scale weights and apply mask\n mask = mask.to(torch.bool) # x.bool() is not currently supported in TorchScript\n s = 1 / (1 - p)\n mod.weight.data = s * weight.masked_fill(mask, 0)\n\n module.register_forward_pre_hook(_forward_pre_hook)\n return module" }, { "identifier": "FairseqDropout", "path": "multi_part_assembly/utils/wx_transformer_utilities/fairseq_dropout.py", "snippet": "class FairseqDropout(nn.Module):\n\n def __init__(self, p, module_name=None):\n super().__init__()\n self.p = p\n self.module_name = module_name\n self.apply_during_inference = False\n\n def forward(self, x, inplace: bool = False):\n if self.training or self.apply_during_inference:\n return F.dropout(x, p=self.p, training=True, inplace=inplace)\n else:\n return x\n\n def make_generation_fast_(\n self,\n name: str,\n retain_dropout: bool = False,\n retain_dropout_modules: Optional[List[str]] = None,\n **kwargs\n ):\n if retain_dropout:\n if retain_dropout_modules is not None and self.module_name is None:\n logger.warning(\n 'Cannot enable dropout during inference for module {} '\n 'because module_name was not set'.format(name)\n )\n elif (\n retain_dropout_modules is None # if None, apply to all modules\n or self.module_name in retain_dropout_modules\n ):\n logger.info(\n 'Enabling dropout during inference for module: {}'.format(name)\n )\n self.apply_during_inference = True\n else:\n logger.info('Disabling dropout for module: {}'.format(name))" } ]
from typing import Dict, List, Optional from .layer_norm import LayerNorm from .multihead_attention import MultiheadAttention from .relational_memory import RelationalMemory from .group_linear_layer import GroupLinearLayer from .basic_mha import MemoryAttention from .quant_noise import quant_noise from .fairseq_dropout import FairseqDropout from torch import Tensor import torch import torch.nn as nn import multi_part_assembly.utils.wx_transformer_utilities.fairseq_utils as utils import random import torch.nn.functional as F
17,997
#print('len qlst', len(qlst)) #for kval in klst: # print(kval.shape) k = torch.cat(klst, dim=3) v = torch.cat(vlst, dim=3) #should return these q,k,v and save to a big list. Also pull in from the list passed in and concat along dim=3, i.e. so that it's nblocks * nlayers. #print('running comm attention with shapes', q.shape, k.shape, v.shape) score = torch.matmul(q, k.transpose(3,4)) #print('score shape', score.shape) score = F.softmax(score, dim=-1) out = torch.matmul(score, v).transpose(2,3) #print('out shape', out.shape) score = score.mean(dim=2) out = out.reshape(seq_len, bsz, self.n_blocks * self.head_dim * self.n_heads) out = self.final(out) out = out.view(seq_len, bsz, self.dim) return out, score class NormLayer(nn.Module): def __init__(self, num_rims, dim, export=False): super(NormLayer, self).__init__() self.num_rims = num_rims self.dim = dim self.weight = nn.Parameter(torch.ones(1,1,dim*num_rims,)) self.bias = nn.Parameter(torch.zeros(1,1,dim*num_rims,)) self.norm = LayerNorm(dim, export=export, elementwise_affine=False) def forward(self, x): seq_len, bsz, _ = x.shape x = x.view(seq_len, bsz, self.num_rims, self.dim) x = self.norm(x) x = x.view(seq_len, bsz, self.num_rims * self.dim) weight_use = self.weight.repeat(seq_len, bsz, 1) bias_use = self.bias.repeat(seq_len, bsz, 1) x = x * weight_use + bias_use return x class TransformerEncoderLayer(nn.Module): """Encoder layer block. In the original paper each operation (multi-head attention or FFN) is postprocessed with: `dropout -> add residual -> layernorm`. In the tensor2tensor code they suggest that learning is more robust when preprocessing each layer with layernorm and postprocessing with: `dropout -> add residual`. We default to the approach in the paper, but the tensor2tensor approach can be enabled by setting *args.encoder_normalize_before* to ``True``. Args: args (argparse.Namespace): parsed command-line arguments """ def __init__(self, args, nb, blockatt, blockatt_memory, use_nfm, out_proj_dim=None): super().__init__() self.blockatt = blockatt self.blockatt_memory = blockatt_memory self.embed_dim = args.encoder_embed_dim self.quant_noise = getattr(args, "quant_noise_pq", 0) self.quant_noise_block_size = getattr(args, "quant_noise_pq_block_size", 8) self.use_nfm = use_nfm print('using nfm?', self.use_nfm) self.nb = nb self.norm_blocks = self.nb self.self_attn = self.build_self_attention(self.embed_dim, args) #should divide embed_dim by nb. Then raise embed_dim in args self.self_attn_layer_norm = NormLayer(self.norm_blocks, self.embed_dim // self.norm_blocks) self.dropout_module = FairseqDropout(args.dropout, module_name=self.__class__.__name__) self.activation_fn = utils.get_activation_fn( activation=getattr(args, "activation_fn", "relu") ) print("SETUP TRANSFORMER LAYER", 'blocks', self.nb) activation_dropout_p = getattr(args, "activation_dropout", 0) if activation_dropout_p == 0: # for backwards compatibility with models that use args.relu_dropout activation_dropout_p = getattr(args, "relu_dropout", 0) self.activation_dropout_module = FairseqDropout( float(activation_dropout_p), module_name=self.__class__.__name__ ) self.normalize_before = args.encoder_normalize_before self.fc1 = self.build_fc1( self.embed_dim, args.encoder_ffn_embed_dim, self.quant_noise, self.quant_noise_block_size ) self.fc2 = self.build_fc2( args.encoder_ffn_embed_dim, self.embed_dim, self.quant_noise, self.quant_noise_block_size ) self.final_layer_norm = NormLayer(self.norm_blocks, self.embed_dim // self.norm_blocks) if self.blockatt: self.comm = Attention(args.encoder_attention_heads, self.nb, self.embed_dim, self.use_nfm) self.comm_norm = NormLayer(self.norm_blocks, self.embed_dim // self.norm_blocks) if self.blockatt_memory: memory_slots = 4 memory_head_size = 128 memory_num_heads = 1 gate_style = 'memory' print('not using special key size gate_style is', gate_style, memory_slots, memory_num_heads, memory_head_size)
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. #from fairseq.modules.shared_group_linear_layer import SharedGroupLinearLayer class TransformerEncoderLayerVanilla(nn.Module): """Encoder layer block. In the original paper each operation (multi-head attention or FFN) is postprocessed with: `dropout -> add residual -> layernorm`. In the tensor2tensor code they suggest that learning is more robust when preprocessing each layer with layernorm and postprocessing with: `dropout -> add residual`. We default to the approach in the paper, but the tensor2tensor approach can be enabled by setting *args.encoder_normalize_before* to ``True``. Args: args (argparse.Namespace): parsed command-line arguments """ def __init__(self, args, out_proj = None): super().__init__() self.embed_dim = args.encoder_embed_dim self.self_attn = self.build_self_attention(self.embed_dim, args) self.self_attn_layer_norm = LayerNorm(self.embed_dim, eps=1e-5) self.dropout = args.dropout self.activation_fn = utils.get_activation_fn( activation=getattr(args, "activation_fn", "relu") ) self.activation_dropout = getattr(args, "activation_dropout", 0) if self.activation_dropout == 0: # for backwards compatibility with models that use args.relu_dropout self.activation_dropout = getattr(args, "relu_dropout", 0) self.normalize_before = args.encoder_normalize_before self.fc1 = self.build_fc1(self.embed_dim, args.encoder_ffn_embed_dim) self.fc2 = self.build_fc2(args.encoder_ffn_embed_dim, self.embed_dim) self.final_layer_norm = LayerNorm(self.embed_dim, eps=1e-5) if out_proj is not None: self.final_linear = nn.Linear(args.encoder_embed_dim, out_proj) else: self.final_linear = None def build_fc1(self, input_dim, output_dim): return nn.Linear(input_dim, output_dim) def build_fc2(self, input_dim, output_dim): return nn.Linear(input_dim, output_dim) def build_self_attention(self, embed_dim, args): return MultiheadAttention( embed_dim, args.encoder_attention_heads, dropout=args.attention_dropout, self_attention=args.self_attention, shared_memory_attention = args.shared_memory_attention, use_topk = args.use_topk, topk = args.topk, num_steps = args.num_steps, mem_slots = args.mem_slots, null_attention = args.null_attention, regressive = args.regressive ) def upgrade_state_dict_named(self, state_dict, name): """ Rename layer norm states from `...layer_norms.0.weight` to `...self_attn_layer_norm.weight` and `...layer_norms.1.weight` to `...final_layer_norm.weight` """ layer_norm_map = {"0": "self_attn_layer_norm", "1": "final_layer_norm"} for old, new in layer_norm_map.items(): for m in ("weight", "bias"): k = "{}.layer_norms.{}.{}".format(name, old, m) if k in state_dict: state_dict["{}.{}.{}".format(name, new, m)] = state_dict[k] del state_dict[k] def forward(self, x, encoder_padding_mask, attn_mask: Optional[Tensor] = None, state = None, memory = None): """ Args: x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)` encoder_padding_mask (ByteTensor): binary ByteTensor of shape `(batch, src_len)` where padding elements are indicated by ``1``. attn_mask (ByteTensor): binary tensor of shape (T_tgt, T_src), where T_tgt is the length of query, while T_src is the length of key, though here both query and key is x here, attn_mask[t_tgt, t_src] = 1 means when calculating embedding for t_tgt, t_src is excluded (or masked out), =0 means it is included in attention Returns: encoded output of shape `(seq_len, batch, embed_dim)` """ residual = x if self.normalize_before: x = self.self_attn_layer_norm(x) if attn_mask is not None: attn_mask = attn_mask.masked_fill(attn_mask.to(torch.bool), -1e8) # anything in original attn_mask = 1, becomes -1e8 # anything in original attn_mask = 0, becomes 0 # Note that we cannot use -inf here, because at some edge cases, # the attention weight (before softmax) for some padded element in query # will become -inf, which results in NaN in model parameters # TODO: to formally solve this problem, we need to change fairseq's # MultiheadAttention. We will do this later on. #print(state is not None) x, memory, _ = self.self_attn( query=state if state is not None else x, key=x, value=x, key_padding_mask=encoder_padding_mask, attn_mask=attn_mask, memory = memory ) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + x if not self.normalize_before: x = self.self_attn_layer_norm(x) residual = x if self.normalize_before: x = self.final_layer_norm(x) x = self.activation_fn(self.fc1(x)) x = F.dropout(x, p=float(self.activation_dropout), training=self.training) x = self.fc2(x) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + x if not self.normalize_before: x = self.final_layer_norm(x) if self.final_linear is not None: x = self.final_linear(x) return x, memory class Attention(nn.Module): def __init__(self, n_heads, n_blocks, dim, use_nfm): super(Attention, self).__init__() self.use_nfm = use_nfm #self.n_heads = n_heads self.n_heads = 12 self.n_blocks = n_blocks self.dim = dim self.block_dim = dim // self.n_blocks #self.head_dim = self.block_dim // self.n_heads self.head_dim = 64 self.scale = self.head_dim ** -0.5 self.query_net = GroupLinearLayer(self.block_dim, self.head_dim * self.n_heads, n_blocks) self.key_net = GroupLinearLayer(self.block_dim, self.head_dim * self.n_heads, n_blocks) self.value_net = GroupLinearLayer(self.block_dim, self.head_dim * self.n_heads, n_blocks) self.final = GroupLinearLayer(self.head_dim * self.n_heads, self.block_dim, n_blocks) def forward(self, x, qkv=None): use_exshare = False if qkv is not None: klst, vlst = qkv seq_len, bsz, _ = x.shape if use_exshare: x = x.view(seq_len, bsz, self.n_blocks * self.block_dim) q = self.query_net(x).view(seq_len, 1, bsz*self.n_blocks, self.n_heads, self.head_dim) k = self.key_net(x).view(seq_len, 1, bsz*self.n_blocks, self.n_heads, self.head_dim) v = self.value_net(x).view(seq_len, 1, bsz*self.n_blocks, self.n_heads, self.head_dim) else: x = x.view(seq_len, bsz, self.n_blocks * self.block_dim) q = self.query_net(x).view(seq_len, bsz, self.n_blocks, self.n_heads, self.head_dim) k = self.key_net(x).view(seq_len, bsz, self.n_blocks, self.n_heads, self.head_dim) v = self.value_net(x).view(seq_len, bsz, self.n_blocks, self.n_heads, self.head_dim) q = q.transpose(2,3) * self.scale k = k.transpose(2,3) v = v.transpose(2,3) if random.uniform(0,1) < 0.00001: print('use NFM?', self.use_nfm) if self.use_nfm: if qkv is not None: klst.append(k) vlst.append(v) #print('len qlst', len(qlst)) #for kval in klst: # print(kval.shape) k = torch.cat(klst, dim=3) v = torch.cat(vlst, dim=3) #should return these q,k,v and save to a big list. Also pull in from the list passed in and concat along dim=3, i.e. so that it's nblocks * nlayers. #print('running comm attention with shapes', q.shape, k.shape, v.shape) score = torch.matmul(q, k.transpose(3,4)) #print('score shape', score.shape) score = F.softmax(score, dim=-1) out = torch.matmul(score, v).transpose(2,3) #print('out shape', out.shape) score = score.mean(dim=2) out = out.reshape(seq_len, bsz, self.n_blocks * self.head_dim * self.n_heads) out = self.final(out) out = out.view(seq_len, bsz, self.dim) return out, score class NormLayer(nn.Module): def __init__(self, num_rims, dim, export=False): super(NormLayer, self).__init__() self.num_rims = num_rims self.dim = dim self.weight = nn.Parameter(torch.ones(1,1,dim*num_rims,)) self.bias = nn.Parameter(torch.zeros(1,1,dim*num_rims,)) self.norm = LayerNorm(dim, export=export, elementwise_affine=False) def forward(self, x): seq_len, bsz, _ = x.shape x = x.view(seq_len, bsz, self.num_rims, self.dim) x = self.norm(x) x = x.view(seq_len, bsz, self.num_rims * self.dim) weight_use = self.weight.repeat(seq_len, bsz, 1) bias_use = self.bias.repeat(seq_len, bsz, 1) x = x * weight_use + bias_use return x class TransformerEncoderLayer(nn.Module): """Encoder layer block. In the original paper each operation (multi-head attention or FFN) is postprocessed with: `dropout -> add residual -> layernorm`. In the tensor2tensor code they suggest that learning is more robust when preprocessing each layer with layernorm and postprocessing with: `dropout -> add residual`. We default to the approach in the paper, but the tensor2tensor approach can be enabled by setting *args.encoder_normalize_before* to ``True``. Args: args (argparse.Namespace): parsed command-line arguments """ def __init__(self, args, nb, blockatt, blockatt_memory, use_nfm, out_proj_dim=None): super().__init__() self.blockatt = blockatt self.blockatt_memory = blockatt_memory self.embed_dim = args.encoder_embed_dim self.quant_noise = getattr(args, "quant_noise_pq", 0) self.quant_noise_block_size = getattr(args, "quant_noise_pq_block_size", 8) self.use_nfm = use_nfm print('using nfm?', self.use_nfm) self.nb = nb self.norm_blocks = self.nb self.self_attn = self.build_self_attention(self.embed_dim, args) #should divide embed_dim by nb. Then raise embed_dim in args self.self_attn_layer_norm = NormLayer(self.norm_blocks, self.embed_dim // self.norm_blocks) self.dropout_module = FairseqDropout(args.dropout, module_name=self.__class__.__name__) self.activation_fn = utils.get_activation_fn( activation=getattr(args, "activation_fn", "relu") ) print("SETUP TRANSFORMER LAYER", 'blocks', self.nb) activation_dropout_p = getattr(args, "activation_dropout", 0) if activation_dropout_p == 0: # for backwards compatibility with models that use args.relu_dropout activation_dropout_p = getattr(args, "relu_dropout", 0) self.activation_dropout_module = FairseqDropout( float(activation_dropout_p), module_name=self.__class__.__name__ ) self.normalize_before = args.encoder_normalize_before self.fc1 = self.build_fc1( self.embed_dim, args.encoder_ffn_embed_dim, self.quant_noise, self.quant_noise_block_size ) self.fc2 = self.build_fc2( args.encoder_ffn_embed_dim, self.embed_dim, self.quant_noise, self.quant_noise_block_size ) self.final_layer_norm = NormLayer(self.norm_blocks, self.embed_dim // self.norm_blocks) if self.blockatt: self.comm = Attention(args.encoder_attention_heads, self.nb, self.embed_dim, self.use_nfm) self.comm_norm = NormLayer(self.norm_blocks, self.embed_dim // self.norm_blocks) if self.blockatt_memory: memory_slots = 4 memory_head_size = 128 memory_num_heads = 1 gate_style = 'memory' print('not using special key size gate_style is', gate_style, memory_slots, memory_num_heads, memory_head_size)
self.memory_layer = RelationalMemory(mem_slots=memory_slots, head_size=memory_head_size, input_size=self.embed_dim, output_size=self.embed_dim,
2
2023-12-15 13:13:01+00:00
24k
m-abr/FCPCodebase
world/Robot.py
[ { "identifier": "Math_Ops", "path": "math_ops/Math_Ops.py", "snippet": "class Math_Ops():\n '''\n This class provides general mathematical operations that are not directly available through numpy \n '''\n \n @staticmethod\n def deg_sph2cart(spherical_vec):\n ''' Converts SimSpark's spherical coordinates in degrees to cartesian coordinates '''\n r = spherical_vec[0]\n h = spherical_vec[1] * pi / 180\n v = spherical_vec[2] * pi / 180\n return np.array([r * cos(v) * cos(h), r * cos(v) * sin(h), r * sin(v)])\n\n @staticmethod\n def deg_sin(deg_angle):\n ''' Returns sin of degrees '''\n return sin(deg_angle * pi / 180)\n\n @staticmethod\n def deg_cos(deg_angle):\n ''' Returns cos of degrees '''\n return cos(deg_angle * pi / 180)\n\n @staticmethod\n def to_3d(vec_2d, value=0) -> np.ndarray:\n ''' Returns new 3d vector from 2d vector '''\n return np.append(vec_2d,value)\n\n @staticmethod\n def to_2d_as_3d(vec_3d) -> np.ndarray:\n ''' Returns new 3d vector where the 3rd dimension is zero '''\n vec_2d_as_3d = np.copy(vec_3d)\n vec_2d_as_3d[2] = 0\n return vec_2d_as_3d\n\n @staticmethod\n def normalize_vec(vec) -> np.ndarray:\n ''' Divides vector by its length '''\n size = np.linalg.norm(vec)\n if size == 0: return vec\n return vec / size\n\n @staticmethod\n def get_active_directory(dir:str) -> str:\n global GLOBAL_DIR\n return GLOBAL_DIR + dir\n\n @staticmethod\n def acos(val):\n ''' arccosine function that limits input '''\n return acos( np.clip(val,-1,1) )\n \n @staticmethod\n def asin(val):\n ''' arcsine function that limits input '''\n return asin( np.clip(val,-1,1) )\n\n @staticmethod\n def normalize_deg(val):\n ''' normalize val in range [-180,180[ '''\n return (val + 180.0) % 360 - 180\n\n @staticmethod\n def normalize_rad(val):\n ''' normalize val in range [-pi,pi[ '''\n return (val + pi) % (2*pi) - pi\n\n @staticmethod\n def deg_to_rad(val):\n ''' convert degrees to radians '''\n return val * 0.01745329251994330\n\n @staticmethod\n def rad_to_deg(val):\n ''' convert radians to degrees '''\n return val * 57.29577951308232\n\n @staticmethod\n def vector_angle(vector, is_rad=False):\n ''' angle (degrees or radians) of 2D vector '''\n if is_rad:\n return atan2(vector[1], vector[0])\n else:\n return atan2(vector[1], vector[0]) * 180 / pi\n\n @staticmethod\n def vectors_angle(vec1, vec2, is_rad=False):\n ''' get angle between vectors (degrees or radians) '''\n ang_rad = acos(np.dot(Math_Ops.normalize_vec(vec1),Math_Ops.normalize_vec(vec2)))\n return ang_rad if is_rad else ang_rad * 180 / pi\n\n @staticmethod\n def vector_from_angle(angle, is_rad=False):\n ''' unit vector with direction given by `angle` '''\n if is_rad:\n return np.array([cos(angle), sin(angle)], float)\n else:\n return np.array([Math_Ops.deg_cos(angle), Math_Ops.deg_sin(angle)], float)\n\n @staticmethod\n def target_abs_angle(pos2d, target, is_rad=False):\n ''' angle (degrees or radians) of vector (target-pos2d) '''\n if is_rad:\n return atan2(target[1]-pos2d[1], target[0]-pos2d[0])\n else:\n return atan2(target[1]-pos2d[1], target[0]-pos2d[0]) * 180 / pi\n\n @staticmethod\n def target_rel_angle(pos2d, ori, target, is_rad=False):\n ''' relative angle (degrees or radians) of target if we're located at 'pos2d' with orientation 'ori' (degrees or radians) '''\n if is_rad:\n return Math_Ops.normalize_rad( atan2(target[1]-pos2d[1], target[0]-pos2d[0]) - ori )\n else:\n return Math_Ops.normalize_deg( atan2(target[1]-pos2d[1], target[0]-pos2d[0]) * 180 / pi - ori )\n\n @staticmethod\n def rotate_2d_vec(vec, angle, is_rad=False):\n ''' rotate 2D vector anticlockwise around the origin by `angle` '''\n cos_ang = cos(angle) if is_rad else cos(angle * pi / 180)\n sin_ang = sin(angle) if is_rad else sin(angle * pi / 180)\n return np.array([cos_ang*vec[0]-sin_ang*vec[1], sin_ang*vec[0]+cos_ang*vec[1]])\n\n @staticmethod\n def distance_point_to_line(p:np.ndarray, a:np.ndarray, b:np.ndarray):\n ''' \n Distance between point p and 2d line 'ab' (and side where p is)\n\n Parameters\n ----------\n a : ndarray\n 2D point that defines line\n b : ndarray\n 2D point that defines line\n p : ndarray\n 2D point\n\n Returns\n -------\n distance : float\n distance between line and point\n side : str\n if we are at a, looking at b, p may be at our \"left\" or \"right\"\n '''\n line_len = np.linalg.norm(b-a)\n\n if line_len == 0: # assumes vertical line\n dist = sdist = np.linalg.norm(p-a)\n else:\n sdist = np.cross(b-a,p-a)/line_len\n dist = abs(sdist)\n\n return dist, \"left\" if sdist>0 else \"right\"\n\n @staticmethod\n def distance_point_to_segment(p:np.ndarray, a:np.ndarray, b:np.ndarray):\n ''' Distance from point p to 2d line segment 'ab' '''\n \n ap = p-a\n ab = b-a\n\n ad = Math_Ops.vector_projection(ap,ab)\n\n # Is d in ab? We can find k in (ad = k * ab) without computing any norm\n # we use the largest dimension of ab to avoid division by 0\n k = ad[0]/ab[0] if abs(ab[0])>abs(ab[1]) else ad[1]/ab[1]\n\n if k <= 0: return np.linalg.norm(ap)\n elif k >= 1: return np.linalg.norm(p-b)\n else: return np.linalg.norm(p-(ad + a)) # p-d\n\n @staticmethod\n def distance_point_to_ray(p:np.ndarray, ray_start:np.ndarray, ray_direction:np.ndarray):\n ''' Distance from point p to 2d ray '''\n \n rp = p-ray_start\n rd = Math_Ops.vector_projection(rp,ray_direction)\n\n # Is d in ray? We can find k in (rd = k * ray_direction) without computing any norm\n # we use the largest dimension of ray_direction to avoid division by 0\n k = rd[0]/ray_direction[0] if abs(ray_direction[0])>abs(ray_direction[1]) else rd[1]/ray_direction[1]\n\n if k <= 0: return np.linalg.norm(rp)\n else: return np.linalg.norm(p-(rd + ray_start)) # p-d\n\n @staticmethod\n def closest_point_on_ray_to_point(p:np.ndarray, ray_start:np.ndarray, ray_direction:np.ndarray):\n ''' Point on ray closest to point p '''\n \n rp = p-ray_start\n rd = Math_Ops.vector_projection(rp,ray_direction)\n\n # Is d in ray? We can find k in (rd = k * ray_direction) without computing any norm\n # we use the largest dimension of ray_direction to avoid division by 0\n k = rd[0]/ray_direction[0] if abs(ray_direction[0])>abs(ray_direction[1]) else rd[1]/ray_direction[1]\n\n if k <= 0: return ray_start\n else: return rd + ray_start\n\n @staticmethod\n def does_circle_intersect_segment(p:np.ndarray, r, a:np.ndarray, b:np.ndarray):\n ''' Returns true if circle (center p, radius r) intersect 2d line segment '''\n\n ap = p-a\n ab = b-a\n\n ad = Math_Ops.vector_projection(ap,ab)\n\n # Is d in ab? We can find k in (ad = k * ab) without computing any norm\n # we use the largest dimension of ab to avoid division by 0\n k = ad[0]/ab[0] if abs(ab[0])>abs(ab[1]) else ad[1]/ab[1]\n\n if k <= 0: return np.dot(ap,ap) <= r*r\n elif k >= 1: return np.dot(p-b,p-b) <= r*r\n \n dp = p-(ad + a)\n return np.dot(dp,dp) <= r*r\n\n @staticmethod\n def vector_projection(a:np.ndarray, b:np.ndarray):\n ''' Vector projection of a onto b '''\n b_dot = np.dot(b,b)\n return b * np.dot(a,b) / b_dot if b_dot != 0 else b\n\n @staticmethod\n def do_noncollinear_segments_intersect(a,b,c,d):\n ''' \n Check if 2d line segment 'ab' intersects with noncollinear 2d line segment 'cd' \n Explanation: https://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/ \n '''\n\n ccw = lambda a,b,c: (c[1]-a[1]) * (b[0]-a[0]) > (b[1]-a[1]) * (c[0]-a[0])\n return ccw(a,c,d) != ccw(b,c,d) and ccw(a,b,c) != ccw(a,b,d)\n\n @staticmethod\n def intersection_segment_opp_goal(a:np.ndarray, b:np.ndarray):\n ''' Computes the intersection point of 2d segment 'ab' and the opponents' goal (front line) '''\n vec_x = b[0]-a[0]\n\n # Collinear intersections are not accepted\n if vec_x == 0: return None\n \n k = (15.01-a[0])/vec_x\n\n # No collision\n if k < 0 or k > 1: return None\n\n intersection_pt = a + (b-a) * k\n\n if -1.01 <= intersection_pt[1] <= 1.01:\n return intersection_pt\n else:\n return None\n\n @staticmethod\n def intersection_circle_opp_goal(p:np.ndarray, r):\n ''' \n Computes the intersection segment of circle (center p, radius r) and the opponents' goal (front line)\n Only the y coordinates are returned since the x coordinates are always equal to 15\n '''\n\n x_dev = abs(15-p[0])\n\n if x_dev > r:\n return None # no intersection with x=15\n\n y_dev = sqrt(r*r - x_dev*x_dev)\n\n p1 = max(p[1] - y_dev, -1.01)\n p2 = min(p[1] + y_dev, 1.01)\n\n if p1 == p2:\n return p1 # return the y coordinate of a single intersection point\n elif p2 < p1:\n return None # no intersection\n else:\n return p1, p2 # return the y coordinates of the intersection segment\n\n\n @staticmethod\n def distance_point_to_opp_goal(p:np.ndarray):\n ''' Distance between point 'p' and the opponents' goal (front line) '''\n\n if p[1] < -1.01:\n return np.linalg.norm( p-(15,-1.01) )\n elif p[1] > 1.01:\n return np.linalg.norm( p-(15, 1.01) )\n else:\n return abs(15-p[0])\n\n\n @staticmethod\n def circle_line_segment_intersection(circle_center, circle_radius, pt1, pt2, full_line=True, tangent_tol=1e-9):\n \"\"\" Find the points at which a circle intersects a line-segment. This can happen at 0, 1, or 2 points.\n\n :param circle_center: The (x, y) location of the circle center\n :param circle_radius: The radius of the circle\n :param pt1: The (x, y) location of the first point of the segment\n :param pt2: The (x, y) location of the second point of the segment\n :param full_line: True to find intersections along full line - not just in the segment. False will just return intersections within the segment.\n :param tangent_tol: Numerical tolerance at which we decide the intersections are close enough to consider it a tangent\n :return Sequence[Tuple[float, float]]: A list of length 0, 1, or 2, where each element is a point at which the circle intercepts a line segment.\n\n Note: We follow: http://mathworld.wolfram.com/Circle-LineIntersection.html\n \"\"\"\n\n (p1x, p1y), (p2x, p2y), (cx, cy) = pt1, pt2, circle_center\n (x1, y1), (x2, y2) = (p1x - cx, p1y - cy), (p2x - cx, p2y - cy)\n dx, dy = (x2 - x1), (y2 - y1)\n dr = (dx ** 2 + dy ** 2)**.5\n big_d = x1 * y2 - x2 * y1\n discriminant = circle_radius ** 2 * dr ** 2 - big_d ** 2\n\n if discriminant < 0: # No intersection between circle and line\n return []\n else: # There may be 0, 1, or 2 intersections with the segment\n intersections = [\n (cx + (big_d * dy + sign * (-1 if dy < 0 else 1) * dx * discriminant**.5) / dr ** 2,\n cy + (-big_d * dx + sign * abs(dy) * discriminant**.5) / dr ** 2)\n for sign in ((1, -1) if dy < 0 else (-1, 1))] # This makes sure the order along the segment is correct\n if not full_line: # If only considering the segment, filter out intersections that do not fall within the segment\n fraction_along_segment = [\n (xi - p1x) / dx if abs(dx) > abs(dy) else (yi - p1y) / dy for xi, yi in intersections]\n intersections = [pt for pt, frac in zip(\n intersections, fraction_along_segment) if 0 <= frac <= 1]\n # If line is tangent to circle, return just one point (as both intersections have same location)\n if len(intersections) == 2 and abs(discriminant) <= tangent_tol:\n return [intersections[0]]\n else:\n return intersections\n\n\n\n\n # adapted from https://stackoverflow.com/questions/3252194/numpy-and-line-intersections\n @staticmethod\n def get_line_intersection(a1, a2, b1, b2):\n \"\"\" \n Returns the point of intersection of the lines passing through a2,a1 and b2,b1.\n a1: [x, y] a point on the first line\n a2: [x, y] another point on the first line\n b1: [x, y] a point on the second line\n b2: [x, y] another point on the second line\n \"\"\"\n s = np.vstack([a1,a2,b1,b2]) # s for stacked\n h = np.hstack((s, np.ones((4, 1)))) # h for homogeneous\n l1 = np.cross(h[0], h[1]) # get first line\n l2 = np.cross(h[2], h[3]) # get second line\n x, y, z = np.cross(l1, l2) # point of intersection\n if z == 0: # lines are parallel\n return np.array([float('inf'), float('inf')])\n return np.array([x/z, y/z],float)" }, { "identifier": "Matrix_3x3", "path": "math_ops/Matrix_3x3.py", "snippet": "class Matrix_3x3():\n\n def __init__(self, matrix = None) -> None:\n '''\n Constructor examples:\n a = Matrix_3x3( ) # create identity matrix\n b = Matrix_3x3( [[1,1,1],[2,2,2],[3,3,3]] ) # manually initialize matrix\n c = Matrix_3x3( [1,1,1,2,2,2,3,3,3] ) # manually initialize matrix\n d = Matrix_3x3( b ) # copy constructor\n '''\n if matrix is None:\n self.m = np.identity(3)\n elif type(matrix) == Matrix_3x3: \n self.m = np.copy(matrix.m)\n else:\n self.m = np.asarray(matrix)\n self.m.shape = (3,3) #reshape if needed, throw error if impossible\n\n\n self.rotation_shortcuts={(1,0,0):self.rotate_x_rad, (-1, 0, 0):self._rotate_x_neg_rad,\n (0,1,0):self.rotate_y_rad, ( 0,-1, 0):self._rotate_y_neg_rad,\n (0,0,1):self.rotate_z_rad, ( 0, 0,-1):self._rotate_z_neg_rad}\n\n @classmethod\n def from_rotation_deg(cls, euler_vec):\n '''\n Create rotation matrix from Euler angles, in degrees.\n Rotation order: RotZ*RotY*RotX\n\n Parameters\n ----------\n euler_vec : array_like, length 3\n vector with Euler angles (x,y,z) aka (roll, pitch, yaw)\n\n Example\n ----------\n Matrix_3x3.from_rotation_deg((roll,pitch,yaw)) # Creates: RotZ(yaw)*RotY(pitch)*RotX(roll)\n '''\n mat = cls().rotate_z_deg(euler_vec[2], True).rotate_y_deg(euler_vec[1], True).rotate_x_deg(euler_vec[0], True)\n return mat\n\n def get_roll_deg(self):\n ''' Get angle around the x-axis in degrees, Rotation order: RotZ*RotY*RotX=Rot '''\n if self.m[2,1] == 0 and self.m[2,2] == 0: \n return 180\n return atan2(self.m[2,1], self.m[2,2]) * 180 / pi\n\n def get_pitch_deg(self):\n ''' Get angle around the y-axis in degrees, Rotation order: RotZ*RotY*RotX=Rot '''\n return atan2(-self.m[2,0], sqrt(self.m[2,1]*self.m[2,1] + self.m[2,2]*self.m[2,2])) * 180 / pi\n\n def get_yaw_deg(self):\n ''' Get angle around the z-axis in degrees, Rotation order: RotZ*RotY*RotX=Rot '''\n if self.m[1,0] == 0 and self.m[0,0] == 0: \n return atan2(self.m[0,1], self.m[1,1]) * 180 / pi\n return atan2(self.m[1,0], self.m[0,0]) * 180 / pi\n\n def get_inclination_deg(self):\n ''' Get inclination of z-axis in relation to reference z-axis '''\n return 90 - (asin(self.m[2,2]) * 180 / pi)\n\n\n def rotate_deg(self, rotation_vec, rotation_deg, in_place=False):\n '''\n Rotates the current rotation matrix\n\n Parameters\n ----------\n rotation_vec : array_like, length 3\n rotation vector\n rotation_rad : float\n rotation in degrees\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_3x3 \n self is returned if in_place is True\n '''\n return self.rotate_rad(rotation_vec, rotation_deg * (pi/180) , in_place)\n\n \n def rotate_rad(self, rotation_vec, rotation_rad, in_place=False):\n '''\n Rotates the current rotation matrix\n\n Parameters\n ----------\n rotation_vec : array_like, length 3\n rotation vector\n rotation_rad : float\n rotation in radians\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_3x3 \n self is returned if in_place is True\n '''\n\n if rotation_rad == 0: return\n\n shortcut = self.rotation_shortcuts.get(tuple(a for a in rotation_vec))\n if shortcut:\n return shortcut(rotation_rad, in_place)\n \n c = np.math.cos(rotation_rad)\n c1 = 1 - c\n s = np.math.sin(rotation_rad)\n x = rotation_vec[0]\n y = rotation_vec[1]\n z = rotation_vec[2]\n xxc1 = x * x * c1\n yyc1 = y * y * c1\n zzc1 = z * z * c1\n xyc1 = x * y * c1\n xzc1 = x * z * c1\n yzc1 = y * z * c1\n xs = x * s\n ys = y * s\n zs = z * s\n\n mat = np.array([\n [xxc1 + c, xyc1 - zs, xzc1 + ys],\n [xyc1 + zs, yyc1 + c, yzc1 - xs],\n [xzc1 - ys, yzc1 + xs, zzc1 + c]])\n\n return self.multiply(mat, in_place)\n\n\n def _rotate_x_neg_rad(self, rotation_rad, in_place=False):\n self.rotate_x_rad(-rotation_rad, in_place)\n\n def _rotate_y_neg_rad(self, rotation_rad, in_place=False):\n self.rotate_y_rad(-rotation_rad, in_place)\n\n def _rotate_z_neg_rad(self, rotation_rad, in_place=False):\n self.rotate_z_rad(-rotation_rad, in_place)\n\n def rotate_x_rad(self, rotation_rad, in_place=False):\n '''\n Rotates the current rotation matrix around the x-axis\n\n Parameters\n ----------\n rotation_rad : float\n rotation in radians\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_3x3 \n self is returned if in_place is True\n '''\n if rotation_rad == 0: \n return self if in_place else Matrix_3x3(self)\n \n c = np.math.cos(rotation_rad)\n s = np.math.sin(rotation_rad)\n\n mat = np.array([\n [1, 0, 0],\n [0, c,-s],\n [0, s, c]])\n\n return self.multiply(mat, in_place)\n\n def rotate_y_rad(self, rotation_rad, in_place=False):\n '''\n Rotates the current rotation matrix around the y-axis\n\n Parameters\n ----------\n rotation_rad : float\n rotation in radians\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_3x3 \n self is returned if in_place is True\n '''\n if rotation_rad == 0: \n return self if in_place else Matrix_3x3(self)\n \n c = np.math.cos(rotation_rad)\n s = np.math.sin(rotation_rad)\n\n mat = np.array([\n [ c, 0, s],\n [ 0, 1, 0],\n [-s, 0, c]])\n\n return self.multiply(mat, in_place)\n\n def rotate_z_rad(self, rotation_rad, in_place=False):\n '''\n Rotates the current rotation matrix around the z-axis\n\n Parameters\n ----------\n rotation_rad : float\n rotation in radians\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_3x3 \n self is returned if in_place is True\n '''\n if rotation_rad == 0: \n return self if in_place else Matrix_3x3(self)\n \n c = np.math.cos(rotation_rad)\n s = np.math.sin(rotation_rad)\n\n mat = np.array([\n [ c,-s, 0],\n [ s, c, 0],\n [ 0, 0, 1]])\n\n return self.multiply(mat, in_place)\n\n def rotate_x_deg(self, rotation_deg, in_place=False):\n '''\n Rotates the current rotation matrix around the x-axis\n\n Parameters\n ----------\n rotation_rad : float\n rotation in degrees\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_3x3 \n self is returned if in_place is True\n '''\n return self.rotate_x_rad(rotation_deg * (pi/180), in_place)\n\n def rotate_y_deg(self, rotation_deg, in_place=False):\n '''\n Rotates the current rotation matrix around the y-axis\n\n Parameters\n ----------\n rotation_rad : float\n rotation in degrees\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_3x3 \n self is returned if in_place is True\n '''\n return self.rotate_y_rad(rotation_deg * (pi/180), in_place)\n\n def rotate_z_deg(self, rotation_deg, in_place=False):\n '''\n Rotates the current rotation matrix around the z-axis\n\n Parameters\n ----------\n rotation_rad : float\n rotation in degrees\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_3x3 \n self is returned if in_place is True\n '''\n return self.rotate_z_rad(rotation_deg * (pi/180), in_place)\n\n def invert(self, in_place=False):\n '''\n Inverts the current rotation matrix\n\n Parameters\n ----------\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_3x3 \n self is returned if in_place is True\n '''\n\n if in_place:\n self.m = np.linalg.inv(self.m)\n return self\n else:\n return Matrix_3x3(np.linalg.inv(self.m))\n\n def multiply(self,mat, in_place=False, reverse_order=False):\n '''\n Multiplies the current rotation matrix by mat\n\n Parameters\n ----------\n mat : Matrix_3x3 or array_like\n multiplier matrix or 3D vector\n in_place: bool, optional\n - True: the internal matrix is changed in-place\n - False: a new matrix is returned and the current one is not changed (default) \n reverse_order: bool, optional\n - False: self * mat\n - True: mat * self\n \n Returns\n -------\n result : Matrix_3x3 | array_like\n Matrix_3x3 is returned if mat is a matrix (self is returned if in_place is True); \n a 3D vector is returned if mat is a vector\n '''\n # get array from matrix object or convert to numpy array (if needed) \n mat = mat.m if type(mat) == Matrix_3x3 else np.asarray(mat)\n\n a,b = (mat, self.m) if reverse_order else (self.m, mat)\n\n if mat.ndim == 1: \n return np.matmul(a, b) # multiplication by 3D vector\n elif in_place:\n np.matmul(a, b, self.m) # multiplication by matrix, in place\n return self\n else: # multiplication by matrix, return new Matrix_3x3\n return Matrix_3x3(np.matmul(a, b))" }, { "identifier": "Matrix_4x4", "path": "math_ops/Matrix_4x4.py", "snippet": "class Matrix_4x4():\n\n def __init__(self, matrix = None) -> None:\n '''\n Constructor examples:\n a = Matrix_4x4( ) # create identity matrix\n b = Matrix_4x4( [[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4]] ) # manually initialize matrix\n c = Matrix_4x4( [1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4] ) # manually initialize matrix\n d = Matrix_4x4( b ) # copy constructor\n '''\n if matrix is None:\n self.m = np.identity(4)\n elif type(matrix) == Matrix_4x4: \n self.m = np.copy(matrix.m)\n elif type(matrix) == Matrix_3x3: \n self.m = np.identity(4)\n self.m[0:3,0:3] = matrix.m\n else:\n self.m = np.asarray(matrix)\n self.m.shape = (4,4) #reshape if needed, throw error if impossible\n\n\n @classmethod\n def from_translation(cls, translation_vec):\n '''\n Create transformation matrix from translation_vec translation\n e.g. Matrix_4x4.from_translation((a,b,c))\n output: [[1,0,0,a],[0,1,0,b],[0,0,1,c],[0,0,0,1]]\n '''\n mat = np.identity(4)\n mat[0:3,3] = translation_vec\n return cls(mat)\n\n @classmethod\n def from_3x3_and_translation(cls, mat3x3:Matrix_3x3, translation_vec):\n '''\n Create transformation matrix from rotation matrix (3x3) and translation\n e.g. Matrix_4x4.from_3x3_and_translation(r,(a,b,c)) \n output: [[r00,r01,r02,a],[r10,r11,r12,b],[r20,r21,r22,c],[0,0,0,1]]\n '''\n mat = np.identity(4)\n mat[0:3,0:3] = mat3x3.m\n mat[0:3,3] = translation_vec\n return cls(mat)\n\n def translate(self, translation_vec, in_place=False):\n '''\n Translates the current transformation matrix\n\n Parameters\n ----------\n translation_vec : array_like, length 3\n translation vector\n in_place: bool, optional\n * True: the internal matrix is changed in-place\n * False: a new matrix is returned and the current one is not changed \n\n Returns\n -------\n result : Matrix_4x4 \n self is returned if in_place is True\n '''\n vec = np.array([*translation_vec,1])# conversion to 4D vector\n np.matmul(self.m, vec, out=vec) # compute only 4th column\n\n if in_place:\n self.m[:,3] = vec\n return self\n else:\n ret = Matrix_4x4(self.m)\n ret.m[:,3] = vec\n return ret\n\n\n def get_translation(self):\n ''' Get translation vector (x,y,z) '''\n return self.m[0:3,3] # return view\n\n def get_x(self):\n return self.m[0,3]\n\n def get_y(self):\n return self.m[1,3]\n\n def get_z(self):\n return self.m[2,3]\n\n def get_rotation_4x4(self):\n ''' Get Matrix_4x4 without translation ''' \n mat = Matrix_4x4(self)\n mat.m[0:3,3] = 0\n return mat\n\n def get_rotation(self):\n ''' Get rotation Matrix_3x3 '''\n return Matrix_3x3(self.m[0:3,0:3])\n\n def get_distance(self):\n ''' Get translation vector length '''\n return np.linalg.norm(self.m[0:3,3])\n\n def get_roll_deg(self):\n ''' Get angle around the x-axis in degrees, Rotation order: RotZ*RotY*RotX=Rot '''\n if self.m[2,1] == 0 and self.m[2,2] == 0: \n return 180\n return atan2(self.m[2,1], self.m[2,2]) * 180 / pi\n\n def get_pitch_deg(self):\n ''' Get angle around the y-axis in degrees, Rotation order: RotZ*RotY*RotX=Rot '''\n return atan2(-self.m[2,0], sqrt(self.m[2,1]*self.m[2,1] + self.m[2,2]*self.m[2,2])) * 180 / pi\n\n def get_yaw_deg(self):\n ''' Get angle around the z-axis in degrees, Rotation order: RotZ*RotY*RotX=Rot '''\n if self.m[1,0] == 0 and self.m[0,0] == 0: \n return atan2(self.m[0,1], self.m[1,1]) * 180 / pi\n return atan2(self.m[1,0], self.m[0,0]) * 180 / pi\n \n def get_inclination_deg(self):\n ''' Get inclination of z-axis in relation to reference z-axis '''\n return 90 - (asin(np.clip(self.m[2,2],-1,1)) * 180 / pi)\n\n def rotate_deg(self, rotation_vec, rotation_deg, in_place=False):\n '''\n Rotates the current transformation matrix\n\n Parameters\n ----------\n rotation_vec : array_like, length 3\n rotation vector\n rotation_rad : float\n rotation in degrees\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_4x4 \n self is returned if in_place is True\n '''\n return self.rotate_rad(rotation_vec, rotation_deg * (pi/180) , in_place)\n\n \n def rotate_rad(self, rotation_vec, rotation_rad, in_place=False):\n '''\n Rotates the current transformation matrix\n\n Parameters\n ----------\n rotation_vec : array_like, length 3\n rotation vector\n rotation_rad : float\n rotation in radians\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_4x4 \n self is returned if in_place is True\n '''\n\n if rotation_rad == 0: \n return self if in_place else Matrix_4x4(self)\n\n # shortcuts for rotation around 1 axis\n if rotation_vec[0]==0:\n if rotation_vec[1]==0:\n if rotation_vec[2]==1:\n return self.rotate_z_rad(rotation_rad, in_place)\n elif rotation_vec[2]==-1:\n return self.rotate_z_rad(-rotation_rad, in_place)\n elif rotation_vec[2]==0:\n if rotation_vec[1]==1:\n return self.rotate_y_rad(rotation_rad, in_place)\n elif rotation_vec[1]==-1:\n return self.rotate_y_rad(-rotation_rad, in_place)\n elif rotation_vec[1]==0 and rotation_vec[2]==0:\n if rotation_vec[0]==1:\n return self.rotate_x_rad(rotation_rad, in_place)\n elif rotation_vec[0]==-1:\n return self.rotate_x_rad(-rotation_rad, in_place)\n \n c = np.math.cos(rotation_rad)\n c1 = 1 - c\n s = np.math.sin(rotation_rad)\n x = rotation_vec[0]\n y = rotation_vec[1]\n z = rotation_vec[2]\n xxc1 = x * x * c1\n yyc1 = y * y * c1\n zzc1 = z * z * c1\n xyc1 = x * y * c1\n xzc1 = x * z * c1\n yzc1 = y * z * c1\n xs = x * s\n ys = y * s\n zs = z * s\n\n mat = np.array([\n [xxc1 + c, xyc1 - zs, xzc1 + ys, 0],\n [xyc1 + zs, yyc1 + c, yzc1 - xs, 0],\n [xzc1 - ys, yzc1 + xs, zzc1 + c, 0],\n [0, 0, 0, 1]])\n\n return self.multiply(mat, in_place)\n\n\n def rotate_x_rad(self, rotation_rad, in_place=False):\n '''\n Rotates the current transformation matrix around the x-axis\n\n Parameters\n ----------\n rotation_rad : float\n rotation in radians\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_4x4 \n self is returned if in_place is True\n '''\n if rotation_rad == 0: \n return self if in_place else Matrix_4x4(self)\n \n c = np.math.cos(rotation_rad)\n s = np.math.sin(rotation_rad)\n\n mat = np.array([\n [1, 0, 0, 0],\n [0, c,-s, 0],\n [0, s, c, 0],\n [0, 0, 0, 1]])\n\n return self.multiply(mat, in_place)\n\n def rotate_y_rad(self, rotation_rad, in_place=False):\n '''\n Rotates the current transformation matrix around the y-axis\n\n Parameters\n ----------\n rotation_rad : float\n rotation in radians\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_4x4 \n self is returned if in_place is True\n '''\n if rotation_rad == 0: \n return self if in_place else Matrix_4x4(self)\n \n c = np.math.cos(rotation_rad)\n s = np.math.sin(rotation_rad)\n\n mat = np.array([\n [ c, 0, s, 0],\n [ 0, 1, 0, 0],\n [-s, 0, c, 0],\n [ 0, 0, 0, 1]])\n\n return self.multiply(mat, in_place)\n\n def rotate_z_rad(self, rotation_rad, in_place=False):\n '''\n Rotates the current transformation matrix around the z-axis\n\n Parameters\n ----------\n rotation_rad : float\n rotation in radians\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_4x4 \n self is returned if in_place is True\n '''\n if rotation_rad == 0: \n return self if in_place else Matrix_4x4(self)\n \n c = np.math.cos(rotation_rad)\n s = np.math.sin(rotation_rad)\n\n mat = np.array([\n [ c,-s, 0, 0],\n [ s, c, 0, 0],\n [ 0, 0, 1, 0],\n [ 0, 0, 0, 1]])\n\n return self.multiply(mat, in_place)\n\n def rotate_x_deg(self, rotation_deg, in_place=False):\n '''\n Rotates the current transformation matrix around the x-axis\n\n Parameters\n ----------\n rotation_rad : float\n rotation in degrees\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_4x4 \n self is returned if in_place is True\n '''\n return self.rotate_x_rad(rotation_deg * (pi/180), in_place)\n\n def rotate_y_deg(self, rotation_deg, in_place=False):\n '''\n Rotates the current transformation matrix around the y-axis\n\n Parameters\n ----------\n rotation_rad : float\n rotation in degrees\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_4x4 \n self is returned if in_place is True\n '''\n return self.rotate_y_rad(rotation_deg * (pi/180), in_place)\n\n def rotate_z_deg(self, rotation_deg, in_place=False):\n '''\n Rotates the current transformation matrix around the z-axis\n\n Parameters\n ----------\n rotation_rad : float\n rotation in degrees\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_4x4 \n self is returned if in_place is True\n '''\n return self.rotate_z_rad(rotation_deg * (pi/180), in_place)\n\n def invert(self, in_place=False):\n '''\n Inverts the current transformation matrix\n\n Parameters\n ----------\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed \n \n Returns\n -------\n result : Matrix_4x4 \n self is returned if in_place is True\n '''\n\n if in_place:\n self.m = np.linalg.inv(self.m)\n return self\n else:\n return Matrix_4x4(np.linalg.inv(self.m))\n\n def multiply(self,mat, in_place=False):\n '''\n Multiplies the current transformation matrix by mat\n\n Parameters\n ----------\n mat : Matrix_4x4 or array_like\n multiplier matrix or 3D vector\n in_place: bool, optional\n * True: the internal matrix is changed in-place (default)\n * False: a new matrix is returned and the current one is not changed (if mat is a 4x4 matrix)\n \n Returns\n -------\n result : Matrix_4x4 | array_like\n Matrix_4x4 is returned if mat is a matrix (self is returned if in_place is True); \n a 3D vector is returned if mat is a vector\n '''\n if type(mat) == Matrix_4x4: \n mat = mat.m\n else:\n mat = np.asarray(mat) # conversion to array, if needed\n if mat.ndim == 1: # multiplication by 3D vector\n vec = np.append(mat,1) # conversion to 4D vector\n return np.matmul(self.m, vec)[0:3] # conversion to 3D vector\n\n if in_place:\n np.matmul(self.m, mat, self.m)\n return self\n else:\n return Matrix_4x4(np.matmul(self.m, mat))\n\n def __call__(self,mat, is_spherical=False):\n '''\n Multiplies the current transformation matrix by mat and returns a new matrix or vector\n\n Parameters\n ----------\n mat : Matrix_4x4 or array_like\n multiplier matrix or 3D vector\n is_spherical : bool\n only relevant if mat is a 3D vector, True if it uses spherical coordinates\n \n Returns\n -------\n result : Matrix_4x4 | array_like\n Matrix_4x4 is returned if mat is a matrix; \n a 3D vector is returned if mat is a vector\n '''\n\n if is_spherical and mat.ndim == 1: mat = M.deg_sph2cart(mat)\n return self.multiply(mat,False)" }, { "identifier": "Body_Part", "path": "world/commons/Body_Part.py", "snippet": "class Body_Part():\n def __init__(self, mass) -> None:\n self.mass = float(mass)\n self.joints = []\n self.transform = Matrix_4x4() # body part to head transformation matrix" }, { "identifier": "Joint_Info", "path": "world/commons/Joint_Info.py", "snippet": "class Joint_Info():\n def __init__(self, xml_element) -> None:\n self.perceptor = xml_element.attrib['perceptor']\n self.effector = xml_element.attrib['effector']\n self.axes = np.array([\n float(xml_element.attrib['xaxis']), \n float(xml_element.attrib['yaxis']), \n float(xml_element.attrib['zaxis'])])\n self.min = int(xml_element.attrib['min'])\n self.max = int(xml_element.attrib['max'])\n\n self.anchor0_part = xml_element[0].attrib['part']\n self.anchor0_axes = np.array([\n float(xml_element[0].attrib['y']), \n float(xml_element[0].attrib['x']), \n float(xml_element[0].attrib['z'])]) #x and y axes are switched\n\n self.anchor1_part = xml_element[1].attrib['part']\n self.anchor1_axes_neg = np.array([\n -float(xml_element[1].attrib['y']), \n -float(xml_element[1].attrib['x']), \n -float(xml_element[1].attrib['z'])]) #x and y axes are switched" } ]
from collections import deque from math import atan, pi, sqrt, tan from math_ops.Math_Ops import Math_Ops as M from math_ops.Matrix_3x3 import Matrix_3x3 from math_ops.Matrix_4x4 import Matrix_4x4 from world.commons.Body_Part import Body_Part from world.commons.Joint_Info import Joint_Info import numpy as np import xml.etree.ElementTree as xmlp
14,671
self.body_parts = dict() # keys='body part names' (given by the robot's XML), values='Body_Part objects' self.unum = unum # Robot's uniform number self.gyro = np.zeros(3) # Angular velocity along the three axes of freedom of the robot's torso (deg/s) self.acc = np.zeros(3) # Proper acceleration along the three axes of freedom of the robot's torso (m/s2) self.frp = dict() # foot "lf"/"rf", toe "lf1"/"rf1" resistance perceptor (relative [p]oint of origin + [f]orce vector) e.g. {"lf":(px,py,pz,fx,fy,fz)} self.feet_toes_last_touch = {"lf":0,"rf":0,"lf1":0,"rf1":0} # foot "lf"/"rf", toe "lf1"/"rf1" World.time_local_ms when foot/toe last touched any surface self.feet_toes_are_touching = {"lf":False,"rf":False,"lf1":False,"rf1":False} # foot "lf"/"rf", toe "lf1"/"rf1" True if touching in last received server message self.fwd_kinematics_list = None # List of body parts, ordered according to dependencies self.rel_cart_CoM_position = np.zeros(3) # Center of Mass position, relative to head, in cartesian coordinates (m) # Joint variables are optimized for performance / array operations self.joints_position = np.zeros(self.no_of_joints) # Joints' angular position (deg) self.joints_speed = np.zeros(self.no_of_joints) # Joints' angular speed (rad/s) self.joints_target_speed = np.zeros(self.no_of_joints) # Joints' target speed (rad/s) (max: 6.1395 rad/s, see rcssserver3d/data/rsg/agent/nao/hingejoint.rsg) self.joints_target_last_speed = np.zeros(self.no_of_joints) # Joints' last target speed (rad/s) (max: 6.1395 rad/s, see rcssserver3d/data/rsg/agent/nao/hingejoint.rsg) self.joints_info = [None] * self.no_of_joints # Joints' constant information (see class Joint_Info) self.joints_transform = [Matrix_4x4() for _ in range(self.no_of_joints)] # Joints' transformation matrix # Localization variables relative to head self.loc_head_to_field_transform = Matrix_4x4() # Transformation matrix from head to field self.loc_field_to_head_transform = Matrix_4x4() # Transformation matrix from field to head self.loc_rotation_head_to_field = Matrix_3x3() # Rotation matrix from head to field self.loc_rotation_field_to_head = Matrix_3x3() # Rotation matrix from field to head self.loc_head_position = np.zeros(3) # Absolute head position (m) self.loc_head_position_history = deque(maxlen=40)# Absolute head position history (queue with up to 40 old positions at intervals of 0.04s, where index 0 is the previous position) self.loc_head_velocity = np.zeros(3) # Absolute head velocity (m/s) (Warning: possibly noisy) self.loc_head_orientation = 0 # Head orientation (deg) self.loc_is_up_to_date = False # False if this is not a visual step, or not enough elements are visible self.loc_last_update = 0 # World.time_local_ms when the localization was last updated self.loc_head_position_last_update = 0 # World.time_local_ms when loc_head_position was last updated by vision or radio self.radio_fallen_state = False # True if (radio says we fell) and (radio is significantly more recent than loc) self.radio_last_update = 0 # World.time_local_ms when radio_fallen_state was last updated (and possibly loc_head_position) # Localization variables relative to torso self.loc_torso_to_field_rotation = Matrix_3x3() # Rotation matrix from torso to field self.loc_torso_to_field_transform = Matrix_4x4() # Transformation matrix from torso to field self.loc_torso_roll = 0 # Torso roll (deg) self.loc_torso_pitch = 0 # Torso pitch (deg) self.loc_torso_orientation = 0 # Torso orientation (deg) self.loc_torso_inclination = 0 # Torso inclination (deg) (inclination of z-axis in relation to field z-axis) self.loc_torso_position = np.zeros(3) # Absolute torso position (m) self.loc_torso_velocity = np.zeros(3) # Absolute torso velocity (m/s) self.loc_torso_acceleration = np.zeros(3) # Absolute Coordinate acceleration (m/s2) # Other localization variables self.cheat_abs_pos = np.zeros(3) # Absolute head position provided by the server as cheat (m) self.cheat_ori = 0.0 # Absolute head orientation provided by the server as cheat (deg) self.loc_CoM_position = np.zeros(3) # Absolute CoM position (m) self.loc_CoM_velocity = np.zeros(3) # Absolute CoM velocity (m/s) # Localization special variables ''' self.loc_head_z is often equivalent to self.loc_head_position[2], but sometimes it differs. There are situations in which the rotation and translation cannot be computed, but the z-coordinate can still be found through vision, in which case: self.loc_is_up_to_date is False self.loc_head_z_is_up_to_date is True It should be used in applications which rely on z as an independent coordinate, such as detecting if the robot has fallen, or as an observation for machine learning. It should NEVER be used for 3D transformations. ''' self.loc_head_z = 0 # Absolute head position (z) - see above for explanation (m) self.loc_head_z_is_up_to_date = False # False if this is not a visual step, or not enough elements are visible self.loc_head_z_last_update = 0 # World.time_local_ms when loc_head_z was last computed self.loc_head_z_vel = 0 # Absolute head velocity (z) (m/s) # Localization + Gyroscope # These variables are reliable. The gyroscope is used to update the rotation when waiting for the next visual cycle self.imu_torso_roll = 0 # Torso roll (deg) (src: Localization + Gyro) self.imu_torso_pitch = 0 # Torso pitch (deg) (src: Localization + Gyro) self.imu_torso_orientation = 0 # Torso orientation (deg) (src: Localization + Gyro) self.imu_torso_inclination = 0 # Torso inclination (deg) (src: Localization + Gyro) self.imu_torso_to_field_rotation = Matrix_3x3() # Rotation matrix from torso to field (src: Localization + Gyro) self.imu_last_visual_update = 0 # World.time_local_ms when the IMU data was last updated with visual information # Localization + Gyroscope + Accelerometer # Warning: these variables are unreliable, since small errors in the Localization Orientation lead to # wrong acceleration -> wrong velocity -> wrong position self.imu_weak_torso_to_field_transform = Matrix_4x4() # Transformation matrix from torso to field (src: Localization + Gyro + Acc) self.imu_weak_head_to_field_transform = Matrix_4x4() # Transformation matrix from head to field (src: Localization + Gyro + Acc) self.imu_weak_field_to_head_transform = Matrix_4x4() # Transformation matrix from field to head (src: Localization + Gyro + Acc) self.imu_weak_torso_position = np.zeros(3) # Absolute torso position (m) (src: Localization + Gyro + Acc) self.imu_weak_torso_velocity = np.zeros(3) # Absolute torso velocity (m/s) (src: Localization + Gyro + Acc) self.imu_weak_torso_acceleration = np.zeros(3) # Absolute torso acceleration (m/s2) (src: Localization + Gyro + Acc) self.imu_weak_torso_next_position = np.zeros(3) # Absolute position in next step estimate (m) (src: Localization + Gyro + Acc) self.imu_weak_torso_next_velocity = np.zeros(3) # Absolute velocity in next step estimate (m/s) (src: Localization + Gyro + Acc) self.imu_weak_CoM_position = np.zeros(3) # Absolute CoM position (m) (src: Localization + Gyro + Acc) self.imu_weak_CoM_velocity = np.zeros(3) # Absolute CoM velocity (m/s) (src: Localization + Gyro + Acc) #Using explicit variables to enable IDE suggestions self.J_HEAD_YAW = 0 self.J_HEAD_PITCH = 1 self.J_LLEG_YAW_PITCH = 2 self.J_RLEG_YAW_PITCH = 3 self.J_LLEG_ROLL = 4 self.J_RLEG_ROLL = 5 self.J_LLEG_PITCH = 6 self.J_RLEG_PITCH = 7 self.J_LKNEE = 8 self.J_RKNEE = 9 self.J_LFOOT_PITCH = 10 self.J_RFOOT_PITCH = 11 self.J_LFOOT_ROLL = 12 self.J_RFOOT_ROLL = 13 self.J_LARM_PITCH = 14 self.J_RARM_PITCH = 15 self.J_LARM_ROLL = 16 self.J_RARM_ROLL = 17 self.J_LELBOW_YAW = 18 self.J_RELBOW_YAW = 19 self.J_LELBOW_ROLL = 20 self.J_RELBOW_ROLL = 21 self.J_LTOE_PITCH = 22 self.J_RTOE_PITCH = 23 #------------------ parse robot xml
class Robot(): STEPTIME = 0.02 # Fixed step time VISUALSTEP = 0.04 # Fixed visual step time SQ_STEPTIME = STEPTIME * STEPTIME GRAVITY = np.array([0,0,-9.81]) IMU_DECAY = 0.996 #IMU's velocity decay #------------------ constants to force symmetry in joints/effectors MAP_PERCEPTOR_TO_INDEX = {"hj1":0, "hj2":1, "llj1":2, "rlj1":3, "llj2":4, "rlj2":5, "llj3":6, "rlj3":7, "llj4":8, "rlj4":9, "llj5":10,"rlj5":11, "llj6":12,"rlj6":13,"laj1":14,"raj1":15, "laj2":16,"raj2":17,"laj3":18,"raj3":19, "laj4":20,"raj4":21,"llj7":22,"rlj7":23 } # Fix symmetry issues 1a/4 (identification) FIX_PERCEPTOR_SET = {'rlj2','rlj6','raj2','laj3','laj4'} FIX_INDICES_LIST = [5,13,17,18,20] # Recommended height for unofficial beam (near ground) BEAM_HEIGHTS = [0.4, 0.43, 0.4, 0.46, 0.4] def __init__(self, unum:int, robot_type:int) -> None: robot_xml = "nao"+str(robot_type)+".xml" # Typical NAO file name self.type = robot_type self.beam_height = Robot.BEAM_HEIGHTS[robot_type] self.no_of_joints = 24 if robot_type == 4 else 22 #Fix symmetry issues 1b/4 (identification) self.FIX_EFFECTOR_MASK = np.ones(self.no_of_joints) self.FIX_EFFECTOR_MASK[Robot.FIX_INDICES_LIST] = -1 self.body_parts = dict() # keys='body part names' (given by the robot's XML), values='Body_Part objects' self.unum = unum # Robot's uniform number self.gyro = np.zeros(3) # Angular velocity along the three axes of freedom of the robot's torso (deg/s) self.acc = np.zeros(3) # Proper acceleration along the three axes of freedom of the robot's torso (m/s2) self.frp = dict() # foot "lf"/"rf", toe "lf1"/"rf1" resistance perceptor (relative [p]oint of origin + [f]orce vector) e.g. {"lf":(px,py,pz,fx,fy,fz)} self.feet_toes_last_touch = {"lf":0,"rf":0,"lf1":0,"rf1":0} # foot "lf"/"rf", toe "lf1"/"rf1" World.time_local_ms when foot/toe last touched any surface self.feet_toes_are_touching = {"lf":False,"rf":False,"lf1":False,"rf1":False} # foot "lf"/"rf", toe "lf1"/"rf1" True if touching in last received server message self.fwd_kinematics_list = None # List of body parts, ordered according to dependencies self.rel_cart_CoM_position = np.zeros(3) # Center of Mass position, relative to head, in cartesian coordinates (m) # Joint variables are optimized for performance / array operations self.joints_position = np.zeros(self.no_of_joints) # Joints' angular position (deg) self.joints_speed = np.zeros(self.no_of_joints) # Joints' angular speed (rad/s) self.joints_target_speed = np.zeros(self.no_of_joints) # Joints' target speed (rad/s) (max: 6.1395 rad/s, see rcssserver3d/data/rsg/agent/nao/hingejoint.rsg) self.joints_target_last_speed = np.zeros(self.no_of_joints) # Joints' last target speed (rad/s) (max: 6.1395 rad/s, see rcssserver3d/data/rsg/agent/nao/hingejoint.rsg) self.joints_info = [None] * self.no_of_joints # Joints' constant information (see class Joint_Info) self.joints_transform = [Matrix_4x4() for _ in range(self.no_of_joints)] # Joints' transformation matrix # Localization variables relative to head self.loc_head_to_field_transform = Matrix_4x4() # Transformation matrix from head to field self.loc_field_to_head_transform = Matrix_4x4() # Transformation matrix from field to head self.loc_rotation_head_to_field = Matrix_3x3() # Rotation matrix from head to field self.loc_rotation_field_to_head = Matrix_3x3() # Rotation matrix from field to head self.loc_head_position = np.zeros(3) # Absolute head position (m) self.loc_head_position_history = deque(maxlen=40)# Absolute head position history (queue with up to 40 old positions at intervals of 0.04s, where index 0 is the previous position) self.loc_head_velocity = np.zeros(3) # Absolute head velocity (m/s) (Warning: possibly noisy) self.loc_head_orientation = 0 # Head orientation (deg) self.loc_is_up_to_date = False # False if this is not a visual step, or not enough elements are visible self.loc_last_update = 0 # World.time_local_ms when the localization was last updated self.loc_head_position_last_update = 0 # World.time_local_ms when loc_head_position was last updated by vision or radio self.radio_fallen_state = False # True if (radio says we fell) and (radio is significantly more recent than loc) self.radio_last_update = 0 # World.time_local_ms when radio_fallen_state was last updated (and possibly loc_head_position) # Localization variables relative to torso self.loc_torso_to_field_rotation = Matrix_3x3() # Rotation matrix from torso to field self.loc_torso_to_field_transform = Matrix_4x4() # Transformation matrix from torso to field self.loc_torso_roll = 0 # Torso roll (deg) self.loc_torso_pitch = 0 # Torso pitch (deg) self.loc_torso_orientation = 0 # Torso orientation (deg) self.loc_torso_inclination = 0 # Torso inclination (deg) (inclination of z-axis in relation to field z-axis) self.loc_torso_position = np.zeros(3) # Absolute torso position (m) self.loc_torso_velocity = np.zeros(3) # Absolute torso velocity (m/s) self.loc_torso_acceleration = np.zeros(3) # Absolute Coordinate acceleration (m/s2) # Other localization variables self.cheat_abs_pos = np.zeros(3) # Absolute head position provided by the server as cheat (m) self.cheat_ori = 0.0 # Absolute head orientation provided by the server as cheat (deg) self.loc_CoM_position = np.zeros(3) # Absolute CoM position (m) self.loc_CoM_velocity = np.zeros(3) # Absolute CoM velocity (m/s) # Localization special variables ''' self.loc_head_z is often equivalent to self.loc_head_position[2], but sometimes it differs. There are situations in which the rotation and translation cannot be computed, but the z-coordinate can still be found through vision, in which case: self.loc_is_up_to_date is False self.loc_head_z_is_up_to_date is True It should be used in applications which rely on z as an independent coordinate, such as detecting if the robot has fallen, or as an observation for machine learning. It should NEVER be used for 3D transformations. ''' self.loc_head_z = 0 # Absolute head position (z) - see above for explanation (m) self.loc_head_z_is_up_to_date = False # False if this is not a visual step, or not enough elements are visible self.loc_head_z_last_update = 0 # World.time_local_ms when loc_head_z was last computed self.loc_head_z_vel = 0 # Absolute head velocity (z) (m/s) # Localization + Gyroscope # These variables are reliable. The gyroscope is used to update the rotation when waiting for the next visual cycle self.imu_torso_roll = 0 # Torso roll (deg) (src: Localization + Gyro) self.imu_torso_pitch = 0 # Torso pitch (deg) (src: Localization + Gyro) self.imu_torso_orientation = 0 # Torso orientation (deg) (src: Localization + Gyro) self.imu_torso_inclination = 0 # Torso inclination (deg) (src: Localization + Gyro) self.imu_torso_to_field_rotation = Matrix_3x3() # Rotation matrix from torso to field (src: Localization + Gyro) self.imu_last_visual_update = 0 # World.time_local_ms when the IMU data was last updated with visual information # Localization + Gyroscope + Accelerometer # Warning: these variables are unreliable, since small errors in the Localization Orientation lead to # wrong acceleration -> wrong velocity -> wrong position self.imu_weak_torso_to_field_transform = Matrix_4x4() # Transformation matrix from torso to field (src: Localization + Gyro + Acc) self.imu_weak_head_to_field_transform = Matrix_4x4() # Transformation matrix from head to field (src: Localization + Gyro + Acc) self.imu_weak_field_to_head_transform = Matrix_4x4() # Transformation matrix from field to head (src: Localization + Gyro + Acc) self.imu_weak_torso_position = np.zeros(3) # Absolute torso position (m) (src: Localization + Gyro + Acc) self.imu_weak_torso_velocity = np.zeros(3) # Absolute torso velocity (m/s) (src: Localization + Gyro + Acc) self.imu_weak_torso_acceleration = np.zeros(3) # Absolute torso acceleration (m/s2) (src: Localization + Gyro + Acc) self.imu_weak_torso_next_position = np.zeros(3) # Absolute position in next step estimate (m) (src: Localization + Gyro + Acc) self.imu_weak_torso_next_velocity = np.zeros(3) # Absolute velocity in next step estimate (m/s) (src: Localization + Gyro + Acc) self.imu_weak_CoM_position = np.zeros(3) # Absolute CoM position (m) (src: Localization + Gyro + Acc) self.imu_weak_CoM_velocity = np.zeros(3) # Absolute CoM velocity (m/s) (src: Localization + Gyro + Acc) #Using explicit variables to enable IDE suggestions self.J_HEAD_YAW = 0 self.J_HEAD_PITCH = 1 self.J_LLEG_YAW_PITCH = 2 self.J_RLEG_YAW_PITCH = 3 self.J_LLEG_ROLL = 4 self.J_RLEG_ROLL = 5 self.J_LLEG_PITCH = 6 self.J_RLEG_PITCH = 7 self.J_LKNEE = 8 self.J_RKNEE = 9 self.J_LFOOT_PITCH = 10 self.J_RFOOT_PITCH = 11 self.J_LFOOT_ROLL = 12 self.J_RFOOT_ROLL = 13 self.J_LARM_PITCH = 14 self.J_RARM_PITCH = 15 self.J_LARM_ROLL = 16 self.J_RARM_ROLL = 17 self.J_LELBOW_YAW = 18 self.J_RELBOW_YAW = 19 self.J_LELBOW_ROLL = 20 self.J_RELBOW_ROLL = 21 self.J_LTOE_PITCH = 22 self.J_RTOE_PITCH = 23 #------------------ parse robot xml
dir = M.get_active_directory("/world/commons/robots/")
1
2023-12-16 23:40:23+00:00
24k
Sam-Izdat/tinycio
src/tinycio/lut.py
[ { "identifier": "ColorSpace", "path": "src/tinycio/colorspace.py", "snippet": "class ColorSpace:\n \"\"\"\n Color space conversion. Applies OETFs and EOTFs as needed but omits tonemapping. Cylindrical transformations are \n treated as distinct color spaces. Example:\n\n .. highlight:: python\n .. code-block:: python\n \n cs_in = ColorSpace.Variant.SRGB_LIN\n cs_out = ColorSpace.Variant.OKLAB\n oklab_image = ColorSpace.convert(srgb_image, source=cs_in, destination=cs_out)\n \"\"\"\n class Variant(IntEnum):\n \"\"\"\n Color space enum. For a list of available options, see :ref:`ref_color_spaces`.\n \"\"\"\n UNKNOWN = 1<<0 \n NONCOLOR = 1<<1 \n CIE_XYZ = 1<<2 \n CIE_XYY = 1<<3 \n SRGB = 1<<4 \n SRGB_LIN = 1<<5 \n REC709 = 1<<6 \n REC2020 = 1<<7 \n REC2020_LIN = 1<<8 \n DCI_P3 = 1<<9 \n DCI_P3_LIN = 1<<10 \n DISPLAY_P3 = 1<<11 \n ACESCG = 1<<12 \n ACESCC = 1<<13 \n ACESCCT = 1<<14 \n ACES2065_1 = 1<<15 \n LMS = 1<<16 \n OKLAB = 1<<17 \n CIELAB = 1<<18 \n CIELUV = 1<<19 \n HSV = 1<<20 \n HSL = 1<<21 \n OKHSV = 1<<22\n OKHSL = 1<<23\n\n SCENE_LINEAR = SRGB_LIN | REC2020_LIN | DCI_P3_LIN | ACESCG | ACES2065_1 | CIE_XYZ\n PERCEPTUAL = OKLAB | CIELAB | CIELUV | OKHSL | OKHSV\n CYLINDRICAL = HSL | HSV | OKHSL | OKHSV\n\n GAMUT_SRGB = SRGB | SRGB_LIN | REC709 | HSL | HSV\n GAMUT_AP0 = ACES2065_1\n GAMUT_AP1 = ACESCG | ACESCC | ACESCCT\n GAMUT_REC2020 = REC2020 | REC2020_LIN\n GAMUT_DCI_P3 = DCI_P3 | DCI_P3_LIN\n GAMUT_DISPLAY_P3= DISPLAY_P3\n GAMUT_OKLAB = OKLAB | OKHSL | OKHSV\n GAMUT_CIE_XYZ = CIE_XYZ | CIE_XYY\n GAMUT_CIELAB = CIELAB\n GAMUT_CIELUV = CIELUV\n GAMUT_OTHER = LMS | UNKNOWN | NONCOLOR\n\n WP_D65 = SRGB | SRGB_LIN | REC709 | DISPLAY_P3 | REC2020 | REC2020_LIN | CIE_XYZ | CIE_XYY\n WP_CCT_6300 = DCI_P3 | DCI_P3_LIN\n WP_CCT_6000 = ACESCG | ACESCC | ACESCCT | ACES2065_1\n\n MODEL_RGB = SRGB | SRGB_LIN | REC709 | REC2020 | REC2020_LIN | DCI_P3 | DCI_P3_LIN | DISPLAY_P3 | \\\n ACESCG | ACESCC | ACESCCT | ACES2065_1\n MODEL_CIE = CIE_XYZ | CIE_XYY | CIELAB | CIELUV\n MODEL_CAM = 0\n MODEL_YUV = 0\n MODEL_OTHER = LMS | HSL | HSV | OKLAB # is OKLAB CAM-based?\n \n NEGATIVE = OKLAB | CIELAB | CIELUV | GAMUT_AP0\n NON_NEGATIVE = ~NEGATIVE\n\n DISABLED = CIELUV\n UNSUPPORTED = OKHSV | OKHSL # disabled doesn't go here - CS must have alternate path\n SUPPORTED = ~UNSUPPORTED \n\n # FIXME: LUV doesn't quite match expected values, needs further testing\n\n mat_xyz_to_srgb = [\n [3.24096994190452134, -1.53738317757009346, -0.498610760293003284],\n [-0.969243636280879826, 1.87596750150772067, 0.0415550574071756125],\n [0.0556300796969936084, -0.203976958888976564, 1.05697151424287856]]\n\n mat_srgb_to_xyz = [\n [0.412390799265959481, 0.357584339383877964, 0.180480788401834288],\n [0.212639005871510358, 0.715168678767755927, 0.072192315360733715],\n [0.0193308187155918507, 0.119194779794625988, 0.950532152249660581]]\n\n mat_srgb_to_acescg = [\n [ 0.6130974024, 0.3395231462, 0.04737945141],\n [ 0.07019372247, 0.916353879, 0.01345239847],\n [ 0.02061559288, 0.1095697729, 0.8698146341]]\n\n # NOTE: Includes \"D60\"/D65 white point conversion\n mat_acescg_to_srgb = [\n [ 1.705050993, -0.6217921206,-0.083258872],\n [-0.1302564175, 1.140804737, -0.01054831907],\n [-0.02400335681,-0.1289689761, 1.152972333]]\n\n # NOTE: Includes \"D60\"/D65 white point conversion\n mat_srgb_to_aces2065_1 = [\n [ 0.439632982, 0.382988698, 0.17737832],\n [ 0.0897764431, 0.813439429, 0.0967841284],\n [ 0.0175411704, 0.111546553, 0.870912277]]\n\n mat_aces2065_1_to_srgb = [\n [ 2.52168619, -1.13413099, -0.387555198],\n [-0.276479914, 1.37271909, -0.0962391736],\n [-0.015378065, -0.152975336, 1.1683534]]\n\n mat_srgb_to_displayp3 = [\n [ 0.822461969, 0.177538031, 1.15772692e-10],\n [ 0.0331941989, 0.966805801, 1.95085037e-11],\n [ 0.0170826307, 0.0723974405, 0.910519929]]\n\n mat_displayp3_to_srgb = [\n [ 1.22494018, -0.224940176, -4.77534979e-11],\n [-0.0420569547, 1.04205695, 3.37864801e-11],\n [-0.0196375546,-0.0786360454, 1.0982736]] \n\n # NOTE: No chromatic adaptation\n mat_srgb_to_dcip3 = [\n [0.868579739716132409, 0.128919138460847047, 0.00250112182302054368],\n [0.0345404102543194426, 0.961811386361919975, 0.0036482033837605824],\n [0.0167714290414502718, 0.0710399977868858352, 0.912188573171663893]]\n\n # NOTE: No chromatic adaptation\n mat_dcip3_to_srgb = [\n [ 1.15751640619975871, -0.154962378073857756, -0.00255402812590095854],\n [-0.0415000715306859699, 1.04556792307969925, -0.00406785154901328463],\n [-0.0180500389562539583,-0.0785782726530290654, 1.09662831160928302]]\n\n # NOTE: No chromatic adaptation\n mat_dcip3_to_xyz = [\n [ 0.445169815564552417, 0.277134409206777664, 0.172282669815564564],\n [ 0.209491677912730539, 0.721595254161043636, 0.0689130679262258258],\n [-3.63410131696985616e-17, 0.0470605600539811521, 0.907355394361973415]]\n\n # NOTE: No chromatic adaptation\n mat_xyz_to_dcip3 = [\n [2.7253940304917328, -1.01800300622718496, -0.440163195190036463],\n [-0.795168025808764195, 1.689732054843624, 0.0226471906084774533],\n [0.0412418913957000325, -0.0876390192158623825, 1.10092937864632191]]\n\n mat_srgb_to_rec2020 = [\n [ 0.627403896, 0.329283039, 0.0433130657],\n [ 0.0690972894, 0.919540395, 0.0113623156],\n [ 0.0163914389, 0.0880133077, 0.895595253]]\n\n mat_rec2020_to_srgb = [\n [ 1.660491, -0.587641139,-0.0728498633],\n [-0.124550475, 1.1328999, -0.00834942258],\n [-0.0181507633,-0.100578898, 1.11872966]]\n\n mat_rec2020_to_xyz = [\n [0.636958048301291, 0.144616903586208, 0.168880975164172],\n [0.262700212011267, 0.677998071518871, 0.059301716469862],\n [4.99410657446607e-17, 0.0280726930490874, 1.06098505771079]]\n\n mat_xyz_to_rec2020 = [\n [1.71665118797127, -0.355670783776393, -0.25336628137366],\n [-0.666684351832489, 1.61648123663494, 0.0157685458139111],\n [0.0176398574453108, -0.0427706132578085, 0.942103121235474]]\n\n # NOTE: No chromatic adaptation\n mat_acescg_to_xyz = [\n [ 0.66245418, 0.13400421, 0.15618769],\n [ 0.27222872, 0.67408177, 0.05368952],\n [-0.00557465, 0.00406073, 1.0103391 ]]\n\n # NOTE: No chromatic adaptation\n mat_xyz_to_acescg = [\n [ 1.64102338, -0.32480329, -0.2364247 ],\n [-0.66366286, 1.61533159, 0.01675635],\n [ 0.01172189, -0.00828444, 0.98839486]]\n\n # NOTE: For CIE XYZ color\n mat_d60_to_d65 = [\n [ 0.98722400,-0.00611327, 0.01595330],\n [-0.00759836, 1.00186000, 0.00533002],\n [ 0.00307257,-0.00509595, 1.08168000]]\n\n # NOTE: For CIE XYZ color\n mat_d65_to_d60 = [\n [ 1.01303000, 0.00610531,-0.01497100],\n [ 0.00769823, 0.99816500,-0.00503203],\n [-0.00284131, 0.00468516, 0.92450700]]\n\n # NOTE: For CIE XYZ color\n mat_d65_to_dci = [\n [0.976578896646979768, -0.0154362646984919742, -0.016686021704209866],\n [-0.0256896658505145926, 1.02853916787996963, -0.00378517365630504153],\n [-0.00570574587417104179, 0.0110778657389971485, 0.871176159390377409]]\n \n # NOTE: For CIE XYZ color\n mat_dci_to_d65 = [\n [1.02449672775257752, 0.0151635410224165156, 0.0196885223342066827],\n [0.0256121933371584198, 0.97258630562441342, 0.00471635229242730096],\n [0.0063842306500876874, -0.012268082736730219, 1.14794244517367791]]\n\n mat_xyz_to_lms = [\n [ 0.8951, 0.2664,-0.1614],\n [-0.7502, 1.7135, 0.0367],\n [ 0.0389,-0.0685, 1.0296]]\n\n mat_lms_to_xyz = [\n [ 0.986993, -0.147054, 0.159963],\n [ 0.432305, 0.51836, 0.0492912],\n [ -0.00852866, 0.0400428, 0.968487]]\n\n # OKLAB's XYZ to LMS\n mat_oklab_m1 = [\n [ 0.8189330101, 0.3618667424, -0.1288597137],\n [ 0.0329845436, 0.9293118715, 0.0361456387],\n [ 0.0482003018, 0.2643662691, 0.6338517070]]\n\n # OKLAB's non-linear L'M'S' to OKLAB\n mat_oklab_m2 = [\n [ 0.2104542553, 0.7936177850, -0.0040720468],\n [ 1.9779984951, -2.4285922050, 0.4505937099],\n [ 0.0259040371, 0.7827717662, -0.8086757660]]\n\n # Inverse of OKLAB M1\n mat_oklab_m1_inv = [\n [ 1.22701385, -0.55779998, 0.28125615],\n [-0.04058018, 1.11225687, -0.07167668],\n [-0.07638128, -0.42148198, 1.58616322]]\n\n # Inverse of OKLAB M2\n mat_oklab_m2_inv = [\n [ 1. , 0.39633779, 0.21580376],\n [ 1.00000001, -0.10556134, -0.06385417],\n [ 1.00000005, -0.08948418, -1.29148554]]\n\n @classmethod\n def convert(cls, im:Union[torch.Tensor, ColorImage], source:Variant, destination:Variant) -> torch.Tensor:\n \"\"\"\n Change the color space of an image. Cylindrical transformations HSV/HSL are \n treated as their own color spaces and assumed to be relative to sRGB linear. \n Unless otherwise noted or required by specification (e.g. ACES), we assume D65 white point.\n\n .. warning::\n\n Tone mapping is not included, so converting the color space of HDR values to \n an LDR-designated color space will not automatically reduce dynamic range. For example, \n taking an HDR image from :code:`ACESCG` (AP1) to :code:`SRGB` will yield the sRGB \n gamma curve, but values outside the required range must still be tone mapped or clamped beforehand.\n\n .. warning::\n\n Cylindrical transformations (HSL, HSV) should be given input in [0, 1] linear sRGB range \n (or equivalent). This is not strictly enforced but input outside this range may yield \n unpredictable results or *NaN* values.\n\n :param im: [C=3, H, W] image tensor \n :type im: torch.Tensor | ColorImage\n :param source: color space to convert from\n :param destination: color space to convert to\n :return: image tensor in designated color space\n \"\"\"\n ip, op = source, destination\n cs = cls.Variant\n tf = TransferFunction\n if ip == op: return im\n\n assert im.dim() == 3 and im.size(0) == 3, f\"expected [C=3, H, W] image tensor, got {im.size()}\"\n assert source != 0, f\"Unknown source color space\"\n assert ip & cs.SUPPORTED, f\"Source color space not supported: {source.name}\"\n assert op & cs.SUPPORTED, f\"Destination color space not supported: {destination.name}\"\n assert ip & ~cs.DISABLED, f\"Source color space disabled: {ColorSpace.Variant(ip).name}\"\n assert op & ~cs.DISABLED, f\"Destination color space disabled: {ColorSpace.Variant(op).name}\"\n\n err_not_implemented = f\"Color space conversion not implemented: {ColorSpace.Variant(ip).name} to {ColorSpace.Variant(op).name}\" \n\n # Direct path where it matters, loop-de-loop elsewhere\n if ip == cs.SRGB_LIN:\n if op == cs.SRGB: im = tf.srgb_oetf(im)\n elif op == cs.REC709: im = tf.rec709_oetf(im)\n elif op == cs.REC2020: im = tf.rec2020_oetf(mm(im, cls.mat_srgb_to_rec2020))\n elif op == cs.REC2020_LIN: im = mm(im, cls.mat_srgb_to_rec2020)\n elif op == cs.DCI_P3: im = tf.dcip3_oetf(mm(mm(mm(im, cls.mat_srgb_to_xyz), cls.mat_d65_to_dci), cls.mat_xyz_to_dcip3))\n elif op == cs.DCI_P3_LIN: im = mm(mm(mm(im, cls.mat_srgb_to_xyz), cls.mat_d65_to_dci), cls.mat_xyz_to_dcip3)\n elif op == cs.DISPLAY_P3: im = tf.srgb_oetf(mm(im, cls.mat_srgb_to_displayp3))\n elif op == cs.CIE_XYZ: im = mm(im, cls.mat_srgb_to_xyz)\n elif op == cs.CIE_XYY: im = cls._xyz_to_xyy(mm(im, cls.mat_srgb_to_xyz))\n elif op == cs.LMS: im = cls._xyz_to_lms(mm(im, cls.mat_srgb_to_xyz))\n elif op == cs.ACESCG: im = mm(im, cls.mat_srgb_to_acescg)\n elif op == cs.ACESCC: im = cls._acescg_to_acescc(mm(im, cls.mat_srgb_to_acescg))\n elif op == cs.ACES2065_1: im = mm(im, cls.mat_srgb_to_aces2065_1)\n elif op == cs.CIELAB: im = cls._xyz_to_cielab(mm(im, cls.mat_srgb_to_xyz))\n elif op == cs.CIELUV: im = cls._xyz_to_cieluv(mm(im, cls.mat_srgb_to_xyz))\n elif op == cs.OKLAB: im = cls._rgb_to_oklab(im)\n elif op == cs.HSL: im = cls._rgb_to_hsl(tf.srgb_oetf(im))\n elif op == cs.HSV: im = cls._rgb_to_hsv(tf.srgb_oetf(im))\n else: raise Exception(err_not_implemented)\n elif ip == cs.SRGB:\n if op == cs.HSL: im = cls._rgb_to_hsl(im)\n elif op == cs.HSV: im = cls._rgb_to_hsv(im)\n else: im = cls.convert(tf.srgb_eotf(im), cs.SRGB_LIN, op)\n elif ip == cs.REC709: im = cls.convert(tf.rec709_eotf(im), cs.SRGB_LIN, op)\n elif ip == cs.REC2020: \n if op == cs.REC2020_LIN: im = tf.rec2020_eotf(im)\n elif op == cs.CIE_XYZ: im = mm(tf.rec2020_eotf(im), cls.mat_rec2020_to_xyz)\n elif op == cs.SRGB_LIN: im = mm(tf.rec2020_eotf(im), cls.mat_rec2020_to_srgb)\n else: im = cls.convert(mm(tf.rec2020_eotf(im), cls.mat_rec2020_to_srgb), cs.SRGB_LIN, op)\n elif ip == cs.REC2020_LIN: \n if op == cs.REC2020: im = tf.rec2020_oetf(im)\n elif op == cs.CIE_XYZ: im = mm(im, cls.mat_rec2020_to_xyz)\n elif op == cs.SRGB_LIN: im = mm(im, cls.mat_rec2020_to_srgb)\n else: im = cls.convert(mm(im, cls.mat_rec2020_to_srgb), cs.SRGB_LIN, op)\n elif ip == cs.DCI_P3: \n if op == cs.DCI_P3_LIN: im = tf.dcip3_eotf(im)\n elif op == cs.CIE_XYZ: im = mm(mm(tf.dcip3_eotf(im), cls.mat_dcip3_to_xyz), cls.mat_dci_to_d65)\n else: im = cls.convert(mm(mm(tf.dcip3_eotf(im), cls.mat_dcip3_to_xyz), cls.mat_dci_to_d65), cs.CIE_XYZ, op)\n elif ip == cs.DCI_P3_LIN: \n if op == cs.DCI_P3: im = tf.dcip3_oetf(im)\n elif op == cs.CIE_XYZ: im = mm(mm(im, cls.mat_dcip3_to_xyz), cls.mat_dci_to_d65)\n else: im = cls.convert(mm(mm(im, cls.mat_dcip3_to_xyz), cls.mat_dci_to_d65), cs.CIE_XYZ, op)\n elif ip == cs.DISPLAY_P3: im = cls.convert(mm(tf.srgb_eotf(im), cls.mat_displayp3_to_srgb), cs.SRGB_LIN, op)\n elif ip == cs.CIE_XYZ:\n if op == cs.CIE_XYY: im = cls._xyz_to_xyy(im)\n elif op == cs.REC2020_LIN: im = mm(im, cls.mat_xyz_to_rec2020)\n elif op == cs.REC2020: im = tf.rec2020_oetf(mm(im, cls.mat_xyz_to_rec2020))\n elif op == cs.DCI_P3_LIN: im = mm(mm(im, cls.mat_d65_to_dci), cls.mat_xyz_to_dcip3)\n elif op == cs.DCI_P3: im = tf.dcip3_oetf(mm(mm(im, cls.mat_d65_to_dci), cls.mat_xyz_to_dcip3))\n elif op == cs.LMS: im = cls._xyz_to_lms(im)\n elif op == cs.ACESCG: im = mm(cls._d65_to_d60(im), cls.mat_xyz_to_acescg)\n elif op == cs.CIELAB: im = cls._xyz_to_cielab(im)\n elif op == cs.CIELUV: im = cls._xyz_to_cieluv(im)\n elif op == cs.OKLAB: im = cls._xyz_to_oklab(im)\n else: im = cls.convert(mm(im, cls.mat_xyz_to_srgb), cs.SRGB_LIN, op)\n elif ip == cs.CIE_XYY: \n if op == cs.CIE_XYZ: im = cls._xyy_to_xyz(im)\n else: im = cls.convert(cls._xyy_to_xyz(im), cs.CIE_XYZ, op)\n elif ip == cs.LMS: \n if op == cs.CIE_XYZ: im = cls._lms_to_xyz(im)\n else: im = cls.convert(cls._lms_to_xyz(im), cs.CIE_XYZ, op)\n elif ip == cs.ACESCG:\n # if op == cs.CIE_XYZ: im = cls._d60_to_d65(mm(im, cls.mat_acescg_to_xyz)) # FIXME: fails unit test (?)\n if op == cs.ACESCC: im = cls._acescg_to_acescc(im)\n else: im = cls.convert(mm(im, cls.mat_acescg_to_srgb), cs.SRGB_LIN, op)\n elif ip == cs.ACESCC:\n if op == cs.ACESCG: im = cls._acescc_to_acescg(im)\n else: im = cls.convert(cls._acescc_to_acescg(im), cs.ACESCG, op)\n elif ip == cs.ACES2065_1: im = cls.convert(mm(im, cls.mat_aces2065_1_to_srgb), cs.SRGB_LIN, op)\n elif ip == cs.HSL:\n if op == cs.SRGB: im = cls._hsl_to_rgb(im)\n else: im = cls.convert(tf.srgb_eotf(cls._hsl_to_rgb(im)), cs.SRGB_LIN, op)\n elif ip == cs.HSV:\n if op == cs.SRGB: im = cls._hsv_to_rgb(im)\n else: im = cls.convert(tf.srgb_eotf(cls._hsv_to_rgb(im)), cs.SRGB_LIN, op)\n elif ip == cs.CIELAB: im = cls.convert(cls._cielab_to_xyz(im), cs.CIE_XYZ, op)\n elif ip == cs.CIELUV: im = cls.convert(cls._cieluv_to_xyz(im), cs.CIE_XYZ, op)\n elif ip == cs.OKLAB:\n if op == cs.CIE_XYZ: im = cls._oklab_to_xyz(im)\n else: im = cls.convert(cls._oklab_to_rgb(im), cs.SRGB_LIN, op)\n else: raise Exception(err_not_implemented)\n\n return im\n\n @classmethod\n def _xyz_to_xyy(cls, xyz:torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert CIE XYZ color space to CIE xyY color space.\n\n :param xyz: Input CIE XYZ color space tensor\n :return: CIE xyY color space tensor\n \"\"\"\n X = xyz[0:1]\n Y = xyz[1:2]\n Z = xyz[2:3]\n x = X / (X + Y + Z)\n y = Y / (X + Y + Z)\n return torch.cat([x, y, Y], dim=0)\n\n @classmethod\n def _xyy_to_xyz(cls, xyy:torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert CIE xyY color space to CIE XYZ color space.\n\n :param xyy: Input CIE xyY color space tensor\n :return: CIE XYZ color space tensor\n \"\"\"\n x = xyy[0:1]\n y = xyy[1:2]\n Y = xyy[2:3]\n X = (Y / y) * x\n Z = (Y / y) * (1. - x - y)\n return torch.cat([X, Y, Z], dim=0)\n\n @classmethod\n def _xyz_to_lms(cls, xyz:torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert CIE XYZ color space to LMS color space.\n\n :param xyz: Input CIE XYZ color space tensor\n :return: LMS color space tensor\n \"\"\"\n return mm(xyz, cls.mat_xyz_to_lms)\n\n @classmethod\n def _lms_to_xyz(cls, lms:torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert LMS color space to CIE XYZ color space.\n\n :param lms: Input LMS color space tensor\n :return: CIE XYZ color space tensor\n \"\"\"\n return mm(lms, cls.mat_lms_to_xyz)\n\n @classmethod\n def _acescg_to_acescc(cls, cg:torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert scene-linear ACEScg to log ACEScc.\n\n :param lms: Input ACEScg color space tensor\n :return: ACEScc color space tensor\n \"\"\"\n res = torch.where(cg < 0.00003051757, \n (torch.log2(0.00001525878 + cg * 0.5) + 9.72) / 17.52, \n (torch.log2(cg) + 9.72) / 17.52)\n return res\n\n @classmethod\n def _acescc_to_acescg(cls, cc:torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert log ACEScc to scene-linear ACEScg.\n\n :param lms: Input ACEScc color space tensor\n :return: ACEScg color space tensor\n \"\"\"\n res = torch.where(cc < -0.3013698630, \n (torch.exp2(cc * 17.52 - 9.72) - 0.00001525878) * 2,\n torch.exp2(cc * 17.52 - 9.72))\n return res\n\n @classmethod\n def _xyz_to_oklab(cls, xyz:torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert CIE XYZ color space to OKLAB color space.\n\n :param xyz: Input CIE XYZ color space tensor\n :return: OKLAB color space tensor\n \"\"\" \n lms = mm(xyz, cls.mat_oklab_m1)\n lms_p = torch.pow(torch.abs(lms), 0.3333333333) * torch.sign(lms).float()\n lab = mm(lms_p, cls.mat_oklab_m2)\n return lab\n\n @classmethod\n def _oklab_to_xyz(cls, lab:torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert OKLAB color space to CIE XYZ color space.\n\n :param lab: Input OKLAB color space tensor\n :return: CIE XYZ color space tensor\n \"\"\"\n lms_p = mm(lab, cls.mat_oklab_m2_inv)\n lms = torch.pow(lms_p, 3.)\n xyz = mm(lms, cls.mat_oklab_m1_inv)\n return xyz\n\n\n @classmethod\n def __pivot_xyz_to_lab(cls, val): \n return torch.where(val > 0.008856, torch.pow(val, 0.3333333333), ((val * 903.3) + 16.0) / 116.0)\n\n @classmethod\n def _xyz_to_cielab(cls, xyz:torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert color space from CIE XYZ to CIELAB.\n\n :param xyz: Input CIE XYZ color space tensor\n :return: CIELAB color space tensor\n \"\"\"\n # https://github.com/CairX/convert-colors-py/blob/master/convcolors/__init__.py\n # MIT License\n\n # Copyright (c) 2022 Thomas Cairns\n\n # Permission is hereby granted, free of charge, to any person obtaining a copy\n # of this software and associated documentation files (the \"Software\"), to deal\n # in the Software without restriction, including without limitation the rights\n # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n # copies of the Software, and to permit persons to whom the Software is\n # furnished to do so, subject to the following conditions:\n\n # The above copyright notice and this permission notice shall be included in all\n # copies or substantial portions of the Software.\n\n # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n # SOFTWARE. \n x = xyz[0:1] / 0.95047 \n y = xyz[1:2] / 1.00000 \n z = xyz[2:3] / 1.08883 \n\n x = cls.__pivot_xyz_to_lab(x)\n y = cls.__pivot_xyz_to_lab(y)\n z = cls.__pivot_xyz_to_lab(z)\n\n l = torch.maximum(torch.zeros_like(y).to(y.device), (116.0 * y) - 16.0)\n a = (x - y) * 500.0\n b = (y - z) * 200.0\n return torch.cat([l, a, b], dim=0)\n\n @classmethod\n def _cielab_to_xyz(cls, lab:torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert color space from CIELAB to CIE XYZ.\n \n .. note::\n\n Assumes D65 standard illuminant.\n\n :param lab: Input CIELAB color space tensor\n :return: CIE XYZ color space tensor\n \"\"\"\n # https://github.com/CairX/convert-colors-py/blob/master/convcolors/__init__.py\n # MIT License\n\n # Copyright (c) 2022 Thomas Cairns\n\n # Permission is hereby granted, free of charge, to any person obtaining a copy\n # of this software and associated documentation files (the \"Software\"), to deal\n # in the Software without restriction, including without limitation the rights\n # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n # copies of the Software, and to permit persons to whom the Software is\n # furnished to do so, subject to the following conditions:\n\n # The above copyright notice and this permission notice shall be included in all\n # copies or substantial portions of the Software.\n\n # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n # SOFTWARE.\n l = lab[0:1]\n a = lab[1:2]\n b = lab[2:3]\n\n # Reminder: The y values is calculated first as it can be reused\n # for the calculation of x and z.\n y = (l + 16.0) / 116.0\n x = y + (a / 500.0)\n z = y - (b / 200.0)\n\n x3 = x * x * x\n z3 = z * z * z\n y3 = y * y * y\n\n x = torch.where(x3 > 0.008856, x3, ((x * 116.0) - 16.0) / 903.3)\n y = torch.where(l > 7.9996248, y3, l / 903.3)\n z = torch.where(z3 > 0.008856, z3, ((z * 116.0) - 16.0) / 903.3)\n\n x = x * 0.95047 \n y = y * 1.00000 \n z = z * 1.08883\n\n return torch.cat([x, y, z], dim=0)\n\n def _xyz_to_cieluv(image:torch.Tensor) -> torch.Tensor:\n \"\"\"\n Converts CIE XYZ to CIELUV. \n \n .. note::\n\n Assumes D65 standard illuminant.\n\n :param image: A pytorch tensor of shape (3, n_pixels_x, n_pixels_y) in which the channels are X, Y, Z\n :return: A pytorch tensor of shape (3, n_pixels_x, n_pixels_y) in which the channels are L, U, V\n \"\"\"\n # https://github.com/stefanLeong/S2CRNet/blob/main/scripts/utils/color.py\n # MIT License\n\n # Copyright (c) 2021 StefanLeong\n\n # Permission is hereby granted, free of charge, to any person obtaining a copy\n # of this software and associated documentation files (the \"Software\"), to deal\n # in the Software without restriction, including without limitation the rights\n # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n # copies of the Software, and to permit persons to whom the Software is\n # furnished to do so, subject to the following conditions:\n\n # The above copyright notice and this permission notice shall be included in all\n # copies or substantial portions of the Software.\n\n # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n # SOFTWARE.\n if len(image.size()) == 3:\n small_L = (29. / 3) ** 3 * image[1]\n large_L = 116 * torch.pow(image[1], 1 / 3.) - 16\n L = torch.where(image[1] <= (6. / 29) ** 3, small_L, large_L)\n\n denom = (image[0] + 15 * image[1] + 3 * image[2])\n u_prime = torch.where(denom != 0., 4 * image[0] / denom, 0.)\n v_prime = torch.where(denom != 0., 9 * image[1] / denom, 0.)\n d = 0\n elif len(image.size()) == 4:\n small_L = (29. / 3) ** 3 * image[:, 1]\n large_L = 116 * torch.pow(image[:, 1], 1 / 3.) - 16\n L = torch.where(image[:, 1] <= (6. / 29) ** 3, small_L, large_L)\n\n denom = (image[:, 0] + 15 * image[:, 1] + 3 * image[:, 2])\n u_prime = torch.where(denom > 0., 4 * image[:, 0] / denom, 0.)\n v_prime = torch.where(denom > 0., 9 * image[:, 1] / denom, 0.)\n d = 1\n\n u = 13 * L * (u_prime - .2009)\n v = 13 * L * (v_prime - .4610)\n\n luv_image = torch.stack((L, u, v), dim=d)\n\n return luv_image\n\n def _cieluv_to_xyz(image:torch.Tensor) -> torch.Tensor:\n \"\"\"\n Converts CIELUV to CIE XYZ. \n \n .. note::\n\n Assumes D65 standard illuminant.\n\n :param image: A pytorch tensor of shape (3, n_pixels_x, n_pixels_y) in which the channels are L, U, V\n :return: A pytorch tensor of shape (3, n_pixels_x, n_pixels_y) in which the channels are X, Y, Z\n \"\"\"\n # https://github.com/stefanLeong/S2CRNet/blob/main/scripts/utils/color.py\n # MIT License\n\n # Copyright (c) 2021 StefanLeong\n\n # Permission is hereby granted, free of charge, to any person obtaining a copy\n # of this software and associated documentation files (the \"Software\"), to deal\n # in the Software without restriction, including without limitation the rights\n # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n # copies of the Software, and to permit persons to whom the Software is\n # furnished to do so, subject to the following conditions:\n\n # The above copyright notice and this permission notice shall be included in all\n # copies or substantial portions of the Software.\n\n # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n # SOFTWARE.\n if len(image.size()) == 3:\n denom = (13 * image[0])\n u_prime = torch.where(denom != 0., image[1] / denom, 0.) + .2009\n v_prime = torch.where(denom != 0., image[2] / denom, 0.) + .4610\n\n small_Y = image[0] * (3. / 29) ** 3\n large_Y = ((image[0] + 16.) / 116.) ** 3\n\n Y = torch.where(image[0] <= 8, small_Y, large_Y)\n d = 0\n # batch of images\n elif len(image.size()) == 4:\n denom = (13 * image[:, 0])\n u_prime = torch.where(denom != 0., image[:, 1] / denom, 0.) + .2009\n v_prime = torch.where(denom != 0., image[:, 2] / denom, 0.) + .4610\n\n small_Y = image[:, 0] * (3. / 29) ** 3\n large_Y = ((image[:, 0] + 16.) / 116.) ** 3\n\n Y = torch.where(image[:, 0] <= 8, small_Y, large_Y)\n d = 1\n\n X = torch.where(v_prime != 0., Y * 9 * u_prime / (4 * v_prime), 0.)\n Z = torch.where(v_prime != 0., Y * (12 - 3 * u_prime - 20 * v_prime) / (4 * v_prime), 0.)\n\n xyz_image = torch.stack((X, Y, Z), dim=d)\n\n return xyz_image\n\n @classmethod\n def _rgb_to_oklab(cls, rgb:torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert color space from linear sRGB to OKLAB.\n\n :param rgb: Input linear sRGB color space tensor\n :return: OKLAB color space tensor\n \"\"\"\n cr = rgb[0:1]\n cg = rgb[1:2]\n cb = rgb[2:3]\n\n l = 0.4122214708 * cr + 0.5363325363 * cg + 0.0514459929 * cb;\n m = 0.2119034982 * cr + 0.6806995451 * cg + 0.1073969566 * cb;\n s = 0.0883024619 * cr + 0.2817188376 * cg + 0.6299787005 * cb;\n\n l_ = torch.pow(torch.abs(l), 0.3333333333) * torch.sign(l).float()\n m_ = torch.pow(torch.abs(m), 0.3333333333) * torch.sign(m).float()\n s_ = torch.pow(torch.abs(s), 0.3333333333) * torch.sign(s).float()\n\n return torch.cat([\n 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,\n 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,\n 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_], dim=0)\n\n @classmethod\n def _oklab_to_rgb(cls, lab:torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert color space from OKLAB to linear sRGB.\n\n :param lab: Input OKLAB color space tensor\n :return: Linear sRGB color space tensor\n \"\"\"\n cl = lab[0:1]\n ca = lab[1:2]\n cb = lab[2:3]\n\n l_ = cl + 0.3963377774 * ca + 0.2158037573 * cb\n m_ = cl - 0.1055613458 * ca - 0.0638541728 * cb\n s_ = cl - 0.0894841775 * ca - 1.2914855480 * cb\n\n l = l_*l_*l_\n m = m_*m_*m_\n s = s_*s_*s_\n\n return torch.cat([\n +4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,\n -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,\n -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s], dim=0)\n\n @classmethod\n def _rgb_to_hsl(cls, rgb: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Transform sRGB image tensor to sRGB-relative HSL. \n \n .. note::\n\n expects non-linear sRGB w/ gamma curve as input\n\n :param rgb: Input sRGB image tensor\n :return: HSL image tensor\n \"\"\"\n # https://github.com/windingwind/seal-3d/blob/main/SealNeRF/color_utils.py\n # MIT License\n\n # Copyright (c) 2022 hawkey\n\n # Permission is hereby granted, free of charge, to any person obtaining a copy\n # of this software and associated documentation files (the \"Software\"), to deal\n # in the Software without restriction, including without limitation the rights\n # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n # copies of the Software, and to permit persons to whom the Software is\n # furnished to do so, subject to the following conditions:\n\n # The above copyright notice and this permission notice shall be included in all\n # copies or substantial portions of the Software.\n\n # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n # SOFTWARE.\n rgb = rgb.unsqueeze(0)\n cmax, cmax_idx = torch.max(rgb, dim=1, keepdim=True)\n cmin = torch.min(rgb, dim=1, keepdim=True)[0]\n delta = cmax - cmin\n hsl_h = torch.empty_like(rgb[:, 0:1, :, :])\n cmax_idx[delta == 0] = 3\n hsl_h[cmax_idx == 0] = (((rgb[:, 1:2] - rgb[:, 2:3]) / delta) % 6)[cmax_idx == 0]\n hsl_h[cmax_idx == 1] = (((rgb[:, 2:3] - rgb[:, 0:1]) / delta) + 2)[cmax_idx == 1]\n hsl_h[cmax_idx == 2] = (((rgb[:, 0:1] - rgb[:, 1:2]) / delta) + 4)[cmax_idx == 2]\n hsl_h[cmax_idx == 3] = 0.\n hsl_h /= 6.\n\n hsl_l = (cmax + cmin) / 2.\n hsl_s = torch.empty_like(hsl_h)\n hsl_s[hsl_l == 0] = 0\n hsl_s[hsl_l == 1] = 0\n hsl_l_ma = torch.bitwise_and(hsl_l > 0, hsl_l < 1)\n hsl_l_s0_5 = torch.bitwise_and(hsl_l_ma, hsl_l <= 0.5)\n hsl_l_l0_5 = torch.bitwise_and(hsl_l_ma, hsl_l > 0.5)\n hsl_s[hsl_l_s0_5] = ((cmax - cmin) / (hsl_l * 2.))[hsl_l_s0_5]\n hsl_s[hsl_l_l0_5] = ((cmax - cmin) / (- hsl_l * 2. + 2.))[hsl_l_l0_5]\n return torch.cat([hsl_h, hsl_s, hsl_l], dim=1).squeeze(0)\n\n @classmethod\n def _hsl_to_rgb(cls, hsl: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Transform sRGB-relative HSL image tensor to sRGB. \n \n .. note::\n\n returns non-linear sRGB w/ gamma curve as output\n\n :param hsl: Input HSL image tensor\n :return: sRGB image tensor\n \"\"\"\n # https://github.com/windingwind/seal-3d/blob/main/SealNeRF/color_utils.py\n # MIT License\n\n # Copyright (c) 2022 hawkey\n\n # Permission is hereby granted, free of charge, to any person obtaining a copy\n # of this software and associated documentation files (the \"Software\"), to deal\n # in the Software without restriction, including without limitation the rights\n # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n # copies of the Software, and to permit persons to whom the Software is\n # furnished to do so, subject to the following conditions:\n\n # The above copyright notice and this permission notice shall be included in all\n # copies or substantial portions of the Software.\n\n # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n # SOFTWARE.\n hsl = hsl.unsqueeze(0)\n hsl_h, hsl_s, hsl_l = hsl[:, 0:1], hsl[:, 1:2], hsl[:, 2:3]\n _c = (-torch.abs(hsl_l * 2. - 1.) + 1) * hsl_s\n _x = _c * (-torch.abs(hsl_h * 6. % 2. - 1) + 1.)\n _m = hsl_l - _c / 2.\n idx = (hsl_h * 6.).type(torch.uint8)\n idx = (idx % 6).expand(-1, 3, -1, -1)\n rgb = torch.empty_like(hsl).to(hsl.device)\n _o = torch.zeros_like(_c).to(hsl.device)\n rgb[idx == 0] = torch.cat([_c, _x, _o], dim=1)[idx == 0]\n rgb[idx == 1] = torch.cat([_x, _c, _o], dim=1)[idx == 1]\n rgb[idx == 2] = torch.cat([_o, _c, _x], dim=1)[idx == 2]\n rgb[idx == 3] = torch.cat([_o, _x, _c], dim=1)[idx == 3]\n rgb[idx == 4] = torch.cat([_x, _o, _c], dim=1)[idx == 4]\n rgb[idx == 5] = torch.cat([_c, _o, _x], dim=1)[idx == 5]\n rgb += _m\n return rgb.squeeze(0)\n\n @classmethod\n def _rgb_to_hsv(cls, rgb: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Transform sRGB image tensor to sRGB-relative HSV. \n \n .. note::\n\n expects non-linear sRGB w/ gamma curve as input\n\n .. warning::\n\n input tensor will be clamped to [0, 1] range\n\n :param rgb: Input sRGB image tensor\n :return: HSV image tensor\n \"\"\"\n # https://github.com/windingwind/seal-3d/blob/main/SealNeRF/color_utils.py\n # MIT License\n\n # Copyright (c) 2022 hawkey\n\n # Permission is hereby granted, free of charge, to any person obtaining a copy\n # of this software and associated documentation files (the \"Software\"), to deal\n # in the Software without restriction, including without limitation the rights\n # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n # copies of the Software, and to permit persons to whom the Software is\n # furnished to do so, subject to the following conditions:\n\n # The above copyright notice and this permission notice shall be included in all\n # copies or substantial portions of the Software.\n\n # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n # SOFTWARE.\n rgb = rgb.clamp(0.,1.).unsqueeze(0)\n cmax, cmax_idx = torch.max(rgb, dim=1, keepdim=True)\n cmin = torch.min(rgb, dim=1, keepdim=True)[0]\n delta = cmax - cmin\n hsv_h = torch.empty_like(rgb[:, 0:1, :, :])\n cmax_idx[delta == 0] = 3\n hsv_h[cmax_idx == 0] = (((rgb[:, 1:2] - rgb[:, 2:3]) / delta) % 6)[cmax_idx == 0]\n hsv_h[cmax_idx == 1] = (((rgb[:, 2:3] - rgb[:, 0:1]) / delta) + 2)[cmax_idx == 1]\n hsv_h[cmax_idx == 2] = (((rgb[:, 0:1] - rgb[:, 1:2]) / delta) + 4)[cmax_idx == 2]\n hsv_h[cmax_idx == 3] = 0.\n hsv_h /= 6.\n hsv_s = torch.where(cmax == 0, torch.tensor(0.).type_as(rgb), delta / cmax)\n hsv_v = cmax\n return torch.cat([hsv_h, hsv_s, hsv_v], dim=1).squeeze(0)\n\n @classmethod\n def _hsv_to_rgb(cls, hsv: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Transform sRGB-relative HSV image tensor to sRGB. \n \n .. note::\n \n returns non-linear sRGB w/ gamma curve as output\n\n :param hsv: Input HSV image tensor\n :return: sRGB image tensor\n \"\"\"\n # https://github.com/windingwind/seal-3d/blob/main/SealNeRF/color_utils.py\n # MIT License\n\n # Copyright (c) 2022 hawkey\n\n # Permission is hereby granted, free of charge, to any person obtaining a copy\n # of this software and associated documentation files (the \"Software\"), to deal\n # in the Software without restriction, including without limitation the rights\n # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n # copies of the Software, and to permit persons to whom the Software is\n # furnished to do so, subject to the following conditions:\n\n # The above copyright notice and this permission notice shall be included in all\n # copies or substantial portions of the Software.\n\n # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n # SOFTWARE.\n hsv = hsv.unsqueeze(0)\n hsv_h, hsv_s, hsv_l = hsv[:, 0:1], hsv[:, 1:2], hsv[:, 2:3]\n _c = hsv_l * hsv_s\n _x = _c * (- torch.abs(hsv_h * 6. % 2. - 1) + 1.)\n _m = hsv_l - _c\n _o = torch.zeros_like(_c).to(hsv.device)\n idx = (hsv_h * 6.).type(torch.uint8)\n idx = (idx % 6).expand(-1, 3, -1, -1)\n rgb = torch.empty_like(hsv).to(hsv.device)\n rgb[idx == 0] = torch.cat([_c, _x, _o], dim=1)[idx == 0]\n rgb[idx == 1] = torch.cat([_x, _c, _o], dim=1)[idx == 1]\n rgb[idx == 2] = torch.cat([_o, _c, _x], dim=1)[idx == 2]\n rgb[idx == 3] = torch.cat([_o, _x, _c], dim=1)[idx == 3]\n rgb[idx == 4] = torch.cat([_x, _o, _c], dim=1)[idx == 4]\n rgb[idx == 5] = torch.cat([_c, _o, _x], dim=1)[idx == 5]\n rgb += _m\n return rgb.squeeze(0)\n\n @classmethod\n def _d60_to_d65(cls, im:torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert CIE XYZ image from \"D60\" to D65 white point.\n\n :param im: Input image tensor\n :return: Converted image tensor\n \"\"\"\n # There is not really a CIE D60 white point, but that's what everyone calls what ACES uses.\n return mm(im, cls.mat_d60_to_d65)\n\n @classmethod\n def _d65_to_d60(cls, im:torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert CIE XYZ image from D65 to \"D60\" white point.\n\n :param torch.Tensor im: Input image tensor\n :return: Converted image tensor\n \"\"\"\n return mm(im, cls.mat_d65_to_d60)" }, { "identifier": "load_lut", "path": "src/tinycio/fsio/lutfile.py", "snippet": "def load_lut(fp:str, lut_format:LUTFormat=LUTFormat.UNKNOWN) -> torch.Tensor:\n \"\"\"\n Load LUT from file.\n\n :param fp: File path to load from.\n :param lut_format: Format of the LUT.\n :return: lattice as PyTorch tensor\n \"\"\"\n fp = os.path.realpath(fp)\n fn, fnext = os.path.splitext(fp)\n if lut_format == LUTFormat.UNKNOWN: lut_format = _infer_lut_file_format(fnext)\n assert lut_format > LUTFormat.UNKNOWN, \"Unrecognized LUT format\"\n lattice = None\n if lut_format == LUTFormat.CUBE_3D:\n with open(fp, 'r') as file:\n # Read lines and filter out comments\n lines = [line.strip() for line in file.readlines() if len(line) > 0 and \"#\" not in line]\n\n # Find the line indicating the start of the LUT data\n lut_start_index = next((i for i, line in enumerate(lines) if line.startswith('LUT_3D_SIZE')), None)\n\n if lut_start_index is None: raise ValueError(\"LUT_3D_SIZE indicator not found in the .cube file.\")\n\n # Extract LUT data\n lut_data = [list(map(float, line.split())) for line in lines[lut_start_index + 1:] \\\n if len(line) > 0 and len(line.split()) == 3 and \"#\" not in line] \n\n # Convert the LUT data to a PyTorch tensor\n lut_size = int(lines[lut_start_index].split()[1])\n\n lattice = torch.tensor(lut_data).view(lut_size, lut_size, lut_size, 3).permute(2,1,0,3)\n else:\n raise Exception(\"Unsupported LUT format\")\n return lattice" }, { "identifier": "save_lut", "path": "src/tinycio/fsio/lutfile.py", "snippet": "def save_lut(lattice:torch.Tensor, fp:str, lut_format:LUTFormat=LUTFormat.UNKNOWN) -> bool:\n \"\"\"\n Save LUT to a file.\n\n .. warning:: \n \n This will overwrite existing files.\n\n :param lattice: PyTorch tensor representing the LUT.\n :param fp: File path for saving the LUT.\n :param lut_format: Format of the LUT.\n :return: True if successful\n \"\"\"\n fp = os.path.realpath(fp)\n fn, fnext = os.path.splitext(fp)\n\n if lut_format == LUTFormat.UNKNOWN: lut_format = _infer_lut_file_format(fnext)\n\n if lut_format == LUTFormat.CUBE_3D:\n # Convert the torch tensor to a list of lists\n lut_data_list = lattice.permute(2,1,0,3).reshape(-1, 3).tolist()\n\n # Write the LUT data to the file\n with open(fp, 'w') as file:\n file.write(f\"LUT_3D_SIZE {lattice.size(0)}\\n\")\n for entry in lut_data_list:\n file.write(\" \".join(map(str, entry)) + \"\\n\")\n\n else:\n raise Exception(\"Unsupported LUT format\")\n\n return True" }, { "identifier": "_infer_lut_file_format", "path": "src/tinycio/fsio/lutfile.py", "snippet": "def _infer_lut_file_format(ext:str) -> LUTFormat:\n ext = ext.strip().lower()\n if ext == '.cube': return LUTFormat.CUBE_3D\n else: return LUTFormat.UNKNOWN" }, { "identifier": "_generate_linear_cube_lut", "path": "src/tinycio/fsio/lutfile.py", "snippet": "def _generate_linear_cube_lut(size: int):\n \"\"\"\n Generate a baseline linear cube LUT.\n\n :param size: Size of the cube LUT (e.g., 33 for a 33x33x33 cube).\n :return: Torch tensor representing the linear cube LUT.\n \"\"\"\n linear_values = torch.linspace(0.0, 1.0, size)\n grid = torch.meshgrid(linear_values, linear_values, linear_values, indexing=\"xy\")\n lut_data = torch.stack(grid, dim=-1).permute(1,0,2,3) # TODO: WTF is even going on here?\n return lut_data" }, { "identifier": "LUTFormat", "path": "src/tinycio/fsio/format.py", "snippet": "class LUTFormat(IntEnum):\n \"\"\"\n Lookup table format. Available options are:\n\n .. highlight:: text\n .. code-block:: text\n \n - UNKNOWN\n - CUBE_3D\n \"\"\"\n UNKNOWN = 1<<0 # no color space specified - flag for guessing\n CUBE_3D = 1<<1 # 3D CUBE LUT https://resolve.cafe/developers/luts/\n\n LUT_3D = CUBE_3D # | etc for later" }, { "identifier": "srgb_luminance", "path": "src/tinycio/util/colorutil.py", "snippet": "def srgb_luminance(im_srgb:Union[torch.Tensor, ColorImage]) -> torch.Tensor:\n \"\"\"\n Return relative luminance of linear sRGB image.\n\n :param im_srgb: [C=3, H, W] color image tensor in sRGB color space\n :type im_srgb: torch.Tensor | ColorImage\n :return: [C=1, H, W] image tensor\n \"\"\"\n lum_r, lum_g, lum_b = 0.2126, 0.7152, 0.0722\n return lum_r * im_srgb[0:1,...] + lum_g * im_srgb[1:2,...] + lum_b * im_srgb[2:3,...]" }, { "identifier": "trilinear_interpolation", "path": "src/tinycio/util/miscutil.py", "snippet": "def trilinear_interpolation(im_3d:torch.Tensor, indices:Union[ColorImage, torch.Tensor]) -> torch.Tensor:\n \"\"\"\n Interpolate 3D image tensor.\n\n :param im_3d: Input 3D image tensor of shape (C, D, H, W).\n :param indices: Indices into the tensor.\n :return: Interpolated color values.\n \"\"\"\n # NOTE: Internal - leaving this clutter undocumented intentionally\n indices_floor = indices.floor().to(torch.long)\n indices_ceil = indices.ceil().clamp(0, im_3d.size(0) - 1).to(torch.long)\n\n weights = (indices - indices_floor).float()\n\n c000 = im_3d[indices_floor[0], indices_floor[1], indices_floor[2]]\n c001 = im_3d[indices_floor[0], indices_floor[1], indices_ceil[2]]\n c010 = im_3d[indices_floor[0], indices_ceil[1], indices_floor[2]]\n c011 = im_3d[indices_floor[0], indices_ceil[1], indices_ceil[2]]\n c100 = im_3d[indices_ceil[0], indices_floor[1], indices_floor[2]]\n c101 = im_3d[indices_ceil[0], indices_floor[1], indices_ceil[2]]\n c110 = im_3d[indices_ceil[0], indices_ceil[1], indices_floor[2]]\n c111 = im_3d[indices_ceil[0], indices_ceil[1], indices_ceil[2]]\n\n interpolated_values = torch.zeros_like(c000).requires_grad_()\n interpolated_values = (\n (1 - weights[0]) * (1 - weights[1]) * (1 - weights[2]) * c000.permute(2,0,1) +\n (1 - weights[0]) * (1 - weights[1]) * weights[2] * c001.permute(2,0,1) +\n (1 - weights[0]) * weights[1] * (1 - weights[2]) * c010.permute(2,0,1) +\n (1 - weights[0]) * weights[1] * weights[2] * c011.permute(2,0,1) +\n weights[0] * (1 - weights[1]) * (1 - weights[2]) * c100.permute(2,0,1) +\n weights[0] * (1 - weights[1]) * weights[2] * c101.permute(2,0,1) +\n weights[0] * weights[1] * (1 - weights[2]) * c110.permute(2,0,1) +\n weights[0] * weights[1] * weights[2] * c111.permute(2,0,1)\n )\n\n return interpolated_values" }, { "identifier": "feature_moments_calculation", "path": "src/tinycio/loss.py", "snippet": "def feature_moments_calculation(feat, eps=1e-5):\n # https://github.com/semchan/NLUT/blob/main/LICENSE\n # MIT License\n # <!-- Copyright (c) 2010, 2011 the Friendika Project -->\n # All rights reserved.\n\n # Permission is hereby granted, free of charge, to any person obtaining a copy\n # of this software and associated documentation files (the \"Software\"), to deal\n # in the Software without restriction, including without limitation the rights\n # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n # copies of the Software, and to permit persons to whom the Software is\n # furnished to do so, subject to the following conditions:\n\n # The above copyright notice and this permission notice shall be included in\n # all copies or substantial portions of the Software.\n\n # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n # THE SOFTWARE\n size = feat.size()\n assert (len(size) == 3)\n N, C = size[:2]\n feat_var = feat.view(N, C, -1).var(dim=2) + eps\n # feat_std = feat_var.sqrt().view(N, C, 1, 1)\n # the first order\n feat_mean = feat.view(N, C, -1).mean(dim=2).view(N, C, 1)\n\n # the second order\n feat_size = 2\n # N, C = size[:2]\n feat_p2 = torch.abs(feat-feat_mean).pow(feat_size).view(N, C, -1)\n N, C,L = feat_p2.shape\n feat_p2 = feat_p2.sum(dim=2)/L\n feat_p2 = feat_p2.pow(1/feat_size).view(N, C, 1)\n # the third order\n feat_size = 3\n # N, C = size[:2]\n feat_p3 = torch.abs(feat-feat_mean).pow(feat_size).view(N, C, -1)\n # N, C,L = feat_p3.shape\n feat_p3 = feat_p3.sum(dim=2)/L\n feat_p3 = feat_p3.pow(1/feat_size).view(N, C, 1)\n\n return feat_mean.view(N, C) , feat_p2.view(N, C), feat_p3.view(N, C)" } ]
import typing import os import torch import torch.optim as optim import torch.nn as nn import torch.nn.functional as F from typing import Union from enum import IntEnum from contextlib import nullcontext from .colorspace import ColorSpace from .fsio.lutfile import load_lut, save_lut, _infer_lut_file_format, _generate_linear_cube_lut from .fsio.format import LUTFormat from .util.colorutil import srgb_luminance from .util.miscutil import trilinear_interpolation from .loss import feature_moments_calculation
19,584
""" Returns linear LUT. Has no effect: when applied, output matches input ([0, 1] range). :param size: Size of the LUT. :param lut_format: Format of the LUT. """ if lut_format == LUTFormat.CUBE_3D: assert cls.__min_size <= size <= cls.__max_size, f"LUT size must be between {cls.__min_size} and {cls.__max_size}" variant = LUTFormat.CUBE_3D lattice = _generate_linear_cube_lut(size) else: raise Exception(f"Backpropagation not implemented for: {lut_format.name}") return cls(size, lattice, variant) @classmethod def get_negative(cls, size:int=32, lut_format:LUTFormat=LUTFormat.CUBE_3D) -> LookupTable: """ Returns negative LUT. Output is inverted ([0, 1] range). :param size: Size of the LUT. :param lut_format: Format of the LUT. """ lut = cls.get_linear(size, lut_format) lut.lattice = 1. - lut.lattice return lut @classmethod def get_random(cls, size:int=32, lut_format:LUTFormat=LUTFormat.CUBE_3D) -> LookupTable: """ Returns random LUT. Everything mapped to random values ([0, 1] range). :param size: Size of the LUT. :param lut_format: Format of the LUT. """ lut = cls.get_linear(size, lut_format) lut.lattice = torch.randn_like(lut.lattice) return lut @classmethod def get_empty(cls, size:int=32, lut_format:LUTFormat=LUTFormat.CUBE_3D) -> LookupTable: """ Returns empty LUT. All values mapped to 0. :param size: Size of the LUT. :param lut_format: Format of the LUT. """ lut = cls.get_linear(size, lut_format) lut.lattice = lut.lattice * 0. return lut def fit_to_image(self, im_source:Union[torch.Tensor, ColorImage], im_target:Union[torch.Tensor, ColorImage], steps:int=500, learning_rate:float=0.003, strength:float=1., fit_height:int=512, fit_width:int=512, device:str='cuda', context:callable=None ) -> bool: """ Perform gradient descent on the lattice, so that the appearance of the source image matches the target. :param im_source: Source image tensor. Values must be in range [0, 1]. :type im_source: torch.Tensor | ColorImage :param im_target: Target image tensor. :type im_target: torch.Tensor | ColorImage :param steps: Number of optimization steps. :param learning_rate: Learning rate for gradient descent. :param strength: Strength of the effect in range [0, 1]. :param fit_height: Image tensors will be interpolated to this height for evaluation. :param fit_width: Image tensors will be interpolated to this width for evaluation. :param device: Device for gradient descent (if None will use input tensor device). :return: True when completed """ assert 0. <= strength <= 1., "strength must be in range [0, 1]" im_source = im_source.clone() device = torch.device(device.strip().lower()) if device is not None else im_source.device im_source = F.interpolate( im_source.unsqueeze(0), size=[fit_height, fit_width], mode='bicubic', align_corners=False).squeeze(0).clamp(0.,1.).to(device) im_target = F.interpolate( im_target.unsqueeze(0), size=[fit_height, fit_width], mode='bicubic', align_corners=False).squeeze(0).clamp(0.,1.).to(device) __ctx = context if context is not None and callable(context) else nullcontext with __ctx() as ctx: cb_callable = hasattr(ctx, 'update_fit_status') and callable(ctx.update_fit_status) cb = ctx.update_fit_status if cb_callable else lambda a, b, c, d: None if self.lut_format == LUTFormat.CUBE_3D: lut = torch.nn.Parameter(self.lattice) lut.requires_grad_() optimizer = optim.Adam([lut], lr=learning_rate) indices = (im_source * (lut.size(0) - 1)).clamp(0, lut.size(0) - 1).to(device) area = fit_height * fit_height fm_mean_scale = area fm_p2_scale = area / 32. fm_p3_scale = area / 64. selfsim_scale = area sat_scale = area # lut optimization goes a bit wild with this for step in range(steps): t_source = trilinear_interpolation(lut.to(device), indices).to(device) loss = 0. # Main feature loss feat_source_mean, feat_source_p2, feat_source_p3 = feature_moments_calculation(t_source.view(1,3,-1)) feat_target_mean, feat_target_p2, feat_target_p3 = feature_moments_calculation(im_target.view(1,3,-1)) loss += F.mse_loss(feat_source_mean, feat_target_mean) * fm_mean_scale * strength loss += F.mse_loss(feat_source_p2, feat_target_p2) * fm_p2_scale * strength loss += F.mse_loss(feat_source_p3, feat_target_p3) * fm_p3_scale * strength # Additional saturation-focused loss
from __future__ import annotations class LookupTable: """ Color lookup table. Example: .. highlight:: python .. code-block:: python lut = LookupTable.get_negative() im_negative = lut.apply(im) :param size: Size of the LUT. :param lattice: Lattice as tensor (defaults to linear). :param lut_format: Format of the LUT. """ size = 32 lattice = None lut_format= LUTFormat.UNKNOWN __min_size, __max_size = 4, 512 def __init__(self, size:int, lattice:torch.Tensor=None, lut_format:LUTFormat=LUTFormat.CUBE_3D): assert self.__min_size <= size <= self.__max_size, f"LUT size must be between {self.__min_size} and {self.__max_size}" self.size == size self.lattice = lattice if lattice is not None else _generate_linear_cube_lut(size) self.lut_format = lut_format @classmethod def load(cls, fp:str, lut_format:LUTFormat=LUTFormat.UNKNOWN) -> LookupTable: """ Load LUT from file. :param fp: File path. :param lut_format: Format of the LUT. """ fp = os.path.realpath(fp) fn, fnext = os.path.splitext(fp) variant = lut_format if lut_format > LUTFormat.UNKNOWN else _infer_lut_file_format(fnext) assert variant > LUTFormat.UNKNOWN, "Unrecognized LUT format" lattice = load_lut(fp, variant) return cls(lattice.size(0), lattice, variant) def save(self, fp:str, lut_format:LUTFormat=LUTFormat.UNKNOWN): """ Save LUT to file. .. warning:: This will overwrite existing files. :param fp: File path. :param lut_format: Format of the LUT. """ fp = os.path.realpath(fp) fn, fnext = os.path.splitext(fp) variant = lut_format if lut_format > LUTFormat.UNKNOWN else _infer_lut_file_format(fnext) or self.variant assert variant > LUTFormat.UNKNOWN, "Unrecognized LUT format" lattice = save_lut(self.lattice, fp, variant) return True def apply(self, im:Union[torch.Tensor, ColorImage]) -> torch.Tensor: """ Apply LUT to image tensor. :param im: Input image tensor :type im: torch.Tensor | ColorImage :return: Image tensor with LUT applied """ assert self.lut_format > LUTFormat.UNKNOWN and self.lattice != None, "No LUT has been loaded" assert im.size(0) == 3, "Image should have three color channels (RGB)" assert self.lattice.size(-1) == 3, "Cube LUT should have three color channels" indices = (im * (self.lattice.size(0) - 1)).clamp(0, self.lattice.size(0) - 1) im_out = trilinear_interpolation(self.lattice, indices) return im_out @classmethod def get_linear(cls, size:int=32, lut_format:LUTFormat=LUTFormat.CUBE_3D) -> LookupTable: """ Returns linear LUT. Has no effect: when applied, output matches input ([0, 1] range). :param size: Size of the LUT. :param lut_format: Format of the LUT. """ if lut_format == LUTFormat.CUBE_3D: assert cls.__min_size <= size <= cls.__max_size, f"LUT size must be between {cls.__min_size} and {cls.__max_size}" variant = LUTFormat.CUBE_3D lattice = _generate_linear_cube_lut(size) else: raise Exception(f"Backpropagation not implemented for: {lut_format.name}") return cls(size, lattice, variant) @classmethod def get_negative(cls, size:int=32, lut_format:LUTFormat=LUTFormat.CUBE_3D) -> LookupTable: """ Returns negative LUT. Output is inverted ([0, 1] range). :param size: Size of the LUT. :param lut_format: Format of the LUT. """ lut = cls.get_linear(size, lut_format) lut.lattice = 1. - lut.lattice return lut @classmethod def get_random(cls, size:int=32, lut_format:LUTFormat=LUTFormat.CUBE_3D) -> LookupTable: """ Returns random LUT. Everything mapped to random values ([0, 1] range). :param size: Size of the LUT. :param lut_format: Format of the LUT. """ lut = cls.get_linear(size, lut_format) lut.lattice = torch.randn_like(lut.lattice) return lut @classmethod def get_empty(cls, size:int=32, lut_format:LUTFormat=LUTFormat.CUBE_3D) -> LookupTable: """ Returns empty LUT. All values mapped to 0. :param size: Size of the LUT. :param lut_format: Format of the LUT. """ lut = cls.get_linear(size, lut_format) lut.lattice = lut.lattice * 0. return lut def fit_to_image(self, im_source:Union[torch.Tensor, ColorImage], im_target:Union[torch.Tensor, ColorImage], steps:int=500, learning_rate:float=0.003, strength:float=1., fit_height:int=512, fit_width:int=512, device:str='cuda', context:callable=None ) -> bool: """ Perform gradient descent on the lattice, so that the appearance of the source image matches the target. :param im_source: Source image tensor. Values must be in range [0, 1]. :type im_source: torch.Tensor | ColorImage :param im_target: Target image tensor. :type im_target: torch.Tensor | ColorImage :param steps: Number of optimization steps. :param learning_rate: Learning rate for gradient descent. :param strength: Strength of the effect in range [0, 1]. :param fit_height: Image tensors will be interpolated to this height for evaluation. :param fit_width: Image tensors will be interpolated to this width for evaluation. :param device: Device for gradient descent (if None will use input tensor device). :return: True when completed """ assert 0. <= strength <= 1., "strength must be in range [0, 1]" im_source = im_source.clone() device = torch.device(device.strip().lower()) if device is not None else im_source.device im_source = F.interpolate( im_source.unsqueeze(0), size=[fit_height, fit_width], mode='bicubic', align_corners=False).squeeze(0).clamp(0.,1.).to(device) im_target = F.interpolate( im_target.unsqueeze(0), size=[fit_height, fit_width], mode='bicubic', align_corners=False).squeeze(0).clamp(0.,1.).to(device) __ctx = context if context is not None and callable(context) else nullcontext with __ctx() as ctx: cb_callable = hasattr(ctx, 'update_fit_status') and callable(ctx.update_fit_status) cb = ctx.update_fit_status if cb_callable else lambda a, b, c, d: None if self.lut_format == LUTFormat.CUBE_3D: lut = torch.nn.Parameter(self.lattice) lut.requires_grad_() optimizer = optim.Adam([lut], lr=learning_rate) indices = (im_source * (lut.size(0) - 1)).clamp(0, lut.size(0) - 1).to(device) area = fit_height * fit_height fm_mean_scale = area fm_p2_scale = area / 32. fm_p3_scale = area / 64. selfsim_scale = area sat_scale = area # lut optimization goes a bit wild with this for step in range(steps): t_source = trilinear_interpolation(lut.to(device), indices).to(device) loss = 0. # Main feature loss feat_source_mean, feat_source_p2, feat_source_p3 = feature_moments_calculation(t_source.view(1,3,-1)) feat_target_mean, feat_target_p2, feat_target_p3 = feature_moments_calculation(im_target.view(1,3,-1)) loss += F.mse_loss(feat_source_mean, feat_target_mean) * fm_mean_scale * strength loss += F.mse_loss(feat_source_p2, feat_target_p2) * fm_p2_scale * strength loss += F.mse_loss(feat_source_p3, feat_target_p3) * fm_p3_scale * strength # Additional saturation-focused loss
sat_s = srgb_luminance(t_source).repeat(3,1,1) - t_source
6
2023-12-15 15:39:08+00:00
24k
Azure-Samples/functions-python-web-crawler
.venv/Lib/site-packages/urllib3/connection.py
[ { "identifier": "HTTPHeaderDict", "path": ".venv/Lib/site-packages/urllib3/_collections.py", "snippet": "class HTTPHeaderDict(typing.MutableMapping[str, str]):\n \"\"\"\n :param headers:\n An iterable of field-value pairs. Must not contain multiple field names\n when compared case-insensitively.\n\n :param kwargs:\n Additional field-value pairs to pass in to ``dict.update``.\n\n A ``dict`` like container for storing HTTP Headers.\n\n Field names are stored and compared case-insensitively in compliance with\n RFC 7230. Iteration provides the first case-sensitive key seen for each\n case-insensitive pair.\n\n Using ``__setitem__`` syntax overwrites fields that compare equal\n case-insensitively in order to maintain ``dict``'s api. For fields that\n compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``\n in a loop.\n\n If multiple fields that are equal case-insensitively are passed to the\n constructor or ``.update``, the behavior is undefined and some will be\n lost.\n\n >>> headers = HTTPHeaderDict()\n >>> headers.add('Set-Cookie', 'foo=bar')\n >>> headers.add('set-cookie', 'baz=quxx')\n >>> headers['content-length'] = '7'\n >>> headers['SET-cookie']\n 'foo=bar, baz=quxx'\n >>> headers['Content-Length']\n '7'\n \"\"\"\n\n _container: typing.MutableMapping[str, list[str]]\n\n def __init__(self, headers: ValidHTTPHeaderSource | None = None, **kwargs: str):\n super().__init__()\n self._container = {} # 'dict' is insert-ordered\n if headers is not None:\n if isinstance(headers, HTTPHeaderDict):\n self._copy_from(headers)\n else:\n self.extend(headers)\n if kwargs:\n self.extend(kwargs)\n\n def __setitem__(self, key: str, val: str) -> None:\n # avoid a bytes/str comparison by decoding before httplib\n if isinstance(key, bytes):\n key = key.decode(\"latin-1\")\n self._container[key.lower()] = [key, val]\n\n def __getitem__(self, key: str) -> str:\n val = self._container[key.lower()]\n return \", \".join(val[1:])\n\n def __delitem__(self, key: str) -> None:\n del self._container[key.lower()]\n\n def __contains__(self, key: object) -> bool:\n if isinstance(key, str):\n return key.lower() in self._container\n return False\n\n def setdefault(self, key: str, default: str = \"\") -> str:\n return super().setdefault(key, default)\n\n def __eq__(self, other: object) -> bool:\n maybe_constructable = ensure_can_construct_http_header_dict(other)\n if maybe_constructable is None:\n return False\n else:\n other_as_http_header_dict = type(self)(maybe_constructable)\n\n return {k.lower(): v for k, v in self.itermerged()} == {\n k.lower(): v for k, v in other_as_http_header_dict.itermerged()\n }\n\n def __ne__(self, other: object) -> bool:\n return not self.__eq__(other)\n\n def __len__(self) -> int:\n return len(self._container)\n\n def __iter__(self) -> typing.Iterator[str]:\n # Only provide the originally cased names\n for vals in self._container.values():\n yield vals[0]\n\n def discard(self, key: str) -> None:\n try:\n del self[key]\n except KeyError:\n pass\n\n def add(self, key: str, val: str, *, combine: bool = False) -> None:\n \"\"\"Adds a (name, value) pair, doesn't overwrite the value if it already\n exists.\n\n If this is called with combine=True, instead of adding a new header value\n as a distinct item during iteration, this will instead append the value to\n any existing header value with a comma. If no existing header value exists\n for the key, then the value will simply be added, ignoring the combine parameter.\n\n >>> headers = HTTPHeaderDict(foo='bar')\n >>> headers.add('Foo', 'baz')\n >>> headers['foo']\n 'bar, baz'\n >>> list(headers.items())\n [('foo', 'bar'), ('foo', 'baz')]\n >>> headers.add('foo', 'quz', combine=True)\n >>> list(headers.items())\n [('foo', 'bar, baz, quz')]\n \"\"\"\n # avoid a bytes/str comparison by decoding before httplib\n if isinstance(key, bytes):\n key = key.decode(\"latin-1\")\n key_lower = key.lower()\n new_vals = [key, val]\n # Keep the common case aka no item present as fast as possible\n vals = self._container.setdefault(key_lower, new_vals)\n if new_vals is not vals:\n # if there are values here, then there is at least the initial\n # key/value pair\n assert len(vals) >= 2\n if combine:\n vals[-1] = vals[-1] + \", \" + val\n else:\n vals.append(val)\n\n def extend(self, *args: ValidHTTPHeaderSource, **kwargs: str) -> None:\n \"\"\"Generic import function for any type of header-like object.\n Adapted version of MutableMapping.update in order to insert items\n with self.add instead of self.__setitem__\n \"\"\"\n if len(args) > 1:\n raise TypeError(\n f\"extend() takes at most 1 positional arguments ({len(args)} given)\"\n )\n other = args[0] if len(args) >= 1 else ()\n\n if isinstance(other, HTTPHeaderDict):\n for key, val in other.iteritems():\n self.add(key, val)\n elif isinstance(other, typing.Mapping):\n for key, val in other.items():\n self.add(key, val)\n elif isinstance(other, typing.Iterable):\n other = typing.cast(typing.Iterable[typing.Tuple[str, str]], other)\n for key, value in other:\n self.add(key, value)\n elif hasattr(other, \"keys\") and hasattr(other, \"__getitem__\"):\n # THIS IS NOT A TYPESAFE BRANCH\n # In this branch, the object has a `keys` attr but is not a Mapping or any of\n # the other types indicated in the method signature. We do some stuff with\n # it as though it partially implements the Mapping interface, but we're not\n # doing that stuff safely AT ALL.\n for key in other.keys():\n self.add(key, other[key])\n\n for key, value in kwargs.items():\n self.add(key, value)\n\n @typing.overload\n def getlist(self, key: str) -> list[str]:\n ...\n\n @typing.overload\n def getlist(self, key: str, default: _DT) -> list[str] | _DT:\n ...\n\n def getlist(\n self, key: str, default: _Sentinel | _DT = _Sentinel.not_passed\n ) -> list[str] | _DT:\n \"\"\"Returns a list of all the values for the named field. Returns an\n empty list if the key doesn't exist.\"\"\"\n try:\n vals = self._container[key.lower()]\n except KeyError:\n if default is _Sentinel.not_passed:\n # _DT is unbound; empty list is instance of List[str]\n return []\n # _DT is bound; default is instance of _DT\n return default\n else:\n # _DT may or may not be bound; vals[1:] is instance of List[str], which\n # meets our external interface requirement of `Union[List[str], _DT]`.\n return vals[1:]\n\n def _prepare_for_method_change(self) -> Self:\n \"\"\"\n Remove content-specific header fields before changing the request\n method to GET or HEAD according to RFC 9110, Section 15.4.\n \"\"\"\n content_specific_headers = [\n \"Content-Encoding\",\n \"Content-Language\",\n \"Content-Location\",\n \"Content-Type\",\n \"Content-Length\",\n \"Digest\",\n \"Last-Modified\",\n ]\n for header in content_specific_headers:\n self.discard(header)\n return self\n\n # Backwards compatibility for httplib\n getheaders = getlist\n getallmatchingheaders = getlist\n iget = getlist\n\n # Backwards compatibility for http.cookiejar\n get_all = getlist\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}({dict(self.itermerged())})\"\n\n def _copy_from(self, other: HTTPHeaderDict) -> None:\n for key in other:\n val = other.getlist(key)\n self._container[key.lower()] = [key, *val]\n\n def copy(self) -> HTTPHeaderDict:\n clone = type(self)()\n clone._copy_from(self)\n return clone\n\n def iteritems(self) -> typing.Iterator[tuple[str, str]]:\n \"\"\"Iterate over all header lines, including duplicate ones.\"\"\"\n for key in self:\n vals = self._container[key.lower()]\n for val in vals[1:]:\n yield vals[0], val\n\n def itermerged(self) -> typing.Iterator[tuple[str, str]]:\n \"\"\"Iterate over all headers, merging duplicate ones together.\"\"\"\n for key in self:\n val = self._container[key.lower()]\n yield val[0], \", \".join(val[1:])\n\n def items(self) -> HTTPHeaderDictItemView: # type: ignore[override]\n return HTTPHeaderDictItemView(self)\n\n def _has_value_for_header(self, header_name: str, potential_value: str) -> bool:\n if header_name in self:\n return potential_value in self._container[header_name.lower()][1:]\n return False\n\n def __ior__(self, other: object) -> HTTPHeaderDict:\n # Supports extending a header dict in-place using operator |=\n # combining items with add instead of __setitem__\n maybe_constructable = ensure_can_construct_http_header_dict(other)\n if maybe_constructable is None:\n return NotImplemented\n self.extend(maybe_constructable)\n return self\n\n def __or__(self, other: object) -> HTTPHeaderDict:\n # Supports merging header dicts using operator |\n # combining items with add instead of __setitem__\n maybe_constructable = ensure_can_construct_http_header_dict(other)\n if maybe_constructable is None:\n return NotImplemented\n result = self.copy()\n result.extend(maybe_constructable)\n return result\n\n def __ror__(self, other: object) -> HTTPHeaderDict:\n # Supports merging header dicts using operator | when other is on left side\n # combining items with add instead of __setitem__\n maybe_constructable = ensure_can_construct_http_header_dict(other)\n if maybe_constructable is None:\n return NotImplemented\n result = type(self)(maybe_constructable)\n result.extend(self)\n return result" }, { "identifier": "assert_header_parsing", "path": ".venv/Lib/site-packages/urllib3/util/response.py", "snippet": "def assert_header_parsing(headers: httplib.HTTPMessage) -> None:\n \"\"\"\n Asserts whether all headers have been successfully parsed.\n Extracts encountered errors from the result of parsing headers.\n\n Only works on Python 3.\n\n :param http.client.HTTPMessage headers: Headers to verify.\n\n :raises urllib3.exceptions.HeaderParsingError:\n If parsing errors are found.\n \"\"\"\n\n # This will fail silently if we pass in the wrong kind of parameter.\n # To make debugging easier add an explicit check.\n if not isinstance(headers, httplib.HTTPMessage):\n raise TypeError(f\"expected httplib.Message, got {type(headers)}.\")\n\n unparsed_data = None\n\n # get_payload is actually email.message.Message.get_payload;\n # we're only interested in the result if it's not a multipart message\n if not headers.is_multipart():\n payload = headers.get_payload()\n\n if isinstance(payload, (bytes, str)):\n unparsed_data = payload\n\n # httplib is assuming a response body is available\n # when parsing headers even when httplib only sends\n # header data to parse_headers() This results in\n # defects on multipart responses in particular.\n # See: https://github.com/urllib3/urllib3/issues/800\n\n # So we ignore the following defects:\n # - StartBoundaryNotFoundDefect:\n # The claimed start boundary was never found.\n # - MultipartInvariantViolationDefect:\n # A message claimed to be a multipart but no subparts were found.\n defects = [\n defect\n for defect in headers.defects\n if not isinstance(\n defect, (StartBoundaryNotFoundDefect, MultipartInvariantViolationDefect)\n )\n ]\n\n if defects or unparsed_data:\n raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)" }, { "identifier": "_DEFAULT_TIMEOUT", "path": ".venv/Lib/site-packages/urllib3/util/timeout.py", "snippet": "_DEFAULT_TIMEOUT: Final[_TYPE_DEFAULT] = _TYPE_DEFAULT.token" }, { "identifier": "_TYPE_TIMEOUT", "path": ".venv/Lib/site-packages/urllib3/util/timeout.py", "snippet": "_TYPE_TIMEOUT = typing.Optional[typing.Union[float, _TYPE_DEFAULT]]" }, { "identifier": "Timeout", "path": ".venv/Lib/site-packages/urllib3/util/timeout.py", "snippet": "class Timeout:\n \"\"\"Timeout configuration.\n\n Timeouts can be defined as a default for a pool:\n\n .. code-block:: python\n\n import urllib3\n\n timeout = urllib3.util.Timeout(connect=2.0, read=7.0)\n\n http = urllib3.PoolManager(timeout=timeout)\n\n resp = http.request(\"GET\", \"https://example.com/\")\n\n print(resp.status)\n\n Or per-request (which overrides the default for the pool):\n\n .. code-block:: python\n\n response = http.request(\"GET\", \"https://example.com/\", timeout=Timeout(10))\n\n Timeouts can be disabled by setting all the parameters to ``None``:\n\n .. code-block:: python\n\n no_timeout = Timeout(connect=None, read=None)\n response = http.request(\"GET\", \"https://example.com/\", timeout=no_timeout)\n\n\n :param total:\n This combines the connect and read timeouts into one; the read timeout\n will be set to the time leftover from the connect attempt. In the\n event that both a connect timeout and a total are specified, or a read\n timeout and a total are specified, the shorter timeout will be applied.\n\n Defaults to None.\n\n :type total: int, float, or None\n\n :param connect:\n The maximum amount of time (in seconds) to wait for a connection\n attempt to a server to succeed. Omitting the parameter will default the\n connect timeout to the system default, probably `the global default\n timeout in socket.py\n <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.\n None will set an infinite timeout for connection attempts.\n\n :type connect: int, float, or None\n\n :param read:\n The maximum amount of time (in seconds) to wait between consecutive\n read operations for a response from the server. Omitting the parameter\n will default the read timeout to the system default, probably `the\n global default timeout in socket.py\n <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.\n None will set an infinite timeout.\n\n :type read: int, float, or None\n\n .. note::\n\n Many factors can affect the total amount of time for urllib3 to return\n an HTTP response.\n\n For example, Python's DNS resolver does not obey the timeout specified\n on the socket. Other factors that can affect total request time include\n high CPU load, high swap, the program running at a low priority level,\n or other behaviors.\n\n In addition, the read and total timeouts only measure the time between\n read operations on the socket connecting the client and the server,\n not the total amount of time for the request to return a complete\n response. For most requests, the timeout is raised because the server\n has not sent the first byte in the specified time. This is not always\n the case; if a server streams one byte every fifteen seconds, a timeout\n of 20 seconds will not trigger, even though the request will take\n several minutes to complete.\n\n If your goal is to cut off any request after a set amount of wall clock\n time, consider having a second \"watcher\" thread to cut off a slow\n request.\n \"\"\"\n\n #: A sentinel object representing the default timeout value\n DEFAULT_TIMEOUT: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT\n\n def __init__(\n self,\n total: _TYPE_TIMEOUT = None,\n connect: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n read: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n ) -> None:\n self._connect = self._validate_timeout(connect, \"connect\")\n self._read = self._validate_timeout(read, \"read\")\n self.total = self._validate_timeout(total, \"total\")\n self._start_connect: float | None = None\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}(connect={self._connect!r}, read={self._read!r}, total={self.total!r})\"\n\n # __str__ provided for backwards compatibility\n __str__ = __repr__\n\n @staticmethod\n def resolve_default_timeout(timeout: _TYPE_TIMEOUT) -> float | None:\n return getdefaulttimeout() if timeout is _DEFAULT_TIMEOUT else timeout\n\n @classmethod\n def _validate_timeout(cls, value: _TYPE_TIMEOUT, name: str) -> _TYPE_TIMEOUT:\n \"\"\"Check that a timeout attribute is valid.\n\n :param value: The timeout value to validate\n :param name: The name of the timeout attribute to validate. This is\n used to specify in error messages.\n :return: The validated and casted version of the given value.\n :raises ValueError: If it is a numeric value less than or equal to\n zero, or the type is not an integer, float, or None.\n \"\"\"\n if value is None or value is _DEFAULT_TIMEOUT:\n return value\n\n if isinstance(value, bool):\n raise ValueError(\n \"Timeout cannot be a boolean value. It must \"\n \"be an int, float or None.\"\n )\n try:\n float(value)\n except (TypeError, ValueError):\n raise ValueError(\n \"Timeout value %s was %s, but it must be an \"\n \"int, float or None.\" % (name, value)\n ) from None\n\n try:\n if value <= 0:\n raise ValueError(\n \"Attempted to set %s timeout to %s, but the \"\n \"timeout cannot be set to a value less \"\n \"than or equal to 0.\" % (name, value)\n )\n except TypeError:\n raise ValueError(\n \"Timeout value %s was %s, but it must be an \"\n \"int, float or None.\" % (name, value)\n ) from None\n\n return value\n\n @classmethod\n def from_float(cls, timeout: _TYPE_TIMEOUT) -> Timeout:\n \"\"\"Create a new Timeout from a legacy timeout value.\n\n The timeout value used by httplib.py sets the same timeout on the\n connect(), and recv() socket requests. This creates a :class:`Timeout`\n object that sets the individual timeouts to the ``timeout`` value\n passed to this function.\n\n :param timeout: The legacy timeout value.\n :type timeout: integer, float, :attr:`urllib3.util.Timeout.DEFAULT_TIMEOUT`, or None\n :return: Timeout object\n :rtype: :class:`Timeout`\n \"\"\"\n return Timeout(read=timeout, connect=timeout)\n\n def clone(self) -> Timeout:\n \"\"\"Create a copy of the timeout object\n\n Timeout properties are stored per-pool but each request needs a fresh\n Timeout object to ensure each one has its own start/stop configured.\n\n :return: a copy of the timeout object\n :rtype: :class:`Timeout`\n \"\"\"\n # We can't use copy.deepcopy because that will also create a new object\n # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to\n # detect the user default.\n return Timeout(connect=self._connect, read=self._read, total=self.total)\n\n def start_connect(self) -> float:\n \"\"\"Start the timeout clock, used during a connect() attempt\n\n :raises urllib3.exceptions.TimeoutStateError: if you attempt\n to start a timer that has been started already.\n \"\"\"\n if self._start_connect is not None:\n raise TimeoutStateError(\"Timeout timer has already been started.\")\n self._start_connect = time.monotonic()\n return self._start_connect\n\n def get_connect_duration(self) -> float:\n \"\"\"Gets the time elapsed since the call to :meth:`start_connect`.\n\n :return: Elapsed time in seconds.\n :rtype: float\n :raises urllib3.exceptions.TimeoutStateError: if you attempt\n to get duration for a timer that hasn't been started.\n \"\"\"\n if self._start_connect is None:\n raise TimeoutStateError(\n \"Can't get connect duration for timer that has not started.\"\n )\n return time.monotonic() - self._start_connect\n\n @property\n def connect_timeout(self) -> _TYPE_TIMEOUT:\n \"\"\"Get the value to use when setting a connection timeout.\n\n This will be a positive float or integer, the value None\n (never timeout), or the default system timeout.\n\n :return: Connect timeout.\n :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None\n \"\"\"\n if self.total is None:\n return self._connect\n\n if self._connect is None or self._connect is _DEFAULT_TIMEOUT:\n return self.total\n\n return min(self._connect, self.total) # type: ignore[type-var]\n\n @property\n def read_timeout(self) -> float | None:\n \"\"\"Get the value for the read timeout.\n\n This assumes some time has elapsed in the connection timeout and\n computes the read timeout appropriately.\n\n If self.total is set, the read timeout is dependent on the amount of\n time taken by the connect timeout. If the connection time has not been\n established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be\n raised.\n\n :return: Value to use for the read timeout.\n :rtype: int, float or None\n :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`\n has not yet been called on this object.\n \"\"\"\n if (\n self.total is not None\n and self.total is not _DEFAULT_TIMEOUT\n and self._read is not None\n and self._read is not _DEFAULT_TIMEOUT\n ):\n # In case the connect timeout has not yet been established.\n if self._start_connect is None:\n return self._read\n return max(0, min(self.total - self.get_connect_duration(), self._read))\n elif self.total is not None and self.total is not _DEFAULT_TIMEOUT:\n return max(0, self.total - self.get_connect_duration())\n else:\n return self.resolve_default_timeout(self._read)" }, { "identifier": "to_str", "path": ".venv/Lib/site-packages/urllib3/util/util.py", "snippet": "def to_str(\n x: str | bytes, encoding: str | None = None, errors: str | None = None\n) -> str:\n if isinstance(x, str):\n return x\n elif not isinstance(x, bytes):\n raise TypeError(f\"not expecting type {type(x).__name__}\")\n if encoding or errors:\n return x.decode(encoding or \"utf-8\", errors=errors or \"strict\")\n return x.decode()" }, { "identifier": "wait_for_read", "path": ".venv/Lib/site-packages/urllib3/util/wait.py", "snippet": "def wait_for_read(sock: socket.socket, timeout: float | None = None) -> bool:\n \"\"\"Waits for reading to be available on a given socket.\n Returns True if the socket is readable, or False if the timeout expired.\n \"\"\"\n return wait_for_socket(sock, read=True, timeout=timeout)" }, { "identifier": "_TYPE_BODY", "path": ".venv/Lib/site-packages/urllib3/_base_connection.py", "snippet": "_TYPE_BODY = typing.Union[bytes, typing.IO[typing.Any], typing.Iterable[bytes], str]" }, { "identifier": "ProxyConfig", "path": ".venv/Lib/site-packages/urllib3/_base_connection.py", "snippet": "class ProxyConfig(typing.NamedTuple):\n ssl_context: ssl.SSLContext | None\n use_forwarding_for_https: bool\n assert_hostname: None | str | Literal[False]\n assert_fingerprint: str | None" }, { "identifier": "_ResponseOptions", "path": ".venv/Lib/site-packages/urllib3/_base_connection.py", "snippet": "class _ResponseOptions(typing.NamedTuple):\n # TODO: Remove this in favor of a better\n # HTTP request/response lifecycle tracking.\n request_method: str\n request_url: str\n preload_content: bool\n decode_content: bool\n enforce_content_length: bool" }, { "identifier": "__version__", "path": ".venv/Lib/site-packages/urllib3/_version.py", "snippet": "" }, { "identifier": "ConnectTimeoutError", "path": ".venv/Lib/site-packages/urllib3/exceptions.py", "snippet": "class ConnectTimeoutError(TimeoutError):\n \"\"\"Raised when a socket timeout occurs while connecting to a server\"\"\"" }, { "identifier": "HeaderParsingError", "path": ".venv/Lib/site-packages/urllib3/exceptions.py", "snippet": "class HeaderParsingError(HTTPError):\n \"\"\"Raised by assert_header_parsing, but we convert it to a log.warning statement.\"\"\"\n\n def __init__(\n self, defects: list[MessageDefect], unparsed_data: bytes | str | None\n ) -> None:\n message = f\"{defects or 'Unknown'}, unparsed data: {unparsed_data!r}\"\n super().__init__(message)" }, { "identifier": "NameResolutionError", "path": ".venv/Lib/site-packages/urllib3/exceptions.py", "snippet": "class NameResolutionError(NewConnectionError):\n \"\"\"Raised when host name resolution fails.\"\"\"\n\n def __init__(self, host: str, conn: HTTPConnection, reason: socket.gaierror):\n message = f\"Failed to resolve '{host}' ({reason})\"\n super().__init__(conn, message)" }, { "identifier": "NewConnectionError", "path": ".venv/Lib/site-packages/urllib3/exceptions.py", "snippet": "class NewConnectionError(ConnectTimeoutError, HTTPError):\n \"\"\"Raised when we fail to establish a new connection. Usually ECONNREFUSED.\"\"\"\n\n def __init__(self, conn: HTTPConnection, message: str) -> None:\n self.conn = conn\n super().__init__(f\"{conn}: {message}\")\n\n @property\n def pool(self) -> HTTPConnection:\n warnings.warn(\n \"The 'pool' property is deprecated and will be removed \"\n \"in urllib3 v2.1.0. Use 'conn' instead.\",\n DeprecationWarning,\n stacklevel=2,\n )\n\n return self.conn" }, { "identifier": "ProxyError", "path": ".venv/Lib/site-packages/urllib3/exceptions.py", "snippet": "class ProxyError(HTTPError):\n \"\"\"Raised when the connection to a proxy fails.\"\"\"\n\n # The original error is also available as __cause__.\n original_error: Exception\n\n def __init__(self, message: str, error: Exception) -> None:\n super().__init__(message, error)\n self.original_error = error" }, { "identifier": "SystemTimeWarning", "path": ".venv/Lib/site-packages/urllib3/exceptions.py", "snippet": "class SystemTimeWarning(SecurityWarning):\n \"\"\"Warned when system time is suspected to be wrong\"\"\"" }, { "identifier": "connection", "path": ".venv/Lib/site-packages/urllib3/util/connection.py", "snippet": "_TYPE_SOCKET_OPTIONS = typing.Sequence[typing.Tuple[int, int, typing.Union[int, bytes]]]\nHAS_IPV6 = _has_ipv6(\"::1\")\ndef is_connection_dropped(conn: BaseHTTPConnection) -> bool: # Platform-specific\ndef create_connection(\n address: tuple[str, int],\n timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n source_address: tuple[str, int] | None = None,\n socket_options: _TYPE_SOCKET_OPTIONS | None = None,\n) -> socket.socket:\ndef _set_socket_options(\n sock: socket.socket, options: _TYPE_SOCKET_OPTIONS | None\n) -> None:\ndef allowed_gai_family() -> socket.AddressFamily:\ndef _has_ipv6(host: str) -> bool:" }, { "identifier": "ssl_", "path": ".venv/Lib/site-packages/urllib3/util/ssl_.py", "snippet": "HAS_NEVER_CHECK_COMMON_NAME = False\nIS_PYOPENSSL = False\nALPN_PROTOCOLS = [\"http/1.1\"]\n_TYPE_VERSION_INFO = typing.Tuple[int, int, int, str, int]\nHASHFUNC_MAP = {32: md5, 40: sha1, 64: sha256}\n_SSL_VERSION_TO_TLS_VERSION: dict[int, int] = {}\n HAS_NEVER_CHECK_COMMON_NAME = False\n OP_NO_COMPRESSION = 0x20000 # type: ignore[assignment]\n OP_NO_TICKET = 0x4000 # type: ignore[assignment]\n PROTOCOL_TLS_CLIENT = 16 # type: ignore[assignment]\n_TYPE_PEER_CERT_RET = typing.Union[\"_TYPE_PEER_CERT_RET_DICT\", bytes, None]\ndef _is_bpo_43522_fixed(\n implementation_name: str,\n version_info: _TYPE_VERSION_INFO,\n pypy_version_info: _TYPE_VERSION_INFO | None,\n) -> bool:\ndef _is_has_never_check_common_name_reliable(\n openssl_version: str,\n openssl_version_number: int,\n implementation_name: str,\n version_info: _TYPE_VERSION_INFO,\n pypy_version_info: _TYPE_VERSION_INFO | None,\n) -> bool:\ndef assert_fingerprint(cert: bytes | None, fingerprint: str) -> None:\ndef resolve_cert_reqs(candidate: None | int | str) -> VerifyMode:\ndef resolve_ssl_version(candidate: None | int | str) -> int:\ndef create_urllib3_context(\n ssl_version: int | None = None,\n cert_reqs: int | None = None,\n options: int | None = None,\n ciphers: str | None = None,\n ssl_minimum_version: int | None = None,\n ssl_maximum_version: int | None = None,\n) -> ssl.SSLContext:\ndef ssl_wrap_socket(\n sock: socket.socket,\n keyfile: str | None = ...,\n certfile: str | None = ...,\n cert_reqs: int | None = ...,\n ca_certs: str | None = ...,\n server_hostname: str | None = ...,\n ssl_version: int | None = ...,\n ciphers: str | None = ...,\n ssl_context: ssl.SSLContext | None = ...,\n ca_cert_dir: str | None = ...,\n key_password: str | None = ...,\n ca_cert_data: None | str | bytes = ...,\n tls_in_tls: Literal[False] = ...,\n) -> ssl.SSLSocket:\ndef ssl_wrap_socket(\n sock: socket.socket,\n keyfile: str | None = ...,\n certfile: str | None = ...,\n cert_reqs: int | None = ...,\n ca_certs: str | None = ...,\n server_hostname: str | None = ...,\n ssl_version: int | None = ...,\n ciphers: str | None = ...,\n ssl_context: ssl.SSLContext | None = ...,\n ca_cert_dir: str | None = ...,\n key_password: str | None = ...,\n ca_cert_data: None | str | bytes = ...,\n tls_in_tls: bool = ...,\n) -> ssl.SSLSocket | SSLTransportType:\ndef ssl_wrap_socket(\n sock: socket.socket,\n keyfile: str | None = None,\n certfile: str | None = None,\n cert_reqs: int | None = None,\n ca_certs: str | None = None,\n server_hostname: str | None = None,\n ssl_version: int | None = None,\n ciphers: str | None = None,\n ssl_context: ssl.SSLContext | None = None,\n ca_cert_dir: str | None = None,\n key_password: str | None = None,\n ca_cert_data: None | str | bytes = None,\n tls_in_tls: bool = False,\n) -> ssl.SSLSocket | SSLTransportType:\ndef is_ipaddress(hostname: str | bytes) -> bool:\ndef _is_key_file_encrypted(key_file: str) -> bool:\ndef _ssl_wrap_socket_impl(\n sock: socket.socket,\n ssl_context: ssl.SSLContext,\n tls_in_tls: bool,\n server_hostname: str | None = None,\n) -> ssl.SSLSocket | SSLTransportType:\n class _TYPE_PEER_CERT_RET_DICT(TypedDict, total=False):" }, { "identifier": "SKIP_HEADER", "path": ".venv/Lib/site-packages/urllib3/util/request.py", "snippet": "SKIP_HEADER = \"@@@SKIP_HEADER@@@\"" }, { "identifier": "SKIPPABLE_HEADERS", "path": ".venv/Lib/site-packages/urllib3/util/request.py", "snippet": "SKIPPABLE_HEADERS = frozenset([\"accept-encoding\", \"host\", \"user-agent\"])" }, { "identifier": "body_to_chunks", "path": ".venv/Lib/site-packages/urllib3/util/request.py", "snippet": "def body_to_chunks(\n body: typing.Any | None, method: str, blocksize: int\n) -> ChunksAndContentLength:\n \"\"\"Takes the HTTP request method, body, and blocksize and\n transforms them into an iterable of chunks to pass to\n socket.sendall() and an optional 'Content-Length' header.\n\n A 'Content-Length' of 'None' indicates the length of the body\n can't be determined so should use 'Transfer-Encoding: chunked'\n for framing instead.\n \"\"\"\n\n chunks: typing.Iterable[bytes] | None\n content_length: int | None\n\n # No body, we need to make a recommendation on 'Content-Length'\n # based on whether that request method is expected to have\n # a body or not.\n if body is None:\n chunks = None\n if method.upper() not in _METHODS_NOT_EXPECTING_BODY:\n content_length = 0\n else:\n content_length = None\n\n # Bytes or strings become bytes\n elif isinstance(body, (str, bytes)):\n chunks = (to_bytes(body),)\n content_length = len(chunks[0])\n\n # File-like object, TODO: use seek() and tell() for length?\n elif hasattr(body, \"read\"):\n\n def chunk_readable() -> typing.Iterable[bytes]:\n nonlocal body, blocksize\n encode = isinstance(body, io.TextIOBase)\n while True:\n datablock = body.read(blocksize)\n if not datablock:\n break\n if encode:\n datablock = datablock.encode(\"iso-8859-1\")\n yield datablock\n\n chunks = chunk_readable()\n content_length = None\n\n # Otherwise we need to start checking via duck-typing.\n else:\n try:\n # Check if the body implements the buffer API.\n mv = memoryview(body)\n except TypeError:\n try:\n # Check if the body is an iterable\n chunks = iter(body)\n content_length = None\n except TypeError:\n raise TypeError(\n f\"'body' must be a bytes-like object, file-like \"\n f\"object, or iterable. Instead was {body!r}\"\n ) from None\n else:\n # Since it implements the buffer API can be passed directly to socket.sendall()\n chunks = (body,)\n content_length = mv.nbytes\n\n return ChunksAndContentLength(chunks=chunks, content_length=content_length)" }, { "identifier": "assert_fingerprint", "path": ".venv/Lib/site-packages/urllib3/util/ssl_.py", "snippet": "def assert_fingerprint(cert: bytes | None, fingerprint: str) -> None:\n \"\"\"\n Checks if given fingerprint matches the supplied certificate.\n\n :param cert:\n Certificate as bytes object.\n :param fingerprint:\n Fingerprint as string of hexdigits, can be interspersed by colons.\n \"\"\"\n\n if cert is None:\n raise SSLError(\"No certificate for the peer.\")\n\n fingerprint = fingerprint.replace(\":\", \"\").lower()\n digest_length = len(fingerprint)\n hashfunc = HASHFUNC_MAP.get(digest_length)\n if not hashfunc:\n raise SSLError(f\"Fingerprint of invalid length: {fingerprint}\")\n\n # We need encode() here for py32; works on py2 and p33.\n fingerprint_bytes = unhexlify(fingerprint.encode())\n\n cert_digest = hashfunc(cert).digest()\n\n if not hmac.compare_digest(cert_digest, fingerprint_bytes):\n raise SSLError(\n f'Fingerprints did not match. Expected \"{fingerprint}\", got \"{cert_digest.hex()}\"'\n )" }, { "identifier": "create_urllib3_context", "path": ".venv/Lib/site-packages/urllib3/util/ssl_.py", "snippet": "def create_urllib3_context(\n ssl_version: int | None = None,\n cert_reqs: int | None = None,\n options: int | None = None,\n ciphers: str | None = None,\n ssl_minimum_version: int | None = None,\n ssl_maximum_version: int | None = None,\n) -> ssl.SSLContext:\n \"\"\"Creates and configures an :class:`ssl.SSLContext` instance for use with urllib3.\n\n :param ssl_version:\n The desired protocol version to use. This will default to\n PROTOCOL_SSLv23 which will negotiate the highest protocol that both\n the server and your installation of OpenSSL support.\n\n This parameter is deprecated instead use 'ssl_minimum_version'.\n :param ssl_minimum_version:\n The minimum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value.\n :param ssl_maximum_version:\n The maximum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value.\n Not recommended to set to anything other than 'ssl.TLSVersion.MAXIMUM_SUPPORTED' which is the\n default value.\n :param cert_reqs:\n Whether to require the certificate verification. This defaults to\n ``ssl.CERT_REQUIRED``.\n :param options:\n Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,\n ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``.\n :param ciphers:\n Which cipher suites to allow the server to select. Defaults to either system configured\n ciphers if OpenSSL 1.1.1+, otherwise uses a secure default set of ciphers.\n :returns:\n Constructed SSLContext object with specified options\n :rtype: SSLContext\n \"\"\"\n if SSLContext is None:\n raise TypeError(\"Can't create an SSLContext object without an ssl module\")\n\n # This means 'ssl_version' was specified as an exact value.\n if ssl_version not in (None, PROTOCOL_TLS, PROTOCOL_TLS_CLIENT):\n # Disallow setting 'ssl_version' and 'ssl_minimum|maximum_version'\n # to avoid conflicts.\n if ssl_minimum_version is not None or ssl_maximum_version is not None:\n raise ValueError(\n \"Can't specify both 'ssl_version' and either \"\n \"'ssl_minimum_version' or 'ssl_maximum_version'\"\n )\n\n # 'ssl_version' is deprecated and will be removed in the future.\n else:\n # Use 'ssl_minimum_version' and 'ssl_maximum_version' instead.\n ssl_minimum_version = _SSL_VERSION_TO_TLS_VERSION.get(\n ssl_version, TLSVersion.MINIMUM_SUPPORTED\n )\n ssl_maximum_version = _SSL_VERSION_TO_TLS_VERSION.get(\n ssl_version, TLSVersion.MAXIMUM_SUPPORTED\n )\n\n # This warning message is pushing users to use 'ssl_minimum_version'\n # instead of both min/max. Best practice is to only set the minimum version and\n # keep the maximum version to be it's default value: 'TLSVersion.MAXIMUM_SUPPORTED'\n warnings.warn(\n \"'ssl_version' option is deprecated and will be \"\n \"removed in urllib3 v2.1.0. Instead use 'ssl_minimum_version'\",\n category=DeprecationWarning,\n stacklevel=2,\n )\n\n # PROTOCOL_TLS is deprecated in Python 3.10 so we always use PROTOCOL_TLS_CLIENT\n context = SSLContext(PROTOCOL_TLS_CLIENT)\n\n if ssl_minimum_version is not None:\n context.minimum_version = ssl_minimum_version\n else: # Python <3.10 defaults to 'MINIMUM_SUPPORTED' so explicitly set TLSv1.2 here\n context.minimum_version = TLSVersion.TLSv1_2\n\n if ssl_maximum_version is not None:\n context.maximum_version = ssl_maximum_version\n\n # Unless we're given ciphers defer to either system ciphers in\n # the case of OpenSSL 1.1.1+ or use our own secure default ciphers.\n if ciphers:\n context.set_ciphers(ciphers)\n\n # Setting the default here, as we may have no ssl module on import\n cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs\n\n if options is None:\n options = 0\n # SSLv2 is easily broken and is considered harmful and dangerous\n options |= OP_NO_SSLv2\n # SSLv3 has several problems and is now dangerous\n options |= OP_NO_SSLv3\n # Disable compression to prevent CRIME attacks for OpenSSL 1.0+\n # (issue #309)\n options |= OP_NO_COMPRESSION\n # TLSv1.2 only. Unless set explicitly, do not request tickets.\n # This may save some bandwidth on wire, and although the ticket is encrypted,\n # there is a risk associated with it being on wire,\n # if the server is not rotating its ticketing keys properly.\n options |= OP_NO_TICKET\n\n context.options |= options\n\n # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is\n # necessary for conditional client cert authentication with TLS 1.3.\n # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older\n # versions of Python. We only enable if certificate verification is enabled to work\n # around Python issue #37428\n # See: https://bugs.python.org/issue37428\n if (\n cert_reqs == ssl.CERT_REQUIRED\n and getattr(context, \"post_handshake_auth\", None) is not None\n ):\n context.post_handshake_auth = True\n\n # The order of the below lines setting verify_mode and check_hostname\n # matter due to safe-guards SSLContext has to prevent an SSLContext with\n # check_hostname=True, verify_mode=NONE/OPTIONAL.\n # We always set 'check_hostname=False' for pyOpenSSL so we rely on our own\n # 'ssl.match_hostname()' implementation.\n if cert_reqs == ssl.CERT_REQUIRED and not IS_PYOPENSSL:\n context.verify_mode = cert_reqs\n context.check_hostname = True\n else:\n context.check_hostname = False\n context.verify_mode = cert_reqs\n\n try:\n context.hostname_checks_common_name = False\n except AttributeError: # Defensive: for CPython < 3.8.9 and 3.9.3; for PyPy < 7.3.8\n pass\n\n # Enable logging of TLS session keys via defacto standard environment variable\n # 'SSLKEYLOGFILE', if the feature is available (Python 3.8+). Skip empty values.\n if hasattr(context, \"keylog_filename\"):\n sslkeylogfile = os.environ.get(\"SSLKEYLOGFILE\")\n if sslkeylogfile:\n context.keylog_filename = sslkeylogfile\n\n return context" }, { "identifier": "is_ipaddress", "path": ".venv/Lib/site-packages/urllib3/util/ssl_.py", "snippet": "def is_ipaddress(hostname: str | bytes) -> bool:\n \"\"\"Detects whether the hostname given is an IPv4 or IPv6 address.\n Also detects IPv6 addresses with Zone IDs.\n\n :param str hostname: Hostname to examine.\n :return: True if the hostname is an IP address, False otherwise.\n \"\"\"\n if isinstance(hostname, bytes):\n # IDN A-label bytes are ASCII compatible.\n hostname = hostname.decode(\"ascii\")\n return bool(_IPV4_RE.match(hostname) or _BRACELESS_IPV6_ADDRZ_RE.match(hostname))" }, { "identifier": "resolve_cert_reqs", "path": ".venv/Lib/site-packages/urllib3/util/ssl_.py", "snippet": "def resolve_cert_reqs(candidate: None | int | str) -> VerifyMode:\n \"\"\"\n Resolves the argument to a numeric constant, which can be passed to\n the wrap_socket function/method from the ssl module.\n Defaults to :data:`ssl.CERT_REQUIRED`.\n If given a string it is assumed to be the name of the constant in the\n :mod:`ssl` module or its abbreviation.\n (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.\n If it's neither `None` nor a string we assume it is already the numeric\n constant which can directly be passed to wrap_socket.\n \"\"\"\n if candidate is None:\n return CERT_REQUIRED\n\n if isinstance(candidate, str):\n res = getattr(ssl, candidate, None)\n if res is None:\n res = getattr(ssl, \"CERT_\" + candidate)\n return res # type: ignore[no-any-return]\n\n return candidate # type: ignore[return-value]" }, { "identifier": "resolve_ssl_version", "path": ".venv/Lib/site-packages/urllib3/util/ssl_.py", "snippet": "def resolve_ssl_version(candidate: None | int | str) -> int:\n \"\"\"\n like resolve_cert_reqs\n \"\"\"\n if candidate is None:\n return PROTOCOL_TLS\n\n if isinstance(candidate, str):\n res = getattr(ssl, candidate, None)\n if res is None:\n res = getattr(ssl, \"PROTOCOL_\" + candidate)\n return typing.cast(int, res)\n\n return candidate" }, { "identifier": "ssl_wrap_socket", "path": ".venv/Lib/site-packages/urllib3/util/ssl_.py", "snippet": "@typing.overload\ndef ssl_wrap_socket(\n sock: socket.socket,\n keyfile: str | None = ...,\n certfile: str | None = ...,\n cert_reqs: int | None = ...,\n ca_certs: str | None = ...,\n server_hostname: str | None = ...,\n ssl_version: int | None = ...,\n ciphers: str | None = ...,\n ssl_context: ssl.SSLContext | None = ...,\n ca_cert_dir: str | None = ...,\n key_password: str | None = ...,\n ca_cert_data: None | str | bytes = ...,\n tls_in_tls: Literal[False] = ...,\n) -> ssl.SSLSocket:\n ..." }, { "identifier": "CertificateError", "path": ".venv/Lib/site-packages/urllib3/util/ssl_match_hostname.py", "snippet": "class CertificateError(ValueError):\n pass" }, { "identifier": "match_hostname", "path": ".venv/Lib/site-packages/urllib3/util/ssl_match_hostname.py", "snippet": "def match_hostname(\n cert: _TYPE_PEER_CERT_RET_DICT | None,\n hostname: str,\n hostname_checks_common_name: bool = False,\n) -> None:\n \"\"\"Verify that *cert* (in decoded format as returned by\n SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125\n rules are followed, but IP addresses are not accepted for *hostname*.\n\n CertificateError is raised on failure. On success, the function\n returns nothing.\n \"\"\"\n if not cert:\n raise ValueError(\n \"empty or no certificate, match_hostname needs a \"\n \"SSL socket or SSL context with either \"\n \"CERT_OPTIONAL or CERT_REQUIRED\"\n )\n try:\n # Divergence from upstream: ipaddress can't handle byte str\n #\n # The ipaddress module shipped with Python < 3.9 does not support\n # scoped IPv6 addresses so we unconditionally strip the Zone IDs for\n # now. Once we drop support for Python 3.9 we can remove this branch.\n if \"%\" in hostname:\n host_ip = ipaddress.ip_address(hostname[: hostname.rfind(\"%\")])\n else:\n host_ip = ipaddress.ip_address(hostname)\n\n except ValueError:\n # Not an IP address (common case)\n host_ip = None\n dnsnames = []\n san: tuple[tuple[str, str], ...] = cert.get(\"subjectAltName\", ())\n key: str\n value: str\n for key, value in san:\n if key == \"DNS\":\n if host_ip is None and _dnsname_match(value, hostname):\n return\n dnsnames.append(value)\n elif key == \"IP Address\":\n if host_ip is not None and _ipaddress_match(value, host_ip):\n return\n dnsnames.append(value)\n\n # We only check 'commonName' if it's enabled and we're not verifying\n # an IP address. IP addresses aren't valid within 'commonName'.\n if hostname_checks_common_name and host_ip is None and not dnsnames:\n for sub in cert.get(\"subject\", ()):\n for key, value in sub:\n if key == \"commonName\":\n if _dnsname_match(value, hostname):\n return\n dnsnames.append(value)\n\n if len(dnsnames) > 1:\n raise CertificateError(\n \"hostname %r \"\n \"doesn't match either of %s\" % (hostname, \", \".join(map(repr, dnsnames)))\n )\n elif len(dnsnames) == 1:\n raise CertificateError(f\"hostname {hostname!r} doesn't match {dnsnames[0]!r}\")\n else:\n raise CertificateError(\"no appropriate subjectAltName fields were found\")" }, { "identifier": "Url", "path": ".venv/Lib/site-packages/urllib3/util/url.py", "snippet": "class Url(\n typing.NamedTuple(\n \"Url\",\n [\n (\"scheme\", typing.Optional[str]),\n (\"auth\", typing.Optional[str]),\n (\"host\", typing.Optional[str]),\n (\"port\", typing.Optional[int]),\n (\"path\", typing.Optional[str]),\n (\"query\", typing.Optional[str]),\n (\"fragment\", typing.Optional[str]),\n ],\n )\n):\n \"\"\"\n Data structure for representing an HTTP URL. Used as a return value for\n :func:`parse_url`. Both the scheme and host are normalized as they are\n both case-insensitive according to RFC 3986.\n \"\"\"\n\n def __new__( # type: ignore[no-untyped-def]\n cls,\n scheme: str | None = None,\n auth: str | None = None,\n host: str | None = None,\n port: int | None = None,\n path: str | None = None,\n query: str | None = None,\n fragment: str | None = None,\n ):\n if path and not path.startswith(\"/\"):\n path = \"/\" + path\n if scheme is not None:\n scheme = scheme.lower()\n return super().__new__(cls, scheme, auth, host, port, path, query, fragment)\n\n @property\n def hostname(self) -> str | None:\n \"\"\"For backwards-compatibility with urlparse. We're nice like that.\"\"\"\n return self.host\n\n @property\n def request_uri(self) -> str:\n \"\"\"Absolute path including the query string.\"\"\"\n uri = self.path or \"/\"\n\n if self.query is not None:\n uri += \"?\" + self.query\n\n return uri\n\n @property\n def authority(self) -> str | None:\n \"\"\"\n Authority component as defined in RFC 3986 3.2.\n This includes userinfo (auth), host and port.\n\n i.e.\n userinfo@host:port\n \"\"\"\n userinfo = self.auth\n netloc = self.netloc\n if netloc is None or userinfo is None:\n return netloc\n else:\n return f\"{userinfo}@{netloc}\"\n\n @property\n def netloc(self) -> str | None:\n \"\"\"\n Network location including host and port.\n\n If you need the equivalent of urllib.parse's ``netloc``,\n use the ``authority`` property instead.\n \"\"\"\n if self.host is None:\n return None\n if self.port:\n return f\"{self.host}:{self.port}\"\n return self.host\n\n @property\n def url(self) -> str:\n \"\"\"\n Convert self into a url\n\n This function should more or less round-trip with :func:`.parse_url`. The\n returned url may not be exactly the same as the url inputted to\n :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls\n with a blank port will have : removed).\n\n Example:\n\n .. code-block:: python\n\n import urllib3\n\n U = urllib3.util.parse_url(\"https://google.com/mail/\")\n\n print(U.url)\n # \"https://google.com/mail/\"\n\n print( urllib3.util.Url(\"https\", \"username:password\",\n \"host.com\", 80, \"/path\", \"query\", \"fragment\"\n ).url\n )\n # \"https://username:[email protected]:80/path?query#fragment\"\n \"\"\"\n scheme, auth, host, port, path, query, fragment = self\n url = \"\"\n\n # We use \"is not None\" we want things to happen with empty strings (or 0 port)\n if scheme is not None:\n url += scheme + \"://\"\n if auth is not None:\n url += auth + \"@\"\n if host is not None:\n url += host\n if port is not None:\n url += \":\" + str(port)\n if path is not None:\n url += path\n if query is not None:\n url += \"?\" + query\n if fragment is not None:\n url += \"#\" + fragment\n\n return url\n\n def __str__(self) -> str:\n return self.url" } ]
import datetime import logging import os import re import socket import sys import typing import warnings import ssl from http.client import HTTPConnection as _HTTPConnection from http.client import HTTPException as HTTPException # noqa: F401 from http.client import ResponseNotReady from socket import timeout as SocketTimeout from typing import Literal from .response import HTTPResponse from .util.ssl_ import _TYPE_PEER_CERT_RET_DICT from .util.ssltransport import SSLTransport from ._collections import HTTPHeaderDict from .util.response import assert_header_parsing from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT, Timeout from .util.util import to_str from .util.wait import wait_for_read from ._base_connection import _TYPE_BODY from ._base_connection import ProxyConfig as ProxyConfig from ._base_connection import _ResponseOptions as _ResponseOptions from ._version import __version__ from .exceptions import ( ConnectTimeoutError, HeaderParsingError, NameResolutionError, NewConnectionError, ProxyError, SystemTimeWarning, ) from .util import SKIP_HEADER, SKIPPABLE_HEADERS, connection, ssl_ from .util.request import body_to_chunks from .util.ssl_ import assert_fingerprint as _assert_fingerprint from .util.ssl_ import ( create_urllib3_context, is_ipaddress, resolve_cert_reqs, resolve_ssl_version, ssl_wrap_socket, ) from .util.ssl_match_hostname import CertificateError, match_hostname from .util.url import Url from .response import HTTPResponse
15,793
) -> _WrappedAndVerifiedSocket: """Logic for constructing an SSLContext from all TLS parameters, passing that down into ssl_wrap_socket, and then doing certificate verification either via hostname or fingerprint. This function exists to guarantee that both proxies and targets have the same behavior when connecting via TLS. """ default_ssl_context = False if ssl_context is None: default_ssl_context = True context = create_urllib3_context( ssl_version=resolve_ssl_version(ssl_version), ssl_minimum_version=ssl_minimum_version, ssl_maximum_version=ssl_maximum_version, cert_reqs=resolve_cert_reqs(cert_reqs), ) else: context = ssl_context context.verify_mode = resolve_cert_reqs(cert_reqs) # In some cases, we want to verify hostnames ourselves if ( # `ssl` can't verify fingerprints or alternate hostnames assert_fingerprint or assert_hostname # assert_hostname can be set to False to disable hostname checking or assert_hostname is False # We still support OpenSSL 1.0.2, which prevents us from verifying # hostnames easily: https://github.com/pyca/pyopenssl/pull/933 or ssl_.IS_PYOPENSSL or not ssl_.HAS_NEVER_CHECK_COMMON_NAME ): context.check_hostname = False # Try to load OS default certs if none are given. We need to do the hasattr() check # for custom pyOpenSSL SSLContext objects because they don't support # load_default_certs(). if ( not ca_certs and not ca_cert_dir and not ca_cert_data and default_ssl_context and hasattr(context, "load_default_certs") ): context.load_default_certs() # Ensure that IPv6 addresses are in the proper format and don't have a # scope ID. Python's SSL module fails to recognize scoped IPv6 addresses # and interprets them as DNS hostnames. if server_hostname is not None: normalized = server_hostname.strip("[]") if "%" in normalized: normalized = normalized[: normalized.rfind("%")] if is_ipaddress(normalized): server_hostname = normalized ssl_sock = ssl_wrap_socket( sock=sock, keyfile=key_file, certfile=cert_file, key_password=key_password, ca_certs=ca_certs, ca_cert_dir=ca_cert_dir, ca_cert_data=ca_cert_data, server_hostname=server_hostname, ssl_context=context, tls_in_tls=tls_in_tls, ) try: if assert_fingerprint: _assert_fingerprint( ssl_sock.getpeercert(binary_form=True), assert_fingerprint ) elif ( context.verify_mode != ssl.CERT_NONE and not context.check_hostname and assert_hostname is not False ): cert: _TYPE_PEER_CERT_RET_DICT = ssl_sock.getpeercert() # type: ignore[assignment] # Need to signal to our match_hostname whether to use 'commonName' or not. # If we're using our own constructed SSLContext we explicitly set 'False' # because PyPy hard-codes 'True' from SSLContext.hostname_checks_common_name. if default_ssl_context: hostname_checks_common_name = False else: hostname_checks_common_name = ( getattr(context, "hostname_checks_common_name", False) or False ) _match_hostname( cert, assert_hostname or server_hostname, # type: ignore[arg-type] hostname_checks_common_name, ) return _WrappedAndVerifiedSocket( socket=ssl_sock, is_verified=context.verify_mode == ssl.CERT_REQUIRED or bool(assert_fingerprint), ) except BaseException: ssl_sock.close() raise def _match_hostname( cert: _TYPE_PEER_CERT_RET_DICT | None, asserted_hostname: str, hostname_checks_common_name: bool = False, ) -> None: # Our upstream implementation of ssl.match_hostname() # only applies this normalization to IP addresses so it doesn't # match DNS SANs so we do the same thing! stripped_hostname = asserted_hostname.strip("[]") if is_ipaddress(stripped_hostname): asserted_hostname = stripped_hostname try:
from __future__ import annotations if typing.TYPE_CHECKING: try: # Compiled with SSL? BaseSSLError = ssl.SSLError except (ImportError, AttributeError): ssl = None # type: ignore[assignment] class BaseSSLError(BaseException): # type: ignore[no-redef] pass # Not a no-op, we're adding this to the namespace so it can be imported. ConnectionError = ConnectionError BrokenPipeError = BrokenPipeError log = logging.getLogger(__name__) port_by_scheme = {"http": 80, "https": 443} # When it comes time to update this value as a part of regular maintenance # (ie test_recent_date is failing) update it to ~6 months before the current date. RECENT_DATE = datetime.date(2022, 1, 1) _CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]") _HAS_SYS_AUDIT = hasattr(sys, "audit") class HTTPConnection(_HTTPConnection): """ Based on :class:`http.client.HTTPConnection` but provides an extra constructor backwards-compatibility layer between older and newer Pythons. Additional keyword parameters are used to configure attributes of the connection. Accepted parameters include: - ``source_address``: Set the source address for the current connection. - ``socket_options``: Set specific options on the underlying socket. If not specified, then defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy. For example, if you wish to enable TCP Keep Alive in addition to the defaults, you might pass: .. code-block:: python HTTPConnection.default_socket_options + [ (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1), ] Or you may want to disable the defaults by passing an empty list (e.g., ``[]``). """ default_port: typing.ClassVar[int] = port_by_scheme["http"] # type: ignore[misc] #: Disable Nagle's algorithm by default. #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]`` default_socket_options: typing.ClassVar[connection._TYPE_SOCKET_OPTIONS] = [ (socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) ] #: Whether this connection verifies the host's certificate. is_verified: bool = False #: Whether this proxy connection verified the proxy host's certificate. # If no proxy is currently connected to the value will be ``None``. proxy_is_verified: bool | None = None blocksize: int source_address: tuple[str, int] | None socket_options: connection._TYPE_SOCKET_OPTIONS | None _has_connected_to_proxy: bool _response_options: _ResponseOptions | None _tunnel_host: str | None _tunnel_port: int | None _tunnel_scheme: str | None def __init__( self, host: str, port: int | None = None, *, timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, source_address: tuple[str, int] | None = None, blocksize: int = 16384, socket_options: None | (connection._TYPE_SOCKET_OPTIONS) = default_socket_options, proxy: Url | None = None, proxy_config: ProxyConfig | None = None, ) -> None: super().__init__( host=host, port=port, timeout=Timeout.resolve_default_timeout(timeout), source_address=source_address, blocksize=blocksize, ) self.socket_options = socket_options self.proxy = proxy self.proxy_config = proxy_config self._has_connected_to_proxy = False self._response_options = None self._tunnel_host: str | None = None self._tunnel_port: int | None = None self._tunnel_scheme: str | None = None # https://github.com/python/mypy/issues/4125 # Mypy treats this as LSP violation, which is considered a bug. # If `host` is made a property it violates LSP, because a writeable attribute is overridden with a read-only one. # However, there is also a `host` setter so LSP is not violated. # Potentially, a `@host.deleter` might be needed depending on how this issue will be fixed. @property def host(self) -> str: """ Getter method to remove any trailing dots that indicate the hostname is an FQDN. In general, SSL certificates don't include the trailing dot indicating a fully-qualified domain name, and thus, they don't validate properly when checked against a domain name that includes the dot. In addition, some servers may not expect to receive the trailing dot when provided. However, the hostname with trailing dot is critical to DNS resolution; doing a lookup with the trailing dot will properly only resolve the appropriate FQDN, whereas a lookup without a trailing dot will search the system's search domain list. Thus, it's important to keep the original host around for use only in those cases where it's appropriate (i.e., when doing DNS lookup to establish the actual TCP connection across which we're going to send HTTP requests). """ return self._dns_host.rstrip(".") @host.setter def host(self, value: str) -> None: """ Setter for the `host` property. We assume that only urllib3 uses the _dns_host attribute; httplib itself only uses `host`, and it seems reasonable that other libraries follow suit. """ self._dns_host = value def _new_conn(self) -> socket.socket: """Establish a socket connection and set nodelay settings on it. :return: New socket connection. """ try: sock = connection.create_connection( (self._dns_host, self.port), self.timeout, source_address=self.source_address, socket_options=self.socket_options, ) except socket.gaierror as e: raise NameResolutionError(self.host, self, e) from e except SocketTimeout as e: raise ConnectTimeoutError( self, f"Connection to {self.host} timed out. (connect timeout={self.timeout})", ) from e except OSError as e: raise NewConnectionError( self, f"Failed to establish a new connection: {e}" ) from e # Audit hooks are only available in Python 3.8+ if _HAS_SYS_AUDIT: sys.audit("http.client.connect", self, self.host, self.port) return sock def set_tunnel( self, host: str, port: int | None = None, headers: typing.Mapping[str, str] | None = None, scheme: str = "http", ) -> None: if scheme not in ("http", "https"): raise ValueError( f"Invalid proxy scheme for tunneling: {scheme!r}, must be either 'http' or 'https'" ) super().set_tunnel(host, port=port, headers=headers) self._tunnel_scheme = scheme def connect(self) -> None: self.sock = self._new_conn() if self._tunnel_host: # If we're tunneling it means we're connected to our proxy. self._has_connected_to_proxy = True # TODO: Fix tunnel so it doesn't depend on self.sock state. self._tunnel() # type: ignore[attr-defined] # If there's a proxy to be connected to we are fully connected. # This is set twice (once above and here) due to forwarding proxies # not using tunnelling. self._has_connected_to_proxy = bool(self.proxy) @property def is_closed(self) -> bool: return self.sock is None @property def is_connected(self) -> bool: if self.sock is None: return False return not wait_for_read(self.sock, timeout=0.0) @property def has_connected_to_proxy(self) -> bool: return self._has_connected_to_proxy def close(self) -> None: try: super().close() finally: # Reset all stateful properties so connection # can be re-used without leaking prior configs. self.sock = None self.is_verified = False self.proxy_is_verified = None self._has_connected_to_proxy = False self._response_options = None self._tunnel_host = None self._tunnel_port = None self._tunnel_scheme = None def putrequest( self, method: str, url: str, skip_host: bool = False, skip_accept_encoding: bool = False, ) -> None: """""" # Empty docstring because the indentation of CPython's implementation # is broken but we don't want this method in our documentation. match = _CONTAINS_CONTROL_CHAR_RE.search(method) if match: raise ValueError( f"Method cannot contain non-token characters {method!r} (found at least {match.group()!r})" ) return super().putrequest( method, url, skip_host=skip_host, skip_accept_encoding=skip_accept_encoding ) def putheader(self, header: str, *values: str) -> None: """""" if not any(isinstance(v, str) and v == SKIP_HEADER for v in values): super().putheader(header, *values) elif to_str(header.lower()) not in SKIPPABLE_HEADERS: skippable_headers = "', '".join( [str.title(header) for header in sorted(SKIPPABLE_HEADERS)] ) raise ValueError( f"urllib3.util.SKIP_HEADER only supports '{skippable_headers}'" ) # `request` method's signature intentionally violates LSP. # urllib3's API is different from `http.client.HTTPConnection` and the subclassing is only incidental. def request( # type: ignore[override] self, method: str, url: str, body: _TYPE_BODY | None = None, headers: typing.Mapping[str, str] | None = None, *, chunked: bool = False, preload_content: bool = True, decode_content: bool = True, enforce_content_length: bool = True, ) -> None: # Update the inner socket's timeout value to send the request. # This only triggers if the connection is re-used. if self.sock is not None: self.sock.settimeout(self.timeout) # Store these values to be fed into the HTTPResponse # object later. TODO: Remove this in favor of a real # HTTP lifecycle mechanism. # We have to store these before we call .request() # because sometimes we can still salvage a response # off the wire even if we aren't able to completely # send the request body. self._response_options = _ResponseOptions( request_method=method, request_url=url, preload_content=preload_content, decode_content=decode_content, enforce_content_length=enforce_content_length, ) if headers is None: headers = {} header_keys = frozenset(to_str(k.lower()) for k in headers) skip_accept_encoding = "accept-encoding" in header_keys skip_host = "host" in header_keys self.putrequest( method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host ) # Transform the body into an iterable of sendall()-able chunks # and detect if an explicit Content-Length is doable. chunks_and_cl = body_to_chunks(body, method=method, blocksize=self.blocksize) chunks = chunks_and_cl.chunks content_length = chunks_and_cl.content_length # When chunked is explicit set to 'True' we respect that. if chunked: if "transfer-encoding" not in header_keys: self.putheader("Transfer-Encoding", "chunked") else: # Detect whether a framing mechanism is already in use. If so # we respect that value, otherwise we pick chunked vs content-length # depending on the type of 'body'. if "content-length" in header_keys: chunked = False elif "transfer-encoding" in header_keys: chunked = True # Otherwise we go off the recommendation of 'body_to_chunks()'. else: chunked = False if content_length is None: if chunks is not None: chunked = True self.putheader("Transfer-Encoding", "chunked") else: self.putheader("Content-Length", str(content_length)) # Now that framing headers are out of the way we send all the other headers. if "user-agent" not in header_keys: self.putheader("User-Agent", _get_default_user_agent()) for header, value in headers.items(): self.putheader(header, value) self.endheaders() # If we're given a body we start sending that in chunks. if chunks is not None: for chunk in chunks: # Sending empty chunks isn't allowed for TE: chunked # as it indicates the end of the body. if not chunk: continue if isinstance(chunk, str): chunk = chunk.encode("utf-8") if chunked: self.send(b"%x\r\n%b\r\n" % (len(chunk), chunk)) else: self.send(chunk) # Regardless of whether we have a body or not, if we're in # chunked mode we want to send an explicit empty chunk. if chunked: self.send(b"0\r\n\r\n") def request_chunked( self, method: str, url: str, body: _TYPE_BODY | None = None, headers: typing.Mapping[str, str] | None = None, ) -> None: """ Alternative to the common request method, which sends the body with chunked encoding and not as one block """ warnings.warn( "HTTPConnection.request_chunked() is deprecated and will be removed " "in urllib3 v2.1.0. Instead use HTTPConnection.request(..., chunked=True).", category=DeprecationWarning, stacklevel=2, ) self.request(method, url, body=body, headers=headers, chunked=True) def getresponse( # type: ignore[override] self, ) -> HTTPResponse: """ Get the response from the server. If the HTTPConnection is in the correct state, returns an instance of HTTPResponse or of whatever object is returned by the response_class variable. If a request has not been sent or if a previous response has not be handled, ResponseNotReady is raised. If the HTTP response indicates that the connection should be closed, then it will be closed before the response is returned. When the connection is closed, the underlying socket is closed. """ # Raise the same error as http.client.HTTPConnection if self._response_options is None: raise ResponseNotReady() # Reset this attribute for being used again. resp_options = self._response_options self._response_options = None # Since the connection's timeout value may have been updated # we need to set the timeout on the socket. self.sock.settimeout(self.timeout) # This is needed here to avoid circular import errors # Get the response from http.client.HTTPConnection httplib_response = super().getresponse() try: assert_header_parsing(httplib_response.msg) except (HeaderParsingError, TypeError) as hpe: log.warning( "Failed to parse headers (url=%s): %s", _url_from_connection(self, resp_options.request_url), hpe, exc_info=True, ) headers = HTTPHeaderDict(httplib_response.msg.items()) response = HTTPResponse( body=httplib_response, headers=headers, status=httplib_response.status, version=httplib_response.version, reason=httplib_response.reason, preload_content=resp_options.preload_content, decode_content=resp_options.decode_content, original_response=httplib_response, enforce_content_length=resp_options.enforce_content_length, request_method=resp_options.request_method, request_url=resp_options.request_url, ) return response class HTTPSConnection(HTTPConnection): """ Many of the parameters to this constructor are passed to the underlying SSL socket by means of :py:func:`urllib3.util.ssl_wrap_socket`. """ default_port = port_by_scheme["https"] # type: ignore[misc] cert_reqs: int | str | None = None ca_certs: str | None = None ca_cert_dir: str | None = None ca_cert_data: None | str | bytes = None ssl_version: int | str | None = None ssl_minimum_version: int | None = None ssl_maximum_version: int | None = None assert_fingerprint: str | None = None def __init__( self, host: str, port: int | None = None, *, timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, source_address: tuple[str, int] | None = None, blocksize: int = 16384, socket_options: None | (connection._TYPE_SOCKET_OPTIONS) = HTTPConnection.default_socket_options, proxy: Url | None = None, proxy_config: ProxyConfig | None = None, cert_reqs: int | str | None = None, assert_hostname: None | str | Literal[False] = None, assert_fingerprint: str | None = None, server_hostname: str | None = None, ssl_context: ssl.SSLContext | None = None, ca_certs: str | None = None, ca_cert_dir: str | None = None, ca_cert_data: None | str | bytes = None, ssl_minimum_version: int | None = None, ssl_maximum_version: int | None = None, ssl_version: int | str | None = None, # Deprecated cert_file: str | None = None, key_file: str | None = None, key_password: str | None = None, ) -> None: super().__init__( host, port=port, timeout=timeout, source_address=source_address, blocksize=blocksize, socket_options=socket_options, proxy=proxy, proxy_config=proxy_config, ) self.key_file = key_file self.cert_file = cert_file self.key_password = key_password self.ssl_context = ssl_context self.server_hostname = server_hostname self.assert_hostname = assert_hostname self.assert_fingerprint = assert_fingerprint self.ssl_version = ssl_version self.ssl_minimum_version = ssl_minimum_version self.ssl_maximum_version = ssl_maximum_version self.ca_certs = ca_certs and os.path.expanduser(ca_certs) self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir) self.ca_cert_data = ca_cert_data # cert_reqs depends on ssl_context so calculate last. if cert_reqs is None: if self.ssl_context is not None: cert_reqs = self.ssl_context.verify_mode else: cert_reqs = resolve_cert_reqs(None) self.cert_reqs = cert_reqs def set_cert( self, key_file: str | None = None, cert_file: str | None = None, cert_reqs: int | str | None = None, key_password: str | None = None, ca_certs: str | None = None, assert_hostname: None | str | Literal[False] = None, assert_fingerprint: str | None = None, ca_cert_dir: str | None = None, ca_cert_data: None | str | bytes = None, ) -> None: """ This method should only be called once, before the connection is used. """ warnings.warn( "HTTPSConnection.set_cert() is deprecated and will be removed " "in urllib3 v2.1.0. Instead provide the parameters to the " "HTTPSConnection constructor.", category=DeprecationWarning, stacklevel=2, ) # If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also # have an SSLContext object in which case we'll use its verify_mode. if cert_reqs is None: if self.ssl_context is not None: cert_reqs = self.ssl_context.verify_mode else: cert_reqs = resolve_cert_reqs(None) self.key_file = key_file self.cert_file = cert_file self.cert_reqs = cert_reqs self.key_password = key_password self.assert_hostname = assert_hostname self.assert_fingerprint = assert_fingerprint self.ca_certs = ca_certs and os.path.expanduser(ca_certs) self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir) self.ca_cert_data = ca_cert_data def connect(self) -> None: sock: socket.socket | ssl.SSLSocket self.sock = sock = self._new_conn() server_hostname: str = self.host tls_in_tls = False # Do we need to establish a tunnel? if self._tunnel_host is not None: # We're tunneling to an HTTPS origin so need to do TLS-in-TLS. if self._tunnel_scheme == "https": self.sock = sock = self._connect_tls_proxy(self.host, sock) tls_in_tls = True # If we're tunneling it means we're connected to our proxy. self._has_connected_to_proxy = True self._tunnel() # type: ignore[attr-defined] # Override the host with the one we're requesting data from. server_hostname = self._tunnel_host if self.server_hostname is not None: server_hostname = self.server_hostname is_time_off = datetime.date.today() < RECENT_DATE if is_time_off: warnings.warn( ( f"System time is way off (before {RECENT_DATE}). This will probably " "lead to SSL verification errors" ), SystemTimeWarning, ) sock_and_verified = _ssl_wrap_socket_and_match_hostname( sock=sock, cert_reqs=self.cert_reqs, ssl_version=self.ssl_version, ssl_minimum_version=self.ssl_minimum_version, ssl_maximum_version=self.ssl_maximum_version, ca_certs=self.ca_certs, ca_cert_dir=self.ca_cert_dir, ca_cert_data=self.ca_cert_data, cert_file=self.cert_file, key_file=self.key_file, key_password=self.key_password, server_hostname=server_hostname, ssl_context=self.ssl_context, tls_in_tls=tls_in_tls, assert_hostname=self.assert_hostname, assert_fingerprint=self.assert_fingerprint, ) self.sock = sock_and_verified.socket self.is_verified = sock_and_verified.is_verified # If there's a proxy to be connected to we are fully connected. # This is set twice (once above and here) due to forwarding proxies # not using tunnelling. self._has_connected_to_proxy = bool(self.proxy) def _connect_tls_proxy(self, hostname: str, sock: socket.socket) -> ssl.SSLSocket: """ Establish a TLS connection to the proxy using the provided SSL context. """ # `_connect_tls_proxy` is called when self._tunnel_host is truthy. proxy_config = typing.cast(ProxyConfig, self.proxy_config) ssl_context = proxy_config.ssl_context sock_and_verified = _ssl_wrap_socket_and_match_hostname( sock, cert_reqs=self.cert_reqs, ssl_version=self.ssl_version, ssl_minimum_version=self.ssl_minimum_version, ssl_maximum_version=self.ssl_maximum_version, ca_certs=self.ca_certs, ca_cert_dir=self.ca_cert_dir, ca_cert_data=self.ca_cert_data, server_hostname=hostname, ssl_context=ssl_context, assert_hostname=proxy_config.assert_hostname, assert_fingerprint=proxy_config.assert_fingerprint, # Features that aren't implemented for proxies yet: cert_file=None, key_file=None, key_password=None, tls_in_tls=False, ) self.proxy_is_verified = sock_and_verified.is_verified return sock_and_verified.socket # type: ignore[return-value] class _WrappedAndVerifiedSocket(typing.NamedTuple): """ Wrapped socket and whether the connection is verified after the TLS handshake """ socket: ssl.SSLSocket | SSLTransport is_verified: bool def _ssl_wrap_socket_and_match_hostname( sock: socket.socket, *, cert_reqs: None | str | int, ssl_version: None | str | int, ssl_minimum_version: int | None, ssl_maximum_version: int | None, cert_file: str | None, key_file: str | None, key_password: str | None, ca_certs: str | None, ca_cert_dir: str | None, ca_cert_data: None | str | bytes, assert_hostname: None | str | Literal[False], assert_fingerprint: str | None, server_hostname: str | None, ssl_context: ssl.SSLContext | None, tls_in_tls: bool = False, ) -> _WrappedAndVerifiedSocket: """Logic for constructing an SSLContext from all TLS parameters, passing that down into ssl_wrap_socket, and then doing certificate verification either via hostname or fingerprint. This function exists to guarantee that both proxies and targets have the same behavior when connecting via TLS. """ default_ssl_context = False if ssl_context is None: default_ssl_context = True context = create_urllib3_context( ssl_version=resolve_ssl_version(ssl_version), ssl_minimum_version=ssl_minimum_version, ssl_maximum_version=ssl_maximum_version, cert_reqs=resolve_cert_reqs(cert_reqs), ) else: context = ssl_context context.verify_mode = resolve_cert_reqs(cert_reqs) # In some cases, we want to verify hostnames ourselves if ( # `ssl` can't verify fingerprints or alternate hostnames assert_fingerprint or assert_hostname # assert_hostname can be set to False to disable hostname checking or assert_hostname is False # We still support OpenSSL 1.0.2, which prevents us from verifying # hostnames easily: https://github.com/pyca/pyopenssl/pull/933 or ssl_.IS_PYOPENSSL or not ssl_.HAS_NEVER_CHECK_COMMON_NAME ): context.check_hostname = False # Try to load OS default certs if none are given. We need to do the hasattr() check # for custom pyOpenSSL SSLContext objects because they don't support # load_default_certs(). if ( not ca_certs and not ca_cert_dir and not ca_cert_data and default_ssl_context and hasattr(context, "load_default_certs") ): context.load_default_certs() # Ensure that IPv6 addresses are in the proper format and don't have a # scope ID. Python's SSL module fails to recognize scoped IPv6 addresses # and interprets them as DNS hostnames. if server_hostname is not None: normalized = server_hostname.strip("[]") if "%" in normalized: normalized = normalized[: normalized.rfind("%")] if is_ipaddress(normalized): server_hostname = normalized ssl_sock = ssl_wrap_socket( sock=sock, keyfile=key_file, certfile=cert_file, key_password=key_password, ca_certs=ca_certs, ca_cert_dir=ca_cert_dir, ca_cert_data=ca_cert_data, server_hostname=server_hostname, ssl_context=context, tls_in_tls=tls_in_tls, ) try: if assert_fingerprint: _assert_fingerprint( ssl_sock.getpeercert(binary_form=True), assert_fingerprint ) elif ( context.verify_mode != ssl.CERT_NONE and not context.check_hostname and assert_hostname is not False ): cert: _TYPE_PEER_CERT_RET_DICT = ssl_sock.getpeercert() # type: ignore[assignment] # Need to signal to our match_hostname whether to use 'commonName' or not. # If we're using our own constructed SSLContext we explicitly set 'False' # because PyPy hard-codes 'True' from SSLContext.hostname_checks_common_name. if default_ssl_context: hostname_checks_common_name = False else: hostname_checks_common_name = ( getattr(context, "hostname_checks_common_name", False) or False ) _match_hostname( cert, assert_hostname or server_hostname, # type: ignore[arg-type] hostname_checks_common_name, ) return _WrappedAndVerifiedSocket( socket=ssl_sock, is_verified=context.verify_mode == ssl.CERT_REQUIRED or bool(assert_fingerprint), ) except BaseException: ssl_sock.close() raise def _match_hostname( cert: _TYPE_PEER_CERT_RET_DICT | None, asserted_hostname: str, hostname_checks_common_name: bool = False, ) -> None: # Our upstream implementation of ssl.match_hostname() # only applies this normalization to IP addresses so it doesn't # match DNS SANs so we do the same thing! stripped_hostname = asserted_hostname.strip("[]") if is_ipaddress(stripped_hostname): asserted_hostname = stripped_hostname try:
match_hostname(cert, asserted_hostname, hostname_checks_common_name)
29
2023-12-16 04:12:01+00:00
24k
YaoFANGUK/video-subtitle-remover
backend/scenedetect/scene_manager.py
[ { "identifier": "SimpleTableCell", "path": "backend/scenedetect/_thirdparty/simpletable.py", "snippet": "class SimpleTableCell(object):\n \"\"\"A table class to create table cells.\n\n Example:\n cell = SimpleTableCell('Hello, world!')\n \"\"\"\n\n def __init__(self, text, header=False):\n \"\"\"Table cell constructor.\n\n Keyword arguments:\n text -- text to be displayed\n header -- flag to indicate this cell is a header cell.\n \"\"\"\n self.text = text\n self.header = header\n\n def __str__(self):\n \"\"\"Return the HTML code for the table cell.\"\"\"\n if self.header:\n return '<th>%s</th>' % (self.text)\n else:\n return '<td>%s</td>' % (self.text)" }, { "identifier": "SimpleTableImage", "path": "backend/scenedetect/_thirdparty/simpletable.py", "snippet": "class SimpleTableImage(object):\n \"\"\"A table class to create table cells with an image.\n\n Example:\n cell = SimpleTableImage('images/image_1.jpg')\n \"\"\"\n\n def __init__(self, image_file, width=None, height=None):\n \"\"\"Table cell constructor.\n\n Keyword arguments:\n image_file -- relative filepath to image file to display.\n width -- (optional) width of the image in pixels\n height -- (optional) height of the image in pixels\n \"\"\"\n self.image_file = image_file\n if width:\n self.width = round(width)\n else:\n self.width = width\n if height:\n self.height = round(height)\n else:\n self.height = height\n\n def __str__(self):\n \"\"\"Return the HTML code for the table cell with the image.\"\"\"\n safe_filename = quote(self.image_file)\n output = '<a href=\"%s\" target=\"_blank\">' % (safe_filename)\n output += '<img src=\"%s\"' % (safe_filename)\n if self.height:\n output += ' height=\"%s\"' % (self.height)\n if self.width:\n output += ' width=\"%s\"' % (self.width)\n output += '></a>'\n\n return output" }, { "identifier": "SimpleTableRow", "path": "backend/scenedetect/_thirdparty/simpletable.py", "snippet": "class SimpleTableRow(object):\n \"\"\"A table class to create table rows, populated by table cells.\n\n Example:\n # Row from list\n row = SimpleTableRow(['Hello,', 'world!'])\n\n # Row from SimpleTableCell\n cell1 = SimpleTableCell('Hello,')\n cell2 = SimpleTableCell('world!')\n row = SimpleTableRow([cell1, cell2])\n \"\"\"\n\n def __init__(self, cells=None, header=False):\n \"\"\"Table row constructor.\n\n Keyword arguments:\n cells -- iterable of SimpleTableCell (default None)\n header -- flag to indicate this row is a header row.\n if the cells are SimpleTableCell, it is the programmer's\n responsibility to verify whether it was created with the\n header flag set to True.\n \"\"\"\n cells = cells or []\n if isinstance(cells[0], SimpleTableCell):\n self.cells = cells\n else:\n self.cells = [SimpleTableCell(cell, header=header) for cell in cells]\n\n self.header = header\n\n def __str__(self):\n \"\"\"Return the HTML code for the table row and its cells as a string.\"\"\"\n row = []\n\n row.append('<tr>')\n\n for cell in self.cells:\n row.append(str(cell))\n\n row.append('</tr>')\n\n return '\\n'.join(row)\n\n def __iter__(self):\n \"\"\"Iterate through row cells\"\"\"\n for cell in self.cells:\n yield cell\n\n def add_cell(self, cell):\n \"\"\"Add a SimpleTableCell object to the list of cells.\"\"\"\n self.cells.append(cell)\n\n def add_cells(self, cells):\n \"\"\"Add a list of SimpleTableCell objects to the list of cells.\"\"\"\n for cell in cells:\n self.cells.append(cell)" }, { "identifier": "SimpleTable", "path": "backend/scenedetect/_thirdparty/simpletable.py", "snippet": "class SimpleTable(object):\n \"\"\"A table class to create HTML tables, populated by HTML table rows.\n\n Example:\n # Table from lists\n table = SimpleTable([['Hello,', 'world!'], ['How', 'are', 'you?']])\n\n # Table with header row\n table = SimpleTable([['Hello,', 'world!'], ['How', 'are', 'you?']],\n header_row=['Header1', 'Header2', 'Header3'])\n\n # Table from SimpleTableRow\n rows = SimpleTableRow(['Hello,', 'world!'])\n table = SimpleTable(rows)\n \"\"\"\n\n def __init__(self, rows=None, header_row=None, css_class=None):\n \"\"\"Table constructor.\n\n Keyword arguments:\n rows -- iterable of SimpleTableRow\n header_row -- row that will be displayed at the beginning of the table.\n if this row is SimpleTableRow, it is the programmer's\n responsibility to verify whether it was created with the\n header flag set to True.\n css_class -- table CSS class\n \"\"\"\n rows = rows or []\n if isinstance(rows[0], SimpleTableRow):\n self.rows = rows\n else:\n self.rows = [SimpleTableRow(row) for row in rows]\n\n if header_row is None:\n self.header_row = None\n elif isinstance(header_row, SimpleTableRow):\n self.header_row = header_row\n else:\n self.header_row = SimpleTableRow(header_row, header=True)\n\n self.css_class = css_class\n\n def __str__(self):\n \"\"\"Return the HTML code for the table as a string.\"\"\"\n table = []\n\n if self.css_class:\n table.append('<table class=%s>' % self.css_class)\n else:\n table.append('<table>')\n\n if self.header_row:\n table.append(str(self.header_row))\n\n for row in self.rows:\n table.append(str(row))\n\n table.append('</table>')\n\n return '\\n'.join(table)\n\n def __iter__(self):\n \"\"\"Iterate through table rows\"\"\"\n for row in self.rows:\n yield row\n\n def add_row(self, row):\n \"\"\"Add a SimpleTableRow object to the list of rows.\"\"\"\n self.rows.append(row)\n\n def add_rows(self, rows):\n \"\"\"Add a list of SimpleTableRow objects to the list of rows.\"\"\"\n for row in rows:\n self.rows.append(row)" }, { "identifier": "HTMLPage", "path": "backend/scenedetect/_thirdparty/simpletable.py", "snippet": "class HTMLPage(object):\n \"\"\"A class to create HTML pages containing CSS and tables.\"\"\"\n\n def __init__(self, tables=None, css=None, encoding=\"utf-8\"):\n \"\"\"HTML page constructor.\n\n Keyword arguments:\n tables -- List of SimpleTable objects\n css -- Cascading Style Sheet specification that is appended before the\n table string\n encoding -- Characters encoding. Default: UTF-8\n \"\"\"\n self.tables = tables or []\n self.css = css\n self.encoding = encoding\n\n def __str__(self):\n \"\"\"Return the HTML page as a string.\"\"\"\n page = []\n\n if self.css:\n page.append('<style type=\"text/css\">\\n%s\\n</style>' % self.css)\n\n # Set encoding\n page.append('<meta http-equiv=\"Content-Type\" content=\"text/html;'\n 'charset=%s\">' % self.encoding)\n\n for table in self.tables:\n page.append(str(table))\n page.append('<br />')\n\n return '\\n'.join(page)\n\n def __iter__(self):\n \"\"\"Iterate through tables\"\"\"\n for table in self.tables:\n yield table\n\n def save(self, filename):\n \"\"\"Save HTML page to a file using the proper encoding\"\"\"\n with codecs.open(filename, 'w', self.encoding) as outfile:\n for line in str(self):\n outfile.write(line)\n\n def add_table(self, table):\n \"\"\"Add a SimpleTable to the page list of tables\"\"\"\n self.tables.append(table)" }, { "identifier": "tqdm", "path": "backend/scenedetect/platform.py", "snippet": "class FakeTqdmObject:\nclass FakeTqdmLoggingRedirect:\nclass CommandTooLong(Exception):\nclass Template(string.Template):\n def __init__(self, **kawrgs):\n def update(self, n=1):\n def close(self):\n def set_description(self, desc=None, refresh=True):\n def __init__(self, **kawrgs):\n def __enter__(self):\n def __exit__(self, type, value, traceback):\ndef get_cv2_imwrite_params() -> Dict[str, Union[int, None]]:\n def _get_cv2_param(param_name: str) -> Union[int, None]:\ndef get_file_name(file_path: AnyStr, include_extension=True) -> AnyStr:\ndef get_and_create_path(file_path: AnyStr, output_directory: Optional[AnyStr] = None) -> AnyStr:\ndef init_logger(log_level: int = logging.INFO,\n show_stdout: bool = False,\n log_file: Optional[str] = None):\ndef invoke_command(args: List[str]) -> int:\ndef get_ffmpeg_path() -> Optional[str]:\ndef get_ffmpeg_version() -> Optional[str]:\ndef get_mkvmerge_version() -> Optional[str]:\ndef get_system_version_info() -> str:\n INFO_TEMPLATE = '[PySceneDetect] %(message)s'\n DEBUG_TEMPLATE = '%(levelname)s: %(module)s.%(funcName)s(): %(message)s'" }, { "identifier": "FrameTimecode", "path": "backend/scenedetect/frame_timecode.py", "snippet": "class FrameTimecode:\n \"\"\"Object for frame-based timecodes, using the video framerate to compute back and\n forth between frame number and seconds/timecode.\n\n A timecode is valid only if it complies with one of the following three types/formats:\n\n 1. Timecode as `str` in the form 'HH:MM:SS[.nnn]' (`'01:23:45'` or `'01:23:45.678'`)\n 2. Number of seconds as `float`, or `str` in form 'Ss' or 'S.SSSs' (`'2s'` or `'2.3456s'`)\n 3. Exact number of frames as `int`, or `str` in form NNNNN (`123` or `'123'`)\n \"\"\"\n\n def __init__(self,\n timecode: Union[int, float, str, 'FrameTimecode'] = None,\n fps: Union[int, float, str, 'FrameTimecode'] = None):\n \"\"\"\n Arguments:\n timecode: A frame number (int), number of seconds (float), or timecode (str in\n the form `'HH:MM:SS'` or `'HH:MM:SS.nnn'`).\n fps: The framerate or FrameTimecode to use as a time base for all arithmetic.\n Raises:\n TypeError: Thrown if either `timecode` or `fps` are unsupported types.\n ValueError: Thrown when specifying a negative timecode or framerate.\n \"\"\"\n # The following two properties are what is used to keep track of time\n # in a frame-specific manner. Note that once the framerate is set,\n # the value should never be modified (only read if required).\n # TODO(v1.0): Make these actual @properties.\n self.framerate = None\n self.frame_num = None\n\n # Copy constructor. Only the timecode argument is used in this case.\n if isinstance(timecode, FrameTimecode):\n self.framerate = timecode.framerate\n self.frame_num = timecode.frame_num\n if fps is not None:\n raise TypeError('Framerate cannot be overwritten when copying a FrameTimecode.')\n else:\n # Ensure other arguments are consistent with API.\n if fps is None:\n raise TypeError('Framerate (fps) is a required argument.')\n if isinstance(fps, FrameTimecode):\n fps = fps.framerate\n\n # Process the given framerate, if it was not already set.\n if not isinstance(fps, (int, float)):\n raise TypeError('Framerate must be of type int/float.')\n if (isinstance(fps, int) and not fps > 0) or (isinstance(fps, float)\n and not fps >= MAX_FPS_DELTA):\n raise ValueError('Framerate must be positive and greater than zero.')\n self.framerate = float(fps)\n\n # Process the timecode value, storing it as an exact number of frames.\n if isinstance(timecode, str):\n self.frame_num = self._parse_timecode_string(timecode)\n else:\n self.frame_num = self._parse_timecode_number(timecode)\n\n # TODO(v1.0): Add a `frame` property to replace the existing one and deprecate this getter.\n def get_frames(self) -> int:\n \"\"\"Get the current time/position in number of frames. This is the\n equivalent of accessing the self.frame_num property (which, along\n with the specified framerate, forms the base for all of the other\n time measurement calculations, e.g. the :meth:`get_seconds` method).\n\n If using to compare a :class:`FrameTimecode` with a frame number,\n you can do so directly against the object (e.g. ``FrameTimecode(10, 10.0) <= 10``).\n\n Returns:\n int: The current time in frames (the current frame number).\n \"\"\"\n return self.frame_num\n\n # TODO(v1.0): Add a `framerate` property to replace the existing one and deprecate this getter.\n def get_framerate(self) -> float:\n \"\"\"Get Framerate: Returns the framerate used by the FrameTimecode object.\n\n Returns:\n float: Framerate of the current FrameTimecode object, in frames per second.\n \"\"\"\n return self.framerate\n\n def equal_framerate(self, fps) -> bool:\n \"\"\"Equal Framerate: Determines if the passed framerate is equal to that of this object.\n\n Arguments:\n fps: Framerate to compare against within the precision constant defined in this module\n (see :data:`MAX_FPS_DELTA`).\n Returns:\n bool: True if passed fps matches the FrameTimecode object's framerate, False otherwise.\n\n \"\"\"\n return math.fabs(self.framerate - fps) < MAX_FPS_DELTA\n\n # TODO(v1.0): Add a `seconds` property to replace this and deprecate the existing one.\n def get_seconds(self) -> float:\n \"\"\"Get the frame's position in number of seconds.\n\n If using to compare a :class:`FrameTimecode` with a frame number,\n you can do so directly against the object (e.g. ``FrameTimecode(10, 10.0) <= 1.0``).\n\n Returns:\n float: The current time/position in seconds.\n \"\"\"\n return float(self.frame_num) / self.framerate\n\n # TODO(v1.0): Add a `timecode` property to replace this and deprecate the existing one.\n def get_timecode(self, precision: int = 3, use_rounding: bool = True) -> str:\n \"\"\"Get a formatted timecode string of the form HH:MM:SS[.nnn].\n\n Args:\n precision: The number of decimal places to include in the output ``[.nnn]``.\n use_rounding: Rounds the output to the desired precision. If False, the value\n will be truncated to the specified precision.\n\n Returns:\n str: The current time in the form ``\"HH:MM:SS[.nnn]\"``.\n \"\"\"\n # Compute hours and minutes based off of seconds, and update seconds.\n secs = self.get_seconds()\n base = 60.0 * 60.0\n hrs = int(secs / base)\n secs -= (hrs * base)\n base = 60.0\n mins = int(secs / base)\n secs -= (mins * base)\n # Convert seconds into string based on required precision.\n if precision > 0:\n if use_rounding:\n secs = round(secs, precision)\n msec = format(secs, '.%df' % precision)[-precision:]\n secs = '%02d.%s' % (int(secs), msec)\n else:\n secs = '%02d' % int(round(secs, 0)) if use_rounding else '%02d' % int(secs)\n # Return hours, minutes, and seconds as a formatted timecode string.\n return '%02d:%02d:%s' % (hrs, mins, secs)\n\n # TODO(v1.0): Add a `previous` property to replace the existing one and deprecate this getter.\n def previous_frame(self) -> 'FrameTimecode':\n \"\"\"Return a new FrameTimecode for the previous frame (or 0 if on frame 0).\"\"\"\n new_timecode = FrameTimecode(self)\n new_timecode.frame_num = max(0, new_timecode.frame_num - 1)\n return new_timecode\n\n def _seconds_to_frames(self, seconds: float) -> int:\n \"\"\"Convert the passed value seconds to the nearest number of frames using\n the current FrameTimecode object's FPS (self.framerate).\n\n Returns:\n Integer number of frames the passed number of seconds represents using\n the current FrameTimecode's framerate property.\n \"\"\"\n return round(seconds * self.framerate)\n\n def _parse_timecode_number(self, timecode: Union[int, float]) -> int:\n \"\"\" Parse a timecode number, storing it as the exact number of frames.\n Can be passed as frame number (int), seconds (float)\n\n Raises:\n TypeError, ValueError\n \"\"\"\n # Process the timecode value, storing it as an exact number of frames.\n # Exact number of frames N\n if isinstance(timecode, int):\n if timecode < 0:\n raise ValueError('Timecode frame number must be positive and greater than zero.')\n return timecode\n # Number of seconds S\n elif isinstance(timecode, float):\n if timecode < 0.0:\n raise ValueError('Timecode value must be positive and greater than zero.')\n return self._seconds_to_frames(timecode)\n # FrameTimecode\n elif isinstance(timecode, FrameTimecode):\n return timecode.frame_num\n elif timecode is None:\n raise TypeError('Timecode/frame number must be specified!')\n else:\n raise TypeError('Timecode format/type unrecognized.')\n\n def _parse_timecode_string(self, timecode_string: str) -> int:\n \"\"\"Parses a string based on the three possible forms (in timecode format,\n as an integer number of frames, or floating-point seconds, ending with 's').\n\n Requires that the `framerate` property is set before calling this method.\n Assuming a framerate of 30.0 FPS, the strings '00:05:00.000', '00:05:00',\n '9000', '300s', and '300.0s' are all possible valid values, all representing\n a period of time equal to 5 minutes, 300 seconds, or 9000 frames (at 30 FPS).\n\n Raises:\n TypeError, ValueError\n \"\"\"\n if self.framerate is None:\n raise TypeError('self.framerate must be set before calling _parse_timecode_string.')\n # Number of seconds S\n if timecode_string.endswith('s'):\n secs = timecode_string[:-1]\n if not secs.replace('.', '').isdigit():\n raise ValueError('All characters in timecode seconds string must be digits.')\n secs = float(secs)\n if secs < 0.0:\n raise ValueError('Timecode seconds value must be positive.')\n return self._seconds_to_frames(secs)\n # Exact number of frames N\n elif timecode_string.isdigit():\n timecode = int(timecode_string)\n if timecode < 0:\n raise ValueError('Timecode frame number must be positive.')\n return timecode\n # Standard timecode in string format 'HH:MM:SS[.nnn]'\n else:\n tc_val = timecode_string.split(':')\n if not (len(tc_val) == 3 and tc_val[0].isdigit() and tc_val[1].isdigit()\n and tc_val[2].replace('.', '').isdigit()):\n raise ValueError('Unrecognized or improperly formatted timecode string.')\n hrs, mins = int(tc_val[0]), int(tc_val[1])\n secs = float(tc_val[2]) if '.' in tc_val[2] else int(tc_val[2])\n if not (hrs >= 0 and mins >= 0 and secs >= 0 and mins < 60 and secs < 60):\n raise ValueError('Invalid timecode range (values outside allowed range).')\n secs += (((hrs * 60.0) + mins) * 60.0)\n return self._seconds_to_frames(secs)\n\n def __iadd__(self, other: Union[int, float, str, 'FrameTimecode']) -> 'FrameTimecode':\n if isinstance(other, int):\n self.frame_num += other\n elif isinstance(other, FrameTimecode):\n if self.equal_framerate(other.framerate):\n self.frame_num += other.frame_num\n else:\n raise ValueError('FrameTimecode instances require equal framerate for addition.')\n # Check if value to add is in number of seconds.\n elif isinstance(other, float):\n self.frame_num += self._seconds_to_frames(other)\n elif isinstance(other, str):\n self.frame_num += self._parse_timecode_string(other)\n else:\n raise TypeError('Unsupported type for performing addition with FrameTimecode.')\n if self.frame_num < 0: # Required to allow adding negative seconds/frames.\n self.frame_num = 0\n return self\n\n def __add__(self, other: Union[int, float, str, 'FrameTimecode']) -> 'FrameTimecode':\n to_return = FrameTimecode(timecode=self)\n to_return += other\n return to_return\n\n def __isub__(self, other: Union[int, float, str, 'FrameTimecode']) -> 'FrameTimecode':\n if isinstance(other, int):\n self.frame_num -= other\n elif isinstance(other, FrameTimecode):\n if self.equal_framerate(other.framerate):\n self.frame_num -= other.frame_num\n else:\n raise ValueError('FrameTimecode instances require equal framerate for subtraction.')\n # Check if value to add is in number of seconds.\n elif isinstance(other, float):\n self.frame_num -= self._seconds_to_frames(other)\n elif isinstance(other, str):\n self.frame_num -= self._parse_timecode_string(other)\n else:\n raise TypeError('Unsupported type for performing subtraction with FrameTimecode: %s' %\n type(other))\n if self.frame_num < 0:\n self.frame_num = 0\n return self\n\n def __sub__(self, other: Union[int, float, str, 'FrameTimecode']) -> 'FrameTimecode':\n to_return = FrameTimecode(timecode=self)\n to_return -= other\n return to_return\n\n def __eq__(self, other: Union[int, float, str, 'FrameTimecode']) -> 'FrameTimecode':\n if isinstance(other, int):\n return self.frame_num == other\n elif isinstance(other, float):\n return self.get_seconds() == other\n elif isinstance(other, str):\n return self.frame_num == self._parse_timecode_string(other)\n elif isinstance(other, FrameTimecode):\n if self.equal_framerate(other.framerate):\n return self.frame_num == other.frame_num\n else:\n raise TypeError(\n 'FrameTimecode objects must have the same framerate to be compared.')\n elif other is None:\n return False\n else:\n raise TypeError('Unsupported type for performing == with FrameTimecode: %s' %\n type(other))\n\n def __ne__(self, other: Union[int, float, str, 'FrameTimecode']) -> bool:\n return not self == other\n\n def __lt__(self, other: Union[int, float, str, 'FrameTimecode']) -> bool:\n if isinstance(other, int):\n return self.frame_num < other\n elif isinstance(other, float):\n return self.get_seconds() < other\n elif isinstance(other, str):\n return self.frame_num < self._parse_timecode_string(other)\n elif isinstance(other, FrameTimecode):\n if self.equal_framerate(other.framerate):\n return self.frame_num < other.frame_num\n else:\n raise TypeError(\n 'FrameTimecode objects must have the same framerate to be compared.')\n else:\n raise TypeError('Unsupported type for performing < with FrameTimecode: %s' %\n type(other))\n\n def __le__(self, other: Union[int, float, str, 'FrameTimecode']) -> bool:\n if isinstance(other, int):\n return self.frame_num <= other\n elif isinstance(other, float):\n return self.get_seconds() <= other\n elif isinstance(other, str):\n return self.frame_num <= self._parse_timecode_string(other)\n elif isinstance(other, FrameTimecode):\n if self.equal_framerate(other.framerate):\n return self.frame_num <= other.frame_num\n else:\n raise TypeError(\n 'FrameTimecode objects must have the same framerate to be compared.')\n else:\n raise TypeError('Unsupported type for performing <= with FrameTimecode: %s' %\n type(other))\n\n def __gt__(self, other: Union[int, float, str, 'FrameTimecode']) -> bool:\n if isinstance(other, int):\n return self.frame_num > other\n elif isinstance(other, float):\n return self.get_seconds() > other\n elif isinstance(other, str):\n return self.frame_num > self._parse_timecode_string(other)\n elif isinstance(other, FrameTimecode):\n if self.equal_framerate(other.framerate):\n return self.frame_num > other.frame_num\n else:\n raise TypeError(\n 'FrameTimecode objects must have the same framerate to be compared.')\n else:\n raise TypeError('Unsupported type for performing > with FrameTimecode: %s' %\n type(other))\n\n def __ge__(self, other: Union[int, float, str, 'FrameTimecode']) -> bool:\n if isinstance(other, int):\n return self.frame_num >= other\n elif isinstance(other, float):\n return self.get_seconds() >= other\n elif isinstance(other, str):\n return self.frame_num >= self._parse_timecode_string(other)\n elif isinstance(other, FrameTimecode):\n if self.equal_framerate(other.framerate):\n return self.frame_num >= other.frame_num\n else:\n raise TypeError(\n 'FrameTimecode objects must have the same framerate to be compared.')\n else:\n raise TypeError('Unsupported type for performing >= with FrameTimecode: %s' %\n type(other))\n\n # TODO(v1.0): __int__ and __float__ should be removed. Mark as deprecated, and indicate\n # need to use relevant property instead.\n\n def __int__(self) -> int:\n return self.frame_num\n\n def __float__(self) -> float:\n return self.get_seconds()\n\n def __str__(self) -> str:\n return self.get_timecode()\n\n def __repr__(self) -> str:\n return '%s [frame=%d, fps=%.3f]' % (self.get_timecode(), self.frame_num, self.framerate)\n\n def __hash__(self) -> int:\n return self.frame_num" }, { "identifier": "VideoStream", "path": "backend/scenedetect/video_stream.py", "snippet": "class VideoStream(ABC):\n \"\"\" Interface which all video backends must implement. \"\"\"\n\n #\n # Default Implementations\n #\n\n @property\n def base_timecode(self) -> FrameTimecode:\n \"\"\"FrameTimecode object to use as a time base.\"\"\"\n return FrameTimecode(timecode=0, fps=self.frame_rate)\n\n #\n # Abstract Static Methods\n #\n\n @staticmethod\n @abstractmethod\n def BACKEND_NAME() -> str:\n \"\"\"Unique name used to identify this backend. Should be a static property in derived\n classes (`BACKEND_NAME = 'backend_identifier'`).\"\"\"\n raise NotImplementedError\n\n #\n # Abstract Properties\n #\n\n @property\n @abstractmethod\n def path(self) -> Union[bytes, str]:\n \"\"\"Video or device path.\"\"\"\n raise NotImplementedError\n\n @property\n @abstractmethod\n def name(self) -> Union[bytes, str]:\n \"\"\"Name of the video, without extension, or device.\"\"\"\n raise NotImplementedError\n\n @property\n @abstractmethod\n def is_seekable(self) -> bool:\n \"\"\"True if seek() is allowed, False otherwise.\"\"\"\n raise NotImplementedError\n\n @property\n @abstractmethod\n def frame_rate(self) -> float:\n \"\"\"Frame rate in frames/sec.\"\"\"\n raise NotImplementedError\n\n @property\n @abstractmethod\n def duration(self) -> Optional[FrameTimecode]:\n \"\"\"Duration of the stream as a FrameTimecode, or None if non terminating.\"\"\"\n raise NotImplementedError\n\n @property\n @abstractmethod\n def frame_size(self) -> Tuple[int, int]:\n \"\"\"Size of each video frame in pixels as a tuple of (width, height).\"\"\"\n raise NotImplementedError\n\n @property\n @abstractmethod\n def aspect_ratio(self) -> float:\n \"\"\"Pixel aspect ratio as a float (1.0 represents square pixels).\"\"\"\n raise NotImplementedError\n\n @property\n @abstractmethod\n def position(self) -> FrameTimecode:\n \"\"\"Current position within stream as FrameTimecode.\n\n This can be interpreted as presentation time stamp, thus frame 1 corresponds\n to the presentation time 0. Returns 0 even if `frame_number` is 1.\"\"\"\n raise NotImplementedError\n\n @property\n @abstractmethod\n def position_ms(self) -> float:\n \"\"\"Current position within stream as a float of the presentation time in\n milliseconds. The first frame has a PTS of 0.\"\"\"\n raise NotImplementedError\n\n @property\n @abstractmethod\n def frame_number(self) -> int:\n \"\"\"Current position within stream as the frame number.\n\n Will return 0 until the first frame is `read`.\"\"\"\n raise NotImplementedError\n\n #\n # Abstract Methods\n #\n\n @abstractmethod\n def read(self, decode: bool = True, advance: bool = True) -> Union[ndarray, bool]:\n \"\"\"Read and decode the next frame as a numpy.ndarray. Returns False when video ends.\n\n Arguments:\n decode: Decode and return the frame.\n advance: Seek to the next frame. If False, will return the current (last) frame.\n\n Returns:\n If decode = True, the decoded frame (numpy.ndarray), or False (bool) if end of video.\n If decode = False, a bool indicating if advancing to the the next frame succeeded.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def reset(self) -> None:\n \"\"\" Close and re-open the VideoStream (equivalent to seeking back to beginning). \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def seek(self, target: Union[FrameTimecode, float, int]) -> None:\n \"\"\"Seek to the given timecode. If given as a frame number, represents the current seek\n pointer (e.g. if seeking to 0, the next frame decoded will be the first frame of the video).\n\n For 1-based indices (first frame is frame #1), the target frame number needs to be converted\n to 0-based by subtracting one. For example, if we want to seek to the first frame, we call\n seek(0) followed by read(). If we want to seek to the 5th frame, we call seek(4) followed\n by read(), at which point frame_number will be 5.\n\n May not be supported on all backend types or inputs (e.g. cameras).\n\n Arguments:\n target: Target position in video stream to seek to.\n If float, interpreted as time in seconds.\n If int, interpreted as frame number.\n Raises:\n SeekError: An error occurs while seeking, or seeking is not supported.\n ValueError: `target` is not a valid value (i.e. it is negative).\n \"\"\"\n raise NotImplementedError" }, { "identifier": "SceneDetector", "path": "backend/scenedetect/scene_detector.py", "snippet": "class SceneDetector:\n \"\"\" Base class to inherit from when implementing a scene detection algorithm.\n\n This API is not yet stable and subject to change.\n\n This represents a \"dense\" scene detector, which returns a list of frames where\n the next scene/shot begins in a video.\n\n Also see the implemented scene detectors in the scenedetect.detectors module\n to get an idea of how a particular detector can be created.\n \"\"\"\n # TODO(v0.7): Make this a proper abstract base class.\n\n stats_manager: Optional[StatsManager] = None\n \"\"\"Optional :class:`StatsManager <scenedetect.stats_manager.StatsManager>` to\n use for caching frame metrics to and from.\"\"\"\n\n # TODO(v1.0): Remove - this is a rarely used case for what is now a neglegible performance gain.\n def is_processing_required(self, frame_num: int) -> bool:\n \"\"\"[DEPRECATED] DO NOT USE\n\n Test if all calculations for a given frame are already done.\n\n Returns:\n False if the SceneDetector has assigned _metric_keys, and the\n stats_manager property is set to a valid StatsManager object containing\n the required frame metrics/calculations for the given frame - thus, not\n needing the frame to perform scene detection.\n\n True otherwise (i.e. the frame_img passed to process_frame is required\n to be passed to process_frame for the given frame_num).\n \"\"\"\n metric_keys = self.get_metrics()\n return not metric_keys or not (self.stats_manager is not None\n and self.stats_manager.metrics_exist(frame_num, metric_keys))\n\n def stats_manager_required(self) -> bool:\n \"\"\"Stats Manager Required: Prototype indicating if detector requires stats.\n\n Returns:\n True if a StatsManager is required for the detector, False otherwise.\n \"\"\"\n return False\n\n def get_metrics(self) -> List[str]:\n \"\"\"Get Metrics: Get a list of all metric names/keys used by the detector.\n\n Returns:\n List of strings of frame metric key names that will be used by\n the detector when a StatsManager is passed to process_frame.\n \"\"\"\n return []\n\n def process_frame(self, frame_num: int, frame_img: Optional[numpy.ndarray]) -> List[int]:\n \"\"\"Process Frame: Computes/stores metrics and detects any scene changes.\n\n Prototype method, no actual detection.\n\n Returns:\n List of frame numbers of cuts to be added to the cutting list.\n \"\"\"\n return []\n\n def post_process(self, frame_num: int) -> List[int]:\n \"\"\"Post Process: Performs any processing after the last frame has been read.\n\n Prototype method, no actual detection.\n\n Returns:\n List of frame numbers of cuts to be added to the cutting list.\n \"\"\"\n return []\n\n @property\n def event_buffer_length(self) -> int:\n \"\"\"The amount of frames a given event can be buffered for, in time. Represents maximum\n amount any event can be behind `frame_number` in the result of :meth:`process_frame`.\n \"\"\"\n return 0" }, { "identifier": "SparseSceneDetector", "path": "backend/scenedetect/scene_detector.py", "snippet": "class SparseSceneDetector(SceneDetector):\n \"\"\"Base class to inherit from when implementing a sparse scene detection algorithm.\n\n This class will be removed in v1.0 and should not be used.\n\n Unlike dense detectors, sparse detectors scene_detect \"events\" and return a *pair* of frames,\n as opposed to just a single cut.\n\n An example of a SparseSceneDetector is the MotionDetector.\n \"\"\"\n\n def process_frame(self, frame_num: int, frame_img: numpy.ndarray) -> List[Tuple[int, int]]:\n \"\"\"Process Frame: Computes/stores metrics and detects any scene changes.\n\n Prototype method, no actual detection.\n\n Returns:\n List of frame pairs representing individual scenes\n to be added to the output scene list directly.\n \"\"\"\n return []\n\n def post_process(self, frame_num: int) -> List[Tuple[int, int]]:\n \"\"\"Post Process: Performs any processing after the last frame has been read.\n\n Prototype method, no actual detection.\n\n Returns:\n List of frame pairs representing individual scenes\n to be added to the output scene list directly.\n \"\"\"\n return []" }, { "identifier": "StatsManager", "path": "backend/scenedetect/stats_manager.py", "snippet": "class StatsManager:\n \"\"\"Provides a key-value store for frame metrics/calculations which can be used\n for two-pass detection algorithms, as well as saving stats to a CSV file.\n\n Analyzing a statistics CSV file is also very useful for finding the optimal\n algorithm parameters for certain detection methods. Additionally, the data\n may be plotted by a graphing module (e.g. matplotlib) by obtaining the\n metric of interest for a series of frames by iteratively calling get_metrics(),\n after having called the detect_scenes(...) method on the SceneManager object\n which owns the given StatsManager instance.\n\n Only metrics consisting of `float` or `int` should be used currently.\n \"\"\"\n\n def __init__(self, base_timecode: FrameTimecode = None):\n \"\"\"Initialize a new StatsManager.\n\n Arguments:\n base_timecode: Timecode associated with this object. Must not be None (default value\n will be removed in a future release).\n \"\"\"\n # Frame metrics is a dict of frame (int): metric_dict (Dict[str, float])\n # of each frame metric key and the value it represents (usually float).\n self._frame_metrics: Dict[FrameTimecode, Dict[str, float]] = dict()\n self._registered_metrics: Set[str] = set() # Set of frame metric keys.\n self._loaded_metrics: Set[str] = set() # Metric keys loaded from stats file.\n self._metrics_updated: bool = False # Flag indicating if metrics require saving.\n self._base_timecode: Optional[FrameTimecode] = base_timecode # Used for timing calculations.\n\n def register_metrics(self, metric_keys: Iterable[str]) -> None:\n \"\"\"Register a list of metric keys that will be used by the detector.\n\n Used to ensure that multiple detector keys don't overlap.\n\n Raises:\n FrameMetricRegistered: A particular metric_key has already been registered/added\n to the StatsManager. Only if the StatsManager is being used for read-only\n access (i.e. all frames in the video have already been processed for the given\n metric_key in the exception) is this behavior desirable.\n \"\"\"\n for metric_key in metric_keys:\n if metric_key not in self._registered_metrics:\n self._registered_metrics.add(metric_key)\n else:\n raise FrameMetricRegistered(metric_key)\n\n # TODO(v1.0): Change frame_number to a FrameTimecode now that it is just a hash and will\n # be required for VFR support.\n def get_metrics(self, frame_number: int, metric_keys: Iterable[str]) -> List[Any]:\n \"\"\"Return the requested statistics/metrics for a given frame.\n\n Arguments:\n frame_number (int): Frame number to retrieve metrics for.\n metric_keys (List[str]): A list of metric keys to look up.\n\n Returns:\n A list containing the requested frame metrics for the given frame number\n in the same order as the input list of metric keys. If a metric could\n not be found, None is returned for that particular metric.\n \"\"\"\n return [self._get_metric(frame_number, metric_key) for metric_key in metric_keys]\n\n def set_metrics(self, frame_number: int, metric_kv_dict: Dict[str, Any]) -> None:\n \"\"\" Set Metrics: Sets the provided statistics/metrics for a given frame.\n\n Arguments:\n frame_number: Frame number to retrieve metrics for.\n metric_kv_dict: A dict mapping metric keys to the\n respective integer/floating-point metric values to set.\n \"\"\"\n for metric_key in metric_kv_dict:\n self._set_metric(frame_number, metric_key, metric_kv_dict[metric_key])\n\n def metrics_exist(self, frame_number: int, metric_keys: Iterable[str]) -> bool:\n \"\"\" Metrics Exist: Checks if the given metrics/stats exist for the given frame.\n\n Returns:\n bool: True if the given metric keys exist for the frame, False otherwise.\n \"\"\"\n return all([self._metric_exists(frame_number, metric_key) for metric_key in metric_keys])\n\n def is_save_required(self) -> bool:\n \"\"\" Is Save Required: Checks if the stats have been updated since loading.\n\n Returns:\n bool: True if there are frame metrics/statistics not yet written to disk,\n False otherwise.\n \"\"\"\n return self._metrics_updated\n\n def save_to_csv(self,\n csv_file: Union[str, bytes, TextIO],\n base_timecode: Optional[FrameTimecode] = None,\n force_save=True) -> None:\n \"\"\" Save To CSV: Saves all frame metrics stored in the StatsManager to a CSV file.\n\n Arguments:\n csv_file: A file handle opened in write mode (e.g. open('...', 'w')) or a path as str.\n base_timecode: [DEPRECATED] DO NOT USE. For backwards compatibility.\n force_save: If True, writes metrics out even if an update is not required.\n\n Raises:\n OSError: If `path` cannot be opened or a write failure occurs.\n \"\"\"\n # TODO(v0.7): Replace with DeprecationWarning that `base_timecode` will be removed in v0.8.\n if base_timecode is not None:\n logger.error('base_timecode is deprecated.')\n\n # Ensure we need to write to the file, and that we have data to do so with.\n if not ((self.is_save_required() or force_save) and self._registered_metrics\n and self._frame_metrics):\n logger.info(\"No metrics to save.\")\n return\n\n assert self._base_timecode is not None\n\n # If we get a path instead of an open file handle, recursively call ourselves\n # again but with file handle instead of path.\n if isinstance(csv_file, (str, bytes)):\n with open(csv_file, 'w') as file:\n self.save_to_csv(csv_file=file, force_save=force_save)\n return\n\n csv_writer = csv.writer(csv_file, lineterminator='\\n')\n metric_keys = sorted(list(self._registered_metrics.union(self._loaded_metrics)))\n csv_writer.writerow([COLUMN_NAME_FRAME_NUMBER, COLUMN_NAME_TIMECODE] + metric_keys)\n frame_keys = sorted(self._frame_metrics.keys())\n logger.info(\"Writing %d frames to CSV...\", len(frame_keys))\n for frame_key in frame_keys:\n frame_timecode = self._base_timecode + frame_key\n csv_writer.writerow(\n [frame_timecode.get_frames() +\n 1, frame_timecode.get_timecode()] +\n [str(metric) for metric in self.get_metrics(frame_key, metric_keys)])\n\n @staticmethod\n def valid_header(row: List[str]) -> bool:\n \"\"\"Check that the given CSV row is a valid header for a statsfile.\n\n Arguments:\n row: A row decoded from the CSV reader.\n\n Returns:\n True if `row` is a valid statsfile header, False otherwise.\n \"\"\"\n if not row or not len(row) >= 2:\n return False\n if row[0] != COLUMN_NAME_FRAME_NUMBER or row[1] != COLUMN_NAME_TIMECODE:\n return False\n return True\n\n # TODO(v1.0): Remove.\n def load_from_csv(self, csv_file: Union[str, bytes, TextIO]) -> Optional[int]:\n \"\"\"[DEPRECATED] DO NOT USE\n\n Load all metrics stored in a CSV file into the StatsManager instance. Will be removed in a\n future release after becoming a no-op.\n\n Arguments:\n csv_file: A file handle opened in read mode (e.g. open('...', 'r')) or a path as str.\n\n Returns:\n int or None: Number of frames/rows read from the CSV file, or None if the\n input file was blank or could not be found.\n\n Raises:\n StatsFileCorrupt: Stats file is corrupt and can't be loaded, or wrong file\n was specified.\n \"\"\"\n # TODO: Make this an error, then make load_from_csv() a no-op, and finally, remove it.\n logger.warning(\"load_from_csv() is deprecated and will be removed in a future release.\")\n\n # If we get a path instead of an open file handle, check that it exists, and if so,\n # recursively call ourselves again but with file set instead of path.\n if isinstance(csv_file, (str, bytes)):\n if os.path.exists(csv_file):\n with open(csv_file, 'r') as file:\n return self.load_from_csv(csv_file=file)\n # Path doesn't exist.\n return None\n\n # If we get here, file is a valid file handle in read-only text mode.\n csv_reader = csv.reader(csv_file, lineterminator='\\n')\n num_cols = None\n num_metrics = None\n num_frames = None\n # First Row: Frame Num, Timecode, [metrics...]\n try:\n row = next(csv_reader)\n # Backwards compatibility for previous versions of statsfile\n # which included an additional header row.\n if not self.valid_header(row):\n row = next(csv_reader)\n except StopIteration:\n # If the file is blank or we couldn't decode anything, assume the file was empty.\n return None\n if not self.valid_header(row):\n raise StatsFileCorrupt()\n num_cols = len(row)\n num_metrics = num_cols - 2\n if not num_metrics > 0:\n raise StatsFileCorrupt('No metrics defined in CSV file.')\n self._loaded_metrics = row[2:]\n num_frames = 0\n for row in csv_reader:\n metric_dict = {}\n if not len(row) == num_cols:\n raise StatsFileCorrupt('Wrong number of columns detected in stats file row.')\n for i, metric_str in enumerate(row[2:]):\n if metric_str and metric_str != 'None':\n try:\n metric_dict[self._loaded_metrics[i]] = float(metric_str)\n except ValueError:\n raise StatsFileCorrupt('Corrupted value in stats file: %s' %\n metric_str) from ValueError\n frame_number = int(row[0])\n # Switch from 1-based to 0-based frame numbers.\n if frame_number > 0:\n frame_number -= 1\n self.set_metrics(frame_number, metric_dict)\n num_frames += 1\n logger.info('Loaded %d metrics for %d frames.', num_metrics, num_frames)\n self._metrics_updated = False\n return num_frames\n\n def _get_metric(self, frame_number: int, metric_key: str) -> Optional[Any]:\n if self._metric_exists(frame_number, metric_key):\n return self._frame_metrics[frame_number][metric_key]\n return None\n\n def _set_metric(self, frame_number: int, metric_key: str, metric_value: Any) -> None:\n self._metrics_updated = True\n if not frame_number in self._frame_metrics:\n self._frame_metrics[frame_number] = dict()\n self._frame_metrics[frame_number][metric_key] = metric_value\n\n def _metric_exists(self, frame_number: int, metric_key: str) -> bool:\n return (frame_number in self._frame_metrics\n and metric_key in self._frame_metrics[frame_number])" }, { "identifier": "FrameMetricRegistered", "path": "backend/scenedetect/stats_manager.py", "snippet": "class FrameMetricRegistered(Exception):\n \"\"\" Raised when attempting to register a frame metric key which has\n already been registered. \"\"\"\n\n def __init__(self,\n metric_key: str,\n message: str = \"Attempted to re-register frame metric key.\"):\n super().__init__(message)\n self.metric_key = metric_key" } ]
import csv import threading import queue import logging import math import sys import cv2 import numpy as np from enum import Enum from typing import Iterable, List, Tuple, Optional, Dict, Callable, Union, TextIO from backend.scenedetect._thirdparty.simpletable import (SimpleTableCell, SimpleTableImage, SimpleTableRow, SimpleTable, HTMLPage) from backend.scenedetect.platform import (tqdm, get_and_create_path, get_cv2_imwrite_params, Template) from backend.scenedetect.frame_timecode import FrameTimecode from backend.scenedetect.video_stream import VideoStream from backend.scenedetect.scene_detector import SceneDetector, SparseSceneDetector from backend.scenedetect.stats_manager import StatsManager, FrameMetricRegistered
14,447
def write_scene_list(output_csv_file: TextIO, scene_list: Iterable[Tuple[FrameTimecode, FrameTimecode]], include_cut_list: bool = True, cut_list: Optional[Iterable[FrameTimecode]] = None) -> None: """Writes the given list of scenes to an output file handle in CSV format. Arguments: output_csv_file: Handle to open file in write mode. scene_list: List of pairs of FrameTimecodes denoting each scene's start/end FrameTimecode. include_cut_list: Bool indicating if the first row should include the timecodes where each scene starts. Should be set to False if RFC 4180 compliant CSV output is required. cut_list: Optional list of FrameTimecode objects denoting the cut list (i.e. the frames in the video that need to be split to generate individual scenes). If not specified, the cut list is generated using the start times of each scene following the first one. """ csv_writer = csv.writer(output_csv_file, lineterminator='\n') # If required, output the cutting list as the first row (i.e. before the header row). if include_cut_list: csv_writer.writerow( ["Timecode List:"] + cut_list if cut_list else [start.get_timecode() for start, _ in scene_list[1:]]) csv_writer.writerow([ "Scene Number", "Start Frame", "Start Timecode", "Start Time (seconds)", "End Frame", "End Timecode", "End Time (seconds)", "Length (frames)", "Length (timecode)", "Length (seconds)" ]) for i, (start, end) in enumerate(scene_list): duration = end - start csv_writer.writerow([ '%d' % (i + 1), '%d' % (start.get_frames() + 1), start.get_timecode(), '%.3f' % start.get_seconds(), '%d' % end.get_frames(), end.get_timecode(), '%.3f' % end.get_seconds(), '%d' % duration.get_frames(), duration.get_timecode(), '%.3f' % duration.get_seconds() ]) def write_scene_list_html(output_html_filename, scene_list, cut_list=None, css=None, css_class='mytable', image_filenames=None, image_width=None, image_height=None): """Writes the given list of scenes to an output file handle in html format. Arguments: output_html_filename: filename of output html file scene_list: List of pairs of FrameTimecodes denoting each scene's start/end FrameTimecode. cut_list: Optional list of FrameTimecode objects denoting the cut list (i.e. the frames in the video that need to be split to generate individual scenes). If not passed, the start times of each scene (besides the 0th scene) is used instead. css: String containing all the css information for the resulting html page. css_class: String containing the named css class image_filenames: dict where key i contains a list with n elements (filenames of the n saved images from that scene) image_width: Optional desired width of images in table in pixels image_height: Optional desired height of images in table in pixels """ if not css: css = """ table.mytable { font-family: times; font-size:12px; color:#000000; border-width: 1px; border-color: #eeeeee; border-collapse: collapse; background-color: #ffffff; width=100%; max-width:550px; table-layout:fixed; } table.mytable th { border-width: 1px; padding: 8px; border-style: solid; border-color: #eeeeee; background-color: #e6eed6; color:#000000; } table.mytable td { border-width: 1px; padding: 8px; border-style: solid; border-color: #eeeeee; } #code { display:inline; font-family: courier; color: #3d9400; } #string { display:inline; font-weight: bold; } """ # Output Timecode list timecode_table = SimpleTable( [["Timecode List:"] + (cut_list if cut_list else [start.get_timecode() for start, _ in scene_list[1:]])], css_class=css_class) # Output list of scenes header_row = [ "Scene Number", "Start Frame", "Start Timecode", "Start Time (seconds)", "End Frame", "End Timecode", "End Time (seconds)", "Length (frames)", "Length (timecode)", "Length (seconds)" ] for i, (start, end) in enumerate(scene_list): duration = end - start
# -*- coding: utf-8 -*- # # PySceneDetect: Python-Based Video Scene Detector # ------------------------------------------------------------------- # [ Site: https://scenedetect.com ] # [ Docs: https://scenedetect.com/docs/ ] # [ Github: https://github.com/Breakthrough/PySceneDetect/ ] # # Copyright (C) 2014-2023 Brandon Castellano <http://www.bcastell.com>. # PySceneDetect is licensed under the BSD 3-Clause License; see the # included LICENSE file, or visit one of the above pages for details. # """``scenedetect.scene_manager`` Module This module implements :class:`SceneManager`, coordinates running a :mod:`SceneDetector <scenedetect.detectors>` over the frames of a video (:mod:`VideoStream <scenedetect.video_stream>`). Video decoding is done in a separate thread to improve performance. This module also contains other helper functions (e.g. :func:`save_images`) which can be used to process the resulting scene list. =============================================================== Usage =============================================================== The following example shows basic usage of a :class:`SceneManager`: .. code:: python from scenedetect import open_video, SceneManager, ContentDetector video = open_video(video_path) scene_manager = SceneManager() scene_manager.add_detector(ContentDetector()) # Detect all scenes in video from current position to end. scene_manager.detect_scenes(video) # `get_scene_list` returns a list of start/end timecode pairs # for each scene that was found. scenes = scene_manager.get_scene_list() An optional callback can also be invoked on each detected scene, for example: .. code:: python from scenedetect import open_video, SceneManager, ContentDetector # Callback to invoke on the first frame of every new scene detection. def on_new_scene(frame_img: numpy.ndarray, frame_num: int): print("New scene found at frame %d." % frame_num) video = open_video(test_video_file) scene_manager = SceneManager() scene_manager.add_detector(ContentDetector()) scene_manager.detect_scenes(video=video, callback=on_new_scene) To use a `SceneManager` with a webcam/device or existing `cv2.VideoCapture` device, use the :class:`VideoCaptureAdapter <scenedetect.backends.opencv.VideoCaptureAdapter>` instead of `open_video`. ======================================================================= Storing Per-Frame Statistics ======================================================================= `SceneManager` can use an optional :class:`StatsManager <scenedetect.stats_manager.StatsManager>` to save frame statistics to disk: .. code:: python from scenedetect import open_video, ContentDetector, SceneManager, StatsManager video = open_video(test_video_file) scene_manager = SceneManager(stats_manager=StatsManager()) scene_manager.add_detector(ContentDetector()) scene_manager.detect_scenes(video=video) scene_list = scene_manager.get_scene_list() print_scenes(scene_list=scene_list) # Save per-frame statistics to disk. scene_manager.stats_manager.save_to_csv(csv_file=STATS_FILE_PATH) The statsfile can be used to find a better threshold for certain inputs, or perform statistical analysis of the video. """ logger = logging.getLogger('pyscenedetect') # TODO: This value can and should be tuned for performance improvements as much as possible, # until accuracy falls, on a large enough dataset. This has yet to be done, but the current # value doesn't seem to have caused any issues at least. DEFAULT_MIN_WIDTH: int = 256 """The default minimum width a frame will be downscaled to when calculating a downscale factor.""" MAX_FRAME_QUEUE_LENGTH: int = 4 """Maximum number of decoded frames which can be buffered while waiting to be processed.""" PROGRESS_BAR_DESCRIPTION = 'Detected: %d | Progress' """Template to use for progress bar.""" class Interpolation(Enum): """Interpolation method used for image resizing. Based on constants defined in OpenCV.""" NEAREST = cv2.INTER_NEAREST """Nearest neighbor interpolation.""" LINEAR = cv2.INTER_LINEAR """Bilinear interpolation.""" CUBIC = cv2.INTER_CUBIC """Bicubic interpolation.""" AREA = cv2.INTER_AREA """Pixel area relation resampling. Provides moire'-free downscaling.""" LANCZOS4 = cv2.INTER_LANCZOS4 """Lanczos interpolation over 8x8 neighborhood.""" def compute_downscale_factor(frame_width: int, effective_width: int = DEFAULT_MIN_WIDTH) -> int: """Get the optimal default downscale factor based on a video's resolution (currently only the width in pixels is considered). The resulting effective width of the video will be between frame_width and 1.5 * frame_width pixels (e.g. if frame_width is 200, the range of effective widths will be between 200 and 300). Arguments: frame_width: Actual width of the video frame in pixels. effective_width: Desired minimum width in pixels. Returns: int: The default downscale factor to use to achieve at least the target effective_width. """ assert not (frame_width < 1 or effective_width < 1) if frame_width < effective_width: return 1 return frame_width // effective_width def get_scenes_from_cuts( cut_list: Iterable[FrameTimecode], start_pos: Union[int, FrameTimecode], end_pos: Union[int, FrameTimecode], base_timecode: Optional[FrameTimecode] = None, ) -> List[Tuple[FrameTimecode, FrameTimecode]]: """Returns a list of tuples of start/end FrameTimecodes for each scene based on a list of detected scene cuts/breaks. This function is called when using the :meth:`SceneManager.get_scene_list` method. The scene list is generated from a cutting list (:meth:`SceneManager.get_cut_list`), noting that each scene is contiguous, starting from the first to last frame of the input. If `cut_list` is empty, the resulting scene will span from `start_pos` to `end_pos`. Arguments: cut_list: List of FrameTimecode objects where scene cuts/breaks occur. base_timecode: The base_timecode of which all FrameTimecodes in the cut_list are based on. num_frames: The number of frames, or FrameTimecode representing duration, of the video that was processed (used to generate last scene's end time). start_frame: The start frame or FrameTimecode of the cut list. Used to generate the first scene's start time. base_timecode: [DEPRECATED] DO NOT USE. For backwards compatibility only. Returns: List of tuples in the form (start_time, end_time), where both start_time and end_time are FrameTimecode objects representing the exact time/frame where each scene occupies based on the input cut_list. """ # TODO(v0.7): Use the warnings module to turn this into a warning. if base_timecode is not None: logger.error('`base_timecode` argument is deprecated has no effect.') # Scene list, where scenes are tuples of (Start FrameTimecode, End FrameTimecode). scene_list = [] if not cut_list: scene_list.append((start_pos, end_pos)) return scene_list # Initialize last_cut to the first frame we processed,as it will be # the start timecode for the first scene in the list. last_cut = start_pos for cut in cut_list: scene_list.append((last_cut, cut)) last_cut = cut # Last scene is from last cut to end of video. scene_list.append((last_cut, end_pos)) return scene_list def write_scene_list(output_csv_file: TextIO, scene_list: Iterable[Tuple[FrameTimecode, FrameTimecode]], include_cut_list: bool = True, cut_list: Optional[Iterable[FrameTimecode]] = None) -> None: """Writes the given list of scenes to an output file handle in CSV format. Arguments: output_csv_file: Handle to open file in write mode. scene_list: List of pairs of FrameTimecodes denoting each scene's start/end FrameTimecode. include_cut_list: Bool indicating if the first row should include the timecodes where each scene starts. Should be set to False if RFC 4180 compliant CSV output is required. cut_list: Optional list of FrameTimecode objects denoting the cut list (i.e. the frames in the video that need to be split to generate individual scenes). If not specified, the cut list is generated using the start times of each scene following the first one. """ csv_writer = csv.writer(output_csv_file, lineterminator='\n') # If required, output the cutting list as the first row (i.e. before the header row). if include_cut_list: csv_writer.writerow( ["Timecode List:"] + cut_list if cut_list else [start.get_timecode() for start, _ in scene_list[1:]]) csv_writer.writerow([ "Scene Number", "Start Frame", "Start Timecode", "Start Time (seconds)", "End Frame", "End Timecode", "End Time (seconds)", "Length (frames)", "Length (timecode)", "Length (seconds)" ]) for i, (start, end) in enumerate(scene_list): duration = end - start csv_writer.writerow([ '%d' % (i + 1), '%d' % (start.get_frames() + 1), start.get_timecode(), '%.3f' % start.get_seconds(), '%d' % end.get_frames(), end.get_timecode(), '%.3f' % end.get_seconds(), '%d' % duration.get_frames(), duration.get_timecode(), '%.3f' % duration.get_seconds() ]) def write_scene_list_html(output_html_filename, scene_list, cut_list=None, css=None, css_class='mytable', image_filenames=None, image_width=None, image_height=None): """Writes the given list of scenes to an output file handle in html format. Arguments: output_html_filename: filename of output html file scene_list: List of pairs of FrameTimecodes denoting each scene's start/end FrameTimecode. cut_list: Optional list of FrameTimecode objects denoting the cut list (i.e. the frames in the video that need to be split to generate individual scenes). If not passed, the start times of each scene (besides the 0th scene) is used instead. css: String containing all the css information for the resulting html page. css_class: String containing the named css class image_filenames: dict where key i contains a list with n elements (filenames of the n saved images from that scene) image_width: Optional desired width of images in table in pixels image_height: Optional desired height of images in table in pixels """ if not css: css = """ table.mytable { font-family: times; font-size:12px; color:#000000; border-width: 1px; border-color: #eeeeee; border-collapse: collapse; background-color: #ffffff; width=100%; max-width:550px; table-layout:fixed; } table.mytable th { border-width: 1px; padding: 8px; border-style: solid; border-color: #eeeeee; background-color: #e6eed6; color:#000000; } table.mytable td { border-width: 1px; padding: 8px; border-style: solid; border-color: #eeeeee; } #code { display:inline; font-family: courier; color: #3d9400; } #string { display:inline; font-weight: bold; } """ # Output Timecode list timecode_table = SimpleTable( [["Timecode List:"] + (cut_list if cut_list else [start.get_timecode() for start, _ in scene_list[1:]])], css_class=css_class) # Output list of scenes header_row = [ "Scene Number", "Start Frame", "Start Timecode", "Start Time (seconds)", "End Frame", "End Timecode", "End Time (seconds)", "Length (frames)", "Length (timecode)", "Length (seconds)" ] for i, (start, end) in enumerate(scene_list): duration = end - start
row = SimpleTableRow([
2
2023-10-25 02:50:01+00:00
24k
EulerSearch/embedding_studio
plugins/default_fine_tuning_method.py
[ { "identifier": "settings", "path": "embedding_studio/core/config.py", "snippet": "class Settings(BaseSettings):\n API_V1_STR: str = \"/api/v1\"\n SECRET_KEY: str = secrets.token_urlsafe(32)\n ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8\n BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []\n FINETUNING_MONGO_HOST: str = os.getenv(\"FINETUNING_MONGO_HOST\", \"mongo\")\n FINETUNING_MONGO_PORT: int = os.getenv(\"FINETUNING_MONGO_PORT\", 27017)\n FINETUNING_MONGO_DB_NAME: str = os.getenv(\n \"FINETUNING_MONGO_DB_NAME\", \"embedding_studio\"\n )\n FINETUNING_MONGO_USERNAME: str = os.getenv(\n \"FINETUNING_MONGO_USERNAME\", \"root\"\n )\n FINETUNING_MONGO_PASSWORD: str = os.getenv(\n \"FINETUNING_MONGO_PASSWORD\", \"mongopassword\"\n )\n FINETUNING_MONGO_URL: str = (\n f\"mongodb://{FINETUNING_MONGO_USERNAME}:{FINETUNING_MONGO_PASSWORD}@\"\n f\"{FINETUNING_MONGO_HOST}:{FINETUNING_MONGO_PORT}\"\n )\n CLICKSTREAM_MONGO_HOST: str = os.getenv(\"CLICKSTREAM_MONGO_HOST\", \"mongo\")\n CLICKSTREAM_MONGO_PORT: int = os.getenv(\"CLICKSTREAM_MONGO_PORT\", 27017)\n CLICKSTREAM_MONGO_DB_NAME: str = os.getenv(\n \"CLICKSTREAM_MONGO_DB_NAME\", \"embedding_studio\"\n )\n CLICKSTREAM_MONGO_USERNAME: str = os.getenv(\n \"CLICKSTREAM_MONGO_USERNAME\", \"root\"\n )\n CLICKSTREAM_MONGO_PASSWORD: str = os.getenv(\n \"CLICKSTREAM_MONGO_PASSWORD\", \"mongopassword\"\n )\n CLICKSTREAM_MONGO_URL: str = (\n f\"mongodb://{CLICKSTREAM_MONGO_USERNAME}:{CLICKSTREAM_MONGO_PASSWORD}@\"\n f\"{CLICKSTREAM_MONGO_HOST}:{CLICKSTREAM_MONGO_PORT}\"\n )\n REDIS_HOST: str = os.getenv(\"REDIS_HOST\", \"localhost\")\n REDIS_PORT: int = os.getenv(\"REDIS_PORT\", 6379)\n REDIS_PASSWORD: str = os.getenv(\"REDIS_PASSWORD\", \"redispassword\")\n REDIS_URL: str = f\"redis://{REDIS_HOST}:{REDIS_PORT}/0\"\n MINIO_HOST: str = os.getenv(\"MINIO_HOST\", \"localhost\")\n MINIO_PORT: int = os.getenv(\"MINIO_PORT\", 9000)\n MINIO_ROOT_USER: str = os.getenv(\"MINIO_ROOT_USER\", \"root\")\n MINIO_ROOT_PASSWORD: str = os.getenv(\n \"MINIO_ROOT_PASSWORD\", \"miniopassword\"\n )\n MINIO_DEFAULT_BUCKETS: str = os.getenv(\n \"MINIO_DEFAULT_BUCKETS\", \"embeddingstudio\"\n )\n MINIO_ACCESS_KEY: str = os.getenv(\n \"MINIO_ACCESS_KEY\", \"mtGNiEvoTL6C0EXAMPLE\"\n )\n MINIO_SECRET_KEY: str = os.getenv(\n \"MINIO_SECRET_KEY\", \"HY5JserXAaWmphNyCpQPEXAMPLEKEYEXAMPLEKEY\"\n )\n MYSQL_HOST: str = os.getenv(\"MYSQL_HOST\", \"localhost\")\n MYSQL_PORT: int = os.getenv(\"MYSQL_PORT\", 3306)\n MYSQL_DATABASE: str = os.getenv(\"MYSQL_DATABASE\", \"mlflow\")\n MYSQL_USER: str = os.getenv(\"MYSQL_USER\", \"mlflow_user\")\n MYSQL_PASSWORD: str = os.getenv(\"MYSQL_PASSWORD\", \"Baxp3O5rUvpIxiD77BfZ\")\n MYSQL_ROOT_PASSWORD: str = os.getenv(\n \"MYSQL_ROOT_PASSWORD\", \"PrK5qmPTDsm2IYKvHVG8\"\n )\n MLFLOW_HOST: str = os.getenv(\"MLFLOW_HOST\", \"localhost\")\n MLFLOW_PORT: int = os.getenv(\"MLFLOW_PORT\", 5001)\n MLFLOW_TRACKING_URI: str = f\"http://{MLFLOW_HOST}:{MLFLOW_PORT}\"\n ES_PLUGINS_PATH: str = os.getenv(\"ES_PLUGINS_PATH\", \"plugins\")\n FINE_TUNING_WORKER_MAX_RETRIES: int = os.getenv(\n \"FINE_TUNING_WORKER_MAX_RETRIES\", 3\n )\n FINE_TUNING_WORKER_TIME_LIMIT: int = os.getenv(\n \"FINE_TUNING_WORKER_TIME_LIMIT\", 18000000\n )\n DEFAULT_MAX_ATTEMPTS: int = os.getenv(\"DEFAULT_MAX_ATTEMPTS\", 3)\n DEFAULT_WAIT_TIME_SECONDS: float = os.getenv(\n \"DEFAULT_WAIT_TIME_SECONDS\", 3.0\n )\n S3_READ_CREDENTIALS_ATTEMPTS: int = os.getenv(\n \"S3_READ_CREDENTIALS_ATTEMPTS\", DEFAULT_MAX_ATTEMPTS\n )\n S3_READ_WAIT_TIME_SECONDS: float = os.getenv(\n \"S3_READ_WAIT_TIME_SECONDS\", DEFAULT_WAIT_TIME_SECONDS\n )\n S3_DOWNLOAD_DATA_ATTEMPTS: int = os.getenv(\n \"S3_DOWNLOAD_DATA_ATTEMPTS\", DEFAULT_MAX_ATTEMPTS\n )\n S3_DOWNLOAD_DATA_WAIT_TIME_SECONDS: float = os.getenv(\n \"S3_DOWNLOAD_DATA_WAIT_TIME_SECONDS\", DEFAULT_WAIT_TIME_SECONDS\n )\n MLFLOW_LOG_METRIC_ATTEMPTS: int = os.getenv(\n \"MLFLOW_LOG_METRIC_ATTEMPTS\", DEFAULT_MAX_ATTEMPTS\n )\n MLFLOW_LOG_METRIC_WAIT_TIME_SECONDS: float = os.getenv(\n \"MLFLOW_LOG_METRIC_WAIT_TIME_SECONDS\", DEFAULT_WAIT_TIME_SECONDS\n )\n MLFLOW_LOG_PARAM_ATTEMPTS: int = os.getenv(\n \"MLFLOW_LOG_PARAM_ATTEMPTS\", DEFAULT_MAX_ATTEMPTS\n )\n MLFLOW_LOG_PARAM_WAIT_TIME_SECONDS: float = os.getenv(\n \"MLFLOW_LOG_PARAM_WAIT_TIME_SECONDS\", DEFAULT_WAIT_TIME_SECONDS\n )\n MLFLOW_LOG_MODEL_ATTEMPTS: int = os.getenv(\n \"MLFLOW_LOG_MODEL_ATTEMPTS\", DEFAULT_MAX_ATTEMPTS\n )\n MLFLOW_LOG_MODEL_WAIT_TIME_SECONDS: float = os.getenv(\n \"MLFLOW_LOG_MODEL_WAIT_TIME_SECONDS\", DEFAULT_WAIT_TIME_SECONDS\n )\n MLFLOW_LOAD_MODEL_ATTEMPTS: int = os.getenv(\n \"MLFLOW_LOAD_MODEL_ATTEMPTS\", DEFAULT_MAX_ATTEMPTS\n )\n MLFLOW_LOAD_MODEL_WAIT_TIME_SECONDS: float = os.getenv(\n \"MLFLOW_LOAD_MODEL_WAIT_TIME_SECONDS\", DEFAULT_WAIT_TIME_SECONDS\n )\n MLFLOW_DELETE_MODEL_ATTEMPTS: int = os.getenv(\n \"MLFLOW_DELETE_MODEL_ATTEMPTS\", DEFAULT_MAX_ATTEMPTS\n )\n MLFLOW_DELETE_MODEL_WAIT_TIME_SECONDS: float = os.getenv(\n \"MLFLOW_DELETE_MODEL_WAIT_TIME_SECONDS\", DEFAULT_WAIT_TIME_SECONDS\n )\n MLFLOW_SEARCH_RUNS_ATTEMPTS: int = os.getenv(\n \"MLFLOW_SEARCH_RUNS_ATTEMPTS\", DEFAULT_MAX_ATTEMPTS\n )\n MLFLOW_SEARCH_RUNS_WAIT_TIME_SECONDS: float = os.getenv(\n \"MLFLOW_SEARCH_RUNS_WAIT_TIME_SECONDS\", DEFAULT_WAIT_TIME_SECONDS\n )\n MLFLOW_END_RUN_ATTEMPTS: int = os.getenv(\n \"MLFLOW_END_RUN_ATTEMPTS\", DEFAULT_MAX_ATTEMPTS\n )\n MLFLOW_END_RUN_WAIT_TIME_SECONDS: float = os.getenv(\n \"MLFLOW_END_RUN_WAIT_TIME_SECONDS\", DEFAULT_WAIT_TIME_SECONDS\n )\n MLFLOW_GET_RUN_ATTEMPTS: int = os.getenv(\n \"MLFLOW_GET_RUN_ATTEMPTS\", DEFAULT_MAX_ATTEMPTS\n )\n MLFLOW_GET_RUN_WAIT_TIME_SECONDS: float = os.getenv(\n \"MLFLOW_GET_RUN_WAIT_TIME_SECONDS\", DEFAULT_WAIT_TIME_SECONDS\n )\n MLFLOW_SEARCH_EXPERIMENTS_ATTEMPTS: int = os.getenv(\n \"MLFLOW_SEARCH_EXPERIMENTS_ATTEMPTS\", DEFAULT_MAX_ATTEMPTS\n )\n MLFLOW_SEARCH_EXPERIMENTS_WAIT_TIME_SECONDS: float = os.getenv(\n \"MLFLOW_SEARCH_EXPERIMENTS_WAIT_TIME_SECONDS\",\n DEFAULT_WAIT_TIME_SECONDS,\n )\n MLFLOW_DELETE_EXPERIMENT_ATTEMPTS: int = os.getenv(\n \"MLFLOW_DELETE_EXPERIMENT_ATTEMPTS\", DEFAULT_MAX_ATTEMPTS\n )\n MLFLOW_DELETE_EXPERIMENT_WAIT_TIME_SECONDS: float = os.getenv(\n \"MLFLOW_DELETE_EXPERIMENT_WAIT_TIME_SECONDS\", DEFAULT_WAIT_TIME_SECONDS\n )\n MLFLOW_CREATE_EXPERIMENT_ATTEMPTS: int = os.getenv(\n \"MLFLOW_CREATE_EXPERIMENT_ATTEMPTS\", DEFAULT_MAX_ATTEMPTS\n )\n MLFLOW_CREATE_EXPERIMENT_WAIT_TIME_SECONDS: float = os.getenv(\n \"MLFLOW_CREATE_EXPERIMENT_WAIT_TIME_SECONDS\", DEFAULT_WAIT_TIME_SECONDS\n )\n MLFLOW_GET_EXPERIMENT_ATTEMPTS: int = os.getenv(\n \"MLFLOW_GET_EXPERIMENT_ATTEMPTS\", DEFAULT_MAX_ATTEMPTS\n )\n MLFLOW_GET_EXPERIMENT_WAIT_TIME_SECONDS: float = os.getenv(\n \"MLFLOW_GET_EXPERIMENT_WAIT_TIME_SECONDS\", DEFAULT_WAIT_TIME_SECONDS\n )\n CLICKSTREAM_TIME_MAX_DELTA_MINUS_SEC: int = os.getenv(\n \"CLICKSTREAM_TIME_MAX_DELTA_MINUS_SEC\", 12 * 60 * 60\n )\n CLICKSTREAM_TIME_MAX_DELTA_PLUS_SEC: int = os.getenv(\n \"CLICKSTREAM_TIME_MAX_DELTA_PLUS_SEC\", 5 * 60\n )" }, { "identifier": "FineTuningMethod", "path": "embedding_studio/core/plugin.py", "snippet": "class FineTuningMethod(ABC):\n \"\"\"Base class (plugin) for fine-tuning methods.\n\n All fine-tuning methods must inherit from this class.\n \"\"\"\n\n meta: PluginMeta\n\n @abstractmethod\n def upload_initial_model(self) -> None:\n \"\"\"Upload the initial model to the storage.\n\n Method that should be implemented by subclasses to upload the\n initial model to the storage.\n \"\"\"\n raise NotImplementedError(\n \"Subclasses must implement upload_initial_model\"\n )\n\n @abstractmethod\n def get_fine_tuning_builder(\n self, clickstream: List[SessionWithEvents]\n ) -> FineTuningBuilder:\n \"\"\"Return a FineTuningBuilder instance for the fine-tuning process.\n\n Method that should be implemented by subclasses to provide a\n FineTuningBuilder instance.\n\n :param clickstream: Collection of user feedback, used to enhance\n the model.\n :return: An instance of FineTuningBuilder used for\n launching the fine-tuning process.\n \"\"\"\n raise NotImplementedError(\n \"Subclasses must implement get_fine_tuning_builder\"\n )" }, { "identifier": "AWSS3ClickstreamParser", "path": "embedding_studio/embeddings/data/clickstream/parsers/s3_parser.py", "snippet": "class AWSS3ClickstreamParser(ClickstreamParser):\n def __init__(\n self, query_item_type: type, search_result_type: type, event_type: type\n ):\n super(AWSS3ClickstreamParser, self).__init__(\n query_item_type, search_result_type, S3FileMeta, event_type\n )" }, { "identifier": "DummyEventType", "path": "embedding_studio/embeddings/data/clickstream/search_event.py", "snippet": "class DummyEventType(EventType):\n importance: float\n\n @property\n def event_importance(self) -> float:\n return self.importance" }, { "identifier": "SearchResult", "path": "embedding_studio/embeddings/data/clickstream/search_event.py", "snippet": "class SearchResult(BaseModel):\n item: ItemMeta\n is_click: bool\n rank: Optional[float] = None\n event_type: Optional[EventType] = None\n timestamp: Optional[int] = None\n\n @validator(\"event_type\", pre=True, always=True)\n def validate_event_type(cls, value, values):\n if value is not None and not isinstance(value, EventType):\n raise ValueError(\"Invalid event_type instance\")\n return value\n\n class Config:\n arbitrary_types_allowed = True\n\n @classmethod\n def from_mongo(\n cls,\n result: SearchResultItem,\n event_ids: Set[str],\n item_type: type,\n event_type: type,\n ) -> \"SearchResult\":\n event_instance = DummyEventType(importance=1)\n\n return cls(\n item=item_type(**result.meta),\n is_click=result.object_id in event_ids,\n event_type=event_instance,\n timestamp=None,\n )\n\n @classmethod\n def from_dict(\n cls, data: dict, item_type: type, event_type: type\n ) -> \"SearchResult\":\n event_data: Optional[Dict] = data.get(\"event_type\")\n event_instance = None\n\n if event_data is not None:\n event_instance = event_type(**event_data)\n\n return cls(\n item=item_type(**data[\"item\"]),\n is_click=data[\"is_click\"],\n rank=data[\"rank\"],\n event_type=event_instance,\n timestamp=int(data.get(\"timestamp\")),\n )" }, { "identifier": "ClickstreamSessionsSplitter", "path": "embedding_studio/embeddings/data/clickstream/splitter.py", "snippet": "class ClickstreamSessionsSplitter:\n def __init__(\n self,\n test_size_ratio: float = 0.2,\n shuffle: bool = True,\n random_state: Optional[int] = None,\n ):\n \"\"\"Generate train / test clickstream sessions split.\n\n :param test_size_ratio: ratio of test split size (default: 0.2)\n :param shuffle: to shuffle or not paired clickstream sessions (default: True)\n :param random_state: random state to sklearn splitter (default: None)\n \"\"\"\n if (\n not isinstance(test_size_ratio, float)\n or test_size_ratio <= 0\n or test_size_ratio >= 1.0\n ):\n raise ValueError(\n f\"test_size_ration is a numeric value in range (0.0, 1.0)\"\n )\n\n if test_size_ratio >= 0.5:\n logger.warning(\n \"test_size_ration is larger than 0.5. It's unusual for ML to have test size > train size.\"\n )\n\n self._test_size_ratio = test_size_ratio\n\n if not isinstance(shuffle, bool):\n raise ValueError(\"shuffle should be boolean\")\n self._shuffle = shuffle\n self._random_state = random_state\n\n @property\n def shuffle(self) -> bool:\n return self._shuffle\n\n def split(self, sessions: List[ClickstreamSession]) -> DatasetDict:\n \"\"\"Split clickstream sessions.\n\n :param sessions: sessions to be split\n :return: train / test splits accordingly (PairedClickstreamDataset)\n \"\"\"\n # Get all IDs\n all_result_ids: Set[str] = set()\n for session in sessions:\n all_result_ids.update(session.results)\n\n if len(all_result_ids) == 0:\n raise ValueError(\"Sessions list is empty\")\n\n # Ensure a minimum number of unique result IDs in each set\n min_unique_test_sessions: int = int(\n self._test_size_ratio * len(sessions)\n )\n\n # Split the result IDs into train and test sets\n train_result_ids, test_result_ids = train_test_split(\n list(all_result_ids),\n test_size=self._test_size_ratio,\n random_state=self._random_state,\n )\n test_result_ids: Set[str] = set(test_result_ids)\n\n # Split sessions into train and test based on result IDs\n train_sessions: List[ClickstreamSession] = []\n test_sessions: List[ClickstreamSession] = []\n\n for session in sessions:\n if len(session.results) == 0:\n continue\n\n if (\n len(set(session.results) & test_result_ids)\n / len(session.results)\n <= 0.5\n ):\n # If less than 50% of result IDs intersect with the test set, add to the train set\n train_sessions.append(session)\n else:\n test_sessions.append(session)\n\n if len(test_sessions) < min_unique_test_sessions:\n logger.warning(\n f\"Clickstream sessions intersects highly, so they are not split well\"\n )\n random_train_session_indexess: List[int] = random.choices(\n list(range(len(train_sessions))),\n k=min_unique_test_sessions - len(test_sessions),\n )\n for i in reversed(sorted(random_train_session_indexess)):\n test_sessions.append(train_sessions.pop(i))\n\n if len(test_sessions) + len(train_sessions) < len(sessions):\n missed_sessions_count = len(sessions) - (\n len(test_sessions) + len(train_sessions)\n )\n logger.warning(\n f\"Clickstream sessions weren't split correctly, add {missed_sessions_count} more sessions to the train split.\"\n )\n\n for session in sessions:\n if (\n session not in train_sessions\n and session not in test_sessions\n ):\n train_sessions.append(session)\n\n return DatasetDict(\n {\n \"train\": PairedClickstreamDataset(\n train_sessions, self.shuffle\n ),\n \"test\": PairedClickstreamDataset(test_sessions, self.shuffle),\n }\n )" }, { "identifier": "TextQueryItem", "path": "embedding_studio/embeddings/data/clickstream/text_query_item.py", "snippet": "class TextQueryItem(QueryItem):\n text: str\n\n class Config:\n arbitrary_types_allowed = True" }, { "identifier": "TextQueryRetriever", "path": "embedding_studio/embeddings/data/clickstream/text_query_retriever.py", "snippet": "class TextQueryRetriever(QueryRetriever):\n def __call__(self, query: TextQueryItem) -> str:\n if not hasattr(query, \"text\"):\n raise ValueError(f\"Query object does not have text attribute\")\n return query.text" }, { "identifier": "AWSS3DataLoader", "path": "embedding_studio/embeddings/data/loaders/s3/s3_loader.py", "snippet": "class AWSS3DataLoader(DataLoader):\n def __init__(self, retry_config: Optional[RetryConfig] = None, **kwargs):\n \"\"\"Items loader from AWS S3.\n\n :param max_attempts: maximum number of attempts (default: 10)\n :param wait_time_seconds: time to wait between (default: 10)\n :param kwargs: dict data for AWSS3Credentials\n \"\"\"\n super(AWSS3DataLoader, self).__init__(**kwargs)\n self.retry_config = (\n retry_config\n if retry_config\n else AWSS3DataLoader._get_default_retry_config()\n )\n self.credentials = AWSS3Credentials(**kwargs)\n self.attempt_exception_types = [EndpointConnectionError]\n\n @staticmethod\n def _get_default_retry_config() -> RetryConfig:\n default_retry_params = RetryParams(\n max_attempts=settings.DEFAULT_MAX_ATTEMPTS,\n wait_time_seconds=settings.DEFAULT_WAIT_TIME_SECONDS,\n )\n\n config = RetryConfig(default_params=default_retry_params)\n config[\"credentials\"] = RetryParams(\n max_attempts=settings.S3_READ_CREDENTIALS_ATTEMPTS,\n wait_time_seconds=settings.S3_READ_WAIT_TIME_SECONDS,\n )\n config[\"download_data\"] = RetryParams(\n max_attempts=settings.S3_DOWNLOAD_DATA_ATTEMPTS,\n wait_time_seconds=settings.S3_DOWNLOAD_DATA_WAIT_TIME_SECONDS,\n )\n return config\n\n @retry_method(name=\"download_data\")\n def _read_from_s3(self, client, bucket: str, file: str) -> Image:\n return read_from_s3(client, bucket, file)\n\n @retry_method(name=\"credentials\")\n def _get_client(self, task_id: str):\n if (\n self.credentials.aws_access_key_id is None\n or self.credentials.aws_secret_access_key is None\n ) and not self.credentials.use_system_info:\n logger.warning(\n \"No specific AWS credentials, use Anonymous session\"\n )\n s3_client = boto3.client(\n \"s3\", config=Config(signature_version=UNSIGNED)\n )\n else:\n sts_client = boto3.client(\n \"sts\",\n aws_access_key_id=self.credentials.aws_access_key_id,\n aws_secret_access_key=self.credentials.aws_secret_access_key,\n )\n if self.credentials.external_id:\n assumed_role_object = sts_client.assume_role(\n RoleArn=self.credentials.role_arn,\n RoleSessionName=task_id,\n ExternalId=self.credentials.external_id,\n )\n else:\n assumed_role_object = sts_client.assume_role(\n RoleArn=self.credentials.role_arn,\n RoleSessionName=task_id,\n )\n credentials = assumed_role_object[\"Credentials\"]\n s3_client = boto3.client(\n \"s3\",\n aws_access_key_id=credentials[\"AccessKeyId\"],\n aws_secret_access_key=credentials[\"SecretAccessKey\"],\n aws_session_token=credentials[\"SessionToken\"],\n )\n return s3_client\n\n def _generate_dataset_from_s3(\n self, files: List[S3FileMeta]\n ) -> Iterable[Dict]:\n if len(files) == 0:\n logger.warning(\"Nothing to download\")\n else:\n logger.info(\"Connecting to aws s3...\")\n task_id: str = str(uuid.uuid4())\n try:\n s3_client = self._get_client(task_id)\n logger.info(\"Start downloading data from S3...\")\n bad_items_count = 0\n for val in files:\n image = None\n try:\n image: Image = read_from_s3(\n s3_client, val.bucket, val.file\n )\n except Exception as e:\n logger.exception(\n f\"Unable to download an item: {val.bucket}/{val.file} Exception: {str(e)}\"\n )\n\n if image is None:\n logger.error(\n f\"Unable to download {val.file} from {val.bucket}\"\n )\n bad_items_count += 1\n continue\n yield {\"item\": image, \"item_id\": val.id}\n\n if bad_items_count == len(files):\n raise FailedToLoadAnythingFromAWSS3()\n\n except Exception as err:\n logger.error(f\"Failed to load dataset from s3: {err}\")\n raise err\n\n def load(self, items_data: List[S3FileMeta]) -> Dataset:\n return Dataset.from_generator(\n lambda: self._generate_dataset_from_s3(items_data)\n )" }, { "identifier": "CLIPItemStorageProducer", "path": "embedding_studio/embeddings/data/storages/producers/clip.py", "snippet": "class CLIPItemStorageProducer(ItemStorageProducer):\n def __init__(\n self,\n field_normalizer: DatasetFieldsNormalizer,\n id_field_name: Optional[str] = None,\n ):\n super(CLIPItemStorageProducer, self).__init__(\n ImageItemsDatasetDictPreprocessor(field_normalizer, 224),\n id_field_name,\n )" }, { "identifier": "DatasetFieldsNormalizer", "path": "embedding_studio/embeddings/data/utils/fields_normalizer.py", "snippet": "class DatasetFieldsNormalizer:\n ID_FIELD_NAME = \"item_id\"\n ITEM_FIELD_NAME = \"item\"\n\n def __init__(self, item_field_name: str, id_field_name: str):\n \"\"\"Unify column names in DatasetDict, so it can be used in fine-tuning script.\n A dataset should have ID column, related to ID in clickstream.\n\n :param item_field_name: name of column with items.\n :param id_field_name: name of ID column\n \"\"\"\n if not id_field_name:\n raise ValueError(\"id_field_name should be non-empty string\")\n self.id_field_name = id_field_name\n\n if not item_field_name:\n raise ValueError(\"item_field_name should be non-empty string\")\n self.item_field_name = item_field_name\n\n def __call__(self, dataset: DatasetDict) -> DatasetDict:\n id_normalizer = (\n lambda id_value: str(id_value.item())\n if (\n isinstance(id_value, Tensor)\n or isinstance(id_value, FloatTensor)\n )\n else str(id_value)\n )\n for key in dataset.keys():\n if (\n DatasetFieldsNormalizer.ID_FIELD_NAME\n not in dataset.column_names[key]\n ):\n dataset = dataset.rename_column(\n self.id_field_name, DatasetFieldsNormalizer.ID_FIELD_NAME\n )\n else:\n logger.warning(\n f\"Dataset {key} split already has {DatasetFieldsNormalizer.ID_FIELD_NAME} field\"\n )\n\n if (\n DatasetFieldsNormalizer.ITEM_FIELD_NAME\n not in dataset.column_names[key]\n ):\n dataset = dataset.rename_column(\n self.item_field_name,\n DatasetFieldsNormalizer.ITEM_FIELD_NAME,\n )\n else:\n logger.warning(\n f\"Dataset {key} split already has {DatasetFieldsNormalizer.ITEM_FIELD_NAME} field\"\n )\n\n return dataset.map(\n lambda example: {\n DatasetFieldsNormalizer.ID_FIELD_NAME: id_normalizer(\n example[DatasetFieldsNormalizer.ID_FIELD_NAME]\n )\n }\n )" }, { "identifier": "CosineProbMarginRankingLoss", "path": "embedding_studio/embeddings/losses/prob_cosine_margin_ranking_loss.py", "snippet": "class CosineProbMarginRankingLoss(ProbMarginRankingLoss):\n def __init__(self, base_margin: Optional[float] = 1.0):\n \"\"\"Embeddings Fine-tuning Loss (modification of MarginRankingLoss)\n Use sigmoid instead of ReLU + results confidences to ignore noises and mistakes.\n Adapt to cosine similarity / distance\n\n :param base_margin: margin ranking loss margin (default: 1.0)\n \"\"\"\n super(CosineProbMarginRankingLoss, self).__init__(\n base_margin=base_margin\n )\n\n def __adjust(self, adjusted_diff: FloatTensor) -> FloatTensor:\n # The way any wrong difference more than 0.01 is worth to be penaltized\n # Sigmoid with this kind of input return prob > 0.1, for difference between\n # pos and more than 0.001. That's our expected behaviour.\n # TODO: implement calculation of magic numbers\n return -400 * adjusted_diff + 6" }, { "identifier": "TextToImageCLIPModel", "path": "embedding_studio/embeddings/models/text_to_image/clip.py", "snippet": "class TextToImageCLIPModel(EmbeddingsModelInterface):\n def __init__(self, clip_model: SentenceTransformer):\n \"\"\"Wrapper to SentenceTransformer CLIP model.\n Usage: model = TextToImageCLIPModel(SentenceTransformer('clip-ViT-B-32'))\n\n :param clip_model: clip model from SentenceTransformer package\n \"\"\"\n super(TextToImageCLIPModel, self).__init__(same_query_and_items=False)\n self.clip_model = clip_model\n self.text_model = torch.nn.Sequential(\n self.clip_model._modules[\"0\"]\n ._modules[\"model\"]\n ._modules[\"text_model\"],\n PassPoolerOutputLayer(),\n self.clip_model._modules[\"0\"]\n ._modules[\"model\"]\n ._modules[\"text_projection\"],\n )\n\n self.vision_model = torch.nn.Sequential(\n self.clip_model._modules[\"0\"]\n ._modules[\"model\"]\n ._modules[\"vision_model\"],\n PassPoolerOutputLayer(),\n self.clip_model._modules[\"0\"]\n ._modules[\"model\"]\n ._modules[\"visual_projection\"],\n )\n\n def get_query_model_params(self) -> Iterator[Parameter]:\n return self.text_model.parameters()\n\n def get_items_model_params(self) -> Iterator[Parameter]:\n return self.vision_model.parameters()\n\n def fix_query_model(self, num_fixed_layers: int):\n if (\n len(self.text_model._modules[\"0\"].encoder.layers)\n <= num_fixed_layers\n ):\n raise ValueError(\n f\"Number of fixed layers ({num_fixed_layers}) >= number \"\n f'of existing layers ({len(self.text_model._modules[\"0\"].encoder.layers)})'\n )\n\n self.text_model._modules[\"0\"].embeddings.requires_grad = False\n for i, attn in enumerate(self.text_model._modules[\"0\"].encoder.layers):\n if i < num_fixed_layers:\n self.text_model._modules[\"0\"].encoder.layers[\n i\n ].requires_grad = False\n\n def unfix_query_model(self):\n self.text_model._modules[\"0\"].embeddings.requires_grad = True\n for i, attn in enumerate(self.text_model._modules[\"0\"].encoder.layers):\n self.text_model._modules[\"0\"].encoder.layers[\n i\n ].requires_grad = True\n\n def fix_item_model(self, num_fixed_layers: int):\n if (\n len(self.vision_model._modules[\"0\"].encoder.layers)\n <= num_fixed_layers\n ):\n raise ValueError(\n f\"Number of fixed layers ({num_fixed_layers}) >= number \"\n f'of existing layers ({len(self.vision_model._modules[\"0\"].encoder.layers)})'\n )\n\n self.vision_model._modules[\"0\"].embeddings.requires_grad = False\n for i, attn in enumerate(\n self.vision_model._modules[\"0\"].encoder.layers\n ):\n if i < num_fixed_layers:\n self.vision_model._modules[\"0\"].encoder.layers[\n i\n ].requires_grad = False\n\n def unfix_item_model(self):\n self.vision_model._modules[\"0\"].embeddings.requires_grad = True\n for i, attn in enumerate(\n self.vision_model._modules[\"0\"].encoder.layers\n ):\n self.vision_model._modules[\"0\"].encoder.layers[\n i\n ].requires_grad = True\n\n def tokenize(self, query: str) -> List[Dict]:\n return self.clip_model.tokenize([query])\n\n def forward_query(self, query: str) -> FloatTensor:\n if len(query) == 0:\n logger.warning(\"Provided query is empty\")\n\n tokenized = self.tokenize(query)\n return self.text_model.forward(tokenized[\"input_ids\"].to(self.device))\n\n def forward_items(self, items: List[np.array]) -> FloatTensor:\n if len(items) == 0:\n raise ValueError(\"items list must not be empty\")\n\n return self.vision_model.forward(torch.stack(items).to(self.device))" }, { "identifier": "SessionWithEvents", "path": "embedding_studio/models/clickstream/sessions.py", "snippet": "class SessionWithEvents(RegisteredSession):\n events: List[SessionEvent]" }, { "identifier": "FineTuningBuilder", "path": "embedding_studio/models/plugin.py", "snippet": "class FineTuningBuilder:\n data_loader: DataLoader\n query_retriever: QueryRetriever\n clickstream_parser: ClickstreamParser\n clickstream_sessions_splitter: ClickstreamSessionsSplitter\n dataset_fields_normalizer: DatasetFieldsNormalizer\n item_storage_producer: ItemStorageProducer\n accumulators: List[MetricsAccumulator]\n experiments_manager: ExperimentsManager\n fine_tuning_settings: FineTuningSettings\n initial_params: Dict[str, List[Any]]\n ranking_data: RankingData\n initial_max_evals: int = 100" }, { "identifier": "PluginMeta", "path": "embedding_studio/models/plugin.py", "snippet": "class PluginMeta(BaseModel):\n name: str\n version: str = \"1.0.0\"\n description: Optional[str] = None" }, { "identifier": "prepare_data", "path": "embedding_studio/workers/fine_tuning/data/prepare_data.py", "snippet": "def prepare_data(\n clickstream_sessions: List[Union[Dict, SessionWithEvents]],\n parser: ClickstreamParser,\n clickstream_splitter: ClickstreamSessionsSplitter,\n query_retriever: QueryRetriever,\n loader: DataLoader,\n storage_producer: ItemStorageProducer,\n) -> RankingData:\n \"\"\"Prepare fine-tuning data.\n\n :param clickstream_sessions: clickstream sessions\n :param parser: how to parse a clickstream session\n :param clickstream_splitter: how to split clickstream sessions\n :param query_retriever: retrieve query item\n :param loader: load items data\n :param storage_producer: get train/test datasets\n :return: train / test clickstream sessiobs and dataset dict\n \"\"\"\n if len(clickstream_sessions) == 0:\n raise ValueError(\"Empty clickstream sessions list\")\n\n logger.info(\"Parse clickstream sessions data\")\n raw_clickstream_sessions: List[RawClickstreamSession] = [\n (\n parser.parse(session)\n if isinstance(session, dict)\n else parser.parse_from_mongo(session)\n )\n for session in clickstream_sessions\n ]\n\n clickstream_sessions: List[ClickstreamSession] = [\n r.get_session() for r in raw_clickstream_sessions\n ]\n\n logger.info(\"Setup query retriever\")\n query_retriever.setup(clickstream_sessions)\n\n logger.info(\"Split clickstream sessions into train / test\")\n clickstream_dataset = clickstream_splitter.split(clickstream_sessions)\n logger.info(\n f'Splitting is finished, train: {len(clickstream_dataset[\"train\"])} / test: {len(clickstream_dataset[\"test\"])}'\n )\n\n logger.info(\"Get list of files to be loaded\")\n files_to_load: Set[ItemMeta] = set()\n for session in raw_clickstream_sessions:\n files_to_load.update(set([r.item for r in session.results]))\n\n if len(files_to_load) == 0:\n raise ValueError(\"Empty clickstream sessions\")\n\n logger.info(\"Download files and prepare DataDict of ItemStorage values\")\n files_to_load: List[ItemMeta] = list(files_to_load)\n\n dataset: DatasetDict = storage_producer(\n loader.load(files_to_load), clickstream_dataset\n )\n\n return RankingData(clickstream_dataset, dataset)" }, { "identifier": "ExperimentsManager", "path": "embedding_studio/workers/fine_tuning/experiments/experiments_tracker.py", "snippet": "class ExperimentsManager:\n def __init__(\n self,\n tracking_uri: str,\n main_metric: str,\n accumulators: List[MetricsAccumulator],\n is_loss: bool = False,\n n_top_runs: int = 10,\n requirements: Optional[str] = None,\n retry_config: Optional[RetryConfig] = None,\n ):\n \"\"\"Wrapper over mlflow package to manage certain fine-tuning experiments.\n\n :param tracking_uri: url of MLFlow server\n :param main_metric: name of main metric that will be used to find best model\n :param accumulators: accumulators of metrics to be logged\n :param is_loss: is main metric loss (if True, then best quality is minimal) (default: False)\n :param n_top_runs: how many hyper params group consider to be used in following tuning steps (default: 10)\n :param requirements: extra requirements to be passed to mlflow.pytorch.log_model (default: None)\n :param retry_config: retry policy (default: None)\n \"\"\"\n if not isinstance(tracking_uri, str) or len(tracking_uri) == 0:\n raise ValueError(\n f\"MLFlow tracking URI value should be a not empty string\"\n )\n mlflow.set_tracking_uri(tracking_uri)\n self._tracking_uri = tracking_uri\n if self._tracking_uri.endswith(\"/\"):\n self._tracking_uri = self._tracking_uri[:-1]\n\n self.retry_config = (\n retry_config\n if retry_config\n else ExperimentsManager._get_default_retry_config()\n )\n self.attempt_exception_types = [RestException]\n\n if not isinstance(main_metric, str) or len(main_metric) == 0:\n raise ValueError(f\"main_metric value should be a not empty string\")\n self.main_metric = main_metric\n self._metric_field = f\"metrics.{self.main_metric}\"\n\n self._n_top_runs = n_top_runs\n self._is_loss = is_loss\n\n if len(accumulators) == 0:\n logger.warning(\n \"No accumulators were provided, there will be no metrics logged except loss\"\n )\n self._accumulators = accumulators\n\n self._requirements: List[str] = (\n _get_base_requirements() if requirements is None else requirements\n )\n\n self._iteration_experiment = None\n self._tuning_iteration = None\n self._tuning_iteration_id = None\n\n self._run = None\n self._run_params = None\n self._run_id = None\n\n def _check_artifact_exists(self, run_id, artifact_path):\n client = mlflow.MlflowClient()\n artifacts = client.list_artifacts(run_id, path=artifact_path)\n return any(artifact.path == artifact_path for artifact in artifacts)\n\n @staticmethod\n def _get_default_retry_config() -> RetryConfig:\n default_retry_params = RetryParams(\n max_attempts=settings.DEFAULT_MAX_ATTEMPTS,\n wait_time_seconds=settings.DEFAULT_WAIT_TIME_SECONDS,\n )\n\n config = RetryConfig(default_params=default_retry_params)\n config[\"log_metric\"] = RetryParams(\n max_attempts=settings.MLFLOW_LOG_METRIC_ATTEMPTS,\n wait_time_seconds=settings.MLFLOW_LOG_METRIC_WAIT_TIME_SECONDS,\n )\n config[\"log_param\"] = RetryParams(\n max_attempts=settings.MLFLOW_LOG_PARAM_ATTEMPTS,\n wait_time_seconds=settings.MLFLOW_LOG_PARAM_WAIT_TIME_SECONDS,\n )\n config[\"log_model\"] = RetryParams(\n max_attempts=settings.MLFLOW_LOG_MODEL_ATTEMPTS,\n wait_time_seconds=settings.MLFLOW_LOG_MODEL_WAIT_TIME_SECONDS,\n )\n config[\"load_model\"] = RetryParams(\n max_attempts=settings.MLFLOW_LOAD_MODEL_ATTEMPTS,\n wait_time_seconds=settings.MLFLOW_LOAD_MODEL_WAIT_TIME_SECONDS,\n )\n config[\"delete_model\"] = RetryParams(\n max_attempts=settings.MLFLOW_DELETE_MODEL_ATTEMPTS,\n wait_time_seconds=settings.MLFLOW_DELETE_MODEL_WAIT_TIME_SECONDS,\n )\n config[\"search_runs\"] = RetryParams(\n max_attempts=settings.MLFLOW_SEARCH_RUNS_ATTEMPTS,\n wait_time_seconds=settings.MLFLOW_SEARCH_RUNS_WAIT_TIME_SECONDS,\n )\n config[\"end_run\"] = RetryParams(\n max_attempts=settings.MLFLOW_END_RUN_ATTEMPTS,\n wait_time_seconds=settings.MLFLOW_END_RUN_WAIT_TIME_SECONDS,\n )\n config[\"get_run\"] = RetryParams(\n max_attempts=settings.MLFLOW_GET_RUN_ATTEMPTS,\n wait_time_seconds=settings.MLFLOW_GET_RUN_WAIT_TIME_SECONDS,\n )\n config[\"search_experiments\"] = RetryParams(\n max_attempts=settings.MLFLOW_SEARCH_EXPERIMENTS_ATTEMPTS,\n wait_time_seconds=settings.MLFLOW_SEARCH_EXPERIMENTS_WAIT_TIME_SECONDS,\n )\n config[\"delete_experiment\"] = RetryParams(\n max_attempts=settings.MLFLOW_DELETE_EXPERIMENT_ATTEMPTS,\n wait_time_seconds=settings.MLFLOW_DELETE_EXPERIMENT_WAIT_TIME_SECONDS,\n )\n config[\"create_experiment\"] = RetryParams(\n max_attempts=settings.MLFLOW_CREATE_EXPERIMENT_ATTEMPTS,\n wait_time_seconds=settings.MLFLOW_CREATE_EXPERIMENT_WAIT_TIME_SECONDS,\n )\n config[\"get_experiment\"] = RetryParams(\n max_attempts=settings.MLFLOW_GET_EXPERIMENT_ATTEMPTS,\n wait_time_seconds=settings.MLFLOW_GET_EXPERIMENT_WAIT_TIME_SECONDS,\n )\n\n return config\n\n @property\n def is_loss(self) -> bool:\n return self._is_loss\n\n def __del__(self):\n self.finish_run()\n self.finish_iteration()\n\n def is_retryable_error(self, e: Exception) -> bool:\n return False\n\n def _get_model_exists_filter(self) -> str:\n return \"metrics.model_uploaded = 1\"\n\n def _get_artifact_url(self, run_id: str, artifact_path: str) -> str:\n return (\n f\"{self._tracking_uri}/get-artifact?path=\"\n f'{urllib.parse.quote(artifact_path, safe=\"\")}&run_uuid={run_id}'\n )\n\n @retry_method(name=\"log_model\")\n def upload_initial_model(self, model: EmbeddingsModelInterface):\n \"\"\"Upload the very first, initial model to the mlflow server\n\n :param model: model to be uploaded\n \"\"\"\n self.finish_iteration()\n experiment_id = get_experiment_id_by_name(INITIAL_EXPERIMENT_NAME)\n if experiment_id is None:\n logger.info(\n f\"Can't find any active iteration with name: {INITIAL_EXPERIMENT_NAME}\"\n )\n try:\n logger.info(\"Create initial experiment\")\n mlflow.create_experiment(INITIAL_EXPERIMENT_NAME)\n except MlflowException as e:\n if \"Cannot set a deleted experiment\" in str(e):\n logger.error(\n f\"Creation of initial experiment is failed: experiment with the same name {INITIAL_EXPERIMENT_NAME} is deleted, but not archived\"\n )\n experiments = mlflow.search_experiments(\n view_type=mlflow.entities.ViewType.ALL\n )\n deleted_experiment_id = None\n\n for exp in experiments:\n if exp.name == INITIAL_EXPERIMENT_NAME:\n deleted_experiment_id = exp.experiment_id\n break\n\n logger.info(\n f\"Restore deleted experiment with the same name: {INITIAL_EXPERIMENT_NAME}\"\n )\n mlflow.tracking.MlflowClient().restore_experiment(\n deleted_experiment_id\n )\n logger.info(\n f\"Archive deleted experiment with the same name: {INITIAL_EXPERIMENT_NAME}\"\n )\n mlflow.tracking.MlflowClient().rename_experiment(\n deleted_experiment_id,\n INITIAL_EXPERIMENT_NAME + \"_archive\",\n )\n logger.info(\n f\"Delete archived experiment with the same name: {INITIAL_EXPERIMENT_NAME}\"\n )\n mlflow.delete_experiment(deleted_experiment_id)\n logger.info(f\"Create initial experiment\")\n mlflow.create_experiment(INITIAL_EXPERIMENT_NAME)\n else:\n raise e\n\n with mlflow.start_run(\n experiment_id=get_experiment_id_by_name(INITIAL_EXPERIMENT_NAME),\n run_name=INITIAL_RUN_NAME,\n ) as run:\n logger.info(\n f\"Upload initial model to {INITIAL_EXPERIMENT_NAME} / {INITIAL_RUN_NAME}\"\n )\n if self._check_artifact_exists(\n get_run_id_by_name(\n get_experiment_id_by_name(INITIAL_EXPERIMENT_NAME),\n INITIAL_RUN_NAME,\n ),\n \"model\",\n ):\n logger.info(\"Model is already uploaded\")\n return\n\n mlflow.pytorch.log_model(\n model, \"model\", pip_requirements=self._requirements\n )\n logger.info(\"Uploading is finished\")\n\n @retry_method(name=\"load_model\")\n def download_initial_model(self) -> EmbeddingsModelInterface:\n \"\"\"Download initial model.\n\n :return: initial embeddings model\n \"\"\"\n model_uri: str = f\"runs:/{get_run_id_by_name(get_experiment_id_by_name(INITIAL_EXPERIMENT_NAME), INITIAL_RUN_NAME)}/model\"\n logger.info(f\"Download the model from {model_uri}\")\n model = mlflow.pytorch.load_model(model_uri)\n logger.info(\"Downloading is finished\")\n return model\n\n @retry_method(name=\"search_runs\")\n def get_top_params(self) -> Optional[List[FineTuningParams]]:\n \"\"\"Get top N previous fine-tuning iteration best params\n\n :return: fine-tuning iteration params\n \"\"\"\n initial_id: Optional[str] = get_experiment_id_by_name(\n INITIAL_EXPERIMENT_NAME\n )\n last_session_id: Optional[str] = self.get_previous_iteration_id()\n if initial_id == last_session_id:\n logger.warning(\n \"Can't retrieve top params, no previous iteration in history\"\n )\n return None\n\n else:\n runs: pd.DataFrame = mlflow.search_runs(\n experiment_ids=[last_session_id],\n filter_string=self._get_model_exists_filter(),\n )\n runs = runs[runs.status == \"FINISHED\"] # and only finished ones\n if runs.shape[0] == 0:\n logger.warning(\n \"Can't retrieve top params, no previous iteration's finished runs with uploaded model in history\"\n )\n return None\n\n # Get the indices that would sort the DataFrame based on the specified parameter\n sorted_indices: np.ndarray = np.argsort(\n runs[self._metric_field].values\n )\n if not self.is_loss:\n sorted_indices = sorted_indices[\n ::-1\n ] # Use [::-1] to sort in descending order\n\n # Extract the top N rows based on the sorted indices\n top_n_rows: np.ndarray = runs.iloc[\n sorted_indices[: self._n_top_runs]\n ]\n\n # Define a mapping dictionary to remove the \"params.\" prefix\n column_mapping: Dict[str, str] = {\n col: col.replace(\"params.\", \"\") for col in top_n_rows.columns\n }\n\n # Rename the columns\n top_n_rows: np.ndarray = top_n_rows.rename(\n columns=column_mapping\n ).to_dict(orient=\"records\")\n\n return [FineTuningParams(**row) for row in top_n_rows]\n\n def _get_best_previous_run_id(self) -> Tuple[Optional[str], bool]:\n initial_id: Optional[str] = get_experiment_id_by_name(\n INITIAL_EXPERIMENT_NAME\n )\n last_session_id: Optional[str] = self.get_previous_iteration_id()\n if initial_id == last_session_id or last_session_id is None:\n return None, True\n else:\n run_id, _ = self._get_best_quality(last_session_id)\n return run_id, False\n\n def _get_best_current_run_id(self) -> Tuple[Optional[str], bool]:\n initial_id: Optional[str] = get_experiment_id_by_name(\n INITIAL_EXPERIMENT_NAME\n )\n if (\n initial_id == self._tuning_iteration_id\n or self._tuning_iteration_id is None\n ):\n return None, True\n else:\n run_id, _ = self._get_best_quality(self._tuning_iteration_id)\n return run_id, False\n\n @retry_method(name=\"load_model\")\n def get_last_model_url(self) -> Optional[str]:\n run_id, is_initial = self._get_best_previous_run_id()\n if is_initial:\n logger.warning(\n \"Can't get the best model URL, no previous iteration in history\"\n )\n return None\n else:\n if run_id is None:\n logger.warning(\n \"Can't get the best model URL, no previous iterations \"\n \"finished runs with uploaded model in history\"\n )\n return None\n path = MODEL_ARTIFACT_PATH\n return self._get_artifact_url(run_id, path)\n\n @retry_method(name=\"load_model\")\n def get_current_model_url(self) -> Optional[str]:\n run_id, is_initial = self._get_best_current_run_id()\n if is_initial:\n logger.warning(\n \"Can't get the best model URL, current run is initial\"\n )\n return None\n\n if run_id is None:\n logger.warning(\n \"Can't get the best model URL, no iterations \"\n \"finished runs with uploaded model in history\"\n )\n return None\n path = MODEL_ARTIFACT_PATH\n return self._get_artifact_url(run_id, path)\n\n @retry_method(name=\"load_model\")\n def get_last_model(self) -> EmbeddingsModelInterface:\n \"\"\"Get previous iteration best embedding model.\n\n :return: best embedding model\n \"\"\"\n run_id, is_initial = self._get_best_previous_run_id()\n if is_initial:\n logger.warning(\n \"Download initial model, no previous iteration in history\"\n )\n return self.download_initial_model()\n\n else:\n if run_id is None:\n logger.warning(\n \"Download initial model, no previous iteration's \"\n \"finished runs with uploaded model in history\"\n )\n return self.download_initial_model()\n else:\n model_uri: str = f\"runs:/{run_id}/model\"\n logger.info(f\"Download the model from {model_uri}\")\n model = mlflow.pytorch.load_model(model_uri)\n logger.info(\"Downloading is finished\")\n return model\n\n @retry_method(name=\"load_model\")\n def get_current_model(self) -> Optional[EmbeddingsModelInterface]:\n \"\"\"Get current iteration best embedding model.\n\n :return: best embedding model\n \"\"\"\n if self._tuning_iteration is None:\n logger.error(\"No current iteration, can't get any model\")\n return\n\n if self._tuning_iteration == INITIAL_EXPERIMENT_NAME:\n logger.info(\"Download initial model\")\n return self.download_initial_model()\n\n run_id, is_initial = self._get_best_current_run_id()\n model_uri: str = f\"runs:/{run_id}/model\"\n logger.info(f\"Download the model from {model_uri}\")\n model = mlflow.pytorch.load_model(model_uri)\n logger.info(\"Downloading is finished\")\n return model\n\n @retry_method(name=\"search_experiments\")\n def get_previous_iteration_id(self) -> Optional[str]:\n if (\n self._tuning_iteration == INITIAL_EXPERIMENT_NAME\n or self._tuning_iteration is None\n ):\n logger.warning(\n f\"Can't find previous iteration - no current iteration was setup\"\n )\n return None\n\n plugin_name = f\"{self._tuning_iteration.plugin_name}\"\n experiments: List[Experiment] = [\n e\n for e in mlflow.search_experiments()\n if (\n e.name.startswith(EXPERIMENT_PREFIX)\n and e.name.find(plugin_name) != -1\n and e.name != str(self._tuning_iteration)\n )\n ]\n if len(experiments) == 0:\n logger.warning(\"No iteration found\")\n return None\n else:\n return max(\n experiments, key=lambda exp: exp.creation_time\n ).experiment_id\n\n @retry_method(name=\"delete_experiment\")\n def delete_previous_iteration(self):\n experiment_id: Optional[str] = self.get_previous_iteration_id()\n\n logger.info(\"Delete models of previous iteration.\")\n runs = mlflow.search_runs(\n experiment_ids=[experiment_id],\n filter_string=self._get_model_exists_filter(),\n )\n runs = runs[runs.status == \"FINISHED\"]\n run_ids = runs[\"run_id\"].tolist()\n\n for run_id in run_ids:\n self.delete_model(run_id, experiment_id)\n\n if experiment_id is not None:\n logger.info(\n f\"Iteration with ID {experiment_id} is going to be deleted\"\n )\n mlflow.tracking.MlflowClient().rename_experiment(\n experiment_id, INITIAL_EXPERIMENT_NAME + \"_archive\"\n )\n mlflow.delete_experiment(experiment_id)\n else:\n logger.warning(\n \"Can't delete a previous iteration, no previous iteration in history\"\n )\n\n @retry_method(name=\"create_experiment\")\n def set_iteration(self, iteration: FineTuningIteration):\n \"\"\"Start a new fine-tuning session.\n\n :param iteration: fine-tuning iteration info\n \"\"\"\n if self._tuning_iteration == INITIAL_EXPERIMENT_NAME:\n self.finish_iteration()\n\n logger.info(\"Start a new fine-tuning iterations\")\n\n self._tuning_iteration = iteration\n self._tuning_iteration_id = get_experiment_id_by_name(str(iteration))\n if self._tuning_iteration_id is None:\n self._tuning_iteration_id = mlflow.create_experiment(\n str(iteration)\n )\n\n self._iteration_experiment = mlflow.set_experiment(\n experiment_id=self._tuning_iteration_id\n )\n\n @retry_method(name=\"start_run\")\n def set_run(self, params: FineTuningParams) -> bool:\n \"\"\"Start a new run with provided fine-tuning params\n\n :param params: provided fine-tuning params\n :return: True if it's a finished run (otherwise False)\n \"\"\"\n convert_value = (\n lambda value: \", \".join(map(str, value))\n if isinstance(value, list)\n else value\n )\n\n if self._tuning_iteration == INITIAL_EXPERIMENT_NAME:\n # TODO: implement exception\n raise ValueError(\"You can't start run for initial iteration\")\n\n if self._run is not None:\n self.finish_run()\n\n logger.info(\n f\"Start a new run for iteration {self._tuning_iteration_id} with params:\\n\\t{str(params)}\"\n )\n\n self._run_params = params\n run_name: str = self._run_params.id\n self._run_id = get_run_id_by_name(self._tuning_iteration_id, run_name)\n\n self._run = mlflow.start_run(\n self._run_id, self._tuning_iteration_id, run_name\n )\n if self._run_id is None:\n self._run_id = self._run.info.run_id\n for key, value in dict(self._tuning_iteration).items():\n mlflow.log_param(key, convert_value(value))\n\n for key, value in dict(self._run_params).items():\n mlflow.log_param(key, convert_value(value))\n\n mlflow.log_metric(\"model_uploaded\", 0)\n\n return False\n else:\n return self._run.info.status == \"FINISHED\"\n\n @retry_method(name=\"search_runs\")\n def model_is_uploaded(self) -> bool:\n runs: pd.DataFrame = mlflow.search_runs(\n experiment_ids=[self._tuning_iteration_id],\n filter_string=self._get_model_exists_filter(),\n )\n runs = runs[runs[\"run_id\"] == self._run_id]\n return runs.shape[0] > 0\n\n @retry_method(name=\"get_experiment\")\n def finish_iteration(self):\n logger.info(f\"Finish current iteration {self._tuning_iteration_id}\")\n self._tuning_iteration = INITIAL_EXPERIMENT_NAME\n self._tuning_iteration_id = get_experiment_id_by_name(\n INITIAL_EXPERIMENT_NAME\n )\n\n if self._tuning_iteration_id is None:\n self._iteration_experiment = mlflow.set_experiment(\n experiment_name=INITIAL_EXPERIMENT_NAME\n )\n self._tuning_iteration_id = (\n self._iteration_experiment.experiment_id\n )\n else:\n self._iteration_experiment = mlflow.set_experiment(\n experiment_id=self._tuning_iteration_id\n )\n\n logger.info(f\"Current iteration is finished\")\n\n @retry_method(name=\"end_run\")\n def finish_run(self):\n logger.info(\n f\"Finish current run {self._tuning_iteration_id} / {self._run_id}\"\n )\n for accumulator in self._accumulators:\n accumulator.clear()\n\n mlflow.end_run()\n\n # Set params to default None\n self._run = None\n self._run_params = None\n self._run_id = None\n\n logger.info(f\"Current run is finished\")\n\n @retry_method(name=\"log_param\")\n def _set_model_as_deleted(self, run_id: str, experiment_id: str):\n with mlflow.start_run(\n run_id=run_id, experiment_id=experiment_id\n ) as run:\n mlflow.log_metric(\"model_deleted\", 1)\n mlflow.log_metric(\"model_uploaded\", 0)\n\n @retry_method(name=\"delete_model\")\n def _delete_model(self, run_id: str, experiment_id: str) -> bool:\n logger.warning(\n f\"Unable to delete a model for run {run_id}, MLFlow has no such functionality, please implement on your own.\"\n )\n return False\n\n @retry_method(name=\"get_run\")\n def delete_model(self, run_id: str, experiment_id: Optional[str] = None):\n experiment_id = (\n self._tuning_iteration_id\n if experiment_id is None\n else experiment_id\n )\n if experiment_id is None:\n raise ValueError(\n f\"No iteration was initialized, unable to delete model.\"\n )\n\n if experiment_id == INITIAL_EXPERIMENT_NAME:\n raise ValueError(f\"Initial model can't be deleted.\")\n\n run_info = None\n try:\n run_info = mlflow.get_run(run_id=run_id)\n except RestException as e:\n if e.get_http_status_code() == 404:\n logger.exception(f\"Run with ID {run_id} doesn't exist.\")\n else:\n raise e\n\n if run_info is not None:\n runs: pd.DataFrame = mlflow.search_runs(\n filter_string=self._get_model_exists_filter()\n )\n runs = runs[runs[\"run_id\"] == run_id]\n if runs.shape[0] == 0:\n logger.warning(\n f\"Run {run_id} has no model being uploaded. Nothing to delete\"\n )\n\n else:\n deleted = None\n try:\n deleted = self._delete_model(run_id, experiment_id)\n except MaxAttemptsReachedException:\n pass\n\n if deleted:\n self._set_model_as_deleted(run_id, experiment_id)\n\n @retry_method(name=\"log_model\")\n def save_model(\n self, model: EmbeddingsModelInterface, best_only: bool = True\n ):\n \"\"\"Save fine-tuned embedding model\n\n :param model: model to be saved\n :param best_only: save only if it's the best (default: True)\n \"\"\"\n if self._tuning_iteration == INITIAL_EXPERIMENT_NAME:\n raise ValueError(\n f\"Can't save not initial model for {INITIAL_EXPERIMENT_NAME} experiment\"\n )\n\n if self._run_id is None:\n raise ValueError(\"There is no current Run\")\n\n logger.info(\n f\"Save model for {self._tuning_iteration_id} / {self._run_id}\"\n )\n if not best_only:\n mlflow.pytorch.log_model(\n model, \"model\", pip_requirements=self._requirements\n )\n mlflow.log_metric(\"model_uploaded\", 1)\n logger.info(\"Upload is finished\")\n else:\n current_quality = self.get_quality()\n best_run_id, best_quality = self.get_best_quality()\n\n if best_run_id is None or (\n current_quality <= best_quality\n if self.is_loss\n else current_quality >= best_quality\n ):\n mlflow.pytorch.log_model(\n model, \"model\", pip_requirements=self._requirements\n )\n mlflow.log_metric(\"model_uploaded\", 1)\n logger.info(\"Upload is finished\")\n\n if best_run_id is not None:\n self.delete_model(best_run_id)\n else:\n logger.info(\"Not the best run - ignore saving\")\n\n @retry_method(name=\"log_metric\")\n def save_metric(self, metric_value: MetricValue):\n \"\"\"Accumulate and save metric value\n\n :param metric_value: value to be logged\n \"\"\"\n for accumulator in self._accumulators:\n for name, value in accumulator.accumulate(metric_value):\n mlflow.log_metric(name, value)\n\n @retry_method(name=\"search_runs\")\n def get_quality(self) -> float:\n \"\"\"Current run quality value\n\n :return: quality value\n \"\"\"\n if self._tuning_iteration == INITIAL_EXPERIMENT_NAME:\n raise ValueError(\n f\"No metrics for {INITIAL_EXPERIMENT_NAME} experiment\"\n )\n\n if self._run_id is None:\n raise ValueError(\"There is no current Run\")\n\n runs: pd.DataFrame = mlflow.search_runs(\n experiment_ids=[self._tuning_iteration_id]\n )\n quality: np.ndarray = runs[runs.run_id == self._run_id][\n self._metric_field\n ]\n return float(quality) if quality.shape[0] == 1 else float(quality[0])\n\n @retry_method(name=\"search_runs\")\n def _get_best_quality(\n self, experiment_id: str\n ) -> Tuple[Optional[str], float]:\n runs: pd.DataFrame = mlflow.search_runs(\n experiment_ids=[experiment_id],\n filter_string=self._get_model_exists_filter(),\n )\n runs = runs[runs.status == \"FINISHED\"] # and not finished ones\n if runs.shape[0] == 0:\n logger.warning(\n \"No finished experiments found with model uploaded, except initial\"\n )\n return None, 0.0\n\n else:\n value: float = (\n runs[self._metric_field].min()\n if self.is_loss\n else runs[self._metric_field].max()\n )\n best: pd.DataFrame = runs[runs[self._metric_field] == value][\n [\"run_id\", self._metric_field]\n ]\n return list(best.itertuples(index=False, name=None))[0]\n\n def get_best_quality(self) -> Tuple[str, float]:\n \"\"\"Get current fine-tuning iteration best quality\n\n :return: run_id and best metric value\n \"\"\"\n if self._tuning_iteration == INITIAL_EXPERIMENT_NAME:\n raise ValueError(\n f\"No metrics for {INITIAL_EXPERIMENT_NAME} experiment\"\n )\n\n return self._get_best_quality(self._tuning_iteration_id)" }, { "identifier": "FineTuningSettings", "path": "embedding_studio/workers/fine_tuning/experiments/finetuning_settings.py", "snippet": "class FineTuningSettings(BaseModel):\n \"\"\"\n\n :param loss_func: loss object for a ranking task\n :param metric_calculators: list of trackable metrics calculators (default: None)\n by default only DistanceShift metric\n :param ranker: ranking function (query, items) -> ranks (defult: cosine similarity)\n :param is_similarity: is ranking function similarity like or distance (default: True)\n :param confidence_calculator: function to calculate results confidences (default: dummy_confidences)\n :param step_size: optimizer steps (default: 500)\n :param gamma: optimizers gamma (default: 0.9)\n :param num_epochs: num of training epochs (default: 10)\n :param batch_size: count of sessions in a batch (default: 1)\n :param test_each_n_sessions: frequency of validation, if value in range [0, 1] - used as ratio (default: -1)\n \"\"\"\n\n loss_func: RankingLossInterface\n metric_calculators: Optional[List[MetricCalculator]] = None\n ranker: Optional[\n Callable[[FloatTensor, FloatTensor], FloatTensor]\n ] = COSINE_SIMILARITY\n is_similarity: Optional[bool] = True\n confidence_calculator: Optional[Callable] = dummy_confidences\n step_size: Optional[int] = 500\n gamma: Optional[float] = 0.9\n num_epochs: Optional[int] = 10\n batch_size: Optional[int] = 1\n test_each_n_sessions: Optional[Union[float, int]] = -1\n\n class Config:\n arbitrary_types_allowed = True" }, { "identifier": "INITIAL_PARAMS", "path": "embedding_studio/workers/fine_tuning/experiments/initial_params/clip.py", "snippet": "INITIAL_PARAMS: Dict[str, List[Union[int, float]]] = {\n \"num_fixed_layers\": [5, 6, 7, 8],\n \"query_lr\": [1e-4, 5e-5, 1e-5, 5e-6, 1e-6, 5e-7],\n \"items_lr\": [1e-4, 5e-5, 1e-5, 5e-6, 1e-6, 5e-7],\n \"query_weight_decay\": [0.0, 1e-6, 1e-5, 1e-4],\n \"items_weight_decay\": [0.0, 1e-6, 1e-5, 1e-4],\n \"margin\": [0.01, 0.025, 0.05],\n}" }, { "identifier": "MetricsAccumulator", "path": "embedding_studio/workers/fine_tuning/experiments/metrics_accumulator.py", "snippet": "class MetricsAccumulator:\n def __init__(\n self,\n name: str,\n calc_mean: bool = False,\n calc_sliding: bool = False,\n calc_min: bool = False,\n calc_max: bool = False,\n window_size: int = 10,\n ):\n \"\"\"Accumulator of metric values + calculator of aggregations like mean, max, min, sliding_mean.\n\n :param name: metric name (metrics with other name will be ignored)\n :param calc_mean: should accumulator calculate mean value (default: False)\n :param calc_sliding: should accumulator calculate sliding mean value (default: False)\n :param calc_min: should accumulator calculate min value (default: False)\n :param calc_max: should accumulator calculate max value (default: False)\n :param window_size: size of sliding window (default: 10)\n \"\"\"\n if not isinstance(name, str) or len(name) == 0:\n raise ValueError(\"MetricsAccumulator's name should not be empty\")\n\n self._name = name\n\n if not isinstance(calc_mean, bool):\n raise ValueError(\"calc_mean value should be bool\")\n self._calc_mean = calc_mean\n\n if not isinstance(calc_sliding, bool):\n raise ValueError(\"calc_sliding value should be bool\")\n self._calc_sliding = calc_sliding\n\n if not isinstance(calc_min, bool):\n raise ValueError(\"calc_min value should be bool\")\n self._calc_min = calc_min\n\n if not isinstance(calc_max, bool):\n raise ValueError(\"calc_max value should be bool\")\n self._calc_max = calc_max\n\n if not isinstance(window_size, int) or window_size <= 1:\n raise ValueError(\n \"window_size value should be integer with value more than 1\"\n )\n\n self._window_size = window_size\n self._values = []\n\n @property\n def name(self) -> str:\n return self._name\n\n def clear(self):\n \"\"\"Clear accumulator\"\"\"\n self._values = []\n\n def accumulate(self, value: MetricValue) -> List[Tuple[str, float]]:\n \"\"\"Add metric value to an accumulator.\n\n :param value: metric to be accumulated\n :return: aggregations\n \"\"\"\n if self.name == value.name:\n self._values.append(value.value)\n\n return self.aggregate()\n\n return []\n\n def aggregate(self) -> List[Tuple[str, float]]:\n \"\"\"Aggregate accumulated metrics\n\n :return: metric aggregations (last, mean, sliding, min, max)\n \"\"\"\n aggregations: List[Tuple[str, float]] = []\n if len(self._values) > 0:\n aggregations.append((self.name, self._values[-1]))\n if self._calc_mean:\n aggregations.append(\n (f\"mean_{self.name}\", float(np.mean(self._values)))\n )\n\n if self._calc_sliding:\n slide_value = float(\n np.mean(self._values)\n if len(self._values) < self._window_size\n else np.mean(self._values[-self._window_size :])\n )\n aggregations.append((f\"sliding_{self.name}\", slide_value))\n\n if self._calc_min:\n aggregations.append((f\"min_{self.name}\", np.min(self._values)))\n\n if self._calc_max:\n aggregations.append((f\"max_{self.name}\", np.max(self._values)))\n\n return aggregations" } ]
from typing import List from sentence_transformers import SentenceTransformer from embedding_studio.core.config import settings from embedding_studio.core.plugin import FineTuningMethod from embedding_studio.embeddings.data.clickstream.parsers.s3_parser import ( AWSS3ClickstreamParser, ) from embedding_studio.embeddings.data.clickstream.search_event import ( DummyEventType, SearchResult, ) from embedding_studio.embeddings.data.clickstream.splitter import ( ClickstreamSessionsSplitter, ) from embedding_studio.embeddings.data.clickstream.text_query_item import ( TextQueryItem, ) from embedding_studio.embeddings.data.clickstream.text_query_retriever import ( TextQueryRetriever, ) from embedding_studio.embeddings.data.loaders.s3.s3_loader import ( AWSS3DataLoader, ) from embedding_studio.embeddings.data.storages.producers.clip import ( CLIPItemStorageProducer, ) from embedding_studio.embeddings.data.utils.fields_normalizer import ( DatasetFieldsNormalizer, ) from embedding_studio.embeddings.losses.prob_cosine_margin_ranking_loss import ( CosineProbMarginRankingLoss, ) from embedding_studio.embeddings.models.text_to_image.clip import ( TextToImageCLIPModel, ) from embedding_studio.models.clickstream.sessions import SessionWithEvents from embedding_studio.models.plugin import FineTuningBuilder, PluginMeta from embedding_studio.workers.fine_tuning.data.prepare_data import prepare_data from embedding_studio.workers.fine_tuning.experiments.experiments_tracker import ( ExperimentsManager, ) from embedding_studio.workers.fine_tuning.experiments.finetuning_settings import ( FineTuningSettings, ) from embedding_studio.workers.fine_tuning.experiments.initial_params.clip import ( INITIAL_PARAMS, ) from embedding_studio.workers.fine_tuning.experiments.metrics_accumulator import ( MetricsAccumulator, )
16,533
class DefaultFineTuningMethod(FineTuningMethod): meta = PluginMeta( name="Default Fine Tuning Method", version="0.0.1", description="A default fine-tuning plugin", ) def __init__(self): # uncomment and pass your credentials to use your own s3 bucket # creds = { # "role_arn": "arn:aws:iam::123456789012:role/some_data" # "aws_access_key_id": "TESTACCESSKEIDTEST11", # "aws_secret_access_key": "QWERTY1232qdsadfasfg5349BBdf30ekp23odk03", # } # self.data_loader = AWSS3DataLoader(**creds) # with empty creds, use anonymous session creds = { } self.data_loader = AWSS3DataLoader(**creds) self.retriever = TextQueryRetriever() self.parser = AWSS3ClickstreamParser(
class DefaultFineTuningMethod(FineTuningMethod): meta = PluginMeta( name="Default Fine Tuning Method", version="0.0.1", description="A default fine-tuning plugin", ) def __init__(self): # uncomment and pass your credentials to use your own s3 bucket # creds = { # "role_arn": "arn:aws:iam::123456789012:role/some_data" # "aws_access_key_id": "TESTACCESSKEIDTEST11", # "aws_secret_access_key": "QWERTY1232qdsadfasfg5349BBdf30ekp23odk03", # } # self.data_loader = AWSS3DataLoader(**creds) # with empty creds, use anonymous session creds = { } self.data_loader = AWSS3DataLoader(**creds) self.retriever = TextQueryRetriever() self.parser = AWSS3ClickstreamParser(
TextQueryItem, SearchResult, DummyEventType
6
2023-10-31 00:33:13+00:00
24k
nv-tlabs/vid2player3d
uhc/utils/convert_amass_isaac.py
[ { "identifier": "SMPL_BONE_ORDER_NAMES", "path": "uhc/smpllib/smpl_parser.py", "snippet": "SMPL_BONE_ORDER_NAMES = [\n \"Pelvis\",\n \"L_Hip\",\n \"R_Hip\",\n \"Torso\",\n \"L_Knee\",\n \"R_Knee\",\n \"Spine\",\n \"L_Ankle\",\n \"R_Ankle\",\n \"Chest\",\n \"L_Toe\",\n \"R_Toe\",\n \"Neck\",\n \"L_Thorax\",\n \"R_Thorax\",\n \"Head\",\n \"L_Shoulder\",\n \"R_Shoulder\",\n \"L_Elbow\",\n \"R_Elbow\",\n \"L_Wrist\",\n \"R_Wrist\",\n \"L_Hand\",\n \"R_Hand\",\n]" }, { "identifier": "Robot", "path": "uhc/smpllib/smpl_local_robot.py", "snippet": "class Robot:\n def __init__(self, cfg, data_dir=\"data/smpl\", model_xml_path=None, masterfoot=False, create_default_skeleton=False, clean_up=False):\n self.bodies = []\n self.weight = 0\n self.height = 0\n self.cfg = cfg\n if model_xml_path is not None:\n self.set_model_xml_path(model_xml_path)\n else:\n self.model_xml_path = None\n self.param_mapping = cfg.get(\"param_mapping\", \"clip\")\n self.smpl_model = cfg.get(\"model\", \"smpl\")\n self.mesh = cfg.get(\"mesh\", False)\n self.gender = cfg.get(\"gender\", \"neutral\")\n self.flatfoot = cfg.get(\"flatfoot\", True)\n self.rel_joint_lm = cfg.get(\n \"rel_joint_lm\", True\n ) # Rolling this out worldwide!!\n\n self.masterfoot = masterfoot\n self.param_specs = self.cfg.get(\"body_params\", {})\n self.hull_dict = {}\n self.beta = (\n torch.zeros((1, 10)).float()\n if self.smpl_model == \"smpl\"\n else torch.zeros((1, 16)).float()\n )\n\n if self.smpl_model == \"smpl\":\n self.smpl_parser_n = SMPL_Parser(model_path=data_dir, gender=\"neutral\", create_transl=False)\n self.smpl_parser_m = SMPL_Parser(model_path=data_dir, gender=\"male\", create_transl=False)\n self.smpl_parser_f = SMPL_Parser(model_path=data_dir, gender=\"female\", create_transl=False)\n elif self.smpl_model == \"smplh\":\n self.smpl_parser_n = SMPLH_Parser(\n model_path=data_dir,\n gender=\"neutral\",\n use_pca=False,\n create_transl=False,\n )\n self.smpl_parser_m = SMPLH_Parser(\n model_path=data_dir, gender=\"male\", use_pca=False, create_transl=False\n )\n self.smpl_parser_f = SMPLH_Parser(\n model_path=data_dir, gender=\"female\", use_pca=False, create_transl=False\n )\n elif self.smpl_model == \"smplx\":\n self.smpl_parser_n = SMPLX_Parser(\n model_path=data_dir,\n gender=\"neutral\",\n use_pca=False,\n create_transl=False,\n )\n self.smpl_parser_m = SMPLX_Parser(\n model_path=data_dir, gender=\"male\", use_pca=False, create_transl=False\n )\n self.smpl_parser_f = SMPLX_Parser(\n model_path=data_dir, gender=\"female\", use_pca=False, create_transl=False\n )\n\n if create_default_skeleton:\n self.load_from_skeleton()\n\n if clean_up:\n atexit.register(self.clean_up)\n\n def set_model_xml_path(self, model_xml_path):\n self.model_xml_path = model_xml_path\n self.model_dir = osp.dirname(model_xml_path)\n self.geom_dir = f'{self.model_dir}/mesh/{uuid.uuid4()}'\n os.makedirs(self.model_dir, exist_ok=True)\n\n def clean_up(self):\n if os.path.exists(self.model_xml_path):\n os.remove(self.model_xml_path)\n if osp.isdir(self.geom_dir):\n shutil.rmtree(self.geom_dir, ignore_errors=True)\n\n def get_joint_vertices(self, pose_aa, th_betas=None, th_trans=None, gender=[0]):\n if gender[0] == 0:\n smpl_parser = self.smpl_parser_n\n elif gender[0] == 1:\n smpl_parser = self.smpl_parser_m\n elif gender[0] == 2:\n smpl_parser = self.smpl_parser_f\n else:\n print(gender)\n raise Exception(\"Gender Not Supported!!\")\n vertices, joints = smpl_parser.get_joints_verts(\n pose=pose_aa, th_betas=th_betas, th_trans=th_trans\n )\n return vertices, joints\n\n def load_from_skeleton(\n self,\n betas=None,\n scale=None,\n v_template=None,\n gender=[0],\n objs_info=None,\n obj_pose=None,\n params=None,\n model_xml_path=None,\n ):\n if model_xml_path is not None:\n self.set_model_xml_path(model_xml_path)\n \n self.tree = None # xml tree\n\n if gender[0] == 0:\n self.smpl_parser = smpl_parser = self.smpl_parser_n\n elif gender[0] == 1:\n self.smpl_parser = smpl_parser = self.smpl_parser_m\n elif gender[0] == 2:\n self.smpl_parser = smpl_parser = self.smpl_parser_f\n else:\n print(gender)\n raise Exception(\"Gender Not Supported!!\")\n\n if betas is None and self.beta is None:\n betas = (\n torch.zeros((1, 10)).float()\n if self.smpl_model == \"smpl\"\n else torch.zeros((1, 16)).float()\n )\n else:\n if len(betas.shape) == 1:\n betas = betas[None, :]\n if params is None:\n self.beta = betas if not betas is None else self.beta\n else:\n # If params is not none, we need to set the beta first\n betas = self.map_params(betas)\n self.beta = torch.from_numpy(\n denormalize_range(\n betas.numpy().squeeze(),\n self.param_specs[\"beta\"][\"lb\"],\n self.param_specs[\"beta\"][\"ub\"],\n )[\n None,\n ]\n )\n if flags.debug:\n print(self.beta)\n\n ## Clear up beta for smpl and smplh\n if self.smpl_model == \"smpl\" and self.beta.shape[1] == 16:\n self.beta = self.beta[:, :10]\n # print(f\"Incorrect shape size for {self.model}!!!\")\n elif self.smpl_model == \"smplh\" and self.beta.shape[1] == 10:\n self.beta = torch.hstack([self.beta, torch.zeros((1, 6)).float()])\n # print(f\"Incorrect shape size for {self.model}!!!\")\n\n if self.mesh:\n rel_geom_dir = os.path.relpath(self.geom_dir, self.model_dir)\n self.skeleton = SkeletonMesh(self.geom_dir, rel_geom_dir)\n zero_pose = torch.zeros((1,72))\n (\n verts,\n joints,\n skin_weights,\n joint_names,\n joint_offsets,\n joint_parents,\n joint_axes,\n joint_dofs,\n joint_range,\n contype,\n conaffinity,\n ) = (smpl_parser.get_mesh_offsets(\n zero_pose=zero_pose, betas=self.beta, flatfoot=self.flatfoot, scale=scale)\n if self.smpl_model != \"smplx\" else\n smpl_parser.get_mesh_offsets(v_template=v_template))\n\n # if self.rel_joint_lm:\n # # if False:\n # joint_range[\"Head\"][0] = np.array([-np.pi / 2, np.pi / 2])\n # joint_range[\"Head\"][1] = np.array([-np.pi / 2, np.pi / 2])\n # joint_range[\"Head\"][2] = np.array([-np.pi / 3, np.pi / 3])\n\n # joint_range[\"Chest\"][0] = np.array([-np.pi / 3, np.pi / 3])\n # joint_range[\"Chest\"][1] = np.array([-np.pi / 3, np.pi / 3])\n # joint_range[\"Chest\"][2] = np.array([-np.pi / 3, np.pi / 3])\n\n # joint_range[\"Spine\"][0] = np.array([-np.pi / 3, np.pi / 3])\n # joint_range[\"Spine\"][1] = np.array([-np.pi / 3, np.pi / 3])\n # joint_range[\"Spine\"][2] = np.array([-np.pi / 3, np.pi / 3])\n\n # joint_range[\"Torso\"][0] = np.array([-np.pi / 3, np.pi / 3])\n # joint_range[\"Torso\"][1] = np.array([-np.pi / 2, np.pi / 2])\n # joint_range[\"Torso\"][2] = np.array([-np.pi / 3, np.pi / 3])\n\n # ##############################\n\n # joint_range[\"L_Thorax\"][0] = np.array([-np.pi , np.pi ])\n # joint_range[\"L_Thorax\"][1] = np.array([-np.pi , np.pi])\n # joint_range[\"L_Thorax\"][2] = np.array([-np.pi, np.pi])\n\n # joint_range[\"R_Thorax\"][0] = np.array([-np.pi , np.pi ])\n # joint_range[\"R_Thorax\"][1] = np.array([-np.pi, np.pi])\n # joint_range[\"R_Thorax\"][2] = np.array([-np.pi, np.pi])\n\n\n # joint_range[\"L_Shoulder\"][0] = np.array([-np.pi , np.pi ])\n # joint_range[\"L_Shoulder\"][1] = np.array([-np.pi , np.pi / 2])\n # joint_range[\"L_Shoulder\"][2] = np.array([-np.pi, np.pi])\n\n # joint_range[\"R_Shoulder\"][0] = np.array([-np.pi , np.pi ])\n # joint_range[\"R_Shoulder\"][1] = np.array([-np.pi/2, np.pi])\n # joint_range[\"R_Shoulder\"][2] = np.array([-np.pi, np.pi])\n\n # ##############################\n\n # joint_range[\"L_Hip\"][0] = np.array([-np.pi / 2, np.pi / 2])\n # joint_range[\"L_Hip\"][1] = np.array([-np.pi / 3, np.pi / 3])\n # joint_range[\"L_Hip\"][2] = np.array([-np.pi / 3, np.pi /2])\n\n # joint_range[\"R_Hip\"][0] = np.array([-np.pi / 2, np.pi / 2])\n # joint_range[\"R_Hip\"][1] = np.array([-np.pi / 3, np.pi / 3])\n # joint_range[\"R_Hip\"][2] = np.array([-np.pi / 2, np.pi / 3])\n\n # joint_range[\"L_Knee\"][0] = np.array([-np.pi / 16, np.pi])\n # joint_range[\"L_Knee\"][1] = np.array([-np.pi / 16, np.pi / 16])\n # joint_range[\"L_Knee\"][2] = np.array([-np.pi / 16, np.pi / 16])\n\n # joint_range[\"R_Knee\"][0] = np.array([-np.pi / 16, np.pi])\n # joint_range[\"R_Knee\"][1] = np.array([-np.pi / 16, np.pi / 16])\n # joint_range[\"R_Knee\"][2] = np.array([-np.pi / 16, np.pi / 16])\n\n # joint_range[\"L_Ankle\"][0] = np.array([-np.pi / 2, np.pi / 2])\n # joint_range[\"L_Ankle\"][1] = np.array([-np.pi / 2, np.pi / 2])\n # joint_range[\"L_Ankle\"][2] = np.array([-np.pi / 2, np.pi / 2])\n\n # joint_range[\"R_Ankle\"][0] = np.array([-np.pi / 2, np.pi / 2])\n # joint_range[\"R_Ankle\"][1] = np.array([-np.pi / 2, np.pi / 2])\n # joint_range[\"R_Ankle\"][2] = np.array([-np.pi / 2, np.pi / 2])\n\n # joint_range[\"L_Toe\"][0] = np.array([-np.pi / 2, np.pi / 2])\n # joint_range[\"L_Toe\"][1] = np.array([-np.pi / 4, np.pi / 4])\n # joint_range[\"L_Toe\"][2] = np.array([-np.pi / 4, np.pi / 4])\n\n # joint_range[\"R_Toe\"][0] = np.array([-np.pi / 2, np.pi / 2])\n # joint_range[\"R_Toe\"][1] = np.array([-np.pi / 4, np.pi / 4])\n # joint_range[\"R_Toe\"][2] = np.array([-np.pi / 4, np.pi / 4])\n\n self.height = np.max(verts[:, 1]) - np.min(verts[:, 1])\n\n size_dict = {}\n\n if (\n len(self.get_params(get_name=True)) > 1 and not params is None\n ): # ZL: dank code, very dank code\n self.set_params(params)\n size_dict = self.get_size()\n size_dict = self.enforce_length_size(size_dict)\n\n # Gear based size\n # gear_dict = self.get_gear()\n # for k, v in size_dict.items():\n # for idx, suffix in enumerate([\"_x\", \"_y\", \"_z\"]):\n # if k + suffix in gear_dict:\n # size_dict[k][idx] *= gear_dict[k + suffix]\n \n self.hull_dict = get_joint_geometries(\n verts,\n joints,\n skin_weights,\n joint_names,\n scale_dict=size_dict,\n geom_dir=f\"{self.geom_dir}/geom\",\n )\n self.skeleton.load_from_offsets(\n joint_offsets,\n joint_parents,\n joint_axes,\n joint_dofs,\n joint_range,\n sites={},\n scale=1,\n equalities={},\n exclude_contacts = [\n [\"Chest\", \"L_Shoulder\"], [\"Chest\", \"R_Shoulder\"], [\"Chest\", \"R_Thorax\"], [\"Chest\", \"L_Thorax\"],\n ['L_Hip', 'Pelvis'],\n ['R_Hip', 'Pelvis'],\n ['Torso', 'Pelvis'],\n ['L_Knee', 'L_Hip'],\n ['R_Knee', 'R_Hip'],\n ['Spine', 'Torso'],\n ['L_Ankle', 'L_Knee'],\n ['R_Ankle', 'R_Knee'],\n ['Chest', 'Spine'],\n ['L_Toe', 'L_Ankle'],\n ['R_Toe', 'R_Ankle'],\n ['Neck', 'Chest'],\n ['L_Thorax', 'Chest'],\n ['R_Thorax', 'Chest'],\n ['Head', 'Neck'],\n ['L_Shoulder', 'L_Thorax'],\n ['R_Shoulder', 'R_Thorax'],\n ['L_Elbow', 'L_Shoulder'],\n ['R_Elbow', 'R_Shoulder'],\n ['L_Wrist', 'L_Elbow'],\n ['R_Wrist', 'R_Elbow'],\n ['L_Hand', 'L_Wrist'],\n ['R_Hand', 'R_Wrist']\n ],\n collision_groups=contype,\n conaffinity=conaffinity,\n simple_geom=False,\n )\n else:\n self.skeleton = Skeleton()\n joint_offsets, parents_dict, channels, joint_range = smpl_parser.get_offsets(betas=self.beta)\n\n channels = [\"x\", \"y\", \"z\"] # ZL: need to fix\n # if self.rel_joint_lm:\n # joint_range[\"L_Knee\"][2] = np.array([-np.pi / 16, np.pi / 16])\n # joint_range[\"L_Knee\"][1] = np.array([-np.pi / 16, np.pi / 16])\n # joint_range[\"L_Knee\"][0] = np.array([-np.pi / 16, np.pi])\n\n # joint_range[\"R_Knee\"][2] = np.array([-np.pi / 16, np.pi / 16])\n # joint_range[\"R_Knee\"][1] = np.array([-np.pi / 16, np.pi / 16])\n # joint_range[\"R_Knee\"][0] = np.array([-np.pi / 16, np.pi])\n\n # joint_range[\"L_Ankle\"][2] = np.array([-np.pi / 2, np.pi / 2])\n # joint_range[\"L_Ankle\"][1] = np.array([-np.pi / 2, np.pi / 2])\n # joint_range[\"L_Ankle\"][0] = np.array([-np.pi / 2, np.pi / 2])\n\n # joint_range[\"R_Ankle\"][2] = np.array([-np.pi / 2, np.pi / 2])\n # joint_range[\"R_Ankle\"][1] = np.array([-np.pi / 2, np.pi / 2])\n # joint_range[\"R_Ankle\"][0] = np.array([-np.pi / 2, np.pi / 2])\n\n # joint_range[\"L_Toe\"][2] = np.array([-np.pi / 4, np.pi / 4])\n # joint_range[\"L_Toe\"][1] = np.array([-np.pi / 4, np.pi / 4])\n # joint_range[\"L_Toe\"][0] = np.array([-np.pi / 2, np.pi / 2])\n\n # joint_range[\"R_Toe\"][2] = np.array([-np.pi / 4, np.pi / 4])\n # joint_range[\"R_Toe\"][1] = np.array([-np.pi / 4, np.pi / 4])\n # joint_range[\"R_Toe\"][0] = np.array([-np.pi / 2, np.pi / 2])\n\n self.skeleton.load_from_offsets(\n joint_offsets, parents_dict, 1, joint_range, {}, channels, {}\n )\n self.bodies = [] ### Cleaning bodies list\n self.bone_length = np.array([np.linalg.norm(i) for i in joint_offsets.values()])\n parser = XMLParser(remove_blank_text=True)\n\n self.tree = parse(\n BytesIO(\n # self.skeleton.write_str(\n # bump_buffer=self.smpl_model == \"smplh\" or self.smpl_model == \"smplx\"\n # )\n self.skeleton.write_str(bump_buffer=True)\n ),\n parser=parser,\n )\n\n self.local_coord = (\n self.tree.getroot().find(\".//compiler\").attrib[\"coordinate\"] == \"local\"\n )\n root = self.tree.getroot().find(\"worldbody\").find(\"body\")\n\n self.add_body(root, None)\n self.init_bodies()\n self.param_names = self.get_params(get_name=True)\n self.init_params = self.get_params()\n self.init_tree = deepcopy(self.tree)\n if self.masterfoot:\n self.add_masterfoot()\n\n\n all_root = self.tree.getroot()\n # contact_node = Element(\"contact\", {})\n\n # SubElement(contact_node,\"exclude\",{\"name\": \"add01\", \"body1\": \"L_Shoulr\", \"body2\": \"Chest\"},)\n # SubElement(contact_node,\"exclude\",{\"name\": \"add02\", \"body1\": \"R_Shoulder\", \"body2\": \"Chest\"},)\n # all_root.append(contact_node)\n return joints\n\n\n def in_body(self, body, point):\n return in_hull(self.hull_dict[body][\"norm_hull\"], point)\n\n def project_to_body(self, body, point):\n in_body = self.in_body(body, point)\n norm_points = self.hull_dict[body][\"norm_verts\"]\n if not in_body[0]:\n return norm_points[np.argmin(np.linalg.norm(norm_points - point, axis=1))]\n else:\n return point.squeeze()\n\n def get_gear(self):\n actuator_dict = {}\n for body in self.bodies:\n for joint in body.joints:\n if not joint.actuator is None:\n actuator_dict[joint.actuator.name] = joint.actuator.gear\n return actuator_dict\n\n def get_size(self):\n size_dict = {}\n for body in self.bodies:\n for geom in body.geoms:\n size_dict[body.name] = geom.size\n return size_dict\n\n def enforce_length_size(self, size_dict):\n distal_dir = {\n \"Pelvis\": 1,\n \"L_Hip\": 1,\n \"L_Knee\": 1,\n \"L_Ankle\": [1, 2],\n \"L_Toe\": [1, 2],\n \"R_Hip\": 1,\n \"R_Knee\": 1,\n \"R_Ankle\": [1, 2],\n \"R_Toe\": [1, 2],\n \"Torso\": 1,\n \"Spine\": 1,\n \"Chest\": 1,\n \"Neck\": 1,\n \"Head\": 1,\n \"L_Thorax\": 0,\n \"L_Shoulder\": 0,\n \"L_Elbow\": 0,\n \"L_Wrist\": 0,\n \"L_Hand\": 0,\n \"R_Thorax\": 0,\n \"R_Shoulder\": 0,\n \"R_Elbow\": 0,\n \"R_Wrist\": 0,\n \"R_Hand\": 0,\n }\n for k, v in size_dict.items():\n subset = np.array(v[distal_dir[k]])\n subset[subset <= 1] = 1\n v[distal_dir[k]] = subset\n\n return size_dict\n\n def add_body(self, body_node, parent_body):\n body = Body(body_node, parent_body, self, self.cfg, new_body=False)\n self.bodies.append(body)\n\n for body_node_c in body_node.findall(\"body\"):\n self.add_body(body_node_c, body)\n\n def init_bodies(self):\n for body in self.bodies:\n body.init()\n self.sync_node()\n\n def sync_node(self):\n for body in self.bodies:\n body.reindex()\n body.sync_node()\n\n def add_masterfoot(self):\n masterfoot_v = self.cfg.get(\"masterfoot_v\", 0)\n body_index = [3, 7]\n for idx in body_index:\n body2clone = body = self.bodies[idx]\n diff_mul = (\n np.linalg.norm(body.pos - body.child[0].pos) / 0.13432456960660616\n )\n\n template_pos = np.array(\n [\n [0, -0.15, 0],\n [-0.08, -0.15, 0.1],\n [0.08, -0.15, 0.1],\n [-0.1, -0.15, 0.2],\n [0.1, -0.15, 0.2],\n [-0.1, -0.15, 0.35],\n [0.1, -0.15, 0.35],\n [-0.1, -0.17, 0.6],\n [0.1, -0.17, 0.6],\n [0, -0.17, 0.6],\n [0.05, -0.17, 0.6],\n [-0.05, -0.17, 0.6],\n ]\n )\n\n template_pos[:, 2] -= 0.08 * diff_mul\n template_pos[:, 0] -= 0.05 * diff_mul if idx == 7 else -0.05 * diff_mul\n template_pos /= 3 / diff_mul\n template_pos += body.pos\n template_pos[:, 1] = np.min(self.hull_dict[body.name][\"verts\"][:, 1])\n\n for i in range(len(template_pos)):\n child_node = deepcopy(body2clone.node)\n actu_node = body.tree.getroot().find(\"actuator\")\n if len(body.child) > 0:\n # Recursively finding the last child to insert\n last_child = body.child[-1]\n # import ipdb; ipdb.set_trace()\n while len(last_child.child) > 0:\n last_child = last_child.child[-1]\n\n actu_insert_index = (\n actu_node.index(\n actu_node.find(\n f'motor[@joint=\"{last_child.joints[-1].name}\"]'\n )\n )\n + 1\n )\n else:\n actu_insert_index = (\n actu_node.index(\n actu_node.find(f'motor[@joint=\"{body.joints[-1].name}\"]')\n )\n + 1\n )\n\n for bnode in child_node.findall(\"body\"):\n child_node.remove(bnode)\n child_body = Body(\n child_node, body, self, self.cfg, new_body=True\n ) # This needs to called after finding the actu_insert_index\n pose_delta = np.array(template_pos[i])\n start = \" \".join(\n [\n f\"{x:.6f}\".rstrip(\"0\").rstrip(\".\")\n for x in np.array([pose_delta[0], pose_delta[1], pose_delta[2]])\n ]\n )\n\n attributes = {\n \"size\": \"0.035\",\n \"type\": \"capsule\",\n \"fromto\": f\"{start} {pose_delta[0] + 0.1} {pose_delta[1]} {pose_delta[2]}\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n for element in child_node.getiterator():\n if element.tag == \"geom\":\n child_node.remove(element)\n if element.tag == \"joint\":\n master_range = self.cfg.get(\"master_range\", 30)\n element.attrib[\"range\"] = f\"-{master_range} {master_range}\"\n\n geom_node = SubElement(child_node, \"geom\", attributes)\n child_body.geoms = [Geom(geom_node, child_body)]\n for joint in child_body.joints:\n new_actu_node = deepcopy(\n actu_node.find(f'motor[@joint=\"{joint.name}\"]')\n )\n\n actu_node.insert(actu_insert_index, new_actu_node)\n joint.actuator = Actuator(new_actu_node, joint)\n actu_insert_index += 1\n child_body.bone_offset = body.bone_offset.copy()\n child_body.param_specs = deepcopy(body.param_specs)\n child_body.param_inited = True\n child_body.rebuild()\n child_body.sync_node()\n body.node.append(child_node)\n self.bodies.append(child_body)\n self.sync_node()\n self.init_tree = deepcopy(self.tree)\n\n def add_child_to_body(self, body):\n if body == self.bodies[0]:\n body2clone = body.child[0]\n else:\n body2clone = body\n child_node = deepcopy(body2clone.node)\n\n actu_node = body.tree.getroot().find(\"actuator\")\n\n if len(body.child) > 0:\n # Recursively finding the last child to insert\n last_child = body.child[-1]\n while len(last_child.child) > 0:\n last_child = last_child.child[-1]\n\n actu_insert_index = (\n actu_node.index(\n actu_node.find(f'motor[@joint=\"{last_child.joints[-1].name}\"]')\n )\n + 1\n )\n else:\n actu_insert_index = (\n actu_node.index(\n actu_node.find(f'motor[@joint=\"{body.joints[-1].name}\"]')\n )\n + 1\n )\n\n for bnode in child_node.findall(\"body\"):\n child_node.remove(bnode)\n\n ######## Special case for the the foot, template geom ##############\n child_body = Body(\n child_node, body, self, self.cfg, new_body=True\n ) # This needs to called after finding the actu_insert_index\n\n start = \" \".join(\n [\n f\"{x:.6f}\".rstrip(\"0\").rstrip(\".\")\n for x in body.pos + np.array([0.0, -0.05, 0.05])\n ]\n )\n\n attributes = {\n \"size\": \"0.020 0.1000 0.0100\",\n \"type\": \"box\",\n \"pos\": start,\n \"quat\": \"0.7071 -0.7071 0.0000 0.0000\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n\n for element in child_node.getiterator():\n if element.tag == \"geom\":\n child_node.remove(element)\n\n geom_node = SubElement(child_node, \"geom\", attributes)\n child_body.geoms = [Geom(geom_node, child_body)]\n ######## Special case for the the foot, template geometry ##############\n\n for joint in child_body.joints:\n new_actu_node = deepcopy(actu_node.find(f'motor[@joint=\"{joint.name}\"]'))\n actu_node.insert(actu_insert_index, new_actu_node)\n joint.actuator = Actuator(new_actu_node, joint)\n actu_insert_index += 1\n child_body.bone_offset = body.bone_offset.copy()\n child_body.param_specs = deepcopy(body.param_specs)\n child_body.param_inited = True\n child_body.rebuild()\n child_body.sync_node()\n body.node.append(child_node)\n self.bodies.append(child_body)\n self.sync_node()\n\n def remove_body(self, body):\n body.node.getparent().remove(body.node)\n body.parent.child.remove(body)\n self.bodies.remove(body)\n actu_node = body.tree.getroot().find(\"actuator\")\n for joint in body.joints:\n actu_node.remove(joint.actuator.node)\n del body\n self.sync_node()\n\n def write_xml(self, fname=None):\n fname = self.model_xml_path if fname is None else fname\n self.tree.write(fname, pretty_print=True)\n\n def export_xml_string(self):\n return etree.tostring(self.tree, pretty_print=True)\n\n def export_vis_string(self, num=2, smpl_robot=None, fname=None, num_cones=0):\n tree = deepcopy(self.tree)\n if smpl_robot is None:\n vis_tree = deepcopy(self.init_tree)\n else:\n vis_tree = deepcopy(smpl_robot.tree)\n\n # Removing actuators from the tree\n remove_elements = [\"actuator\", \"contact\", \"equality\"]\n for elem in remove_elements:\n node = tree.getroot().find(elem)\n if node is None:\n # print(f\"has no elem: {elem}\")\n pass\n else:\n node.getparent().remove(node)\n\n option = tree.getroot().find(\"option\")\n flag = SubElement(option, \"flag\", {\"contact\": \"disable\"})\n option.addnext(Element(\"size\", {\"njmax\": \"1000\"}))\n\n worldbody = tree.getroot().find(\"worldbody\")\n asset = tree.getroot().find(\"asset\")\n vis_worldbody = vis_tree.getroot().find(\"worldbody\")\n\n geom_body = vis_worldbody.find(\"geom\")\n\n vis_meshes = vis_tree.getroot().find(\"asset\").findall(\"mesh\")\n\n for i in range(1, num):\n vis_meshes = deepcopy(vis_meshes)\n for mesh in vis_meshes:\n old_file = mesh.attrib[\"file\"]\n mesh.attrib[\"file\"] = mesh.attrib[\"file\"].replace(\".stl\", f\"_{i}.stl\")\n shutil.copy(old_file, mesh.attrib[\"file\"])\n asset.append(mesh)\n\n body = vis_worldbody.find(\"body\")\n for i in range(1, num):\n new_body = deepcopy(body)\n new_body.attrib[\"name\"] = \"%d_%s\" % (i, new_body.attrib[\"name\"])\n new_body.find(\"geom\").attrib[\"rgba\"] = \"0.7 0 0 1\"\n\n for node in new_body.findall(\".//body\"):\n node.attrib[\"name\"] = \"%d_%s\" % (i, node.attrib[\"name\"])\n node.find(\"geom\").attrib[\"rgba\"] = \"0.7 0 0 1\"\n for node in new_body.findall(\".//joint\"):\n node.attrib[\"name\"] = \"%d_%s\" % (i, node.attrib[\"name\"])\n for node in new_body.findall(\".//site\"):\n node.attrib[\"name\"] = \"%d_%s\" % (i, node.attrib[\"name\"])\n for node in new_body.findall(\".//geom\"):\n node.attrib[\"mesh\"] = \"%s_%d\" % (node.attrib[\"mesh\"], i)\n worldbody.append(new_body)\n\n for i in range(num_cones):\n body_node = Element(\"body\", {\"pos\": \"0 0 0\"})\n geom_node = SubElement(\n body_node,\n \"geom\",\n {\"mesh\": \"cone\", \"type\": \"mesh\", \"rgba\": \"0.0 0.8 1.0 1.0\"},\n )\n worldbody.append(body_node)\n for i in range(num_cones):\n worldbody.append(\n Element(\n \"geom\",\n {\n \"fromto\": \"0.0 0.0 0.0 0.0 1.0 0.0\",\n \"rgba\": \"0.0 0.8 1.0 1.0\",\n \"type\": \"cylinder\",\n \"size\": \"0.0420\",\n },\n )\n )\n if num_cones > 0:\n asset = tree.getroot().find(\"asset\")\n SubElement(\n asset,\n \"mesh\",\n {\n \"name\": \"cone\",\n \"file\": \"/hdd/zen/dev/copycat/Copycat/assets/mujoco_models/common/cone.stl\",\n \"scale\": \"0.025 0.025 0.04\",\n },\n )\n\n if fname is not None:\n print(\"Writing to file: %s\" % fname)\n tree.write(fname, pretty_print=True)\n vis_str = etree.tostring(tree, pretty_print=True)\n return vis_str\n\n def export_vis_string_self(self, num=3, smpl_robot=None, fname=None, num_cones=0):\n # colors = [\"0.8 0.6 .4 1\", \"0.7 0 0 1\", \"0.0 0.0 0.7 1\"] * num\n colors = [f\"{np.random.random():.3f} {np.random.random():.3f} {np.random.random():.3f} 1\" for _ in range(num)]\n # Export multiple vis strings\n tree = deepcopy(self.tree)\n if smpl_robot is None:\n vis_tree = deepcopy(self.init_tree)\n else:\n vis_tree = deepcopy(smpl_robot.tree)\n\n # Removing actuators from the tree\n remove_elements = [\"actuator\", \"contact\", \"equality\"]\n for elem in remove_elements:\n node = tree.getroot().find(elem)\n if node is None:\n # print(f\"has no elem: {elem}\")\n pass\n else:\n node.getparent().remove(node)\n\n option = tree.getroot().find(\"option\")\n flag = SubElement(option, \"flag\", {\"contact\": \"disable\"})\n option.addnext(Element(\"size\", {\"njmax\": \"1000\"}))\n\n worldbody = tree.getroot().find(\"worldbody\")\n asset = tree.getroot().find(\"asset\")\n vis_worldbody = vis_tree.getroot().find(\"worldbody\")\n\n geom_body = vis_worldbody.find(\"geom\")\n\n vis_meshes = vis_tree.getroot().find(\"asset\").findall(\"mesh\")\n for i in range(1, num):\n cur_meshes = deepcopy(vis_meshes)\n for mesh in cur_meshes:\n old_file = mesh.attrib[\"file\"]\n mesh.attrib[\"file\"] = mesh.attrib[\"file\"].replace(\".stl\", f\"_{i}.stl\")\n shutil.copy(old_file, mesh.attrib[\"file\"])\n asset.append(mesh)\n\n body = vis_worldbody.find(\"body\")\n for i in range(1, num):\n new_body = deepcopy(body)\n new_body.attrib[\"name\"] = \"%d_%s\" % (i, new_body.attrib[\"name\"])\n new_body.find(\"geom\").attrib[\"rgba\"] = colors[i]\n\n for node in new_body.findall(\".//body\"):\n node.attrib[\"name\"] = \"%d_%s\" % (i, node.attrib[\"name\"])\n node.find(\"geom\").attrib[\"rgba\"] = colors[i]\n for node in new_body.findall(\".//joint\"):\n node.attrib[\"name\"] = \"%d_%s\" % (i, node.attrib[\"name\"])\n for node in new_body.findall(\".//site\"):\n node.attrib[\"name\"] = \"%d_%s\" % (i, node.attrib[\"name\"])\n for node in new_body.findall(\".//geom\"):\n node.attrib[\"mesh\"] = \"%s_%d\" % (node.attrib[\"mesh\"], i)\n worldbody.append(new_body)\n\n if fname is not None:\n print(\"Writing to file: %s\" % fname)\n tree.write(fname, pretty_print=True)\n vis_str = etree.tostring(tree, pretty_print=True)\n return vis_str\n\n def demap_params(self, params):\n if not np.all((params <= 1.0) & (params >= -1.0)):\n print(f\"param out of bounds: {params}\")\n params = np.clip(params, -1.0, 1.0)\n if self.param_mapping == \"sin\":\n params = np.arcsin(params) / (0.5 * np.pi)\n return params\n\n def get_params(self, get_name=False):\n param_list = []\n if self.beta is not None and \"beta\" in self.param_specs:\n if get_name:\n param_list += [\"beta\"]\n else:\n beta = normalize_range(\n self.beta.numpy().squeeze(),\n self.param_specs[\"beta\"][\"lb\"],\n self.param_specs[\"beta\"][\"ub\"],\n )\n param_list.append(beta)\n\n for body in self.bodies:\n body.get_params(param_list, get_name)\n\n if not get_name and len(param_list) > 0:\n params = np.concatenate(param_list)\n params = self.demap_params(params)\n else:\n params = np.array(param_list)\n return params\n\n def map_params(self, params):\n if self.param_mapping == \"clip\":\n params = np.clip(params, -1.0, 1.0)\n elif self.param_mapping == \"sin\":\n params = np.sin(params * (0.5 * np.pi))\n return params\n\n def set_params(self, params):\n # clip params to range\n params = self.map_params(params)\n\n if \"beta\" in self.param_specs:\n self.beta = torch.from_numpy(\n denormalize_range(\n params[0:10],\n self.param_specs[\"beta\"][\"lb\"],\n self.param_specs[\"beta\"][\"ub\"],\n )[\n None,\n ]\n )\n params = params[10:]\n\n for body in self.bodies:\n params = body.set_params(params)\n assert len(params) == 0 # all parameters need to be consumed!\n\n self.sync_node()\n\n def rebuild(self):\n for body in self.bodies:\n body.rebuild()\n body.sync_node()\n\n def get_gnn_edges(self):\n edges = []\n for i, body in enumerate(self.bodies):\n if body.parent is not None:\n j = self.bodies.index(body.parent)\n edges.append([i, j])\n edges.append([j, i])\n edges = np.stack(edges, axis=1)\n return edges" }, { "identifier": "MotionLib", "path": "embodied_pose/utils/motion_lib.py", "snippet": "class MotionLib():\n def __init__(self, motion_file, dof_body_ids, dof_offsets,\n key_body_ids, device, clean_up=False):\n self._dof_body_ids = dof_body_ids\n self._dof_offsets = dof_offsets\n self._num_dof = dof_offsets[-1]\n self._key_body_ids = torch.tensor(key_body_ids, device=device)\n self._device = device\n self._load_motions(motion_file)\n\n motions = self._motions\n self.gts = torch.cat([m.global_translation for m in motions], dim=0).float()\n self.grs = torch.cat([m.global_rotation for m in motions], dim=0).float()\n self.lrs = torch.cat([m.local_rotation for m in motions], dim=0).float()\n self.grvs = torch.cat([m.global_root_velocity for m in motions], dim=0).float()\n self.gravs = torch.cat([m.global_root_angular_velocity for m in motions], dim=0).float()\n self.dvs = torch.cat([m.dof_vels for m in motions], dim=0).float()\n\n self.generate_length_starts()\n\n self.motion_ids = torch.arange(len(self._motions), dtype=torch.long, device=self._device)\n\n if clean_up:\n del self._motions\n del self._motion_aa\n\n return\n\n def generate_length_starts(self):\n lengths = self._motion_num_frames\n lengths_shifted = lengths.roll(1)\n lengths_shifted[0] = 0\n self.length_starts = lengths_shifted.cumsum(0)\n\n def merge_multiple_motion_libs(self, motion_lib_arr):\n keys = ['gts', 'grs', 'lrs', 'grvs', 'gravs', 'dvs', '_motion_weights',\n '_motion_lengths', '_motion_num_frames', '_motion_dt', '_motion_fps', '_motion_bodies', '_motion_body_idx', '_motion_body_scales', '_motion_min_verts_h', '_motion_seq_ids', '_motion_seq_names', '_motion_kp2d', '_motion_cam_proj']\n \n for key in keys:\n if key not in self.__dict__ or self.__dict__[key] is None:\n continue\n \n if key == '_motion_seq_names':\n for mlib in motion_lib_arr:\n self.__dict__[key].extend(mlib.__dict__[key])\n else:\n arr = [self.__dict__[key]] + [mlib.__dict__[key] for mlib in motion_lib_arr]\n self.__dict__[key] = torch.cat(arr, dim=0)\n \n self.generate_length_starts()\n self._motion_weights = self._motion_weights / sum(self._motion_weights)\n self.motion_ids = torch.arange(len(self._motion_lengths), dtype=torch.long, device=self._device)\n\n def num_motions(self):\n return len(self.motion_ids)\n\n def get_total_length(self):\n return sum(self._motion_lengths)\n\n def get_motion(self, motion_id):\n return self._motions[motion_id]\n\n def sample_motions(self, n, weights_from_lenth=True):\n if weights_from_lenth:\n motion_weights = self._motion_lengths / sum(self._motion_lengths)\n else:\n motion_weights = self._motion_weights\n motion_ids = torch.multinomial(motion_weights, num_samples=n, replacement=True)\n\n return motion_ids\n\n def sample_time(self, motion_ids, truncate_time=None, motion_time_range=None):\n n = len(motion_ids)\n phase = torch.rand(motion_ids.shape, device=self._device)\n \n motion_len = self._motion_lengths[motion_ids]\n if (truncate_time is not None):\n assert(truncate_time >= 0.0)\n motion_len = torch.clamp_min(motion_len - truncate_time, 0)\n \n if motion_time_range is not None:\n start, end = motion_time_range\n if start is None:\n start = 0\n start = torch.ones_like(motion_len) * start\n if end is None:\n end = motion_len\n else:\n end = torch.ones_like(motion_len) * end\n motion_time = start + (end - start) * phase\n else:\n motion_time = phase * motion_len\n return motion_time\n\n def get_motion_length(self, motion_ids):\n return self._motion_lengths[motion_ids]\n\n def get_motion_state(self, motion_ids, motion_times, return_rigid_body=False, return_body_shape=False, num_motion_cycles=0, motion_cycle_len=None, device=None, adjust_height=False, ground_tolerance=0.0, return_kp2d=False):\n\n motion_len = self._motion_lengths[motion_ids]\n num_frames = self._motion_num_frames[motion_ids]\n dt = self._motion_dt[motion_ids]\n\n frame_idx0, frame_idx1, blend = self._calc_frame_blend(motion_times, motion_len, num_frames, dt)\n\n f0l = frame_idx0 + self.length_starts[motion_ids]\n f1l = frame_idx1 + self.length_starts[motion_ids]\n\n root_pos0 = self.gts[f0l, 0]\n root_pos1 = self.gts[f1l, 0]\n\n root_rot0 = self.grs[f0l, 0]\n root_rot1 = self.grs[f1l, 0]\n\n local_rot0 = self.lrs[f0l]\n local_rot1 = self.lrs[f1l]\n\n root_vel = self.grvs[f0l]\n\n root_ang_vel = self.gravs[f0l]\n \n key_pos0 = self.gts[f0l.unsqueeze(-1), self._key_body_ids.unsqueeze(0)]\n key_pos1 = self.gts[f1l.unsqueeze(-1), self._key_body_ids.unsqueeze(0)]\n\n dof_vel = self.dvs[f0l]\n\n vals = [root_pos0, root_pos1, local_rot0, local_rot1, root_vel, root_ang_vel, key_pos0, key_pos1]\n for v in vals:\n assert v.dtype != torch.float64\n\n\n blend = blend.unsqueeze(-1)\n\n root_pos = (1.0 - blend) * root_pos0 + blend * root_pos1\n\n root_rot = torch_utils.slerp(root_rot0, root_rot1, blend)\n\n blend_exp = blend.unsqueeze(-1)\n key_pos = (1.0 - blend_exp) * key_pos0 + blend_exp * key_pos1\n \n local_rot = torch_utils.slerp(local_rot0, local_rot1, torch.unsqueeze(blend, axis=-1))\n dof_pos = self._local_rotation_to_dof(local_rot)\n\n if motion_cycle_len is not None:\n fr_start = self.length_starts[motion_ids]\n fr_end = fr_start + motion_cycle_len\n root_start_pos = self.gts[fr_start, 0]\n root_start_rot = self.grs[fr_start, 0]\n root_end_pos = self.gts[fr_end, 0]\n root_end_rot = self.grs[fr_end, 0]\n cycle_trans = root_end_pos - root_start_pos\n new_trans = cycle_trans * num_motion_cycles[:, None]\n new_trans[:, 2] = 0\n\n root_pos += new_trans\n key_pos += new_trans[:, None, :]\n\n if adjust_height:\n min_vh = self._motion_min_verts_h[motion_ids] - ground_tolerance\n root_pos[..., 2] -= min_vh\n key_pos[..., 2] -= min_vh[:, None]\n\n res = (root_pos, root_rot, dof_pos, root_vel, root_ang_vel, dof_vel, key_pos)\n \n if return_rigid_body:\n rb_pos0 = self.gts[f0l]\n rb_pos1 = self.gts[f1l]\n rb_pos = (1.0 - blend_exp) * rb_pos0 + blend_exp * rb_pos1\n\n rb_rot0 = self.grs[f0l]\n rb_rot1 = self.grs[f1l]\n rb_rot = torch_utils.slerp(rb_rot0, rb_rot1, blend_exp)\n\n if motion_cycle_len is not None:\n rb_pos += new_trans[:, None, :]\n\n if adjust_height:\n rb_pos[..., 2] -= min_vh[:, None]\n\n res += (rb_pos, rb_rot)\n\n if return_body_shape:\n res += (self._motion_bodies[motion_ids])\n\n if return_kp2d:\n blend_round = torch.round(blend_exp)\n kp2d0 = self._motion_kp2d[f0l]\n kp2d1 = self._motion_kp2d[f1l]\n kp2d = (1.0 - blend_round) * kp2d0 + blend_round * kp2d1\n \n cam_proj0 = self._motion_cam_proj[f0l]\n cam_proj1 = self._motion_cam_proj[f1l]\n cam_proj = (1.0 - blend_round) * cam_proj0 + blend_round * cam_proj1\n\n res += (kp2d, cam_proj)\n \n if device is not None and res[0].device != device:\n res = tuple([x.to(device) for x in res])\n\n return res\n\n def get_all_rb_pos(self, motion_ids, adjust_height=False, ground_tolerance=0.0):\n fr_start = self.length_starts[motion_ids]\n fr_end = fr_start + self._motion_num_frames[motion_ids]\n rb_pos = self.gts[fr_start:fr_end].clone()\n if adjust_height:\n min_vh = self._motion_min_verts_h[motion_ids] - ground_tolerance\n rb_pos[..., 2] -= min_vh\n return rb_pos\n\n def _load_motions(self, motion_file):\n self._motions = []\n self._motion_lengths = []\n self._motion_weights = []\n self._motion_fps = []\n self._motion_dt = []\n self._motion_num_frames = []\n self._motion_files = []\n self._motion_bodies = []\n self._motion_body_scales = []\n self._motion_body_idx = []\n self._motion_aa = []\n self._motion_kp2d = []\n self._motion_cam_proj = []\n self._motion_min_verts_h = []\n self._motion_seq_names = []\n self._motion_seq_ids = []\n\n total_len = 0.0\n\n motion_files, motion_weights = self._fetch_motion_files(motion_file)\n num_motion_files = len(motion_files)\n for f in range(num_motion_files):\n curr_file = motion_files[f]\n # normal string file name\n if (isinstance(curr_file, str)):\n print(\"Loading {:d}/{:d} motion files: {:s}\".format(f + 1, num_motion_files, curr_file))\n motion_file_data = np.load(curr_file, allow_pickle=True).item()\n curr_motion = SkeletonMotion.from_dict(motion_file_data)\n self._motion_aa.append(torch.zeros(72, device=self._device, dtype=torch.float32))\n self._motion_bodies.append(torch.zeros(17, device=self._device, dtype=torch.float32))\n self._motion_body_scales.append(1.0)\n self._motion_body_idx.append(0)\n self._motion_min_verts_h.append(0.0)\n self._motion_files.append(curr_file)\n # data dict\n elif (isinstance(curr_file, dict)):\n motion_file_data = curr_file\n curr_motion = SkeletonMotion.from_dict(curr_file)\n if \"beta\" in motion_file_data:\n beta, gender, pose_aa, min_verts_h = motion_file_data['beta'], motion_file_data['gender'], motion_file_data['pose_aa'], motion_file_data['min_verts_h']\n\n if isinstance(gender, bytes):\n gender = gender.decode(\"utf-8\")\n if gender == \"neutral\":\n gender = [0]\n elif gender == \"male\":\n gender = [1]\n elif gender == \"female\":\n gender = [2]\n else:\n raise Exception(\"Gender Not Supported!!\")\n self._motion_aa.append(torch.tensor(pose_aa, device=self._device, dtype=torch.float32))\n self._motion_bodies.append(torch.tensor(np.concatenate((gender, beta)), device=self._device, dtype=torch.float32))\n self._motion_body_scales.append(motion_file_data['body_scale'])\n self._motion_body_idx.append(motion_file_data['beta_idx'])\n self._motion_min_verts_h.append(min_verts_h)\n self._motion_seq_ids.append(motion_file_data['seq_idx'])\n self._motion_seq_names.append(motion_file_data['seq_name'])\n if 'kp2d' in motion_file_data:\n self._motion_kp2d.append(torch.tensor(motion_file_data['kp2d'], device=self._device, dtype=torch.float32))\n self._motion_cam_proj.append(torch.tensor(motion_file_data['cam_proj'], device=self._device, dtype=torch.float32))\n else:\n raise Exception(\"No beta in motion file!\")\n\n motion_fps = curr_motion.fps\n curr_dt = 1.0 / motion_fps\n\n num_frames = curr_motion.tensor.shape[0]\n curr_len = 1.0 / motion_fps * (num_frames - 1)\n\n self._motion_fps.append(motion_fps)\n self._motion_dt.append(curr_dt)\n self._motion_num_frames.append(num_frames)\n \n curr_dof_vels = self._compute_motion_dof_vels(curr_motion)\n curr_motion.dof_vels = curr_dof_vels\n\n # Moving motion tensors to the GPU\n if USE_CACHE:\n curr_motion = DeviceCache(curr_motion, self._device) \n else:\n curr_motion.tensor = curr_motion.tensor.to(self._device)\n curr_motion._skeleton_tree._parent_indices = curr_motion._skeleton_tree._parent_indices.to(self._device)\n curr_motion._skeleton_tree._local_translation = curr_motion._skeleton_tree._local_translation.to(self._device)\n curr_motion._rotation = curr_motion._rotation.to(self._device)\n\n self._motions.append(curr_motion)\n self._motion_lengths.append(curr_len)\n \n curr_weight = motion_weights[f]\n self._motion_weights.append(curr_weight)\n\n self._motion_lengths = torch.tensor(self._motion_lengths, device=self._device, dtype=torch.float32)\n\n self._motion_weights = torch.tensor(self._motion_weights, dtype=torch.float32, device=self._device)\n self._motion_weights /= self._motion_weights.sum()\n\n self._motion_fps = torch.tensor(self._motion_fps, device=self._device, dtype=torch.float32)\n self._motion_bodies = torch.stack(self._motion_bodies, dim=0)\n self._motion_body_scales = torch.tensor(self._motion_body_scales, device=self._device, dtype=torch.float32)\n self._motion_body_idx = torch.tensor(self._motion_body_idx, device=self._device)\n self._motion_kp2d = torch.cat(self._motion_kp2d, dim=0) if len(self._motion_kp2d) > 0 else None\n self._motion_cam_proj = torch.cat(self._motion_cam_proj, dim=0) if len(self._motion_cam_proj) > 0 else None\n self._motion_min_verts_h = torch.tensor(self._motion_min_verts_h, device=self._device, dtype=torch.float32)\n self._motion_dt = torch.tensor(self._motion_dt, device=self._device, dtype=torch.float32)\n self._motion_num_frames = torch.tensor(self._motion_num_frames, device=self._device)\n self._motion_seq_ids = torch.tensor(self._motion_seq_ids, device=self._device)\n\n return\n\n def _fetch_motion_files(self, motion_file):\n\n if isinstance(motion_file, dict):\n\n motion_files = list(motion_file.values())\n motion_weights = [1/len(motion_files)] * len(motion_files)\n\n else:\n ext = os.path.splitext(motion_file)[1]\n if (ext == \".yaml\"):\n dir_name = os.path.dirname(motion_file)\n motion_files = []\n motion_weights = []\n\n with open(os.path.join(os.getcwd(), motion_file), 'r') as f:\n motion_config = yaml.load(f, Loader=yaml.SafeLoader)\n\n motion_list = motion_config['motions']\n for motion_entry in motion_list:\n curr_file = motion_entry['file']\n curr_weight = motion_entry['weight']\n assert(curr_weight >= 0)\n\n curr_file = os.path.join(dir_name, curr_file)\n motion_weights.append(curr_weight)\n motion_files.append(curr_file)\n\n elif (ext == \".pkl\"):\n motion_data = joblib.load(motion_file)\n motion_files = list(motion_data.values())\n motion_weights = [1/len(motion_files)] * len(motion_files)\n\n\n else:\n motion_files = [motion_file]\n motion_weights = [1.0]\n\n return motion_files, motion_weights\n\n def _calc_frame_blend(self, time, len, num_frames, dt):\n\n phase = time / len\n phase = torch.clip(phase, 0.0, 1.0)\n\n frame_idx0 = (phase * (num_frames - 1)).long()\n frame_idx1 = torch.min(frame_idx0 + 1, num_frames - 1)\n blend = (time - frame_idx0 * dt) / dt\n\n return frame_idx0, frame_idx1, blend\n\n def _get_num_bodies(self):\n motion = self.get_motion(0)\n num_bodies = motion.num_joints\n return num_bodies\n\n def _compute_motion_dof_vels(self, motion):\n num_frames = motion.tensor.shape[0]\n dt = 1.0 / motion.fps\n dof_vels = []\n\n for f in range(num_frames - 1):\n local_rot0 = motion.local_rotation[f]\n local_rot1 = motion.local_rotation[f + 1]\n frame_dof_vel = self._local_rotation_to_dof_vel(local_rot0, local_rot1, dt)\n frame_dof_vel = frame_dof_vel\n dof_vels.append(frame_dof_vel)\n \n dof_vels.append(dof_vels[-1])\n dof_vels = torch.stack(dof_vels, dim=0)\n\n return dof_vels\n \n def _local_rotation_to_dof(self, local_rot):\n body_ids = self._dof_body_ids\n dof_offsets = self._dof_offsets\n\n n = local_rot.shape[0]\n dof_pos = torch.zeros((n, self._num_dof), dtype=torch.float, device=self._device)\n\n for j in range(len(body_ids)):\n body_id = body_ids[j]\n joint_offset = dof_offsets[j]\n joint_size = dof_offsets[j + 1] - joint_offset\n\n if (joint_size == 3):\n joint_q = local_rot[:, body_id]\n joint_exp_map = torch_utils.quat_to_exp_map(joint_q)\n dof_pos[:, joint_offset:(joint_offset + joint_size)] = joint_exp_map\n elif (joint_size == 1):\n joint_q = local_rot[:, body_id]\n joint_theta, joint_axis = torch_utils.quat_to_angle_axis(joint_q)\n joint_theta = joint_theta * joint_axis[..., 1] # assume joint is always along y axis\n\n joint_theta = normalize_angle(joint_theta)\n dof_pos[:, joint_offset] = joint_theta\n\n else:\n print(\"Unsupported joint type\")\n assert(False)\n\n return dof_pos\n\n def _local_rotation_to_dof_vel(self, local_rot0, local_rot1, dt):\n body_ids = self._dof_body_ids\n dof_offsets = self._dof_offsets\n\n dof_vel = torch.zeros([self._num_dof], device=self._device)\n\n diff_quat_data = quat_mul_norm(quat_inverse(local_rot0), local_rot1)\n diff_angle, diff_axis = quat_angle_axis(diff_quat_data)\n local_vel = diff_axis * diff_angle.unsqueeze(-1) / dt\n local_vel = local_vel\n\n for j in range(len(body_ids)):\n body_id = body_ids[j]\n joint_offset = dof_offsets[j]\n joint_size = dof_offsets[j + 1] - joint_offset\n\n if (joint_size == 3):\n joint_vel = local_vel[body_id]\n dof_vel[joint_offset:(joint_offset + joint_size)] = joint_vel\n\n elif (joint_size == 1):\n assert(joint_size == 1)\n joint_vel = local_vel[body_id]\n dof_vel[joint_offset] = joint_vel[1] # assume joint is always along y axis\n\n else:\n print(\"Unsupported joint type\")\n assert(False)\n\n return dof_vel" } ]
import joblib import numpy as np import os import sys import argparse import torch import yaml import ipdb from scipy.spatial.transform import Rotation as sRot from tqdm import tqdm from uhc.smpllib.smpl_parser import SMPL_BONE_ORDER_NAMES as joint_names from uhc.smpllib.smpl_local_robot import Robot as LocalRobot from embodied_pose.utils.motion_lib import MotionLib from poselib.skeleton.skeleton3d import SkeletonTree, SkeletonMotion, SkeletonState
16,442
key = ",".join([f"{x:.6f}" for x in beta]) beta_mapping[key] = i print(f'AMASS data has {len(beta_mapping)} unique body shapes!') joblib.dump({'beta_arr': beta_arr, 'beta_mapping': beta_mapping}, f'{args.out_dir}/shape_data.pkl') robot_cfg = { "mesh": True, "model": "smpl", "body_params": {}, "joint_params": {}, "geom_params": {}, "actuator_params": {}, } model_xml_path = f"/tmp/smpl/smpl_mesh_humanoid_v1_convert.xml" smpl_local_robot = LocalRobot( robot_cfg, data_dir= "data/smpl", model_xml_path=model_xml_path ) mujoco_joint_names = [ 'Pelvis', 'L_Hip', 'L_Knee', 'L_Ankle', 'L_Toe', 'R_Hip', 'R_Knee', 'R_Ankle', 'R_Toe', 'Torso', 'Spine', 'Chest', 'Neck', 'Head', 'L_Thorax', 'L_Shoulder', 'L_Elbow', 'L_Wrist', 'L_Hand', 'R_Thorax', 'R_Shoulder', 'R_Elbow', 'R_Wrist', 'R_Hand' ] smpl_2_mujoco = [ joint_names.index(q) for q in mujoco_joint_names if q in joint_names ] amass_full_motion_dict = {} sequences = np.array(list(amass_data.keys())) if num_seq is not None: sequences = sequences[:num_seq] seq_mapping = {seq_name.item(): seq_idx for seq_idx, seq_name in enumerate(sequences)} motion_lib_seq_arr = np.array_split(sequences, num_motion_libs) seq_name_splits = {} for i, seq_arr in enumerate(motion_lib_seq_arr): seq_name_splits[i] = [seq_name.item()[2:] for seq_name in seq_arr] joblib.dump(seq_name_splits, f'{args.out_dir}/seq_name_splits.pkl') for i, motion_lib_seqs in enumerate(tqdm(motion_lib_seq_arr)): motion_lib_input_dict = dict() for key_name in motion_lib_seqs: key_name = key_name.item() smpl_data_entry = amass_data[key_name] file_name = f"data/amass/singles/{key_name}.npy" seq_len = smpl_data_entry['pose_aa'].shape[0] pose_aa = smpl_data_entry['pose_aa'].copy() trans = smpl_data_entry['trans'].copy() beta = smpl_data_entry['beta'][:10].copy() gender = smpl_data_entry['gender'] fps = 30.0 if isinstance(gender, np.ndarray): gender = gender.item() if isinstance(gender, bytes): gender = gender.decode("utf-8") if gender == "neutral": gender_number = [0] smpl_parser = smpl_local_robot.smpl_parser_n elif gender == "male": gender_number = [1] smpl_parser = smpl_local_robot.smpl_parser_m elif gender == "female": gender_number = [2] smpl_parser = smpl_local_robot.smpl_parser_f else: ipdb.set_trace() raise Exception("Gender Not Supported!!") batch_size = pose_aa.shape[0] pose_aa = np.concatenate([pose_aa[:, :66], np.zeros((batch_size, 6))], axis=1) # TODO: need to extract correct handle rotations instead of zero pose_quat = sRot.from_rotvec(pose_aa.reshape(-1, 3)).as_quat().reshape(batch_size, 24, 4)[..., smpl_2_mujoco, :] smpl_local_robot.load_from_skeleton(betas=torch.from_numpy(beta[None, ]), gender=gender_number) smpl_local_robot.write_xml() skeleton_tree = SkeletonTree.from_mjcf(model_xml_path) root_trans = trans + skeleton_tree.local_translation[0].numpy() new_sk_state = SkeletonState.from_rotation_and_root_translation( skeleton_tree, torch.from_numpy(pose_quat), torch.from_numpy(root_trans), is_local=True) verts, joints = smpl_parser.get_joints_verts( pose=torch.from_numpy(pose_aa), th_betas=torch.from_numpy(beta[None, ]), th_trans=torch.from_numpy(trans) ) # min_verts_h = verts[..., 2].min().item() min_verts_h = verts[..., 2].min(dim=-1)[0].mean().item() beta_key = ",".join([f"{x:.6f}" for x in beta]) new_motion = SkeletonMotion.from_skeleton_state(new_sk_state, fps=fps) new_motion_out = new_motion.to_dict() new_motion_out['seq_name'] = key_name new_motion_out['seq_idx'] = seq_mapping[key_name] new_motion_out['trans'] = trans new_motion_out['root_trans'] = root_trans new_motion_out['pose_aa'] = pose_aa new_motion_out['beta'] = beta new_motion_out['beta_idx'] = beta_mapping[beta_key] new_motion_out['gender'] = gender new_motion_out['min_verts_h'] = min_verts_h new_motion_out['body_scale'] = 1.0 new_motion_out['__name__'] = "SkeletonMotion" motion_lib_input_dict[key_name] = new_motion_out
sys.path.append(os.getcwd()) parser = argparse.ArgumentParser() parser.add_argument('--amass_data', type=str, default="data/amass/amass_copycat_take5_5.pkl") parser.add_argument('--out_dir', type=str, default="data/motion_lib/amass") parser.add_argument('--num_seq', type=int, default=None) parser.add_argument('--num_motion_libs', type=int, default=14) args = parser.parse_args() num_seq = args.num_seq num_motion_libs = args.num_motion_libs os.makedirs(args.out_dir, exist_ok=True) meta_data = { "amass_data": args.amass_data, "num_seq": num_seq, "num_motion_libs": num_motion_libs } yaml.safe_dump(meta_data, open(f'{args.out_dir}/args.yml', 'w')) amass_data = joblib.load(args.amass_data) info = joblib.load('data/misc/smpl_body_info.pkl') # body_shapes all_beta = [x['beta'][:10] for x in amass_data.values()] _, index = np.unique([",".join([f"{x:.6f}" for x in beta]) for beta in all_beta], return_index=True) index.sort() beta_arr = [all_beta[i] for i in index] beta_mapping = dict() for i, beta in enumerate(beta_arr): key = ",".join([f"{x:.6f}" for x in beta]) beta_mapping[key] = i print(f'AMASS data has {len(beta_mapping)} unique body shapes!') joblib.dump({'beta_arr': beta_arr, 'beta_mapping': beta_mapping}, f'{args.out_dir}/shape_data.pkl') robot_cfg = { "mesh": True, "model": "smpl", "body_params": {}, "joint_params": {}, "geom_params": {}, "actuator_params": {}, } model_xml_path = f"/tmp/smpl/smpl_mesh_humanoid_v1_convert.xml" smpl_local_robot = LocalRobot( robot_cfg, data_dir= "data/smpl", model_xml_path=model_xml_path ) mujoco_joint_names = [ 'Pelvis', 'L_Hip', 'L_Knee', 'L_Ankle', 'L_Toe', 'R_Hip', 'R_Knee', 'R_Ankle', 'R_Toe', 'Torso', 'Spine', 'Chest', 'Neck', 'Head', 'L_Thorax', 'L_Shoulder', 'L_Elbow', 'L_Wrist', 'L_Hand', 'R_Thorax', 'R_Shoulder', 'R_Elbow', 'R_Wrist', 'R_Hand' ] smpl_2_mujoco = [ joint_names.index(q) for q in mujoco_joint_names if q in joint_names ] amass_full_motion_dict = {} sequences = np.array(list(amass_data.keys())) if num_seq is not None: sequences = sequences[:num_seq] seq_mapping = {seq_name.item(): seq_idx for seq_idx, seq_name in enumerate(sequences)} motion_lib_seq_arr = np.array_split(sequences, num_motion_libs) seq_name_splits = {} for i, seq_arr in enumerate(motion_lib_seq_arr): seq_name_splits[i] = [seq_name.item()[2:] for seq_name in seq_arr] joblib.dump(seq_name_splits, f'{args.out_dir}/seq_name_splits.pkl') for i, motion_lib_seqs in enumerate(tqdm(motion_lib_seq_arr)): motion_lib_input_dict = dict() for key_name in motion_lib_seqs: key_name = key_name.item() smpl_data_entry = amass_data[key_name] file_name = f"data/amass/singles/{key_name}.npy" seq_len = smpl_data_entry['pose_aa'].shape[0] pose_aa = smpl_data_entry['pose_aa'].copy() trans = smpl_data_entry['trans'].copy() beta = smpl_data_entry['beta'][:10].copy() gender = smpl_data_entry['gender'] fps = 30.0 if isinstance(gender, np.ndarray): gender = gender.item() if isinstance(gender, bytes): gender = gender.decode("utf-8") if gender == "neutral": gender_number = [0] smpl_parser = smpl_local_robot.smpl_parser_n elif gender == "male": gender_number = [1] smpl_parser = smpl_local_robot.smpl_parser_m elif gender == "female": gender_number = [2] smpl_parser = smpl_local_robot.smpl_parser_f else: ipdb.set_trace() raise Exception("Gender Not Supported!!") batch_size = pose_aa.shape[0] pose_aa = np.concatenate([pose_aa[:, :66], np.zeros((batch_size, 6))], axis=1) # TODO: need to extract correct handle rotations instead of zero pose_quat = sRot.from_rotvec(pose_aa.reshape(-1, 3)).as_quat().reshape(batch_size, 24, 4)[..., smpl_2_mujoco, :] smpl_local_robot.load_from_skeleton(betas=torch.from_numpy(beta[None, ]), gender=gender_number) smpl_local_robot.write_xml() skeleton_tree = SkeletonTree.from_mjcf(model_xml_path) root_trans = trans + skeleton_tree.local_translation[0].numpy() new_sk_state = SkeletonState.from_rotation_and_root_translation( skeleton_tree, torch.from_numpy(pose_quat), torch.from_numpy(root_trans), is_local=True) verts, joints = smpl_parser.get_joints_verts( pose=torch.from_numpy(pose_aa), th_betas=torch.from_numpy(beta[None, ]), th_trans=torch.from_numpy(trans) ) # min_verts_h = verts[..., 2].min().item() min_verts_h = verts[..., 2].min(dim=-1)[0].mean().item() beta_key = ",".join([f"{x:.6f}" for x in beta]) new_motion = SkeletonMotion.from_skeleton_state(new_sk_state, fps=fps) new_motion_out = new_motion.to_dict() new_motion_out['seq_name'] = key_name new_motion_out['seq_idx'] = seq_mapping[key_name] new_motion_out['trans'] = trans new_motion_out['root_trans'] = root_trans new_motion_out['pose_aa'] = pose_aa new_motion_out['beta'] = beta new_motion_out['beta_idx'] = beta_mapping[beta_key] new_motion_out['gender'] = gender new_motion_out['min_verts_h'] = min_verts_h new_motion_out['body_scale'] = 1.0 new_motion_out['__name__'] = "SkeletonMotion" motion_lib_input_dict[key_name] = new_motion_out
motion_lib = MotionLib(motion_file=motion_lib_input_dict,
2
2023-10-30 20:43:43+00:00
24k
masked-spacetime-hashing/msth
MSTH/datamanager.py
[ { "identifier": "CameraOptimizerConfig", "path": "nerfstudio/cameras/camera_optimizers.py", "snippet": "class CameraOptimizerConfig(InstantiateConfig):\n \"\"\"Configuration of optimization for camera poses.\"\"\"\n\n _target: Type = field(default_factory=lambda: CameraOptimizer)\n\n mode: Literal[\"off\", \"SO3xR3\", \"SE3\"] = \"off\"\n \"\"\"Pose optimization strategy to use. If enabled, we recommend SO3xR3.\"\"\"\n\n position_noise_std: float = 0.0\n \"\"\"Noise to add to initial positions. Useful for debugging.\"\"\"\n\n orientation_noise_std: float = 0.0\n \"\"\"Noise to add to initial orientations. Useful for debugging.\"\"\"\n\n optimizer: AdamOptimizerConfig = AdamOptimizerConfig(lr=6e-4, eps=1e-15)\n \"\"\"ADAM parameters for camera optimization.\"\"\"\n\n scheduler: SchedulerConfig = ExponentialDecaySchedulerConfig(max_steps=10000)\n \"\"\"Learning rate scheduler for camera optimizer..\"\"\"\n\n param_group: tyro.conf.Suppress[str] = \"camera_opt\"\n \"\"\"Name of the parameter group used for pose optimization. Can be any string that doesn't conflict with other\n groups.\"\"\"" }, { "identifier": "RayBundle", "path": "nerfstudio/cameras/rays.py", "snippet": "class RayBundle(TensorDataclass):\n \"\"\"A bundle of ray parameters.\"\"\"\n\n # TODO(ethan): make sure the sizes with ... are correct\n origins: TensorType[..., 3]\n \"\"\"Ray origins (XYZ)\"\"\"\n directions: TensorType[..., 3]\n \"\"\"Unit ray direction vector\"\"\"\n pixel_area: TensorType[..., 1]\n \"\"\"Projected area of pixel a distance 1 away from origin\"\"\"\n camera_indices: Optional[TensorType[..., 1]] = None\n \"\"\"Camera indices\"\"\"\n nears: Optional[TensorType[..., 1]] = None\n \"\"\"Distance along ray to start sampling\"\"\"\n fars: Optional[TensorType[..., 1]] = None\n \"\"\"Rays Distance along ray to stop sampling\"\"\"\n metadata: Optional[Dict[str, TensorType[\"num_rays\", \"latent_dims\"]]] = None\n \"\"\"Additional metadata or data needed for interpolation, will mimic shape of rays\"\"\"\n times: Optional[TensorType[..., 1]] = None\n \"\"\"Times at which rays are sampled\"\"\"\n\n def set_camera_indices(self, camera_index: int) -> None:\n \"\"\"Sets all of the the camera indices to a specific camera index.\n\n Args:\n camera_index: Camera index.\n \"\"\"\n self.camera_indices = torch.ones_like(self.origins[..., 0:1]).long() * camera_index\n\n def __len__(self) -> int:\n num_rays = torch.numel(self.origins) // self.origins.shape[-1]\n return num_rays\n\n def sample(self, num_rays: int) -> \"RayBundle\":\n \"\"\"Returns a RayBundle as a subset of rays.\n\n Args:\n num_rays: Number of rays in output RayBundle\n\n Returns:\n RayBundle with subset of rays.\n \"\"\"\n assert num_rays <= len(self)\n indices = random.sample(range(len(self)), k=num_rays)\n return self[indices]\n\n def get_row_major_sliced_ray_bundle(self, start_idx: int, end_idx: int) -> \"RayBundle\":\n \"\"\"Flattens RayBundle and extracts chunk given start and end indices.\n\n Args:\n start_idx: Start index of RayBundle chunk.\n end_idx: End index of RayBundle chunk.\n\n Returns:\n Flattened RayBundle with end_idx-start_idx rays.\n\n \"\"\"\n return self.flatten()[start_idx:end_idx]\n\n def get_ray_samples(\n self,\n bin_starts: TensorType[\"bs\":..., \"num_samples\", 1],\n bin_ends: TensorType[\"bs\":..., \"num_samples\", 1],\n spacing_starts: Optional[TensorType[\"bs\":..., \"num_samples\", 1]] = None,\n spacing_ends: Optional[TensorType[\"bs\":..., \"num_samples\", 1]] = None,\n spacing_to_euclidean_fn: Optional[Callable] = None,\n ) -> RaySamples:\n \"\"\"Produces samples for each ray by projection points along the ray direction. Currently samples uniformly.\n\n Args:\n bin_starts: Distance from origin to start of bin.\n bin_ends: Distance from origin to end of bin.\n\n Returns:\n Samples projected along ray.\n \"\"\"\n deltas = bin_ends - bin_starts\n if self.camera_indices is not None:\n camera_indices = self.camera_indices[..., None]\n else:\n camera_indices = None\n\n shaped_raybundle_fields = self[..., None]\n\n frustums = Frustums(\n origins=shaped_raybundle_fields.origins, # [..., 1, 3]\n directions=shaped_raybundle_fields.directions, # [..., 1, 3]\n starts=bin_starts, # [..., num_samples, 1]\n ends=bin_ends, # [..., num_samples, 1]\n pixel_area=shaped_raybundle_fields.pixel_area, # [..., 1, 1]\n )\n\n ray_samples = RaySamples(\n frustums=frustums,\n camera_indices=camera_indices, # [..., 1, 1]\n deltas=deltas, # [..., num_samples, 1]\n spacing_starts=spacing_starts, # [..., num_samples, 1]\n spacing_ends=spacing_ends, # [..., num_samples, 1]\n spacing_to_euclidean_fn=spacing_to_euclidean_fn,\n metadata=shaped_raybundle_fields.metadata,\n times=None if self.times is None else self.times[..., None], # [..., 1, 1]\n )\n\n return ray_samples" }, { "identifier": "DataManager", "path": "nerfstudio/data/datamanagers/base_datamanager.py", "snippet": "class DataManager(nn.Module):\n \"\"\"Generic data manager's abstract class\n\n This version of the data manager is designed be a monolithic way to load data and latents,\n especially since this may contain learnable parameters which need to be shared across the train\n and test data managers. The idea is that we have setup methods for train and eval separately and\n this can be a combined train/eval if you want.\n\n Usage:\n To get data, use the next_train and next_eval functions.\n This data manager's next_train and next_eval methods will return 2 things:\n 1. A Raybundle: This will contain the rays we are sampling, with latents and\n conditionals attached (everything needed at inference)\n 2. A \"batch\" of auxiliary information: This will contain the mask, the ground truth\n pixels, etc needed to actually train, score, etc the model\n\n Rationale:\n Because of this abstraction we've added, we can support more NeRF paradigms beyond the\n vanilla nerf paradigm of single-scene, fixed-images, no-learnt-latents.\n We can now support variable scenes, variable number of images, and arbitrary latents.\n\n\n Train Methods:\n setup_train: sets up for being used as train\n iter_train: will be called on __iter__() for the train iterator\n next_train: will be called on __next__() for the training iterator\n get_train_iterable: utility that gets a clean pythonic iterator for your training data\n\n Eval Methods:\n setup_eval: sets up for being used as eval\n iter_eval: will be called on __iter__() for the eval iterator\n next_eval: will be called on __next__() for the eval iterator\n get_eval_iterable: utility that gets a clean pythonic iterator for your eval data\n\n\n Attributes:\n train_count (int): the step number of our train iteration, needs to be incremented manually\n eval_count (int): the step number of our eval iteration, needs to be incremented manually\n train_dataset (Dataset): the dataset for the train dataset\n eval_dataset (Dataset): the dataset for the eval dataset\n\n Additional attributes specific to each subclass are defined in the setup_train and setup_eval\n functions.\n\n \"\"\"\n\n train_dataset: Optional[Dataset] = None\n eval_dataset: Optional[Dataset] = None\n train_sampler: Optional[DistributedSampler] = None\n eval_sampler: Optional[DistributedSampler] = None\n\n def __init__(self):\n \"\"\"Constructor for the DataManager class.\n\n Subclassed DataManagers will likely need to override this constructor.\n\n If you aren't manually calling the setup_train and setup_eval functions from an overriden\n constructor, that you call super().__init__() BEFORE you initialize any\n nn.Modules or nn.Parameters, but AFTER you've already set all the attributes you need\n for the setup functions.\"\"\"\n super().__init__()\n self.train_count = 0\n self.eval_count = 0\n if self.train_dataset and self.test_mode != \"inference\":\n self.setup_train()\n if self.eval_dataset and self.test_mode != \"inference\":\n self.setup_eval()\n\n def forward(self):\n \"\"\"Blank forward method\n\n This is an nn.Module, and so requires a forward() method normally, although in our case\n we do not need a forward() method\"\"\"\n raise NotImplementedError\n\n def iter_train(self):\n \"\"\"The __iter__ function for the train iterator.\n\n This only exists to assist the get_train_iterable function, since we need to pass\n in an __iter__ function for our trivial iterable that we are making.\"\"\"\n self.train_count = 0\n\n def iter_eval(self):\n \"\"\"The __iter__ function for the eval iterator.\n\n This only exists to assist the get_eval_iterable function, since we need to pass\n in an __iter__ function for our trivial iterable that we are making.\"\"\"\n self.eval_count = 0\n\n def get_train_iterable(self, length=-1) -> IterableWrapper:\n \"\"\"Gets a trivial pythonic iterator that will use the iter_train and next_train functions\n as __iter__ and __next__ methods respectively.\n\n This basically is just a little utility if you want to do something like:\n | for ray_bundle, batch in datamanager.get_train_iterable():\n | <eval code here>\n since the returned IterableWrapper is just an iterator with the __iter__ and __next__\n methods (methods bound to our DataManager instance in this case) specified in the constructor.\n \"\"\"\n return IterableWrapper(self.iter_train, self.next_train, length)\n\n def get_eval_iterable(self, length=-1) -> IterableWrapper:\n \"\"\"Gets a trivial pythonic iterator that will use the iter_eval and next_eval functions\n as __iter__ and __next__ methods respectively.\n\n This basically is just a little utility if you want to do something like:\n | for ray_bundle, batch in datamanager.get_eval_iterable():\n | <eval code here>\n since the returned IterableWrapper is just an iterator with the __iter__ and __next__\n methods (methods bound to our DataManager instance in this case) specified in the constructor.\n \"\"\"\n return IterableWrapper(self.iter_eval, self.next_eval, length)\n\n @abstractmethod\n def setup_train(self):\n \"\"\"Sets up the data manager for training.\n\n Here you will define any subclass specific object attributes from the attribute\"\"\"\n\n @abstractmethod\n def setup_eval(self):\n \"\"\"Sets up the data manager for evaluation\"\"\"\n\n @abstractmethod\n def next_train(self, step: int) -> Tuple[RayBundle, Dict]:\n \"\"\"Returns the next batch of data from the train data manager.\n\n Args:\n step: the step number of the eval image to retrieve\n Returns:\n A tuple of the ray bundle for the image, and a dictionary of additional batch information\n such as the groudtruth image.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def next_eval(self, step: int) -> Tuple[RayBundle, Dict]:\n \"\"\"Returns the next batch of data from the eval data manager.\n\n Args:\n step: the step number of the eval image to retrieve\n Returns:\n A tuple of the ray bundle for the image, and a dictionary of additional batch information\n such as the groudtruth image.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def next_eval_image(self, step: int) -> Tuple[int, RayBundle, Dict]:\n \"\"\"Retreive the next eval image.\n\n Args:\n step: the step number of the eval image to retrieve\n Returns:\n A tuple of the step number, the ray bundle for the image, and a dictionary of\n additional batch information such as the groudtruth image.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def get_train_rays_per_batch(self) -> int:\n \"\"\"Returns the number of rays per batch for training.\"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def get_eval_rays_per_batch(self) -> int:\n \"\"\"Returns the number of rays per batch for evaluation.\"\"\"\n raise NotImplementedError\n\n def get_datapath(self) -> Optional[Path]: # pylint:disable=no-self-use\n \"\"\"Returns the path to the data. This is used to determine where to save camera paths.\"\"\"\n return None\n\n def get_training_callbacks( # pylint:disable=no-self-use\n self, training_callback_attributes: TrainingCallbackAttributes # pylint: disable=unused-argument\n ) -> List[TrainingCallback]:\n \"\"\"Returns a list of callbacks to be used during training.\"\"\"\n return []\n\n @abstractmethod\n def get_param_groups(self) -> Dict[str, List[Parameter]]: # pylint: disable=no-self-use\n \"\"\"Get the param groups for the data manager.\n\n Returns:\n A list of dictionaries containing the data manager's param groups.\n \"\"\"\n return {}" }, { "identifier": "DataManagerConfig", "path": "nerfstudio/data/datamanagers/base_datamanager.py", "snippet": "class DataManagerConfig(InstantiateConfig):\n \"\"\"Configuration for data manager instantiation; DataManager is in charge of keeping the train/eval dataparsers;\n After instantiation, data manager holds both train/eval datasets and is in charge of returning unpacked\n train/eval data at each iteration\n \"\"\"\n\n _target: Type = field(default_factory=lambda: DataManager)\n \"\"\"Target class to instantiate.\"\"\"\n data: Optional[Path] = None\n \"\"\"Source of data, may not be used by all models.\"\"\"\n camera_optimizer: Optional[CameraOptimizerConfig] = None\n \"\"\"Specifies the camera pose optimizer used during training. Helpful if poses are noisy.\"\"\"" }, { "identifier": "PixelSampler", "path": "nerfstudio/data/pixel_samplers.py", "snippet": "class PixelSampler: # pylint: disable=too-few-public-methods\n \"\"\"Samples 'pixel_batch's from 'image_batch's.\n\n Args:\n num_rays_per_batch: number of rays to sample per batch\n keep_full_image: whether or not to include a reference to the full image in returned batch\n \"\"\"\n\n def __init__(self, num_rays_per_batch: int, keep_full_image: bool = False, **kwargs) -> None:\n self.kwargs = kwargs\n self.num_rays_per_batch = num_rays_per_batch\n self.keep_full_image = keep_full_image\n\n def set_num_rays_per_batch(self, num_rays_per_batch: int):\n \"\"\"Set the number of rays to sample per batch.\n\n Args:\n num_rays_per_batch: number of rays to sample per batch\n \"\"\"\n self.num_rays_per_batch = num_rays_per_batch\n\n def sample_method( # pylint: disable=no-self-use\n self,\n batch_size: int,\n num_images: int,\n image_height: int,\n image_width: int,\n mask: Optional[TensorType] = None,\n device: Union[torch.device, str] = \"cpu\",\n ) -> TensorType[\"batch_size\", 3]:\n \"\"\"\n Naive pixel sampler, uniformly samples across all possible pixels of all possible images.\n\n Args:\n batch_size: number of samples in a batch\n num_images: number of images to sample over\n mask: mask of possible pixels in an image to sample from.\n \"\"\"\n if isinstance(mask, torch.Tensor):\n nonzero_indices = torch.nonzero(mask[..., 0], as_tuple=False)\n chosen_indices = random.sample(range(len(nonzero_indices)), k=batch_size)\n indices = nonzero_indices[chosen_indices]\n else:\n indices = torch.floor(\n torch.rand((batch_size, 3), device=device)\n * torch.tensor([num_images, image_height, image_width], device=device)\n ).long()\n\n return indices\n\n def collate_image_dataset_batch(self, batch: Dict, num_rays_per_batch: int, keep_full_image: bool = False):\n \"\"\"\n Operates on a batch of images and samples pixels to use for generating rays.\n Returns a collated batch which is input to the Graph.\n It will sample only within the valid 'mask' if it's specified.\n\n Args:\n batch: batch of images to sample from\n num_rays_per_batch: number of rays to sample per batch\n keep_full_image: whether or not to include a reference to the full image in returned batch\n \"\"\"\n\n device = batch[\"image\"].device\n num_images, image_height, image_width, _ = batch[\"image\"].shape\n\n if \"mask\" in batch:\n indices = self.sample_method(\n num_rays_per_batch, num_images, image_height, image_width, mask=batch[\"mask\"], device=device\n )\n else:\n indices = self.sample_method(num_rays_per_batch, num_images, image_height, image_width, device=device)\n\n c, y, x = (i.flatten() for i in torch.split(indices, 1, dim=-1))\n collated_batch = {\n key: value[c, y, x] for key, value in batch.items() if key != \"image_idx\" and value is not None\n }\n\n assert collated_batch[\"image\"].shape == (num_rays_per_batch, 3), collated_batch[\"image\"].shape\n\n # Needed to correct the random indices to their actual camera idx locations.\n indices[:, 0] = batch[\"image_idx\"][c]\n collated_batch[\"indices\"] = indices # with the abs camera indices\n\n if keep_full_image:\n collated_batch[\"full_image\"] = batch[\"image\"]\n\n return collated_batch\n\n def collate_image_dataset_batch_list(self, batch: Dict, num_rays_per_batch: int, keep_full_image: bool = False):\n \"\"\"\n Does the same as collate_image_dataset_batch, except it will operate over a list of images / masks inside\n a list.\n\n We will use this with the intent of DEPRECIATING it as soon as we find a viable alternative.\n The intention will be to replace this with a more efficient implementation that doesn't require a for loop, but\n since pytorch's ragged tensors are still in beta (this would allow for some vectorization), this will do.\n\n Args:\n batch: batch of images to sample from\n num_rays_per_batch: number of rays to sample per batch\n keep_full_image: whether or not to include a reference to the full image in returned batch\n \"\"\"\n\n device = batch[\"image\"][0].device\n num_images = len(batch[\"image\"])\n\n # only sample within the mask, if the mask is in the batch\n all_indices = []\n all_images = []\n\n if \"mask\" in batch:\n num_rays_in_batch = num_rays_per_batch // num_images\n for i in range(num_images):\n\n image_height, image_width, _ = batch[\"image\"][i].shape\n\n if i == num_images - 1:\n num_rays_in_batch = num_rays_per_batch - (num_images - 1) * num_rays_in_batch\n\n indices = self.sample_method(\n num_rays_in_batch, 1, image_height, image_width, mask=batch[\"mask\"][i], device=device\n )\n indices[:, 0] = i\n all_indices.append(indices)\n all_images.append(batch[\"image\"][i][indices[:, 1], indices[:, 2]])\n\n else:\n num_rays_in_batch = num_rays_per_batch // num_images\n for i in range(num_images):\n image_height, image_width, _ = batch[\"image\"][i].shape\n if i == num_images - 1:\n num_rays_in_batch = num_rays_per_batch - (num_images - 1) * num_rays_in_batch\n indices = self.sample_method(num_rays_in_batch, 1, image_height, image_width, device=device)\n indices[:, 0] = i\n all_indices.append(indices)\n all_images.append(batch[\"image\"][i][indices[:, 1], indices[:, 2]])\n\n indices = torch.cat(all_indices, dim=0)\n\n c, y, x = (i.flatten() for i in torch.split(indices, 1, dim=-1))\n collated_batch = {\n key: value[c, y, x]\n for key, value in batch.items()\n if key != \"image_idx\" and key != \"image\" and key != \"mask\" and value is not None\n }\n\n collated_batch[\"image\"] = torch.cat(all_images, dim=0)\n\n assert collated_batch[\"image\"].shape == (num_rays_per_batch, 3), collated_batch[\"image\"].shape\n\n # Needed to correct the random indices to their actual camera idx locations.\n indices[:, 0] = batch[\"image_idx\"][c]\n collated_batch[\"indices\"] = indices # with the abs camera indices\n\n if keep_full_image:\n collated_batch[\"full_image\"] = batch[\"image\"]\n\n return collated_batch\n\n def sample(self, image_batch: Dict):\n \"\"\"Sample an image batch and return a pixel batch.\n\n Args:\n image_batch: batch of images to sample from\n \"\"\"\n if isinstance(image_batch[\"image\"], list):\n image_batch = dict(image_batch.items()) # copy the dictionary so we don't modify the original\n pixel_batch = self.collate_image_dataset_batch_list(\n image_batch, self.num_rays_per_batch, keep_full_image=self.keep_full_image\n )\n elif isinstance(image_batch[\"image\"], torch.Tensor):\n pixel_batch = self.collate_image_dataset_batch(\n image_batch, self.num_rays_per_batch, keep_full_image=self.keep_full_image\n )\n else:\n raise ValueError(\"image_batch['image'] must be a list or torch.Tensor\")\n return pixel_batch" }, { "identifier": "nerfstudio_collate", "path": "nerfstudio/data/utils/nerfstudio_collate.py", "snippet": "def nerfstudio_collate(\n batch, extra_mappings: Union[Dict[type, Callable], None] = None\n): # pylint: disable=too-many-return-statements\n r\"\"\"\n This is the default pytorch collate function, but with support for nerfstudio types. All documentation\n below is copied straight over from pytorch's default_collate function, python version 3.8.13,\n pytorch version '1.12.1+cu113'. Custom nerfstudio types are accounted for at the end, and extra\n mappings can be passed in to handle custom types. These mappings are from types: callable (types\n being like int or float or the return value of type(3.), etc). The only code before we parse for custom types that\n was changed from default pytorch was the addition of the extra_mappings argument, a find and replace operation\n from default_collate to nerfstudio_collate, and the addition of the nerfstudio_collate_err_msg_format variable.\n\n\n Function that takes in a batch of data and puts the elements within the batch\n into a tensor with an additional outer dimension - batch size. The exact output type can be\n a :class:`torch.Tensor`, a `Sequence` of :class:`torch.Tensor`, a\n Collection of :class:`torch.Tensor`, or left unchanged, depending on the input type.\n This is used as the default function for collation when\n `batch_size` or `batch_sampler` is defined in :class:`~torch.utils.data.DataLoader`.\n\n Here is the general input type (based on the type of the element within the batch) to output type mapping:\n\n * :class:`torch.Tensor` -> :class:`torch.Tensor` (with an added outer dimension batch size)\n * NumPy Arrays -> :class:`torch.Tensor`\n * `float` -> :class:`torch.Tensor`\n * `int` -> :class:`torch.Tensor`\n * `str` -> `str` (unchanged)\n * `bytes` -> `bytes` (unchanged)\n * `Mapping[K, V_i]` -> `Mapping[K, nerfstudio_collate([V_1, V_2, ...])]`\n * `NamedTuple[V1_i, V2_i, ...]` -> `NamedTuple[nerfstudio_collate([V1_1, V1_2, ...]),\n nerfstudio_collate([V2_1, V2_2, ...]), ...]`\n * `Sequence[V1_i, V2_i, ...]` -> `Sequence[nerfstudio_collate([V1_1, V1_2, ...]),\n nerfstudio_collate([V2_1, V2_2, ...]), ...]`\n\n Args:\n batch: a single batch to be collated\n\n Examples:\n >>> # Example with a batch of `int`s:\n >>> nerfstudio_collate([0, 1, 2, 3])\n tensor([0, 1, 2, 3])\n >>> # Example with a batch of `str`s:\n >>> nerfstudio_collate(['a', 'b', 'c'])\n ['a', 'b', 'c']\n >>> # Example with `Map` inside the batch:\n >>> nerfstudio_collate([{'A': 0, 'B': 1}, {'A': 100, 'B': 100}])\n {'A': tensor([ 0, 100]), 'B': tensor([ 1, 100])}\n >>> # Example with `NamedTuple` inside the batch:\n >>> Point = namedtuple('Point', ['x', 'y'])\n >>> nerfstudio_collate([Point(0, 0), Point(1, 1)])\n Point(x=tensor([0, 1]), y=tensor([0, 1]))\n >>> # Example with `Tuple` inside the batch:\n >>> nerfstudio_collate([(0, 1), (2, 3)])\n [tensor([0, 2]), tensor([1, 3])]\n >>> # Example with `List` inside the batch:\n >>> nerfstudio_collate([[0, 1], [2, 3]])\n [tensor([0, 2]), tensor([1, 3])]\n \"\"\"\n if extra_mappings is None:\n extra_mappings = {}\n elem = batch[0]\n elem_type = type(elem)\n if isinstance(elem, torch.Tensor): # pylint: disable=no-else-return\n out = None\n if torch.utils.data.get_worker_info() is not None:\n # If we're in a background process, concatenate directly into a\n # shared memory tensor to avoid an extra copy\n numel = sum(x.numel() for x in batch)\n storage = elem.storage()._new_shared(numel, device=elem.device) # pylint: disable=protected-access\n out = elem.new(storage).resize_(len(batch), *list(elem.size()))\n return torch.stack(batch, 0, out=out)\n elif elem_type.__module__ == \"numpy\" and elem_type.__name__ != \"str_\" and elem_type.__name__ != \"string_\":\n # pylint: disable=no-else-return, consider-using-in\n if elem_type.__name__ == \"ndarray\" or elem_type.__name__ == \"memmap\":\n # array of string classes and object\n if np_str_obj_array_pattern.search(elem.dtype.str) is not None:\n raise TypeError(NERFSTUDIO_COLLATE_ERR_MSG_FORMAT.format(elem.dtype))\n\n return nerfstudio_collate([torch.as_tensor(b) for b in batch], extra_mappings=extra_mappings)\n elif elem.shape == (): # scalars\n return torch.as_tensor(batch)\n elif isinstance(elem, float):\n return torch.tensor(batch, dtype=torch.float64)\n elif isinstance(elem, int):\n return torch.tensor(batch)\n elif isinstance(elem, string_classes):\n return batch\n elif isinstance(elem, collections.abc.Mapping):\n try:\n return elem_type(\n {key: nerfstudio_collate([d[key] for d in batch], extra_mappings=extra_mappings) for key in elem}\n )\n except TypeError:\n # The mapping type may not support `__init__(iterable)`.\n return {key: nerfstudio_collate([d[key] for d in batch], extra_mappings=extra_mappings) for key in elem}\n elif isinstance(elem, tuple) and hasattr(elem, \"_fields\"): # namedtuple\n return elem_type(*(nerfstudio_collate(samples, extra_mappings=extra_mappings) for samples in zip(*batch)))\n elif isinstance(elem, collections.abc.Sequence):\n # check to make sure that the elements in batch have consistent size\n it = iter(batch)\n elem_size = len(next(it))\n if not all(len(elem) == elem_size for elem in it):\n raise RuntimeError(\"each element in list of batch should be of equal size\")\n transposed = list(zip(*batch)) # It may be accessed twice, so we use a list.\n\n if isinstance(elem, tuple):\n return [\n nerfstudio_collate(samples, extra_mappings=extra_mappings) for samples in transposed\n ] # Backwards compatibility.\n else:\n try:\n return elem_type([nerfstudio_collate(samples, extra_mappings=extra_mappings) for samples in transposed])\n except TypeError:\n # The sequence type may not support `__init__(iterable)` (e.g., `range`).\n return [nerfstudio_collate(samples, extra_mappings=extra_mappings) for samples in transposed]\n\n # NerfStudio types supported below\n\n elif isinstance(elem, Cameras):\n # If a camera, just concatenate along the batch dimension. In the future, this may change to stacking\n assert all((isinstance(cam, Cameras) for cam in batch))\n assert all((cam.distortion_params is None for cam in batch)) or all(\n (cam.distortion_params is not None for cam in batch)\n ), \"All cameras must have distortion parameters or none of them should have distortion parameters.\\\n Generalized batching will be supported in the future.\"\n\n # If no batch dimension exists, then we need to stack everything and create a batch dimension on 0th dim\n if elem.shape == ():\n op = torch.stack\n # If batch dimension exists, then we need to concatenate along the 0th dimension\n else:\n op = torch.cat\n\n return Cameras(\n op([cameras.camera_to_worlds for cameras in batch], dim=0),\n op([cameras.fx for cameras in batch], dim=0),\n op([cameras.fy for cameras in batch], dim=0),\n op([cameras.cx for cameras in batch], dim=0),\n op([cameras.cy for cameras in batch], dim=0),\n height=op([cameras.height for cameras in batch], dim=0),\n width=op([cameras.width for cameras in batch], dim=0),\n distortion_params=op(\n [\n cameras.distortion_params\n if cameras.distortion_params is not None\n else torch.zeros_like(cameras.distortion_params)\n for cameras in batch\n ],\n dim=0,\n ),\n camera_type=op([cameras.camera_type for cameras in batch], dim=0),\n times=torch.stack(\n [cameras.times if cameras.times is not None else -torch.ones_like(cameras.times) for cameras in batch],\n dim=0,\n ),\n )\n\n for type_key in extra_mappings:\n if isinstance(elem, type_key):\n return extra_mappings[type_key](batch)\n\n raise TypeError(NERFSTUDIO_COLLATE_ERR_MSG_FORMAT.format(elem_type))" }, { "identifier": "RayGenerator", "path": "nerfstudio/model_components/ray_generators.py", "snippet": "class RayGenerator(nn.Module):\n \"\"\"torch.nn Module for generating rays.\n This class is the interface between the scene's cameras/camera optimizer and the ray sampler.\n\n Args:\n cameras: Camera objects containing camera info.\n pose_optimizer: pose optimization module, for optimizing noisy camera intrinsics/extrinsics.\n \"\"\"\n\n def __init__(self, cameras: Cameras, pose_optimizer: CameraOptimizer) -> None:\n super().__init__()\n self.cameras = cameras\n self.pose_optimizer = pose_optimizer\n self.register_buffer(\"image_coords\", cameras.get_image_coords(), persistent=False)\n\n def forward(self, ray_indices: TensorType[\"num_rays\", 3]) -> RayBundle:\n \"\"\"Index into the cameras to generate the rays.\n\n Args:\n ray_indices: Contains camera, row, and col indices for target rays.\n \"\"\"\n c = ray_indices[:, 0] # camera indices\n y = ray_indices[:, 1] # row indices\n x = ray_indices[:, 2] # col indices\n coords = self.image_coords[y, x]\n\n camera_opt_to_camera = self.pose_optimizer(c)\n\n ray_bundle = self.cameras.generate_rays(\n camera_indices=c.unsqueeze(-1),\n coords=coords,\n camera_opt_to_camera=camera_opt_to_camera,\n )\n return ray_bundle" }, { "identifier": "VideoDataParser", "path": "MSTH/dataparser.py", "snippet": "class VideoDataParser(DataParser):\n \"\"\"Video dataparser\"\"\"\n\n config: VideoDataParserConfig\n downscale_factor: Optional[int] = None\n\n def _generate_dataparser_outputs(self, split: str = \"train\") -> VideoDataParserOutputs:\n # print(list(os.listdir(self.config.data)))\n use_separate_file = False\n if \"transforms_train.json\" in list(os.listdir(self.config.data)):\n use_separate_file = True\n CONSOLE.log(\"Using separated config files for train and eval\")\n meta_train = load_from_json(self.config.data / \"transforms_train.json\")\n meta_val = load_from_json(self.config.data / \"transforms_test.json\")\n\n num_train_cams = len(meta_train[\"frames\"])\n num_val_cams = len(meta_val[\"frames\"])\n meta = deepcopy(meta_train)\n meta[\"frames\"].extend(meta_val[\"frames\"])\n else:\n meta = load_from_json(self.config.data / \"transforms.json\")\n num_tot_cams = len(meta[\"frames\"])\n num_train_cams = math.ceil(num_tot_cams * self.config.train_split_fraction)\n data_dir = self.config.data\n print(self.config.data)\n # exit(0)\n\n video_filenames = []\n poses = []\n\n fx_fixed = \"fl_x\" in meta\n fy_fixed = \"fl_y\" in meta\n cx_fixed = \"cx\" in meta\n cy_fixed = \"cy\" in meta\n height_fixed = \"h\" in meta\n width_fixed = \"w\" in meta\n distort_fixed = False\n for distort_key in [\"k1\", \"k2\", \"k3\", \"p1\", \"p2\"]:\n if distort_key in meta:\n distort_fixed = True\n break\n fx = []\n fy = []\n cx = []\n cy = []\n height = []\n width = []\n distort = []\n\n num_frames = meta[\"num_frames\"]\n start_frame = meta.get(\"start_frame\", 0)\n\n for frame in meta[\"frames\"]:\n filepath = PurePath(frame[\"file_path\"])\n assert filepath.suffix in [\".mp4\", \".mov\", \".mkv\"]\n\n if not fx_fixed:\n assert \"fl_x\" in frame, \"fx not specified in frame\"\n fx.append(float(frame[\"fl_x\"]))\n if not fy_fixed:\n assert \"fl_y\" in frame, \"fy not specified in frame\"\n fy.append(float(frame[\"fl_y\"]))\n if not cx_fixed:\n assert \"cx\" in frame, \"cx not specified in frame\"\n cx.append(float(frame[\"cx\"]))\n if not cy_fixed:\n assert \"cy\" in frame, \"cy not specified in frame\"\n cy.append(float(frame[\"cy\"]))\n if not height_fixed:\n assert \"h\" in frame, \"height not specified in frame\"\n height.append(int(frame[\"h\"]))\n if not width_fixed:\n assert \"w\" in frame, \"width not specified in frame\"\n width.append(int(frame[\"w\"]))\n if not distort_fixed:\n distort.append(\n camera_utils.get_distortion_params(\n k1=float(frame[\"k1\"]) if \"k1\" in frame else 0.0,\n k2=float(frame[\"k2\"]) if \"k2\" in frame else 0.0,\n k3=float(frame[\"k3\"]) if \"k3\" in frame else 0.0,\n k4=float(frame[\"k4\"]) if \"k4\" in frame else 0.0,\n p1=float(frame[\"p1\"]) if \"p1\" in frame else 0.0,\n p2=float(frame[\"p2\"]) if \"p2\" in frame else 0.0,\n )\n )\n\n video_filenames.append(self.config.data / filepath)\n poses.append(np.array(frame[\"transform_matrix\"]))\n\n num_tot_cams = len(video_filenames)\n num_eval_cams = num_tot_cams - num_train_cams\n\n if not use_separate_file:\n i_all = np.arange(num_tot_cams)\n i_train = np.arange(num_train_cams)\n\n i_eval = np.setdiff1d(i_all, i_train)\n # i_eval = i_all[-1:]\n # i_train = i_all[:-1]\n else:\n i_all = np.arange(num_tot_cams)\n i_train = i_all[:-1]\n i_eval = i_all[-1:]\n\n if split == \"train\":\n indices = i_train\n elif split in [\"val\", \"test\"]:\n indices = i_eval\n else:\n raise ValueError(f\"Unknown dataparser split {split}\")\n\n if split != \"train\":\n CONSOLE.print(f\"Eval camera names: {(video_filenames[i_eval[0]])}\")\n else:\n CONSOLE.print(\"Train camera names:\")\n for ii in i_train:\n CONSOLE.print(f\"{video_filenames[i_train[ii]]}\")\n\n if \"orientation_override\" in meta:\n orientation_method = meta[\"orientation_override\"]\n CONSOLE.log(f\"[yellow] Dataset is overriding orientation method to {orientation_method}\")\n else:\n orientation_method = self.config.orientation_method\n\n poses = torch.from_numpy(np.array(poses).astype(np.float32))\n\n if self.config.use_llff_poses:\n poses_path = Path(self.config.data) / \"poses.npy\"\n poses = np.load(poses_path)\n if poses.shape[0] != len(video_filenames):\n # for coffee martini n3dv\n poses = np.delete(poses, -6, axis=0)\n paddings = np.array([[[0.0, 0.0, 0.0, 1.0]]] * poses.shape[0])\n poses = np.concatenate([poses, paddings], axis=1)\n poses = torch.from_numpy(poses).to(torch.float32)\n perm = [i for i in range(1, len(i_train) + 1)]\n perm.append(0)\n poses = poses[perm]\n\n # cv2gl_flip = torch.eye(4, dtype=torch.float32)\n # cv2gl_flip[1][1] = -1.0\n # cv2gl_flip[2][2] = -1.0\n # cv2gl_swap = torch.eye(4, dtype=torch.float32)\n # cv2gl_swap[1][1] = 0.0\n # cv2gl_swap[2][2] = 0.0\n # cv2gl_swap[1][2] = 1.0\n # cv2gl_swap[2][1] = 1.0\n # cv2gl = cv2gl_flip @ cv2gl_swap\n # print(cv2gl)\n def convert_pose(c2ws):\n flip_yz = torch.eye(4, dtype=torch.float32)\n flip_yz[1, 1] = -1.0\n flip_yz[2, 2] = -1.0\n return torch.einsum(\"bij,jk->bik\", c2ws, flip_yz)\n\n if self.config.convert_pose:\n poses = convert_pose(poses)\n if self.config.is_trf_pose:\n poses = convert_trf_pose(poses)\n\n poses, transform_matrix = camera_utils.auto_orient_and_center_poses(\n poses,\n method=orientation_method,\n center_poses=self.config.center_poses,\n )\n\n ## debug\n # print(poses[..., 2, 3].max())\n # print(poses[..., 2, 3].min())\n # print(poses[..., 0, 3].max())\n # print(poses[..., 0, 3].min())\n # print(poses[..., 1, 3].max())\n # print(poses[..., 1, 3].min())\n # exit(0)\n\n # Scale poses\n scale_factor = 1.0\n if self.config.auto_scale_poses:\n scale_factor /= float(torch.max(torch.abs(poses[:, :3, 3])))\n scale_factor *= self.config.scale_factor\n\n poses[:, :3, 3] *= scale_factor\n\n if self.config.offset is not None:\n poses[..., :3, 3] += torch.tensor(self.config.offset, dtype=torch.float32)\n\n if self.config.set_camera_plane:\n assert self.config.look_axis >= 0\n idx = self.config.look_axis\n if not self.config.look_along_positive:\n \"\"\"set camera plane to 1 is x-axsis, used in llff data\"\"\"\n dist = torch.min(1.0 - poses[..., idx, 3]).item() - 0.1\n print(dist)\n poses[..., idx, 3] += dist\n else:\n dist = torch.min(1.0 + poses[..., idx, 3]).item() + 0.1\n print(dist)\n poses[..., idx, 3] -= dist\n\n # Choose image_filenames and poses based on split, but after auto orient and scaling the poses.\n video_filenames = [video_filenames[i] for i in indices]\n poses = poses[indices]\n\n # in x,y,z order\n # assumes that the scene is centered at the origin\n aabb_scale = self.config.scene_scale\n if isinstance(aabb_scale, float):\n scene_box = SceneBox(\n aabb=torch.tensor(\n [[-aabb_scale, -aabb_scale, -aabb_scale], [aabb_scale, aabb_scale, aabb_scale]], dtype=torch.float32\n )\n )\n else:\n if len(aabb_scale) == 3:\n scene_box = SceneBox(\n aabb=torch.tensor(\n [\n [-aabb_scale[0], -aabb_scale[1], -aabb_scale[2]],\n [aabb_scale[0], aabb_scale[1], aabb_scale[2]],\n ],\n dtype=torch.float32,\n )\n )\n elif len(aabb_scale) == 2:\n scene_box = SceneBox(\n aabb=torch.tensor(\n [\n [-aabb_scale[0][0], -aabb_scale[0][1], -aabb_scale[0][2]],\n [aabb_scale[1][0], aabb_scale[1][1], aabb_scale[1][2]],\n ],\n dtype=torch.float32,\n )\n )\n\n if \"camera_model\" in meta:\n camera_type = CAMERA_MODEL_TO_TYPE[meta[\"camera_model\"]]\n else:\n camera_type = CameraType.PERSPECTIVE\n\n idx_tensor = torch.tensor(indices, dtype=torch.long)\n fx = float(meta[\"fl_x\"]) if fx_fixed else torch.tensor(fx, dtype=torch.float32)[idx_tensor]\n fy = float(meta[\"fl_y\"]) if fy_fixed else torch.tensor(fy, dtype=torch.float32)[idx_tensor]\n cx = float(meta[\"cx\"]) if cx_fixed else torch.tensor(cx, dtype=torch.float32)[idx_tensor]\n cy = float(meta[\"cy\"]) if cy_fixed else torch.tensor(cy, dtype=torch.float32)[idx_tensor]\n height = int(meta[\"h\"]) if height_fixed else torch.tensor(height, dtype=torch.int32)[idx_tensor]\n width = int(meta[\"w\"]) if width_fixed else torch.tensor(width, dtype=torch.int32)[idx_tensor]\n if distort_fixed:\n distortion_params = camera_utils.get_distortion_params(\n k1=float(meta[\"k1\"]) if \"k1\" in meta else 0.0,\n k2=float(meta[\"k2\"]) if \"k2\" in meta else 0.0,\n k3=float(meta[\"k3\"]) if \"k3\" in meta else 0.0,\n k4=float(meta[\"k4\"]) if \"k4\" in meta else 0.0,\n p1=float(meta[\"p1\"]) if \"p1\" in meta else 0.0,\n p2=float(meta[\"p2\"]) if \"p2\" in meta else 0.0,\n )\n else:\n distortion_params = torch.stack(distort, dim=0)[idx_tensor]\n\n ## debug\n if split != \"train\":\n print(poses)\n\n def get_elem(t):\n if isinstance(t, (float, int)):\n return t\n if t.dim() == 0:\n return t.item()\n else:\n return get_elem(t[0])\n return t\n\n cameras = Cameras(\n fx=fx,\n fy=fy,\n cx=cx,\n cy=cy,\n distortion_params=distortion_params,\n height=height,\n width=width,\n camera_to_worlds=poses[:, :3, :4],\n camera_type=camera_type,\n )\n\n ## TODO: check this workaround\n self.downscale_factor = self.config.downscale_factor\n ## check if downscale needed\n cap = cv2.VideoCapture(str(video_filenames[0]))\n sample_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n sample_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n assert np.isclose(sample_width / sample_height, get_elem(width) / get_elem(height))\n calced_downscale_factor = get_elem(height) / sample_height\n cap.release()\n\n print(f\"loaded video size: ({sample_height}, {sample_width})\")\n\n if not np.isclose(calced_downscale_factor, self.downscale_factor):\n print(\"downscale provided is incorrect, changed to the real one calulated using the loaded video\")\n\n self.downscale_factor = calced_downscale_factor\n\n assert self.downscale_factor is not None\n cameras.rescale_output_resolution(scaling_factor=1.0 / self.downscale_factor)\n\n ndc_h = 2 * get_elem(fy) / get_elem(height)\n ndc_w = 2 * get_elem(fx) / get_elem(width)\n ndc_coeffs = (ndc_w, ndc_h)\n if self.config.invert_ndc_coeffs:\n ndc_coeffs = (ndc_h, ndc_w)\n\n ndc_near = self.config.ndc_near\n if ndc_near is None:\n ndc_near = -1.0 if not self.config.use_llff_poses else 1.0\n\n dataparser_outputs = VideoDataParserOutputs(\n data_dir=self.config.data,\n video_filenames=video_filenames,\n num_frames=num_frames,\n start_frame=start_frame,\n cameras=cameras,\n scene_box=scene_box,\n # mask_filenames=mask_filenames if len(mask_filenames) > 0 else None,\n dataparser_scale=scale_factor,\n dataparser_transform=transform_matrix,\n metadata={\n # \"depth_filenames\": depth_filenames if len(depth_filenames) > 0 else None,\n # \"depth_unit_scale_factor\": self.config.depth_unit_scale_factor,\n \"ndc_coeffs\": ndc_coeffs,\n \"ndc_near\": -1.0 if not self.config.use_llff_poses else 1.0,\n \"orientation\": self.config.orientation_method,\n \"use_llff_poses\": self.config.use_llff_poses,\n \"ndc_near_plane\": self.config.ndc_near_plane,\n \"ndc_far_plane\": self.config.ndc_far_plane,\n },\n )\n return dataparser_outputs" }, { "identifier": "VideoDataParserConfig", "path": "MSTH/dataparser.py", "snippet": "class VideoDataParserConfig(DataParserConfig):\n \"\"\"Nerfstudio dataset config\"\"\"\n\n _target: Type = field(default_factory=lambda: VideoDataParser)\n \"\"\"target class to instantiate\"\"\"\n data: Path = Path(\"/opt/czl/nerf/data/flame_salmon_videos\")\n \"\"\"Directory or explicit json file path specifying location of data.\"\"\"\n scale_factor: float = 1.0\n \"\"\"How much to scale the camera origins by.\"\"\"\n downscale_factor: Optional[int] = 1\n \"\"\"How much to downscale images. If not set, images are chosen such that the max dimension is <1600px.\"\"\"\n scene_scale: Union[float, List[float]] = 1.0\n \"\"\"How much to scale the region of interest by.\"\"\"\n orientation_method: Literal[\"pca\", \"up\", \"none\"] = \"up\"\n \"\"\"The method to use for orientation.\"\"\"\n center_poses: bool = True\n \"\"\"Whether to center the poses.\"\"\"\n auto_scale_poses: bool = True\n \"\"\"Whether to automatically scale the poses to fit in +/- 1 bounding box.\"\"\"\n train_split_fraction: float = 0.9\n \"\"\"The fraction of images to use for training. The remaining images are for eval.\"\"\"\n depth_unit_scale_factor: float = 1e-3\n \"\"\"Scales the depth values to meters. Default value is 0.001 for a millimeter to meter conversion.\"\"\"\n use_llff_poses: bool = False\n convert_pose: bool = True\n # convert pose from opencv to opengl when use llff poses\n offset: Optional[List[float]] = None\n set_camera_plane: bool = False\n look_along_positive: bool = False\n look_axis: int = -1\n invert_ndc_coeffs: bool = False\n ndc_near: Optional[float] = None\n ndc_near_plane: float = 0.0\n ndc_far_plane: float = 1.0\n is_trf_pose: bool = False" }, { "identifier": "VideoDataParserOutputs", "path": "MSTH/dataparser.py", "snippet": "class VideoDataParserOutputs:\n data_dir: Path\n video_filenames: List[Path]\n start_frame: int\n num_frames: int\n \"\"\"Dataparser outputs for the which will be used by the DataManager\n for creating RayBundle and RayGT objects.\"\"\"\n\n \"\"\"Filenames for the images.\"\"\"\n cameras: Cameras\n \"\"\"Camera object storing collection of camera information in dataset.\"\"\"\n alpha_color: Optional[TensorType[3]] = None\n \"\"\"Color of dataset background.\"\"\"\n scene_box: SceneBox = SceneBox()\n \"\"\"Scene box of dataset. Used to bound the scene or provide the scene scale depending on model.\"\"\"\n mask_filenames: Optional[List[Path]] = None\n \"\"\"Filenames for any masks that are required\"\"\"\n metadata: Dict[str, Any] = to_immutable_dict({})\n \"\"\"Dictionary of any metadata that be required for the given experiment.\n Will be processed by the InputDataset to create any additional tensors that may be required.\n \"\"\"\n dataparser_transform: TensorType[3, 4] = torch.eye(4)[:3, :]\n \"\"\"Transform applied by the dataparser.\"\"\"\n dataparser_scale: float = 1.0\n \"\"\"Scale applied by the dataparser.\"\"\"\n\n def as_dict(self) -> dict:\n \"\"\"Returns the dataclass as a dictionary.\"\"\"\n return vars(self)\n\n def save_dataparser_transform(self, path: Path):\n \"\"\"Save dataparser transform to json file. Some dataparsers will apply a transform to the poses,\n this method allows the transform to be saved so that it can be used in other applications.\n\n Args:\n path: path to save transform to\n \"\"\"\n data = {\n \"transform\": self.dataparser_transform.tolist(),\n \"scale\": float(self.dataparser_scale),\n }\n if not path.parent.exists():\n path.parent.mkdir(parents=True)\n with open(path, \"w\", encoding=\"UTF-8\") as file:\n json.dump(data, file, indent=4)" }, { "identifier": "VideoDataset", "path": "MSTH/dataset.py", "snippet": "class VideoDataset(Dataset):\n def __init__(\n self,\n dataparser_outputs: VideoDataParserOutputs,\n scale_factor: float = 1.0,\n mask_extend_radius: int = 5,\n next_n_frames: int = 1,\n ) -> None:\n super().__init__()\n self._dataparser_outputs = dataparser_outputs\n self.scale_factor = scale_factor\n\n self.scene_box = deepcopy(dataparser_outputs.scene_box)\n self.metadata = deepcopy(dataparser_outputs.metadata)\n self.cameras = deepcopy(dataparser_outputs.cameras)\n self.cameras.rescale_output_resolution(scaling_factor=scale_factor)\n self.vcs = []\n # TODO: maybe add h and w to dataparseroutputs ?\n self.h = self.cameras.height[0][0].item()\n assert isinstance(self.h, int), \"support only all the inputs share same size\"\n self.w = self.cameras.width[0][0].item()\n self._prepare_video_captures()\n self.next_n_frames = next_n_frames\n if next_n_frames > 1:\n self.load_first_n_frames()\n else:\n self.load_first_frame()\n self.mask_extend_radius = mask_extend_radius\n # TODO: add support on starting from a specific frame for resuming training\n\n def _prepare_video_captures(self):\n \"\"\"loading video captures\"\"\"\n print(\"loading video captures ...\")\n for video_filename in self._dataparser_outputs.video_filenames:\n self.vcs.append(cv2.VideoCapture(str(video_filename)))\n self.num_cams = len(self.vcs)\n self.num_frames = self._dataparser_outputs.num_frames\n self.start_frame = self._dataparser_outputs.start_frame\n\n # TODO: check image format\n self.cur_frame_buffer = np.zeros([self.num_cams, self.h, self.w, 3], dtype=np.float32)\n self.prev_frame_buffer = np.zeros([self.num_cams, self.h, self.w, 3], dtype=np.float32)\n self.next_frame_buffer = np.zeros([self.num_cams, self.h, self.w, 3], dtype=np.float32)\n\n self.next_frame_loading_results = None\n self.cur_frame = 0\n\n # depretade\n # def _calc_mask(self):\n # \"\"\"assuming cur_frame and last_frame is set correctly\"\"\"\n # # TODO: add how to calc diff here\n # print(self.cur_frame_buffer.shape)\n # with Timer(\"calc norm\"):\n # diff = torch.from_numpy(np.linalg.norm(self.cur_frame_buffer - self.prev_frame_buffer, ord=2, axis=-1))\n # # TODO: add threshold here\n # mask_threshold = torch.mean(diff)\n # self.mask = torch.where(diff > mask_threshold, 1, 0)\n\n def __len__(self):\n return len(self._dataparser_outputs.video_filenames)\n\n def load_first_frame(self):\n print(\"loading first image ...\")\n for idx in range(self.num_cams):\n success, self.cur_frame_buffer[idx] = self.vcs[idx].read()\n assert success\n # self.cur_frame_buffer[idx] = cv2.cvtColor(self.cur_frame_buffer[idx], cv2.COLOR_BGR2RGB)\n self.cur_frame_buffer[idx] = self.cur_frame_buffer[idx][..., [2, 1, 0]]\n self.cur_frame = 1\n self.cur_frame_buffer /= 255.0\n self.mask = torch.ones([self.num_cams, self.h, self.w, 1])\n self.next_mask = torch.zeros([self.num_cams, self.h, self.w, 1])\n self.load_next_frame()\n assert self.next_frame_loading_results is not None\n\n def tick(self):\n if self.next_frame_loading_results is not None:\n concurrent.futures.wait(self.next_frame_loading_results)\n self.set_next_frame()\n self.load_next_frame()\n self.cur_frame += 1\n\n def set_next_frame(self):\n tmp = self.prev_frame_buffer\n self.prev_frame_buffer = self.cur_frame_buffer\n self.cur_frame_buffer = self.next_frame_buffer\n self.next_frame_buffer = tmp\n self.mask, self.next_mask = self.next_mask, self.mask\n\n def load_next_frame_worker(self, idx: int):\n \"\"\"worker function for setting next frame with idx-th camera\"\"\"\n success, self.next_frame_buffer[idx] = self.vcs[idx].read()\n assert success\n # self.next_frame_buffer[idx] = cv2.cvtColor(self.next_frame_buffer[idx], cv2.COLOR_BGR2RGB)\n self.next_frame_buffer[idx] = self.next_frame_buffer[idx][..., [2, 1, 0]]\n self.next_frame_buffer[idx] /= 255.0\n new_mask = np.linalg.norm(self.next_frame_buffer[idx] - self.cur_frame_buffer[idx], ord=np.inf, axis=-1)\n ## determine how to set threshold\n # mask_threshold = np.mean(new_mask) * 5.0\n # self.next_mask[idx] = torch.where(torch.from_numpy(new_mask) > mask_threshold, 1.0, 0.0)\n new_mask = get_mask_single_image(new_mask)\n # print(\"here\")\n # try:\n self.next_mask[idx] = extend_mask(new_mask, self.mask_extend_radius).unsqueeze(-1)\n\n def load_next_frame(self):\n self.next_frame_loading_results = []\n executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)\n for i in range(self.num_cams):\n self.next_frame_loading_results.append(executor.submit(self.load_next_frame_worker, i))\n\n # assert len(self.next_frame_loading_results) == self.num_cams\n\n def get_numpy_image(self, image_idx: int) -> npt.NDArray[np.uint8]:\n return self.cur_frame_buffer[image_idx]\n\n def get_image(self, image_idx: int) -> TensorType[\"image_height\", \"image_width\", \"num_channels\"]:\n image = torch.from_numpy(self.get_numpy_image(image_idx))\n assert image.size(-1) == 3\n\n return image\n\n def get_mask(self, image_idx: int) -> TensorType[\"image_height\", \"image_width\"]:\n return self.mask[image_idx]\n\n def load_next_n_frames_worker(self, next_n_frames, idx: int):\n for _ in range(next_n_frames - 1):\n success, _ = self.vcs[idx].read()\n assert success, \"load next frame failed !\"\n success, self.next_frame_buffer[idx] = self.vcs[idx].read()\n assert success\n # self.next_frame_buffer[idx] = cv2.cvtColor(self.next_frame_buffer[idx], cv2.COLOR_BGR2RGB)\n self.next_frame_buffer[idx] = self.next_frame_buffer[idx][..., [2, 1, 0]]\n self.next_frame_buffer[idx] /= 255.0\n new_mask = np.linalg.norm(self.next_frame_buffer[idx] - self.cur_frame_buffer[idx], ord=np.inf, axis=-1)\n ## determine how to set threshold\n\n new_mask = get_mask_single_image(new_mask)\n\n self.next_mask[idx] = extend_mask(new_mask, self.mask_extend_radius).unsqueeze(-1)\n\n def load_next_n_frames(self, next_n_frame: int):\n self.next_frame_loading_results = []\n executor = concurrent.futures.ThreadPoolExecutor(max_workers=os.cpu_count() - 1)\n for i in range(self.num_cams):\n self.next_frame_loading_results.append(executor.submit(self.load_next_n_frames_worker, next_n_frame, i))\n\n def load_first_n_frames(self):\n print(\"loading first image ...\")\n for idx in range(self.num_cams):\n success, self.cur_frame_buffer[idx] = self.vcs[idx].read()\n assert success\n # self.cur_frame_buffer[idx] = cv2.cvtColor(self.cur_frame_buffer[idx], cv2.COLOR_BGR2RGB)\n self.cur_frame_buffer[idx] = self.cur_frame_buffer[idx][..., [2, 1, 0]]\n self.cur_frame = 1\n self.cur_frame_buffer /= 255.0\n self.mask = torch.ones([self.num_cams, self.h, self.w, 1])\n self.next_mask = torch.zeros([self.num_cams, self.h, self.w, 1])\n self.load_next_n_frames(self.next_n_frames)\n assert self.next_frame_loading_results is not None\n\n def tick_n_frames(self):\n if self.next_frame_loading_results is not None:\n concurrent.futures.wait(self.next_frame_loading_results)\n self.set_next_frame()\n self.load_next_n_frames(self.next_n_frames)\n self.cur_frame += 1\n\n def __del__(self):\n for vc in self.vcs:\n vc.release()\n\n def get_all_data(self, device: Union[torch.device, str] = \"cpu\") -> Dict[str, TensorType]:\n return get_dict_to_torch(\n {\"image\": torch.from_numpy(self.cur_frame_buffer), \"mask\": self.mask}, device, exclude=[\"image\"]\n )\n\n def __getitem__(self, index) -> Dict:\n return {\"image\": self.get_image(index), \"mask\": self.get_mask(index)}" }, { "identifier": "VideoDatasetWithFeature", "path": "MSTH/dataset.py", "snippet": "class VideoDatasetWithFeature(Dataset):\n def __init__(\n self,\n dataparser_outputs: VideoDataParserOutputs,\n scale_factor: float = 1.0,\n mask_extend_radius: int = 5,\n next_n_frames: int = 1,\n pretrained_path: Union[str, Path] = \"\",\n fe_device: Union[str, torch.device] = \"cuda\",\n ) -> None:\n super().__init__()\n self._dataparser_outputs = dataparser_outputs\n self.scale_factor = scale_factor\n\n self.scene_box = deepcopy(dataparser_outputs.scene_box)\n self.metadata = deepcopy(dataparser_outputs.metadata)\n self.cameras = deepcopy(dataparser_outputs.cameras)\n self.cameras.rescale_output_resolution(scaling_factor=scale_factor)\n self.fe_device = fe_device\n self.feature_extractor = ResUNet.load_from_pretrained(pretrained_path)\n self.feature_extractor.to(self.fe_device)\n self.vcs = []\n # TODO: maybe add h and w to dataparseroutputs ?\n self.h = self.cameras.height[0][0].item()\n assert isinstance(self.h, int), \"support only all the inputs share same size\"\n self.w = self.cameras.width[0][0].item()\n self._prepare_video_captures()\n self.next_n_frames = next_n_frames\n self.load_first_frame()\n # self._build_feats()\n self.mask_extend_radius = mask_extend_radius\n # TODO: add support on starting from a specific frame for resuming training\n\n def _prepare_video_captures(self):\n \"\"\"loading video captures\"\"\"\n print(\"loading video captures ...\")\n for video_filename in self._dataparser_outputs.video_filenames:\n self.vcs.append(cv2.VideoCapture(str(video_filename)))\n self.num_cams = len(self.vcs)\n self.num_frames = self._dataparser_outputs.num_frames\n self.start_frame = self._dataparser_outputs.start_frame\n\n # TODO: check image format\n self.cur_frame_buffer = np.zeros([self.num_cams, self.h, self.w, 3], dtype=np.float32)\n self.prev_frame_buffer = np.zeros([self.num_cams, self.h, self.w, 3], dtype=np.float32)\n self.next_frame_buffer = np.zeros([self.num_cams, self.h, self.w, 3], dtype=np.float32)\n\n self.next_frame_loading_results = None\n self.cur_frame = 0\n\n def __len__(self):\n return len(self._dataparser_outputs.video_filenames)\n\n def load_first_frame(self):\n print(\"loading first image ...\")\n for idx in range(self.num_cams):\n success, self.cur_frame_buffer[idx] = self.vcs[idx].read()\n assert success\n # self.cur_frame_buffer[idx] = cv2.cvtColor(self.cur_frame_buffer[idx], cv2.COLOR_BGR2RGB)\n self.cur_frame_buffer[idx] = self.cur_frame_buffer[idx][..., [2, 1, 0]]\n self.cur_frame = 1\n self.cur_frame_buffer /= 255.0\n self.mask = torch.ones([self.num_cams, self.h, self.w, 1])\n self.next_mask = torch.zeros([self.num_cams, self.h, self.w, 1])\n self.load_next_frame()\n self.extract_cur_frame_feature()\n assert self.next_frame_loading_results is not None\n\n def tick(self):\n if self.next_frame_loading_results is not None:\n concurrent.futures.wait(self.next_frame_loading_results)\n self.set_next_frame()\n self.load_next_frame()\n self.cur_frame += 1\n\n def set_next_frame(self):\n tmp = self.prev_frame_buffer\n self.prev_frame_buffer = self.cur_frame_buffer\n self.cur_frame_buffer = self.next_frame_buffer\n self.next_frame_buffer = tmp\n self.mask, self.next_mask = self.next_mask, self.mask\n\n def load_next_frame_worker(self, idx: int):\n \"\"\"worker function for setting next frame with idx-th camera\"\"\"\n success, self.next_frame_buffer[idx] = self.vcs[idx].read()\n assert success\n # self.next_frame_buffer[idx] = cv2.cvtColor(self.next_frame_buffer[idx], cv2.COLOR_BGR2RGB)\n self.next_frame_buffer[idx] = self.next_frame_buffer[idx][..., [2, 1, 0]]\n self.next_frame_buffer[idx] /= 255.0\n new_mask = np.linalg.norm(self.next_frame_buffer[idx] - self.cur_frame_buffer[idx], ord=np.inf, axis=-1)\n ## determine how to set threshold\n # mask_threshold = np.mean(new_mask) * 5.0\n # self.next_mask[idx] = torch.where(torch.from_numpy(new_mask) > mask_threshold, 1.0, 0.0)\n new_mask = get_mask_single_image(new_mask)\n # print(\"here\")\n # try:\n self.next_mask[idx] = extend_mask(new_mask, self.mask_extend_radius).unsqueeze(-1)\n\n # print(\"hello\")\n\n def load_next_frame(self):\n self.next_frame_loading_results = []\n executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)\n for i in range(self.num_cams):\n self.next_frame_loading_results.append(executor.submit(self.load_next_frame_worker, i))\n\n # assert len(self.next_frame_loading_results) == self.num_cams\n\n def get_numpy_image(self, image_idx: int) -> npt.NDArray[np.uint8]:\n return self.cur_frame_buffer[image_idx]\n\n def get_image(self, image_idx: int) -> TensorType[\"image_height\", \"image_width\", \"num_channels\"]:\n image = torch.from_numpy(self.get_numpy_image(image_idx))\n assert image.size(-1) == 3\n\n return image\n\n def get_mask(self, image_idx: int) -> TensorType[\"image_height\", \"image_width\"]:\n return self.mask[image_idx]\n\n def load_next_n_frames_worker(self, next_n_frames, idx: int):\n for _ in range(next_n_frames - 1):\n success, _ = self.vcs[idx].read()\n assert success, \"load next frame failed !\"\n success, self.next_frame_buffer[idx] = self.vcs[idx].read()\n assert success\n # self.next_frame_buffer[idx] = cv2.cvtColor(self.next_frame_buffer[idx], cv2.COLOR_BGR2RGB)\n self.next_frame_buffer[idx] = self.next_frame_buffer[idx][..., [2, 1, 0]]\n self.next_frame_buffer[idx] /= 255.0\n new_mask = np.linalg.norm(self.next_frame_buffer[idx] - self.cur_frame_buffer[idx], ord=np.inf, axis=-1)\n ## determine how to set threshold\n\n new_mask = get_mask_single_image(new_mask)\n\n self.next_mask[idx] = extend_mask(new_mask, self.mask_extend_radius).unsqueeze(-1)\n\n def extract_cur_frame_feature(self):\n self.device_cur_frame = torch.from_numpy(self.cur_frame_buffer).to(self.fe_device)\n\n num_images = self.cur_frame_buffer.shape[0]\n self.cur_frame_feats_buffer = torch.zeros(self.device_cur_frame.shape[:-1] + (32,))\n mini_bs = 2\n for start in range(0, num_images, mini_bs):\n end = min(num_images, start + mini_bs)\n self.cur_frame_feats_buffer[start:end] = self.feature_extractor(self.device_cur_frame[start:end])[1].to(\n \"cpu\"\n )\n\n # set to zero array for testing\n # self.cur_frame_feats_buffer = torch.zeros(self.cur_frame_buffer.shape[:-1] + (32,))\n\n print(\"feature shape: \", self.cur_frame_feats_buffer.shape)\n\n def _build_feats(self):\n # workaround for test\n self.cur_frame_feats_buffer = torch.zeros(self.cur_frame_buffer.shape[:-1] + (32,))\n\n def get_all_data(self, device: Union[torch.device, str] = \"cpu\") -> Dict[str, TensorType]:\n return get_dict_to_torch(\n {\"image\": torch.from_numpy(self.cur_frame_buffer), \"mask\": self.mask}, device, exclude=[\"image\"]\n )\n\n def __getitem__(self, index) -> Dict:\n return {\"image\": self.get_image(index), \"mask\": self.get_mask(index)}" }, { "identifier": "VideoDatasetAllCached", "path": "MSTH/dataset.py", "snippet": "class VideoDatasetAllCached(Dataset):\n def __init__(\n self,\n dataparser_outputs: VideoDataParserOutputs,\n scale_factor: float = 1.0,\n mask_extend_radius: int = 5,\n use_mask: bool = False,\n ) -> None:\n super().__init__()\n self._dataparser_outputs = dataparser_outputs\n self.scale_factor = scale_factor\n self.mask_extend_radius = mask_extend_radius\n\n self.scene_box = deepcopy(dataparser_outputs.scene_box)\n self.metadata = deepcopy(dataparser_outputs.metadata)\n self.cameras = deepcopy(dataparser_outputs.cameras)\n self.cameras.rescale_output_resolution(scaling_factor=scale_factor)\n self.vcs = []\n # TODO: maybe add h and w to dataparseroutputs ?\n self.h = self.cameras.height[0][0].item()\n assert isinstance(self.h, int), \"support only all the inputs share same size\"\n self.w = self.cameras.width[0][0].item()\n self.num_cams = len(self._dataparser_outputs.video_filenames)\n self.num_frames = self._dataparser_outputs.num_frames\n self.use_mask = use_mask\n self.cache_all_frames()\n\n def cache_all_frames(self):\n self.frames = torch.zeros([self.num_cams, self._dataparser_outputs.num_frames, self.h, self.w, 3])\n\n if self.use_mask:\n self.masks = torch.zeros(\n [self.num_cams, self._dataparser_outputs.num_frames, self.h, self.w, 1], dtype=torch.bool\n )\n\n for i in trange(self.num_cams):\n vc = cv2.VideoCapture(str(self._dataparser_outputs.video_filenames[i]))\n for j in range(self.num_frames):\n suc, frame = vc.read()\n assert suc\n self.frames[i, j] = torch.from_numpy(frame[..., [2, 1, 0]]) / 255.0\n if self.use_mask:\n if j == 0:\n self.masks[i, j].fill_(False)\n else:\n self.masks[i, j] = torch.norm(self.frames[i, j] - self.frames[i, j - 1], p=np.inf, dim=-1)[\n ..., None\n ]\n self.masks[i, j] = get_mask_single_image(self.masks[i, j]).to(torch.bool)\n self.masks[i, j] = extend_mask(self.masks[i, j, ..., 0], self.mask_extend_radius)[..., None].to(\n torch.bool\n )\n\n def __len__(self):\n return len(self._dataparser_outputs.video_filenames)\n\n # def __getitem__(self, index):\n # return self.frames[index]" }, { "identifier": "VideoDatasetAllCachedUint8", "path": "MSTH/dataset.py", "snippet": "class VideoDatasetAllCachedUint8(Dataset):\n def __init__(\n self,\n dataparser_outputs: VideoDataParserOutputs,\n scale_factor: float = 1.0,\n mask_extend_radius: int = 5,\n use_mask: bool = True,\n use_median=False,\n ) -> None:\n super().__init__()\n self._dataparser_outputs = dataparser_outputs\n self.scale_factor = scale_factor\n self.use_mask = use_mask\n self.use_median = use_median\n\n self.scene_box = deepcopy(dataparser_outputs.scene_box)\n self.metadata = deepcopy(dataparser_outputs.metadata)\n self.cameras = deepcopy(dataparser_outputs.cameras)\n self.cameras.rescale_output_resolution(scaling_factor=scale_factor)\n # self.fe_device = fe_device\n # self.feature_extractor = ResUNet.load_from_pretrained(pretrained_path)\n # self.feature_extractor.to(self.fe_device)\n # self.vcs = []\n # TODO: maybe add h and w to dataparseroutputs ?\n self.h = self.cameras.height[0][0].item()\n assert isinstance(self.h, int), \"support only all the inputs share same size\"\n self.w = self.cameras.width[0][0].item()\n self.mask_extend_radius = mask_extend_radius\n self.num_cams = len(self._dataparser_outputs.video_filenames)\n self.num_frames = self._dataparser_outputs.num_frames\n self.cache_all_frames()\n\n def cache_all_frames(self):\n self.frames = torch.zeros(\n [self.num_cams, self._dataparser_outputs.num_frames, self.h, self.w, 3], dtype=torch.uint8\n )\n\n self.masks = torch.zeros(\n [self.num_cams, self._dataparser_outputs.num_frames, self.h, self.w, 1], dtype=torch.bool\n )\n\n for i in trange(self.num_cams):\n vc = cv2.VideoCapture(str(self._dataparser_outputs.video_filenames[i]))\n for j in range(self.num_frames):\n suc, frame = vc.read()\n assert suc\n self.frames[i, j] = torch.from_numpy(frame[..., [2, 1, 0]])\n\n if self.use_mask:\n masks_path = self._dataparser_outputs.data_dir / \"masks.pt\"\n if masks_path.exists():\n self.masks = torch.load(masks_path, map_location=\"cpu\")\n CONSOLE.log(\"load precomputed mask from {}\".format(str(masks_path)))\n else:\n self.masks = get_varianece_mask(self.frames, device=\"cuda\")\n torch.save(self.masks, masks_path)\n CONSOLE.log(\"Masks calced and saved since no cached masks found\")\n\n num_mask_pixels = torch.count_nonzero(self.masks).item()\n CONSOLE.log(\n f\"masked: {num_mask_pixels}/{self.masks.numel()}, rate: {num_mask_pixels/self.masks.numel():.2f}\"\n )\n\n if self.use_median:\n medians_path = self._dataparser_outputs.data_dir / \"medians.pt\"\n if medians_path.exists():\n self.medians = torch.load(medians_path, map_location=\"cpu\")\n CONSOLE.log(\"load precomputed median from {}\".format(str(medians_path)))\n else:\n self.medians = get_median(self.frames, device=\"cuda\")\n torch.save(self.medians, medians_path)\n CONSOLE.log(\"Medians calced and saved since no cached medians found\")\n\n def __getitem__(self, index):\n images = self.frames[index, 0].to(torch.float32) / 255.0\n return {\"image\": images}\n\n def __len__(self):\n return len(self._dataparser_outputs.video_filenames)" }, { "identifier": "CompletePixelSampler", "path": "MSTH/sampler.py", "snippet": "CONSOLE = Console(width=120)\n T = self.dataset.frames.shape[1]\n C, T, H, W = self.dataset.frames.shape[:-1]\nclass CompletePixelSamplerIter:\nclass CompletePixelSampler:\nclass PixelTimeUniformSampler_origin:\nclass PixelTimeUniformSampler:\nclass PixelTimeSampler:\nclass SpatioTemporalSampler:\nclass ISGSampler:\nclass ISTSampler:\nclass VarTemporalSampler:\nclass ErrorMapSampler:\n def __init__(self, num_rays_per_batch: int, image_batch: Dict, drop_last: bool = False) -> None:\n def set_batch(self, batch):\n def get_batch(self, indices: TensorType[\"num_rays_per_batch\", 3]):\n def __iter__(self):\n def __next__(self):\n def __init__(\n self, num_rays_per_batch: int, image_batch: Dict, drop_last: bool = False, use_mask: bool = True\n ) -> None:\n def set_batch(self, batch):\n def get_batch(self, indices: TensorType[\"num_rays_per_batch\", 3]):\n def _reset(self):\n def _reset_inverse(self):\n def sample(self):\n def sample_inverse(self):\n def __init__(\n self, dataset: VideoDatasetAllCached, num_rays_per_batch: int, drop_last: bool = False, use_mask: bool = True\n ) -> None:\n def get_batch(self, indices):\n def sample(self):\n def __init__(\n self, dataset: VideoDatasetAllCached, num_rays_per_batch: int, drop_last: bool = False, use_mask: bool = True\n ) -> None:\n def get_batch(self, indices):\n def sample(self):\n def set_num_rays_per_batch(self, num_rays_per_batch):\n def __init__(\n self,\n dataset: Union[VideoDatasetAllCached, VideoDatasetAllCachedUint8],\n num_rays_per_batch: int,\n static_dynamic_ratio,\n drop_last: bool = False,\n static_dynamic_ratio_end=None,\n total_steps=None,\n ) -> None:\n def set_static_dynamic_ratio(self):\n def _reset_static(self):\n def _reset_dynamic(self):\n def static_sample_indices(self):\n def dynamic_sample_indices(self):\n def get_batch(self, indices):\n def sample(self):\n def set_num_rays_per_batch(self, num_rays_per_batch):\n def __init__(\n self,\n dataset: Union[VideoDatasetAllCached, VideoDatasetAllCachedUint8],\n num_rays_per_batch: int,\n static_dynamic_ratio,\n drop_last: bool = False,\n static_dynamic_ratio_end=None,\n total_steps=None,\n n_time_for_dynamic=lambda x: 1,\n use_temporal_weight=\"none\",\n ) -> None:\n def set_static_dynamic_ratio(self):\n def _reset_static(self):\n def _reset_dynamic(self):\n def static_sample_indices(self):\n def dynamic_sample_indices(self):\n def get_batch(self, indices, is_static):\n def sample(self):\n def __init__(\n self, dataset, num_rays_per_batch, num_rays_per_pixel, gamma, alpha_fn, use_spatial_uniform, sd_ratio_fn\n ) -> None:\n def _update(self):\n def _reset_static(self):\n def _reset_dynamic(self):\n def static_sample_indices(self):\n def dynamic_sample_indices(self):\n def sample(self):\n def __init__(self) -> None:\n def __init__(\n self,\n dataset,\n num_rays_per_batch,\n sreso,\n treso,\n ema_coeff,\n stratified_on_cams,\n static_init,\n replacement,\n device,\n ) -> None:\n def update(self, batch, error):\n def get_batch(self, indices, extras=None):\n def sample(self):" }, { "identifier": "Timer", "path": "MSTH/utils.py", "snippet": "class Timer:\n recorder = defaultdict(list)\n\n def __init__(self, des=\"\", verbose=True, record=False) -> None:\n self.des = des\n self.verbose = verbose\n self.record = record\n\n def __enter__(self):\n return self\n self.start = time.time()\n self.start_cuda = torch.cuda.Event(enable_timing=True)\n self.end_cuda = torch.cuda.Event(enable_timing=True)\n self.start_cuda.record()\n return self\n\n def __exit__(self, *args):\n return\n self.end = time.time()\n self.end_cuda.record()\n self.interval = self.end - self.start\n if self.verbose:\n torch.cuda.synchronize()\n print(f\"[cudasync]{self.des} consuming {self.start_cuda.elapsed_time(self.end_cuda)/1000.:.8f}\")\n\n print(f\"{self.des} consuming {self.interval:.8f}\")\n if self.record:\n Timer.recorder[self.des].append(self.interval)\n\n @staticmethod\n def show_recorder():\n pprint(Timer.recorder)" } ]
import random import torch import os from dataclasses import dataclass, field from typing import Dict, List, Optional, Tuple, Type, Union from typing import Literal, Callable from typing_extensions import Literal from pathlib import Path from rich.progress import Console from torch.nn.parameter import Parameter from torch.utils.data.dataloader import DataLoader from nerfstudio.cameras.camera_optimizers import CameraOptimizerConfig from nerfstudio.cameras.rays import RayBundle from nerfstudio.data.datamanagers.base_datamanager import DataManager, DataManagerConfig from nerfstudio.data.pixel_samplers import PixelSampler from nerfstudio.data.utils.nerfstudio_collate import nerfstudio_collate from nerfstudio.model_components.ray_generators import RayGenerator from MSTH.dataparser import ( VideoDataParser, VideoDataParserConfig, VideoDataParserOutputs, ) from MSTH.dataset import VideoDataset, VideoDatasetWithFeature, VideoDatasetAllCached, VideoDatasetAllCachedUint8 from MSTH.sampler import ( CompletePixelSampler, CompletePixelSamplerIter, PixelTimeSampler, PixelTimeUniformSampler, spacetime_samplers, spacetime_samplers_default_args, PixelTimeUniformSampler_origin, SpatioTemporalSampler, ) from MSTH.utils import Timer
19,872
try: except ImportError: # from MSTH.dataset import EvalVideoDataset, VideoDataset CONSOLE = Console(width=120) @dataclass class VideoDataManagerConfig(DataManagerConfig): """Video Data Manager config""" _target: Type = field(default_factory=lambda: VideoDataManager) dataparser: VideoDataParserConfig = VideoDataParserConfig() collate_fn = staticmethod(nerfstudio_collate) """Specifies the collate function to use for the train and eval dataloaders.""" camera_res_scale_factor: float = 1.0 train_num_rays_per_batch: int = 1024 eval_num_rays_per_batch: int = 1024 camera_optimizer: CameraOptimizerConfig = CameraOptimizerConfig() mask_extend_radius: int = 5 next_n_frames: int = 1 """mask extend radius for gaussian filter""" class VideoDataManager(DataManager): train_dataset: VideoDataset eval_dataset: VideoDataset
try: except ImportError: # from MSTH.dataset import EvalVideoDataset, VideoDataset CONSOLE = Console(width=120) @dataclass class VideoDataManagerConfig(DataManagerConfig): """Video Data Manager config""" _target: Type = field(default_factory=lambda: VideoDataManager) dataparser: VideoDataParserConfig = VideoDataParserConfig() collate_fn = staticmethod(nerfstudio_collate) """Specifies the collate function to use for the train and eval dataloaders.""" camera_res_scale_factor: float = 1.0 train_num_rays_per_batch: int = 1024 eval_num_rays_per_batch: int = 1024 camera_optimizer: CameraOptimizerConfig = CameraOptimizerConfig() mask_extend_radius: int = 5 next_n_frames: int = 1 """mask extend radius for gaussian filter""" class VideoDataManager(DataManager): train_dataset: VideoDataset eval_dataset: VideoDataset
train_dataparser_outputs: VideoDataParserOutputs
9
2023-10-26 04:39:15+00:00
24k
chenruduan/OAReactDiff
oa_reactdiff/trainer/pl_trainer.py
[ { "identifier": "ProcessedQM9", "path": "oa_reactdiff/dataset/qm9.py", "snippet": "class ProcessedQM9(BaseQM9):\n def __init__(\n self,\n npz_path,\n center=True,\n pad_fragments=2,\n device=\"cpu\",\n zero_charge=False,\n remove_h=False,\n **kwargs,\n ):\n super().__init__(\n npz_path=npz_path,\n center=center,\n device=device,\n zero_charge=zero_charge,\n remove_h=remove_h,\n )\n\n self.n_fragments = pad_fragments + 1\n self.device = torch.device(device)\n\n n_samples = len(self.raw_dataset[\"charges\"])\n self.n_samples = n_samples\n\n self.data = {}\n self.process_molecules(\"raw_dataset\", n_samples, idx=0)\n\n for idx in range(pad_fragments):\n self.patch_dummy_molecules(idx + 1)\n\n self.data[\"condition\"] = [\n torch.zeros(\n size=(1, 1),\n dtype=torch.int64,\n device=self.device,\n )\n for _ in range(self.n_samples)\n ]" }, { "identifier": "ProcessedDoubleQM9", "path": "oa_reactdiff/dataset/qm9.py", "snippet": "class ProcessedDoubleQM9(BaseQM9):\n def __init__(\n self,\n npz_path,\n center=True,\n pad_fragments=1,\n device=\"cpu\",\n zero_charge=False,\n remove_h=False,\n **kwargs,\n ):\n super().__init__(\n npz_path=npz_path,\n center=center,\n device=device,\n zero_charge=zero_charge,\n remove_h=remove_h,\n )\n\n self.n_fragments = pad_fragments + 2\n self.device = torch.device(device)\n n_samples = len(self.raw_dataset[\"charges\"])\n self.n_samples = len(self.raw_dataset[\"charges\"])\n\n self.get_subsets()\n self.get_pairs()\n\n self.data = {}\n self.process_molecules(\"frag1_data\", n_samples, idx=0)\n self.process_molecules(\"frag2_data\", n_samples, idx=1)\n\n for idx in range(pad_fragments):\n self.patch_dummy_molecules(idx + 2)\n\n self.data[\"condition\"] = [\n torch.zeros(\n size=(1, 1),\n dtype=torch.int64,\n device=self.device,\n )\n for _ in range(self.n_samples)\n ]\n\n def get_pairs(self):\n self.frag1_data, self.frag2_data = {}, {}\n frag1_O_idx_1sthalf = np.random.choice(\n len(self.hasO_set[\"charges\"]),\n int(self.n_samples / 2),\n replace=True,\n )\n frag2_N_idx_1sthalf = np.random.choice(\n len(self.hasN_set[\"charges\"]),\n int(self.n_samples / 2),\n replace=True,\n )\n frag1_N_idx_2ndhalf = np.random.choice(\n len(self.hasN_set[\"charges\"]),\n int(self.n_samples / 2),\n replace=True,\n )\n frag2_O_idx_2ndhalf = np.random.choice(\n len(self.hasO_set[\"charges\"]),\n int(self.n_samples / 2),\n replace=True,\n )\n self.frag1_data = {\n key: np.concatenate(\n [\n self.hasO_set[key][frag1_O_idx_1sthalf],\n self.hasN_set[key][frag1_N_idx_2ndhalf],\n ],\n axis=0,\n )\n for key in self.raw_dataset\n }\n self.frag2_data = {\n key: np.concatenate(\n [\n self.hasN_set[key][frag2_N_idx_1sthalf],\n self.hasO_set[key][frag2_O_idx_2ndhalf],\n ],\n axis=0,\n )\n for key in self.raw_dataset\n }" }, { "identifier": "ProcessedTripleQM9", "path": "oa_reactdiff/dataset/qm9.py", "snippet": "class ProcessedTripleQM9(BaseQM9):\n def __init__(\n self,\n npz_path,\n center=True,\n pad_fragments=0,\n device=\"cpu\",\n zero_charge=False,\n remove_h=False,\n **kwargs,\n ):\n super().__init__(\n npz_path=npz_path,\n center=center,\n device=device,\n zero_charge=zero_charge,\n remove_h=remove_h,\n )\n\n self.n_fragments = pad_fragments + 3\n self.device = torch.device(device)\n n_samples = len(self.raw_dataset[\"charges\"])\n self.n_samples = len(self.raw_dataset[\"charges\"])\n\n self.get_subsets()\n self.get_pairs()\n\n self.data = {}\n self.process_molecules(\"frag1_data\", n_samples, idx=0)\n self.process_molecules(\"frag2_data\", n_samples, idx=1)\n self.process_molecules(\"frag3_data\", n_samples, idx=2)\n\n for idx in range(pad_fragments):\n self.patch_dummy_molecules(idx + 3)\n\n self.data[\"condition\"] = [\n torch.zeros(\n size=(1, 1),\n dtype=torch.int64,\n device=self.device,\n )\n for _ in range(self.n_samples)\n ]\n\n def get_pairs(self):\n n1 = int(self.n_samples / 3)\n n2 = int(self.n_samples / 3)\n n3 = self.n_samples - n1 - n2\n self.frag1_data, self.frag2_data = {}, {}\n frag1_O_idx_1_3 = np.random.choice(\n len(self.hasO_set[\"charges\"]),\n n1,\n replace=True,\n )\n frag2_N_idx_1_3 = np.random.choice(\n len(self.hasN_set[\"charges\"]),\n n1,\n replace=True,\n )\n frag3_F_idx_1_3 = np.random.choice(\n len(self.hasF_set[\"charges\"]),\n n1,\n replace=True,\n )\n frag1_F_idx_2_3 = np.random.choice(\n len(self.hasF_set[\"charges\"]),\n n2,\n replace=True,\n )\n frag2_O_idx_2_3 = np.random.choice(\n len(self.hasO_set[\"charges\"]),\n n2,\n replace=True,\n )\n frag3_N_idx_2_3 = np.random.choice(\n len(self.hasN_set[\"charges\"]),\n n2,\n replace=True,\n )\n frag1_N_idx_3_3 = np.random.choice(\n len(self.hasN_set[\"charges\"]),\n n3,\n replace=True,\n )\n frag2_F_idx_3_3 = np.random.choice(\n len(self.hasF_set[\"charges\"]),\n n3,\n replace=True,\n )\n frag3_O_idx_3_3 = np.random.choice(\n len(self.hasO_set[\"charges\"]),\n n3,\n replace=True,\n )\n self.frag1_data = {\n key: np.concatenate(\n [\n self.hasO_set[key][frag1_O_idx_1_3],\n self.hasF_set[key][frag1_F_idx_2_3],\n self.hasN_set[key][frag1_N_idx_3_3],\n ],\n axis=0,\n )\n for key in self.raw_dataset\n }\n self.frag2_data = {\n key: np.concatenate(\n [\n self.hasN_set[key][frag2_N_idx_1_3],\n self.hasO_set[key][frag2_O_idx_2_3],\n self.hasF_set[key][frag2_F_idx_3_3],\n ],\n axis=0,\n )\n for key in self.raw_dataset\n }\n self.frag3_data = {\n key: np.concatenate(\n [\n self.hasF_set[key][frag3_F_idx_1_3],\n self.hasN_set[key][frag3_N_idx_2_3],\n self.hasO_set[key][frag3_O_idx_3_3],\n ],\n axis=0,\n )\n for key in self.raw_dataset\n }" }, { "identifier": "ProcessedTS1x", "path": "oa_reactdiff/dataset/transition1x.py", "snippet": "class ProcessedTS1x(BaseDataset):\n def __init__(\n self,\n npz_path,\n center=True,\n pad_fragments=0,\n device=\"cpu\",\n zero_charge=False,\n remove_h=False,\n single_frag_only=True,\n swapping_react_prod=False,\n append_frag=False,\n reflection=False,\n use_by_ind=False,\n only_ts=False,\n confidence_model=False,\n position_key=\"positions\",\n ediff=None,\n **kwargs,\n ):\n super().__init__(\n npz_path=npz_path,\n center=center,\n device=device,\n zero_charge=zero_charge,\n remove_h=remove_h,\n )\n if confidence_model:\n use_by_ind = False\n if remove_h:\n print(\"remove_h is ignored because it is not reasonble for TS.\")\n if single_frag_only:\n single_frag_inds = np.where(\n np.array(self.raw_dataset[\"single_fragment\"]) == 1\n )[0]\n else:\n single_frag_inds = np.array(range(len(self.raw_dataset[\"single_fragment\"])))\n if use_by_ind:\n use_inds = self.raw_dataset[\"use_ind\"]\n else:\n use_inds = range(len(self.raw_dataset[\"single_fragment\"]))\n single_frag_inds = list(set(single_frag_inds).intersection(set(use_inds)))\n\n data_duplicated = copy.deepcopy(self.raw_dataset)\n for k, mapped_k in FRAG_MAPPING.items():\n for v, val in data_duplicated[k].items():\n self.raw_dataset[k][v] = [val[ii] for ii in single_frag_inds]\n if swapping_react_prod:\n mapped_val = data_duplicated[mapped_k][v]\n self.raw_dataset[k][v] += [\n mapped_val[ii] for ii in single_frag_inds\n ]\n if reflection:\n for k, mapped_k in FRAG_MAPPING.items():\n for v, val in self.raw_dataset[k].items():\n if v in [\"wB97x_6-31G(d).forces\", position_key]:\n self.raw_dataset[k][v] += [reflect_z(_val) for _val in val]\n else:\n self.raw_dataset[k][v] += val\n\n self.reactant = self.raw_dataset[\"reactant\"]\n self.transition_state = self.raw_dataset[\"transition_state\"]\n self.product = self.raw_dataset[\"product\"]\n\n self.n_fragments = pad_fragments + 3\n self.device = torch.device(device)\n n_samples = len(self.reactant[\"charges\"])\n self.n_samples = len(self.reactant[\"charges\"])\n\n self.data = {}\n repeat = 2 if swapping_react_prod else 1\n if confidence_model:\n self.data[\"target\"] = torch.tensor(\n self.raw_dataset[\"target\"] * repeat\n ).unsqueeze(1)\n self.data[\"rmsd\"] = torch.tensor(\n self.raw_dataset[\"rmsd\"] * repeat\n ).unsqueeze(1)\n if ediff is not None:\n self.data[\"ediff\"] = torch.tensor(\n self.raw_dataset[ediff][\"ediff\"] * repeat\n ).unsqueeze(1)\n if not only_ts:\n if not append_frag:\n self.process_molecules(\n \"reactant\", n_samples, idx=0, position_key=position_key\n )\n self.process_molecules(\"transition_state\", n_samples, idx=1)\n self.process_molecules(\n \"product\", n_samples, idx=2, position_key=position_key\n )\n else:\n self.process_molecules(\n \"reactant\",\n n_samples,\n idx=0,\n append_charge=0,\n position_key=position_key,\n )\n self.process_molecules(\n \"transition_state\", n_samples, idx=1, append_charge=1\n )\n self.process_molecules(\n \"product\",\n n_samples,\n idx=2,\n append_charge=0,\n position_key=position_key,\n )\n\n for idx in range(pad_fragments):\n self.patch_dummy_molecules(idx + 3)\n else:\n if not append_frag:\n self.process_molecules(\"transition_state\", n_samples, idx=0)\n else:\n self.process_molecules(\n \"transition_state\", n_samples, idx=0, append_charge=1\n )\n # for idx in range(2):\n # self.patch_dummy_molecules(idx + 1)\n\n self.data[\"condition\"] = [\n torch.zeros(\n size=(1, 1),\n dtype=torch.int64,\n device=self.device,\n )\n for _ in range(self.n_samples)\n ]" }, { "identifier": "EGNNDynamics", "path": "oa_reactdiff/dynamics/egnn_dynamics.py", "snippet": "class EGNNDynamics(BaseDynamics):\n def __init__(\n self,\n model_config: Dict,\n fragment_names: List[str],\n node_nfs: List[int],\n edge_nf: int,\n condition_nf: int = 0,\n pos_dim: int = 3,\n update_pocket_coords: bool = True,\n condition_time: bool = True,\n edge_cutoff: Optional[float] = None,\n model: nn.Module = EGNN,\n device: torch.device = torch.device(\"cuda\"),\n enforce_same_encoding: Optional[List] = None,\n source: Optional[Dict] = None,\n ) -> None:\n r\"\"\"Base dynamics class set up for denoising process.\n\n Args:\n model_config (Dict): config for the equivariant model.\n fragment_names (List[str]): list of names for fragments\n node_nfs (List[int]): list of number of input node attributues.\n edge_nf (int): number of input edge attributes.\n condition_nf (int): number of attributes for conditional generation.\n Defaults to 0.\n pos_dim (int): dimension for position vector. Defaults to 3.\n update_pocket_coords (bool): whether to update positions of everything.\n Defaults to True.\n condition_time (bool): whether to condition on time. Defaults to True.\n edge_cutoff (Optional[float]): cutoff for building intra-fragment edges.\n Defaults to None.\n model (Optional[nn.Module]): Module for equivariant model. Defaults to None.\n \"\"\"\n super().__init__(\n model_config,\n fragment_names,\n node_nfs,\n edge_nf,\n condition_nf,\n pos_dim,\n update_pocket_coords,\n condition_time,\n edge_cutoff,\n model,\n device,\n enforce_same_encoding,\n source=source,\n )\n\n def forward(\n self,\n xh: List[Tensor],\n edge_index: Tensor,\n t: Tensor,\n conditions: Tensor,\n n_frag_switch: Tensor,\n combined_mask: Tensor,\n edge_attr: Optional[Tensor] = None,\n ) -> Tuple[List[Tensor], Tensor]:\n r\"\"\"predict noise /mu.\n\n Args:\n xh (List[Tensor]): list of concatenated tensors for pos and h\n edge_index (Tensor): [n_edge, 2]\n t (Tensor): time tensor. If dim is 1, same for all samples;\n otherwise different t for different samples\n conditions (Tensor): condition tensors\n n_frag_switch (Tensor): [n_nodes], fragment index for each nodes\n combined_mask (Tensor): [n_nodes], sample index for each node\n edge_attr (Optional[Tensor]): [n_edge, dim_edge_attribute]. Defaults to None.\n\n Raises:\n NotImplementedError: The fragement-position-fixed mode is not implement.\n\n Returns:\n Tuple[List[Tensor], Tensor]: updated pos-h and edge attributes\n \"\"\"\n pos = torch.concat(\n [_xh[:, : self.pos_dim].clone() for _xh in xh],\n dim=0,\n )\n h = torch.concat(\n [\n self.encoders[ii](xh[ii][:, self.pos_dim :].clone())\n for ii, name in enumerate(self.fragment_names)\n ],\n dim=0,\n )\n if self.edge_encoder is not None:\n edge_attr = self.edge_encoder(edge_attr)\n\n condition_dim = 0\n if self.condition_time:\n if len(t.size()) == 1:\n # t is the same for all elements in batch.\n h_time = torch.empty_like(h[:, 0:1]).fill_(t.item())\n else:\n # t is different over the batch dimension.\n h_time = t[combined_mask]\n h = torch.cat([h, h_time], dim=1)\n condition_dim += 1\n\n if self.condition_nf > 0:\n h_condition = conditions[combined_mask]\n h = torch.cat([h, h_condition], dim=1)\n condition_dim += self.condition_nf\n\n subgraph_mask = get_subgraph_mask(edge_index, n_frag_switch)\n if self.update_pocket_coords:\n update_coords_mask = None\n else:\n raise NotImplementedError # no need to mask pos for inpainting mode.\n\n h_final, pos_final, edge_attr_final = self.model(\n h,\n pos,\n edge_index,\n edge_attr,\n node_mask=None,\n edge_mask=None,\n update_coords_mask=update_coords_mask,\n subgraph_mask=subgraph_mask[:, None],\n )\n vel = pos_final - pos\n if torch.any(torch.isnan(vel)):\n print(\"Warning: detected nan in pos, resetting EGNN output to randn.\")\n vel = torch.randn_like(vel)\n if torch.any(torch.isnan(vel)):\n print(\"Warning: detected nan in h, resetting EGNN output to randn.\")\n h_final = torch.randn_like(h_final)\n\n h_final = h_final[:, :-condition_dim]\n\n frag_index = self.compute_frag_index(n_frag_switch)\n xh_final = [\n torch.cat(\n [\n self.remove_mean_batch(\n vel[frag_index[ii] : frag_index[ii + 1]],\n combined_mask[frag_index[ii] : frag_index[ii + 1]],\n ),\n self.decoders[ii](h_final[frag_index[ii] : frag_index[ii + 1]]),\n ],\n dim=-1,\n )\n for ii, name in enumerate(self.fragment_names)\n ]\n\n # xh_final = self.enpose_pbc(xh_final)\n\n if edge_attr_final is None or edge_attr_final.size(1) <= max(1, self.dist_dim):\n edge_attr_final = None\n else:\n edge_attr_final = self.edge_decoder(edge_attr_final)\n return xh_final, edge_attr_final\n\n @staticmethod\n def enpose_pbc(xh: List[Tensor], magnitude=10.0) -> List[Tensor]:\n xrange = magnitude * 2\n xh = [torch.remainder(_xh + magnitude, xrange) - magnitude for _xh in xh]\n return xh\n\n @staticmethod\n def compute_frag_index(n_frag_switch: Tensor) -> np.ndarray:\n counts = [\n torch.where(n_frag_switch == ii)[0].numel()\n for ii in torch.unique(n_frag_switch)\n ]\n return np.concatenate([np.array([0]), np.cumsum(counts)])\n\n @torch.no_grad()\n def adjust_edge_attr_on_new_eij(\n self,\n edge_index: Tensor,\n edge_attr: Tensor,\n edge_index_new: Tensor,\n ) -> Tensor:\n r\"\"\"Get ready new edge attributes (e_ij) given old {ij, e_ij} and new {ij}\n\n Args:\n edge_index (Tensor): ij\n edge_attr (Tensor): e_ij\n edge_index_new (Tensor): new ij\n\n Raises:\n ValueError: finding multiple entries for the same ij pair\n\n Returns:\n Tensor: new e_ij\n \"\"\"\n edge_index_T = torch.transpose(edge_index, 1, 0)\n edge_index_new_T = torch.transpose(edge_index_new, 1, 0)\n\n edge_attr_new = []\n for _ind, ij in enumerate(edge_index_new_T):\n ind = torch.where((ij == edge_index_T).all(dim=1))[0]\n if ind.size(0) > 1:\n raise ValueError(f\"ind should only be 0 or 1, getting {ind}\")\n\n if ind.size(0) == 0:\n self.create_new_edge_attr(\n ind_new=_ind,\n ij_new=ij,\n edge_index_new_T=edge_index_new_T,\n edge_attr_new=edge_attr_new,\n edge_attr=edge_attr,\n )\n else:\n edge_attr_new.append(edge_attr[ind.item()].detach())\n return torch.stack(edge_attr_new, dim=0)\n\n @staticmethod\n def init_edge_attr(sample_edge_attr):\n r\"\"\"initialize edge attributes.\"\"\"\n return torch.rand_like(sample_edge_attr)\n\n def create_new_edge_attr(\n self,\n ind_new: Tensor,\n ij_new: Tensor,\n edge_index_new_T: Tensor,\n edge_attr_new: List[Tensor],\n edge_attr: Tensor,\n ) -> List[Tensor]:\n r\"\"\"Create new edge attrbution for ij that is not present in old connections\n\n Args:\n ind_new (Tensor): natural index of new ij\n ij_new (Tensor): new ij\n edge_index_new_T (Tensor): new edge indexes, [n_edge, 2]\n edge_attr_new (List[Tensor]): list of new edge attributes\n edge_attr (Tensor): old edge attributes\n\n Raises:\n ValueError: not ji found for ij in new indexes\n\n Returns:\n List[Tensor]: list of new edge attributes\n \"\"\"\n ij_new_reverse = ij_new[torch.tensor([1, 0])]\n ind_new_reverse = torch.where((ij_new_reverse == edge_index_new_T).all(dim=1))[\n 0\n ]\n print(ind_new_reverse)\n if ind_new_reverse.size(0) == 0:\n raise ValueError(f\"should always find a reverse ind.\")\n # print(ij_new, ind_new, ind_new_reverse)\n if ind_new_reverse.item() >= ind_new:\n edge_attr_new.append(self.init_edge_attr(edge_attr[0]))\n else:\n edge_attr_new.append(edge_attr_new[ind_new_reverse.item()])\n return edge_attr_new\n\n @staticmethod\n def remove_mean_batch(x, indices):\n mean = scatter_mean(x, indices, dim=0)\n x = x - mean[indices]\n return x" }, { "identifier": "Confidence", "path": "oa_reactdiff/dynamics/confidence.py", "snippet": "class Confidence(BaseDynamics):\n def __init__(\n self,\n model_config: Dict,\n fragment_names: List[str],\n node_nfs: List[int],\n edge_nf: int,\n condition_nf: int = 0,\n pos_dim: int = 3,\n edge_cutoff: Optional[float] = None,\n model: nn.Module = EGNN,\n device: torch.device = torch.device(\"cuda\"),\n enforce_same_encoding: Optional[List] = None,\n source: Optional[Dict] = None,\n **kwargs,\n ) -> None:\n r\"\"\"Confindence score for generated samples.\n\n Args:\n model_config (Dict): config for the equivariant model.\n fragment_names (List[str]): list of names for fragments\n node_nfs (List[int]): list of number of input node attributues.\n edge_nf (int): number of input edge attributes.\n condition_nf (int): number of attributes for conditional generation.\n Defaults to 0.\n pos_dim (int): dimension for position vector. Defaults to 3.\n update_pocket_coords (bool): whether to update positions of everything.\n Defaults to True.\n condition_time (bool): whether to condition on time. Defaults to True.\n edge_cutoff (Optional[float]): cutoff for building intra-fragment edges.\n Defaults to None.\n model (Optional[nn.Module]): Module for equivariant model. Defaults to None.\n \"\"\"\n model_config.update({\"for_conf\": True})\n update_pocket_coords = True\n condition_time = (True,)\n super().__init__(\n model_config,\n fragment_names,\n node_nfs,\n edge_nf,\n condition_nf,\n pos_dim,\n update_pocket_coords,\n condition_time,\n edge_cutoff,\n model,\n device,\n enforce_same_encoding,\n source=source,\n )\n\n hidden_channels = model_config[\"hidden_channels\"]\n self.readout = GatedMLP(\n in_dim=hidden_channels,\n out_dims=[hidden_channels, hidden_channels, 1],\n activation=\"swish\",\n bias=True,\n last_layer_no_activation=True,\n )\n\n def _forward(\n self,\n xh: List[Tensor],\n edge_index: Tensor,\n t: Tensor,\n conditions: Tensor,\n n_frag_switch: Tensor,\n combined_mask: Tensor,\n edge_attr: Optional[Tensor] = None,\n ) -> Tensor:\n r\"\"\"predict confidence.\n\n Args:\n xh (List[Tensor]): list of concatenated tensors for pos and h\n edge_index (Tensor): [n_edge, 2]\n t (Tensor): time tensor. If dim is 1, same for all samples;\n otherwise different t for different samples\n conditions (Tensor): condition tensors\n n_frag_switch (Tensor): [n_nodes], fragment index for each nodes\n combined_mask (Tensor): [n_nodes], sample index for each node\n edge_attr (Optional[Tensor]): [n_edge, dim_edge_attribute]. Defaults to None.\n\n Raises:\n NotImplementedError: The fragement-position-fixed mode is not implement.\n\n Returns:\n Tensor: binary probability of confidence fo each graph.\n \"\"\"\n pos = torch.concat(\n [_xh[:, : self.pos_dim].clone() for _xh in xh],\n dim=0,\n )\n h = torch.concat(\n [\n self.encoders[ii](xh[ii][:, self.pos_dim :].clone())\n for ii, name in enumerate(self.fragment_names)\n ],\n dim=0,\n )\n if self.edge_encoder is not None:\n edge_attr = self.edge_encoder(edge_attr)\n\n condition_dim = 0\n if self.condition_time:\n if len(t.size()) == 1:\n # t is the same for all elements in batch.\n h_time = torch.empty_like(h[:, 0:1]).fill_(t.item())\n else:\n # t is different over the batch dimension.\n h_time = t[combined_mask]\n h = torch.cat([h, h_time], dim=1)\n condition_dim += 1\n\n if self.condition_nf > 0:\n h_condition = conditions[combined_mask]\n h = torch.cat([h, h_condition], dim=1)\n condition_dim += self.condition_nf\n\n subgraph_mask = get_subgraph_mask(edge_index, n_frag_switch)\n if self.update_pocket_coords:\n update_coords_mask = None\n else:\n raise NotImplementedError # no need to mask pos for inpainting mode.\n\n node_features = self.model(\n h,\n pos,\n edge_index,\n edge_attr,\n node_mask=None,\n edge_mask=None,\n update_coords_mask=update_coords_mask,\n subgraph_mask=subgraph_mask[:, None],\n ) # (n_node, n_hidden)\n\n graph_features = scatter_mean(\n node_features,\n index=combined_mask,\n dim=0,\n ) # (n_system, n_hidden)\n conf = self.readout(graph_features)\n return conf.squeeze()\n\n def forward(\n self,\n representations: List[Dict],\n conditions: Tensor,\n ):\n masks = [repre[\"mask\"] for repre in representations]\n combined_mask = torch.cat(masks)\n edge_index = get_edges_index(combined_mask, remove_self_edge=True)\n fragments_nodes = [repr[\"size\"] for repr in representations]\n n_frag_switch = get_n_frag_switch(fragments_nodes)\n\n xh = [\n torch.cat(\n [repre[feature_type] for feature_type in FEATURE_MAPPING],\n dim=1,\n )\n for repre in representations\n ]\n\n pred = self._forward(\n xh=xh,\n edge_index=edge_index,\n t=torch.tensor([0]),\n conditions=conditions,\n n_frag_switch=n_frag_switch,\n combined_mask=combined_mask,\n edge_attr=None,\n )\n return pred" }, { "identifier": "DiffSchedule", "path": "oa_reactdiff/diffusion/_schedule.py", "snippet": "class DiffSchedule(nn.Module):\n def __init__(self, gamma_module: nn.Module, norm_values: Tuple[float]) -> None:\n super().__init__()\n self.gamma_module = gamma_module\n self.norm_values = norm_values\n self.check_issues_norm_values()\n\n @staticmethod\n def inflate_batch_array(array, target):\n r\"\"\"\n Inflates the batch array (array) with only a single axis\n (i.e. shape = (batch_size,), or possibly more empty axes\n (i.e. shape (batch_size, 1, ..., 1)) to match the target shape.\n \"\"\"\n target_shape = (array.size(0),) + (1,) * (len(target.size()) - 1)\n return array.view(target_shape)\n\n def sigma(self, gamma, target_tensor):\n r\"\"\"Computes sigma given gamma.\"\"\"\n return self.inflate_batch_array(torch.sqrt(torch.sigmoid(gamma)), target_tensor)\n\n def alpha(self, gamma, target_tensor):\n r\"\"\"Computes alpha given gamma.\"\"\"\n return self.inflate_batch_array(\n torch.sqrt(torch.sigmoid(-gamma)), target_tensor\n )\n\n @staticmethod\n def SNR(gamma):\n r\"\"\"Computes signal to noise ratio (alpha^2/sigma^2) given gamma.\"\"\"\n return torch.exp(-gamma)\n\n def sigma_and_alpha_t_given_s(\n self, gamma_t: Tensor, gamma_s: Tensor, target_tensor: Tensor\n ) -> tuple[Tensor, Tensor, Tensor]:\n r\"\"\"\n Computes sigma t given s, using gamma_t and gamma_s. Used during sampling.\n These are defined as:\n alpha t given s = alpha t / alpha s,\n sigma t given s = sqrt(1 - (alpha t given s) ^2 ).\n \"\"\"\n sigma2_t_given_s = self.inflate_batch_array(\n -torch.expm1(F.softplus(gamma_s) - F.softplus(gamma_t)), target_tensor\n )\n\n # alpha_t_given_s = alpha_t / alpha_s\n log_alpha2_t = F.logsigmoid(-gamma_t)\n log_alpha2_s = F.logsigmoid(-gamma_s)\n log_alpha2_t_given_s = log_alpha2_t - log_alpha2_s\n\n alpha_t_given_s = torch.exp(0.5 * log_alpha2_t_given_s)\n alpha_t_given_s = self.inflate_batch_array(alpha_t_given_s, target_tensor)\n\n sigma_t_given_s = torch.sqrt(sigma2_t_given_s)\n\n return sigma2_t_given_s, sigma_t_given_s, alpha_t_given_s\n\n def check_issues_norm_values(self, num_stdevs=8):\n zeros = torch.zeros((1, 1))\n gamma_0 = self.gamma_module(zeros)\n sigma_0 = self.sigma(gamma_0, target_tensor=zeros).item()\n\n # Checked if 1 / norm_value is still larger than 10 * standard\n # deviation.\n norm_value = self.norm_values[1]\n\n if sigma_0 * num_stdevs > 1.0 / norm_value:\n raise ValueError(\n f\"Value for normalization value {norm_value} probably too \"\n f\"large with sigma_0 {sigma_0:.5f} and \"\n f\"1 / norm_value = {1. / norm_value}\"\n )" }, { "identifier": "PredefinedNoiseSchedule", "path": "oa_reactdiff/diffusion/_schedule.py", "snippet": "class PredefinedNoiseSchedule(nn.Module):\n r\"\"\"\n Predefined noise schedule. Essentially creates a lookup array for predefined\n (non-learned) noise schedules.\n \"\"\"\n\n def __init__(\n self,\n noise_schedule: str,\n timesteps: int,\n precision: float,\n ):\n super().__init__()\n self.timesteps = timesteps\n\n if \"cosine\" in noise_schedule:\n splits = noise_schedule.split(\"_\")\n assert len(splits) <= 2\n power = 1 if len(splits) == 1 else float(splits[1])\n alphas2 = cosine_beta_schedule(timesteps, raise_to_power=power)\n elif \"polynomial\" in noise_schedule:\n splits = noise_schedule.split(\"_\")\n assert len(splits) == 2\n power = float(splits[1])\n alphas2 = polynomial_schedule(timesteps, s=precision, power=power)\n elif \"csin\" in noise_schedule:\n splits = noise_schedule.split(\"_\")\n assert len(splits) == 4\n start, end, tau = float(splits[1]), float(splits[2]), float(splits[3])\n alphas2 = ccosine_schedule(timesteps, start=start, end=end, tau=tau)\n elif \"linear\" in noise_schedule:\n alphas2 = linear_schedule(timesteps)\n else:\n raise ValueError(noise_schedule)\n\n # print(\"alphas2\", alphas2)\n\n sigmas2 = 1 - alphas2\n\n log_alphas2 = np.log(alphas2)\n log_sigmas2 = np.log(sigmas2)\n\n log_alphas2_to_sigmas2 = log_alphas2 - log_sigmas2\n\n # print(\"gamma\", -log_alphas2_to_sigmas2)\n\n self.gamma = torch.nn.Parameter(\n torch.from_numpy(-log_alphas2_to_sigmas2).float(), requires_grad=False\n )\n\n def forward(self, t):\n t_int = torch.round(t * self.timesteps).long()\n return self.gamma[t_int]" }, { "identifier": "Normalizer", "path": "oa_reactdiff/diffusion/_normalizer.py", "snippet": "class Normalizer(nn.Module):\n def __init__(\n self,\n norm_values: Tuple = (1.0, 1.0, 1.0),\n norm_biases: Tuple = (0.0, 0.0, 0.0),\n pos_dim: int = 3,\n ) -> None:\n super().__init__()\n self.norm_values = norm_values\n self.norm_biases = norm_biases\n self.pos_dim = pos_dim\n\n def normalize(self, representations: List[Dict]) -> List[Dict]:\n for ii in range(len(representations)):\n for jj, feature_type in enumerate(FEATURE_MAPPING):\n representations[ii][feature_type] = (\n representations[ii][feature_type] - self.norm_biases[jj]\n ) / self.norm_values[jj]\n return representations\n\n def unnormalize(self, x: Tensor, ind: int) -> Tensor:\n return x * self.norm_values[ind] + self.norm_biases[ind]\n\n def unnormalize_z(self, z_combined: List[Tensor]) -> List[Tensor]:\n for ii in range(len(z_combined)):\n z_combined[ii][:, : self.pos_dim] = self.unnormalize(\n z_combined[ii][:, : self.pos_dim], 0\n )\n z_combined[ii][:, self.pos_dim : -1] = self.unnormalize(\n z_combined[ii][:, self.pos_dim : -1], 1\n )\n z_combined[ii][:, -1:] = self.unnormalize(z_combined[ii][:, -1:], 2)\n return z_combined" }, { "identifier": "FEATURE_MAPPING", "path": "oa_reactdiff/diffusion/_normalizer.py", "snippet": "FEATURE_MAPPING = [\"pos\", \"one_hot\", \"charge\"]" }, { "identifier": "EnVariationalDiffusion", "path": "oa_reactdiff/diffusion/en_diffusion.py", "snippet": "class EnVariationalDiffusion(nn.Module):\n \"\"\"\n The E(n) Diffusion Module.\n \"\"\"\n\n def __init__(\n self,\n dynamics: EGNNDynamics,\n schdule: DiffSchedule,\n normalizer: Normalizer,\n size_histogram: Optional[Dict] = None,\n loss_type: str = \"l2\",\n pos_only: bool = False,\n fixed_idx: Optional[List] = None,\n ):\n super().__init__()\n assert loss_type in {\"vlb\", \"l2\"}\n\n self.dynamics = dynamics\n self.schedule = schdule\n self.normalizer = normalizer\n self.size_histogram = size_histogram\n self.loss_type = loss_type\n self.pos_only = pos_only\n self.fixed_idx = fixed_idx or []\n\n self.pos_dim = dynamics.pos_dim\n self.node_nfs = dynamics.node_nfs\n self.fragment_names = dynamics.fragment_names\n self.T = schdule.gamma_module.timesteps\n self.norm_values = normalizer.norm_values\n self.norm_biases = normalizer.norm_biases\n\n # ------ FORWARD PASS ------\n\n def forward(\n self,\n representations: List[Dict],\n conditions: Tensor,\n return_pred: bool = False,\n ):\n r\"\"\"\n Computes the loss and NLL terms.\n\n #TODO: edge_attr not considered at all\n \"\"\"\n num_sample = representations[0][\"size\"].size(0)\n n_nodes = torch.stack(\n [repr[\"size\"] for repr in representations],\n dim=0,\n ).sum(dim=0)\n device = representations[0][\"pos\"].device\n masks = [repre[\"mask\"] for repre in representations]\n combined_mask = torch.cat(masks)\n edge_index = get_edges_index(combined_mask, remove_self_edge=True)\n fragments_nodes = [repr[\"size\"] for repr in representations]\n n_frag_switch = get_n_frag_switch(fragments_nodes)\n\n # Normalize data, take into account volume change in x.\n representations = self.normalizer.normalize(representations)\n\n # Likelihood change due to normalization\n delta_log_px = self.delta_log_px(n_nodes.sum())\n\n # Sample a timestep t for each example in batch\n # At evaluation time, loss_0 will be computed separately to decrease\n # variance in the estimator (costs two forward passes)\n lowest_t = 0 if self.training else 1\n t_int = torch.randint(\n lowest_t, self.T + 1, size=(num_sample, 1), device=device\n ).float()\n s_int = t_int - 1 # previous timestep\n\n # Masks: important to compute log p(x | z0).\n t_is_zero = (t_int == 0).float()\n t_is_not_zero = 1 - t_is_zero\n\n # Normalize t to [0, 1]. Note that the negative\n # step of s will never be used, since then p(x | z0) is computed.\n s = s_int / self.T\n t = t_int / self.T\n\n # Compute gamma_s and gamma_t via the network.\n gamma_s = self.schedule.inflate_batch_array(\n self.schedule.gamma_module(s), representations[0][\"pos\"]\n )\n gamma_t = self.schedule.inflate_batch_array(\n self.schedule.gamma_module(t), representations[0][\"pos\"]\n )\n\n # Concatenate x, and h[categorical].\n xh = [\n torch.cat(\n [repre[feature_type] for feature_type in FEATURE_MAPPING],\n dim=1,\n )\n for repre in representations\n ]\n\n # Find noised representation\n z_t, eps_xh = self.noised_representation(xh, masks, gamma_t)\n\n # Neural net prediction.\n net_eps_xh, net_eps_edge_attr = self.dynamics(\n xh=z_t,\n edge_index=edge_index,\n t=t,\n conditions=conditions,\n n_frag_switch=n_frag_switch,\n combined_mask=combined_mask,\n edge_attr=None, # TODO: no edge_attr is considered now\n )\n\n if return_pred:\n return eps_xh, net_eps_xh\n\n # TODO: LJ term not implemented\n # xh_lig_hat = self.xh_given_zt_and_epsilon(z_t_lig, net_out_lig, gamma_t,\n # ligand['mask'])\n if self.pos_only:\n for ii in range(len(masks)):\n net_eps_xh[ii][:, self.pos_dim :] = torch.zeros_like(\n net_eps_xh[ii][:, self.pos_dim :],\n device=device,\n )\n # Compute the L2 error.\n error_t: List[Tensor] = [\n utils.sum_except_batch(\n (eps_xh[ii] - net_eps_xh[ii]) ** 2,\n masks[ii],\n dim_size=num_sample,\n )\n for ii in range(len(masks))\n ] # TODO: no edge_attr contribution\n\n # Compute weighting with SNR: (1 - SNR(s-t)) for epsilon parametrization\n SNR_weight = (1 - self.schedule.SNR(gamma_s - gamma_t)).squeeze(1)\n assert error_t[0].size() == SNR_weight.size()\n\n # The _constants_ depending on sigma_0 from the\n # cross entropy term E_q(z0 | x) [log p(x | z0)].\n neg_log_constants = -self.log_constants_p_x_given_z0(\n n_nodes=n_nodes, device=device\n )\n\n # The KL between q(zT | x) and p(zT) = Normal(0, 1).\n # Should be close to zero.\n # kl_prior = self.kl_prior_with_pocket(\n # xh_lig, xh_pocket, ligand['mask'], pocket['mask'],\n # ligand['size'] + pocket['size'])\n # TODO: approximate KL prior with zero now, which should not influence training.\n kl_prior = torch.zeros_like(neg_log_constants)\n\n if self.training:\n # Computes the L_0 term (even if gamma_t is not actually gamma_0)\n # and this will later be selected via masking.\n log_p_h_given_z0 = self.log_pxh_given_z0_without_constants(\n representations=representations,\n z_t=z_t,\n eps_xh=eps_xh,\n net_eps_xh=net_eps_xh,\n gamma_t=gamma_t,\n epsilon=1e-10,\n )\n loss_0_x = [\n -_log_p_fragment * t_is_zero.squeeze()\n for _log_p_fragment in log_p_h_given_z0[0]\n ]\n loss_0_cat = [\n -_log_p_fragment * t_is_zero.squeeze()\n for _log_p_fragment in log_p_h_given_z0[1]\n ]\n loss_0_charge = [\n -_log_p_fragment * t_is_zero.squeeze()\n for _log_p_fragment in log_p_h_given_z0[2]\n ]\n\n # apply t_is_zero mask\n error_t = [_error_t * t_is_not_zero.squeeze() for _error_t in error_t]\n\n else:\n # Compute noise values for t = 0.\n t_zeros = torch.zeros_like(s)\n gamma_0 = self.schedule.inflate_batch_array(\n self.schedule.gamma_module(t_zeros), representations[0][\"pos\"]\n )\n\n # Sample z_0 given x, h for timestep t, from q(z_t | x, h)\n z_0, eps_0_xh = self.noised_representation(xh, masks, gamma_0)\n net_eps_0_xh, net_eps_0_edge_attr = self.dynamics(\n xh=z_0,\n edge_index=edge_index,\n t=t_zeros,\n conditions=conditions,\n n_frag_switch=n_frag_switch,\n combined_mask=combined_mask,\n edge_attr=None, # TODO: no edge_attr is considered now\n )\n\n log_p_h_given_z0 = self.log_pxh_given_z0_without_constants(\n representations=representations,\n z_t=z_0,\n eps_xh=eps_0_xh,\n net_eps_xh=net_eps_0_xh,\n gamma_t=gamma_0,\n epsilon=1e-10,\n )\n loss_0_x = [-_log_p_fragment for _log_p_fragment in log_p_h_given_z0[0]]\n loss_0_cat = [-_log_p_fragment for _log_p_fragment in log_p_h_given_z0[1]]\n loss_0_charge = [\n -_log_p_fragment for _log_p_fragment in log_p_h_given_z0[2]\n ]\n\n loss_terms = {\n \"delta_log_px\": delta_log_px,\n \"error_t\": error_t,\n \"SNR_weight\": SNR_weight,\n \"loss_0_x\": loss_0_x,\n \"loss_0_cat\": loss_0_cat,\n \"loss_0_charge\": loss_0_charge,\n \"neg_log_constants\": neg_log_constants,\n \"kl_prior\": kl_prior,\n \"log_pN\": torch.zeros_like(kl_prior),\n \"t_int\": t_int.squeeze(),\n \"net_eps_xh\": net_eps_xh,\n \"eps_xh\": eps_xh,\n }\n return loss_terms\n\n def delta_log_px(self, num_nodes):\n return -self.subspace_dimensionality(num_nodes) * np.log(self.norm_values[0])\n\n def subspace_dimensionality(self, input_size):\n r\"\"\"\n Compute the dimensionality on translation-invariant linear subspace\n where distributions on x are defined.\n \"\"\"\n return (input_size - 1) * self.pos_dim\n\n def noised_representation(\n self,\n xh: List[Tensor],\n masks: List[Tensor],\n gamma_t: Tensor,\n ) -> Tuple[List[Tensor], List[Tensor]]:\n # Compute alpha_t and sigma_t from gamma.\n alpha_t = self.schedule.alpha(gamma_t, xh[0])\n sigma_t = self.schedule.sigma(gamma_t, xh[0])\n\n # Sample zt ~ Normal(alpha_t x, sigma_t)\n eps_xh = self.sample_combined_position_feature_noise(masks)\n\n # Sample z_t given x, h for timestep t, from q(z_t | x, h)\n z_t = [\n alpha_t[masks[ii]] * xh[ii] + sigma_t[masks[ii]] * eps_xh[ii]\n for ii in range(len(masks))\n ]\n\n return z_t, eps_xh\n\n def sample_combined_position_feature_noise(\n self,\n masks: List[Tensor],\n ) -> List[Tensor]:\n r\"\"\"\n Samples mean-centered normal noise for z_x, and standard normal noise for z_h.\n Note that we only need to put the center of gravity of *each fragment* to the origin.\n \"\"\"\n eps_xh = []\n for ii, mask in enumerate(masks):\n _eps_x = utils.sample_center_gravity_zero_gaussian_batch(\n size=(len(mask), self.pos_dim),\n indices=[mask],\n )\n _eps_h = utils.sample_gaussian(\n size=(len(mask), self.node_nfs[ii] - self.pos_dim),\n device=mask.device,\n )\n if self.pos_only:\n _eps_h = torch.zeros_like(_eps_h, device=mask.device)\n eps_xh.append(torch.cat([_eps_x, _eps_h], dim=1))\n for idx in self.fixed_idx:\n eps_xh[idx] = torch.zeros_like(eps_xh[idx], device=mask.device)\n return eps_xh\n\n def log_constants_p_x_given_z0(self, n_nodes, device):\n r\"\"\"Computes p(x|z0).\"\"\"\n\n batch_size = len(n_nodes)\n degrees_of_freedom_x = self.subspace_dimensionality(n_nodes).to(device)\n\n zeros = torch.zeros((batch_size, 1), device=device)\n gamma_0 = self.schedule.gamma_module(zeros)\n\n # Recall that sigma_x = sqrt(sigma_0^2 / alpha_0^2) = SNR(-0.5 gamma_0).\n log_sigma_x = 0.5 * gamma_0.view(batch_size)\n return degrees_of_freedom_x * (-log_sigma_x - 0.5 * np.log(2 * np.pi))\n\n def kl_prior(self):\n return NotImplementedError\n\n @staticmethod\n def gaussian_KL(q_mu_minus_p_mu_squared, q_sigma, p_sigma, d):\n \"\"\"Computes the KL distance between two normal distributions.\n Args:\n q_mu_minus_p_mu_squared: Squared difference between mean of\n distribution q and distribution p: ||mu_q - mu_p||^2\n q_sigma: Standard deviation of distribution q.\n p_sigma: Standard deviation of distribution p.\n d: dimension\n Returns:\n The KL distance\n \"\"\"\n return (\n d * torch.log(p_sigma / q_sigma)\n + 0.5 * (d * q_sigma**2 + q_mu_minus_p_mu_squared) / (p_sigma**2)\n - 0.5 * d\n )\n\n def log_pxh_given_z0_without_constants(\n self,\n representations: List[Dict],\n z_t: List[Tensor],\n eps_xh: List[Tensor],\n net_eps_xh: List[Tensor],\n gamma_t: Tensor,\n epsilon: float = 1e-10,\n ) -> List[List[Tensor]]:\n # Compute sigma_0 and rescale to the integer scale of the data.\n # for pos\n log_p_x_given_z0_without_constants = [\n -0.5\n * (\n utils.sum_except_batch(\n (eps_xh[ii][:, : self.pos_dim] - net_eps_xh[ii][:, : self.pos_dim])\n ** 2,\n representations[ii][\"mask\"],\n dim_size=representations[0][\"size\"].size(0),\n )\n )\n for ii in range(len(representations))\n ]\n\n # only keep first several elements\n z_t = [_z_t[:, : 3 + 5 + 1] for _z_t in z_t]\n for ii, repr in enumerate(representations):\n representations[ii][\"charge\"] = representations[ii][\"charge\"][:, :1]\n # for ohe of atom types\n sigma_0 = self.schedule.sigma(gamma_t, target_tensor=z_t[0])\n sigma_0_cat = sigma_0 * self.normalizer.norm_values[1]\n atoms = [\n self.normalizer.unnormalize(repr[\"one_hot\"], ind=1)\n for repr in representations\n ]\n est_atoms = [\n self.normalizer.unnormalize(_z_t[:, self.pos_dim : -1], ind=1)\n for _z_t in z_t\n ]\n centered_atoms = [_est_atoms - 1 for _est_atoms in est_atoms]\n log_ph_cat_proportionals = [\n torch.log(\n utils.cdf_standard_gaussian(\n (centered_atoms[ii] + 0.5)\n / sigma_0_cat[representations[ii][\"mask\"]]\n )\n - utils.cdf_standard_gaussian(\n (centered_atoms[ii] - 0.5)\n / sigma_0_cat[representations[ii][\"mask\"]]\n )\n + epsilon\n )\n for ii in range(len(representations))\n ]\n log_probabilities = [\n _log_ph_cat_proportionals\n - torch.logsumexp(\n _log_ph_cat_proportionals,\n dim=1,\n keepdim=True,\n )\n for _log_ph_cat_proportionals in log_ph_cat_proportionals\n ]\n log_p_hcat_given_z0 = [\n utils.sum_except_batch(\n log_probabilities[ii] * atoms[ii],\n representations[ii][\"mask\"],\n dim_size=representations[0][\"size\"].size(0),\n )\n for ii in range(len(representations))\n ]\n\n # for atom charge\n sigma_0_charge = sigma_0 * self.normalizer.norm_values[2]\n charges = [\n self.normalizer.unnormalize(repr[\"charge\"], ind=2)\n for repr in representations\n ]\n est_charges = [\n self.normalizer.unnormalize(_z_t[:, -1:], ind=2).long() for _z_t in z_t\n ]\n for ii in range(len(representations)):\n assert charges[ii].size() == est_charges[ii].size()\n centered_charges = [\n charges[ii] - est_charges[ii] for ii in range(len(representations))\n ]\n log_ph_charge_proportionals = [\n torch.log(\n utils.cdf_standard_gaussian(\n (centered_charges[ii] + 0.5)\n / sigma_0_charge[representations[ii][\"mask\"]]\n )\n - utils.cdf_standard_gaussian(\n (centered_charges[ii] - 0.5)\n / sigma_0_charge[representations[ii][\"mask\"]]\n )\n + epsilon\n )\n for ii in range(len(representations))\n ]\n log_p_hcharge_given_z0 = [\n utils.sum_except_batch(\n log_ph_charge_proportionals[ii],\n representations[ii][\"mask\"],\n dim_size=representations[0][\"size\"].size(0),\n )\n for ii in range(len(representations))\n ]\n\n log_p_h_given_z0 = [\n log_p_x_given_z0_without_constants,\n log_p_hcat_given_z0,\n log_p_hcharge_given_z0,\n ]\n return log_p_h_given_z0\n\n # ------ INVERSE PASS ------\n\n @torch.no_grad()\n def sample(\n self,\n n_samples: int,\n fragments_nodes: List[torch.tensor],\n conditions: Optional[Tensor] = None,\n return_frames: int = 1,\n timesteps: Optional[int] = None,\n h0: Optional[List[Tensor]] = None,\n ):\n r\"\"\"\n Draw samples from the generative model. Optionally, return intermediate\n states for visualization purposes.\n \"\"\"\n timesteps = self.T if timesteps is None else timesteps\n assert 0 < return_frames <= timesteps\n assert timesteps % return_frames == 0\n assert h0 is not None if self.pos_only else True\n\n fragments_masks = [\n get_mask_for_frag(natm_nodes) for natm_nodes in fragments_nodes\n ]\n combined_mask = torch.cat(fragments_masks)\n edge_index = get_edges_index(combined_mask, remove_self_edge=True)\n n_frag_switch = get_n_frag_switch(fragments_nodes)\n\n zt_xh = self.sample_combined_position_feature_noise(masks=fragments_masks)\n if self.pos_only:\n zt_xh = [\n torch.cat([zt_xh[ii][:, : self.pos_dim], h0[ii]], dim=1)\n for ii in range(len(h0))\n ]\n\n utils.assert_mean_zero_with_mask(\n torch.cat(\n [_zt_xh[:, : self.pos_dim] for _zt_xh in zt_xh],\n dim=0,\n ),\n combined_mask,\n )\n\n out_samples = [\n [\n torch.zeros((return_frames,) + _zt_xh.size(), device=_zt_xh.device)\n for _zt_xh in zt_xh\n ]\n for _ in range(return_frames)\n ]\n\n # Iteratively sample p(z_s | z_t) for t = 1, ..., T, with s = t - 1.\n for s in reversed(range(0, timesteps)):\n s_array = torch.full((n_samples, 1), fill_value=s, device=zt_xh[0].device)\n t_array = s_array + 1\n s_array = s_array / timesteps\n t_array = t_array / timesteps\n\n # print(s, zt_xh)\n\n zt_xh = self.sample_p_zs_given_zt(\n s=s_array,\n t=t_array,\n zt_xh=zt_xh,\n edge_index=edge_index,\n n_frag_switch=n_frag_switch,\n masks=fragments_masks,\n conditions=conditions,\n fix_noise=False,\n )\n if self.pos_only:\n zt_xh = [\n torch.cat([zt_xh[ii][:, : self.pos_dim], h0[ii]], dim=1)\n for ii in range(len(h0))\n ]\n\n # save frame\n if (s * return_frames) % timesteps == 0:\n idx = (s * return_frames) // timesteps\n out_samples[idx] = self.normalizer.unnormalize_z(zt_xh)\n\n pos, cat, charge = self.sample_p_xh_given_z0(\n z0_xh=zt_xh,\n edge_index=edge_index,\n n_frag_switch=n_frag_switch,\n masks=fragments_masks,\n batch_size=n_samples,\n conditions=conditions,\n )\n if self.pos_only:\n cat = [_h0[:, :-1] for _h0 in h0]\n charge = [_h0[:, -1:] for _h0 in h0]\n utils.assert_mean_zero_with_mask(\n torch.cat(\n [_pos[:, : self.pos_dim] for _pos in pos],\n dim=0,\n ),\n combined_mask,\n )\n\n # Overwrite last frame with the resulting x and h.\n out_samples[0] = [\n torch.cat([pos[ii], cat[ii], charge[ii]], dim=1) for ii in range(len(pos))\n ]\n return out_samples, fragments_masks\n\n def sample_p_zs_given_zt(\n self,\n s: Tensor,\n t: Tensor,\n zt_xh: List[Tensor],\n edge_index: Tensor,\n n_frag_switch: Tensor,\n masks: List[Tensor],\n conditions: Optional[Tensor] = None,\n fix_noise: bool = False,\n ):\n \"\"\"Samples from zs ~ p(zs | zt). Only used during sampling.\"\"\"\n gamma_s = self.schedule.gamma_module(s)\n gamma_t = self.schedule.gamma_module(t)\n\n (\n sigma2_t_given_s,\n sigma_t_given_s,\n alpha_t_given_s,\n ) = self.schedule.sigma_and_alpha_t_given_s(gamma_t, gamma_s, zt_xh[0])\n\n sigma_s = self.schedule.sigma(gamma_s, target_tensor=zt_xh[0])\n sigma_t = self.schedule.sigma(gamma_t, target_tensor=zt_xh[0])\n\n # Neural net prediction.\n combined_mask = torch.cat(masks)\n net_eps_xh, net_eps_edge_attr = self.dynamics(\n xh=zt_xh,\n edge_index=edge_index,\n t=t,\n conditions=conditions,\n n_frag_switch=n_frag_switch,\n combined_mask=combined_mask,\n edge_attr=None, # TODO: no edge_attr is considered now\n )\n utils.assert_mean_zero_with_mask(\n torch.cat(\n [_zt_xh[:, : self.pos_dim] for _zt_xh in zt_xh],\n dim=0,\n ),\n combined_mask,\n )\n utils.assert_mean_zero_with_mask(\n torch.cat(\n [_net_eps_xh[:, : self.pos_dim] for _net_eps_xh in net_eps_xh],\n dim=0,\n ),\n combined_mask,\n )\n\n # Note: mu_{t->s} = 1 / alpha_{t|s} z_t - sigma_{t|s}^2 / sigma_t / alpha_{t|s} epsilon\n # follows from the definition of mu_{t->s} and Equ. (7) in the EDM paper\n mu = [\n zt_xh[ii] / alpha_t_given_s[masks[ii]]\n - net_eps_xh[ii] * (sigma2_t_given_s / alpha_t_given_s / sigma_t)[masks[ii]]\n for ii in range(len(zt_xh))\n ]\n\n # Compute sigma for p(zs | zt).\n sigma = sigma_t_given_s * sigma_s / sigma_t\n\n # Sample zs given the paramters derived from zt.\n zs_xh = self.sample_normal(mu=mu, sigma=sigma, masks=masks, fix_noise=fix_noise)\n\n # Project down to avoid numerical runaway of the center of gravity.\n for ii in range(len(masks)):\n zs_xh[ii][:, : self.pos_dim] = utils.remove_mean_batch(\n zs_xh[ii][:, : self.pos_dim],\n masks[ii],\n )\n return zs_xh\n\n def sample_normal(\n self,\n mu: List[Tensor],\n sigma: Tensor,\n masks: List[Tensor],\n fix_noise: bool = False,\n ) -> List[Tensor]:\n r\"\"\"Samples from a Normal distribution.\"\"\"\n if fix_noise:\n # bs = 1 if fix_noise else mu.size(0)\n raise NotImplementedError(\"fix_noise option isn't implemented yet\")\n eps_xh = self.sample_combined_position_feature_noise(masks=masks)\n zs_xh = [mu[ii] + sigma[masks[ii]] * eps_xh[ii] for ii in range(len(masks))]\n return zs_xh\n\n def sample_p_xh_given_z0(\n self,\n z0_xh: List[Tensor],\n edge_index: Tensor,\n n_frag_switch: Tensor,\n masks: List[Tensor],\n batch_size: int,\n conditions: Optional[Tensor] = None,\n fix_noise: bool = False,\n ) -> Tuple[List[Tensor]]:\n \"\"\"Samples x ~ p(x|z0).\"\"\"\n t_zeros = torch.zeros(size=(batch_size, 1), device=z0_xh[0].device)\n gamma_0 = self.schedule.gamma_module(t_zeros)\n # Computes sqrt(sigma_0^2 / alpha_0^2)\n sigma_x = self.schedule.SNR(-0.5 * gamma_0)\n net_eps_xh, net_eps_edge_attr = self.dynamics(\n xh=z0_xh,\n edge_index=edge_index,\n t=t_zeros,\n conditions=conditions,\n n_frag_switch=n_frag_switch,\n combined_mask=torch.cat(masks),\n edge_attr=None, # TODO: no edge_attr is considered now\n )\n\n # Compute mu for p(zs | zt).\n mu_x = self.compute_x_pred(\n net_eps_xh=net_eps_xh,\n zt_xh=z0_xh,\n gamma_t=gamma_0,\n masks=masks,\n )\n x0_xh = self.sample_normal(\n mu=mu_x, sigma=sigma_x, masks=masks, fix_noise=fix_noise\n )\n\n pos_0 = [\n self.normalizer.unnormalize(x0_xh[ii][:, : self.pos_dim], ii)\n for ii in range(len(masks))\n ]\n cat_0 = [\n self.normalizer.unnormalize(x0_xh[ii][:, self.pos_dim : -1], ii)\n for ii in range(len(masks))\n ]\n charge_0 = [\n torch.round(self.normalizer.unnormalize(x0_xh[ii][:, -1:], ii)).long()\n for ii in range(len(masks))\n ]\n\n cat_0 = [\n F.one_hot(torch.argmax(cat_0[ii], dim=1), self.node_nfs[ii] - 4).long()\n for ii in range(len(masks))\n ]\n return pos_0, cat_0, charge_0\n\n def compute_x_pred(\n self,\n net_eps_xh: List[Tensor],\n zt_xh: List[Tensor],\n gamma_t: Tensor,\n masks: List[Tensor],\n ) -> List[Tensor]:\n \"\"\"Commputes x_pred, i.e. the most likely prediction of x.\"\"\"\n sigma_t = self.schedule.sigma(gamma_t, target_tensor=net_eps_xh[0])\n alpha_t = self.schedule.alpha(gamma_t, target_tensor=net_eps_xh[0])\n x_pred = [\n 1.0 / alpha_t[masks[ii]] * (zt_xh[ii] - sigma_t[masks[ii]] * net_eps_xh[ii])\n for ii in range(len(masks))\n ]\n return x_pred\n\n # ------ INPAINT ------\n @torch.no_grad()\n def inpaint(\n self,\n n_samples: int,\n fragments_nodes: List[torch.tensor],\n conditions: Optional[Tensor] = None,\n return_frames: int = 1,\n resamplings: int = 1,\n jump_length: int = 1,\n timesteps: Optional[int] = None,\n xh_fixed: Optional[List[Tensor]] = None,\n frag_fixed: Optional[List] = None,\n ):\n r\"\"\"\n Draw samples from the generative model. Optionally, return intermediate\n states for visualization purposes.\n \"\"\"\n timesteps = self.T if timesteps is None else timesteps\n assert 0 < return_frames <= timesteps\n assert timesteps % return_frames == 0\n assert len(xh_fixed)\n\n fragments_masks = [\n get_mask_for_frag(natm_nodes) for natm_nodes in fragments_nodes\n ]\n combined_mask = torch.cat(fragments_masks)\n edge_index = get_edges_index(combined_mask, remove_self_edge=True)\n n_frag_switch = get_n_frag_switch(fragments_nodes)\n\n h0 = [_xh_fixed[:, self.pos_dim :].long() for _xh_fixed in xh_fixed]\n\n for ii, _ in enumerate(xh_fixed):\n xh_fixed[ii][:, : self.pos_dim] = utils.remove_mean_batch(\n xh_fixed[ii][:, : self.pos_dim],\n fragments_masks[ii],\n )\n utils.assert_mean_zero_with_mask(\n torch.cat(\n [_xh_fixed[:, : self.pos_dim] for _xh_fixed in xh_fixed],\n dim=0,\n ),\n combined_mask,\n )\n\n zt_xh = self.sample_combined_position_feature_noise(masks=fragments_masks)\n if self.pos_only:\n zt_xh = [\n torch.cat([zt_xh[ii][:, : self.pos_dim], h0[ii]], dim=1)\n for ii in range(len(h0))\n ]\n\n utils.assert_mean_zero_with_mask(\n torch.cat(\n [_zt_xh[:, : self.pos_dim] for _zt_xh in zt_xh],\n dim=0,\n ),\n combined_mask,\n )\n\n out_samples = [\n [\n torch.zeros((return_frames,) + _zt_xh.size(), device=_zt_xh.device)\n for _zt_xh in zt_xh\n ]\n for _ in range(return_frames)\n ]\n\n schedule = get_repaint_schedule(resamplings, jump_length, timesteps)\n s = timesteps - 1\n for i, n_denoise_steps in enumerate(schedule):\n for j in range(n_denoise_steps):\n s_array = torch.full(\n (n_samples, 1), fill_value=s, device=zt_xh[0].device\n )\n t_array = s_array + 1\n s_array = s_array / timesteps\n t_array = t_array / timesteps\n\n gamma_s = self.schedule.inflate_batch_array(\n self.schedule.gamma_module(s_array), xh_fixed[0]\n )\n\n zt_known, _ = self.noised_representation(\n xh_fixed, fragments_masks, gamma_s\n )\n zt_unknown = self.sample_p_zs_given_zt(\n s=s_array,\n t=t_array,\n zt_xh=zt_xh,\n edge_index=edge_index,\n n_frag_switch=n_frag_switch,\n masks=fragments_masks,\n conditions=conditions,\n fix_noise=False,\n )\n\n if self.pos_only:\n zt_known = [\n torch.cat([zt_known[ii][:, : self.pos_dim], h0[ii]], dim=1)\n for ii in range(len(h0))\n ]\n zt_unknown = [\n torch.cat([zt_unknown[ii][:, : self.pos_dim], h0[ii]], dim=1)\n for ii in range(len(h0))\n ]\n\n zt_xh = [\n zt_known[ii] if ii in frag_fixed else zt_unknown[ii]\n for ii in range(len(h0))\n ]\n\n # Noise combined representation, i.e., resample\n if j == n_denoise_steps - 1 and i < len(schedule) - 1:\n # Go back jump_length steps\n t = s + jump_length\n t_array = torch.full(\n (n_samples, 1), fill_value=t, device=zt_xh[0].device\n )\n t_array = t_array / timesteps\n\n gamma_s = self.schedule.inflate_batch_array(\n self.schedule.gamma_module(s_array), xh_fixed[0]\n )\n gamma_t = self.schedule.inflate_batch_array(\n self.schedule.gamma_module(t_array), xh_fixed[0]\n )\n\n zt_xh = self.sample_p_zt_given_zs(\n zt_xh, fragments_masks, gamma_t, gamma_s\n )\n s = t\n\n s = s - 1\n\n # # save frame\n # if (s * return_frames) % timesteps == 0:\n # idx = (s * return_frames) // timesteps\n # out_samples[idx] = self.normalizer.unnormalize_z(zt_xh)\n\n pos, cat, charge = self.sample_p_xh_given_z0(\n z0_xh=zt_xh,\n edge_index=edge_index,\n n_frag_switch=n_frag_switch,\n masks=fragments_masks,\n batch_size=n_samples,\n conditions=conditions,\n )\n if self.pos_only:\n cat = [_h0[:, :-1] for _h0 in h0]\n charge = [_h0[:, -1:] for _h0 in h0]\n utils.assert_mean_zero_with_mask(\n torch.cat(\n [_pos[:, : self.pos_dim] for _pos in pos],\n dim=0,\n ),\n combined_mask,\n )\n\n # Overwrite last frame with the resulting x and h.\n out_samples[0] = [\n torch.cat([pos[ii], cat[ii], charge[ii]], dim=1) for ii in range(len(pos))\n ]\n return out_samples, fragments_masks\n\n # ------ INPAINT ------\n @torch.no_grad()\n def inpaint_fixed(\n self,\n n_samples: int,\n fragments_nodes: List[torch.tensor],\n conditions: Optional[Tensor] = None,\n return_frames: int = 1,\n resamplings: int = 1,\n jump_length: int = 1,\n timesteps: Optional[int] = None,\n xh_fixed: Optional[List[Tensor]] = None,\n frag_fixed: Optional[List] = None,\n ):\n r\"\"\"\n Draw samples from the generative model. Optionally, return intermediate\n states for visualization purposes.\n \"\"\"\n timesteps = self.T if timesteps is None else timesteps\n assert 0 < return_frames <= timesteps\n assert timesteps % return_frames == 0\n assert len(xh_fixed)\n\n fragments_masks = [\n get_mask_for_frag(natm_nodes) for natm_nodes in fragments_nodes\n ]\n combined_mask = torch.cat(fragments_masks)\n edge_index = get_edges_index(combined_mask, remove_self_edge=True)\n n_frag_switch = get_n_frag_switch(fragments_nodes)\n\n h0 = [_xh_fixed[:, self.pos_dim :].long() for _xh_fixed in xh_fixed]\n\n for ii, _ in enumerate(xh_fixed):\n xh_fixed[ii][:, : self.pos_dim] = utils.remove_mean_batch(\n xh_fixed[ii][:, : self.pos_dim],\n fragments_masks[ii],\n )\n utils.assert_mean_zero_with_mask(\n torch.cat(\n [_xh_fixed[:, : self.pos_dim] for _xh_fixed in xh_fixed],\n dim=0,\n ),\n combined_mask,\n )\n\n zt_xh = self.sample_combined_position_feature_noise(masks=fragments_masks)\n if self.pos_only:\n zt_xh = [\n torch.cat([zt_xh[ii][:, : self.pos_dim], h0[ii]], dim=1)\n for ii in range(len(h0))\n ]\n\n utils.assert_mean_zero_with_mask(\n torch.cat(\n [_zt_xh[:, : self.pos_dim] for _zt_xh in zt_xh],\n dim=0,\n ),\n combined_mask,\n )\n\n out_samples = [\n [\n torch.zeros((return_frames,) + _zt_xh.size(), device=_zt_xh.device)\n for _zt_xh in zt_xh\n ]\n for _ in range(return_frames)\n ]\n\n schedule = get_repaint_schedule(resamplings, jump_length, timesteps)\n s = timesteps - 1\n for i, n_denoise_steps in enumerate(schedule):\n for j in range(n_denoise_steps):\n s_array = torch.full(\n (n_samples, 1), fill_value=s, device=zt_xh[0].device\n )\n t_array = s_array + 1\n s_array = s_array / timesteps\n t_array = t_array / timesteps\n\n gamma_s = self.schedule.inflate_batch_array(\n self.schedule.gamma_module(s_array), xh_fixed[0]\n )\n\n zt_known, _ = self.noised_representation(\n xh_fixed, fragments_masks, gamma_s\n )\n zt_unknown = self.sample_p_zs_given_zt(\n s=s_array,\n t=t_array,\n zt_xh=zt_xh,\n edge_index=edge_index,\n n_frag_switch=n_frag_switch,\n masks=fragments_masks,\n conditions=conditions,\n fix_noise=False,\n )\n\n if self.pos_only:\n zt_known = [\n torch.cat([zt_known[ii][:, : self.pos_dim], h0[ii]], dim=1)\n for ii in range(len(h0))\n ]\n zt_unknown = [\n torch.cat([zt_unknown[ii][:, : self.pos_dim], h0[ii]], dim=1)\n for ii in range(len(h0))\n ]\n\n zt_xh = [\n zt_known[ii] if ii in frag_fixed else zt_unknown[ii]\n for ii in range(len(h0))\n ]\n\n # Noise combined representation, i.e., resample\n if j == n_denoise_steps - 1 and i < len(schedule) - 1:\n # Go back jump_length steps\n t = s + jump_length\n t_array = torch.full(\n (n_samples, 1), fill_value=t, device=zt_xh[0].device\n )\n t_array = t_array / timesteps\n\n gamma_s = self.schedule.inflate_batch_array(\n self.schedule.gamma_module(s_array), xh_fixed[0]\n )\n gamma_t = self.schedule.inflate_batch_array(\n self.schedule.gamma_module(t_array), xh_fixed[0]\n )\n\n zt_xh = self.sample_p_zt_given_zs(\n zt_xh, fragments_masks, gamma_t, gamma_s\n )\n s = t\n\n s = s - 1\n\n # # save frame\n # if (s * return_frames) % timesteps == 0:\n # idx = (s * return_frames) // timesteps\n # out_samples[idx] = self.normalizer.unnormalize_z(zt_xh)\n\n pos, cat, charge = self.sample_p_xh_given_z0(\n z0_xh=zt_xh,\n edge_index=edge_index,\n n_frag_switch=n_frag_switch,\n masks=fragments_masks,\n batch_size=n_samples,\n conditions=conditions,\n )\n if self.pos_only:\n cat = [_h0[:, :-1] for _h0 in h0]\n charge = [_h0[:, -1:] for _h0 in h0]\n utils.assert_mean_zero_with_mask(\n torch.cat(\n [_pos[:, : self.pos_dim] for _pos in pos],\n dim=0,\n ),\n combined_mask,\n )\n\n # Overwrite last frame with the resulting x and h.\n out_samples[0] = [\n torch.cat([pos[ii], cat[ii], charge[ii]], dim=1) for ii in range(len(pos))\n ]\n return out_samples, fragments_masks\n\n def sample_p_zt_given_zs(\n self,\n zs: List[Tensor],\n masks: List[Tensor],\n gamma_t: Tensor,\n gamma_s: Tensor,\n fix_noise: bool = False,\n ) -> List[Tensor]:\n (\n sigma2_t_given_s,\n sigma_t_given_s,\n alpha_t_given_s,\n ) = self.schedule.sigma_and_alpha_t_given_s(gamma_t, gamma_s, zs[0])\n\n mu = [alpha_t_given_s[masks[ii]] * zs[ii] for ii in range(len(masks))]\n zt = self.sample_normal(\n mu=mu, sigma=sigma_t_given_s, masks=masks, fix_noise=fix_noise\n )\n\n for ii in range(len(masks)):\n zt[ii][:, : self.pos_dim] = utils.remove_mean_batch(\n zt[ii][:, : self.pos_dim],\n masks[ii],\n )\n return zt" }, { "identifier": "average_over_batch_metrics", "path": "oa_reactdiff/trainer/_metrics.py", "snippet": "def average_over_batch_metrics(batch_metrics: List[Dict], allowed: List = []):\n epoch_metrics = {}\n effective_batch = {}\n for ii, out in enumerate(batch_metrics):\n for k, v in out.items():\n if not (k in allowed or len(allowed) == 0):\n continue\n if ii == 0:\n epoch_metrics[k] = v\n effective_batch[k] = 1\n else:\n if not np.isnan(v):\n epoch_metrics[k] += v\n effective_batch[k] += 1\n for k in epoch_metrics:\n epoch_metrics[k] /= effective_batch[k]\n return epoch_metrics" }, { "identifier": "pretty_print", "path": "oa_reactdiff/trainer/_metrics.py", "snippet": "def pretty_print(epoch, metric_dict, prefix=\"Train\"):\n out = f\"{prefix} epoch {epoch} \"\n for k, v in metric_dict.items():\n out += f\"{k} {v:.2f} \"\n print(out)" }, { "identifier": "batch_rmsd", "path": "oa_reactdiff/analyze/rmsd.py", "snippet": "def batch_rmsd(\n fragments_nodes: List[Tensor],\n out_samples: List[Tensor],\n xh: List[Tensor],\n idx: int = 1,\n threshold=0.5,\n):\n rmsds = []\n out_samples_use = out_samples[idx]\n xh_use = xh[idx]\n nodes = fragments_nodes[idx].long().cpu().numpy()\n start_ind, end_ind = 0, 0\n for jj, natoms in enumerate(nodes):\n end_ind += natoms\n mol1 = xh2pmg(out_samples_use[start_ind:end_ind])\n mol2 = xh2pmg(xh_use[start_ind:end_ind])\n try:\n rmsd = pymatgen_rmsd(mol1, mol2, ignore_chirality=True, threshold=threshold)\n except:\n rmsd = 1.0\n rmsds.append(min(rmsd, 1.0))\n start_ind = end_ind\n return rmsds" } ]
from typing import Dict, List, Optional, Tuple from pathlib import Path from torch import nn from torch.utils.data import DataLoader from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts, StepLR from pytorch_lightning import LightningModule from torchmetrics.classification import ( BinaryAccuracy, BinaryAUROC, BinaryF1Score, BinaryPrecision, BinaryCohenKappa, ) from torchmetrics import PearsonCorrCoef, SpearmanCorrCoef, MeanAbsoluteError from oa_reactdiff.dataset import ( ProcessedQM9, ProcessedDoubleQM9, ProcessedTripleQM9, ProcessedTS1x, ) from oa_reactdiff.dynamics import EGNNDynamics, Confidence from oa_reactdiff.diffusion._schedule import DiffSchedule, PredefinedNoiseSchedule from oa_reactdiff.diffusion._normalizer import Normalizer, FEATURE_MAPPING from oa_reactdiff.diffusion.en_diffusion import EnVariationalDiffusion from oa_reactdiff.trainer._metrics import average_over_batch_metrics, pretty_print from oa_reactdiff.analyze.rmsd import batch_rmsd import torch import copy import torch.nn.functional as F import numpy as np import pandas as pd import oa_reactdiff.utils.training_tools as utils
19,977
PROCESS_FUNC = { "QM9": ProcessedQM9, "DoubleQM9": ProcessedDoubleQM9, "TripleQM9": ProcessedTripleQM9, "TS1x": ProcessedTS1x, } FILE_TYPE = { "QM9": ".npz", "DoubleQM9": ".npz", "TripleQM9": ".npz", "TS1x": ".pkl", } LR_SCHEDULER = { "cos": CosineAnnealingWarmRestarts, "step": StepLR, } class DDPMModule(LightningModule): def __init__( self, model_config: Dict, optimizer_config: Dict, training_config: Dict, node_nfs: List[int] = [9] * 3, edge_nf: int = 4, condition_nf: int = 3, fragment_names: List[str] = ["inorg_node", "org_edge", "org_node"], pos_dim: int = 3, update_pocket_coords: bool = True, condition_time: bool = True, edge_cutoff: Optional[float] = None, norm_values: Tuple = (1.0, 1.0, 1.0), norm_biases: Tuple = (0.0, 0.0, 0.0), noise_schedule: str = "polynomial_2", timesteps: int = 1000, precision: float = 1e-5, loss_type: str = "l2", pos_only: bool = False, process_type: Optional[str] = None, model: nn.Module = None, enforce_same_encoding: Optional[List] = None, scales: List[float] = [1.0, 1.0, 1.0], eval_epochs: int = 20, source: Optional[Dict] = None, fixed_idx: Optional[List] = None, ) -> None: super().__init__() egnn_dynamics = EGNNDynamics( model_config=model_config, node_nfs=node_nfs, edge_nf=edge_nf, condition_nf=condition_nf, fragment_names=fragment_names, pos_dim=pos_dim, update_pocket_coords=update_pocket_coords, condition_time=condition_time, edge_cutoff=edge_cutoff, model=model, enforce_same_encoding=enforce_same_encoding, source=source, )
PROCESS_FUNC = { "QM9": ProcessedQM9, "DoubleQM9": ProcessedDoubleQM9, "TripleQM9": ProcessedTripleQM9, "TS1x": ProcessedTS1x, } FILE_TYPE = { "QM9": ".npz", "DoubleQM9": ".npz", "TripleQM9": ".npz", "TS1x": ".pkl", } LR_SCHEDULER = { "cos": CosineAnnealingWarmRestarts, "step": StepLR, } class DDPMModule(LightningModule): def __init__( self, model_config: Dict, optimizer_config: Dict, training_config: Dict, node_nfs: List[int] = [9] * 3, edge_nf: int = 4, condition_nf: int = 3, fragment_names: List[str] = ["inorg_node", "org_edge", "org_node"], pos_dim: int = 3, update_pocket_coords: bool = True, condition_time: bool = True, edge_cutoff: Optional[float] = None, norm_values: Tuple = (1.0, 1.0, 1.0), norm_biases: Tuple = (0.0, 0.0, 0.0), noise_schedule: str = "polynomial_2", timesteps: int = 1000, precision: float = 1e-5, loss_type: str = "l2", pos_only: bool = False, process_type: Optional[str] = None, model: nn.Module = None, enforce_same_encoding: Optional[List] = None, scales: List[float] = [1.0, 1.0, 1.0], eval_epochs: int = 20, source: Optional[Dict] = None, fixed_idx: Optional[List] = None, ) -> None: super().__init__() egnn_dynamics = EGNNDynamics( model_config=model_config, node_nfs=node_nfs, edge_nf=edge_nf, condition_nf=condition_nf, fragment_names=fragment_names, pos_dim=pos_dim, update_pocket_coords=update_pocket_coords, condition_time=condition_time, edge_cutoff=edge_cutoff, model=model, enforce_same_encoding=enforce_same_encoding, source=source, )
normalizer = Normalizer(
8
2023-10-30 02:53:38+00:00
24k
nv-tlabs/pacer
scripts/vis_egoquest_sp.py
[ { "identifier": "SMPL_Parser", "path": "uhc/smpllib/smpl_parser.py", "snippet": "class SMPL_Parser(_SMPL):\n def __init__(self, create_transl=False, *args, **kwargs):\n \"\"\"SMPL model constructor\n Parameters\n ----------\n model_path: str\n The path to the folder or to the file where the model\n parameters are stored\n data_struct: Strct\n A struct object. If given, then the parameters of the model are\n read from the object. Otherwise, the model tries to read the\n parameters from the given `model_path`. (default = None)\n create_global_orient: bool, optional\n Flag for creating a member variable for the global orientation\n of the body. (default = True)\n global_orient: torch.tensor, optional, Bx3\n The default value for the global orientation variable.\n (default = None)\n create_body_pose: bool, optional\n Flag for creating a member variable for the pose of the body.\n (default = True)\n body_pose: torch.tensor, optional, Bx(Body Joints * 3)\n The default value for the body pose variable.\n (default = None)\n create_betas: bool, optional\n Flag for creating a member variable for the shape space\n (default = True).\n betas: torch.tensor, optional, Bx10\n The default value for the shape member variable.\n (default = None)\n create_transl: bool, optional\n Flag for creating a member variable for the translation\n of the body. (default = True)\n transl: torch.tensor, optional, Bx3\n The default value for the transl variable.\n (default = None)\n dtype: torch.dtype, optional\n The data type for the created variables\n batch_size: int, optional\n The batch size used for creating the member variables\n joint_mapper: object, optional\n An object that re-maps the joints. Useful if one wants to\n re-order the SMPL joints to some other convention (e.g. MSCOCO)\n (default = None)\n gender: str, optional\n Which gender to load\n vertex_ids: dict, optional\n A dictionary containing the indices of the extra vertices that\n will be selected\n \"\"\"\n super(SMPL_Parser, self).__init__(*args, **kwargs)\n self.device = next(self.parameters()).device\n self.joint_names = SMPL_BONE_ORDER_NAMES\n\n self.joint_axes = {x: np.identity(3) for x in self.joint_names}\n self.joint_dofs = {x: [\"x\", \"y\", \"z\"] for x in self.joint_names}\n self.joint_range = {\n x: np.hstack([np.ones([3, 1]) * -np.pi,\n np.ones([3, 1]) * np.pi])\n for x in self.joint_names\n }\n self.joint_range[\"L_Elbow\"] *= 4\n self.joint_range[\"R_Elbow\"] *= 4\n self.joint_range[\"L_Shoulder\"] *= 4\n self.joint_range[\"R_Shoulder\"] *= 4\n\n self.contype = {1: self.joint_names}\n self.conaffinity = {1: self.joint_names}\n\n # self.contype = {\n # 3: ['Pelvis', 'L_Hip', 'L_Knee', 'L_Ankle', 'L_Toe', 'R_Hip', 'R_Knee','R_Ankle', 'R_Toe', 'Torso', 'Spine', 'Neck', 'Head','L_Thorax', 'L_Elbow', 'L_Wrist', 'L_Hand', 'R_Thorax', 'R_Elbow', 'R_Wrist', 'R_Hand'],\n # 1: ['Chest', \"L_Shoulder\", \"R_Shoulder\"]\n # }\n\n # self.conaffinity = {\n # 1: ['Pelvis', 'L_Hip', 'L_Knee', 'L_Ankle', 'L_Toe', 'R_Hip', 'R_Knee','R_Ankle', 'R_Toe', 'Torso', 'Spine', 'Neck', 'Head','L_Thorax', 'L_Elbow', 'L_Wrist', 'L_Hand', 'R_Thorax', 'R_Elbow', 'R_Wrist', 'R_Hand'],\n # 3: ['Chest', \"L_Shoulder\", \"R_Shoulder\"]\n # }\n\n self.zero_pose = torch.zeros(1, 72).float()\n\n def forward(self, *args, **kwargs):\n smpl_output = super(SMPL_Parser, self).forward(*args, **kwargs)\n return smpl_output\n\n def get_joints_verts(self, pose, th_betas=None, th_trans=None):\n \"\"\"\n Pose should be batch_size x 72\n \"\"\"\n if pose.shape[1] != 72:\n pose = pose.reshape(-1, 72)\n\n pose = pose.float()\n if th_betas is not None:\n th_betas = th_betas.float()\n\n if th_betas.shape[-1] == 16:\n th_betas = th_betas[:, :10]\n\n batch_size = pose.shape[0]\n\n smpl_output = self.forward(\n betas=th_betas,\n transl=th_trans,\n body_pose=pose[:, 3:],\n global_orient=pose[:, :3],\n )\n vertices = smpl_output.vertices\n joints = smpl_output.joints[:, :24]\n # joints = smpl_output.joints[:,JOINST_TO_USE]\n return vertices, joints\n\n def get_offsets(self, zero_pose=None, betas=torch.zeros(1, 10).float()):\n with torch.no_grad():\n if zero_pose is None:\n verts, Jtr = self.get_joints_verts(self.zero_pose,\n th_betas=betas)\n else:\n verts, Jtr = self.get_joints_verts(zero_pose, th_betas=betas)\n verts_np = verts.detach().cpu().numpy()\n jts_np = Jtr.detach().cpu().numpy()\n parents = self.parents.cpu().numpy()\n offsets_smpl = [np.array([0, 0, 0])]\n for i in range(1, len(parents)):\n p_id = parents[i]\n p3d = jts_np[0, p_id]\n curr_3d = jts_np[0, i]\n offset_curr = curr_3d - p3d\n offsets_smpl.append(offset_curr)\n offsets_smpl = np.array(offsets_smpl)\n joint_names = self.joint_names\n joint_pos = Jtr[0].numpy()\n smpl_joint_parents = self.parents.cpu().numpy()\n joint_offsets = {\n joint_names[c]:\n (joint_pos[c] - joint_pos[p]) if c > 0 else joint_pos[c]\n for c, p in enumerate(smpl_joint_parents)\n }\n parents_dict = {\n joint_names[i]: joint_names[parents[i]]\n for i in range(len(joint_names))\n }\n channels = [\"z\", \"y\", \"x\"]\n skin_weights = self.lbs_weights.numpy()\n return (verts[0], jts_np[0], skin_weights, self.joint_names,\n joint_offsets, parents_dict, channels, self.joint_range)\n\n def get_mesh_offsets(self,\n zero_pose=None,\n betas=torch.zeros(1, 10),\n flatfoot=False):\n with torch.no_grad():\n joint_names = self.joint_names\n if zero_pose is None:\n verts, Jtr = self.get_joints_verts(self.zero_pose,\n th_betas=betas)\n else:\n verts, Jtr = self.get_joints_verts(zero_pose, th_betas=betas)\n\n verts_np = verts.detach().cpu().numpy()\n verts = verts_np[0]\n\n if flatfoot:\n feet_subset = verts[:, 1] < np.min(verts[:, 1]) + 0.01\n verts[feet_subset, 1] = np.mean(verts[feet_subset][:, 1])\n\n smpl_joint_parents = self.parents.cpu().numpy()\n\n joint_pos = Jtr[0].numpy()\n joint_offsets = {\n joint_names[c]:\n (joint_pos[c] - joint_pos[p]) if c > 0 else joint_pos[c]\n for c, p in enumerate(smpl_joint_parents)\n }\n joint_parents = {\n x: joint_names[i] if i >= 0 else None\n for x, i in zip(joint_names, smpl_joint_parents)\n }\n\n # skin_weights = smpl_layer.th_weights.numpy()\n skin_weights = self.lbs_weights.numpy()\n return (\n verts,\n joint_pos,\n skin_weights,\n joint_names,\n joint_offsets,\n joint_parents,\n self.joint_axes,\n self.joint_dofs,\n self.joint_range,\n self.contype,\n self.conaffinity,\n )\n\n def get_mesh_offsets_batch(self, betas=torch.zeros(1, 10), flatfoot=False):\n with torch.no_grad():\n joint_names = self.joint_names\n verts, Jtr = self.get_joints_verts(self.zero_pose.repeat(\n betas.shape[0], 1),\n th_betas=betas)\n verts_np = verts.detach().cpu().numpy()\n verts = verts_np[0]\n\n if flatfoot:\n feet_subset = verts[:, 1] < np.min(verts[:, 1]) + 0.01\n verts[feet_subset, 1] = np.mean(verts[feet_subset][:, 1])\n\n smpl_joint_parents = self.parents.cpu().numpy()\n\n joint_pos = Jtr\n joint_offsets = {\n joint_names[c]:\n (joint_pos[:, c] - joint_pos[:, p]) if c > 0 else joint_pos[:,\n c]\n for c, p in enumerate(smpl_joint_parents)\n }\n joint_parents = {\n x: joint_names[i] if i >= 0 else None\n for x, i in zip(joint_names, smpl_joint_parents)\n }\n\n skin_weights = self.lbs_weights\n return (\n verts,\n joint_pos,\n skin_weights,\n joint_names,\n joint_offsets,\n joint_parents,\n self.joint_axes,\n self.joint_dofs,\n self.joint_range,\n self.contype,\n self.conaffinity,\n )" }, { "identifier": "SMPLH_Parser", "path": "uhc/smpllib/smpl_parser.py", "snippet": "class SMPLH_Parser(_SMPLH):\n def __init__(self, *args, **kwargs):\n super(SMPLH_Parser, self).__init__(*args, **kwargs)\n self.device = next(self.parameters()).device\n self.joint_names = SMPLH_BONE_ORDER_NAMES\n self.joint_axes = {x: np.identity(3) for x in self.joint_names}\n self.joint_dofs = {x: [\"z\", \"y\", \"x\"] for x in self.joint_names}\n self.joint_range = {\n x: np.hstack([np.ones([3, 1]) * -np.pi,\n np.ones([3, 1]) * np.pi])\n for x in self.joint_names\n }\n self.joint_range[\"L_Elbow\"] *= 4\n self.joint_range[\"R_Elbow\"] *= 4\n # import ipdb\n # ipdb.set_trace()\n\n self.contype = {1: self.joint_names}\n self.conaffinity = {1: self.joint_names}\n self.zero_pose = torch.zeros(1, 156).float()\n\n def forward(self, *args, **kwargs):\n smpl_output = super(SMPLH_Parser, self).forward(*args, **kwargs)\n return smpl_output\n\n def get_joints_verts(self, pose, th_betas=None, th_trans=None):\n \"\"\"\n Pose should be batch_size x 156\n \"\"\"\n\n if pose.shape[1] != 156:\n pose = pose.reshape(-1, 156)\n pose = pose.float()\n if th_betas is not None:\n th_betas = th_betas.float()\n\n batch_size = pose.shape[0]\n smpl_output = self.forward(\n body_pose=pose[:, 3:66],\n global_orient=pose[:, :3],\n L_hand_pose=pose[:, 66:111],\n R_hand_pose=pose[:, 111:156],\n betas=th_betas,\n transl=th_trans,\n )\n vertices = smpl_output.vertices\n joints = smpl_output.joints\n # joints = smpl_output.joints[:,JOINST_TO_USE]\n return vertices, joints\n\n def get_offsets(self, betas=torch.zeros(1, 16).float()):\n with torch.no_grad():\n verts, jts = self.get_joints_verts(self.zero_pose, th_betas=betas)\n verts_np = verts.detach().cpu().numpy()\n jts_np = jts.detach().cpu().numpy()\n\n parents = self.parents.cpu().numpy()\n offsets_smpl = [np.array([0, 0, 0])]\n for i in range(1, len(parents)):\n p_id = parents[i]\n p3d = jts_np[0, p_id]\n curr_3d = jts_np[0, i]\n offset_curr = curr_3d - p3d\n offsets_smpl.append(offset_curr)\n offsets_smpl = np.array(offsets_smpl)\n names_smpl = self.joint_names\n offset_smpl_dict = {\n names_smpl[i]: offsets_smpl[i]\n for i in range(len(names_smpl))\n }\n parents_dict = {\n names_smpl[i]: names_smpl[parents[i]]\n for i in range(len(names_smpl))\n }\n parents_dict[\"Hips\"] = \"None\"\n channels = [\"z\", \"y\", \"x\"]\n\n return offset_smpl_dict, parents_dict, channels\n\n def get_mesh_offsets(self, betas=torch.zeros(1, 16), flatfoot=False):\n with torch.no_grad():\n joint_names = self.joint_names\n verts, Jtr = self.get_joints_verts(self.zero_pose, th_betas=betas)\n\n verts_np = verts.detach().cpu().numpy()\n verts = verts_np[0]\n\n if flatfoot:\n feet_subset = verts[:, 1] < np.min(verts[:, 1]) + 0.01\n verts[feet_subset, 1] = np.mean(verts[feet_subset][:, 1])\n\n smpl_joint_parents = self.parents.cpu().numpy()\n joint_pos = Jtr[0].numpy()\n joint_offsets = {\n joint_names[c]:\n (joint_pos[c] - joint_pos[p]) if c > 0 else joint_pos[c]\n for c, p in enumerate(smpl_joint_parents)\n }\n joint_parents = {\n x: joint_names[i] if i >= 0 else None\n for x, i in zip(joint_names, smpl_joint_parents)\n }\n\n # skin_weights = smpl_layer.th_weights.numpy()\n skin_weights = self.lbs_weights.numpy()\n return (\n verts,\n joint_pos,\n skin_weights,\n joint_names,\n joint_offsets,\n joint_parents,\n self.joint_axes,\n self.joint_dofs,\n self.joint_range,\n self.contype,\n self.conaffinity,\n )" }, { "identifier": "SMPLX_Parser", "path": "uhc/smpllib/smpl_parser.py", "snippet": "class SMPLX_Parser(_SMPLX):\n def __init__(self, *args, **kwargs):\n super(SMPLX_Parser, self).__init__(*args, **kwargs)\n self.device = next(self.parameters()).device\n self.joint_names = SMPLH_BONE_ORDER_NAMES\n self.joint_axes = {x: np.identity(3) for x in self.joint_names}\n self.joint_dofs = {x: [\"z\", \"y\", \"x\"] for x in self.joint_names}\n self.joint_range = {\n x: np.hstack([np.ones([3, 1]) * -np.pi,\n np.ones([3, 1]) * np.pi])\n for x in self.joint_names\n }\n self.joint_range[\"L_Elbow\"] *= 4\n self.joint_range[\"R_Elbow\"] *= 4\n # import ipdb\n # ipdb.set_trace()\n\n self.contype = {1: self.joint_names}\n self.conaffinity = {1: self.joint_names}\n self.zero_pose = torch.zeros(1, 156).float()\n self.joint_to_use = [\n SMPLX_BONE_ORDER_NAMES.index(i) for i in SMPLH_BONE_ORDER_NAMES\n ]\n self.parents_to_use = np.concatenate(\n [np.arange(0, 22), np.arange(25, 55)])\n\n def forward(self, *args, **kwargs):\n smpl_output = super(SMPLX_Parser, self).forward(*args, **kwargs)\n return smpl_output\n\n def get_joints_verts(self, pose, th_betas=None, th_trans=None):\n \"\"\"\n Pose should be batch_size x 156\n \"\"\"\n\n if pose.shape[1] != 156:\n pose = pose.reshape(-1, 156)\n pose = pose.float()\n if th_betas is not None:\n th_betas = th_betas.float()\n\n batch_size = pose.shape[0]\n smpl_output = self.forward(\n body_pose=pose[:, 3:66],\n global_orient=pose[:, :3],\n left_hand_pose=pose[:, 66:111],\n right_hand_pose=pose[:, 111:156],\n betas=th_betas,\n transl=th_trans,\n )\n vertices = smpl_output.vertices\n joints = smpl_output.joints\n # return vertices, joints\n return vertices, joints\n\n def get_offsets(self, v_template=None):\n if not v_template is None:\n self.v_template = v_template\n with torch.no_grad():\n verts, jts = self.get_joints_verts(self.zero_pose)\n verts_np = verts.detach().cpu().numpy()\n jts_np = jts.detach().cpu().numpy()\n\n parents = self.parents.cpu().numpy()\n offsets_smpl = [np.array([0, 0, 0])]\n for i in range(1, len(parents)):\n p_id = parents[i]\n p3d = jts_np[0, p_id]\n curr_3d = jts_np[0, i]\n offset_curr = curr_3d - p3d\n offsets_smpl.append(offset_curr)\n offsets_smpl = np.array(offsets_smpl)\n names_smpl = self.joint_names\n offset_smpl_dict = {\n names_smpl[i]: offsets_smpl[i]\n for i in range(len(names_smpl))\n }\n parents_dict = {\n names_smpl[i]: names_smpl[parents[i]]\n for i in range(len(names_smpl))\n }\n parents_dict[\"Hips\"] = \"None\"\n channels = [\"z\", \"y\", \"x\"]\n return offset_smpl_dict, parents_dict, channels\n\n def get_mesh_offsets(self, v_template=None):\n if not v_template is None:\n self.v_template = v_template\n with torch.no_grad():\n # joint_names = self.joint_names\n joint_names = SMPLX_BONE_ORDER_NAMES\n verts, Jtr = self.get_joints_verts(self.zero_pose)\n\n smpl_joint_parents = self.parents.cpu().numpy()\n joint_pos = Jtr[0].numpy()\n # print(\n # joint_pos.shape,\n # smpl_joint_parents.shape,\n # len(self.parents_to_use),\n # self.parents.cpu().numpy().shape,\n # )\n joint_offsets = {\n joint_names[c]:\n (joint_pos[c] - joint_pos[p]) if c > 0 else joint_pos[c]\n for c, p in enumerate(smpl_joint_parents)\n if joint_names[c] in self.joint_names\n }\n joint_parents = {\n x: joint_names[i] if i >= 0 else None\n for x, i in zip(joint_names, smpl_joint_parents)\n if joint_names[i] in self.joint_names\n }\n\n verts = verts[0].numpy()\n # skin_weights = smpl_layer.th_weights.numpy()\n skin_weights = self.lbs_weights.numpy()[:, self.parents_to_use]\n return (\n verts,\n joint_pos,\n skin_weights,\n self.joint_names,\n joint_offsets,\n joint_parents,\n self.joint_axes,\n self.joint_dofs,\n self.joint_range,\n self.contype,\n self.conaffinity,\n )" }, { "identifier": "SkeletonTree", "path": "poselib/poselib/skeleton/skeleton3d.py", "snippet": "class SkeletonTree(Serializable):\n \"\"\"\n A skeleton tree gives a complete description of a rigid skeleton. It describes a tree structure\n over a list of nodes with their names indicated by strings. Each edge in the tree has a local\n translation associated with it which describes the distance between the two nodes that it\n connects. \n\n Basic Usage:\n >>> t = SkeletonTree.from_mjcf(SkeletonTree.__example_mjcf_path__)\n >>> t\n SkeletonTree(\n node_names=['torso', 'front_left_leg', 'aux_1', 'front_left_foot', 'front_right_leg', 'aux_2', 'front_right_foot', 'left_back_leg', 'aux_3', 'left_back_foot', 'right_back_leg', 'aux_4', 'right_back_foot'],\n parent_indices=tensor([-1, 0, 1, 2, 0, 4, 5, 0, 7, 8, 0, 10, 11]),\n local_translation=tensor([[ 0.0000, 0.0000, 0.7500],\n [ 0.0000, 0.0000, 0.0000],\n [ 0.2000, 0.2000, 0.0000],\n [ 0.2000, 0.2000, 0.0000],\n [ 0.0000, 0.0000, 0.0000],\n [-0.2000, 0.2000, 0.0000],\n [-0.2000, 0.2000, 0.0000],\n [ 0.0000, 0.0000, 0.0000],\n [-0.2000, -0.2000, 0.0000],\n [-0.2000, -0.2000, 0.0000],\n [ 0.0000, 0.0000, 0.0000],\n [ 0.2000, -0.2000, 0.0000],\n [ 0.2000, -0.2000, 0.0000]])\n )\n >>> t.node_names\n ['torso', 'front_left_leg', 'aux_1', 'front_left_foot', 'front_right_leg', 'aux_2', 'front_right_foot', 'left_back_leg', 'aux_3', 'left_back_foot', 'right_back_leg', 'aux_4', 'right_back_foot']\n >>> t.parent_indices\n tensor([-1, 0, 1, 2, 0, 4, 5, 0, 7, 8, 0, 10, 11])\n >>> t.local_translation\n tensor([[ 0.0000, 0.0000, 0.7500],\n [ 0.0000, 0.0000, 0.0000],\n [ 0.2000, 0.2000, 0.0000],\n [ 0.2000, 0.2000, 0.0000],\n [ 0.0000, 0.0000, 0.0000],\n [-0.2000, 0.2000, 0.0000],\n [-0.2000, 0.2000, 0.0000],\n [ 0.0000, 0.0000, 0.0000],\n [-0.2000, -0.2000, 0.0000],\n [-0.2000, -0.2000, 0.0000],\n [ 0.0000, 0.0000, 0.0000],\n [ 0.2000, -0.2000, 0.0000],\n [ 0.2000, -0.2000, 0.0000]])\n >>> t.parent_of('front_left_leg')\n 'torso'\n >>> t.index('front_right_foot')\n 6\n >>> t[2]\n 'aux_1'\n \"\"\"\n\n __example_mjcf_path__ = os.path.join(\n os.path.dirname(os.path.realpath(__file__)), \"tests/ant.xml\"\n )\n\n def __init__(self, node_names, parent_indices, local_translation, local_xml_rotation):\n \"\"\"\n :param node_names: a list of names for each tree node\n :type node_names: List[str]\n :param parent_indices: an int32-typed tensor that represents the edge to its parent.\\\n -1 represents the root node\n :type parent_indices: Tensor\n :param local_translation: a 3d vector that gives local translation information\n :type local_translation: Tensor\n \"\"\"\n ln, lp, ll = len(node_names), len(parent_indices), len(local_translation)\n assert len(set((ln, lp, ll))) == 1\n self._node_names = node_names\n self._parent_indices = parent_indices.long()\n self._local_translation = local_translation\n self._local_xml_rotation = local_xml_rotation\n self._node_indices = {self.node_names[i]: i for i in range(len(self))}\n\n def __len__(self):\n \"\"\" number of nodes in the skeleton tree \"\"\"\n return len(self.node_names)\n\n def __iter__(self):\n \"\"\" iterator that iterate through the name of each node \"\"\"\n yield from self.node_names\n\n def __getitem__(self, item):\n \"\"\" get the name of the node given the index \"\"\"\n return self.node_names[item]\n\n def __repr__(self):\n return (\n \"SkeletonTree(\\n node_names={},\\n parent_indices={},\"\n \"\\n local_translation={}\\n)\".format(\n self._indent(repr(self.node_names)),\n self._indent(repr(self.parent_indices)),\n self._indent(repr(self.local_translation)),\n )\n )\n\n def _indent(self, s):\n return \"\\n \".join(s.split(\"\\n\"))\n\n @property\n def node_names(self):\n return self._node_names\n\n @property\n def parent_indices(self):\n return self._parent_indices\n\n @property\n def local_translation(self):\n return self._local_translation\n\n @property\n def num_joints(self):\n \"\"\" number of nodes in the skeleton tree \"\"\"\n return len(self)\n\n @classmethod\n def from_dict(cls, dict_repr, *args, **kwargs):\n return cls(\n list(map(str, dict_repr[\"node_names\"])),\n TensorUtils.from_dict(dict_repr[\"parent_indices\"], *args,\n **kwargs),\n TensorUtils.from_dict(dict_repr[\"local_translation\"], *args,\n **kwargs),\n TensorUtils.from_dict(dict_repr[\"local_xml_rotation\"], *args,\n **kwargs),\n )\n\n def to_dict(self):\n return OrderedDict(\n [\n (\"node_names\", self.node_names),\n (\"parent_indices\", tensor_to_dict(self.parent_indices)),\n (\"local_translation\", tensor_to_dict(self.local_translation)),\n (\"local_xml_rotation\", tensor_to_dict(self._local_xml_rotation)),\n ]\n )\n\n @classmethod\n def from_mjcf(cls, path: str) -> \"SkeletonTree\":\n \"\"\"\n Parses a mujoco xml scene description file and returns a Skeleton Tree.\n We use the model attribute at the root as the name of the tree.\n \n :param path:\n :type path: string\n :return: The skeleton tree constructed from the mjcf file\n :rtype: SkeletonTree\n \"\"\"\n tree = ET.parse(path)\n xml_doc_root = tree.getroot()\n xml_world_body = xml_doc_root.find(\"worldbody\")\n if xml_world_body is None:\n raise ValueError(\"MJCF parsed incorrectly please verify it.\")\n # assume this is the root\n xml_body_root = xml_world_body.find(\"body\")\n if xml_body_root is None:\n raise ValueError(\"MJCF parsed incorrectly please verify it.\")\n\n node_names = []\n parent_indices = []\n local_translation = []\n local_xml_rotation = []\n\n # recursively adding all nodes into the skel_tree\n def _add_xml_node(xml_node, parent_index, node_index):\n node_name = xml_node.attrib.get(\"name\")\n # parse the local translation into float list\n pos = np.fromstring(xml_node.attrib.get(\"pos\"), dtype=float, sep=\" \")\n quat = np.fromstring(xml_node.attrib.get(\"quat\", \"1 0 0 0\"), dtype=float, sep=\" \")[[1, 2, 3, 0]]\n node_names.append(node_name)\n parent_indices.append(parent_index)\n local_translation.append(pos)\n local_xml_rotation.append(quat)\n curr_index = node_index\n node_index += 1\n for next_node in xml_node.findall(\"body\"):\n node_index = _add_xml_node(next_node, curr_index, node_index)\n return node_index\n\n _add_xml_node(xml_body_root, -1, 0)\n\n return cls(\n node_names,\n torch.from_numpy(np.array(parent_indices, dtype=np.int32)),\n torch.from_numpy(np.array(local_translation, dtype=np.float32)),\n torch.from_numpy(np.array(local_xml_rotation, dtype=np.float32)),\n )\n\n def parent_of(self, node_name):\n \"\"\" get the name of the parent of the given node\n\n :param node_name: the name of the node\n :type node_name: string\n :rtype: string\n \"\"\"\n return self[int(self.parent_indices[self.index(node_name)].item())]\n\n def index(self, node_name):\n \"\"\" get the index of the node\n \n :param node_name: the name of the node\n :type node_name: string\n :rtype: int\n \"\"\"\n return self._node_indices[node_name]\n\n def drop_nodes_by_names(\n self, node_names: List[str], pairwise_translation=None\n ) -> \"SkeletonTree\":\n new_length = len(self) - len(node_names)\n new_node_names = []\n new_local_translation = torch.zeros(\n new_length, 3, dtype=self.local_translation.dtype\n )\n new_parent_indices = torch.zeros(new_length, dtype=self.parent_indices.dtype)\n parent_indices = self.parent_indices.numpy()\n new_node_indices: dict = {}\n new_node_index = 0\n for node_index in range(len(self)):\n if self[node_index] in node_names:\n continue\n tb_node_index = parent_indices[node_index]\n if tb_node_index != -1:\n local_translation = self.local_translation[node_index, :]\n while tb_node_index != -1 and self[tb_node_index] in node_names:\n local_translation += self.local_translation[tb_node_index, :]\n tb_node_index = parent_indices[tb_node_index]\n assert tb_node_index != -1, \"the root node cannot be dropped\"\n\n if pairwise_translation is not None:\n local_translation = pairwise_translation[\n tb_node_index, node_index, :\n ]\n else:\n local_translation = self.local_translation[node_index, :]\n\n new_node_names.append(self[node_index])\n new_local_translation[new_node_index, :] = local_translation\n if tb_node_index == -1:\n new_parent_indices[new_node_index] = -1\n else:\n new_parent_indices[new_node_index] = new_node_indices[\n self[tb_node_index]\n ]\n new_node_indices[self[node_index]] = new_node_index\n new_node_index += 1\n\n return SkeletonTree(new_node_names, new_parent_indices, new_local_translation)\n\n def keep_nodes_by_names(\n self, node_names: List[str], pairwise_translation=None\n ) -> \"SkeletonTree\":\n nodes_to_drop = list(filter(lambda x: x not in node_names, self))\n return self.drop_nodes_by_names(nodes_to_drop, pairwise_translation)" }, { "identifier": "SkeletonMotion", "path": "poselib/poselib/skeleton/skeleton3d.py", "snippet": "class SkeletonMotion(SkeletonState):\n def __init__(self, tensor_backend, skeleton_tree, is_local, fps, *args, **kwargs):\n self._fps = fps\n super().__init__(tensor_backend, skeleton_tree, is_local, *args, **kwargs)\n\n def clone(self):\n return SkeletonMotion(\n self.tensor.clone(), self.skeleton_tree, self._is_local, self._fps\n )\n\n @property\n def invariant_property(self):\n return {\n \"skeleton_tree\": self.skeleton_tree,\n \"is_local\": self.is_local,\n \"fps\": self.fps,\n }\n\n @property\n def global_velocity(self):\n \"\"\" global velocity \"\"\"\n curr_index = self.num_joints * 4 + 3\n return self.tensor[..., curr_index : curr_index + self.num_joints * 3].reshape(\n *(self.tensor.shape[:-1] + (self.num_joints, 3))\n )\n\n @property\n def global_angular_velocity(self):\n \"\"\" global angular velocity \"\"\"\n curr_index = self.num_joints * 7 + 3\n return self.tensor[..., curr_index : curr_index + self.num_joints * 3].reshape(\n *(self.tensor.shape[:-1] + (self.num_joints, 3))\n )\n\n @property\n def fps(self):\n \"\"\" number of frames per second \"\"\"\n return self._fps\n\n @property\n def time_delta(self):\n \"\"\" time between two adjacent frames \"\"\"\n return 1.0 / self.fps\n\n @property\n def global_root_velocity(self):\n \"\"\" global root velocity \"\"\"\n return self.global_velocity[..., 0, :]\n\n @property\n def global_root_angular_velocity(self):\n \"\"\" global root angular velocity \"\"\"\n return self.global_angular_velocity[..., 0, :]\n\n @classmethod\n def from_state_vector_and_velocity(\n cls,\n skeleton_tree,\n state_vector,\n global_velocity,\n global_angular_velocity,\n is_local,\n fps,\n ):\n \"\"\"\n Construct a skeleton motion from a skeleton state vector, global velocity and angular\n velocity at each joint.\n\n :param skeleton_tree: the skeleton tree that the motion is based on \n :type skeleton_tree: SkeletonTree\n :param state_vector: the state vector from the skeleton state by `.tensor`\n :type state_vector: Tensor\n :param global_velocity: the global velocity at each joint\n :type global_velocity: Tensor\n :param global_angular_velocity: the global angular velocity at each joint\n :type global_angular_velocity: Tensor\n :param is_local: if the rotation ins the state vector is given in local frame\n :type is_local: boolean\n :param fps: number of frames per second\n :type fps: int\n\n :rtype: SkeletonMotion\n \"\"\"\n state_shape = state_vector.shape[:-1]\n v = global_velocity.reshape(*(state_shape + (-1,)))\n av = global_angular_velocity.reshape(*(state_shape + (-1,)))\n new_state_vector = torch.cat([state_vector, v, av], axis=-1)\n return cls(\n new_state_vector, skeleton_tree=skeleton_tree, is_local=is_local, fps=fps,\n )\n\n @classmethod\n def from_skeleton_state(\n cls: Type[\"SkeletonMotion\"], skeleton_state: SkeletonState, fps: int\n ):\n \"\"\"\n Construct a skeleton motion from a skeleton state. The velocities are estimated using second\n order guassian filter along the last axis. The skeleton state must have at least .dim >= 1\n\n :param skeleton_state: the skeleton state that the motion is based on \n :type skeleton_state: SkeletonState\n :param fps: number of frames per second\n :type fps: int\n\n :rtype: SkeletonMotion\n \"\"\"\n\n assert (\n type(skeleton_state) == SkeletonState\n ), \"expected type of {}, got {}\".format(SkeletonState, type(skeleton_state))\n\n global_velocity = SkeletonMotion._compute_velocity(\n p=skeleton_state.global_translation, time_delta=1 / fps\n )\n global_angular_velocity = SkeletonMotion._compute_angular_velocity(\n r=skeleton_state.global_rotation, time_delta=1 / fps\n )\n\n return cls.from_state_vector_and_velocity(\n skeleton_tree=skeleton_state.skeleton_tree,\n state_vector=skeleton_state.tensor,\n global_velocity=global_velocity,\n global_angular_velocity=global_angular_velocity,\n is_local=skeleton_state.is_local,\n fps=fps,\n )\n\n @staticmethod\n def _to_state_vector(rot, rt, vel, avel):\n state_shape = rot.shape[:-2]\n skeleton_state_v = SkeletonState._to_state_vector(rot, rt)\n v = vel.reshape(*(state_shape + (-1,)))\n av = avel.reshape(*(state_shape + (-1,)))\n skeleton_motion_v = torch.cat([skeleton_state_v, v, av], axis=-1)\n return skeleton_motion_v\n\n @classmethod\n def from_dict(\n cls: Type[\"SkeletonMotion\"], dict_repr: OrderedDict, *args, **kwargs\n ) -> \"SkeletonMotion\":\n rot = TensorUtils.from_dict(dict_repr[\"rotation\"], *args, **kwargs)\n rt = TensorUtils.from_dict(dict_repr[\"root_translation\"], *args, **kwargs)\n vel = TensorUtils.from_dict(dict_repr[\"global_velocity\"], *args, **kwargs)\n avel = TensorUtils.from_dict(\n dict_repr[\"global_angular_velocity\"], *args, **kwargs\n )\n return cls(\n SkeletonMotion._to_state_vector(rot, rt, vel, avel),\n skeleton_tree=SkeletonTree.from_dict(\n dict_repr[\"skeleton_tree\"], *args, **kwargs\n ),\n is_local=dict_repr[\"is_local\"],\n fps=dict_repr[\"fps\"],\n )\n\n def to_dict(self) -> OrderedDict:\n return OrderedDict(\n [\n (\"rotation\", tensor_to_dict(self.rotation)),\n (\"root_translation\", tensor_to_dict(self.root_translation)),\n (\"global_velocity\", tensor_to_dict(self.global_velocity)),\n (\"global_angular_velocity\", tensor_to_dict(self.global_angular_velocity)),\n (\"skeleton_tree\", self.skeleton_tree.to_dict()),\n (\"is_local\", self.is_local),\n (\"fps\", self.fps),\n ]\n )\n\n @classmethod\n def from_fbx(\n cls: Type[\"SkeletonMotion\"],\n fbx_file_path,\n fbx_configs,\n skeleton_tree=None,\n is_local=True,\n fps=120,\n root_joint=\"\",\n root_trans_index=0,\n *args,\n **kwargs,\n ) -> \"SkeletonMotion\":\n \"\"\"\n Construct a skeleton motion from a fbx file (TODO - generalize this). If the skeleton tree\n is not given, it will use the first frame of the mocap to construct the skeleton tree.\n\n :param fbx_file_path: the path of the fbx file\n :type fbx_file_path: string\n :param fbx_configs: the configuration in terms of {\"tmp_path\": ..., \"fbx_py27_path\": ...}\n :type fbx_configs: dict\n :param skeleton_tree: the optional skeleton tree that the rotation will be applied to\n :type skeleton_tree: SkeletonTree, optional\n :param is_local: the state vector uses local or global rotation as the representation\n :type is_local: bool, optional, default=True\n :rtype: SkeletonMotion\n \"\"\"\n joint_names, joint_parents, transforms, fps = fbx_to_array(\n fbx_file_path, fbx_configs, root_joint, fps\n )\n # swap the last two axis to match the convention\n local_transform = euclidean_to_transform(\n transformation_matrix=torch.from_numpy(\n np.swapaxes(np.array(transforms), -1, -2),\n ).float()\n )\n local_rotation = transform_rotation(local_transform)\n root_translation = transform_translation(local_transform)[..., root_trans_index, :]\n joint_parents = torch.from_numpy(np.array(joint_parents)).int()\n\n if skeleton_tree is None:\n local_translation = transform_translation(local_transform).reshape(\n -1, len(joint_parents), 3\n )[0]\n skeleton_tree = SkeletonTree(joint_names, joint_parents, local_translation)\n skeleton_state = SkeletonState.from_rotation_and_root_translation(\n skeleton_tree, r=local_rotation, t=root_translation, is_local=True\n )\n if not is_local:\n skeleton_state = skeleton_state.global_repr()\n return cls.from_skeleton_state(\n skeleton_state=skeleton_state, fps=fps\n )\n\n @staticmethod\n def _compute_velocity(p, time_delta, guassian_filter=True):\n velocity = torch.from_numpy(\n filters.gaussian_filter1d(\n np.gradient(p.numpy(), axis=-3), 2, axis=-3, mode=\"nearest\"\n )\n / time_delta,\n )\n return velocity\n\n @staticmethod\n def _compute_angular_velocity(r, time_delta: float, guassian_filter=True):\n # assume the second last dimension is the time axis\n diff_quat_data = quat_identity_like(r)\n diff_quat_data[..., :-1, :, :] = quat_mul_norm(\n r[..., 1:, :, :], quat_inverse(r[..., :-1, :, :])\n )\n diff_angle, diff_axis = quat_angle_axis(diff_quat_data)\n angular_velocity = diff_axis * diff_angle.unsqueeze(-1) / time_delta\n angular_velocity = torch.from_numpy(\n filters.gaussian_filter1d(\n angular_velocity.numpy(), 2, axis=-3, mode=\"nearest\"\n ),\n )\n return angular_velocity\n\n def crop(self, start: int, end: int, fps: Optional[int] = None):\n \"\"\"\n Crop the motion along its last axis. This is equivalent to performing a slicing on the\n object with [..., start: end: skip_every] where skip_every = old_fps / fps. Note that the\n new fps provided must be a factor of the original fps. \n\n :param start: the beginning frame index\n :type start: int\n :param end: the ending frame index\n :type end: int\n :param fps: number of frames per second in the output (if not given the original fps will be used)\n :type fps: int, optional\n :rtype: SkeletonMotion\n \"\"\"\n if fps is None:\n new_fps = int(self.fps)\n old_fps = int(self.fps)\n else:\n new_fps = int(fps)\n old_fps = int(self.fps)\n assert old_fps % fps == 0, (\n \"the resampling doesn't support fps with non-integer division \"\n \"from the original fps: {} => {}\".format(old_fps, fps)\n )\n skip_every = old_fps // new_fps\n s = slice(start, end, skip_every)\n z = self[..., s]\n\n rot = z.local_rotation if z.is_local else z.global_rotation\n rt = z.root_translation\n vel = z.global_velocity\n avel = z.global_angular_velocity\n return SkeletonMotion(\n SkeletonMotion._to_state_vector(rot, rt, vel, avel),\n skeleton_tree=z.skeleton_tree,\n is_local=z.is_local,\n fps=new_fps,\n )\n\n def retarget_to(\n self,\n joint_mapping: Dict[str, str],\n source_tpose_local_rotation,\n source_tpose_root_translation: np.ndarray,\n target_skeleton_tree: \"SkeletonTree\",\n target_tpose_local_rotation,\n target_tpose_root_translation: np.ndarray,\n rotation_to_target_skeleton,\n scale_to_target_skeleton: float,\n z_up: bool = True,\n ) -> \"SkeletonMotion\":\n \"\"\" \n Same as the one in :class:`SkeletonState`. This method discards all velocity information before\n retargeting and re-estimate the velocity after the retargeting. The same fps is used in the\n new retargetted motion.\n\n :param joint_mapping: a dictionary of that maps the joint node from the source skeleton to \\\n the target skeleton\n :type joint_mapping: Dict[str, str]\n \n :param source_tpose_local_rotation: the local rotation of the source skeleton\n :type source_tpose_local_rotation: Tensor\n \n :param source_tpose_root_translation: the root translation of the source tpose\n :type source_tpose_root_translation: np.ndarray\n \n :param target_skeleton_tree: the target skeleton tree\n :type target_skeleton_tree: SkeletonTree\n \n :param target_tpose_local_rotation: the local rotation of the target skeleton\n :type target_tpose_local_rotation: Tensor\n \n :param target_tpose_root_translation: the root translation of the target tpose\n :type target_tpose_root_translation: Tensor\n \n :param rotation_to_target_skeleton: the rotation that needs to be applied to the source\\\n skeleton to align with the target skeleton. Essentially the rotation is t_R_s, where t is\\\n the frame of reference of the target skeleton and s is the frame of reference of the source\\\n skeleton\n :type rotation_to_target_skeleton: Tensor\n :param scale_to_target_skeleton: the factor that needs to be multiplied from source\\\n skeleton to target skeleton (unit in distance). For example, to go from `cm` to `m`, the \\\n factor needs to be 0.01.\n :type scale_to_target_skeleton: float\n :rtype: SkeletonMotion\n \"\"\"\n return SkeletonMotion.from_skeleton_state(\n super().retarget_to(\n joint_mapping,\n source_tpose_local_rotation,\n source_tpose_root_translation,\n target_skeleton_tree,\n target_tpose_local_rotation,\n target_tpose_root_translation,\n rotation_to_target_skeleton,\n scale_to_target_skeleton,\n z_up,\n ),\n self.fps,\n )\n\n def retarget_to_by_tpose(\n self,\n joint_mapping: Dict[str, str],\n source_tpose: \"SkeletonState\",\n target_tpose: \"SkeletonState\",\n rotation_to_target_skeleton,\n scale_to_target_skeleton: float,\n z_up: bool = True,\n ) -> \"SkeletonMotion\":\n \"\"\" \n Same as the one in :class:`SkeletonState`. This method discards all velocity information before\n retargeting and re-estimate the velocity after the retargeting. The same fps is used in the\n new retargetted motion.\n\n :param joint_mapping: a dictionary of that maps the joint node from the source skeleton to \\\n the target skeleton\n :type joint_mapping: Dict[str, str]\n \n :param source_tpose: t-pose of the source skeleton\n :type source_tpose: SkeletonState\n \n :param target_tpose: t-pose of the target skeleton\n :type target_tpose: SkeletonState\n \n :param rotation_to_target_skeleton: the rotation that needs to be applied to the source\\\n skeleton to align with the target skeleton. Essentially the rotation is t_R_s, where t is\\\n the frame of reference of the target skeleton and s is the frame of reference of the source\\\n skeleton\n :type rotation_to_target_skeleton: Tensor\n :param scale_to_target_skeleton: the factor that needs to be multiplied from source\\\n skeleton to target skeleton (unit in distance). For example, to go from `cm` to `m`, the \\\n factor needs to be 0.01.\n :type scale_to_target_skeleton: float\n :rtype: SkeletonMotion\n \"\"\"\n return self.retarget_to(\n joint_mapping,\n source_tpose.local_rotation,\n source_tpose.root_translation,\n target_tpose.skeleton_tree,\n target_tpose.local_rotation,\n target_tpose.root_translation,\n rotation_to_target_skeleton,\n scale_to_target_skeleton,\n z_up,\n )" }, { "identifier": "SkeletonState", "path": "poselib/poselib/skeleton/skeleton3d.py", "snippet": "class SkeletonState(Serializable):\n \"\"\"\n A skeleton state contains all the information needed to describe a static state of a skeleton.\n It requires a skeleton tree, local/global rotation at each joint and the root translation.\n\n Example:\n >>> t = SkeletonTree.from_mjcf(SkeletonTree.__example_mjcf_path__)\n >>> zero_pose = SkeletonState.zero_pose(t)\n >>> plot_skeleton_state(zero_pose) # can be imported from `.visualization.common`\n [plot of the ant at zero pose\n >>> local_rotation = zero_pose.local_rotation.clone()\n >>> local_rotation[2] = torch.tensor([0, 0, 1, 0])\n >>> new_pose = SkeletonState.from_rotation_and_root_translation(\n ... skeleton_tree=t,\n ... r=local_rotation,\n ... t=zero_pose.root_translation,\n ... is_local=True\n ... )\n >>> new_pose.local_rotation\n tensor([[0., 0., 0., 1.],\n [0., 0., 0., 1.],\n [0., 1., 0., 0.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.]])\n >>> plot_skeleton_state(new_pose) # you should be able to see one of ant's leg is bent\n [plot of the ant with the new pose\n >>> new_pose.global_rotation # the local rotation is propagated to the global rotation at joint #3\n tensor([[0., 0., 0., 1.],\n [0., 0., 0., 1.],\n [0., 1., 0., 0.],\n [0., 1., 0., 0.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.]])\n\n Global/Local Representation (cont. from the previous example)\n >>> new_pose.is_local\n True\n >>> new_pose.tensor # this will return the local rotation followed by the root translation\n tensor([0., 0., 0., 1., 0., 0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 1., 0., 0.,\n 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1.,\n 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0.,\n 0.])\n >>> new_pose.tensor.shape # 4 * 13 (joint rotation) + 3 (root translatio\n torch.Size([55])\n >>> new_pose.global_repr().is_local\n False\n >>> new_pose.global_repr().tensor # this will return the global rotation followed by the root translation instead\n tensor([0., 0., 0., 1., 0., 0., 0., 1., 0., 1., 0., 0., 0., 1., 0., 0., 0., 0.,\n 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1.,\n 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0.,\n 0.])\n >>> new_pose.global_repr().tensor.shape # 4 * 13 (joint rotation) + 3 (root translation\n torch.Size([55])\n \"\"\"\n\n def __init__(self, tensor_backend, skeleton_tree, is_local):\n self._skeleton_tree = skeleton_tree\n self._is_local = is_local\n self.tensor = tensor_backend.clone()\n\n def __len__(self):\n return self.tensor.shape[0]\n\n @property\n def rotation(self):\n if not hasattr(self, \"_rotation\"):\n self._rotation = self.tensor[..., : self.num_joints * 4].reshape(\n *(self.tensor.shape[:-1] + (self.num_joints, 4))\n )\n return self._rotation\n\n @property\n def _local_rotation(self):\n if self._is_local:\n return self.rotation\n else:\n return None\n\n @property\n def _global_rotation(self):\n if not self._is_local:\n return self.rotation\n else:\n return None\n\n @property\n def is_local(self):\n \"\"\" is the rotation represented in local frame? \n \n :rtype: bool\n \"\"\"\n return self._is_local\n\n @property\n def invariant_property(self):\n return {\"skeleton_tree\": self.skeleton_tree, \"is_local\": self.is_local}\n\n @property\n def num_joints(self):\n \"\"\" number of joints in the skeleton tree \n \n :rtype: int\n \"\"\"\n return self.skeleton_tree.num_joints\n\n @property\n def skeleton_tree(self):\n \"\"\" skeleton tree \n \n :rtype: SkeletonTree\n \"\"\"\n return self._skeleton_tree\n\n @property\n def root_translation(self):\n \"\"\" root translation \n \n :rtype: Tensor\n \"\"\"\n if not hasattr(self, \"_root_translation\"):\n self._root_translation = self.tensor[\n ..., self.num_joints * 4 : self.num_joints * 4 + 3\n ]\n return self._root_translation\n\n @property\n def global_transformation(self):\n \"\"\" global transformation of each joint (transform from joint frame to global frame) \"\"\"\n # Forward kinemaitcs.\n \n if not hasattr(self, \"_global_transformation\"):\n local_transformation = self.local_transformation.clone()\n global_transformation = []\n parent_indices = self.skeleton_tree.parent_indices.numpy()\n # global_transformation = local_transformation.identity_like()\n \n local_transformation[..., :4] = quat_mul(\n self.skeleton_tree._local_xml_rotation,\n local_transformation[..., :4])\n\n for node_index in range(len(self.skeleton_tree)):\n parent_index = parent_indices[node_index]\n if parent_index == -1:\n global_transformation.append(\n local_transformation[..., node_index, :]\n )\n else:\n # Here to factor in the local xml rotation\n\n global_transformation.append(\n transform_mul(\n global_transformation[parent_index],\n local_transformation[..., node_index, :],\n )\n )\n self._global_transformation = torch.stack(global_transformation, axis=-2)\n return self._global_transformation\n\n @property\n def global_rotation(self):\n \"\"\" global rotation of each joint (rotation matrix to rotate from joint's F.O.R to global\n F.O.R) \"\"\"\n if self._global_rotation is None:\n if not hasattr(self, \"_comp_global_rotation\"):\n self._comp_global_rotation = transform_rotation(\n self.global_transformation\n )\n return self._comp_global_rotation\n else:\n return self._global_rotation\n\n @property\n def global_translation(self):\n \"\"\" global translation of each joint \"\"\"\n if not hasattr(self, \"_global_translation\"):\n self._global_translation = transform_translation(self.global_transformation)\n return self._global_translation\n\n @property\n def global_translation_xy(self):\n \"\"\" global translation in xy \"\"\"\n trans_xy_data = self.global_translation.zeros_like()\n trans_xy_data[..., 0:2] = self.global_translation[..., 0:2]\n return trans_xy_data\n\n @property\n def global_translation_xz(self):\n \"\"\" global translation in xz \"\"\"\n trans_xz_data = self.global_translation.zeros_like()\n trans_xz_data[..., 0:1] = self.global_translation[..., 0:1]\n trans_xz_data[..., 2:3] = self.global_translation[..., 2:3]\n return trans_xz_data\n\n @property\n def local_rotation(self):\n \"\"\" the rotation from child frame to parent frame given in the order of child nodes appeared\n in `.skeleton_tree.node_names` \"\"\"\n if self._local_rotation is None:\n if not hasattr(self, \"_comp_local_rotation\"):\n local_rotation = quat_identity_like(self.global_rotation)\n for node_index in range(len(self.skeleton_tree)):\n parent_index = self.skeleton_tree.parent_indices[node_index]\n if parent_index == -1:\n local_rotation[..., node_index, :] = self.global_rotation[\n ..., node_index, :\n ]\n else:\n local_rotation[..., node_index, :] = quat_mul_norm(\n quat_inverse(self.global_rotation[..., parent_index, :]),\n self.global_rotation[..., node_index, :],\n )\n self._comp_local_rotation = local_rotation\n return self._comp_local_rotation\n else:\n return self._local_rotation\n\n @property\n def local_transformation(self):\n \"\"\" local translation + local rotation. It describes the transformation from child frame to \n parent frame given in the order of child nodes appeared in `.skeleton_tree.node_names` \"\"\"\n if not hasattr(self, \"_local_transformation\"):\n self._local_transformation = transform_from_rotation_translation(\n r=self.local_rotation, t=self.local_translation\n )\n return self._local_transformation\n\n @property\n def local_translation(self):\n \"\"\" local translation of the skeleton state. It is identical to the local translation in\n `.skeleton_tree.local_translation` except the root translation. The root translation is\n identical to `.root_translation` \"\"\"\n if not hasattr(self, \"_local_translation\"):\n broadcast_shape = (\n tuple(self.tensor.shape[:-1])\n + (len(self.skeleton_tree),)\n + tuple(self.skeleton_tree.local_translation.shape[-1:])\n )\n local_translation = self.skeleton_tree.local_translation.broadcast_to(\n *broadcast_shape\n ).clone()\n local_translation[..., 0, :] = self.root_translation\n self._local_translation = local_translation\n return self._local_translation\n\n # Root Properties\n @property\n def root_translation_xy(self):\n \"\"\" root translation on xy \"\"\"\n if not hasattr(self, \"_root_translation_xy\"):\n self._root_translation_xy = self.global_translation_xy[..., 0, :]\n return self._root_translation_xy\n\n @property\n def global_root_rotation(self):\n \"\"\" root rotation \"\"\"\n if not hasattr(self, \"_global_root_rotation\"):\n self._global_root_rotation = self.global_rotation[..., 0, :]\n return self._global_root_rotation\n\n @property\n def global_root_yaw_rotation(self):\n \"\"\" root yaw rotation \"\"\"\n if not hasattr(self, \"_global_root_yaw_rotation\"):\n self._global_root_yaw_rotation = self.global_root_rotation.yaw_rotation()\n return self._global_root_yaw_rotation\n\n # Properties relative to root\n @property\n def local_translation_to_root(self):\n \"\"\" The 3D translation from joint frame to the root frame. \"\"\"\n if not hasattr(self, \"_local_translation_to_root\"):\n self._local_translation_to_root = (\n self.global_translation - self.root_translation.unsqueeze(-1)\n )\n return self._local_translation_to_root\n\n @property\n def local_rotation_to_root(self):\n \"\"\" The 3D rotation from joint frame to the root frame. It is equivalent to \n The root_R_world * world_R_node \"\"\"\n return (\n quat_inverse(self.global_root_rotation).unsqueeze(-1) * self.global_rotation\n )\n\n def compute_forward_vector(\n self,\n left_shoulder_index,\n right_shoulder_index,\n left_hip_index,\n right_hip_index,\n gaussian_filter_width=20,\n ):\n \"\"\" Computes forward vector based on cross product of the up vector with \n average of the right->left shoulder and hip vectors \"\"\"\n global_positions = self.global_translation\n # Perpendicular to the forward direction.\n # Uses the shoulders and hips to find this.\n side_direction = (\n global_positions[:, left_shoulder_index].numpy()\n - global_positions[:, right_shoulder_index].numpy()\n + global_positions[:, left_hip_index].numpy()\n - global_positions[:, right_hip_index].numpy()\n )\n side_direction = (\n side_direction\n / np.sqrt((side_direction ** 2).sum(axis=-1))[..., np.newaxis]\n )\n\n # Forward direction obtained by crossing with the up direction.\n forward_direction = np.cross(side_direction, np.array([[0, 1, 0]]))\n\n # Smooth the forward direction with a Gaussian.\n # Axis 0 is the time/frame axis.\n forward_direction = filters.gaussian_filter1d(\n forward_direction, gaussian_filter_width, axis=0, mode=\"nearest\"\n )\n forward_direction = (\n forward_direction\n / np.sqrt((forward_direction ** 2).sum(axis=-1))[..., np.newaxis]\n )\n\n return torch.from_numpy(forward_direction)\n\n @staticmethod\n def _to_state_vector(rot, rt):\n # Tensorbackend: local rotation and translation, rotation is is in quat 33 * 4 + 3\n state_shape = rot.shape[:-2]\n vr = rot.reshape(*(state_shape + (-1,)))\n vt = rt.broadcast_to(*state_shape + rt.shape[-1:]).reshape(\n *(state_shape + (-1,))\n )\n v = torch.cat([vr, vt], axis=-1)\n return v\n\n @classmethod\n def from_dict(\n cls: Type[\"SkeletonState\"], dict_repr: OrderedDict, *args, **kwargs\n ) -> \"SkeletonState\":\n rot = TensorUtils.from_dict(dict_repr[\"rotation\"], *args, **kwargs)\n rt = TensorUtils.from_dict(dict_repr[\"root_translation\"], *args, **kwargs)\n return cls(\n SkeletonState._to_state_vector(rot, rt),\n SkeletonTree.from_dict(dict_repr[\"skeleton_tree\"], *args, **kwargs),\n dict_repr[\"is_local\"],\n )\n\n def to_dict(self) -> OrderedDict:\n return OrderedDict(\n [\n (\"rotation\", tensor_to_dict(self.rotation)),\n (\"root_translation\", tensor_to_dict(self.root_translation)),\n (\"skeleton_tree\", self.skeleton_tree.to_dict()),\n (\"is_local\", self.is_local),\n ]\n )\n\n @classmethod\n def from_rotation_and_root_translation(cls, skeleton_tree, r, t, is_local=True):\n \"\"\"\n Construct a skeleton state from rotation and root translation\n\n :param skeleton_tree: the skeleton tree\n :type skeleton_tree: SkeletonTree\n :param r: rotation (either global or local)\n :type r: Tensor\n :param t: root translation\n :type t: Tensor\n :param is_local: to indicate that whether the rotation is local or global\n :type is_local: bool, optional, default=True\n \"\"\"\n assert (\n r.dim() > 0\n ), \"the rotation needs to have at least 1 dimension (dim = {})\".format(r.dim)\n return cls(\n SkeletonState._to_state_vector(r, t),\n skeleton_tree=skeleton_tree,\n is_local=is_local,\n )\n\n @classmethod\n def zero_pose(cls, skeleton_tree):\n \"\"\"\n Construct a zero-pose skeleton state from the skeleton tree by assuming that all the local\n rotation is 0 and root translation is also 0.\n\n :param skeleton_tree: the skeleton tree as the rigid body\n :type skeleton_tree: SkeletonTree\n \"\"\"\n return cls.from_rotation_and_root_translation(\n skeleton_tree=skeleton_tree,\n r=quat_identity([skeleton_tree.num_joints]),\n t=torch.zeros(3, dtype=skeleton_tree.local_translation.dtype),\n is_local=True,\n )\n\n def local_repr(self):\n \"\"\" \n Convert the skeleton state into local representation. This will only affects the values of\n .tensor. If the skeleton state already has `is_local=True`. This method will do nothing. \n\n :rtype: SkeletonState\n \"\"\"\n if self.is_local:\n return self\n return SkeletonState.from_rotation_and_root_translation(\n self.skeleton_tree,\n r=self.local_rotation,\n t=self.root_translation,\n is_local=True,\n )\n\n def global_repr(self):\n \"\"\" \n Convert the skeleton state into global representation. This will only affects the values of\n .tensor. If the skeleton state already has `is_local=False`. This method will do nothing. \n\n :rtype: SkeletonState\n \"\"\"\n if not self.is_local:\n return self\n return SkeletonState.from_rotation_and_root_translation(\n self.skeleton_tree,\n r=self.global_rotation,\n t=self.root_translation,\n is_local=False,\n )\n\n def _get_pairwise_average_translation(self):\n global_transform_inv = transform_inverse(self.global_transformation)\n p1 = global_transform_inv.unsqueeze(-2)\n p2 = self.global_transformation.unsqueeze(-3)\n\n pairwise_translation = (\n transform_translation(transform_mul(p1, p2))\n .reshape(-1, len(self.skeleton_tree), len(self.skeleton_tree), 3)\n .mean(axis=0)\n )\n return pairwise_translation\n\n def _transfer_to(self, new_skeleton_tree: SkeletonTree):\n old_indices = list(map(self.skeleton_tree.index, new_skeleton_tree))\n return SkeletonState.from_rotation_and_root_translation(\n new_skeleton_tree,\n r=self.global_rotation[..., old_indices, :],\n t=self.root_translation,\n is_local=False,\n )\n\n def drop_nodes_by_names(\n self, node_names: List[str], estimate_local_translation_from_states: bool = True\n ) -> \"SkeletonState\":\n \"\"\" \n Drop a list of nodes from the skeleton and re-compute the local rotation to match the \n original joint position as much as possible. \n\n :param node_names: a list node names that specifies the nodes need to be dropped\n :type node_names: List of strings\n :param estimate_local_translation_from_states: the boolean indicator that specifies whether\\\n or not to re-estimate the local translation from the states (avg.)\n :type estimate_local_translation_from_states: boolean\n :rtype: SkeletonState\n \"\"\"\n if estimate_local_translation_from_states:\n pairwise_translation = self._get_pairwise_average_translation()\n else:\n pairwise_translation = None\n new_skeleton_tree = self.skeleton_tree.drop_nodes_by_names(\n node_names, pairwise_translation\n )\n return self._transfer_to(new_skeleton_tree)\n\n def keep_nodes_by_names(\n self, node_names: List[str], estimate_local_translation_from_states: bool = True\n ) -> \"SkeletonState\":\n \"\"\" \n Keep a list of nodes and drop all other nodes from the skeleton and re-compute the local \n rotation to match the original joint position as much as possible. \n\n :param node_names: a list node names that specifies the nodes need to be dropped\n :type node_names: List of strings\n :param estimate_local_translation_from_states: the boolean indicator that specifies whether\\\n or not to re-estimate the local translation from the states (avg.)\n :type estimate_local_translation_from_states: boolean\n :rtype: SkeletonState\n \"\"\"\n return self.drop_nodes_by_names(\n list(filter(lambda x: (x not in node_names), self)),\n estimate_local_translation_from_states,\n )\n\n def _remapped_to(\n self, joint_mapping: Dict[str, str], target_skeleton_tree: SkeletonTree\n ):\n joint_mapping_inv = {target: source for source, target in joint_mapping.items()}\n reduced_target_skeleton_tree = target_skeleton_tree.keep_nodes_by_names(\n list(joint_mapping_inv)\n )\n n_joints = (\n len(joint_mapping),\n len(self.skeleton_tree),\n len(reduced_target_skeleton_tree),\n )\n assert (\n len(set(n_joints)) == 1\n ), \"the joint mapping is not consistent with the skeleton trees\"\n source_indices = list(\n map(\n lambda x: self.skeleton_tree.index(joint_mapping_inv[x]),\n reduced_target_skeleton_tree,\n )\n )\n target_local_rotation = self.local_rotation[..., source_indices, :]\n return SkeletonState.from_rotation_and_root_translation(\n skeleton_tree=reduced_target_skeleton_tree,\n r=target_local_rotation,\n t=self.root_translation,\n is_local=True,\n )\n\n def retarget_to(\n self,\n joint_mapping: Dict[str, str],\n source_tpose_local_rotation,\n source_tpose_root_translation: np.ndarray,\n target_skeleton_tree: SkeletonTree,\n target_tpose_local_rotation,\n target_tpose_root_translation: np.ndarray,\n rotation_to_target_skeleton,\n scale_to_target_skeleton: float,\n z_up: bool = True,\n ) -> \"SkeletonState\":\n \"\"\" \n Retarget the skeleton state to a target skeleton tree. This is a naive retarget\n implementation with rough approximations. The function follows the procedures below.\n\n Steps:\n 1. Drop the joints from the source (self) that do not belong to the joint mapping\\\n with an implementation that is similar to \"keep_nodes_by_names()\" - take a\\\n look at the function doc for more details (same for source_tpose)\n \n 2. Rotate the source state and the source tpose by \"rotation_to_target_skeleton\"\\\n to align the source with the target orientation\n \n 3. Extract the root translation and normalize it to match the scale of the target\\\n skeleton\n \n 4. Extract the global rotation from source state relative to source tpose and\\\n re-apply the relative rotation to the target tpose to construct the global\\\n rotation after retargetting\n \n 5. Combine the computed global rotation and the root translation from 3 and 4 to\\\n complete the retargeting.\n \n 6. Make feet on the ground (global translation z)\n\n :param joint_mapping: a dictionary of that maps the joint node from the source skeleton to \\\n the target skeleton\n :type joint_mapping: Dict[str, str]\n \n :param source_tpose_local_rotation: the local rotation of the source skeleton\n :type source_tpose_local_rotation: Tensor\n \n :param source_tpose_root_translation: the root translation of the source tpose\n :type source_tpose_root_translation: np.ndarray\n \n :param target_skeleton_tree: the target skeleton tree\n :type target_skeleton_tree: SkeletonTree\n \n :param target_tpose_local_rotation: the local rotation of the target skeleton\n :type target_tpose_local_rotation: Tensor\n \n :param target_tpose_root_translation: the root translation of the target tpose\n :type target_tpose_root_translation: Tensor\n \n :param rotation_to_target_skeleton: the rotation that needs to be applied to the source\\\n skeleton to align with the target skeleton. Essentially the rotation is t_R_s, where t is\\\n the frame of reference of the target skeleton and s is the frame of reference of the source\\\n skeleton\n :type rotation_to_target_skeleton: Tensor\n :param scale_to_target_skeleton: the factor that needs to be multiplied from source\\\n skeleton to target skeleton (unit in distance). For example, to go from `cm` to `m`, the \\\n factor needs to be 0.01.\n :type scale_to_target_skeleton: float\n :rtype: SkeletonState\n \"\"\"\n\n # STEP 0: Preprocess\n source_tpose = SkeletonState.from_rotation_and_root_translation(\n skeleton_tree=self.skeleton_tree,\n r=source_tpose_local_rotation,\n t=source_tpose_root_translation,\n is_local=True,\n )\n target_tpose = SkeletonState.from_rotation_and_root_translation(\n skeleton_tree=target_skeleton_tree,\n r=target_tpose_local_rotation,\n t=target_tpose_root_translation,\n is_local=True,\n )\n\n # STEP 1: Drop the irrelevant joints\n pairwise_translation = self._get_pairwise_average_translation()\n node_names = list(joint_mapping)\n new_skeleton_tree = self.skeleton_tree.keep_nodes_by_names(\n node_names, pairwise_translation\n )\n\n # TODO: combine the following steps before STEP 3\n source_tpose = source_tpose._transfer_to(new_skeleton_tree)\n source_state = self._transfer_to(new_skeleton_tree)\n\n source_tpose = source_tpose._remapped_to(joint_mapping, target_skeleton_tree)\n source_state = source_state._remapped_to(joint_mapping, target_skeleton_tree)\n\n # STEP 2: Rotate the source to align with the target\n new_local_rotation = source_tpose.local_rotation.clone()\n new_local_rotation[..., 0, :] = quat_mul_norm(\n rotation_to_target_skeleton, source_tpose.local_rotation[..., 0, :]\n )\n\n source_tpose = SkeletonState.from_rotation_and_root_translation(\n skeleton_tree=source_tpose.skeleton_tree,\n r=new_local_rotation,\n t=quat_rotate(rotation_to_target_skeleton, source_tpose.root_translation),\n is_local=True,\n )\n\n new_local_rotation = source_state.local_rotation.clone()\n new_local_rotation[..., 0, :] = quat_mul_norm(\n rotation_to_target_skeleton, source_state.local_rotation[..., 0, :]\n )\n source_state = SkeletonState.from_rotation_and_root_translation(\n skeleton_tree=source_state.skeleton_tree,\n r=new_local_rotation,\n t=quat_rotate(rotation_to_target_skeleton, source_state.root_translation),\n is_local=True,\n )\n\n # STEP 3: Normalize to match the target scale\n root_translation_diff = (\n source_state.root_translation - source_tpose.root_translation\n ) * scale_to_target_skeleton\n\n # STEP 4: the global rotation from source state relative to source tpose and\n # re-apply to the target\n current_skeleton_tree = source_state.skeleton_tree\n target_tpose_global_rotation = source_state.global_rotation[0, :].clone()\n for current_index, name in enumerate(current_skeleton_tree):\n if name in target_tpose.skeleton_tree:\n target_tpose_global_rotation[\n current_index, :\n ] = target_tpose.global_rotation[\n target_tpose.skeleton_tree.index(name), :\n ]\n\n global_rotation_diff = quat_mul_norm(\n source_state.global_rotation, quat_inverse(source_tpose.global_rotation)\n )\n new_global_rotation = quat_mul_norm(\n global_rotation_diff, target_tpose_global_rotation\n )\n\n # STEP 5: Putting 3 and 4 together\n current_skeleton_tree = source_state.skeleton_tree\n shape = source_state.global_rotation.shape[:-1]\n shape = shape[:-1] + target_tpose.global_rotation.shape[-2:-1]\n new_global_rotation_output = quat_identity(shape)\n for current_index, name in enumerate(target_skeleton_tree):\n while name not in current_skeleton_tree:\n name = target_skeleton_tree.parent_of(name)\n parent_index = current_skeleton_tree.index(name)\n new_global_rotation_output[:, current_index, :] = new_global_rotation[\n :, parent_index, :\n ]\n\n source_state = SkeletonState.from_rotation_and_root_translation(\n skeleton_tree=target_skeleton_tree,\n r=new_global_rotation_output,\n t=target_tpose.root_translation + root_translation_diff,\n is_local=False,\n ).local_repr()\n\n return source_state\n\n def retarget_to_by_tpose(\n self,\n joint_mapping: Dict[str, str],\n source_tpose: \"SkeletonState\",\n target_tpose: \"SkeletonState\",\n rotation_to_target_skeleton,\n scale_to_target_skeleton: float,\n ) -> \"SkeletonState\":\n \"\"\" \n Retarget the skeleton state to a target skeleton tree. This is a naive retarget\n implementation with rough approximations. See the method `retarget_to()` for more information\n\n :param joint_mapping: a dictionary of that maps the joint node from the source skeleton to \\\n the target skeleton\n :type joint_mapping: Dict[str, str]\n \n :param source_tpose: t-pose of the source skeleton\n :type source_tpose: SkeletonState\n \n :param target_tpose: t-pose of the target skeleton\n :type target_tpose: SkeletonState\n \n :param rotation_to_target_skeleton: the rotation that needs to be applied to the source\\\n skeleton to align with the target skeleton. Essentially the rotation is t_R_s, where t is\\\n the frame of reference of the target skeleton and s is the frame of reference of the source\\\n skeleton\n :type rotation_to_target_skeleton: Tensor\n :param scale_to_target_skeleton: the factor that needs to be multiplied from source\\\n skeleton to target skeleton (unit in distance). For example, to go from `cm` to `m`, the \\\n factor needs to be 0.01.\n :type scale_to_target_skeleton: float\n :rtype: SkeletonState\n \"\"\"\n assert (\n len(source_tpose.shape) == 0 and len(target_tpose.shape) == 0\n ), \"the retargeting script currently doesn't support vectorized operations\"\n return self.retarget_to(\n joint_mapping,\n source_tpose.local_rotation,\n source_tpose.root_translation,\n target_tpose.skeleton_tree,\n target_tpose.local_rotation,\n target_tpose.root_translation,\n rotation_to_target_skeleton,\n scale_to_target_skeleton,\n )" }, { "identifier": "SMPL_BONE_ORDER_NAMES", "path": "uhc/smpllib/smpl_mujoco.py", "snippet": "class SMPLConverter:\nclass SMPL_M_Renderer(object):\nclass SMPL_M_Viewer(object):\n def __init__(self, model, new_model, smpl_model=\"smpl\"):\n def qpos_smpl_2_new(self, qpos):\n def qvel_smpl_2_new(self, qpvel):\n def qpos_new_2_smpl(self, qpos):\n def qvel_new_2_smpl(self, qvel):\n def jpos_new_2_smpl(self, jpos):\n def get_new_qpos_lim(self):\n def get_new_qvel_lim(self):\n def get_new_body_lim(self):\n def get_new_diff_weight(self):\n def get_new_jkp(self):\n def get_new_jkd(self):\n def get_new_a_scale(self):\n def get_new_torque_limit(self):\n def __init__(\n self,\n model_file=\"/hdd/zen/dev/copycat/Copycat/assets/mujoco_models/humanoid_smpl_neutral_mesh.xml\",\n render_size=(960, 480),\n ):\n def render_smpl(\n self,\n body_pose,\n tran=None,\n output_name=None,\n size=(960, 480),\n frame_rate=30,\n add_text=None,\n offset_z=0,\n ):\n def render_qpose_and_write(\n self,\n qpos,\n output_name=None,\n size=(960, 480),\n frame_rate=30,\n add_text=None,\n offset_z=0,\n follow=False,\n ):\n def render_qpose(\n self,\n qpose,\n size=(960, 480),\n frame_rate=30,\n add_text=None,\n offset_z=0,\n follow=False,\n ):\n def show_pose(self, size=(960, 480), loop=False):\n def set_smpl_pose(self, pose, tran=None, offset_z=0):\n def set_smpl_pose_6d(self, full_pose, tran=None, offset_z=0):\n def set_qpose(self, qpose):\n def show_pose_thread(self, return_img=False):\n def __init__(\n self,\n model_file=\"/hdd/zen/dev/copycat/Copycat/assets/mujoco_models/humanoid_smpl_neutral_mesh.xml\",\n render_size=(960, 480),\n ):\n def render_qpose(self, qpose, follow=False):\n def show_pose(self, return_img=False, size=(1920, 1080), loop=False):\n def show_pose_in_thread(self, return_img=False, size=(1920, 1080)):\n def show_pose_thread(self, return_img=False):\n def set_smpl_pose(self, pose, trans=None, offset_z=0):\n def set_smpl_pose_6d(self, full_pose, offset_z=0):\n def set_qpose(self, qpose):\ndef smplh_to_smpl(pose):\ndef smpl_to_smplh(pose):\ndef smpl_to_qpose(\n pose,\n mj_model,\n trans=None,\n normalize=False,\n random_root=False,\n count_offset=True,\n use_quat=False,\n euler_order=\"ZYX\",\n model=\"smpl\",\n):\ndef smpl_to_qpose_multi(\n pose,\n offset,\n mujoco_body_order,\n num_people=1,\n trans=None,\n normalize=False,\n random_root=False,\n count_offset=True,\n use_quat=False,\n euler_order=\"ZYX\",\n model=\"smpl\",\n):\ndef smpl_to_qpose_torch(\n pose,\n mj_model,\n trans=None,\n normalize=False,\n random_root=False,\n count_offset=True,\n use_quat=False,\n euler_order=\"ZYX\",\n model=\"smpl\",\n):\ndef qpos_to_smpl(qpos, mj_model, smpl_model=\"smpl\"):\ndef qpos_to_smpl_torch(qpos, mj_model, smpl_model=\"smpl\"):\ndef smpl_6d_to_qpose(full_pose, model, normalize=False):\ndef normalize_smpl_pose(pose_aa, trans=None, random_root=False):" } ]
import os import argparse import numpy as np import scenepic as sp import torch import cv2 import joblib from uhc.smpllib.smpl_parser import ( SMPL_Parser, SMPLH_Parser, SMPLX_Parser, ) from tqdm import tqdm from scipy.spatial.transform import Rotation as sRot from poselib.poselib.skeleton.skeleton3d import SkeletonTree,SkeletonMotion, SkeletonState from uhc.smpllib.smpl_mujoco import SMPL_BONE_ORDER_NAMES as joint_names
21,232
"""Example script demonstrating the basic ScenePic functionality.""" mujoco_joint_names = [ 'Pelvis', 'L_Hip', 'L_Knee', 'L_Ankle', 'L_Toe', 'R_Hip', 'R_Knee', 'R_Ankle', 'R_Toe', 'Torso', 'Spine', 'Chest', 'Neck', 'Head', 'L_Thorax', 'L_Shoulder', 'L_Elbow', 'L_Wrist', 'L_Hand', 'R_Thorax', 'R_Shoulder', 'R_Elbow', 'R_Wrist', 'R_Hand' ] Name = "getting_started" Title = "Getting Started" data_dir = "data/smpl" smpl_parser_n = SMPL_Parser(model_path=data_dir,gender="neutral") smpl_parser_m = SMPL_Parser(model_path=data_dir,gender="male") smpl_parser_f = SMPL_Parser(model_path=data_dir,gender="female") # texture_path ="/hdd/zen/data/SURREAL/smpl_data/" # texture_image = cv2.imread("/hdd/zen/data/SURREAL/smpl_data/textures/male/nongrey_male_0550.jpg") pkl_dir = "output/renderings/smpl_ego_4_1-2022-10-05-20:51:40.pkl" Name = pkl_dir.split("/")[-1].split(".")[0] pkl_data = joblib.load(pkl_dir) mujoco_2_smpl = [ mujoco_joint_names.index(q) for q in joint_names if q in mujoco_joint_names ] def build_scene() -> sp.Scene: scene = sp.Scene() scene.framerate = 30 base_size = 600 num_per_row = 4 items = list(pkl_data.items()) # num_items = 4 num_items = len(items) for entry_key, data_seq in items[:num_items]: main = scene.create_canvas_3d(width=base_size, height=base_size, canvas_id=entry_key) gender, beta = data_seq['betas'][0], data_seq['betas'][1:] if gender == 0: smpl_parser = smpl_parser_n humanoid_color = np.array([[0, 1, 100]]).repeat(6890, axis=0) elif gender == 1: smpl_parser = smpl_parser_m humanoid_color = np.array([[0, 0.75, 1]]).repeat(6890, axis=0) else: smpl_parser = smpl_parser_f humanoid_color = np.array([[0.8, 0.15, 0.15]]).repeat(6890, axis=0) ground = scene.create_mesh("ground") ground.add_quad(color=sp.Colors.Gray, p0=np.array([-50, -50, 0]), p1=np.array([50, -50, 0]), p2=np.array([50, 50, 0]), p3=np.array([-50, 50, 0]), normal =np.array([0, 0, 1]) ) ref_jt_pos_full = data_seq['body_pos_full'].numpy()[::2] skeleon_motion = SkeletonMotion.from_dict(data_seq) offset = skeleon_motion.skeleton_tree.local_translation[0] global_rot = skeleon_motion.global_rotation B, J, N = global_rot.shape pose_quat_global = (sRot.from_quat(global_rot.reshape(-1, 4).numpy()) * sRot.from_quat([0.5, 0.5, 0.5, 0.5])).as_quat().reshape(B, -1, 4)[::2] # downsample to 30 fps B_down = pose_quat_global.shape[0] body_trans = skeleon_motion.global_translation[::2] root_trans = body_trans[:, 0] root_trans_offset = root_trans - offset
"""Example script demonstrating the basic ScenePic functionality.""" mujoco_joint_names = [ 'Pelvis', 'L_Hip', 'L_Knee', 'L_Ankle', 'L_Toe', 'R_Hip', 'R_Knee', 'R_Ankle', 'R_Toe', 'Torso', 'Spine', 'Chest', 'Neck', 'Head', 'L_Thorax', 'L_Shoulder', 'L_Elbow', 'L_Wrist', 'L_Hand', 'R_Thorax', 'R_Shoulder', 'R_Elbow', 'R_Wrist', 'R_Hand' ] Name = "getting_started" Title = "Getting Started" data_dir = "data/smpl" smpl_parser_n = SMPL_Parser(model_path=data_dir,gender="neutral") smpl_parser_m = SMPL_Parser(model_path=data_dir,gender="male") smpl_parser_f = SMPL_Parser(model_path=data_dir,gender="female") # texture_path ="/hdd/zen/data/SURREAL/smpl_data/" # texture_image = cv2.imread("/hdd/zen/data/SURREAL/smpl_data/textures/male/nongrey_male_0550.jpg") pkl_dir = "output/renderings/smpl_ego_4_1-2022-10-05-20:51:40.pkl" Name = pkl_dir.split("/")[-1].split(".")[0] pkl_data = joblib.load(pkl_dir) mujoco_2_smpl = [ mujoco_joint_names.index(q) for q in joint_names if q in mujoco_joint_names ] def build_scene() -> sp.Scene: scene = sp.Scene() scene.framerate = 30 base_size = 600 num_per_row = 4 items = list(pkl_data.items()) # num_items = 4 num_items = len(items) for entry_key, data_seq in items[:num_items]: main = scene.create_canvas_3d(width=base_size, height=base_size, canvas_id=entry_key) gender, beta = data_seq['betas'][0], data_seq['betas'][1:] if gender == 0: smpl_parser = smpl_parser_n humanoid_color = np.array([[0, 1, 100]]).repeat(6890, axis=0) elif gender == 1: smpl_parser = smpl_parser_m humanoid_color = np.array([[0, 0.75, 1]]).repeat(6890, axis=0) else: smpl_parser = smpl_parser_f humanoid_color = np.array([[0.8, 0.15, 0.15]]).repeat(6890, axis=0) ground = scene.create_mesh("ground") ground.add_quad(color=sp.Colors.Gray, p0=np.array([-50, -50, 0]), p1=np.array([50, -50, 0]), p2=np.array([50, 50, 0]), p3=np.array([-50, 50, 0]), normal =np.array([0, 0, 1]) ) ref_jt_pos_full = data_seq['body_pos_full'].numpy()[::2] skeleon_motion = SkeletonMotion.from_dict(data_seq) offset = skeleon_motion.skeleton_tree.local_translation[0] global_rot = skeleon_motion.global_rotation B, J, N = global_rot.shape pose_quat_global = (sRot.from_quat(global_rot.reshape(-1, 4).numpy()) * sRot.from_quat([0.5, 0.5, 0.5, 0.5])).as_quat().reshape(B, -1, 4)[::2] # downsample to 30 fps B_down = pose_quat_global.shape[0] body_trans = skeleon_motion.global_translation[::2] root_trans = body_trans[:, 0] root_trans_offset = root_trans - offset
new_sk_state = SkeletonState.from_rotation_and_root_translation(
5
2023-10-31 20:47:12+00:00
24k
Improbable-AI/dexenv
dexenv/envs/dclaw_multiobjs.py
[ { "identifier": "DClawBase", "path": "dexenv/envs/dclaw_base.py", "snippet": "class DClawBase(VecTask):\n\n def __init__(self, cfg, sim_device, rl_device, graphics_device_id):\n\n self.cfg = cfg\n headless = self.cfg.headless\n self.randomize = self.cfg[\"task\"][\"randomize\"]\n if self.randomize:\n logger.warning(f'Domain randomization is enabled!')\n self.randomization_params = self.cfg[\"task\"][\"randomization_params\"]\n self.aggregate_mode = self.cfg[\"env\"][\"aggregateMode\"]\n\n self.dist_reward_scale = self.cfg[\"env\"][\"rew\"][\"distRewardScale\"]\n self.rot_reward_scale = self.cfg[\"env\"][\"rew\"][\"rotRewardScale\"]\n self.success_tolerance = self.cfg[\"env\"][\"rew\"][\"successTolerance\"]\n self.reach_goal_bonus = self.cfg[\"env\"][\"rew\"][\"reachGoalBonus\"]\n self.fall_dist = self.cfg[\"env\"][\"rew\"][\"fallDistance\"]\n self.fall_penalty = self.cfg[\"env\"][\"rew\"][\"fallPenalty\"]\n self.rot_eps = self.cfg[\"env\"][\"rew\"][\"rotEps\"]\n\n self.vel_obs_scale = 0.2 # scale factor of velocity based observations\n self.force_torque_obs_scale = 10.0 # scale factor of velocity based observations\n\n self.reset_position_noise = self.cfg[\"env\"][\"resetPositionNoise\"]\n self.reset_rotation_noise = self.cfg[\"env\"][\"resetRotationNoise\"]\n self.reset_dof_pos_noise = self.cfg[\"env\"][\"resetDofPosRandomInterval\"]\n self.reset_dof_vel_noise = self.cfg[\"env\"][\"resetDofVelRandomInterval\"]\n\n self.force_scale = self.cfg[\"env\"].get(\"forceScale\", 0.0)\n self.force_prob_range = self.cfg[\"env\"].get(\"forceProbRange\", [0.001, 0.1])\n self.force_decay = self.cfg[\"env\"].get(\"forceDecay\", 0.99)\n self.force_decay_interval = self.cfg[\"env\"].get(\"forceDecayInterval\", 0.08)\n\n self.dclaw_dof_speed_scale = self.cfg[\"env\"][\"dofSpeedScale\"]\n # self.act_moving_average = self.cfg[\"env\"][\"actionsMovingAverage\"]\n\n self.debug_viz = self.cfg[\"env\"][\"enableDebugVis\"]\n\n self.max_episode_length = self.cfg[\"env\"][\"episodeLength\"]\n self.reset_time = self.cfg[\"env\"].get(\"resetTime\", -1.0)\n self.print_success_stat = self.cfg[\"env\"][\"printNumSuccesses\"]\n self.max_consecutive_successes = self.cfg[\"env\"][\"maxConsecutiveSuccesses\"]\n self.av_factor = self.cfg[\"env\"].get(\"averFactor\", 0.1)\n\n self.object_type = self.cfg[\"env\"][\"objectType\"]\n\n self.asset_files_dict = {\n \"block\": \"urdf/objects/cube_multicolor.urdf\",\n \"egg\": \"mjcf/open_ai_assets/hand/egg.xml\",\n \"airplane\": \"single_objects/airplane/model.urdf\",\n 'power_drill': 'single_objects/power_drill/model.urdf',\n 'mug': 'single_objects/mug/model.urdf',\n 'elephant': 'asymm/train/elephant/var_000/model.urdf',\n 'train': 'asymm/train/train/var_000/model.urdf',\n 'stanford_bunny': 'asymm/train/stanford_bunny/var_004/model.urdf'\n\n }\n self.objs_in_isaacgym = ['block', 'egg']\n\n if \"asset\" in self.cfg[\"env\"]:\n self.asset_files_dict[\"block\"] = self.cfg[\"env\"][\"asset\"].get(\"assetFileNameBlock\",\n self.asset_files_dict[\"block\"])\n self.asset_files_dict[\"egg\"] = self.cfg[\"env\"][\"asset\"].get(\"assetFileNameEgg\",\n self.asset_files_dict[\"egg\"])\n\n self.obs_type = self.cfg[\"env\"][\"observationType\"]\n\n if not (self.obs_type in [\"full_no_vel\", \"full\", \"full_state\"]):\n raise Exception(\n \"Unknown type of observations!\\nobservationType should be one of: [openai, full_no_vel, full, full_state]\")\n\n print(\"Obs type:\", self.obs_type)\n\n ## TODO: change value here\n self.num_obs_dict = {\n \"full_no_vel\": 42,\n \"full\": 87,\n \"full_state\": 114\n }\n\n self.up_axis = 'z'\n\n num_states = 0\n\n self.cfg[\"env\"][\"numObservations\"] = self.num_obs_dict[self.obs_type]\n self.cfg[\"env\"][\"numStates\"] = num_states\n self.cfg[\"env\"][\"numActions\"] = 12\n self.hist_buf_reset_env_ids = None\n\n super().__init__(config=self.cfg,\n sim_device=sim_device,\n rl_device=rl_device,\n graphics_device_id=graphics_device_id,\n headless=headless)\n\n self.dt = self.sim_params.dt\n control_freq_inv = self.cfg[\"env\"].get(\"controlFrequencyInv\", 1)\n if self.reset_time > 0.0:\n self.max_episode_length = int(round(self.reset_time / (control_freq_inv * self.dt)))\n print(\"Reset time: \", self.reset_time)\n print(\"New episode length: \", self.max_episode_length)\n\n if self.viewer != None:\n cam_pos = gymapi.Vec3(0.16, -0.5, 0.5)\n cam_target = gymapi.Vec3(0.0, 0.0, 0.15)\n self.gym.viewer_camera_look_at(self.viewer, None, cam_pos, cam_target)\n\n actor_root_state_tensor = self.gym.acquire_actor_root_state_tensor(self.sim)\n dof_state_tensor = self.gym.acquire_dof_state_tensor(self.sim)\n rigid_body_tensor = self.gym.acquire_rigid_body_state_tensor(self.sim)\n dof_force_tensor = self.gym.acquire_dof_force_tensor(self.sim)\n\n if self.obs_type == \"full_state\":\n sensor_tensor = self.gym.acquire_force_sensor_tensor(self.sim)\n self.vec_sensor_tensor = gymtorch.wrap_tensor(sensor_tensor).view(self.num_envs, self.num_fingertips * 6)\n\n dof_force_tensor = self.gym.acquire_dof_force_tensor(self.sim)\n self.dof_force_tensor = gymtorch.wrap_tensor(dof_force_tensor).view(self.num_envs,\n self.num_dclaw_dofs)\n\n self.gym.refresh_actor_root_state_tensor(self.sim)\n self.gym.refresh_dof_state_tensor(self.sim)\n if self.cfg.env.dof_torque_on:\n self.gym.refresh_dof_force_tensor(self.sim)\n self.gym.refresh_rigid_body_state_tensor(self.sim)\n\n self.dof_state = gymtorch.wrap_tensor(dof_state_tensor)\n self.dclaw_dof_state = self.dof_state.view(self.num_envs, -1, 2)[:, :self.num_dclaw_dofs]\n self.dclaw_dof_pos = self.dclaw_dof_state[..., 0]\n self.dclaw_dof_vel = self.dclaw_dof_state[..., 1]\n if self.cfg.env.dof_torque_on:\n self.dclaw_dof_torque = gymtorch.wrap_tensor(dof_force_tensor).view(self.num_envs, -1)\n else:\n self.dclaw_dof_torque = None\n\n self.rigid_body_states = gymtorch.wrap_tensor(rigid_body_tensor).view(self.num_envs, -1, 13)\n self.num_bodies = self.rigid_body_states.shape[1]\n\n self.root_state_tensor = gymtorch.wrap_tensor(actor_root_state_tensor).view(-1, 13)\n\n if self.cfg.env.rew.pen_tb_contact:\n _net_cf = self.gym.acquire_net_contact_force_tensor(self.sim)\n self.net_contact_force = gymtorch.wrap_tensor(_net_cf).view(self.num_envs, -1, 3)\n table_handle = self.gym.find_actor_handle(self.envs[0], 'table')\n self.table_body_index = self.gym.find_actor_rigid_body_index(self.envs[0],\n table_handle,\n 'table',\n gymapi.DOMAIN_ENV)\n logger.warning(f'Table body index:{self.table_body_index}')\n self.table_contact_force = self.net_contact_force[:, self.table_body_index]\n\n self.num_dofs = self.gym.get_sim_dof_count(self.sim) // self.num_envs\n self.prev_targets = torch.zeros((self.num_envs, self.num_dofs), dtype=torch.float, device=self.device)\n self.cur_targets = torch.zeros((self.num_envs, self.num_dofs), dtype=torch.float, device=self.device)\n\n self.global_indices = torch.arange(self.num_envs * 3, dtype=torch.int32, device=self.device).view(self.num_envs, -1)\n\n self.reset_goal_buf = self.reset_buf.clone()\n self.successes = torch.zeros(self.num_envs, dtype=torch.float, device=self.device)\n self.consecutive_successes = torch.zeros(1, dtype=torch.float, device=self.device)\n\n self.av_factor = to_torch(self.av_factor, dtype=torch.float, device=self.device)\n\n self.total_successes = 0\n self.total_resets = 0\n\n self.force_decay = to_torch(self.force_decay, dtype=torch.float, device=self.device)\n self.force_prob_range = to_torch(self.force_prob_range, dtype=torch.float, device=self.device)\n self.random_force_prob = torch.exp((torch.log(self.force_prob_range[0]) - torch.log(self.force_prob_range[1]))\n * torch.rand(self.num_envs, device=self.device) + torch.log(\n self.force_prob_range[1]))\n\n self.rb_forces = torch.zeros((self.num_envs, self.num_bodies, 3), dtype=torch.float, device=self.device)\n\n self.num_actions = self.num_dclaw_dofs\n self.actions = self.zero_actions()\n DClawBase.compute_observations(self)\n self.num_observations = self.obs_buf.shape[-1]\n self.cfg.env.numObservations = self.num_observations\n self.create_ob_act_space()\n\n def create_sim(self):\n self.dt = self.cfg[\"sim\"][\"dt\"]\n self.up_axis_idx = self.set_sim_params_up_axis(self.sim_params, self.up_axis)\n\n self.sim = super().create_sim(self.device_id, self.graphics_device_id, self.physics_engine, self.sim_params)\n self._create_ground_plane()\n self._create_envs(self.num_envs, self.cfg[\"env\"]['envSpacing'], int(np.sqrt(self.num_envs)))\n\n if self.randomize:\n self.apply_randomizations(self.randomization_params)\n\n def _create_ground_plane(self):\n plane_params = gymapi.PlaneParams()\n plane_params.normal = gymapi.Vec3(0.0, 0.0, 1.0)\n plane_params.distance = 0.1\n self.gym.add_ground(self.sim, plane_params)\n\n def _create_envs(self, num_envs, spacing, num_per_row):\n lower = gymapi.Vec3(-spacing, -spacing, 0.0)\n upper = gymapi.Vec3(spacing, spacing, spacing)\n\n asset_root = dexenv.LIB_PATH.joinpath('assets', 'dclaw').as_posix()\n object_asset_file = self.asset_files_dict[self.object_type]\n\n dclaw_asset, dclaw_dof_props = self.get_dclaw_asset(asset_root=asset_root)\n table_asset = self.get_table_asset()\n table_pose = self.get_table_pose()\n\n if self.obs_type == \"full_state\":\n sensor_pose = gymapi.Transform()\n for ft_handle in self.fingertip_handles:\n self.gym.create_asset_force_sensor(dclaw_asset, ft_handle, sensor_pose)\n\n if self.object_type in self.objs_in_isaacgym:\n asset_root = get_module_path('isaacgymenvs').parent.joinpath('assets').as_posix()\n else:\n asset_root = dexenv.LIB_PATH.joinpath('assets').as_posix()\n\n object_asset_options = gymapi.AssetOptions()\n if self.cfg.env.vhacd:\n object_asset_options.convex_decomposition_from_submeshes = True\n\n object_asset = self.gym.load_asset(self.sim, asset_root, object_asset_file, object_asset_options)\n\n object_asset_options.disable_gravity = True\n goal_asset = self.gym.load_asset(self.sim, asset_root, object_asset_file, object_asset_options)\n\n dclaw_start_pose = self.get_dclaw_start_pose()\n object_start_pose = self.get_object_start_pose(dclaw_start_pose)\n\n goal_start_pose = self.get_goal_object_start_pose(object_start_pose=object_start_pose)\n\n self.dclaws = []\n self.envs = []\n\n self.object_init_state = []\n self.hand_start_states = []\n\n self.hand_indices = []\n self.fingertip_indices = []\n self.object_indices = []\n self.goal_object_indices = []\n\n self.render_camera_handles = []\n if self.cfg.rgb_render:\n render_cam_pose, render_cam_params = self.get_visual_render_camera_setup()\n\n self.fingertip_handles = [self.gym.find_asset_rigid_body_index(dclaw_asset, name) for name in\n self.fingertips]\n print(f'Fingertip handles:{self.fingertip_handles}')\n\n dclaw_rb_count = self.gym.get_asset_rigid_body_count(dclaw_asset)\n object_rb_count = self.gym.get_asset_rigid_body_count(object_asset)\n object_rs_count = self.gym.get_asset_rigid_shape_count(object_asset)\n self.object_rb_handles = list(range(dclaw_rb_count, dclaw_rb_count + object_rb_count))\n self.object_handles = []\n\n max_agg_bodies = self.num_dclaw_bodies + 2 * object_rb_count + 1\n max_agg_shapes = self.num_dclaw_shapes + 2 * object_rs_count + 1\n\n for i in range(self.num_envs):\n env_ptr = self.gym.create_env(\n self.sim, lower, upper, num_per_row\n )\n\n if self.aggregate_mode >= 1:\n self.gym.begin_aggregate(env_ptr, max_agg_bodies, max_agg_shapes, True)\n\n self.create_hand_actor(env_ptr=env_ptr,\n dclaw_asset=dclaw_asset,\n dclaw_start_pose=dclaw_start_pose,\n dclaw_dof_props=dclaw_dof_props,\n env_id=i)\n\n object_handle = self.gym.create_actor(env_ptr, object_asset, object_start_pose, \"object\", i, 0, 1)\n self.object_handles.append(object_handle)\n self.object_init_state.append([object_start_pose.p.x, object_start_pose.p.y, object_start_pose.p.z,\n object_start_pose.r.x, object_start_pose.r.y, object_start_pose.r.z,\n object_start_pose.r.w,\n 0, 0, 0, 0, 0, 0])\n object_idx = self.gym.get_actor_index(env_ptr, object_handle, gymapi.DOMAIN_SIM)\n self.object_indices.append(object_idx)\n\n goal_handle = self.gym.create_actor(env_ptr, goal_asset, goal_start_pose, \"goal_object\", i + self.num_envs,\n 0, 2)\n goal_object_idx = self.gym.get_actor_index(env_ptr, goal_handle, gymapi.DOMAIN_SIM)\n self.goal_object_indices.append(goal_object_idx)\n\n if self.cfg.env.blockscale is not None and self.cfg.env.objectType == 'block':\n blockscale = float(self.cfg.env.blockscale)\n self.gym.set_actor_scale(env_ptr, object_handle, blockscale)\n self.gym.set_actor_scale(env_ptr, goal_handle, blockscale)\n\n if self.object_type != \"block\":\n self.gym.set_rigid_body_color(\n env_ptr, object_handle, 0, gymapi.MESH_VISUAL, gymapi.Vec3(0.6, 0.72, 0.98))\n self.gym.set_rigid_body_color(\n env_ptr, goal_handle, 0, gymapi.MESH_VISUAL, gymapi.Vec3(0.6, 0.72, 0.98))\n table_handle = self.gym.create_actor(env_ptr, table_asset, table_pose, \"table\", i, 0)\n\n if self.cfg.rgb_render:\n render_camera_handle = self.create_camera(render_cam_pose, env_ptr, render_cam_params)\n self.render_camera_handles.append(render_camera_handle[0])\n\n if self.aggregate_mode > 0:\n self.gym.end_aggregate(env_ptr)\n\n self.envs.append(env_ptr)\n\n self.setup_torch_states()\n\n def create_camera(self, camera_poses, env_ptr, camera_params):\n cam_handles = []\n for ic in range(min(len(camera_poses), self.cfg.cam.cam_num)):\n camera_handle = self.gym.create_camera_sensor(env_ptr, camera_params)\n if isinstance(camera_poses[ic], tuple):\n self.gym.set_camera_location(camera_handle, env_ptr, camera_poses[ic][0], camera_poses[ic][1])\n else:\n self.gym.set_camera_transform(camera_handle, env_ptr, camera_poses[ic])\n cam_handles.append(camera_handle)\n return cam_handles\n\n def get_visual_render_camera_setup(self):\n cam_pos = np.array([-0.7, 0, 0.5])\n cam_focus_pt = np.array([0.08, 0, 0.15])\n cam_focus_pt = gymapi.Vec3(*cam_focus_pt)\n cam_pos = gymapi.Vec3(*cam_pos)\n camera_poses = [(cam_pos, cam_focus_pt)]\n camera_params = get_camera_params(width=self.cfg.cam.visual_render_width,\n height=self.cfg.cam.visual_render_height,\n hov=45,\n cuda=False)\n return camera_poses, camera_params\n\n def create_hand_actor(self, env_ptr, dclaw_asset, dclaw_start_pose, dclaw_dof_props, env_id):\n dclaw_actor = self.gym.create_actor(env_ptr, dclaw_asset, dclaw_start_pose, \"hand\", env_id, 0, 0)\n if self.cfg.env.dof_torque_on:\n self.gym.enable_actor_dof_force_sensors(env_ptr, dclaw_actor)\n self.hand_start_states.append(\n [dclaw_start_pose.p.x, dclaw_start_pose.p.y, dclaw_start_pose.p.z,\n dclaw_start_pose.r.x, dclaw_start_pose.r.y, dclaw_start_pose.r.z,\n dclaw_start_pose.r.w,\n 0, 0, 0, 0, 0, 0])\n self.gym.set_actor_dof_properties(env_ptr, dclaw_actor, dclaw_dof_props)\n hand_idx = self.gym.get_actor_index(env_ptr, dclaw_actor, gymapi.DOMAIN_SIM)\n self.hand_indices.append(hand_idx)\n\n self.gym.set_actor_dof_states(env_ptr, dclaw_actor, self.dclaw_default_dof_states, gymapi.STATE_ALL)\n if self.obs_type == \"full_state\":\n self.gym.enable_actor_dof_force_sensors(env_ptr, dclaw_actor)\n self.dclaws.append(dclaw_actor)\n self.set_hand_color(env_ptr, dclaw_actor)\n\n def set_hand_color(self, env_ptr, dclaw_actor):\n rgd_dict = self.gym.get_actor_rigid_body_dict(env_ptr, dclaw_actor)\n for bd, bd_id in rgd_dict.items():\n if bd not in dclaw_body_color_mapping:\n continue\n color = gymapi.Vec3(*dclaw_body_color_mapping[bd])\n self.gym.set_rigid_body_color(env_ptr, dclaw_actor,\n bd_id, gymapi.MESH_VISUAL,\n color)\n\n def get_table_asset(self):\n asset_options = gymapi.AssetOptions()\n asset_options.armature = 0.001\n asset_options.fix_base_link = True\n asset_options.thickness = 0.001\n asset_options.disable_gravity = True\n table_dims = gymapi.Vec3(0.6, 0.6, 0.1)\n table_asset = self.gym.create_box(self.sim,\n table_dims.x,\n table_dims.y,\n table_dims.z,\n asset_options)\n table_props = self.gym.get_asset_rigid_shape_properties(table_asset)\n for p in table_props:\n p.friction = self.cfg.env.table.friction\n p.torsion_friction = self.cfg.env.table.torsion_friction\n p.restitution = self.cfg.env.table.restitution\n p.rolling_friction = self.cfg.env.table.rolling_friction\n self.gym.set_asset_rigid_shape_properties(table_asset, table_props)\n return table_asset\n\n def get_table_pose(self):\n object_start_pose = gymapi.Transform()\n object_start_pose.p = gymapi.Vec3()\n object_start_pose.p.x = 0\n object_start_pose.p.y = 0\n object_start_pose.p.z = -0.05\n return object_start_pose\n\n def get_dclaw_start_pose(self):\n dclaw_start_pose = gymapi.Transform()\n dclaw_start_pose.p = gymapi.Vec3(*get_axis_params(0.25, self.up_axis_idx))\n dclaw_start_pose.r = gymapi.Quat.from_axis_angle(gymapi.Vec3(0, 1, 0), np.pi)\n return dclaw_start_pose\n\n def setup_torch_states(self):\n self.render_rgb_obs_buf = None\n if self.cfg.rgb_render:\n self.gym.set_light_parameters(self.sim, 0, gymapi.Vec3(0.9, 0.9, 0.9),\n gymapi.Vec3(0.9, 0.9, 0.9), gymapi.Vec3(0, 0, 0))\n else:\n self.gym.set_light_parameters(self.sim, 0, gymapi.Vec3(0.9, 0.9, 0.9),\n gymapi.Vec3(0.7, 0.7, 0.7), gymapi.Vec3(0, 0, 0))\n self.object_init_state = to_torch(self.object_init_state, device=self.device, dtype=torch.float).view(\n self.num_envs, 13)\n self.goal_states = self.object_init_state.clone()\n self.goal_states[:, self.up_axis_idx] -= 0.04\n self.goal_init_state = self.goal_states.clone()\n self.hand_start_states = to_torch(self.hand_start_states, device=self.device).view(self.num_envs, 13)\n\n self.fingertip_handles = to_torch(self.fingertip_handles, dtype=torch.long, device=self.device)\n self.object_rb_handles = to_torch(self.object_rb_handles, dtype=torch.long, device=self.device)\n self.object_rb_masses = None\n self.update_obj_mass()\n self.hand_indices = to_torch(self.hand_indices, dtype=torch.long, device=self.device)\n self.object_indices = to_torch(self.object_indices, dtype=torch.long, device=self.device)\n self.goal_object_indices = to_torch(self.goal_object_indices, dtype=torch.long, device=self.device)\n\n def get_dclaw_asset(self, asset_root=None, asset_options=None):\n # load dclaw asset\n if asset_options is None:\n asset_options = gymapi.AssetOptions()\n asset_options.flip_visual_attachments = False\n asset_options.fix_base_link = True\n asset_options.collapse_fixed_joints = False\n asset_options.disable_gravity = False\n asset_options.thickness = 0.001\n asset_options.angular_damping = 0.01\n asset_options.override_inertia = True\n asset_options.override_com = True\n logger.info(f'VHACD:{self.cfg.env.vhacd}')\n if self.cfg.env.vhacd:\n asset_options.convex_decomposition_from_submeshes = True\n if self.cfg.physics_engine == \"physx\":\n # if self.physics_engine == gymapi.SIM_PHYSX:\n asset_options.use_physx_armature = True\n asset_options.default_dof_drive_mode = gymapi.DOF_MODE_POS\n\n if asset_root is None:\n asset_root = dexenv.LIB_PATH.joinpath('assets', 'dclaw_4f').as_posix()\n robot_name = self.cfg.env.robot\n asset_root = pathlib_file(asset_root).parent.joinpath(f'{robot_name}').as_posix()\n dclaw_asset = self.gym.load_asset(self.sim, asset_root, f\"{robot_name}.urdf\", asset_options)\n print(f'Dclaw asset root:{asset_root} robot name:{robot_name}')\n\n self.num_dclaw_bodies = self.gym.get_asset_rigid_body_count(dclaw_asset)\n self.num_dclaw_shapes = self.gym.get_asset_rigid_shape_count(dclaw_asset)\n self.num_dclaw_dofs = self.gym.get_asset_dof_count(dclaw_asset)\n\n print(f'D-Claw:')\n print(f'\\t Number of bodies: {self.num_dclaw_bodies}')\n print(f'\\t Number of shapes: {self.num_dclaw_shapes}')\n print(f'\\t Number of dofs: {self.num_dclaw_dofs}')\n\n self.dclaw_asset_dof_dict = self.gym.get_asset_dof_dict(dclaw_asset)\n joint_names = self.dclaw_asset_dof_dict.keys()\n logger.info(f'Joint names:{joint_names}')\n\n self.dof_joint_indices = list(self.dclaw_asset_dof_dict.values())\n dinds = np.array(self.dof_joint_indices)\n assert np.all(np.diff(dinds) > 0) # check if it's in a sorted order (ascending)\n\n rb_links = self.gym.get_asset_rigid_body_names(dclaw_asset)\n self.fingertips = [x for x in rb_links if 'tip_link' in x] # [\"one_tip_link\", \"two_tip_link\", \"three_tip_link\"]\n self.num_fingertips = len(self.fingertips)\n\n print(f'Number of fingertips:{self.num_fingertips} Fingertips:{self.fingertips}')\n\n print(f'Actuator --- DoF Index')\n for act_name, act_index in zip(joint_names, self.dof_joint_indices):\n print(f'\\t {act_name} {act_index}')\n\n dclaw_dof_props = self.gym.get_asset_dof_properties(dclaw_asset)\n\n def set_dof_prop(props, prop_name, val):\n if np.isscalar(val):\n props[prop_name].fill(val)\n elif len(val) == 3:\n props[prop_name] = np.array(list(val) * int(len(props[prop_name]) / 3))\n else:\n props[prop_name] = np.array(val)\n\n if self.cfg[\"env\"][\"dof_vel_hard_limit\"] is not None:\n vel_hard_limit = self.cfg[\"env\"][\"dof_vel_hard_limit\"] if not self.cfg.env.soft_control else self.cfg[\"env\"][\"soft_dof_vel_hard_limit\"]\n print(f'Setting DOF velocity limit to:{vel_hard_limit}')\n set_dof_prop(dclaw_dof_props, 'velocity', vel_hard_limit)\n if self.cfg[\"env\"][\"effort_limit\"] is not None:\n effort_limit = self.cfg[\"env\"][\"effort_limit\"] if not self.cfg.env.soft_control else self.cfg[\"env\"][\"soft_effort_limit\"]\n print(f'Setting DOF effort limit to:{effort_limit}')\n set_dof_prop(dclaw_dof_props, 'effort', effort_limit)\n if self.cfg[\"env\"][\"stiffness\"] is not None:\n stiffness = self.cfg[\"env\"][\"stiffness\"] if not self.cfg.env.soft_control else self.cfg[\"env\"][\"soft_stiffness\"]\n print(f'Setting stiffness to:{stiffness}')\n set_dof_prop(dclaw_dof_props, 'stiffness', stiffness)\n if self.cfg[\"env\"][\"damping\"] is not None:\n damping = self.cfg[\"env\"][\"damping\"] if not self.cfg.env.soft_control else self.cfg[\"env\"][\"soft_damping\"]\n print(f'Setting damping to:{damping}')\n set_dof_prop(dclaw_dof_props, 'damping', damping)\n\n self.dclaw_dof_lower_limits = []\n self.dclaw_dof_upper_limits = []\n\n self.dclaw_default_dof_states = np.zeros(self.num_dclaw_dofs, dtype=gymapi.DofState.dtype)\n self.dclaw_default_dof_pos = self.dclaw_default_dof_states['pos']\n self.dclaw_default_dof_vel = self.dclaw_default_dof_states['vel']\n for i in range(self.num_dclaw_dofs):\n self.dclaw_dof_lower_limits.append(dclaw_dof_props['lower'][i])\n self.dclaw_dof_upper_limits.append(dclaw_dof_props['upper'][i])\n if i % 3 == 1:\n self.dclaw_default_dof_pos[i] = 0.8\n elif i % 3 == 2:\n self.dclaw_default_dof_pos[i] = -1.1\n else:\n self.dclaw_default_dof_pos[i] = 0.\n self.dclaw_default_dof_vel[i] = 0.0\n\n self.dof_joint_indices = to_torch(self.dof_joint_indices, dtype=torch.long, device=self.device)\n self.dclaw_dof_lower_limits = to_torch(self.dclaw_dof_lower_limits, device=self.device)\n self.dclaw_dof_upper_limits = to_torch(self.dclaw_dof_upper_limits, device=self.device)\n self.dclaw_default_dof_pos = to_torch(self.dclaw_default_dof_pos, device=self.device)\n self.dclaw_default_dof_vel = to_torch(self.dclaw_default_dof_vel, device=self.device)\n\n self.fingertip_handles = [self.gym.find_asset_rigid_body_index(dclaw_asset, name) for name in\n self.fingertips]\n\n dclaw_asset_props = self.gym.get_asset_rigid_shape_properties(dclaw_asset)\n for p in dclaw_asset_props:\n p.friction = self.cfg.env.hand.friction\n p.torsion_friction = self.cfg.env.hand.torsion_friction\n p.rolling_friction = self.cfg.env.hand.rolling_friction\n p.restitution = self.cfg.env.hand.restitution\n self.gym.set_asset_rigid_shape_properties(dclaw_asset, dclaw_asset_props)\n return dclaw_asset, dclaw_dof_props\n\n def get_object_start_pose(self, dclaw_start_pose):\n object_start_pose = gymapi.Transform()\n object_start_pose.p = gymapi.Vec3()\n if self.cfg.env.obj_init_delta_pos is not None:\n delta_pos = self.cfg.env.obj_init_delta_pos\n object_start_pose.p.x = dclaw_start_pose.p.x + delta_pos[0]\n object_start_pose.p.y = dclaw_start_pose.p.y + delta_pos[1]\n object_start_pose.p.z = dclaw_start_pose.p.z + delta_pos[2]\n else:\n object_start_pose.p.x = dclaw_start_pose.p.x\n pose_dy, pose_dz = 0., -0.13\n object_start_pose.p.y = dclaw_start_pose.p.y + pose_dy\n object_start_pose.p.z = dclaw_start_pose.p.z + pose_dz\n return object_start_pose\n\n def get_goal_object_start_pose(self, object_start_pose):\n self.goal_displacement = gymapi.Vec3(0., 0, 0.25)\n self.goal_displacement_tensor = to_torch(\n [self.goal_displacement.x, self.goal_displacement.y, self.goal_displacement.z], device=self.device)\n goal_start_pose = gymapi.Transform()\n goal_start_pose.p = object_start_pose.p + self.goal_displacement\n return goal_start_pose\n\n def set_dof_props(self, props_dict):\n param_setters_map = get_property_setter_map(self.gym)\n param_getters_map = get_property_getter_map(self.gym)\n prop_name = 'dof_properties'\n setter = param_setters_map[prop_name]\n for env_id in range(len(self.envs)):\n env = self.envs[env_id]\n handle = self.gym.find_actor_handle(env, 'hand')\n prop = param_getters_map[prop_name](env, handle)\n for dof_prop_name, dof_prop_values in props_dict.items():\n if env_id == 0:\n assert len(dof_prop_values) == len(self.envs)\n prop_val = dof_prop_values[env_id]\n prop[dof_prop_name].fill(prop_val)\n success = setter(env, handle, prop)\n if not success:\n logger.warning(f'Setting dof properties is not successful!')\n\n def update_obj_mass(self, env_ids=None):\n object_rb_masses = []\n env_pool = env_ids if env_ids is not None else list(range(self.num_envs))\n if len(env_pool) < 1:\n return\n for env_id, object_handle in zip(env_pool, self.object_handles):\n env_ptr = self.envs[env_id]\n object_rb_props = self.gym.get_actor_rigid_body_properties(env_ptr, object_handle)\n object_rb_masses.append([prop.mass for prop in object_rb_props])\n if self.object_rb_masses is None:\n self.object_rb_masses = to_torch(object_rb_masses, dtype=torch.float, device=self.device)\n else:\n self.object_rb_masses[env_pool] = to_torch(object_rb_masses, dtype=torch.float, device=self.device)\n\n def reset(self) -> torch.Tensor:\n \"\"\"Reset the environment.\n Returns:\n Observation dictionary\n \"\"\"\n zero_actions = self.zero_actions()\n self.reset_buf.fill_(1)\n self.reset_goal_buf.fill_(1)\n if self.cfg.env.action_ema is not None:\n self.action_ema_val = zero_actions.clone()\n # step the simulator\n\n self.step(zero_actions)\n\n return self.update_obs()\n\n def compute_reward(self, actions):\n res = compute_dclaw_reward(\n self.reset_buf, self.reset_goal_buf, self.progress_buf,\n self.successes, self.max_episode_length,\n self.object_pos, self.object_rot, self.goal_pos, self.goal_rot,\n self.cfg['env']['rew'], self.actions,\n self.fingertip_pos, self.fingertip_vel, self.object_linvel, self.object_angvel,\n self.dclaw_dof_vel, self.dclaw_dof_torque,\n table_cf=self.table_contact_force if self.cfg.env.rew.pen_tb_contact else None\n )\n self.rew_buf[:] = res[0] * self.cfg.env.rew.rew_scale\n self.done_buf[:] = res[1]\n self.reset_buf[:] = res[2]\n self.reset_goal_buf[:] = res[3]\n self.progress_buf[:] = res[4]\n self.successes[:] = res[5]\n abs_rot_dist = res[6]\n reward_terms = res[7]\n timeout_envs = res[8]\n\n self.extras['success'] = self.reset_goal_buf.detach().to(self.rl_device).flatten()\n self.extras['abs_dist'] = abs_rot_dist.detach().to(self.rl_device)\n self.extras['TimeLimit.truncated'] = timeout_envs.detach().to(self.rl_device)\n for reward_key, reward_val in reward_terms.items():\n self.extras[reward_key] = reward_val.detach()\n\n def get_images(self):\n rgb = self.render_rgb_obs_buf\n return rgb\n\n def compute_observations(self):\n self.gym.refresh_dof_state_tensor(self.sim)\n if self.cfg.env.dof_torque_on:\n self.gym.refresh_dof_force_tensor(self.sim)\n self.gym.refresh_actor_root_state_tensor(self.sim)\n self.gym.refresh_rigid_body_state_tensor(self.sim)\n\n if self.obs_type == \"full_state\":\n self.gym.refresh_force_sensor_tensor(self.sim)\n self.gym.refresh_dof_force_tensor(self.sim)\n\n if self.cfg.env.rew.pen_tb_contact:\n self.gym.refresh_net_contact_force_tensor(self.sim)\n\n self.object_pose = self.root_state_tensor[self.object_indices, 0:7]\n self.object_pos = self.root_state_tensor[self.object_indices, 0:3]\n self.object_rot = self.root_state_tensor[self.object_indices, 3:7]\n self.object_linvel = self.root_state_tensor[self.object_indices, 7:10]\n self.object_angvel = self.root_state_tensor[self.object_indices, 10:13]\n\n self.goal_pose = self.goal_states[:, 0:7]\n self.goal_pos = self.goal_states[:, 0:3]\n self.goal_rot = self.goal_states[:, 3:7]\n\n self.fingertip_state = self.rigid_body_states[:, self.fingertip_handles][:, :, 0:13]\n self.fingertip_pos = self.rigid_body_states[:, self.fingertip_handles][:, :, 0:3]\n self.fingertip_vel = self.rigid_body_states[:, self.fingertip_handles][:, :, 7:13]\n\n if self.obs_type == \"full_no_vel\":\n obs_buf = self.compute_full_observations(no_vel=True)\n elif self.obs_type == \"full\":\n obs_buf = self.compute_full_observations()\n elif self.obs_type == \"full_state\":\n obs_buf = self.compute_full_state()\n else:\n print(\"Unkown observations type!\")\n self.obs_buf = obs_buf\n\n if self.cfg.rgb_render:\n self.gym.fetch_results(self.sim, True)\n self.gym.step_graphics(self.sim)\n self.gym.render_all_camera_sensors(self.sim)\n self.gym.start_access_image_tensors(self.sim)\n self.render_rgb_obs_buf = self.get_numpy_rgb_images(self.render_camera_handles)\n self.gym.end_access_image_tensors(self.sim)\n\n def allocate_ob_buffers(self):\n self.obs_buf = torch.zeros(\n (self.num_envs, self.num_obs), device=self.device, dtype=torch.float)\n\n def compute_full_observations(self, no_vel=False):\n scaled_dof_pos = unscale(\n self.dclaw_dof_pos,\n self.dclaw_dof_lower_limits,\n self.dclaw_dof_upper_limits\n )\n quat_dist = quat_mul(self.object_rot, quat_conjugate(self.goal_rot))\n\n if no_vel:\n out = torch.cat(\n [\n scaled_dof_pos,\n self.object_pose,\n self.goal_rot,\n quat_dist,\n self.fingertip_pos.reshape(self.num_envs, 3 * self.num_fingertips),\n self.actions\n ],\n dim=-1\n )\n else:\n out = torch.cat(\n [\n scaled_dof_pos,\n self.vel_obs_scale * self.dclaw_dof_vel,\n self.object_pose,\n self.object_linvel,\n self.vel_obs_scale * self.object_angvel,\n self.goal_rot,\n quat_dist,\n self.fingertip_state.reshape(self.num_envs, 13 * self.num_fingertips),\n self.actions\n ],\n dim=-1\n )\n return out\n\n def compute_full_state(self):\n obs_buf = self.compute_full_observations()\n obs_no_actions = obs_buf[:, :-9]\n actions = obs_buf[:, -9:]\n out = torch.cat(\n [\n obs_no_actions,\n self.force_torque_obs_scale * self.dof_force_tensor,\n self.force_torque_obs_scale * self.vec_sensor_tensor,\n actions\n ],\n dim=-1\n )\n\n return out\n\n def update_obs(self):\n if self.randomize:\n self.obs_buf = self.dr_randomizations['observations']['noise_lambda'](self.obs_buf)\n\n self.obs_dict[\"ob\"] = torch.clamp(self.obs_buf, -self.clip_obs, self.clip_obs).to(self.rl_device)\n if self.num_states > 0:\n self.obs_dict[\"state\"] = self.get_state()\n return self.obs_dict\n\n def reset_target_pose(self, env_ids, apply_reset=False):\n new_rot = random_quaternions(num=len(env_ids), device=self.device, order='xyzw')\n\n self.goal_states[env_ids, 0:3] = self.goal_init_state[env_ids, 0:3]\n self.goal_states[env_ids, 3:7] = new_rot\n self.root_state_tensor[self.goal_object_indices[env_ids], 0:3] = self.goal_states[env_ids, 0:3] + self.goal_displacement_tensor\n self.root_state_tensor[self.goal_object_indices[env_ids], 3:7] = self.goal_states[env_ids, 3:7]\n self.root_state_tensor[self.goal_object_indices[env_ids], 7:13] = torch.zeros_like(\n self.root_state_tensor[self.goal_object_indices[env_ids], 7:13])\n\n if apply_reset:\n goal_object_indices = self.goal_object_indices[env_ids].to(torch.int32)\n self.gym.set_actor_root_state_tensor_indexed(self.sim,\n gymtorch.unwrap_tensor(self.root_state_tensor),\n gymtorch.unwrap_tensor(goal_object_indices), len(env_ids))\n self.reset_goal_buf[env_ids] = 0\n\n def reset_idx(self, env_ids, goal_env_ids):\n if self.randomize and not self.cfg.env.rand_once:\n self.apply_randomizations(self.randomization_params)\n\n rand_floats = torch_rand_float(-1.0, 1.0, (len(env_ids), self.num_dclaw_dofs * 2 + 3), device=self.device)\n\n self.reset_target_pose(env_ids)\n self.rb_forces[env_ids, :, :] = 0.0\n\n self.root_state_tensor[self.object_indices[env_ids]] = self.object_init_state[env_ids].clone()\n self.root_state_tensor[self.object_indices[env_ids], 0:3] = self.object_init_state[env_ids, 0:3] + \\\n self.reset_position_noise * rand_floats[:, 0:3]\n\n new_object_rot = random_quaternions(num=len(env_ids), device=self.device, order='xyzw')\n\n self.root_state_tensor[self.object_indices[env_ids], 3:7] = new_object_rot\n self.root_state_tensor[self.object_indices[env_ids], 7:13] = torch.zeros_like(\n self.root_state_tensor[self.object_indices[env_ids], 7:13])\n\n object_indices = torch.unique(torch.cat([self.object_indices[env_ids],\n self.goal_object_indices[env_ids],\n self.goal_object_indices[goal_env_ids]]).to(torch.int32))\n self.gym.set_actor_root_state_tensor_indexed(self.sim,\n gymtorch.unwrap_tensor(self.root_state_tensor),\n gymtorch.unwrap_tensor(object_indices), len(object_indices))\n self.random_force_prob[env_ids] = torch.exp(\n (torch.log(self.force_prob_range[0]) - torch.log(self.force_prob_range[1]))\n * torch.rand(len(env_ids), device=self.device) + torch.log(self.force_prob_range[1]))\n\n delta_max = self.dclaw_dof_upper_limits - self.dclaw_default_dof_pos\n delta_min = self.dclaw_dof_lower_limits - self.dclaw_default_dof_pos\n rand_delta = delta_min + (delta_max - delta_min) * rand_floats[:, 3:3 + self.num_dclaw_dofs]\n\n pos = self.dclaw_default_dof_pos + self.reset_dof_pos_noise * rand_delta\n self.dclaw_dof_pos[env_ids, :] = pos\n self.dclaw_dof_vel[env_ids, :] = self.dclaw_default_dof_vel + \\\n self.reset_dof_vel_noise * rand_floats[:,\n 3 + self.num_dclaw_dofs:3 + self.num_dclaw_dofs * 2]\n self.prev_targets[env_ids, :self.num_dclaw_dofs] = pos\n self.cur_targets[env_ids, :self.num_dclaw_dofs] = pos\n\n hand_indices = self.hand_indices[env_ids].to(torch.int32)\n self.gym.set_dof_position_target_tensor_indexed(self.sim,\n gymtorch.unwrap_tensor(self.prev_targets),\n gymtorch.unwrap_tensor(hand_indices), len(env_ids))\n self.gym.set_dof_state_tensor_indexed(self.sim,\n gymtorch.unwrap_tensor(self.dof_state),\n gymtorch.unwrap_tensor(hand_indices), len(env_ids))\n\n self.progress_buf[env_ids] = 0\n self.reset_buf[env_ids] = 0\n self.successes[env_ids] = 0\n\n def get_numpy_rgb_images(self, camera_handles):\n rgb_obs_buf = []\n for cam_handles, env in zip(camera_handles, self.envs):\n cam_ob = []\n if isinstance(cam_handles, list):\n for cam_handle in cam_handles:\n color_image = self.gym.get_camera_image(self.sim, env, cam_handle, gymapi.IMAGE_COLOR)\n color_image = color_image.reshape(color_image.shape[0], -1, 4)[..., :3]\n cam_ob.append(color_image)\n rgb_obs_buf.append(cam_ob)\n else:\n color_image = self.gym.get_camera_image(self.sim, env, cam_handles, gymapi.IMAGE_COLOR)\n color_image = color_image.reshape(color_image.shape[0], -1, 4)[..., :3]\n rgb_obs_buf.append(color_image)\n rgb_obs_buf = np.stack(rgb_obs_buf)\n return rgb_obs_buf\n\n def pre_physics_step(self, actions):\n env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)\n goal_env_ids = self.reset_goal_buf.nonzero(as_tuple=False).squeeze(-1)\n\n if len(goal_env_ids) > 0 and len(env_ids) == 0:\n self.reset_target_pose(goal_env_ids, apply_reset=True)\n elif len(goal_env_ids) > 0:\n self.reset_target_pose(goal_env_ids)\n\n if len(env_ids) > 0:\n self.reset_idx(env_ids, goal_env_ids)\n\n self.actions = actions.clone().to(self.device)\n\n if self.cfg.env.action_ema is not None:\n self.action_ema_val[env_ids] = 0\n self.action_ema_val[goal_env_ids] = 0\n self.actions = self.actions * self.cfg.env.action_ema + self.action_ema_val * (1 - self.cfg.env.action_ema)\n self.action_ema_val = self.actions.clone()\n if self.cfg.env.dof_vel_pol_limit is not None:\n delta_action = self.actions * self.cfg.env.dof_vel_pol_limit * (self.dt * self.cfg.env.controlFrequencyInv)\n else:\n delta_action = self.dclaw_dof_speed_scale * self.dt * self.actions\n if self.cfg.env.relativeToPrevTarget:\n targets = self.prev_targets[:, self.dof_joint_indices] + delta_action\n else:\n targets = self.dclaw_dof_pos + delta_action\n\n self.cur_targets[:, self.dof_joint_indices] = tensor_clamp(targets,\n self.dclaw_dof_lower_limits[\n self.dof_joint_indices],\n self.dclaw_dof_upper_limits[\n self.dof_joint_indices])\n\n self.prev_targets[:, self.dof_joint_indices] = self.cur_targets[:, self.dof_joint_indices]\n self.gym.set_dof_position_target_tensor(self.sim, gymtorch.unwrap_tensor(self.cur_targets))\n\n if self.force_scale > 0.0:\n self.rb_forces *= torch.pow(self.force_decay, self.dt / self.force_decay_interval)\n # apply new forces\n force_indices = (torch.rand(self.num_envs, device=self.device) < self.random_force_prob).nonzero()\n rb_force_shape = self.rb_forces[force_indices, self.object_rb_handles, :].shape\n rb_force_dir = torch.randn(rb_force_shape, device=self.device)\n rb_force_dir = rb_force_dir / rb_force_dir.norm(dim=-1, keepdim=True)\n self.rb_forces[force_indices, self.object_rb_handles, :] = rb_force_dir * self.object_rb_masses[force_indices] * self.force_scale\n self.gym.apply_rigid_body_force_tensors(self.sim, gymtorch.unwrap_tensor(self.rb_forces), None,\n gymapi.LOCAL_SPACE)\n\n def post_physics_step(self):\n self.progress_buf += 1\n self.randomize_buf += 1\n\n self.compute_observations()\n self.compute_reward(self.actions)\n\n if self.viewer and self.debug_viz:\n # draw axes on target object\n self.gym.clear_lines(self.viewer)\n self.gym.refresh_rigid_body_state_tensor(self.sim)\n\n for i in range(self.num_envs):\n targetx = (self.goal_pos[i] + quat_apply(self.goal_rot[i],\n to_torch([1, 0, 0], device=self.device) * 0.2)).cpu().numpy()\n targety = (self.goal_pos[i] + quat_apply(self.goal_rot[i],\n to_torch([0, 1, 0], device=self.device) * 0.2)).cpu().numpy()\n targetz = (self.goal_pos[i] + quat_apply(self.goal_rot[i],\n to_torch([0, 0, 1], device=self.device) * 0.2)).cpu().numpy()\n\n p0 = self.goal_pos[i].cpu().numpy() + self.goal_displacement_tensor.cpu().numpy()\n self.gym.add_lines(self.viewer, self.envs[i], 1,\n [p0[0], p0[1], p0[2], targetx[0], targetx[1], targetx[2]], [0.85, 0.1, 0.1])\n self.gym.add_lines(self.viewer, self.envs[i], 1,\n [p0[0], p0[1], p0[2], targety[0], targety[1], targety[2]], [0.1, 0.85, 0.1])\n self.gym.add_lines(self.viewer, self.envs[i], 1,\n [p0[0], p0[1], p0[2], targetz[0], targetz[1], targetz[2]], [0.1, 0.1, 0.85])\n\n objectx = (self.object_pos[i] + quat_apply(self.object_rot[i],\n to_torch([1, 0, 0], device=self.device) * 0.2)).cpu().numpy()\n objecty = (self.object_pos[i] + quat_apply(self.object_rot[i],\n to_torch([0, 1, 0], device=self.device) * 0.2)).cpu().numpy()\n objectz = (self.object_pos[i] + quat_apply(self.object_rot[i],\n to_torch([0, 0, 1], device=self.device) * 0.2)).cpu().numpy()\n\n p0 = self.object_pos[i].cpu().numpy()\n self.gym.add_lines(self.viewer, self.envs[i], 1,\n [p0[0], p0[1], p0[2], objectx[0], objectx[1], objectx[2]], [0.85, 0.1, 0.1])\n self.gym.add_lines(self.viewer, self.envs[i], 1,\n [p0[0], p0[1], p0[2], objecty[0], objecty[1], objecty[2]], [0.1, 0.85, 0.1])\n self.gym.add_lines(self.viewer, self.envs[i], 1,\n [p0[0], p0[1], p0[2], objectz[0], objectz[1], objectz[2]], [0.1, 0.1, 0.85])" }, { "identifier": "chunker_list", "path": "dexenv/utils/common.py", "snippet": "def chunker_list(seq_list, nchunks):\n # split the list into n parts/chunks\n return [seq_list[i::nchunks] for i in range(nchunks)]" }, { "identifier": "get_all_files_with_name", "path": "dexenv/utils/common.py", "snippet": "def get_all_files_with_name(directory, name,\n exclude_patterns=None,\n include_patterns=None,\n sort=True,\n ):\n directory = pathlib_file(directory)\n files = directory.glob(f'**/{name}')\n files = [x for x in files if x.is_file() and x.name == name]\n if exclude_patterns is not None:\n files = filter_with_exclude_patterns(files, exclude_patterns)\n if include_patterns is not None:\n files = filter_with_include_patterns(files, include_patterns)\n if sort:\n files = sorted(files)\n return files" }, { "identifier": "load_from_pickle", "path": "dexenv/utils/common.py", "snippet": "def load_from_pickle(file_name):\n file_name = pathlib_file(file_name)\n with file_name.open('rb') as f:\n data = pkl.load(f)\n return data" }, { "identifier": "load_a_goal_object_asset", "path": "dexenv/utils/isaac_utils.py", "snippet": "@torch.no_grad()\ndef load_a_goal_object_asset(gym, sim, asset_root, object_urdf, asset_options=None, vhacd=True):\n if asset_options is None:\n asset_options = gymapi.AssetOptions()\n if vhacd:\n asset_options.convex_decomposition_from_submeshes = True\n asset_options.thickness = 0.001\n asset_options.disable_gravity = True\n asset_options.override_inertia = True\n # asset_options.override_com = True\n\n rela_file = object_urdf.relative_to(asset_root).as_posix()\n obj_asset = gym.load_asset(sim,\n asset_root.as_posix(),\n rela_file,\n asset_options)\n return obj_asset" }, { "identifier": "load_an_object_asset", "path": "dexenv/utils/isaac_utils.py", "snippet": "@torch.no_grad()\ndef load_an_object_asset(gym, sim, asset_root, object_urdf, asset_options=None, vhacd=True):\n if asset_options is None:\n asset_options = gymapi.AssetOptions()\n asset_options.thickness = 0.001\n asset_options.override_inertia = True\n # asset_options.override_com = True\n if vhacd:\n asset_options.convex_decomposition_from_submeshes = True\n rela_file = object_urdf.relative_to(asset_root).as_posix()\n obj_asset = gym.load_asset(sim,\n asset_root.as_posix(),\n rela_file,\n asset_options)\n return obj_asset" }, { "identifier": "load_obj_texture", "path": "dexenv/utils/isaac_utils.py", "snippet": "@torch.no_grad()\ndef load_obj_texture(gym, sim, object_urdf):\n texture_files = get_all_files_with_suffix(object_urdf.parent, 'png')\n num_textures = len(texture_files)\n if num_textures > 1:\n logger.warning(f'Multiple image files exist, will use the first image as the texture!')\n elif num_textures == 0:\n raise RuntimeError(f'No texture file is found!')\n texture_file = texture_files[0]\n texture_handle = gym.create_texture_from_file(sim,\n texture_file.as_posix(),\n )\n return texture_handle" } ]
import numpy as np import torch import dexenv from gym.utils import seeding from isaacgym import gymapi from loguru import logger from tqdm import tqdm from dexenv.envs.dclaw_base import DClawBase from dexenv.utils.common import chunker_list from dexenv.utils.common import get_all_files_with_name from dexenv.utils.common import load_from_pickle from dexenv.utils.isaac_utils import load_a_goal_object_asset from dexenv.utils.isaac_utils import load_an_object_asset from dexenv.utils.isaac_utils import load_obj_texture
15,615
# add goal object goal_handle = self.gym.create_actor(env_ptr, goal_assets[obj_asset_id], goal_start_pose, "goal_object", i + self.num_envs, 0, 2) goal_object_idx = self.gym.get_actor_index(env_ptr, goal_handle, gymapi.DOMAIN_SIM) self.goal_object_indices.append(goal_object_idx) if self.cfg.obj.load_texture: self.gym.set_rigid_body_texture(env_ptr, object_handle, 0, gymapi.MESH_VISUAL_AND_COLLISION, object_textures[obj_asset_id] ) self.gym.set_rigid_body_texture(env_ptr, goal_handle, 0, gymapi.MESH_VISUAL_AND_COLLISION, object_textures[obj_asset_id] ) else: color = np.array([179, 193, 134]) / 255.0 self.gym.set_rigid_body_color( env_ptr, object_handle, 0, gymapi.MESH_VISUAL, gymapi.Vec3(*color)) self.gym.set_rigid_body_color( env_ptr, goal_handle, 0, gymapi.MESH_VISUAL, gymapi.Vec3(*color)) table_handle = self.gym.create_actor(env_ptr, table_asset, table_pose, "table", i, 0) self.gym.set_rigid_body_color(env_ptr, table_handle, 0, gymapi.MESH_VISUAL, gymapi.Vec3(180 / 255., 180 / 255., 180 / 255.)) if self.cfg.rgb_render: render_camera_handle = self.create_camera(render_cam_pose, env_ptr, render_cam_params) self.render_camera_handles.append(render_camera_handle[0]) if self.aggregate_mode > 0: self.gym.end_aggregate(env_ptr) self.envs.append(env_ptr) object_rb_props = self.gym.get_actor_rigid_body_properties(env_ptr, object_handle) self.object_rb_masses = [prop.mass for prop in object_rb_props] self.setup_torch_states() self.env_obj_ids = torch.LongTensor(env_obj_ids).to(self.device).view(-1, 1) self.object_cat_indices = torch.LongTensor(self.object_cat_indices).to(self.device).view(-1, 1) def parse_obj_dataset(self, dataset): asset_root = dexenv.LIB_PATH.joinpath('assets') split_dataset_name = dataset.split(':') if len(split_dataset_name) == 1: dataset_path = asset_root.joinpath(dataset, 'train') else: target_object = split_dataset_name[1] dataset_path = asset_root.joinpath(split_dataset_name[0], 'train', target_object) logger.warning(f'Dataset path:{dataset_path}') urdf_files = get_all_files_with_name(dataset_path, name='model.urdf') permute_ids = self.np_random.permutation(np.arange(len(urdf_files))) permuted_urdfs = [urdf_files[i] for i in permute_ids] object_categories = sorted(list(set([self.get_object_category(urdf) for urdf in permuted_urdfs]))) obj_name_to_id = {name: idx for idx, name in enumerate(object_categories)} return permuted_urdfs, dataset_path, obj_name_to_id def get_object_category(self, urdf_path): cat = urdf_path.parents[0].name if 'var_' in cat: cat = urdf_path.parents[1].name return cat def load_object_asset(self): asset_root = dexenv.LIB_PATH.joinpath('assets') object_urdfs = self.object_urdfs object_assets, goal_assets, object_ids, object_tex_handles, object_ptds = [], [], [], [], [] object_cat_ids = [] if self.cfg.obj.object_id is not None: urdf_to_load = self.object_urdfs[self.cfg.obj.object_id] logger.info(f'Loading a single object: {urdf_to_load}') obj_asset, goal_asset, texture_handle, ptd = self.load_an_object(asset_root, urdf_to_load) object_assets.append(obj_asset) goal_assets.append(goal_asset) object_ids.append(self.object_urdfs.index(urdf_to_load)) object_tex_handles.append(texture_handle) object_ptds.append(ptd) object_cat_ids.append(self.obj_name_to_cat_id[self.get_object_category(urdf_to_load)]) else: if self.cfg.obj.start_id is None: start = 0 end = min(len(object_urdfs), self.cfg.obj.num_objs) else: start = self.cfg.obj.start_id end = min(start + self.cfg.obj.num_objs, len(object_urdfs)) iters = range(start, end) logger.info(f'Loading object IDs from {start} to {end}.') for idx in tqdm(iters, desc='Loading Asset'): urdf_to_load = object_urdfs[idx] obj_asset, goal_asset, texture_handle, ptd = self.load_an_object(asset_root, urdf_to_load) object_assets.append(obj_asset) goal_assets.append(goal_asset) object_ids.append(self.object_urdfs.index(urdf_to_load)) object_tex_handles.append(texture_handle) object_ptds.append(ptd) object_cat_ids.append(self.obj_name_to_cat_id[self.get_object_category(urdf_to_load)]) return object_assets, goal_assets, object_ids, object_tex_handles, object_ptds, object_cat_ids def load_an_object(self, asset_root, object_urdf): out = [] obj_asset = load_an_object_asset(self.gym, self.sim, asset_root, object_urdf, vhacd=self.cfg.env.vhacd) obj_asset = self.change_obj_asset_dyn(obj_asset) goal_obj_asset = load_a_goal_object_asset(self.gym, self.sim, asset_root, object_urdf, vhacd=False) ptd = None if self.cfg.env.loadCADPTD: ptd_file = object_urdf.parent.joinpath(f'point_cloud_{self.cfg.env.objCadNumPts}_pts.pkl') if ptd_file.exists(): ptd = load_from_pickle(ptd_file) out.append(obj_asset) out.append(goal_obj_asset) if self.cfg.obj.load_texture:
class DclawMultiObjs(DClawBase): def __init__(self, cfg, sim_device, rl_device, graphics_device_id): self.set_random_gen() self.object_urdfs, self.dataset_path, self.obj_name_to_cat_id = self.parse_obj_dataset(cfg.obj.dataset) self.num_objects = len(self.object_urdfs) logger.info(f'Object urdf root path:{self.dataset_path}.') logger.info(f'Number of available objects:{self.num_objects}.') super().__init__(cfg=cfg, sim_device=sim_device, rl_device=rl_device, graphics_device_id=graphics_device_id) def set_random_gen(self, seed=12345): self.np_random, seed = seeding.np_random(seed) def _create_envs(self, num_envs, spacing, num_per_row): lower = gymapi.Vec3(-spacing, -spacing, 0.0) upper = gymapi.Vec3(spacing, spacing, spacing) asset_root = dexenv.LIB_PATH.joinpath('assets', 'dclaw').as_posix() dclaw_asset, dclaw_dof_props = self.get_dclaw_asset(asset_root=asset_root) # load manipulated object and goal assets table_asset = self.get_table_asset() table_pose = self.get_table_pose() object_assets, goal_assets, object_ids, object_textures, object_ptds, object_cat_ids = self.load_object_asset() # create fingertip force sensors, if needed if self.obs_type == "full_state": sensor_pose = gymapi.Transform() for ft_handle in self.fingertip_handles: self.gym.create_asset_force_sensor(dclaw_asset, ft_handle, sensor_pose) dclaw_start_pose = self.get_dclaw_start_pose() object_start_pose = self.get_object_start_pose(dclaw_start_pose) goal_start_pose = self.get_goal_object_start_pose(object_start_pose=object_start_pose) self.dclaws = [] self.envs = [] self.object_init_state = [] self.hand_start_states = [] self.hand_indices = [] self.fingertip_indices = [] self.object_indices = [] self.object_cat_indices = [] self.goal_object_indices = [] self.render_camera_handles = [] if self.cfg.rgb_render: render_cam_pose, render_cam_params = self.get_visual_render_camera_setup() self.fingertip_handles = [self.gym.find_asset_rigid_body_index(dclaw_asset, name) for name in self.fingertips] dclaw_rb_count = self.gym.get_asset_rigid_body_count(dclaw_asset) object_rb_count = self.gym.get_asset_rigid_body_count(object_assets[0]) self.object_rb_handles = list(range(dclaw_rb_count, dclaw_rb_count + object_rb_count)) self.object_handles = [] num_object_assets = len(object_assets) env_obj_ids = [] for i in range(self.num_envs): # create env instance obj_asset_id = i % num_object_assets env_obj_ids.append(object_ids[obj_asset_id]) env_ptr = self.gym.create_env( self.sim, lower, upper, num_per_row ) if self.aggregate_mode >= 1: # compute aggregate size obj_num_bodies = self.gym.get_asset_rigid_body_count(object_assets[obj_asset_id]) obj_num_shapes = self.gym.get_asset_rigid_shape_count(object_assets[obj_asset_id]) max_agg_bodies = self.num_dclaw_bodies + obj_num_bodies * 2 + 1 max_agg_shapes = self.num_dclaw_shapes + obj_num_shapes * 2 + 1 self.gym.begin_aggregate(env_ptr, max_agg_bodies, max_agg_shapes, True) self.create_hand_actor(env_ptr=env_ptr, dclaw_asset=dclaw_asset, dclaw_start_pose=dclaw_start_pose, dclaw_dof_props=dclaw_dof_props, env_id=i) # add object object_handle = self.gym.create_actor(env_ptr, object_assets[obj_asset_id], object_start_pose, "object", i, 0, 1) self.object_handles.append(object_handle) self.object_init_state.append([object_start_pose.p.x, object_start_pose.p.y, object_start_pose.p.z, object_start_pose.r.x, object_start_pose.r.y, object_start_pose.r.z, object_start_pose.r.w, 0, 0, 0, 0, 0, 0]) object_idx = self.gym.get_actor_index(env_ptr, object_handle, gymapi.DOMAIN_SIM) self.object_indices.append(object_idx) self.object_cat_indices.append(object_cat_ids[obj_asset_id]) # add goal object goal_handle = self.gym.create_actor(env_ptr, goal_assets[obj_asset_id], goal_start_pose, "goal_object", i + self.num_envs, 0, 2) goal_object_idx = self.gym.get_actor_index(env_ptr, goal_handle, gymapi.DOMAIN_SIM) self.goal_object_indices.append(goal_object_idx) if self.cfg.obj.load_texture: self.gym.set_rigid_body_texture(env_ptr, object_handle, 0, gymapi.MESH_VISUAL_AND_COLLISION, object_textures[obj_asset_id] ) self.gym.set_rigid_body_texture(env_ptr, goal_handle, 0, gymapi.MESH_VISUAL_AND_COLLISION, object_textures[obj_asset_id] ) else: color = np.array([179, 193, 134]) / 255.0 self.gym.set_rigid_body_color( env_ptr, object_handle, 0, gymapi.MESH_VISUAL, gymapi.Vec3(*color)) self.gym.set_rigid_body_color( env_ptr, goal_handle, 0, gymapi.MESH_VISUAL, gymapi.Vec3(*color)) table_handle = self.gym.create_actor(env_ptr, table_asset, table_pose, "table", i, 0) self.gym.set_rigid_body_color(env_ptr, table_handle, 0, gymapi.MESH_VISUAL, gymapi.Vec3(180 / 255., 180 / 255., 180 / 255.)) if self.cfg.rgb_render: render_camera_handle = self.create_camera(render_cam_pose, env_ptr, render_cam_params) self.render_camera_handles.append(render_camera_handle[0]) if self.aggregate_mode > 0: self.gym.end_aggregate(env_ptr) self.envs.append(env_ptr) object_rb_props = self.gym.get_actor_rigid_body_properties(env_ptr, object_handle) self.object_rb_masses = [prop.mass for prop in object_rb_props] self.setup_torch_states() self.env_obj_ids = torch.LongTensor(env_obj_ids).to(self.device).view(-1, 1) self.object_cat_indices = torch.LongTensor(self.object_cat_indices).to(self.device).view(-1, 1) def parse_obj_dataset(self, dataset): asset_root = dexenv.LIB_PATH.joinpath('assets') split_dataset_name = dataset.split(':') if len(split_dataset_name) == 1: dataset_path = asset_root.joinpath(dataset, 'train') else: target_object = split_dataset_name[1] dataset_path = asset_root.joinpath(split_dataset_name[0], 'train', target_object) logger.warning(f'Dataset path:{dataset_path}') urdf_files = get_all_files_with_name(dataset_path, name='model.urdf') permute_ids = self.np_random.permutation(np.arange(len(urdf_files))) permuted_urdfs = [urdf_files[i] for i in permute_ids] object_categories = sorted(list(set([self.get_object_category(urdf) for urdf in permuted_urdfs]))) obj_name_to_id = {name: idx for idx, name in enumerate(object_categories)} return permuted_urdfs, dataset_path, obj_name_to_id def get_object_category(self, urdf_path): cat = urdf_path.parents[0].name if 'var_' in cat: cat = urdf_path.parents[1].name return cat def load_object_asset(self): asset_root = dexenv.LIB_PATH.joinpath('assets') object_urdfs = self.object_urdfs object_assets, goal_assets, object_ids, object_tex_handles, object_ptds = [], [], [], [], [] object_cat_ids = [] if self.cfg.obj.object_id is not None: urdf_to_load = self.object_urdfs[self.cfg.obj.object_id] logger.info(f'Loading a single object: {urdf_to_load}') obj_asset, goal_asset, texture_handle, ptd = self.load_an_object(asset_root, urdf_to_load) object_assets.append(obj_asset) goal_assets.append(goal_asset) object_ids.append(self.object_urdfs.index(urdf_to_load)) object_tex_handles.append(texture_handle) object_ptds.append(ptd) object_cat_ids.append(self.obj_name_to_cat_id[self.get_object_category(urdf_to_load)]) else: if self.cfg.obj.start_id is None: start = 0 end = min(len(object_urdfs), self.cfg.obj.num_objs) else: start = self.cfg.obj.start_id end = min(start + self.cfg.obj.num_objs, len(object_urdfs)) iters = range(start, end) logger.info(f'Loading object IDs from {start} to {end}.') for idx in tqdm(iters, desc='Loading Asset'): urdf_to_load = object_urdfs[idx] obj_asset, goal_asset, texture_handle, ptd = self.load_an_object(asset_root, urdf_to_load) object_assets.append(obj_asset) goal_assets.append(goal_asset) object_ids.append(self.object_urdfs.index(urdf_to_load)) object_tex_handles.append(texture_handle) object_ptds.append(ptd) object_cat_ids.append(self.obj_name_to_cat_id[self.get_object_category(urdf_to_load)]) return object_assets, goal_assets, object_ids, object_tex_handles, object_ptds, object_cat_ids def load_an_object(self, asset_root, object_urdf): out = [] obj_asset = load_an_object_asset(self.gym, self.sim, asset_root, object_urdf, vhacd=self.cfg.env.vhacd) obj_asset = self.change_obj_asset_dyn(obj_asset) goal_obj_asset = load_a_goal_object_asset(self.gym, self.sim, asset_root, object_urdf, vhacd=False) ptd = None if self.cfg.env.loadCADPTD: ptd_file = object_urdf.parent.joinpath(f'point_cloud_{self.cfg.env.objCadNumPts}_pts.pkl') if ptd_file.exists(): ptd = load_from_pickle(ptd_file) out.append(obj_asset) out.append(goal_obj_asset) if self.cfg.obj.load_texture:
texture_handle = load_obj_texture(self.gym, self.sim, object_urdf)
6
2023-10-25 17:22:41+00:00
24k
ai-safety-foundation/sparse_autoencoder
sparse_autoencoder/activation_resampler/tests/test_activation_resampler.py
[ { "identifier": "ActivationResampler", "path": "sparse_autoencoder/activation_resampler/activation_resampler.py", "snippet": "class ActivationResampler:\n \"\"\"Activation resampler.\n\n Collates the number of times each neuron fires over a set number of learned activation vectors,\n and then provides the parameters necessary to reset any dead neurons.\n\n Motivation:\n Over the course of training, a subset of autoencoder neurons will have zero activity across\n a large number of datapoints. The authors of *Towards Monosemanticity: Decomposing Language\n Models With Dictionary Learning* found that “resampling” these dead neurons during training\n improves the number of likely-interpretable features (i.e., those in the high density\n cluster) and reduces total loss. This resampling may be compatible with the Lottery Ticket\n Hypothesis and increase the number of chances the network has to find promising feature\n directions.\n\n An interesting nuance around dead neurons involves the ultralow density cluster. They found\n that if we increase the number of training steps then networks will kill off more of these\n ultralow density neurons. This reinforces the use of the high density cluster as a useful\n metric because there can exist neurons that are de facto dead but will not appear to be when\n looking at the number of dead neurons alone.\n\n This approach is designed to seed new features to fit inputs where the current autoencoder\n performs worst. Resetting the encoder norm and bias are crucial to ensuring this resampled\n neuron will only fire weakly for inputs similar to the one used for its reinitialization.\n This was done to minimize interference with the rest of the network.\n\n Warning:\n The optimizer should be reset after applying this function, as the Adam state will be\n incorrect for the modified weights and biases.\n\n Warning:\n This approach is also known to create sudden loss spikes, and resampling too frequently\n causes training to diverge.\n \"\"\"\n\n _activations_seen_since_last_resample: int = 0\n \"\"\"Number of activations since we last resampled.\"\"\"\n\n _collated_neuron_activity: Float[Tensor, Axis.names(Axis.COMPONENT, Axis.LEARNT_FEATURE)]\n \"\"\"Collated neuron activity, over the current data collection window.\"\"\"\n\n _threshold_is_dead_portion_fires: float\n \"\"\"Threshold for determining if a neuron has fired (or is dead).\"\"\"\n\n _max_n_resamples: int\n \"\"\"Maximum number of times that resampling should be performed.\"\"\"\n\n _n_activations_collated_since_last_resample: int = 0\n \"\"\"Number of activations collated since we last resampled.\n\n Number of vectors used to collate neuron activity, over the current collation window.\n \"\"\"\n\n _n_components: int\n \"\"\"Number of components.\"\"\"\n\n _n_times_resampled: int = 0\n \"\"\"Number of times that resampling has been performed.\"\"\"\n\n neuron_activity_window_end: int\n \"\"\"End of the window for collecting neuron activity.\"\"\"\n\n neuron_activity_window_start: int\n \"\"\"Start of the window for collecting neuron activity.\"\"\"\n\n @validate_call\n def __init__(\n self,\n n_learned_features: PositiveInt,\n n_components: NonNegativeInt = 1,\n resample_interval: PositiveInt = 200_000_000,\n max_n_resamples: NonNegativeInt = 4,\n n_activations_activity_collate: PositiveInt = 100_000_000,\n resample_dataset_size: PositiveInt = 819_200,\n threshold_is_dead_portion_fires: Annotated[float, Field(strict=True, ge=0, le=1)] = 0.0,\n ) -> None:\n r\"\"\"Initialize the activation resampler.\n\n Defaults to values used in the Anthropic Towards Monosemanticity paper.\n\n Args:\n n_learned_features: Number of learned features\n n_components: Number of components that the SAE is being trained on.\n resample_interval: Interval in number of autoencoder input activation vectors trained\n on, before resampling.\n max_n_resamples: Maximum number of resamples to perform throughout the entire pipeline.\n Set to inf if you want to have no limit.\n n_activations_activity_collate: Number of autoencoder learned activation vectors to\n collate before resampling (the activation resampler will start collecting on vector\n $\\text{resample_interval} - \\text{n_steps_collate}$).\n resample_dataset_size: Number of autoencoder input activations to use for calculating\n the loss, as part of the resampling process to create the reset neuron weights.\n threshold_is_dead_portion_fires: Threshold for determining if a neuron is dead (has\n \"fired\" in less than this portion of the collated sample).\n\n Raises:\n ValueError: If any of the arguments are invalid (e.g. negative integers).\n \"\"\"\n if n_activations_activity_collate > resample_interval:\n error_message = (\n \"Number of steps to collate must be less than or equal to the resample interval.\"\n )\n raise ValueError(error_message)\n\n super().__init__()\n self.neuron_activity_window_end = resample_interval\n self.neuron_activity_window_start = resample_interval - n_activations_activity_collate\n self._max_n_resamples = max_n_resamples\n self._collated_neuron_activity = torch.zeros(\n (n_components, n_learned_features), dtype=torch.int64\n )\n self._resample_dataset_size = resample_dataset_size\n self._threshold_is_dead_portion_fires = threshold_is_dead_portion_fires\n self._n_components = n_components\n\n def _get_dead_neuron_indices(\n self,\n ) -> list[Int64[Tensor, Axis.names(Axis.LEARNT_FEATURE_IDX)]]:\n \"\"\"Identify the indices of neurons that are dead.\n\n Identifies any neurons that have fired less than the threshold portion of the collated\n sample size.\n\n Example:\n >>> resampler = ActivationResampler(n_learned_features=6, n_components=2)\n >>> resampler._collated_neuron_activity = torch.tensor(\n ... [[1, 1, 0, 0, 1, 1], [1, 1, 1, 1, 1, 0]]\n ... )\n >>> resampler._get_dead_neuron_indices()\n [tensor([2, 3]), tensor([5])]\n\n Returns:\n List of dead neuron indices for each component.\n\n Raises:\n ValueError: If no neuron activity has been collated yet.\n \"\"\"\n # Check we have already collated some neuron activity\n if torch.all(self._collated_neuron_activity == 0):\n error_message = \"Cannot get dead neuron indices without neuron activity.\"\n raise ValueError(error_message)\n\n # Find any neurons that fire less than the threshold portion of times\n threshold_is_dead_n_fires: int = int(\n self._n_activations_collated_since_last_resample * self._threshold_is_dead_portion_fires\n )\n\n return [\n torch.where(self._collated_neuron_activity[component_idx] <= threshold_is_dead_n_fires)[\n 0\n ].to(dtype=torch.int64)\n for component_idx in range(self._n_components)\n ]\n\n def compute_loss_and_get_activations(\n self,\n store: ActivationStore,\n autoencoder: SparseAutoencoder | DataParallel[SparseAutoencoder] | DeepSpeedEngine,\n loss_fn: AbstractLoss,\n train_batch_size: int,\n ) -> LossInputActivationsTuple:\n \"\"\"Compute the loss on a random subset of inputs.\n\n Motivation:\n Helps find input vectors that have high SAE loss, so that we can resample dead neurons\n in a way that improves performance on these specific input vectors.\n\n Args:\n store: Activation store.\n autoencoder: Sparse autoencoder model.\n loss_fn: Loss function.\n train_batch_size: Train batch size (also used for resampling).\n\n Returns:\n A tuple of loss per item, and all input activations.\n\n Raises:\n ValueError: If the number of items in the store is less than the number of inputs\n \"\"\"\n with torch.no_grad():\n loss_batches: list[Float[Tensor, Axis.BATCH]] = []\n input_activations_batches: list[\n Float[Tensor, Axis.names(Axis.BATCH, Axis.INPUT_OUTPUT_FEATURE)]\n ] = []\n dataloader = DataLoader(store, batch_size=train_batch_size)\n n_inputs = self._resample_dataset_size\n n_batches_required: int = n_inputs // train_batch_size\n model_device: torch.device = get_model_device(autoencoder)\n\n for batch_idx, batch in enumerate(iter(dataloader)):\n input_activations_batches.append(batch)\n source_activations = batch.to(model_device)\n learned_activations, reconstructed_activations = autoencoder(source_activations)\n loss_batches.append(\n loss_fn.forward(\n source_activations, learned_activations, reconstructed_activations\n )\n )\n if batch_idx >= n_batches_required:\n break\n\n loss_per_item = torch.cat(loss_batches).to(model_device)\n input_activations = torch.cat(input_activations_batches).to(model_device)\n\n # Check we generated enough data\n if len(loss_per_item) < n_inputs:\n error_message = (\n f\"Cannot get {n_inputs} items from the store, \"\n f\"as only {len(loss_per_item)} were available.\"\n )\n raise ValueError(error_message)\n\n return LossInputActivationsTuple(loss_per_item, input_activations)\n\n @staticmethod\n def assign_sampling_probabilities(\n loss: Float[Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL)],\n ) -> Float[Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL)]:\n \"\"\"Assign the sampling probabilities for each input activations vector.\n\n Assign each input vector a probability of being picked that is proportional to the square of\n the autoencoder's loss on that input.\n\n Examples:\n >>> loss = torch.tensor([1.0, 2.0, 3.0])\n >>> ActivationResampler.assign_sampling_probabilities(loss).round(decimals=2)\n tensor([0.0700, 0.2900, 0.6400])\n\n >>> loss = torch.tensor([[1.0, 2], [2, 4], [3, 6]])\n >>> ActivationResampler.assign_sampling_probabilities(loss).round(decimals=2)\n tensor([[0.0700, 0.0700],\n [0.2900, 0.2900],\n [0.6400, 0.6400]])\n\n Args:\n loss: Loss per item.\n\n Returns:\n A tensor of probabilities for each item.\n \"\"\"\n square_loss = loss.pow(2)\n return square_loss / square_loss.sum(0)\n\n @staticmethod\n def sample_input(\n probabilities: Float[Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL)],\n input_activations: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.INPUT_OUTPUT_FEATURE)\n ],\n n_samples: list[int],\n ) -> list[Float[Tensor, Axis.names(Axis.DEAD_FEATURE, Axis.INPUT_OUTPUT_FEATURE)]]:\n \"\"\"Sample an input vector based on the provided probabilities.\n\n Example:\n >>> probabilities = torch.tensor([[0.1], [0.2], [0.7]])\n >>> input_activations = torch.tensor([[[1.0, 2.0]], [[3.0, 4.0]], [[5.0, 6.0]]])\n >>> _seed = torch.manual_seed(0) # For reproducibility in example\n >>> sampled_input = ActivationResampler.sample_input(\n ... probabilities, input_activations, [2]\n ... )\n >>> sampled_input[0].tolist()\n [[5.0, 6.0], [3.0, 4.0]]\n\n Args:\n probabilities: Probabilities for each input.\n input_activations: Input activation vectors.\n n_samples: Number of samples to take (number of dead neurons).\n\n Returns:\n Sampled input activation vector.\n\n Raises:\n ValueError: If the number of samples is greater than the number of input activations.\n \"\"\"\n sampled_inputs: list[\n Float[Tensor, Axis.names(Axis.DEAD_FEATURE, Axis.INPUT_OUTPUT_FEATURE)]\n ] = []\n\n for component_idx, component_n_samples in enumerate(n_samples):\n component_probabilities: Float[Tensor, Axis.BATCH] = get_component_slice_tensor(\n input_tensor=probabilities,\n n_dim_with_component=2,\n component_dim=1,\n component_idx=component_idx,\n )\n\n component_input_activations: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.INPUT_OUTPUT_FEATURE)\n ] = get_component_slice_tensor(\n input_tensor=input_activations,\n n_dim_with_component=3,\n component_dim=1,\n component_idx=component_idx,\n )\n\n if component_n_samples > len(component_input_activations):\n exception_message = (\n f\"Cannot sample {component_n_samples} inputs from \"\n f\"{len(component_input_activations)} input activations.\"\n )\n raise ValueError(exception_message)\n\n # Handle the 0 dead neurons case\n if component_n_samples == 0:\n sampled_inputs.append(\n torch.empty(\n (0, component_input_activations.shape[-1]),\n dtype=component_input_activations.dtype,\n device=component_input_activations.device,\n )\n )\n continue\n\n # Handle the 1+ dead neuron case\n component_sample_indices: Int64[Tensor, Axis.LEARNT_FEATURE_IDX] = torch.multinomial(\n component_probabilities, num_samples=component_n_samples\n )\n sampled_inputs.append(component_input_activations[component_sample_indices, :])\n\n return sampled_inputs\n\n @staticmethod\n def renormalize_and_scale(\n sampled_input: Float[Tensor, Axis.names(Axis.DEAD_FEATURE, Axis.INPUT_OUTPUT_FEATURE)],\n neuron_activity: Int64[Tensor, Axis.names(Axis.LEARNT_FEATURE)],\n encoder_weight: Float[Tensor, Axis.names(Axis.LEARNT_FEATURE, Axis.INPUT_OUTPUT_FEATURE)],\n ) -> Float[Tensor, Axis.names(Axis.DEAD_FEATURE, Axis.INPUT_OUTPUT_FEATURE)]:\n \"\"\"Renormalize and scale the resampled dictionary vectors.\n\n Renormalize the input vector to equal the average norm of the encoder weights for alive\n neurons times 0.2.\n\n Example:\n >>> from torch.nn import Parameter\n >>> _seed = torch.manual_seed(0) # For reproducibility in example\n >>> sampled_input = torch.tensor([[3.0, 4.0]])\n >>> neuron_activity = torch.tensor([3, 0, 5, 0, 1, 3])\n >>> encoder_weight = Parameter(torch.ones((6, 2)))\n >>> rescaled_input = ActivationResampler.renormalize_and_scale(\n ... sampled_input,\n ... neuron_activity,\n ... encoder_weight\n ... )\n >>> rescaled_input.round(decimals=1)\n tensor([[0.2000, 0.2000]])\n\n Args:\n sampled_input: Tensor of the sampled input activation.\n neuron_activity: Tensor representing the number of times each neuron fired.\n encoder_weight: Tensor of encoder weights.\n\n Returns:\n Rescaled sampled input.\n\n Raises:\n ValueError: If there are no alive neurons.\n \"\"\"\n alive_neuron_mask: Bool[Tensor, \" learned_features\"] = neuron_activity > 0\n\n # Check there is at least one alive neuron\n if not torch.any(alive_neuron_mask):\n error_message = \"No alive neurons found.\"\n raise ValueError(error_message)\n\n # Handle no dead neurons\n n_dead_neurons = len(sampled_input)\n if n_dead_neurons == 0:\n return torch.empty(\n (0, sampled_input.shape[-1]), dtype=sampled_input.dtype, device=sampled_input.device\n )\n\n # Calculate the average norm of the encoder weights for alive neurons.\n detached_encoder_weight = encoder_weight.detach() # Don't track gradients\n alive_encoder_weights: Float[\n Tensor, Axis.names(Axis.ALIVE_FEATURE, Axis.INPUT_OUTPUT_FEATURE)\n ] = detached_encoder_weight[alive_neuron_mask, :]\n average_alive_norm: Float[Tensor, Axis.SINGLE_ITEM] = alive_encoder_weights.norm(\n dim=-1\n ).mean()\n\n # Renormalize the input vector to equal the average norm of the encoder weights for alive\n # neurons times 0.2.\n renormalized_input: Float[\n Tensor, Axis.names(Axis.DEAD_FEATURE, Axis.INPUT_OUTPUT_FEATURE)\n ] = torch.nn.functional.normalize(sampled_input, dim=-1)\n return renormalized_input * (average_alive_norm * 0.2)\n\n def resample_dead_neurons(\n self,\n activation_store: ActivationStore,\n autoencoder: SparseAutoencoder | DataParallel[SparseAutoencoder] | DeepSpeedEngine,\n loss_fn: AbstractLoss,\n train_batch_size: int,\n ) -> list[ParameterUpdateResults]:\n \"\"\"Resample dead neurons.\n\n Args:\n activation_store: Activation store.\n autoencoder: Sparse autoencoder model.\n loss_fn: Loss function.\n train_batch_size: Train batch size (also used for resampling).\n\n Returns:\n For each component that the SAE is being trained on, the indices of dead neurons and the\n updates for the encoder and decoder weights and biases.\n \"\"\"\n parameter_update_results: list[ParameterUpdateResults] = []\n\n with torch.no_grad():\n dead_neuron_indices: list[\n Int64[Tensor, Axis.names(Axis.LEARNT_FEATURE_IDX)]\n ] = self._get_dead_neuron_indices()\n\n # Compute the loss for the current model on a random subset of inputs and get the\n # activations.\n loss_per_item, input_activations = self.compute_loss_and_get_activations(\n store=activation_store,\n autoencoder=autoencoder,\n loss_fn=loss_fn,\n train_batch_size=train_batch_size,\n )\n\n # Assign each input vector a probability of being picked that is proportional to the\n # square of the autoencoder's loss on that input.\n sample_probabilities: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL)\n ] = self.assign_sampling_probabilities(loss_per_item)\n\n # For each dead neuron sample an input according to these probabilities.\n sampled_input: list[\n Float[Tensor, Axis.names(Axis.DEAD_FEATURE, Axis.INPUT_OUTPUT_FEATURE)]\n ] = self.sample_input(\n sample_probabilities, input_activations, [len(dead) for dead in dead_neuron_indices]\n )\n\n for component_idx in range(self._n_components):\n # Renormalize each input vector to have unit L2 norm and set this to be the\n # dictionary vector for the dead autoencoder neuron.\n renormalized_input: Float[\n Tensor, Axis.names(Axis.DEAD_FEATURE, Axis.INPUT_OUTPUT_FEATURE)\n ] = torch.nn.functional.normalize(sampled_input[component_idx], dim=-1)\n\n dead_decoder_weight_updates = rearrange(\n renormalized_input, \"dead_neuron input_feature -> input_feature dead_neuron\"\n )\n\n # For the corresponding encoder vector, renormalize the input vector to equal the\n # average norm of the encoder weights for alive neurons times 0.2. Set the\n # corresponding encoder bias element to zero.\n encoder_weight: Float[\n Tensor, Axis.names(Axis.LEARNT_FEATURE, Axis.INPUT_OUTPUT_FEATURE)\n ] = get_component_slice_tensor(autoencoder.encoder.weight, 3, 0, component_idx)\n\n rescaled_sampled_input = self.renormalize_and_scale(\n sampled_input=sampled_input[component_idx],\n neuron_activity=self._collated_neuron_activity[component_idx],\n encoder_weight=encoder_weight,\n )\n\n dead_encoder_bias_updates = torch.zeros_like(\n dead_neuron_indices[component_idx],\n dtype=dead_decoder_weight_updates.dtype,\n device=dead_decoder_weight_updates.device,\n )\n\n parameter_update_results.append(\n ParameterUpdateResults(\n dead_neuron_indices=dead_neuron_indices[component_idx],\n dead_encoder_weight_updates=rescaled_sampled_input,\n dead_encoder_bias_updates=dead_encoder_bias_updates,\n dead_decoder_weight_updates=dead_decoder_weight_updates,\n )\n )\n\n return parameter_update_results\n\n def step_resampler(\n self,\n batch_neuron_activity: Int64[Tensor, Axis.names(Axis.COMPONENT, Axis.LEARNT_FEATURE)],\n activation_store: ActivationStore,\n autoencoder: SparseAutoencoder | DataParallel[SparseAutoencoder] | DeepSpeedEngine,\n loss_fn: AbstractLoss,\n train_batch_size: int,\n ) -> list[ParameterUpdateResults] | None:\n \"\"\"Step the resampler, collating neuron activity and resampling if necessary.\n\n Args:\n batch_neuron_activity: Number of times each neuron fired in the current batch.\n activation_store: Activation store.\n autoencoder: Sparse autoencoder model.\n loss_fn: Loss function.\n train_batch_size: Train batch size (also used for resampling).\n\n Returns:\n Parameter update results (for each component that the SAE is being trained on) if\n resampling is due. Otherwise None.\n \"\"\"\n # Update the counter\n self._activations_seen_since_last_resample += len(activation_store)\n\n if self._n_times_resampled < self._max_n_resamples:\n # Collate neuron activity, if in the data collection window. For example in the\n # Anthropic Towards Monosemanticity paper, the window started collecting at 100m\n # activations and stopped at 200m (and then repeated this again a few times until the\n # max times to resample was hit).\n if self._activations_seen_since_last_resample >= self.neuron_activity_window_start:\n detached_neuron_activity = batch_neuron_activity.detach().cpu()\n self._collated_neuron_activity.add_(detached_neuron_activity)\n self._n_activations_collated_since_last_resample += train_batch_size\n\n # Check if we should resample.\n if self._activations_seen_since_last_resample >= self.neuron_activity_window_end:\n # Get resampled dictionary vectors\n resample_res = self.resample_dead_neurons(\n activation_store=activation_store,\n autoencoder=autoencoder,\n loss_fn=loss_fn,\n train_batch_size=train_batch_size,\n )\n\n # Update counters\n self._activations_seen_since_last_resample = 0\n self._n_activations_collated_since_last_resample = 0\n self._n_times_resampled += 1\n\n # Reset the collated neuron activity\n self._collated_neuron_activity.zero_()\n\n return resample_res\n\n return None\n\n def __str__(self) -> str:\n \"\"\"Return a string representation of the activation resampler.\"\"\"\n return (\n f\"ActivationResampler(\"\n f\"n_components={self._n_components}, \"\n f\"neuron_activity_window_start={self.neuron_activity_window_end}, \"\n f\"neuron_activity_window_end={self.neuron_activity_window_end}, \"\n f\"max_resamples={self._max_n_resamples}, \"\n f\"resample_dataset_size={self._resample_dataset_size}, \"\n f\"dead_neuron_threshold={self._threshold_is_dead_portion_fires})\"\n )" }, { "identifier": "ActivationStore", "path": "sparse_autoencoder/activation_store/base_store.py", "snippet": "class ActivationStore(\n Dataset[Float[Tensor, Axis.names(Axis.COMPONENT_OPTIONAL, Axis.INPUT_OUTPUT_FEATURE)]], ABC\n):\n \"\"\"Activation Store Abstract Class.\n\n Extends the `torch.utils.data.Dataset` class to provide an activation store, with additional\n :meth:`append` and :meth:`extend` methods (the latter of which should typically be\n non-blocking). The resulting activation store can be used with a `torch.utils.data.DataLoader`\n to iterate over the dataset.\n\n Extend this class if you want to create a new activation store (noting you also need to create\n `__getitem__` and `__len__` methods from the underlying `torch.utils.data.Dataset` class).\n\n Example:\n >>> import torch\n >>> class MyActivationStore(ActivationStore):\n ...\n ... @property\n ... def current_activations_stored_per_component(self):\n ... raise NotImplementedError\n ...\n ... @property\n ... def n_components(self):\n ... raise NotImplementedError\n ...\n ... def __init__(self):\n ... super().__init__()\n ... self._data = [] # In this example, we just store in a list\n ...\n ... def append(self, item) -> None:\n ... self._data.append(item)\n ...\n ... def extend(self, batch):\n ... self._data.extend(batch)\n ...\n ... def empty(self):\n ... self._data = []\n ...\n ... def __getitem__(self, index: int):\n ... return self._data[index]\n ...\n ... def __len__(self) -> int:\n ... return len(self._data)\n ...\n >>> store = MyActivationStore()\n >>> store.append(torch.randn(100))\n >>> print(len(store))\n 1\n \"\"\"\n\n @abstractmethod\n def append(\n self,\n item: Float[Tensor, Axis.names(Axis.INPUT_OUTPUT_FEATURE)],\n component_idx: int,\n ) -> Future | None:\n \"\"\"Add a Single Item to the Store.\"\"\"\n\n @abstractmethod\n def extend(\n self,\n batch: Float[Tensor, Axis.names(Axis.BATCH, Axis.INPUT_OUTPUT_FEATURE)],\n component_idx: int,\n ) -> Future | None:\n \"\"\"Add a Batch to the Store.\"\"\"\n\n @abstractmethod\n def empty(self) -> None:\n \"\"\"Empty the Store.\"\"\"\n\n @property\n @abstractmethod\n def n_components(self) -> int:\n \"\"\"Number of components.\"\"\"\n\n @property\n @abstractmethod\n def current_activations_stored_per_component(self) -> list[int]:\n \"\"\"Current activations stored per component.\"\"\"\n\n @abstractmethod\n def __len__(self) -> int:\n \"\"\"Get the Length of the Store.\"\"\"\n\n @abstractmethod\n def __getitem__(\n self, index: tuple[int, ...] | slice | int\n ) -> Float[Tensor, Axis.names(Axis.ANY)]:\n \"\"\"Get an Item from the Store.\"\"\"\n\n def shuffle(self) -> None:\n \"\"\"Optional shuffle method.\"\"\"\n\n @final\n @validate_call\n def fill_with_test_data(\n self,\n n_batches: PositiveInt = 1,\n batch_size: PositiveInt = 16,\n n_components: PositiveInt = 1,\n input_features: PositiveInt = 256,\n ) -> None:\n \"\"\"Fill the store with test data.\n\n For use when testing your code, to ensure it works with a real activation store.\n\n Warning:\n You may want to use `torch.seed(0)` to make the random data deterministic, if your test\n requires inspecting the data itself.\n\n Example:\n >>> from sparse_autoencoder.activation_store.tensor_store import TensorActivationStore\n >>> store = TensorActivationStore(max_items=100, n_neurons=256, n_components=1)\n >>> store.fill_with_test_data(batch_size=100)\n >>> len(store)\n 100\n\n Args:\n n_batches: Number of batches to fill the store with.\n batch_size: Number of items per batch.\n n_components: Number of source model components the SAE is trained on.\n input_features: Number of input features per item.\n \"\"\"\n for _ in range(n_batches):\n for component_idx in range(n_components):\n sample = torch.rand(batch_size, input_features)\n self.extend(sample, component_idx)" }, { "identifier": "TensorActivationStore", "path": "sparse_autoencoder/activation_store/tensor_store.py", "snippet": "class TensorActivationStore(ActivationStore):\n \"\"\"Tensor Activation Store.\n\n Stores tensors in a (large) tensor of shape (item, neuron). Requires the number of activation\n vectors to be stored to be known in advance. Multiprocess safe.\n\n Extends the `torch.utils.data.Dataset` class to provide a list-based activation store, with\n additional :meth:`append` and :meth:`extend` methods (the latter of which is non-blocking).\n\n Examples:\n Create an empty activation dataset:\n\n >>> import torch\n >>> store = TensorActivationStore(max_items=1000, n_neurons=100, n_components=2)\n\n Add a single activation vector to the dataset (for a component):\n\n >>> store.append(torch.randn(100), component_idx=0)\n >>> store.append(torch.randn(100), component_idx=1)\n >>> len(store)\n 1\n\n Add a [batch, neurons] activation tensor to the dataset:\n\n >>> store.empty()\n >>> batch = torch.randn(10, 100)\n >>> store.extend(batch, component_idx=0)\n >>> store.extend(batch, component_idx=1)\n >>> len(store)\n 10\n\n Shuffle the dataset **before passing it to the DataLoader**:\n\n >>> store.shuffle() # Faster than using the DataLoader shuffle argument\n\n Use the dataloader to iterate over the dataset:\n\n >>> loader = torch.utils.data.DataLoader(store, shuffle=False, batch_size=2)\n >>> next_item = next(iter(loader))\n >>> next_item.shape\n torch.Size([2, 2, 100])\n \"\"\"\n\n _data: Float[Tensor, Axis.names(Axis.ITEMS, Axis.COMPONENT, Axis.INPUT_OUTPUT_FEATURE)]\n \"\"\"Underlying Tensor Data Store.\"\"\"\n\n _items_stored: list[int]\n \"\"\"Number of items stored.\"\"\"\n\n max_items: int\n \"\"\"Maximum Number of Items to Store.\"\"\"\n\n _n_components: int\n \"\"\"Number of components\"\"\"\n\n @property\n def n_components(self) -> int:\n \"\"\"Number of components.\"\"\"\n return self._n_components\n\n @property\n def current_activations_stored_per_component(self) -> list[int]:\n \"\"\"Number of activations stored per component.\"\"\"\n return self._items_stored\n\n @validate_call(config={\"arbitrary_types_allowed\": True})\n def __init__(\n self,\n max_items: PositiveInt,\n n_neurons: PositiveInt,\n n_components: PositiveInt,\n device: torch.device | None = None,\n ) -> None:\n \"\"\"Initialise the Tensor Activation Store.\n\n Args:\n max_items: Maximum number of items to store per component (individual activation\n vectors).\n n_neurons: Number of neurons in each activation vector.\n n_components: Number of components to store (i.e. number of source models).\n device: Device to store the activation vectors on.\n \"\"\"\n self._n_components = n_components\n self._items_stored = [0] * n_components\n self._max_items = max_items\n self._data = torch.empty((max_items, n_components, n_neurons), device=device)\n\n def __len__(self) -> int:\n \"\"\"Length Dunder Method.\n\n Returns the number of activation vectors per component in the dataset.\n\n Example:\n >>> import torch\n >>> store = TensorActivationStore(max_items=10_000_000, n_neurons=100, n_components=1)\n >>> store.append(torch.randn(100), component_idx=0)\n >>> store.append(torch.randn(100), component_idx=0)\n >>> len(store)\n 2\n\n Returns:\n The number of activation vectors in the dataset.\n \"\"\"\n # Min as this is the amount of activations that can be fetched by get_item\n return min(self.current_activations_stored_per_component)\n\n def __sizeof__(self) -> int:\n \"\"\"Sizeof Dunder Method.\n\n Example:\n >>> import torch\n >>> store = TensorActivationStore(max_items=2, n_neurons=100, n_components=1)\n >>> store.__sizeof__() # Pre-allocated tensor of 2x100\n 800\n\n Returns:\n The size of the underlying tensor in bytes.\n \"\"\"\n return self._data.element_size() * self._data.nelement()\n\n def __getitem__(\n self, index: tuple[int, ...] | slice | int\n ) -> Float[Tensor, Axis.names(Axis.ANY)]:\n \"\"\"Get Item Dunder Method.\n\n Examples:\n >>> import torch\n >>> store = TensorActivationStore(max_items=2, n_neurons=5, n_components=1)\n >>> store.append(torch.zeros(5), component_idx=0)\n >>> store.append(torch.ones(5), component_idx=0)\n >>> store[1, 0]\n tensor([1., 1., 1., 1., 1.])\n\n Args:\n index: The index of the tensor to fetch.\n\n Returns:\n The activation store item at the given index.\n \"\"\"\n return self._data[index]\n\n def shuffle(self) -> None:\n \"\"\"Shuffle the Data In-Place.\n\n This is much faster than using the shuffle argument on `torch.utils.data.DataLoader`.\n\n Example:\n >>> import torch\n >>> _seed = torch.manual_seed(42)\n >>> store = TensorActivationStore(max_items=10, n_neurons=1, n_components=1)\n >>> store.append(torch.tensor([0.]), component_idx=0)\n >>> store.append(torch.tensor([1.]), component_idx=0)\n >>> store.append(torch.tensor([2.]), component_idx=0)\n >>> store.shuffle()\n >>> [store[i, 0].item() for i in range(3)]\n [0.0, 2.0, 1.0]\n \"\"\"\n # Generate a permutation of the indices for the active data\n perm = torch.randperm(len(self))\n\n # Use this permutation to shuffle the active data in-place\n self._data[: len(self)] = self._data[perm]\n\n def append(self, item: Float[Tensor, Axis.INPUT_OUTPUT_FEATURE], component_idx: int) -> None:\n \"\"\"Add a single item to the store.\n\n Example:\n >>> import torch\n >>> store = TensorActivationStore(max_items=10, n_neurons=5, n_components=1)\n >>> store.append(torch.zeros(5), component_idx=0)\n >>> store.append(torch.ones(5), component_idx=0)\n >>> store[1, 0]\n tensor([1., 1., 1., 1., 1.])\n\n Args:\n item: The item to append to the dataset.\n component_idx: The component index to append the item to.\n\n Raises:\n IndexError: If there is no space remaining.\n \"\"\"\n # Check we have space\n if self._items_stored[component_idx] + 1 > self._max_items:\n raise StoreFullError\n\n self._data[self._items_stored[component_idx], component_idx] = item.to(\n self._data.device,\n )\n self._items_stored[component_idx] += 1\n\n def extend(\n self,\n batch: Float[Tensor, Axis.names(Axis.BATCH, Axis.INPUT_OUTPUT_FEATURE)],\n component_idx: int,\n ) -> None:\n \"\"\"Add a batch to the store.\n\n Examples:\n >>> import torch\n >>> store = TensorActivationStore(max_items=10, n_neurons=5, n_components=1)\n >>> store.extend(torch.zeros(2, 5), component_idx=0)\n >>> len(store)\n 2\n\n Args:\n batch: The batch to append to the dataset.\n component_idx: The component index to append the batch to.\n\n Raises:\n IndexError: If there is no space remaining.\n \"\"\"\n # Check we have space\n n_activation_tensors: int = batch.shape[0]\n if self._items_stored[component_idx] + n_activation_tensors > self._max_items:\n raise StoreFullError\n\n self._data[\n self._items_stored[component_idx] : self._items_stored[component_idx]\n + n_activation_tensors,\n component_idx,\n ] = batch.to(self._data.device)\n self._items_stored[component_idx] += n_activation_tensors\n\n def empty(self) -> None:\n \"\"\"Empty the store.\n\n Example:\n >>> import torch\n >>> store = TensorActivationStore(max_items=10, n_neurons=5, n_components=1)\n >>> store.extend(torch.zeros(2, 5), component_idx=0)\n >>> len(store)\n 2\n >>> store.empty()\n >>> len(store)\n 0\n \"\"\"\n # We don't need to zero the data, just reset the number of items stored\n self._items_stored = [0 for _ in self._items_stored]" }, { "identifier": "SparseAutoencoder", "path": "sparse_autoencoder/autoencoder/model.py", "snippet": "class SparseAutoencoder(Module):\n \"\"\"Sparse Autoencoder Model.\"\"\"\n\n config: SparseAutoencoderConfig\n \"\"\"Model config.\"\"\"\n\n geometric_median_dataset: Float[\n Tensor, Axis.names(Axis.COMPONENT_OPTIONAL, Axis.INPUT_OUTPUT_FEATURE)\n ]\n \"\"\"Estimated Geometric Median of the Dataset.\n\n Used for initialising :attr:`tied_bias`.\n \"\"\"\n\n tied_bias: Float[\n Parameter, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.INPUT_OUTPUT_FEATURE)\n ]\n \"\"\"Tied Bias Parameter.\n\n The same bias is used pre-encoder and post-decoder.\n \"\"\"\n\n pre_encoder_bias: TiedBias\n \"\"\"Pre-Encoder Bias.\"\"\"\n\n encoder: LinearEncoder\n \"\"\"Encoder.\"\"\"\n\n decoder: UnitNormDecoder\n \"\"\"Decoder.\"\"\"\n\n post_decoder_bias: TiedBias\n \"\"\"Post-Decoder Bias.\"\"\"\n\n def __init__(\n self,\n config: SparseAutoencoderConfig,\n geometric_median_dataset: Float[\n Tensor, Axis.names(Axis.COMPONENT_OPTIONAL, Axis.INPUT_OUTPUT_FEATURE)\n ]\n | None = None,\n ) -> None:\n \"\"\"Initialize the Sparse Autoencoder Model.\n\n Args:\n config: Model config.\n geometric_median_dataset: Estimated geometric median of the dataset.\n \"\"\"\n super().__init__()\n\n self.config = config\n\n # Store the geometric median of the dataset (so that we can reset parameters). This is not a\n # parameter itself (the tied bias parameter is used for that), so gradients are disabled.\n tied_bias_shape = shape_with_optional_dimensions(\n config.n_components, config.n_input_features\n )\n if geometric_median_dataset is not None:\n self.geometric_median_dataset = geometric_median_dataset.clone()\n self.geometric_median_dataset.requires_grad = False\n else:\n self.geometric_median_dataset = torch.zeros(tied_bias_shape)\n self.geometric_median_dataset.requires_grad = False\n\n # Initialize the tied bias\n self.tied_bias = Parameter(torch.empty(tied_bias_shape))\n self.initialize_tied_parameters()\n\n # Initialize the components\n self.pre_encoder_bias = TiedBias(self.tied_bias, TiedBiasPosition.PRE_ENCODER)\n\n self.encoder = LinearEncoder(\n input_features=config.n_input_features,\n learnt_features=config.n_learned_features,\n n_components=config.n_components,\n )\n\n self.decoder = UnitNormDecoder(\n learnt_features=config.n_learned_features,\n decoded_features=config.n_input_features,\n n_components=config.n_components,\n )\n\n self.post_decoder_bias = TiedBias(self.tied_bias, TiedBiasPosition.POST_DECODER)\n\n def forward(\n self,\n x: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.INPUT_OUTPUT_FEATURE)\n ],\n ) -> ForwardPassResult:\n \"\"\"Forward Pass.\n\n Args:\n x: Input activations (e.g. activations from an MLP layer in a transformer model).\n\n Returns:\n Tuple of learned activations and decoded activations.\n \"\"\"\n x = self.pre_encoder_bias(x)\n learned_activations = self.encoder(x)\n x = self.decoder(learned_activations)\n decoded_activations = self.post_decoder_bias(x)\n\n return ForwardPassResult(learned_activations, decoded_activations)\n\n def initialize_tied_parameters(self) -> None:\n \"\"\"Initialize the tied parameters.\"\"\"\n # The tied bias is initialised as the geometric median of the dataset\n self.tied_bias.data = self.geometric_median_dataset\n\n def reset_parameters(self) -> None:\n \"\"\"Reset the parameters.\"\"\"\n self.initialize_tied_parameters()\n for module in self.network:\n if \"reset_parameters\" in dir(module):\n module.reset_parameters()\n\n @property\n def reset_optimizer_parameter_details(self) -> list[ResetOptimizerParameterDetails]:\n \"\"\"Reset optimizer parameter details.\n\n Details of the parameters that should be reset in the optimizer, when resetting\n dictionary vectors.\n\n Returns:\n List of tuples of the form `(parameter, axis)`, where `parameter` is the parameter to\n reset (e.g. encoder.weight), and `axis` is the axis of the parameter to reset.\n \"\"\"\n return (\n self.encoder.reset_optimizer_parameter_details\n + self.decoder.reset_optimizer_parameter_details\n )\n\n def post_backwards_hook(self) -> None:\n \"\"\"Hook to be called after each learning step.\n\n This can be used to e.g. constrain weights to unit norm.\n \"\"\"\n self.decoder.constrain_weights_unit_norm()\n\n @staticmethod\n @validate_call\n def get_single_component_state_dict(\n state: SparseAutoencoderState, component_idx: NonNegativeInt\n ) -> dict[str, Tensor]:\n \"\"\"Get the state dict for a single component.\n\n Args:\n state: Sparse Autoencoder state.\n component_idx: Index of the component to get the state dict for.\n\n Returns:\n State dict for the component.\n\n Raises:\n ValueError: If the state dict doesn't contain a components dimension.\n \"\"\"\n # Check the state has a components dimension\n if state.config.n_components is None:\n error_message = (\n \"Trying to load a single component from the state dict, but the state dict \"\n \"doesn't contain a components dimension.\"\n )\n raise ValueError(error_message)\n\n # Return the state dict for the component\n return {key: value[component_idx] for key, value in state.state_dict.items()}\n\n def save(self, file_path: Path) -> None:\n \"\"\"Save the model config and state dict to a file.\n\n Args:\n file_path: Path to save the model to.\n \"\"\"\n file_path.parent.mkdir(parents=True, exist_ok=True)\n state = SparseAutoencoderState(config=self.config, state_dict=self.state_dict())\n torch.save(state, file_path)\n\n @staticmethod\n def load(\n file_path: FILE_LIKE,\n component_idx: PositiveInt | None = None,\n ) -> \"SparseAutoencoder\":\n \"\"\"Load the model from a file.\n\n Args:\n file_path: Path to load the model from.\n component_idx: If loading a state dict from a model that has been trained on multiple\n components (e.g. all MLP layers) you may want to to load just one component. In this\n case you can set `component_idx` to the index of the component to load. Note you\n should not set this if you want to load a state dict from a model that has been\n trained on a single component (or if you want to load all components).\n\n Returns:\n The loaded model.\n \"\"\"\n # Load the file\n serialized_state = torch.load(file_path, map_location=torch.device(\"cpu\"))\n state = SparseAutoencoderState.model_validate(serialized_state)\n\n # Initialise the model\n config = SparseAutoencoderConfig(\n n_input_features=state.config.n_input_features,\n n_learned_features=state.config.n_learned_features,\n n_components=state.config.n_components if component_idx is None else None,\n )\n state_dict = (\n SparseAutoencoder.get_single_component_state_dict(state, component_idx)\n if component_idx is not None\n else state.state_dict\n )\n model = SparseAutoencoder(config)\n model.load_state_dict(state_dict)\n\n return model\n\n def save_to_wandb(\n self,\n artifact_name: str,\n directory: DirectoryPath = DEFAULT_TMP_DIR,\n ) -> str:\n \"\"\"Save the model to wandb.\n\n Args:\n artifact_name: A human-readable name for this artifact, which is how you can identify\n this artifact in the UI or reference it in use_artifact calls. Names can contain\n letters, numbers, underscores, hyphens, and dots. The name must be unique across a\n project. Example: \"sweep_name 1e9 activations\".\n directory: Directory to save the model to.\n\n Returns:\n Name of the wandb artifact.\n\n Raises:\n ValueError: If wandb is not initialised.\n \"\"\"\n # Save the file\n directory.mkdir(parents=True, exist_ok=True)\n file_name = artifact_name + \".pt\"\n file_path = directory / file_name\n self.save(file_path)\n\n # Upload to wandb\n if wandb.run is None:\n error_message = \"Trying to save the model to wandb, but wandb is not initialised.\"\n raise ValueError(error_message)\n artifact = wandb.Artifact(\n artifact_name,\n type=\"model\",\n description=\"Sparse Autoencoder model state, created with `sparse_autoencoder`.\",\n )\n artifact.add_file(str(file_path), name=\"sae-model-state.pt\")\n artifact.save()\n wandb.log_artifact(artifact)\n artifact.wait()\n\n return artifact.source_qualified_name\n\n @staticmethod\n def load_from_wandb(\n wandb_artifact_name: str,\n component_idx: PositiveInt | None = None,\n ) -> \"SparseAutoencoder\":\n \"\"\"Load the model from wandb.\n\n Args:\n wandb_artifact_name: Name of the wandb artifact to load the model from (e.g.\n \"username/project/artifact_name:version\").\n component_idx: If loading a state dict from a model that has been trained on multiple\n components (e.g. all MLP layers) you may want to to load just one component. In this\n case you can set `component_idx` to the index of the component to load. Note you\n should not set this if you want to load a state dict from a model that has been\n trained on a single component (or if you want to load all components).\n\n Returns:\n The loaded model.\n \"\"\"\n api = wandb.Api()\n artifact = api.artifact(wandb_artifact_name, type=\"model\")\n download_path = artifact.download()\n return SparseAutoencoder.load(Path(download_path) / \"sae-model-state.pt\", component_idx)\n\n def save_to_hugging_face(\n self,\n file_name: str,\n repo_id: str,\n directory: DirectoryPath = DEFAULT_TMP_DIR,\n hf_access_token: str | None = None,\n ) -> None:\n \"\"\"Save the model to Hugging Face.\n\n Args:\n file_name: Name of the file (e.g. \"model-something.pt\").\n repo_id: ID of the repo to save the model to.\n directory: Directory to save the model to.\n hf_access_token: Hugging Face access token.\n \"\"\"\n # Save the file\n directory.mkdir(parents=True, exist_ok=True)\n file_path = directory / file_name\n self.save(file_path)\n\n # Upload to Hugging Face\n api = HfApi(token=hf_access_token)\n api.upload_file(\n path_or_fileobj=file_path,\n path_in_repo=file_name,\n repo_id=repo_id,\n repo_type=\"model\",\n )\n\n @staticmethod\n def load_from_hugging_face(\n file_name: str,\n repo_id: str,\n component_idx: PositiveInt | None = None,\n ) -> \"SparseAutoencoder\":\n \"\"\"Load the model from Hugging Face.\n\n Args:\n file_name: File name of the .pt state file.\n repo_id: ID of the repo to load the model from.\n component_idx: If loading a state dict from a model that has been trained on multiple\n components (e.g. all MLP layers) you may want to to load just one component. In this\n case you can set `component_idx` to the index of the component to load. Note you\n should not set this if you want to load a state dict from a model that has been\n trained on a single component (or if you want to load all components).\n\n Returns:\n The loaded model.\n \"\"\"\n local_file = hf_hub_download(\n repo_id=repo_id,\n repo_type=\"model\",\n filename=file_name,\n revision=\"main\",\n )\n\n return SparseAutoencoder.load(Path(local_file), component_idx)" }, { "identifier": "SparseAutoencoderConfig", "path": "sparse_autoencoder/autoencoder/model.py", "snippet": "class SparseAutoencoderConfig(BaseModel, frozen=True):\n \"\"\"SAE model config.\"\"\"\n\n n_input_features: PositiveInt\n \"\"\"Number of input features.\n\n E.g. `d_mlp` if training on MLP activations from TransformerLens).\n \"\"\"\n\n n_learned_features: PositiveInt\n \"\"\"Number of learned features.\n\n The initial paper experimented with 1 to 256 times the number of input features, and primarily\n used a multiple of 8.\"\"\"\n\n n_components: PositiveInt | None = None\n \"\"\"Number of source model components the SAE is trained on.\"\"\n\n This is useful if you want to train the SAE on several components of the source model at once.\n If `None`, the SAE is assumed to be trained on just one component (in this case the model won't\n contain a component axis in any of the parameters).\n \"\"\"" }, { "identifier": "L2ReconstructionLoss", "path": "sparse_autoencoder/loss/decoded_activations_l2.py", "snippet": "class L2ReconstructionLoss(AbstractLoss):\n \"\"\"L2 Reconstruction loss.\n\n L2 reconstruction loss is calculated as the sum squared error between each each input vector\n and it's corresponding decoded vector. The original paper found that models trained with some\n loss functions such as cross-entropy loss generally prefer to represent features\n polysemantically, whereas models trained with L2 may achieve the same loss for both\n polysemantic and monosemantic representations of true features.\n\n Example:\n >>> import torch\n >>> loss = L2ReconstructionLoss()\n >>> input_activations = torch.tensor([[5.0, 4], [3.0, 4]])\n >>> output_activations = torch.tensor([[1.0, 5], [1.0, 5]])\n >>> unused_activations = torch.zeros_like(input_activations)\n >>> # Outputs both loss and metrics to log\n >>> loss.forward(input_activations, unused_activations, output_activations)\n tensor([8.5000, 2.5000])\n \"\"\"\n\n _reduction: LossReductionType\n \"\"\"MSE reduction type.\"\"\"\n\n def __init__(self, reduction: LossReductionType = LossReductionType.MEAN) -> None:\n \"\"\"Initialise the L2 reconstruction loss.\n\n Args:\n reduction: MSE reduction type.\n \"\"\"\n super().__init__()\n self._reduction = reduction\n\n def log_name(self) -> str:\n \"\"\"Log name.\n\n Returns:\n Name of the loss module for logging.\n \"\"\"\n return \"l2_reconstruction_loss\"\n\n def forward(\n self,\n source_activations: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.INPUT_OUTPUT_FEATURE)\n ],\n learned_activations: Float[ # noqa: ARG002\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.LEARNT_FEATURE)\n ],\n decoded_activations: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.INPUT_OUTPUT_FEATURE)\n ],\n ) -> (\n Float[Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL)]\n | Float[Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.INPUT_OUTPUT_FEATURE)]\n ):\n \"\"\"Calculate the L2 reconstruction loss.\n\n Args:\n source_activations: Source activations (input activations to the autoencoder from the\n source model).\n learned_activations: Learned activations (intermediate activations in the autoencoder).\n decoded_activations: Decoded activations.\n\n Returns:\n Loss per batch item.\n \"\"\"\n square_error_loss = mse_loss(source_activations, decoded_activations, reduction=\"none\")\n\n match self._reduction:\n case LossReductionType.MEAN:\n return square_error_loss.mean(dim=-1)\n case LossReductionType.SUM:\n return square_error_loss.sum(dim=-1)\n case LossReductionType.NONE:\n return square_error_loss" }, { "identifier": "LearnedActivationsL1Loss", "path": "sparse_autoencoder/loss/learned_activations_l1.py", "snippet": "class LearnedActivationsL1Loss(AbstractLoss):\n \"\"\"Learned activations L1 (absolute error) loss.\n\n L1 loss penalty is the absolute sum of the learned activations. The L1 penalty is this\n multiplied by the l1_coefficient (designed to encourage sparsity).\n\n Example:\n >>> l1_loss = LearnedActivationsL1Loss(0.1)\n >>> learned_activations = torch.tensor([[2.0, -3], [2.0, -3]])\n >>> unused_activations = torch.zeros_like(learned_activations)\n >>> # Returns loss and metrics to log\n >>> l1_loss.forward(unused_activations, learned_activations, unused_activations)[0]\n tensor(0.5000)\n \"\"\"\n\n l1_coefficient: float | Float[Tensor, Axis.names(Axis.COMPONENT_OPTIONAL)]\n \"\"\"L1 coefficient.\"\"\"\n\n def log_name(self) -> str:\n \"\"\"Log name.\n\n Returns:\n Name of the loss module for logging.\n \"\"\"\n return \"learned_activations_l1_loss_penalty\"\n\n @validate_call(config={\"arbitrary_types_allowed\": True})\n def __init__(\n self, l1_coefficient: PositiveFloat | Float[Tensor, Axis.names(Axis.COMPONENT_OPTIONAL)]\n ) -> None:\n \"\"\"Initialize the absolute error loss.\n\n Args:\n l1_coefficient: L1 coefficient. The original paper experimented with L1 coefficients of\n [0.01, 0.008, 0.006, 0.004, 0.001]. They used 250 tokens per prompt, so as an\n approximate guide if you use e.g. 2x this number of tokens you might consider using\n 0.5x the l1 coefficient.\n \"\"\"\n self.l1_coefficient = l1_coefficient\n super().__init__()\n\n def _l1_loss(\n self,\n source_activations: Float[ # noqa: ARG002\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.INPUT_OUTPUT_FEATURE)\n ],\n learned_activations: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.LEARNT_FEATURE)\n ],\n decoded_activations: Float[ # noqa: ARG002s\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.INPUT_OUTPUT_FEATURE)\n ],\n ) -> _L1LossAndPenalty:\n \"\"\"Learned activations L1 (absolute error) loss.\n\n Args:\n source_activations: Source activations (input activations to the autoencoder from the\n source model).\n learned_activations: Learned activations (intermediate activations in the autoencoder).\n decoded_activations: Decoded activations.\n\n Returns:\n Tuple of itemwise absolute loss, and itemwise absolute loss multiplied by the l1\n coefficient.\n \"\"\"\n # Absolute loss is the summed absolute value of the learned activations (i.e. over the\n # learned feature axis).\n itemwise_absolute_loss: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL)\n ] = torch.abs(learned_activations).sum(dim=-1)\n\n itemwise_absolute_loss_penalty: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL)\n ] = itemwise_absolute_loss * self.l1_coefficient\n\n return _L1LossAndPenalty(\n itemwise_absolute_loss=itemwise_absolute_loss,\n itemwise_absolute_loss_penalty=itemwise_absolute_loss_penalty,\n )\n\n def forward(\n self,\n source_activations: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.INPUT_OUTPUT_FEATURE)\n ],\n learned_activations: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.LEARNT_FEATURE)\n ],\n decoded_activations: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.INPUT_OUTPUT_FEATURE)\n ],\n ) -> Float[Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL)]:\n \"\"\"Learned activations L1 (absolute error) loss.\n\n Args:\n source_activations: Source activations (input activations to the autoencoder from the\n source model).\n learned_activations: Learned activations (intermediate activations in the autoencoder).\n decoded_activations: Decoded activations.\n\n Returns:\n Loss per batch item.\n \"\"\"\n return self._l1_loss(\n source_activations, learned_activations, decoded_activations\n ).itemwise_absolute_loss_penalty\n\n # Override to add both the loss and the penalty to the log\n def scalar_loss_with_log(\n self,\n source_activations: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.INPUT_OUTPUT_FEATURE)\n ],\n learned_activations: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.LEARNT_FEATURE)\n ],\n decoded_activations: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.INPUT_OUTPUT_FEATURE)\n ],\n batch_reduction: LossReductionType = LossReductionType.MEAN,\n component_reduction: LossReductionType = LossReductionType.NONE,\n ) -> LossResultWithMetrics:\n \"\"\"Scalar L1 loss (reduced across the batch and component axis) with logging.\n\n Args:\n source_activations: Source activations (input activations to the autoencoder from the\n source model).\n learned_activations: Learned activations (intermediate activations in the autoencoder).\n decoded_activations: Decoded activations.\n batch_reduction: Batch reduction type. Typically you would choose LossReductionType.MEAN\n to make the loss independent of the batch size.\n component_reduction: Component reduction type.\n\n Returns:\n Tuple of the L1 absolute error batch scalar loss and a dict of the properties to log\n (loss before and after the l1 coefficient).\n\n Raises:\n ValueError: If batch_reduction is LossReductionType.NONE.\n \"\"\"\n itemwise_absolute_loss, itemwise_absolute_loss_penalty = self._l1_loss(\n source_activations, learned_activations, decoded_activations\n )\n\n match batch_reduction:\n case LossReductionType.MEAN:\n batch_scalar_loss = itemwise_absolute_loss.mean(0)\n batch_scalar_loss_penalty = itemwise_absolute_loss_penalty.mean(0)\n case LossReductionType.SUM:\n batch_scalar_loss = itemwise_absolute_loss.sum(0)\n batch_scalar_loss_penalty = itemwise_absolute_loss_penalty.sum(0)\n case LossReductionType.NONE:\n error_message = \"Batch reduction type NONE not supported.\"\n raise ValueError(error_message)\n\n # Create the log\n metrics: list[MetricResult] = [\n MetricResult(\n name=\"loss\",\n postfix=\"learned_activations_l1\",\n component_wise_values=batch_scalar_loss.unsqueeze(0)\n if batch_scalar_loss.ndim == 0\n else batch_scalar_loss,\n location=MetricLocation.TRAIN,\n ),\n MetricResult(\n name=\"loss\",\n postfix=self.log_name(),\n component_wise_values=batch_scalar_loss_penalty.unsqueeze(0)\n if batch_scalar_loss_penalty.ndim == 0\n else batch_scalar_loss_penalty,\n location=MetricLocation.TRAIN,\n ),\n ]\n\n match component_reduction:\n case LossReductionType.MEAN:\n batch_scalar_loss_penalty = batch_scalar_loss_penalty.mean(0)\n case LossReductionType.SUM:\n batch_scalar_loss_penalty = batch_scalar_loss_penalty.sum(0)\n case LossReductionType.NONE:\n pass\n\n return LossResultWithMetrics(loss=batch_scalar_loss_penalty, loss_metrics=metrics)\n\n def extra_repr(self) -> str:\n \"\"\"Extra representation string.\"\"\"\n return f\"l1_coefficient={self.l1_coefficient}\"" }, { "identifier": "LossReducer", "path": "sparse_autoencoder/loss/reducer.py", "snippet": "class LossReducer(AbstractLoss):\n \"\"\"Loss reducer.\n\n Reduces multiple loss algorithms into a single loss algorithm (by summing). Analogous to\n nn.Sequential.\n\n Example:\n >>> from sparse_autoencoder.loss.decoded_activations_l2 import L2ReconstructionLoss\n >>> from sparse_autoencoder.loss.learned_activations_l1 import LearnedActivationsL1Loss\n >>> LossReducer(\n ... L2ReconstructionLoss(),\n ... LearnedActivationsL1Loss(0.001),\n ... )\n LossReducer(\n (0): L2ReconstructionLoss()\n (1): LearnedActivationsL1Loss(l1_coefficient=0.001)\n )\n\n \"\"\"\n\n _modules: dict[str, \"AbstractLoss\"]\n \"\"\"Children loss modules.\"\"\"\n\n def log_name(self) -> str:\n \"\"\"Log name.\n\n Returns:\n Name of the loss module for logging.\n \"\"\"\n return \"total_loss\"\n\n def __init__(\n self,\n *loss_modules: AbstractLoss,\n ):\n \"\"\"Initialize the loss reducer.\n\n Args:\n *loss_modules: Loss modules to reduce.\n\n Raises:\n ValueError: If the loss reducer has no loss modules.\n \"\"\"\n super().__init__()\n\n for idx, loss_module in enumerate(loss_modules):\n self._modules[str(idx)] = loss_module\n\n if len(self) == 0:\n error_message = \"Loss reducer must have at least one loss module.\"\n raise ValueError(error_message)\n\n def forward(\n self,\n source_activations: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.INPUT_OUTPUT_FEATURE)\n ],\n learned_activations: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.LEARNT_FEATURE)\n ],\n decoded_activations: Float[\n Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL, Axis.INPUT_OUTPUT_FEATURE)\n ],\n ) -> Float[Tensor, Axis.names(Axis.BATCH, Axis.COMPONENT_OPTIONAL)]:\n \"\"\"Reduce loss.\n\n Args:\n source_activations: Source activations (input activations to the autoencoder from the\n source model).\n learned_activations: Learned activations (intermediate activations in the autoencoder).\n decoded_activations: Decoded activations.\n\n Returns:\n Mean loss across the batch, summed across the loss modules.\n \"\"\"\n all_modules_loss: Float[Tensor, \"module train_batch\"] = torch.stack(\n [\n loss_module.forward(source_activations, learned_activations, decoded_activations)\n for loss_module in self._modules.values()\n ]\n )\n\n return all_modules_loss.sum(dim=0)\n\n def __dir__(self) -> list[str]:\n \"\"\"Dir dunder method.\"\"\"\n return list(self._modules.__dir__())\n\n def __getitem__(self, idx: int) -> AbstractLoss:\n \"\"\"Get item dunder method.\"\"\"\n return self._modules[str(idx)]\n\n def __iter__(self) -> Iterator[AbstractLoss]:\n \"\"\"Iterator dunder method.\"\"\"\n return iter(self._modules.values())\n\n def __len__(self) -> int:\n \"\"\"Length dunder method.\"\"\"\n return len(self._modules)" }, { "identifier": "Axis", "path": "sparse_autoencoder/tensor_types.py", "snippet": "class Axis(LowercaseStrEnum):\n \"\"\"Tensor axis names.\n\n Used to annotate tensor types.\n\n Example:\n When used directly it prints a string:\n\n >>> print(Axis.INPUT_OUTPUT_FEATURE)\n input_output_feature\n\n The primary use is to annotate tensor types:\n\n >>> from jaxtyping import Float\n >>> from torch import Tensor\n >>> from typing import TypeAlias\n >>> batch: TypeAlias = Float[Tensor, Axis.names(Axis.BATCH, Axis.INPUT_OUTPUT_FEATURE)]\n >>> print(batch)\n <class 'jaxtyping.Float[Tensor, 'batch input_output_feature']'>\n\n You can also join multiple axis together to represent the dimensions of a tensor:\n\n >>> print(Axis.names(Axis.BATCH, Axis.INPUT_OUTPUT_FEATURE))\n batch input_output_feature\n \"\"\"\n\n # Component idx\n COMPONENT = auto()\n \"\"\"Component index.\"\"\"\n\n COMPONENT_OPTIONAL = \"*component\"\n \"\"\"Optional component index.\"\"\"\n\n # Batches\n SOURCE_DATA_BATCH = auto()\n \"\"\"Batch of prompts used to generate source model activations.\"\"\"\n\n BATCH = auto()\n \"\"\"Batch of items that the SAE is being trained on.\"\"\"\n\n STORE_BATCH = auto()\n \"\"\"Batch of items to be written to the store.\"\"\"\n\n ITEMS = auto()\n \"\"\"Arbitrary number of items.\"\"\"\n\n # Features\n INPUT_OUTPUT_FEATURE = auto()\n \"\"\"Input or output feature (e.g. feature in activation vector from source model).\"\"\"\n\n LEARNT_FEATURE = auto()\n \"\"\"Learn feature (e.g. feature in learnt activation vector).\"\"\"\n\n DEAD_FEATURE = auto()\n \"\"\"Dead feature.\"\"\"\n\n ALIVE_FEATURE = auto()\n \"\"\"Alive feature.\"\"\"\n\n # Feature indices\n INPUT_OUTPUT_FEATURE_IDX = auto()\n \"\"\"Input or output feature index.\"\"\"\n\n LEARNT_FEATURE_IDX = auto()\n \"\"\"Learn feature index.\"\"\"\n\n # Other\n POSITION = auto()\n \"\"\"Token position.\"\"\"\n\n SINGLE_ITEM = \"\"\n \"\"\"Single item axis.\"\"\"\n\n ANY = \"...\"\n \"\"\"Any number of axis.\"\"\"\n\n @staticmethod\n def names(*axis: \"Axis\") -> str:\n \"\"\"Join multiple axis together, to represent the dimensions of a tensor.\n\n Example:\n >>> print(Axis.names(Axis.BATCH, Axis.INPUT_OUTPUT_FEATURE))\n batch input_output_feature\n\n Args:\n *axis: Axis to join.\n\n Returns:\n Joined axis string.\n \"\"\"\n return \" \".join(a.value for a in axis)" } ]
from jaxtyping import Float, Int64 from torch import Tensor from torch.nn import Parameter from sparse_autoencoder.activation_resampler.activation_resampler import ActivationResampler from sparse_autoencoder.activation_store.base_store import ActivationStore from sparse_autoencoder.activation_store.tensor_store import TensorActivationStore from sparse_autoencoder.autoencoder.model import SparseAutoencoder, SparseAutoencoderConfig from sparse_autoencoder.loss.decoded_activations_l2 import L2ReconstructionLoss from sparse_autoencoder.loss.learned_activations_l1 import LearnedActivationsL1Loss from sparse_autoencoder.loss.reducer import LossReducer from sparse_autoencoder.tensor_types import Axis import pytest import torch
16,542
"""Tests for the resample_neurons module.""" DEFAULT_N_ACTIVATIONS_STORE: int = 100 DEFAULT_N_INPUT_FEATURES: int = 3 DEFAULT_N_LEARNED_FEATURES: int = 5 DEFAULT_N_COMPONENTS: int = 2 @pytest.fixture() def full_activation_store() -> ActivationStore: """Create a dummy activation store, pre-populated with data.""" store = TensorActivationStore( max_items=DEFAULT_N_ACTIVATIONS_STORE, n_components=DEFAULT_N_COMPONENTS, n_neurons=DEFAULT_N_INPUT_FEATURES, ) store.fill_with_test_data( batch_size=DEFAULT_N_ACTIVATIONS_STORE, input_features=DEFAULT_N_INPUT_FEATURES, n_batches=1, n_components=DEFAULT_N_COMPONENTS, ) return store @pytest.fixture() def autoencoder_model() -> SparseAutoencoder: """Create a dummy autoencoder model.""" return SparseAutoencoder( SparseAutoencoderConfig( n_input_features=DEFAULT_N_INPUT_FEATURES, n_learned_features=DEFAULT_N_LEARNED_FEATURES, n_components=DEFAULT_N_COMPONENTS, ) ) @pytest.fixture() def loss_fn() -> LossReducer: """Loss function fixture."""
"""Tests for the resample_neurons module.""" DEFAULT_N_ACTIVATIONS_STORE: int = 100 DEFAULT_N_INPUT_FEATURES: int = 3 DEFAULT_N_LEARNED_FEATURES: int = 5 DEFAULT_N_COMPONENTS: int = 2 @pytest.fixture() def full_activation_store() -> ActivationStore: """Create a dummy activation store, pre-populated with data.""" store = TensorActivationStore( max_items=DEFAULT_N_ACTIVATIONS_STORE, n_components=DEFAULT_N_COMPONENTS, n_neurons=DEFAULT_N_INPUT_FEATURES, ) store.fill_with_test_data( batch_size=DEFAULT_N_ACTIVATIONS_STORE, input_features=DEFAULT_N_INPUT_FEATURES, n_batches=1, n_components=DEFAULT_N_COMPONENTS, ) return store @pytest.fixture() def autoencoder_model() -> SparseAutoencoder: """Create a dummy autoencoder model.""" return SparseAutoencoder( SparseAutoencoderConfig( n_input_features=DEFAULT_N_INPUT_FEATURES, n_learned_features=DEFAULT_N_LEARNED_FEATURES, n_components=DEFAULT_N_COMPONENTS, ) ) @pytest.fixture() def loss_fn() -> LossReducer: """Loss function fixture."""
return LossReducer(LearnedActivationsL1Loss(0.01), L2ReconstructionLoss())
6
2023-10-27 07:37:15+00:00
24k
OATML-Markslab/ProteinNPT
scripts/train.py
[ { "identifier": "ProteinNPTModel", "path": "proteinnpt/model.py", "snippet": "class ProteinNPTModel(nn.Module):\n def __init__(self, args, alphabet):\n super().__init__()\n self.args = args\n self.alphabet = alphabet\n self.alphabet_size = len(alphabet)\n self.padding_idx = alphabet.padding_idx\n self.mask_idx = alphabet.mask_idx\n self.cls_idx = alphabet.cls_idx\n self.eos_idx = alphabet.eos_idx\n self.prepend_bos = alphabet.prepend_bos\n self.append_eos = alphabet.append_eos\n self.target_names_input = self.args.target_config.keys()\n self.target_names = [x for x in self.args.target_config.keys() if self.args.target_config[x][\"in_NPT_loss\"]]\n self.num_targets_input = len(self.target_names_input) #Includes all targets, incl. zero-shot fitness predictions\n self.num_targets = len(self.target_names) #Number of actual targets we want to predict\n self.MSA_sample_sequences = None\n self.training_sample_sequences_indices = None\n self.device = None\n self.optimizer = None\n self.model_type = args.model_type\n self.PNPT_ensemble_test_num_seeds = -1\n self.PNPT_no_reconstruction_error = False\n self.deactivate_col_attention = False\n self.tranception_attention = False\n \n assert self.args.embed_dim % self.args.attention_heads ==0, \"Embedding size {} needs to be a multiple of number of heads {}\".format(self.args.embed_dim, self.args.attention_heads)\n if self.args.aa_embeddings in [\"MSA_Transformer\",\"ESM1v\"]:\n model, _ = utils.esm.pretrained.load_model_and_alphabet(args.embedding_model_location)\n self.aa_embedding = model\n self.aa_embedding_dim = self.aa_embedding.embed_tokens.weight.shape[-1]\n elif self.args.aa_embeddings == \"Tranception\":\n self.aa_embedding_dim = 1280\n config = json.load(open(args.embedding_model_location+os.sep+'config.json'))\n config = utils.tranception.config.TranceptionConfig(**config)\n config.tokenizer = self.alphabet\n config.inference_time_retrieval_type = None\n config.retrieval_aggregation_mode = None\n self.aa_embedding = utils.tranception.model_pytorch.TranceptionLMHeadModel.from_pretrained(pretrained_model_name_or_path=args.embedding_model_location,config=config)\n elif self.args.aa_embeddings == \"Linear_embedding\":\n self.aa_embedding = nn.Embedding(\n self.alphabet_size, self.args.embed_dim, padding_idx=self.padding_idx\n )\n self.aa_positions_embedding = LearnedPositionalEmbedding(\n self.args.max_positions,\n self.args.embed_dim,\n self.padding_idx,\n )\n self.aa_embedding_dim = self.args.embed_dim\n\n if self.aa_embedding_dim != self.args.embed_dim: #Need to project internally\n self.token_embedding_projection = nn.Linear(\n self.aa_embedding_dim,\n self.args.embed_dim\n )\n self.token_embedding_expansion = nn.Linear(\n self.args.embed_dim,\n self.aa_embedding_dim\n )\n\n self.target_embedding = nn.ModuleDict(\n { \n target_name:\n nn.Linear(\n self.args.target_config[target_name][\"dim\"] + 1, #Need to add one as we append the mask flag to each input target \n self.args.embed_dim\n )\n if self.args.target_config[target_name][\"type\"]==\"continuous\"\n else \n nn.Embedding(\n self.args.target_config[target_name][\"dim\"],\n self.args.embed_dim\n )\n for target_name in self.target_names_input\n }\n )\n \n self.dropout_module = nn.Dropout(self.args.dropout)\n\n self.layers = nn.ModuleList(\n [\n AxialTransformerLayer(\n self.args.embed_dim,\n self.args.ffn_embed_dim,\n self.args.attention_heads,\n self.args.dropout,\n self.args.attention_dropout,\n self.args.activation_dropout,\n getattr(self.args, \"max_tokens_per_msa\", self.args.max_tokens_per_msa),\n self.deactivate_col_attention,\n self.tranception_attention,\n self.num_targets_input,\n )\n for _ in range(self.args.num_protein_npt_layers)\n ]\n )\n self.emb_layer_norm_before = ESM1bLayerNorm(self.args.embed_dim)\n self.emb_layer_norm_after = ESM1bLayerNorm(self.args.embed_dim)\n \n if self.args.aa_embeddings in [\"MSA_Transformer\",\"ESM1v\"]:\n weight = self.aa_embedding.embed_tokens.weight\n elif self.args.aa_embeddings == \"Tranception\":\n weight = self.aa_embedding.lm_head.weight\n else:\n weight = self.aa_embedding.weight\n\n self.lm_head = RobertaLMHead(\n embed_dim=self.aa_embedding_dim,\n output_dim=self.alphabet_size,\n weight=weight\n )\n \n target_pred_input_dim = self.args.embed_dim\n\n if args.target_prediction_model==\"MLP\": \n self.layer_pre_head = nn.ModuleDict(\n {\n target_name:\n nn.Sequential(\n nn.Linear(target_pred_input_dim, target_pred_input_dim),\n nn.Dropout(self.args.dropout),\n nn.ReLU()\n ) \n for target_name in self.target_names\n }\n )\n \n if args.target_prediction_model==\"ConvBERT\":\n configuration = ConvBertConfig(\n hidden_size = self.args.embed_dim,\n num_attention_heads = self.args.attention_heads,\n conv_kernel_size = self.args.conv_kernel_size,\n hidden_act = \"gelu\",\n hidden_dropout_prob = self.args.dropout,\n attention_probs_dropout_prob = self.args.dropout\n )\n self.layer_pre_head = ConvBertLayer(configuration)\n \n if args.target_prediction_model==\"CNN\":\n self.layer_pre_head = nn.Sequential(\n nn.Conv1d(in_channels=target_pred_input_dim, out_channels=target_pred_input_dim, kernel_size = self.args.conv_kernel_size, padding='same'),\n nn.Dropout(self.args.dropout),\n nn.ReLU()\n )\n \n if self.args.target_prediction_head == \"Target_embeddings_only\":\n target_pred_input_dim = target_pred_input_dim\n elif self.args.target_prediction_head == \"Target_embeddings_and_AA_embeddings_mean_pooled\":\n target_pred_input_dim = target_pred_input_dim * (1 + self.num_targets_input)\n\n if self.args.augmentation==\"zero_shot_fitness_predictions_covariate\":\n self.zero_shot_fitness_prediction_weight = nn.ModuleDict(\n { \n target_name: nn.Linear(1, self.args.target_config[target_name][\"dim\"], bias=False)\n for target_name in self.target_names\n }\n )\n for target_name in self.target_names:\n torch.nn.init.constant_(self.zero_shot_fitness_prediction_weight[target_name].weight,1e-4)\n\n self.target_pred_head = nn.ModuleDict(\n { \n target_name: nn.Linear(target_pred_input_dim, self.args.target_config[target_name][\"dim\"])\n for target_name in self.target_names\n }\n )\n \n def set_device(self):\n if self.device is None:\n self.device = next(self.parameters()).device\n print(\"Model device: {}\".format(self.device))\n \n def forward(self, tokens, targets=None, zero_shot_fitness_predictions=None, sequence_embeddings=None, repr_layers=[], need_head_weights=False):\n padding_mask = tokens.eq(self.padding_idx) \n if not padding_mask.any(): padding_mask = None\n \n if self.args.aa_embeddings == \"MSA_Transformer\" and self.args.sequence_embeddings_location is None:\n assert tokens.ndim == 3, \"Finding dimension of tokens to be: {}\".format(tokens.ndim)\n num_MSAs_in_batch, num_sequences_in_alignments, seqlen = tokens.size() # N, B, L (seqs with labels, seqs in MSA, seq length)\n batch_size = num_MSAs_in_batch\n else:\n assert tokens.ndim == 2, \"Finding dimension of tokens to be: {}\".format(tokens.ndim)\n batch_size, seqlen = tokens.size() # N, L (seqs with labels, seq length)\n \n if sequence_embeddings is not None:\n x = sequence_embeddings.to(self.device)\n else:\n if self.args.aa_embeddings == \"MSA_Transformer\":\n output = self.aa_embedding(tokens, repr_layers=[12])\n x = output[\"representations\"][12][:] # N, B, L, D\n x = x[:,0,:,:] # N, L, D. #In each MSA batch the first sequence is what we care about. The other MSA sequences were just to compute embeddings and logits\n elif self.args.aa_embeddings == \"ESM1v\":\n last_layer_index = 33\n output = self.aa_embedding(tokens, repr_layers=[last_layer_index])\n x = output[\"representations\"][last_layer_index][:] # N, L, D\n elif self.args.aa_embeddings ==\"Linear_embedding\":\n x = self.aa_embedding(tokens)\n x = x + self.aa_positions_embedding(tokens.view(batch_size, seqlen)).view(x.size()) # Need position embedding in PNPT since we will apply axial attention\n else:\n print(\"AA embeddings not recognized\")\n sys.exit(0)\n \n if self.aa_embedding_dim != self.args.embed_dim: x = self.token_embedding_projection(x)\n \n if self.args.target_prediction_head != \"Target_embeddings_and_AA_embeddings_mean_pooled\": #We mix AA embeddings pre NPT\n if self.args.target_prediction_model == \"CNN\": \n assert len(x.size())==3, \"Size error input\"\n N, L, D = x.size()\n x = x.permute(0,2,1) #N, D, L\n x = self.layer_pre_head(x)\n x = x.permute(0,2,1)\n elif self.args.target_prediction_model == \"ConvBERT\":\n x = self.layer_pre_head(x)[0]\n\n x = x.view(1, batch_size, seqlen, self.args.embed_dim) # 1, N, L, D\n \n #Dimensions for each target (there are self.num_targets of them):\n y = []\n for target_name in self.target_names_input:\n num_sequences_with_target, dim_targets = targets[target_name].shape # N, D_t #In most cases dim_targets = D_t = 2 (original dimension of continuous input + 1 dim for mask)\n y.append(self.target_embedding[target_name](targets[target_name]).view(num_sequences_with_target,1,self.args.embed_dim))\n y = torch.cat(y, dim=-2) #concatenate across second to last dimension # N, num_targets, D\n assert y.shape == (num_sequences_with_target, self.num_targets_input, self.args.embed_dim), \"Error in y shape: {}\".format(y.shape)\n y = y.view(1, num_sequences_with_target, self.num_targets_input, self.args.embed_dim) # 1, N, num_targets, D\n \n #Concatenate AA tokens and targets\n x = torch.cat((x,y),dim=-2) # 1, N, (L+num_targets), D\n x = self.emb_layer_norm_before(x)\n x = self.dropout_module(x)\n\n if padding_mask is not None:\n padding_mask_with_targets = torch.zeros(num_MSAs_in_batch, num_sequences_in_alignments, seqlen + self.num_targets_input)\n padding_mask_with_targets[...,:seqlen] = padding_mask\n padding_mask = padding_mask_with_targets\n x = x * (1 - padding_mask.unsqueeze(-1).type_as(x))\n \n repr_layers = set(repr_layers)\n hidden_representations = {}\n if 0 in repr_layers: hidden_representations[0] = x\n if need_head_weights:\n row_attn_weights = []\n col_attn_weights = []\n\n # 1 x N x L x D -> N x L x 1 x D\n x = x.permute(1, 2, 0, 3)\n for layer_idx, layer in enumerate(self.layers):\n x = layer(\n x,\n self_attn_padding_mask=padding_mask,\n need_head_weights=need_head_weights,\n )\n if need_head_weights:\n x, col_attn, row_attn = x\n col_attn_weights.append(col_attn.permute(2, 0, 1, 3, 4).cpu())\n row_attn_weights.append(row_attn.permute(1, 0, 2, 3).cpu())\n if (layer_idx + 1) in repr_layers:\n hidden_representations[layer_idx + 1] = x.permute(2, 0, 1, 3)\n x = self.emb_layer_norm_after(x)\n x = x.permute(2, 0, 1, 3) # N x L x 1 x D -> 1 x N x L x D\n assert x.shape == (1, num_sequences_with_target, seqlen + self.num_targets_input, self.args.embed_dim), \"Error with axial transformer\"\n # last hidden representation should have layer norm applied\n if (layer_idx + 1) in repr_layers: hidden_representations[layer_idx + 1] = x\n \n # Loss over NPT MLM objective\n if self.aa_embedding_dim != self.args.embed_dim:\n logits_protein_sequence = self.lm_head(self.token_embedding_expansion(x[...,:seqlen,:]))\n else:\n logits_protein_sequence = self.lm_head(x[...,:seqlen,:]) #Remove dependency on targets for final AA predictions. logits size: (1, N, L, Vocab)\n \n x = x.view(num_sequences_with_target, seqlen + self.num_targets_input, self.args.embed_dim)\n x, y = x[:,:seqlen,:], x[:,seqlen:,:] # (N,L,D) and (N,num_targets,D)\n assert y.shape == (num_sequences_with_target, self.num_targets_input, self.args.embed_dim)\n if self.args.target_prediction_head == \"Target_embeddings_and_AA_embeddings_mean_pooled\": \n if self.args.target_prediction_model == \"CNN\": \n assert len(x.size())==3, \"Size error input\"\n N, L, D = x.size()\n x = x.permute(0,2,1) #N, D, L\n x = self.layer_pre_head(x)\n x = x.permute(0,2,1)\n elif self.args.target_prediction_model == \"ConvBERT\":\n x = self.layer_pre_head(x)[0]\n x = x.mean(dim=-2) # N, D\n y = y.view(num_sequences_with_target,self.num_targets_input * self.args.embed_dim)\n y = torch.cat((x,y),dim=-1) # N, (1+num_targets) * D\n \n target_predictions = {}\n for target_index, target_name in enumerate(self.target_names):\n if self.args.target_prediction_head == \"Target_embeddings_and_AA_embeddings_mean_pooled\": \n target_predictions[target_name] = self.target_pred_head[target_name](y).view(-1) #We use the concatenated X and target embeddings (all of them) to predict each target\n else:\n if self.args.target_prediction_model == \"MLP\": y[:,target_index,:] = self.layer_pre_head[target_name](y[:,target_index,:])\n target_predictions[target_name] = self.target_pred_head[target_name](y[:,target_index,:]).view(-1) #input the embedding with the relevant target_index\n if self.args.augmentation==\"zero_shot_fitness_predictions_covariate\":\n target_predictions[target_name] += self.zero_shot_fitness_prediction_weight[target_name](zero_shot_fitness_predictions).squeeze()\n \n result = {\"logits_protein_sequence\": logits_protein_sequence, \"target_predictions\": target_predictions, \"representations\": hidden_representations}\n \n if need_head_weights:\n col_attentions = torch.stack(col_attn_weights, 1)\n row_attentions = torch.stack(row_attn_weights, 1)\n result[\"col_attentions\"] = col_attentions\n result[\"row_attentions\"] = row_attentions\n\n return result\n\n def forward_with_uncertainty(self, tokens, targets, zero_shot_fitness_predictions=None, sequence_embeddings=None, num_MC_dropout_samples=10, number_of_mutated_seqs_to_score=None):\n \"\"\"\n Performs MC dropout to compute predictions and the corresponding uncertainties.\n Assumes 1D predictions (eg., prediction of continuous output)\n \"\"\"\n self.eval() \n for m in self.modules(): #Move all dropout layers in train mode to support MC dropout. Keep everything else in eval mode.\n if m.__class__.__name__.startswith('Dropout'):\n m.train()\n with torch.no_grad():\n predictions_dict = defaultdict(list)\n for _ in range(num_MC_dropout_samples):\n target_predictions_sample = self.forward(tokens, targets, zero_shot_fitness_predictions=zero_shot_fitness_predictions, sequence_embeddings=sequence_embeddings)[\"target_predictions\"]\n for target_name in self.target_names:\n predictions_dict[target_name].append(target_predictions_sample[target_name])\n results_with_uncertainty={}\n for target_name in self.target_names:\n concatenated_target_pred = torch.cat([x.view(-1,1) for x in predictions_dict[target_name]],dim=-1)\n results_with_uncertainty[target_name] = {}\n results_with_uncertainty[target_name]['predictions_avg'] = concatenated_target_pred.mean(dim=-1)\n results_with_uncertainty[target_name]['uncertainty'] = concatenated_target_pred.std(dim=-1)\n return results_with_uncertainty\n \n @property\n def num_layers(self):\n return self.args.num_protein_npt_layers\n \n def max_tokens_per_msa_(self, value: int) -> None:\n \"\"\"\n Batching attention computations when gradients are disabled as per MSA_Transformer\n Set this value to infinity to disable this behavior.\n \"\"\"\n for module in self.modules():\n if isinstance(module, (RowSelfAttention, ColumnSelfAttention)):\n module.max_tokens_per_msa = value\n\n def protein_npt_loss(self, token_predictions_logits, token_labels, target_predictions, target_labels, MLM_reconstruction_loss_weight, label_smoothing=0.0):\n target_prediction_loss_weight = 1.0 - MLM_reconstruction_loss_weight\n total_loss = 0.0\n if (token_labels is not None) and (MLM_reconstruction_loss_weight > 0.0):\n if self.args.aa_embeddings == \"MSA_Transformer\" and self.args.sequence_embeddings_location is None: token_labels = token_labels[:,0,:] #Only keep the token labels for seq to score. Drops the token labels for MSA sequences\n masked_lm_loss = CrossEntropyLoss(reduction=\"mean\", label_smoothing=label_smoothing)(token_predictions_logits.reshape(-1, self.alphabet_size), token_labels.reshape(-1))\n reconstruction_loss = masked_lm_loss\n total_loss += MLM_reconstruction_loss_weight * reconstruction_loss\n else:\n reconstruction_loss = torch.tensor(0.0)\n target_prediction_loss = {}\n for target_name in self.target_names:\n if self.args.target_config[target_name][\"in_NPT_loss\"]:\n if self.args.target_config[target_name][\"type\"]==\"continuous\":\n loss_masked_targets = ~target_labels[target_name].eq(-100) #Masked items are the ones for which the label was not set to -100\n if loss_masked_targets.sum()==0 or torch.isnan(target_labels[target_name][loss_masked_targets]).sum() > 0: #First condition true if we dont mask anything (eg., all target missing at eval). Second condition true if we force-mask one value at train time (to satisfy min_num_labels_masked in mast_target()) and corresponding target value is missing\n tgt_loss = torch.tensor(0.0)\n else:\n tgt_loss = MSELoss(reduction=\"mean\")(target_predictions[target_name][loss_masked_targets], target_labels[target_name][loss_masked_targets]) #we do not average the loss per batch, so that it's easier to do 1 full average across all batches\n if torch.isnan(tgt_loss).sum() > 0:\n print(\"Detected nan loss\")\n print(target_predictions[target_name])\n else:\n tgt_loss = CrossEntropyLoss(reduction=\"mean\", label_smoothing=label_smoothing)(target_predictions[target_name].view(-1, self.args.target_config[target_name][\"dim\"]), target_labels[target_name].view(-1)) # Note: we dont add one to the # of categories in the CE loss here (we dont predict <mask>)\n target_prediction_loss[target_name] = tgt_loss\n \n total_loss += target_prediction_loss_weight * target_prediction_loss[target_name]\n return total_loss, reconstruction_loss, target_prediction_loss\n\n def create_optimizer(self):\n \"\"\"\n Setup the optimizer.\n We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the\n Trainer's init through `optimizers`, or subclass and override this method in a subclass.\n Adapted from Huggingface Transformers library.\n \"\"\"\n if self.optimizer is None:\n all_parameters = utils.model_utils.get_parameter_names(self, [nn.LayerNorm])\n decay_parameters = [name for name in all_parameters if (\"bias\" not in name and \"pseudo_likelihood_weight\" not in name and 'zero_shot_fitness_prediction_weight' not in name)]\n psl_decay_parameters = [name for name in all_parameters if (\"bias\" not in name and (\"pseudo_likelihood_weight\" in name or \"zero_shot_fitness_prediction_weight\" in name))]\n optimizer_grouped_parameters = [\n {\n \"params\": [p for n, p in self.named_parameters() if n in decay_parameters],\n \"weight_decay\": self.args.weight_decay,\n },\n {\n \"params\": [p for n, p in self.named_parameters() if n in psl_decay_parameters],\n \"weight_decay\": 1e-8, #Small decay on pseudo-likelihood as in Hsu et al.\n },\n {\n \"params\": [p for n, p in self.named_parameters() if (n not in decay_parameters and n not in psl_decay_parameters)],\n \"weight_decay\": 0.0,\n },\n ] \n optimizer_kwargs = {\n \"betas\": (self.args.adam_beta1, self.args.adam_beta2),\n \"eps\": self.args.adam_epsilon,\n \"lr\": self.args.max_learning_rate\n }\n optimizer = AdamW(optimizer_grouped_parameters, **optimizer_kwargs)\n return optimizer" }, { "identifier": "AugmentedPropertyPredictor", "path": "baselines/model.py", "snippet": "class AugmentedPropertyPredictor(nn.Module):\n def __init__(self, args, alphabet):\n super().__init__()\n self.args = args\n self.alphabet = alphabet\n self.alphabet_size = len(alphabet)\n print(\"Alphabet: {}\".format(alphabet))\n print(\"Alphabet size: {}\".format(self.alphabet_size))\n self.padding_idx = alphabet.padding_idx\n self.mask_idx = alphabet.mask_idx\n self.cls_idx = alphabet.cls_idx\n self.eos_idx = alphabet.eos_idx\n self.prepend_bos = alphabet.prepend_bos\n self.append_eos = alphabet.append_eos\n self.target_names = self.args.target_config.keys() \n self.MSA_sample_sequences = None \n self.device = None\n self.model_type = args.model_type \n if self.args.aa_embeddings in [\"MSA_Transformer\",\"ESM1v\"]:\n model, _ = utils.esm.pretrained.load_model_and_alphabet(args.embedding_model_location)\n self.aa_embedding = model\n if self.args.aa_embeddings == \"MSA_Transformer\": self.args.seq_len = self.args.MSA_seq_len #If MSA does not cover full sequence length, we adjust seq_len param to be MSA_len (sequences truncated as needed in preprocessing)\n elif self.args.aa_embeddings == \"Linear_embedding\":\n self.aa_embedding = nn.Sequential(\n nn.Embedding(\n self.alphabet_size, self.args.embed_dim, padding_idx=self.padding_idx\n ),\n nn.ReLU()\n )\n elif self.args.aa_embeddings == \"One_hot_encoding\":\n self.args.target_prediction_head == \"One_hot_encoding\"\n elif self.args.aa_embeddings == \"Tranception\":\n self.aa_embedding_dim = 1280\n config = json.load(open(args.embedding_model_location+os.sep+'config.json'))\n config = utils.tranception.config.TranceptionConfig(**config)\n config.tokenizer = get_tranception_tokenizer()\n config.inference_time_retrieval_type = None\n config.retrieval_aggregation_mode = None\n self.aa_embedding = utils.tranception.model_pytorch.TranceptionLMHeadModel.from_pretrained(pretrained_model_name_or_path=args.embedding_model_location,config=config)\n self.config = config\n else:\n print(\"Error: Specified AA embedding invalid\")\n sys.exit(0)\n\n if self.args.aa_embeddings != \"One_hot_encoding\": \n self.emb_layer_norm_after = ESM1bLayerNorm(self.args.embed_dim)\n self.dropout_module = nn.Dropout(self.args.dropout)\n\n if self.args.target_prediction_head == \"AA_embeddings_mean_pooled\":\n target_pred_input_dim = self.args.embed_dim\n elif self.args.target_prediction_head == \"One_hot_encoding\":\n target_pred_input_dim = (self.args.seq_len + 1) * self.alphabet_size if args.target_prediction_model!=\"CNN\" else self.alphabet_size #Add one for the BOS token\n else:\n print(self.args.target_prediction_head)\n print(\"Error: Specified embedding aggregation invalid\")\n sys.exit(0)\n \n if args.target_prediction_model==\"MLP\":\n self.layer_pre_head = nn.Sequential(\n nn.Linear(target_pred_input_dim, target_pred_input_dim),\n nn.Dropout(self.args.dropout),\n nn.ReLU()\n )\n elif args.target_prediction_model==\"ConvBERT\":\n configuration = ConvBertConfig(\n hidden_size = self.args.embed_dim,\n num_attention_heads = self.args.attention_heads if self.args.attention_heads is not None else 4,\n conv_kernel_size = self.args.conv_kernel_size,\n hidden_act = \"gelu\",\n hidden_dropout_prob = self.args.dropout,\n attention_probs_dropout_prob = self.args.dropout\n )\n self.layer_pre_head = ConvBertLayer(configuration)\n elif args.target_prediction_model==\"CNN\":\n self.layer_pre_head = nn.Sequential(\n nn.Conv1d(in_channels=target_pred_input_dim, out_channels=target_pred_input_dim, kernel_size = self.args.conv_kernel_size, padding='same'),\n nn.Dropout(self.args.dropout),\n nn.ReLU()\n )\n target_pred_input_dim = target_pred_input_dim if self.args.target_prediction_head != \"One_hot_encoding\" else target_pred_input_dim * (self.args.seq_len + 1)\n elif args.target_prediction_model==\"light_attention\":\n # Adapted from Stark et al (https://github.com/HannesStark/protein-localization)\n self.feature_convolution = nn.Conv1d(self.args.embed_dim, self.args.embed_dim, self.args.conv_kernel_size, stride=1, padding='same')\n self.attention_convolution = nn.Conv1d(self.args.embed_dim, self.args.embed_dim, self.args.conv_kernel_size, stride=1, padding='same')\n self.softmax = nn.Softmax(dim=-1)\n self.dropout = nn.Dropout(self.args.dropout)\n self.linear = nn.Sequential(\n nn.Linear(2 * self.args.embed_dim, 32),\n nn.Dropout(self.args.dropout),\n nn.ReLU(),\n nn.BatchNorm1d(32)\n )\n target_pred_input_dim = 32\n elif args.target_prediction_model==\"linear\":\n pass\n else:\n print(\"Error: Specified layer_pre_head invalid\")\n sys.exit(0)\n\n if self.args.augmentation==\"zero_shot_fitness_predictions_covariate\":\n self.zero_shot_fitness_prediction_weight = nn.ModuleDict(\n { \n target_name: nn.Linear(1, self.args.target_config[target_name][\"dim\"], bias=False)\n for target_name in self.target_names\n }\n )\n for target_name in self.target_names:\n torch.nn.init.constant_(self.zero_shot_fitness_prediction_weight[target_name].weight,1.0)\n\n self.target_pred_head = nn.ModuleDict(\n { \n target_name: nn.Linear(target_pred_input_dim, self.args.target_config[target_name][\"dim\"])\n for target_name in self.target_names #If multiple targets, we learn a separate linear head for each separately\n }\n )\n \n def set_device(self):\n if self.device is None:\n self.device = next(self.parameters()).device\n print(\"Model device: {}\".format(self.device))\n\n def forward(self, tokens, zero_shot_fitness_predictions=None, sequence_embeddings=None, repr_layers=[]):\n if self.args.aa_embeddings == \"MSA_Transformer\" and self.args.sequence_embeddings_location is None:\n assert tokens.ndim == 3, \"Finding dimension of tokens to be: {}\".format(tokens.ndim)\n num_MSAs_in_batch, num_sequences_in_alignments, seqlen = tokens.size()\n batch_size = num_MSAs_in_batch\n else:\n assert tokens.ndim == 2, \"Finding dimension of tokens to be: {}\".format(tokens.ndim)\n batch_size, seqlen = tokens.size()\n \n if sequence_embeddings is not None:\n x = sequence_embeddings.to(self.device)\n else:\n if self.args.aa_embeddings == \"MSA_Transformer\":\n output = self.aa_embedding(tokens, repr_layers=[12])\n x = output[\"representations\"][12][:] # B, N, L, D\n x = x[:,0,:,:] #In each MSA batch the first sequence is what we care about. The other MSA sequences were just to compute embeddings and logits\n elif self.args.aa_embeddings == \"ESM1v\":\n last_layer_index = 33\n output = self.aa_embedding(tokens, repr_layers=[last_layer_index])\n x = output[\"representations\"][last_layer_index][:] # N, L, D\n elif self.args.aa_embeddings == \"Tranception\":\n processed_batch = {'input_ids': tokens, 'labels': tokens}\n output = self.aa_embedding(**processed_batch, return_dict=True, output_hidden_states=True)\n x = output.hidden_states[0]\n elif self.args.aa_embeddings ==\"Linear_embedding\":\n x = self.aa_embedding(tokens)\n elif self.args.aa_embeddings == \"One_hot_encoding\":\n x = nn.functional.one_hot(tokens, num_classes=self.alphabet_size).view(batch_size,-1).float()\n if self.args.target_prediction_model == \"CNN\": x = x.view(batch_size,seqlen,self.alphabet_size)\n\n if self.args.aa_embeddings != \"One_hot_encoding\":\n x = self.emb_layer_norm_after(x)\n x = self.dropout_module(x)\n \n repr_layers = set(repr_layers)\n hidden_representations = {}\n if 0 in repr_layers:\n hidden_representations[0] = x\n\n if self.args.target_prediction_model == \"CNN\": \n assert len(x.size())==3, \"Size error input\"\n N, L, D = x.size()\n x = x.permute(0,2,1) #N, D, L\n x = self.layer_pre_head(x)\n x = x.permute(0,2,1)\n elif self.args.target_prediction_model == \"ConvBERT\":\n x = self.layer_pre_head(x)[0]\n elif self.args.target_prediction_model==\"light_attention\":\n x = x.permute(0,2,1) #N, D, L\n o = self.feature_convolution(x) \n o = self.dropout(o)\n attention = self.attention_convolution(x)\n o1 = torch.sum(o * self.softmax(attention), dim=-1)\n o2, _ = torch.max(o, dim=-1)\n o = torch.cat([o1, o2], dim=-1)\n x = self.linear(o)\n \n if self.args.target_prediction_head == \"AA_embeddings_mean_pooled\": x = x.mean(dim=-2)\n \n if self.args.target_prediction_model == \"MLP\": x = self.layer_pre_head(x)\n \n target_predictions = {}\n for target_name in self.target_names:\n target_predictions[target_name] = self.target_pred_head[target_name](x).view(-1)\n if self.args.augmentation==\"zero_shot_fitness_predictions_covariate\":\n target_predictions[target_name] += self.zero_shot_fitness_prediction_weight[target_name](zero_shot_fitness_predictions).squeeze()\n\n result = {\"target_predictions\": target_predictions, \"representations\": hidden_representations}\n \n return result\n \n def forward_with_uncertainty(self, tokens, zero_shot_fitness_predictions=None, sequence_embeddings=None, num_MC_dropout_samples=10):\n \"\"\"\n Performs MC dropout to compute predictions and the corresponding uncertainties.\n Assumes 1D predictions (eg., prediction of continuous output).\n \"\"\"\n self.eval() \n for m in self.modules(): #Move all dropout layers in train mode to support MC dropout. Keep everything else in eval mode.\n if m.__class__.__name__.startswith('Dropout'):\n m.train()\n with torch.no_grad(): \n predictions_dict = defaultdict(list)\n for _ in range(num_MC_dropout_samples):\n target_predictions_sample = self.forward(tokens, zero_shot_fitness_predictions=zero_shot_fitness_predictions, sequence_embeddings=sequence_embeddings)[\"target_predictions\"]\n for target_name in self.target_names:\n predictions_dict[target_name].append(target_predictions_sample[target_name])\n results_with_uncertainty={}\n for target_name in self.target_names:\n concatenated_target_pred = torch.cat([x.view(-1,1) for x in predictions_dict[target_name]],dim=-1)\n results_with_uncertainty[target_name] = {}\n results_with_uncertainty[target_name]['predictions_avg'] = concatenated_target_pred.mean(dim=-1)\n results_with_uncertainty[target_name]['uncertainty'] = concatenated_target_pred.std(dim=-1)\n return results_with_uncertainty\n\n @property\n def num_layers(self):\n return self.args.num_protein_npt_layers\n \n def max_tokens_per_msa_(self, value: int) -> None:\n \"\"\"\n Batching attention computations when gradients are disabled as per MSA_Transformer\n Set this value to infinity to disable this behavior.\n \"\"\"\n for module in self.modules():\n if isinstance(module, (RowSelfAttention, ColumnSelfAttention)):\n module.max_tokens_per_msa = value\n\n def prediction_loss(self, target_predictions, target_labels, label_smoothing=0.1):\n total_target_prediction_loss = 0.0\n target_prediction_loss_dict = {}\n for target_name in self.target_names:\n non_missing_target_indicator = ~torch.isnan(target_labels[target_name])\n if self.args.target_config[target_name][\"type\"]==\"continuous\":\n tgt_loss = MSELoss(reduction=\"sum\")(target_predictions[target_name][non_missing_target_indicator], target_labels[target_name][non_missing_target_indicator])\n else:\n tgt_loss = CrossEntropyLoss(reduction=\"none\",label_smoothing=label_smoothing)(target_predictions[target_name].view(-1, self.args.target_config[target_name][\"dim\"]), target_labels[target_name].view(-1))\n target_prediction_loss_dict[target_name] = tgt_loss\n total_target_prediction_loss += tgt_loss\n return total_target_prediction_loss, target_prediction_loss_dict\n\n def create_optimizer(self):\n \"\"\"\n Setup the optimizer.\n We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the\n Trainer's init through `optimizers`, or subclass and override this method in a subclass.\n Adapted from Huggingface Transformers library.\n \"\"\"\n all_parameters = utils.model_utils.get_parameter_names(self, [nn.LayerNorm])\n decay_parameters = [name for name in all_parameters if (\"bias\" not in name and \"pseudo_likelihood_weight\" not in name and 'zero_shot_fitness_prediction_weight' not in name)]\n psl_decay_parameters = [name for name in all_parameters if (\"bias\" not in name and (\"pseudo_likelihood_weight\" in name or \"zero_shot_fitness_prediction_weight\" in name))]\n optimizer_grouped_parameters = [\n {\n \"params\": [p for n, p in self.named_parameters() if n in decay_parameters],\n \"weight_decay\": self.args.weight_decay,\n },\n {\n \"params\": [p for n, p in self.named_parameters() if n in psl_decay_parameters],\n \"weight_decay\": 1e-8, #Small decay on pseudo-likelihood as in Hsu et al.\n },\n {\n \"params\": [p for n, p in self.named_parameters() if (n not in decay_parameters and n not in psl_decay_parameters)],\n \"weight_decay\": 0.0,\n },\n ] \n optimizer_kwargs = {\n \"betas\": (self.args.adam_beta1, self.args.adam_beta2),\n \"eps\": self.args.adam_epsilon,\n \"lr\": self.args.max_learning_rate\n }\n optimizer = AdamW(optimizer_grouped_parameters, **optimizer_kwargs)\n return optimizer" }, { "identifier": "Alphabet", "path": "utils/esm/data.py", "snippet": "class Alphabet(object):\n def __init__(\n self,\n standard_toks: Sequence[str],\n prepend_toks: Sequence[str] = (\"<null_0>\", \"<pad>\", \"<eos>\", \"<unk>\"),\n append_toks: Sequence[str] = (\"<cls>\", \"<mask>\", \"<sep>\"),\n prepend_bos: bool = True,\n append_eos: bool = False,\n use_msa: bool = False,\n ):\n #ESM Alphabet: {'<cls>': 0, '<pad>': 1, '<eos>': 2, '<unk>': 3, 'L': 4, 'A': 5, 'G': 6, 'V': 7, 'S': 8, 'E': 9, 'R': 10, 'T': 11, 'I': 12, 'D': 13, 'P': 14, 'K': 15, 'Q': 16, 'N': 17, 'F': 18, 'Y': 19, 'M': 20, 'H': 21, 'W': 22, 'C': 23, 'X': 24, 'B': 25, 'U': 26, 'Z': 27, 'O': 28, '.': 29, '-': 30, '<null_1>': 31, '<mask>': 32}\n self.standard_toks = list(standard_toks)\n self.prepend_toks = list(prepend_toks)\n self.append_toks = list(append_toks)\n self.prepend_bos = prepend_bos\n self.append_eos = append_eos\n self.use_msa = use_msa\n\n self.all_toks = list(self.prepend_toks)\n self.all_toks.extend(self.standard_toks)\n for i in range((8 - (len(self.all_toks) % 8)) % 8):\n self.all_toks.append(f\"<null_{i + 1}>\")\n self.all_toks.extend(self.append_toks)\n\n self.tok_to_idx = {tok: i for i, tok in enumerate(self.all_toks)}\n\n self.unk_idx = self.tok_to_idx[\"<unk>\"]\n self.padding_idx = self.get_idx(\"<pad>\")\n self.cls_idx = self.get_idx(\"<cls>\")\n self.mask_idx = self.get_idx(\"<mask>\")\n self.eos_idx = self.get_idx(\"<eos>\")\n self.all_special_tokens = ['<eos>', '<unk>', '<pad>', '<cls>', '<mask>']\n self.unique_no_split_tokens = self.all_toks\n\n def __len__(self):\n return len(self.all_toks)\n\n def get_idx(self, tok):\n return self.tok_to_idx.get(tok, self.unk_idx)\n\n def get_tok(self, ind):\n return self.all_toks[ind]\n\n def to_dict(self):\n return self.tok_to_idx.copy()\n\n def get_batch_converter(self, truncation_seq_length: int = None):\n if self.use_msa:\n return MSABatchConverter(self, truncation_seq_length)\n else:\n return BatchConverter(self, truncation_seq_length)\n\n @classmethod\n def from_architecture(cls, name: str) -> \"Alphabet\":\n if name in (\"ESM-1\", \"protein_bert_base\"):\n standard_toks = proteinseq_toks[\"toks\"]\n prepend_toks: Tuple[str, ...] = (\"<null_0>\", \"<pad>\", \"<eos>\", \"<unk>\")\n append_toks: Tuple[str, ...] = (\"<cls>\", \"<mask>\", \"<sep>\")\n prepend_bos = True\n append_eos = False\n use_msa = False\n elif name in (\"ESM-1b\", \"roberta_large\"):\n standard_toks = proteinseq_toks[\"toks\"]\n prepend_toks = (\"<cls>\", \"<pad>\", \"<eos>\", \"<unk>\")\n append_toks = (\"<mask>\",)\n prepend_bos = True\n append_eos = True\n use_msa = False\n elif name in (\"MSA Transformer\", \"msa_transformer\"):\n standard_toks = proteinseq_toks[\"toks\"]\n prepend_toks = (\"<cls>\", \"<pad>\", \"<eos>\", \"<unk>\")\n append_toks = (\"<mask>\",)\n prepend_bos = True\n append_eos = False\n use_msa = True\n elif \"invariant_gvp\" in name.lower():\n standard_toks = proteinseq_toks[\"toks\"]\n prepend_toks = (\"<null_0>\", \"<pad>\", \"<eos>\", \"<unk>\")\n append_toks = (\"<mask>\", \"<cath>\", \"<af2>\")\n prepend_bos = True\n append_eos = False\n use_msa = False\n else:\n raise ValueError(\"Unknown architecture selected\")\n return cls(standard_toks, prepend_toks, append_toks, prepend_bos, append_eos, use_msa)\n\n def _tokenize(self, text) -> str:\n return text.split()\n\n def tokenize(self, text, **kwargs) -> List[str]:\n \"\"\"\n Inspired by https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils.py\n Converts a string in a sequence of tokens, using the tokenizer.\n\n Args:\n text (:obj:`str`):\n The sequence to be encoded.\n\n Returns:\n :obj:`List[str]`: The list of tokens.\n \"\"\"\n\n def split_on_token(tok, text):\n result = []\n split_text = text.split(tok)\n for i, sub_text in enumerate(split_text):\n # AddedToken can control whitespace stripping around them.\n # We use them for GPT2 and Roberta to have different behavior depending on the special token\n # Cf. https://github.com/huggingface/transformers/pull/2778\n # and https://github.com/huggingface/transformers/issues/3788\n # We strip left and right by default\n if i < len(split_text) - 1:\n sub_text = sub_text.rstrip()\n if i > 0:\n sub_text = sub_text.lstrip()\n\n if i == 0 and not sub_text:\n result.append(tok)\n elif i == len(split_text) - 1:\n if sub_text:\n result.append(sub_text)\n else:\n pass\n else:\n if sub_text:\n result.append(sub_text)\n result.append(tok)\n return result\n\n def split_on_tokens(tok_list, text):\n if not text.strip():\n return []\n\n tokenized_text = []\n text_list = [text]\n for tok in tok_list:\n tokenized_text = []\n for sub_text in text_list:\n if sub_text not in self.unique_no_split_tokens:\n tokenized_text.extend(split_on_token(tok, sub_text))\n else:\n tokenized_text.append(sub_text)\n text_list = tokenized_text\n\n return list(\n itertools.chain.from_iterable(\n (\n self._tokenize(token)\n if token not in self.unique_no_split_tokens\n else [token]\n for token in tokenized_text\n )\n )\n )\n\n no_split_token = self.unique_no_split_tokens\n tokenized_text = split_on_tokens(no_split_token, text)\n return tokenized_text\n\n def encode(self, text):\n return [self.tok_to_idx[tok] for tok in self.tokenize(text)]" }, { "identifier": "get_tranception_tokenizer", "path": "utils/tranception/model_pytorch.py", "snippet": "def get_tranception_tokenizer():\n #Tranception Alphabet: \"vocab\":{\"[UNK]\":0,\"[CLS]\":1,\"[SEP]\":2,\"[PAD]\":3,\"[MASK]\":4,\"A\":5,\"C\":6,\"D\":7,\"E\":8,\"F\":9,\"G\":10,\"H\":11,\"I\":12,\"K\":13,\"L\":14,\"M\":15,\"N\":16,\"P\":17,\"Q\":18,\"R\":19,\"S\":20,\"T\":21,\"V\":22,\"W\":23,\"Y\":24}\n dir_path = os.path.dirname(os.path.abspath(__file__))\n tokenizer = PreTrainedTokenizerFast(tokenizer_file=dir_path + os.sep + \"utils/tokenizers/Basic_tokenizer\", unk_token=\"[UNK]\", sep_token=\"[SEP]\", pad_token=\"[PAD]\", cls_token=\"[CLS]\",mask_token=\"[MASK]\")\n os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n tokenizer.tok_to_idx = tokenizer.vocab\n tokenizer.padding_idx = tokenizer.tok_to_idx[\"[PAD]\"]\n tokenizer.mask_idx = tokenizer.tok_to_idx[\"[MASK]\"]\n tokenizer.cls_idx = tokenizer.tok_to_idx[\"[CLS]\"]\n tokenizer.eos_idx = tokenizer.tok_to_idx[\"[SEP]\"]\n tokenizer.prepend_bos = True\n tokenizer.append_eos = True\n return tokenizer" }, { "identifier": "get_train_val_test_data", "path": "utils/data_utils.py", "snippet": "def get_train_val_test_data(args, assay_file_names):\n target_names = args.target_config.keys() \n assay_data={}\n merge = None\n main_target_name = None\n main_target_name_count = 0\n for target in target_names:\n if args.target_config[target][\"main_target\"]: \n main_target_name=target\n main_target_name_count+=1\n assert main_target_name is not None, \"No main target referenced. Please update config to select a unique main target.\"\n assert main_target_name_count <= 1, \"Several main targets referenced. Please update config to select a unique main target.\"\n \n assay_data[main_target_name] = pd.read_csv(args.target_config[main_target_name][\"location\"] + os.sep + assay_file_names[main_target_name])[['mutant','mutated_sequence',args.target_config[main_target_name][\"var_name\"],args.fold_variable_name]] \n assay_data[main_target_name].columns = ['mutant','mutated_sequence', main_target_name, args.fold_variable_name]\n merge = assay_data[main_target_name]\n \n for target_name in target_names:\n if target_name!=main_target_name:\n print(target_name)\n print(args.target_config)\n print(assay_file_names)\n assay_data[target_name] = pd.read_csv(args.target_config[target_name][\"location\"] + os.sep + assay_file_names[target_name])[['mutant',args.target_config[target_name][\"var_name\"]]] \n assay_data[target_name].columns = ['mutant',target_name]\n merge = pd.merge(merge, assay_data[target_name], how='left', on='mutant')\n \n if args.augmentation==\"zero_shot_fitness_predictions_covariate\":\n zero_shot_fitness_predictions = pd.read_csv(args.zero_shot_fitness_predictions_location + os.sep + assay_file_names[main_target_name])[['mutant',args.zero_shot_fitness_predictions_var_name]]\n zero_shot_fitness_predictions.columns = ['mutant','zero_shot_fitness_predictions']\n zero_shot_fitness_predictions['zero_shot_fitness_predictions'] = standardize(zero_shot_fitness_predictions['zero_shot_fitness_predictions'])\n merge = pd.merge(merge,zero_shot_fitness_predictions,how='inner',on='mutant')\n\n train_val_test_splits = split_data_based_on_test_fold_index(\n dataframe = merge, \n fold_variable_name = args.fold_variable_name,\n test_fold_index = args.test_fold_index,\n use_validation_set = args.use_validation_set\n )\n splits_dict = {}\n for split_name, split in zip(['train','val','test'], train_val_test_splits):\n if split_name=='val' and not args.use_validation_set: continue\n splits_dict[split_name] = {}\n splits_dict[split_name]['mutant_mutated_seq_pairs'] = list(zip(list(split['mutant']),list(split['mutated_sequence'])))\n raw_targets = {target_name: split[target_name] for target_name in target_names}\n if args.augmentation==\"zero_shot_fitness_predictions_covariate\": raw_targets['zero_shot_fitness_predictions'] = split['zero_shot_fitness_predictions']\n if split_name==\"train\":\n raw_targets, target_processing = preprocess_training_targets(raw_targets, args.target_config)\n else:\n raw_targets = preprocess_test_targets(raw_targets, args.target_config, target_processing)\n for target_name in target_names: \n splits_dict[split_name][target_name] = raw_targets[target_name]\n if args.augmentation==\"zero_shot_fitness_predictions_covariate\": splits_dict[split_name]['zero_shot_fitness_predictions'] = raw_targets['zero_shot_fitness_predictions']\n # load dict into dataset objects\n train_data = Dataset.from_dict(splits_dict['train'])\n val_data = Dataset.from_dict(splits_dict['val']) if args.use_validation_set else None\n test_data = Dataset.from_dict(splits_dict['test'])\n return train_data, val_data, test_data, target_processing" }, { "identifier": "standardize", "path": "utils/data_utils.py", "snippet": "def standardize(x):\n return (x - x.mean()) / x.std()" }, { "identifier": "pnpt_count_non_nan", "path": "utils/data_utils.py", "snippet": "def pnpt_count_non_nan(x):\n missing_mask = np.isnan(x) | np.equal(x,-100)\n return np.count_nonzero(~missing_mask)" }, { "identifier": "pnpt_spearmanr", "path": "utils/data_utils.py", "snippet": "def pnpt_spearmanr(prediction,target):\n mask_missing_values = np.isnan(target) | np.equal(target, -100) #In PNPT missing values are never masked so corresponding labels are always set to -100\n return spearmanr(prediction[~mask_missing_values], target[~mask_missing_values])[0] #first value is spearman rho, second is the corresponding p-value " }, { "identifier": "process_MSA", "path": "utils/msa_utils.py", "snippet": "def process_MSA(args, MSA_filename, MSA_weights_filename):\n filtered_MSA_filename = filter_msa(filename = args.MSA_data_folder + os.sep + MSA_filename, path_to_hhfilter = args.path_to_hhfilter)\n MSA_all_sequences, MSA_non_ref_sequences_weights = compute_sequence_weights(MSA_filename = filtered_MSA_filename, MSA_weights_filename = args.MSA_weight_data_folder + os.sep + MSA_weights_filename)\n return MSA_all_sequences, MSA_non_ref_sequences_weights" }, { "identifier": "Trainer", "path": "utils/model_utils.py", "snippet": "class Trainer():\n def __init__(self, \n model,\n args,\n train_data, \n val_data,\n MSA_sequences, \n MSA_weights,\n MSA_start_position,\n MSA_end_position,\n target_processing,\n distributed_training=False\n ):\n self.model = model\n self.args = args\n self.train_data = train_data\n self.val_data = val_data\n self.MSA_sequences = MSA_sequences\n self.MSA_weights = MSA_weights\n self.MSA_start_position = MSA_start_position\n self.MSA_end_position = MSA_end_position\n self.target_processing = target_processing\n self.distributed_training = distributed_training\n \n def train(self):\n \"\"\"\n Returns the last value of training_step (useful in case of early stopping for isntance)\n \"\"\"\n \n self.model.train()\n self.model.cuda()\n self.model.set_device()\n\n if self.distributed_training:\n self.model = torch.nn.parallel.DistributedDataParallel(self.model)\n train_sampler = torch.utils.data.distributed.DistributedSampler(self.train_data)\n else:\n train_sampler = None\n \n #To ensure reproducibility with seed setting\n def seed_worker(worker_id):\n worker_seed = torch.initial_seed() % 2**32\n np.random.seed(worker_seed)\n random.seed(worker_seed)\n g = torch.Generator()\n g.manual_seed(0)\n train_loader = torch.utils.data.DataLoader(\n dataset=self.train_data, \n batch_size=self.args.training_num_assay_sequences_per_batch_per_gpu, \n shuffle=(train_sampler is None),\n num_workers=self.args.num_data_loaders_workers, \n pin_memory=True, \n sampler=train_sampler,\n collate_fn=collate_fn_protein_npt,\n worker_init_fn=seed_worker,\n generator=g,\n )\n optimizer = self.model.create_optimizer()\n scheduler = learning_rate_scheduler(\n num_warmup_steps=self.args.num_warmup_steps, \n num_total_training_steps=self.args.num_total_training_steps, \n max_learning_rate=self.args.max_learning_rate, \n min_learning_rate=self.args.min_learning_rate\n )\n \n train_iterator = iter(train_loader)\n num_epochs = 0\n prior_log_time = time.time()\n total_train_time = 0\n log_train_total_loss = 0\n if self.model.model_type==\"ProteinNPT\":\n log_train_reconstruction_loss = 0\n log_train_num_masked_tokens = 0\n log_train_num_target_masked_tokens_dict = defaultdict(int)\n else:\n log_num_sequences_predicted = 0\n log_train_target_prediction_loss_dict = defaultdict(int)\n all_spearmans_eval_during_training = []\n max_average_spearman_across_targets = - math.inf\n if self.args.training_fp16: scaler = torch.cuda.amp.GradScaler()\n\n for training_step in tqdm.tqdm(range(1, self.args.num_total_training_steps+1)):\n optimizer.zero_grad(set_to_none=True)\n lr = scheduler(training_step)\n update_lr_optimizer(optimizer, lr)\n reconstruction_loss_coeff = get_reconstruction_loss_coefficient(training_step, num_total_training_steps=self.args.num_total_training_steps) if (self.model.model_type==\"ProteinNPT\" and not self.model.PNPT_no_reconstruction_error) else 0\n for gradient_accum_step in range(self.args.gradient_accumulation):\n try:\n batch = next(train_iterator)\n except:\n num_epochs +=1\n train_iterator = iter(train_loader)\n batch = next(train_iterator)\n \n if self.model.model_type==\"ProteinNPT\":\n processed_batch = proteinnpt.data_processing.process_batch(\n batch = batch,\n model = self.model,\n alphabet = self.model.alphabet, \n args = self.args, \n MSA_sequences = self.MSA_sequences, \n MSA_weights = self.MSA_weights,\n MSA_start_position = self.MSA_start_position, \n MSA_end_position = self.MSA_end_position,\n target_processing = self.target_processing,\n training_sequences = None,\n proba_target_mask = 0.15,\n proba_aa_mask = 0.15,\n eval_mode = False,\n device=self.model.device,\n indel_mode=self.args.indel_mode\n )\n else:\n processed_batch = baselines.data_processing.process_batch(\n batch = batch,\n model = self.model,\n alphabet = self.model.alphabet, \n args = self.args, \n MSA_sequences = self.MSA_sequences, \n MSA_weights = self.MSA_weights,\n MSA_start_position = self.MSA_start_position, \n MSA_end_position = self.MSA_end_position,\n device=self.model.device,\n eval_mode=False,\n indel_mode=self.args.indel_mode\n )\n\n if self.args.augmentation==\"zero_shot_fitness_predictions_covariate\":\n zero_shot_fitness_predictions = processed_batch['target_labels']['zero_shot_fitness_predictions'].view(-1,1)\n del processed_batch['target_labels']['zero_shot_fitness_predictions']\n else:\n zero_shot_fitness_predictions = None\n \n if self.args.training_fp16:\n with torch.cuda.amp.autocast():\n if self.model.model_type==\"ProteinNPT\":\n output = self.model(\n tokens=processed_batch['masked_tokens'],\n targets=processed_batch['masked_targets'],\n zero_shot_fitness_predictions=zero_shot_fitness_predictions,\n sequence_embeddings=processed_batch['sequence_embeddings']\n )\n total_loss, reconstruction_loss, target_prediction_loss_dict = self.model.protein_npt_loss(\n token_predictions_logits=output['logits_protein_sequence'], \n token_labels=processed_batch['token_labels'], \n target_predictions=output['target_predictions'], \n target_labels=processed_batch['target_labels'], \n MLM_reconstruction_loss_weight=reconstruction_loss_coeff, \n label_smoothing=self.args.label_smoothing\n )\n else:\n output = self.model(\n tokens=processed_batch['input_tokens'],\n zero_shot_fitness_predictions=zero_shot_fitness_predictions,\n sequence_embeddings=processed_batch['sequence_embeddings']\n )\n total_loss, target_prediction_loss_dict = self.model.prediction_loss(\n target_predictions=output[\"target_predictions\"], \n target_labels=processed_batch['target_labels'],\n label_smoothing=self.args.label_smoothing\n )\n scaler.scale(total_loss).backward()\n else:\n if self.model.model_type==\"ProteinNPT\":\n output = self.model(\n tokens=processed_batch['masked_tokens'],\n targets=processed_batch['masked_targets'],\n zero_shot_fitness_predictions=zero_shot_fitness_predictions,\n sequence_embeddings=processed_batch['sequence_embeddings']\n )\n total_loss, reconstruction_loss, target_prediction_loss_dict = self.model.protein_npt_loss(\n token_predictions_logits=output['logits_protein_sequence'], \n token_labels=processed_batch['token_labels'], \n target_predictions=output['target_predictions'], \n target_labels=processed_batch['target_labels'], \n MLM_reconstruction_loss_weight=reconstruction_loss_coeff, \n label_smoothing=self.args.label_smoothing\n )\n if total_loss.item() > 10.0 and training_step >= 100:\n print(\"High training loss detected: {}\".format(total_loss.item()))\n else:\n output = self.model(\n tokens=processed_batch['input_tokens'],\n zero_shot_fitness_predictions=zero_shot_fitness_predictions,\n sequence_embeddings=processed_batch['sequence_embeddings']\n )\n total_loss, target_prediction_loss_dict = self.model.prediction_loss(\n target_predictions=output[\"target_predictions\"], \n target_labels=processed_batch['target_labels'],\n label_smoothing=self.args.label_smoothing\n )\n total_loss.backward()\n torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.args.grad_norm_clip)\n # Taking optimizer update out of the inner loop to support gradient accumulation\n if self.args.training_fp16:\n with torch.cuda.amp.autocast():\n scaler.step(optimizer)\n scaler.update()\n else:\n optimizer.step()\n\n log_train_total_loss += total_loss\n for target_name in self.model.target_names:\n log_train_target_prediction_loss_dict[target_name] += target_prediction_loss_dict[target_name]\n if self.model.model_type==\"ProteinNPT\": \n log_train_reconstruction_loss += reconstruction_loss\n log_train_num_masked_tokens += processed_batch['masked_tokens'].eq(self.model.alphabet.mask_idx).sum()\n for target_name in self.model.target_names:\n log_train_num_target_masked_tokens_dict[target_name] += processed_batch['masked_targets'][target_name][:,-1].eq(1.0).sum().item() # Masked targets are encoded by 1.0. Mask column is the very last one\n else:\n log_num_sequences_predicted += len(batch['mutant_mutated_seq_pairs'])\n \n if training_step % self.args.num_logging_training_steps == 0 and self.args.use_wandb:\n time_end_step = time.time()\n delta_time_since_last_log = time_end_step - prior_log_time\n total_train_time += delta_time_since_last_log\n prior_log_time = time_end_step\n train_logs = {\n \"training_step\": training_step, \n \"step_time\": delta_time_since_last_log / (self.args.num_logging_training_steps)\n }\n if self.model.model_type==\"ProteinNPT\": \n train_logs[\"train_total_loss_per_step\"]: log_train_total_loss / self.args.num_logging_training_steps\n train_logs[\"train_reconstruction_loss_per_masked_token\"] = log_train_reconstruction_loss / log_train_num_masked_tokens\n for target_name in self.model.target_names:\n train_logs[\"train_prediction_\"+str(target_name)+\"_loss_per_masked_token\"] = log_train_target_prediction_loss_dict[target_name] / log_train_num_target_masked_tokens_dict[target_name]\n else:\n train_logs[\"train_total_loss_per_seq\"]: log_train_total_loss / log_num_sequences_predicted\n for target_name in self.model.target_names:\n train_logs[\"train_prediction_\"+str(target_name)+\"_loss_per_seq\"] = log_train_target_prediction_loss_dict[target_name] / log_num_sequences_predicted\n wandb.log(train_logs)\n log_train_total_loss = 0\n log_train_target_prediction_loss_dict = defaultdict(int)\n if self.model.model_type==\"ProteinNPT\":\n log_train_reconstruction_loss = 0\n log_train_num_masked_tokens = 0\n log_train_num_target_masked_tokens_dict = defaultdict(int)\n else:\n log_num_sequences_predicted = 0 \n \n if self.args.save_model_checkpoint and (training_step % self.args.num_saving_training_steps) == 0:\n if not os.path.exists(self.args.model_location): os.mkdir(self.args.model_location)\n if not os.path.exists(self.args.model_location + os.sep + 'checkpoint-'+str(training_step)): os.mkdir(self.args.model_location + os.sep + 'checkpoint-'+str(training_step))\n torch.save({\n 'training_step': training_step,\n 'args': self.args,\n 'state_dict': self.model.state_dict(),\n 'optimizer' : optimizer.state_dict()\n }, \n self.args.model_location + os.sep + 'checkpoint-'+str(training_step) + os.sep + 'checkpoint.t7'\n )\n \n if training_step % self.args.num_eval_steps == 0 and self.args.use_validation_set:\n if self.model.model_type==\"ProteinNPT\":\n eval_results = self.eval(\n test_data=self.val_data,\n train_data=self.train_data,\n reconstruction_loss_weight=0.0,\n output_all_predictions=True\n )\n else:\n eval_results = self.eval(\n test_data=self.val_data, \n output_all_predictions=True\n )\n eval_logs = {\"Training step\": training_step} \n if self.model.model_type==\"ProteinNPT\":\n normalization = 0\n for target_name in self.model.target_names: normalization += eval_results['eval_num_masked_targets'][target_name]\n else:\n normalization = eval_results['eval_num_predicted_targets']\n eval_logs['Eval total loss per seq.']: eval_results['eval_total_loss'] / normalization\n average_spearman_across_targets = 0 #If early stopping based on validation spearman and multiple targets, we check that avg spearman is not decreasing for a certain # of times in a row\n for target_name in self.model.target_names:\n if self.model.model_type==\"ProteinNPT\": normalization = eval_results['eval_num_masked_targets'][target_name] #Update for PNPT (keeep the same normalization constant otherwise)\n eval_logs['Eval loss '+str(target_name)+' per seq.'] = eval_results['eval_target_prediction_loss_dict'][target_name] / normalization\n eval_logs['Eval spearman '+target_name] = spearmanr(eval_results['output_scores']['predictions_'+target_name], eval_results['output_scores']['labels_'+target_name])[0]\n average_spearman_across_targets += eval_logs['Eval spearman '+target_name]\n average_spearman_across_targets /= len(self.model.target_names)\n print(\" | \".join([key + \": \"+str(round(eval_logs[key],5)) for key in eval_logs.keys()]))\n if self.args.use_wandb: wandb.log(eval_logs)\n # Early stopping\n all_spearmans_eval_during_training.append(average_spearman_across_targets)\n if average_spearman_across_targets > max_average_spearman_across_targets: max_average_spearman_across_targets = average_spearman_across_targets\n if (training_step >= 1000) and (self.args.early_stopping_patience is not None) and (np.array(all_spearmans_eval_during_training)[-self.args.early_stopping_patience:].max() < max_average_spearman_across_targets):\n print(\"Early stopping. Training step: {}. Total eval loss: {}. Avg spearman: {}\".format(training_step, eval_results['eval_total_loss'], average_spearman_across_targets))\n break\n self.model.train() #Move back the model to train mode after eval loop\n trainer_final_status = {\n 'total_training_steps': training_step,\n 'total_train_time': total_train_time,\n 'total_training_epochs': num_epochs\n }\n return trainer_final_status\n\n def eval(self, test_data, output_all_predictions=False, need_head_weights=False, train_data = None, reconstruction_loss_weight=0.5, selected_indices_seed=0):\n \"\"\"\n total_eval_target_prediction_loss is the sum of all target prediction losses across all targets\n total_eval_target_prediction_loss contains the breakdown by target\n num_predicted_targets has the number of predicted items\n output_scores is a dict with sequences, predictions and labels\n \"\"\"\n self.model.eval()\n self.model.cuda()\n self.model.set_device()\n with torch.no_grad():\n eval_loader = torch.utils.data.DataLoader(\n dataset=test_data, \n batch_size=self.args.eval_num_sequences_to_score_per_batch_per_gpu, \n shuffle=False,\n num_workers=self.args.num_data_loaders_workers, \n pin_memory=True,\n collate_fn=collate_fn_protein_npt\n )\n eval_iterator = iter(eval_loader)\n \n eval_total_loss = 0\n if self.model.model_type==\"ProteinNPT\": \n eval_reconstruction_loss = 0\n eval_num_masked_tokens = 0\n eval_num_masked_targets = defaultdict(int)\n else:\n num_predicted_targets = 0\n eval_target_prediction_loss_dict = defaultdict(int)\n output_scores = defaultdict(list) if output_all_predictions else None\n\n if need_head_weights:\n col_attentions=[]\n row_attentions=[]\n\n for batch in tqdm.tqdm(eval_iterator):\n if output_all_predictions: \n output_scores['mutated_sequence'] += list(zip(*batch['mutant_mutated_seq_pairs']))[1]\n output_scores['mutant'] += list(zip(*batch['mutant_mutated_seq_pairs']))[0]\n if self.model.model_type==\"ProteinNPT\":\n processed_batch = proteinnpt.data_processing.process_batch(\n batch = batch,\n model = self.model,\n alphabet = self.model.alphabet, \n args = self.args, \n MSA_sequences = self.MSA_sequences, \n MSA_weights = self.MSA_weights,\n MSA_start_position = self.MSA_start_position, \n MSA_end_position = self.MSA_end_position,\n target_processing = self.target_processing,\n training_sequences = train_data,\n proba_target_mask = 1.0, \n proba_aa_mask = 0.0,\n eval_mode = True,\n device=self.model.device,\n selected_indices_seed=selected_indices_seed,\n indel_mode=self.args.indel_mode\n )\n else:\n processed_batch = baselines.data_processing.process_batch(\n batch = batch,\n model = self.model,\n alphabet = self.model.alphabet, \n args = self.args, \n MSA_sequences = self.MSA_sequences, \n MSA_weights = self.MSA_weights,\n MSA_start_position = self.MSA_start_position, \n MSA_end_position = self.MSA_end_position,\n device=self.model.device,\n eval_mode=True,\n indel_mode=self.args.indel_mode\n )\n if self.args.augmentation==\"zero_shot_fitness_predictions_covariate\":\n zero_shot_fitness_predictions = processed_batch['target_labels']['zero_shot_fitness_predictions'].view(-1,1)\n del processed_batch['target_labels']['zero_shot_fitness_predictions']\n else:\n zero_shot_fitness_predictions = None\n \n if self.model.model_type==\"ProteinNPT\":\n output = self.model(\n tokens=processed_batch['masked_tokens'],\n targets=processed_batch['masked_targets'],\n zero_shot_fitness_predictions=zero_shot_fitness_predictions,\n sequence_embeddings=processed_batch['sequence_embeddings'],\n need_head_weights=need_head_weights\n )\n batch_loss, batch_reconstruction_loss, batch_target_prediction_loss_dict = self.model.protein_npt_loss(\n token_predictions_logits=output['logits_protein_sequence'], \n token_labels=processed_batch['token_labels'], \n target_predictions=output['target_predictions'], \n target_labels=processed_batch['target_labels'], \n MLM_reconstruction_loss_weight=reconstruction_loss_weight, \n label_smoothing=self.args.label_smoothing\n )\n if batch_loss.item() > 10.0:\n print(\"High eval loss detected: {}\".format(batch_loss.item()))\n else:\n output = self.model(\n tokens=processed_batch['input_tokens'],\n zero_shot_fitness_predictions=zero_shot_fitness_predictions,\n sequence_embeddings=processed_batch['sequence_embeddings']\n )\n batch_loss, batch_target_prediction_loss_dict = self.model.prediction_loss(\n target_predictions=output[\"target_predictions\"], \n target_labels=processed_batch['target_labels'],\n label_smoothing=self.args.label_smoothing\n )\n \n eval_total_loss += batch_loss.item()\n for target_name in self.model.target_names:\n eval_target_prediction_loss_dict[target_name] += batch_target_prediction_loss_dict[target_name].item()\n if self.model.model_type==\"ProteinNPT\":\n eval_reconstruction_loss += batch_reconstruction_loss.item()\n eval_num_masked_tokens += processed_batch['masked_tokens'].eq(self.model.alphabet.mask_idx).sum().item()\n for target_name in self.model.target_names:\n eval_num_masked_targets[target_name] += processed_batch['masked_targets'][target_name][:,-1].eq(1.0).sum().item()\n else:\n num_predicted_targets += len(batch['mutant_mutated_seq_pairs'])\n if output_all_predictions:\n num_of_mutated_seqs_to_score = processed_batch['num_of_mutated_seqs_to_score'] if self.model.model_type==\"ProteinNPT\" else len(processed_batch['mutant_mutated_seq_pairs'])\n for target_name in self.model.target_names:\n output_scores['predictions_'+target_name] += list(output[\"target_predictions\"][target_name][:num_of_mutated_seqs_to_score].cpu().numpy())\n output_scores['labels_'+target_name] += list(processed_batch['target_labels'][target_name][:num_of_mutated_seqs_to_score].cpu().numpy())\n if need_head_weights:\n col_attentions.append(output[\"col_attentions\"])\n row_attentions.append(output[\"row_attentions\"])\n\n output_scores = pd.DataFrame.from_dict(output_scores)\n output_scores_numeric_cols = [col_name for col_name in output_scores.columns if col_name not in ['mutant','mutated_sequence']]\n output_scores = output_scores.groupby(['mutant'])[output_scores_numeric_cols].mean().reset_index() \n mutated_seqs_dict = {}\n mutant_mutated_seqs = list(zip(*test_data['mutant_mutated_seq_pairs']))\n mutated_seqs_dict['mutant'] = mutant_mutated_seqs[0]\n mutated_seqs_dict['mutated_sequence'] = mutant_mutated_seqs[1]\n mutated_seqs_df = pd.DataFrame.from_dict(mutated_seqs_dict)\n output_scores = pd.merge(output_scores, mutated_seqs_df, on='mutant', how='left')\n \n\n eval_results = {\n 'eval_total_loss':eval_total_loss,\n 'eval_target_prediction_loss_dict':eval_target_prediction_loss_dict,\n 'output_scores': output_scores\n }\n if need_head_weights:\n print(\"dimension of first attention column {}\".format(col_attentions[0].shape))\n eval_results['col_attentions'] = torch.stack(col_attentions, dim=0).cpu().numpy()\n eval_results['row_attentions'] = torch.stack(row_attentions, dim=0).cpu().numpy()\n \n if self.model.model_type==\"ProteinNPT\":\n eval_results['eval_reconstruction_loss']=eval_reconstruction_loss\n eval_results['eval_num_masked_tokens']=eval_num_masked_tokens\n eval_results['eval_num_masked_targets']=eval_num_masked_targets\n else:\n eval_results['eval_num_predicted_targets']=num_predicted_targets\n return eval_results" } ]
import os,gc import json import argparse import random import numpy as np import pandas as pd import wandb import torch import proteinnpt,baselines,utils from collections import defaultdict from proteinnpt.model import ProteinNPTModel from baselines.model import AugmentedPropertyPredictor from utils.esm.data import Alphabet from utils.tranception.model_pytorch import get_tranception_tokenizer from utils.data_utils import get_train_val_test_data, standardize, pnpt_count_non_nan, pnpt_spearmanr from utils.msa_utils import process_MSA from utils.model_utils import Trainer
20,530
else: args.augmentation_short="none" for target_index,target in enumerate(args.target_config): if "location" not in args.target_config[target].keys(): # Note: the case of zero-shot fitness predictions is already handled above if present if args.assay_location is not None: # We passed at least one path for the assay location num_targets = [x for x in args.target_config.keys() if args.target_config[x]["in_NPT_loss"]] if len(args.assay_location) > 1: assert len(args.assay_location)==num_targets, "Trying to predict {} targets, but only referencing {} distinct paths for them.".format(num_targets,len(args.assay_location)) args.target_config[target]["location"] = args.assay_location[target_index] print("Location used for target {} if {}".format(target,args.assay_location[target_index])) else: args.target_config[target]["location"] = args.assay_location[0] print("Location used for target {} if {}".format(target,args.assay_location[0])) else: print("Assay location not provided. Defaulting to location for single substitutions fitness assays: {}".format(args.data_location + os.sep + 'data/fitness/substitutions_singles')) args.target_config[target]["location"] = args.data_location + os.sep + 'data/fitness/substitutions_singles' return args def log_performance_fold(args,target_names,test_eval_results,trainer_final_status,perf_list,logs_folder=None): test_logs = {'total_training_steps': trainer_final_status['total_training_steps'], 'total_training_epochs': trainer_final_status['total_training_epochs'], 'total_train_time': trainer_final_status['total_train_time']} if logs_folder is None: dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) logs_folder = dir_path+os.sep+'output' if not os.path.exists(logs_folder): os.mkdir(logs_folder) if args.model_type=="ProteinNPT": normalization = 0 for target_name in target_names: normalization += test_eval_results['eval_num_masked_targets'][target_name] else: normalization = test_eval_results['eval_num_predicted_targets'] test_logs['Test total loss per seq.'] = test_eval_results['eval_total_loss'] / normalization spearmans = {target_name: pnpt_spearmanr(test_eval_results['output_scores']['predictions_'+target_name], test_eval_results['output_scores']['labels_'+target_name]) for target_name in target_names} num_obs_spearmans = {target_name: pnpt_count_non_nan(test_eval_results['output_scores']['labels_'+target_name]) for target_name in target_names} for target_name in target_names: print("Spearman {} target: {}".format(target_name,spearmans[target_name])) test_logs['Test Spearman '+target_name] = spearmans[target_name] if args.model_type=="ProteinNPT": normalization = test_eval_results['eval_num_masked_targets'][target_name] test_logs['Test loss '+str(target_name)+' per seq.'] = test_eval_results['eval_target_prediction_loss_dict'][target_name] / normalization with open(logs_folder+os.sep+"test_performance_by_fold_"+args.model_name_suffix+".csv", "a") as perf_tracker: if os.path.getsize(logs_folder+os.sep+"test_performance_by_fold_"+args.model_name_suffix+".csv") == 0: header="fold_index,model_type,model_name_suffix,targets,assay_id,UniProt_id,fold_variable_name,total_training_steps,total_training_epochs,aa_embeddings,target_prediction_model,target_prediction_head,augmentation,frozen_embedding_parameters,dropout,weight_decay,early_stopping_patience,use_validation_set,training_num_assay_sequences_per_batch_per_gpu,eval_num_sequences_to_score_per_batch_per_gpu,eval_num_training_sequences_per_batch_per_gpu,eval_training_sequences_sampling_method,num_MSA_sequences_per_training_instance,embed_dim,ffn_embed_dim,attention_heads,conv_kernel_size,num_protein_npt_layers,total_loss" for target_name in target_names: header += (",loss_" + target_name + ",Spearman_" + target_name + ",num_obs_Spearman_" + target_name) perf_tracker.write(header+"\n") perf = ",".join([str(x) for x in perf_list]) + "," + str(round(test_logs['Test total loss per seq.'],5)) for target_name in target_names: perf += ("," + str(round(test_logs['Test loss '+str(target_name)+' per seq.'],5)) +","+str(spearmans[target_name])+","+str(num_obs_spearmans[target_name])) perf_tracker.write(perf+"\n") return test_logs, spearmans def log_performance_all_folds(args,target_names,all_test_predictions_across_folds,spearmans_across_folds,perf_list,logs_folder=None): if not os.path.exists(args.output_scores_location + os.sep + 'all_aggregated_predictions'): os.mkdir(args.output_scores_location + os.sep + 'all_aggregated_predictions') all_test_predictions_across_folds = pd.DataFrame.from_dict(all_test_predictions_across_folds) all_test_predictions_across_folds.to_csv(args.output_scores_location + os.sep + 'all_aggregated_predictions' + os.sep + model_name_prefix + ".csv", index=False) if logs_folder is None: dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) logs_folder = dir_path+os.sep+'output' if not os.path.exists(logs_folder): os.mkdir(logs_folder) with open(logs_folder+os.sep+"test_performance_overall_"+perf_list[2]+".csv", "a") as overall_perf: if os.path.getsize(logs_folder+os.sep+"test_performance_overall_"+perf_list[2]+".csv") == 0: header = "model_type,model_name_suffix,targets,assay_id,UniProt_id,fold_variable_name,total_training_steps,total_training_epochs,aa_embeddings,target_prediction_model,target_prediction_head,augmentation,frozen_embedding_parameters,dropout,weight_decay,early_stopping_patience,use_validation_set,training_num_assay_sequences_per_batch_per_gpu,eval_num_sequences_to_score_per_batch_per_gpu,eval_num_training_sequences_per_batch_per_gpu,eval_training_sequences_sampling_method,num_MSA_sequences_per_training_instance,embed_dim,ffn_embed_dim,attention_heads,conv_kernel_size,num_protein_npt_layers,total_loss" for target_name in target_names: header += (",loss_" + target_name + ",Spearman_" + target_name + ",Std_dev_Spearman_" + target_name + ",num_obs_Spearman_" + target_name + ",standardized_loss_" + target_name + ",standardized_Spearman_" + target_name) overall_perf.write(header+"\n") perf = ",".join([str(x) for x in perf_list[1:]]) #Remove fold_index from perf_list for target_name in target_names: missing_mask = np.isnan(all_test_predictions_across_folds['labels_'+target_name]) | np.equal(all_test_predictions_across_folds['labels_'+target_name],-100) MSE = ((all_test_predictions_across_folds['predictions_'+target_name][~missing_mask] - all_test_predictions_across_folds['labels_'+target_name][~missing_mask])**2).mean() spearman = pnpt_spearmanr(all_test_predictions_across_folds['predictions_'+target_name], all_test_predictions_across_folds['labels_'+target_name]) num_obs_spearman = pnpt_count_non_nan(all_test_predictions_across_folds['labels_'+target_name]) MSE_standardized = ((all_test_predictions_across_folds['fold_standardized_predictions_'+target_name][~missing_mask] - all_test_predictions_across_folds['labels_'+target_name][~missing_mask])**2).mean() spearman_standardized = pnpt_spearmanr(all_test_predictions_across_folds['fold_standardized_predictions_'+target_name], all_test_predictions_across_folds['labels_'+target_name]) spearman_std_dev = np.array(spearmans_across_folds[target_name]).std() perf += ("," + str(MSE) +","+str(spearman) + ","+ str(spearman_std_dev) + "," + str(num_obs_spearman) + "," + str(MSE_standardized) +","+str(spearman_standardized)) overall_perf.write(perf+"\n") def main(args): # Set random seeds torch.manual_seed(args.seed) np.random.seed(args.seed) random.seed(args.seed) # target_names are the true targets we want to predict. target_names_input also includes auxiliary labels (as used in ProteinNPT) target_names = [x for x in args.target_config.keys() if args.target_config[x]["in_NPT_loss"]] target_names_input = args.target_config.keys() num_targets = len(target_names) num_targets_input = len(target_names_input) print("We want to predict {} target(s): {}".format(num_targets, ' and '.join(target_names))) if num_targets_input > num_targets: print("We leverage {} target(s) and auxiliary labels: {}".format(num_targets_input, ' and '.join(target_names_input))) assay_reference_file = pd.read_csv(args.assay_reference_file_location) assay_id=assay_reference_file["DMS_id"][args.assay_index] args.seq_len = int(assay_reference_file["seq_len"][assay_reference_file["DMS_id"]==assay_id].values[0]) args.MSA_seq_len = int(assay_reference_file["MSA_len"][assay_reference_file["DMS_id"]==assay_id].values[0]) print("Training model for assay: {}, where the test_fold index is: {}".format(assay_id, args.test_fold_index)) args.save_model_checkpoint = not args.do_not_save_model_checkpoint args.frozen_embedding_parameters = not args.fine_tune_model_embedding_parameters if args.model_type=="MSA_Transformer_pred": assert args.num_MSA_sequences_per_training_instance==args.num_MSA_sequences_per_eval_instance, "MSA_Transformer_pred only supports same size of MSA for train and eval" effective_batch_size = args.gradient_accumulation * args.training_num_assay_sequences_per_batch_per_gpu print("Effective batch size is {}".format(effective_batch_size)) model_hypers = [args.aa_embeddings,args.target_prediction_model,args.target_prediction_head,args.augmentation,args.frozen_embedding_parameters,args.dropout,args.weight_decay, \ args.early_stopping_patience, args.use_validation_set, args.training_num_assay_sequences_per_batch_per_gpu, args.eval_num_sequences_to_score_per_batch_per_gpu, args.eval_num_training_sequences_per_batch_per_gpu, \ args.eval_training_sequences_sampling_method, args.num_MSA_sequences_per_training_instance, args.embed_dim, args.ffn_embed_dim, args.attention_heads, args.conv_kernel_size, args.num_protein_npt_layers] model_hypers_str = ','.join([str(x) for x in model_hypers]) model_name_prefix = '_'.join([str(x) for x in [args.model_type,assay_id,"_".join(target_names_input),args.fold_variable_name,'embed_'+args.aa_embeddings,'head_'+str(args.target_prediction_model),'aug_'+str(args.augmentation_short), \ 'froz_'+str(args.frozen_embedding_parameters),'drop_'+str(args.dropout),'val_'+str(args.use_validation_set),args.model_name_suffix]]) model_name = model_name_prefix + "_fold-" + str(args.test_fold_index) if not os.path.exists(args.model_location+os.sep+model_name): os.mkdir(args.model_location+os.sep+model_name) with open(args.model_location+os.sep+model_name+os.sep+'training_arguments', 'w') as f: json.dump(args.__dict__, f, indent=2) print("Model name: "+model_name) assay_file_name = assay_reference_file["DMS_filename"][assay_reference_file["DMS_id"]==assay_id].values[0] # File name of main assay used during training (if single property, this is also the only assay). Retrieved embeddings are always for this assay. args.sequence_embeddings_location = args.sequence_embeddings_folder + os.sep + assay_file_name.split(".csv")[0] + '.h5' if args.sequence_embeddings_folder else None print("Sequence embeddings: {}".format(args.sequence_embeddings_location)) if args.use_wandb: wandb.login() # Create & initiate model alphabet = get_tranception_tokenizer() if args.aa_embeddings=="Tranception" else Alphabet.from_architecture("msa_transformer") if args.model_type=="ProteinNPT":
def setup_config_and_paths(args): # All parameters that are not defined by end user are fetched from the config file if args.model_config_location is not None: args.main_config=json.load(open(args.model_config_location)) for key in args.main_config: if args.__dict__[key] is None: args.__dict__[key] = args.main_config[key] # File paths config for local_path in ['embedding_model_location','MSA_data_folder','MSA_weight_data_folder','path_to_hhfilter']: if getattr(args, local_path): setattr(args, local_path, args.data_location + os.sep + getattr(args, local_path)) if not os.path.exists(args.data_location + os.sep + 'model_predictions'): os.mkdir(args.data_location + os.sep + 'model_predictions') if not os.path.exists(args.data_location + os.sep + 'checkpoint'): os.mkdir(args.data_location + os.sep + 'checkpoint') args.output_scores_location = args.data_location + os.sep + 'model_predictions' + os.sep + args.model_name_suffix if not os.path.exists(args.output_scores_location): os.mkdir(args.output_scores_location) args.model_location = args.data_location + os.sep + 'checkpoint' + os.sep + args.model_name_suffix if not os.path.exists(args.model_location): os.mkdir(args.model_location) # Target config args.target_config=json.load(open(args.target_config_location)) zero_shot_predictions_mapping={ "MSA_Transformer_pred": "MSA_Transformer_ensemble", "ESM1v_pred": "ESM1v_ensemble", "TranceptEVE_pred": "TranceptEVE_L", "Tranception_pred": "Tranception_L", "DeepSequence_pred": "DeepSequence_ensemble" } if args.model_type=="ProteinNPT": zero_shot_predictions_mapping["ProteinNPT"]=zero_shot_predictions_mapping[args.aa_embeddings+"_pred"] if args.augmentation=="zero_shot_fitness_predictions_auxiliary_labels": # Add auxiliary label to target_config assert args.zero_shot_fitness_predictions_location is not None, "Location of zero-shot fitness predictions to use as auxiliary labels not properly referenced" print("Using zero-shot fitness predictions as auxiliary labels") args.target_config["zero_shot_fitness_predictions"] = { "type": "continuous", "dim": 1, "var_name": zero_shot_predictions_mapping[args.model_type], #Select the relevant model for zero-shot fitness predictions "location": args.zero_shot_fitness_predictions_location, "in_NPT_loss": False, "main_target": False } args.augmentation_short="auxiliary" elif args.augmentation=="zero_shot_fitness_predictions_covariate": # Will use zero-shot fitness predictions as an additional model covariate assert args.zero_shot_fitness_predictions_location is not None, "Location of zero-shot fitness predictions to use as model covariate not properly referenced" print("Using zero-shot fitness predictions as covariate") args.augmentation_short="covariate" args.zero_shot_fitness_predictions_var_name = zero_shot_predictions_mapping[args.model_type] else: args.augmentation_short="none" for target_index,target in enumerate(args.target_config): if "location" not in args.target_config[target].keys(): # Note: the case of zero-shot fitness predictions is already handled above if present if args.assay_location is not None: # We passed at least one path for the assay location num_targets = [x for x in args.target_config.keys() if args.target_config[x]["in_NPT_loss"]] if len(args.assay_location) > 1: assert len(args.assay_location)==num_targets, "Trying to predict {} targets, but only referencing {} distinct paths for them.".format(num_targets,len(args.assay_location)) args.target_config[target]["location"] = args.assay_location[target_index] print("Location used for target {} if {}".format(target,args.assay_location[target_index])) else: args.target_config[target]["location"] = args.assay_location[0] print("Location used for target {} if {}".format(target,args.assay_location[0])) else: print("Assay location not provided. Defaulting to location for single substitutions fitness assays: {}".format(args.data_location + os.sep + 'data/fitness/substitutions_singles')) args.target_config[target]["location"] = args.data_location + os.sep + 'data/fitness/substitutions_singles' return args def log_performance_fold(args,target_names,test_eval_results,trainer_final_status,perf_list,logs_folder=None): test_logs = {'total_training_steps': trainer_final_status['total_training_steps'], 'total_training_epochs': trainer_final_status['total_training_epochs'], 'total_train_time': trainer_final_status['total_train_time']} if logs_folder is None: dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) logs_folder = dir_path+os.sep+'output' if not os.path.exists(logs_folder): os.mkdir(logs_folder) if args.model_type=="ProteinNPT": normalization = 0 for target_name in target_names: normalization += test_eval_results['eval_num_masked_targets'][target_name] else: normalization = test_eval_results['eval_num_predicted_targets'] test_logs['Test total loss per seq.'] = test_eval_results['eval_total_loss'] / normalization spearmans = {target_name: pnpt_spearmanr(test_eval_results['output_scores']['predictions_'+target_name], test_eval_results['output_scores']['labels_'+target_name]) for target_name in target_names} num_obs_spearmans = {target_name: pnpt_count_non_nan(test_eval_results['output_scores']['labels_'+target_name]) for target_name in target_names} for target_name in target_names: print("Spearman {} target: {}".format(target_name,spearmans[target_name])) test_logs['Test Spearman '+target_name] = spearmans[target_name] if args.model_type=="ProteinNPT": normalization = test_eval_results['eval_num_masked_targets'][target_name] test_logs['Test loss '+str(target_name)+' per seq.'] = test_eval_results['eval_target_prediction_loss_dict'][target_name] / normalization with open(logs_folder+os.sep+"test_performance_by_fold_"+args.model_name_suffix+".csv", "a") as perf_tracker: if os.path.getsize(logs_folder+os.sep+"test_performance_by_fold_"+args.model_name_suffix+".csv") == 0: header="fold_index,model_type,model_name_suffix,targets,assay_id,UniProt_id,fold_variable_name,total_training_steps,total_training_epochs,aa_embeddings,target_prediction_model,target_prediction_head,augmentation,frozen_embedding_parameters,dropout,weight_decay,early_stopping_patience,use_validation_set,training_num_assay_sequences_per_batch_per_gpu,eval_num_sequences_to_score_per_batch_per_gpu,eval_num_training_sequences_per_batch_per_gpu,eval_training_sequences_sampling_method,num_MSA_sequences_per_training_instance,embed_dim,ffn_embed_dim,attention_heads,conv_kernel_size,num_protein_npt_layers,total_loss" for target_name in target_names: header += (",loss_" + target_name + ",Spearman_" + target_name + ",num_obs_Spearman_" + target_name) perf_tracker.write(header+"\n") perf = ",".join([str(x) for x in perf_list]) + "," + str(round(test_logs['Test total loss per seq.'],5)) for target_name in target_names: perf += ("," + str(round(test_logs['Test loss '+str(target_name)+' per seq.'],5)) +","+str(spearmans[target_name])+","+str(num_obs_spearmans[target_name])) perf_tracker.write(perf+"\n") return test_logs, spearmans def log_performance_all_folds(args,target_names,all_test_predictions_across_folds,spearmans_across_folds,perf_list,logs_folder=None): if not os.path.exists(args.output_scores_location + os.sep + 'all_aggregated_predictions'): os.mkdir(args.output_scores_location + os.sep + 'all_aggregated_predictions') all_test_predictions_across_folds = pd.DataFrame.from_dict(all_test_predictions_across_folds) all_test_predictions_across_folds.to_csv(args.output_scores_location + os.sep + 'all_aggregated_predictions' + os.sep + model_name_prefix + ".csv", index=False) if logs_folder is None: dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) logs_folder = dir_path+os.sep+'output' if not os.path.exists(logs_folder): os.mkdir(logs_folder) with open(logs_folder+os.sep+"test_performance_overall_"+perf_list[2]+".csv", "a") as overall_perf: if os.path.getsize(logs_folder+os.sep+"test_performance_overall_"+perf_list[2]+".csv") == 0: header = "model_type,model_name_suffix,targets,assay_id,UniProt_id,fold_variable_name,total_training_steps,total_training_epochs,aa_embeddings,target_prediction_model,target_prediction_head,augmentation,frozen_embedding_parameters,dropout,weight_decay,early_stopping_patience,use_validation_set,training_num_assay_sequences_per_batch_per_gpu,eval_num_sequences_to_score_per_batch_per_gpu,eval_num_training_sequences_per_batch_per_gpu,eval_training_sequences_sampling_method,num_MSA_sequences_per_training_instance,embed_dim,ffn_embed_dim,attention_heads,conv_kernel_size,num_protein_npt_layers,total_loss" for target_name in target_names: header += (",loss_" + target_name + ",Spearman_" + target_name + ",Std_dev_Spearman_" + target_name + ",num_obs_Spearman_" + target_name + ",standardized_loss_" + target_name + ",standardized_Spearman_" + target_name) overall_perf.write(header+"\n") perf = ",".join([str(x) for x in perf_list[1:]]) #Remove fold_index from perf_list for target_name in target_names: missing_mask = np.isnan(all_test_predictions_across_folds['labels_'+target_name]) | np.equal(all_test_predictions_across_folds['labels_'+target_name],-100) MSE = ((all_test_predictions_across_folds['predictions_'+target_name][~missing_mask] - all_test_predictions_across_folds['labels_'+target_name][~missing_mask])**2).mean() spearman = pnpt_spearmanr(all_test_predictions_across_folds['predictions_'+target_name], all_test_predictions_across_folds['labels_'+target_name]) num_obs_spearman = pnpt_count_non_nan(all_test_predictions_across_folds['labels_'+target_name]) MSE_standardized = ((all_test_predictions_across_folds['fold_standardized_predictions_'+target_name][~missing_mask] - all_test_predictions_across_folds['labels_'+target_name][~missing_mask])**2).mean() spearman_standardized = pnpt_spearmanr(all_test_predictions_across_folds['fold_standardized_predictions_'+target_name], all_test_predictions_across_folds['labels_'+target_name]) spearman_std_dev = np.array(spearmans_across_folds[target_name]).std() perf += ("," + str(MSE) +","+str(spearman) + ","+ str(spearman_std_dev) + "," + str(num_obs_spearman) + "," + str(MSE_standardized) +","+str(spearman_standardized)) overall_perf.write(perf+"\n") def main(args): # Set random seeds torch.manual_seed(args.seed) np.random.seed(args.seed) random.seed(args.seed) # target_names are the true targets we want to predict. target_names_input also includes auxiliary labels (as used in ProteinNPT) target_names = [x for x in args.target_config.keys() if args.target_config[x]["in_NPT_loss"]] target_names_input = args.target_config.keys() num_targets = len(target_names) num_targets_input = len(target_names_input) print("We want to predict {} target(s): {}".format(num_targets, ' and '.join(target_names))) if num_targets_input > num_targets: print("We leverage {} target(s) and auxiliary labels: {}".format(num_targets_input, ' and '.join(target_names_input))) assay_reference_file = pd.read_csv(args.assay_reference_file_location) assay_id=assay_reference_file["DMS_id"][args.assay_index] args.seq_len = int(assay_reference_file["seq_len"][assay_reference_file["DMS_id"]==assay_id].values[0]) args.MSA_seq_len = int(assay_reference_file["MSA_len"][assay_reference_file["DMS_id"]==assay_id].values[0]) print("Training model for assay: {}, where the test_fold index is: {}".format(assay_id, args.test_fold_index)) args.save_model_checkpoint = not args.do_not_save_model_checkpoint args.frozen_embedding_parameters = not args.fine_tune_model_embedding_parameters if args.model_type=="MSA_Transformer_pred": assert args.num_MSA_sequences_per_training_instance==args.num_MSA_sequences_per_eval_instance, "MSA_Transformer_pred only supports same size of MSA for train and eval" effective_batch_size = args.gradient_accumulation * args.training_num_assay_sequences_per_batch_per_gpu print("Effective batch size is {}".format(effective_batch_size)) model_hypers = [args.aa_embeddings,args.target_prediction_model,args.target_prediction_head,args.augmentation,args.frozen_embedding_parameters,args.dropout,args.weight_decay, \ args.early_stopping_patience, args.use_validation_set, args.training_num_assay_sequences_per_batch_per_gpu, args.eval_num_sequences_to_score_per_batch_per_gpu, args.eval_num_training_sequences_per_batch_per_gpu, \ args.eval_training_sequences_sampling_method, args.num_MSA_sequences_per_training_instance, args.embed_dim, args.ffn_embed_dim, args.attention_heads, args.conv_kernel_size, args.num_protein_npt_layers] model_hypers_str = ','.join([str(x) for x in model_hypers]) model_name_prefix = '_'.join([str(x) for x in [args.model_type,assay_id,"_".join(target_names_input),args.fold_variable_name,'embed_'+args.aa_embeddings,'head_'+str(args.target_prediction_model),'aug_'+str(args.augmentation_short), \ 'froz_'+str(args.frozen_embedding_parameters),'drop_'+str(args.dropout),'val_'+str(args.use_validation_set),args.model_name_suffix]]) model_name = model_name_prefix + "_fold-" + str(args.test_fold_index) if not os.path.exists(args.model_location+os.sep+model_name): os.mkdir(args.model_location+os.sep+model_name) with open(args.model_location+os.sep+model_name+os.sep+'training_arguments', 'w') as f: json.dump(args.__dict__, f, indent=2) print("Model name: "+model_name) assay_file_name = assay_reference_file["DMS_filename"][assay_reference_file["DMS_id"]==assay_id].values[0] # File name of main assay used during training (if single property, this is also the only assay). Retrieved embeddings are always for this assay. args.sequence_embeddings_location = args.sequence_embeddings_folder + os.sep + assay_file_name.split(".csv")[0] + '.h5' if args.sequence_embeddings_folder else None print("Sequence embeddings: {}".format(args.sequence_embeddings_location)) if args.use_wandb: wandb.login() # Create & initiate model alphabet = get_tranception_tokenizer() if args.aa_embeddings=="Tranception" else Alphabet.from_architecture("msa_transformer") if args.model_type=="ProteinNPT":
model = ProteinNPTModel(args, alphabet)
0
2023-10-28 11:41:05+00:00
24k
CVHub520/yolov5_obb
val.py
[ { "identifier": "poly2hbb", "path": "utils/rboxs_utils.py", "snippet": "def poly2hbb(polys):\n \"\"\"\n Trans poly format to hbb format\n Args:\n rboxes (array/tensor): (num_gts, poly) \n\n Returns:\n hbboxes (array/tensor): (num_gts, [xc yc w h]) \n \"\"\"\n assert polys.shape[-1] == 8\n if isinstance(polys, torch.Tensor):\n x = polys[:, 0::2] # (num, 4) \n y = polys[:, 1::2]\n x_max = torch.amax(x, dim=1) # (num)\n x_min = torch.amin(x, dim=1)\n y_max = torch.amax(y, dim=1)\n y_min = torch.amin(y, dim=1)\n x_ctr, y_ctr = (x_max + x_min) / 2.0, (y_max + y_min) / 2.0 # (num)\n h = y_max - y_min # (num)\n w = x_max - x_min\n x_ctr, y_ctr, w, h = x_ctr.reshape(-1, 1), y_ctr.reshape(-1, 1), w.reshape(-1, 1), h.reshape(-1, 1) # (num, 1)\n hbboxes = torch.cat((x_ctr, y_ctr, w, h), dim=1)\n else:\n x = polys[:, 0::2] # (num, 4) \n y = polys[:, 1::2]\n x_max = np.amax(x, axis=1) # (num)\n x_min = np.amin(x, axis=1) \n y_max = np.amax(y, axis=1)\n y_min = np.amin(y, axis=1)\n x_ctr, y_ctr = (x_max + x_min) / 2.0, (y_max + y_min) / 2.0 # (num)\n h = y_max - y_min # (num)\n w = x_max - x_min\n x_ctr, y_ctr, w, h = x_ctr.reshape(-1, 1), y_ctr.reshape(-1, 1), w.reshape(-1, 1), h.reshape(-1, 1) # (num, 1)\n hbboxes = np.concatenate((x_ctr, y_ctr, w, h), axis=1)\n return hbboxes" }, { "identifier": "rbox2poly", "path": "utils/rboxs_utils.py", "snippet": "def rbox2poly(obboxes):\n \"\"\"\n Trans rbox format to poly format.\n Args:\n rboxes (array/tensor): (num_gts, [cx cy l s θ]) θ∈[-pi/2, pi/2)\n\n Returns:\n polys (array/tensor): (num_gts, [x1 y1 x2 y2 x3 y3 x4 y4]) \n \"\"\"\n if isinstance(obboxes, torch.Tensor):\n center, w, h, theta = obboxes[:, :2], obboxes[:, 2:3], obboxes[:, 3:4], obboxes[:, 4:5]\n Cos, Sin = torch.cos(theta), torch.sin(theta)\n\n vector1 = torch.cat(\n (w/2 * Cos, -w/2 * Sin), dim=-1)\n vector2 = torch.cat(\n (-h/2 * Sin, -h/2 * Cos), dim=-1)\n point1 = center + vector1 + vector2\n point2 = center + vector1 - vector2\n point3 = center - vector1 - vector2\n point4 = center - vector1 + vector2\n order = obboxes.shape[:-1]\n return torch.cat(\n (point1, point2, point3, point4), dim=-1).reshape(*order, 8)\n else:\n center, w, h, theta = np.split(obboxes, (2, 3, 4), axis=-1)\n Cos, Sin = np.cos(theta), np.sin(theta)\n\n vector1 = np.concatenate(\n [w/2 * Cos, -w/2 * Sin], axis=-1)\n vector2 = np.concatenate(\n [-h/2 * Sin, -h/2 * Cos], axis=-1)\n\n point1 = center + vector1 + vector2\n point2 = center + vector1 - vector2\n point3 = center - vector1 - vector2\n point4 = center - vector1 + vector2\n order = obboxes.shape[:-1]\n return np.concatenate(\n [point1, point2, point3, point4], axis=-1).reshape(*order, 8)" }, { "identifier": "DetectMultiBackend", "path": "models/common.py", "snippet": "class DetectMultiBackend(nn.Module):\n # YOLOv5 MultiBackend class for python inference on various backends\n def __init__(self, weights='yolov5s.pt', device=None, dnn=False):\n # Usage:\n # PyTorch: weights = *.pt\n # TorchScript: *.torchscript\n # CoreML: *.mlmodel\n # TensorFlow: *_saved_model\n # TensorFlow: *.pb\n # TensorFlow Lite: *.tflite\n # ONNX Runtime: *.onnx\n # OpenCV DNN: *.onnx with dnn=True\n # TensorRT: *.engine\n from models.experimental import attempt_download, attempt_load # scoped to avoid circular import\n\n super().__init__()\n w = str(weights[0] if isinstance(weights, list) else weights)\n suffix = Path(w).suffix.lower()\n suffixes = ['.pt', '.torchscript', '.onnx', '.engine', '.tflite', '.pb', '', '.mlmodel']\n check_suffix(w, suffixes) # check weights have acceptable suffix\n pt, jit, onnx, engine, tflite, pb, saved_model, coreml = (suffix == x for x in suffixes) # backend booleans\n stride, names = 64, [f'class{i}' for i in range(1000)] # assign defaults\n w = attempt_download(w) # download if not local\n\n if jit: # TorchScript\n LOGGER.info(f'Loading {w} for TorchScript inference...')\n extra_files = {'config.txt': ''} # model metadata\n model = torch.jit.load(w, _extra_files=extra_files)\n if extra_files['config.txt']:\n d = json.loads(extra_files['config.txt']) # extra_files dict\n stride, names = int(d['stride']), d['names']\n elif pt: # PyTorch\n model = attempt_load(weights if isinstance(weights, list) else w, map_location=device)\n stride = int(model.stride.max()) # model stride\n names = model.module.names if hasattr(model, 'module') else model.names # get class names\n self.model = model # explicitly assign for to(), cpu(), cuda(), half()\n elif coreml: # CoreML\n LOGGER.info(f'Loading {w} for CoreML inference...')\n import coremltools as ct\n model = ct.models.MLModel(w)\n elif dnn: # ONNX OpenCV DNN\n LOGGER.info(f'Loading {w} for ONNX OpenCV DNN inference...')\n check_requirements(('opencv-python>=4.5.4',))\n net = cv2.dnn.readNetFromONNX(w)\n elif onnx: # ONNX Runtime\n LOGGER.info(f'Loading {w} for ONNX Runtime inference...')\n cuda = torch.cuda.is_available()\n check_requirements(('onnx', 'onnxruntime-gpu' if cuda else 'onnxruntime'))\n import onnxruntime\n providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if cuda else ['CPUExecutionProvider']\n session = onnxruntime.InferenceSession(w, providers=providers)\n elif engine: # TensorRT\n LOGGER.info(f'Loading {w} for TensorRT inference...')\n import tensorrt as trt # https://developer.nvidia.com/nvidia-tensorrt-download\n check_version(trt.__version__, '8.0.0', verbose=True) # version requirement\n Binding = namedtuple('Binding', ('name', 'dtype', 'shape', 'data', 'ptr'))\n logger = trt.Logger(trt.Logger.INFO)\n with open(w, 'rb') as f, trt.Runtime(logger) as runtime:\n model = runtime.deserialize_cuda_engine(f.read())\n bindings = OrderedDict()\n for index in range(model.num_bindings):\n name = model.get_binding_name(index)\n dtype = trt.nptype(model.get_binding_dtype(index))\n shape = tuple(model.get_binding_shape(index))\n data = torch.from_numpy(np.empty(shape, dtype=np.dtype(dtype))).to(device)\n bindings[name] = Binding(name, dtype, shape, data, int(data.data_ptr()))\n binding_addrs = OrderedDict((n, d.ptr) for n, d in bindings.items())\n context = model.create_execution_context()\n batch_size = bindings['images'].shape[0]\n else: # TensorFlow model (TFLite, pb, saved_model)\n if pb: # https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt\n LOGGER.info(f'Loading {w} for TensorFlow *.pb inference...')\n import tensorflow as tf\n\n def wrap_frozen_graph(gd, inputs, outputs):\n x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=\"\"), []) # wrapped\n return x.prune(tf.nest.map_structure(x.graph.as_graph_element, inputs),\n tf.nest.map_structure(x.graph.as_graph_element, outputs))\n\n graph_def = tf.Graph().as_graph_def()\n graph_def.ParseFromString(open(w, 'rb').read())\n frozen_func = wrap_frozen_graph(gd=graph_def, inputs=\"x:0\", outputs=\"Identity:0\")\n elif saved_model:\n LOGGER.info(f'Loading {w} for TensorFlow saved_model inference...')\n import tensorflow as tf\n model = tf.keras.models.load_model(w)\n elif tflite: # https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python\n if 'edgetpu' in w.lower():\n LOGGER.info(f'Loading {w} for TensorFlow Lite Edge TPU inference...')\n import tflite_runtime.interpreter as tfli\n delegate = {'Linux': 'libedgetpu.so.1', # install https://coral.ai/software/#edgetpu-runtime\n 'Darwin': 'libedgetpu.1.dylib',\n 'Windows': 'edgetpu.dll'}[platform.system()]\n interpreter = tfli.Interpreter(model_path=w, experimental_delegates=[tfli.load_delegate(delegate)])\n else:\n LOGGER.info(f'Loading {w} for TensorFlow Lite inference...')\n import tensorflow as tf\n interpreter = tf.lite.Interpreter(model_path=w) # load TFLite model\n interpreter.allocate_tensors() # allocate\n input_details = interpreter.get_input_details() # inputs\n output_details = interpreter.get_output_details() # outputs\n self.__dict__.update(locals()) # assign all variables to self\n\n def forward(self, im, augment=False, visualize=False, val=False):\n # YOLOv5 MultiBackend inference\n b, ch, h, w = im.shape # batch, channel, height, width\n if self.pt or self.jit: # PyTorch\n y = self.model(im) if self.jit else self.model(im, augment=augment, visualize=visualize)\n return y if val else y[0]\n elif self.coreml: # CoreML\n im = im.permute(0, 2, 3, 1).cpu().numpy() # torch BCHW to numpy BHWC shape(1,320,192,3)\n im = Image.fromarray((im[0] * 255).astype('uint8'))\n # im = im.resize((192, 320), Image.ANTIALIAS)\n y = self.model.predict({'image': im}) # coordinates are xywh normalized\n box = xywh2xyxy(y['coordinates'] * [[w, h, w, h]]) # xyxy pixels\n conf, cls = y['confidence'].max(1), y['confidence'].argmax(1).astype(np.float)\n y = np.concatenate((box, conf.reshape(-1, 1), cls.reshape(-1, 1)), 1)\n elif self.onnx: # ONNX\n im = im.cpu().numpy() # torch to numpy\n if self.dnn: # ONNX OpenCV DNN\n self.net.setInput(im)\n y = self.net.forward()\n else: # ONNX Runtime\n y = self.session.run([self.session.get_outputs()[0].name], {self.session.get_inputs()[0].name: im})[0]\n elif self.engine: # TensorRT\n assert im.shape == self.bindings['images'].shape, (im.shape, self.bindings['images'].shape)\n self.binding_addrs['images'] = int(im.data_ptr())\n self.context.execute_v2(list(self.binding_addrs.values()))\n y = self.bindings['output'].data\n else: # TensorFlow model (TFLite, pb, saved_model)\n im = im.permute(0, 2, 3, 1).cpu().numpy() # torch BCHW to numpy BHWC shape(1,320,192,3)\n if self.pb:\n y = self.frozen_func(x=self.tf.constant(im)).numpy()\n elif self.saved_model:\n y = self.model(im, training=False).numpy()\n elif self.tflite:\n input, output = self.input_details[0], self.output_details[0]\n int8 = input['dtype'] == np.uint8 # is TFLite quantized uint8 model\n if int8:\n scale, zero_point = input['quantization']\n im = (im / scale + zero_point).astype(np.uint8) # de-scale\n self.interpreter.set_tensor(input['index'], im)\n self.interpreter.invoke()\n y = self.interpreter.get_tensor(output['index'])\n if int8:\n scale, zero_point = output['quantization']\n y = (y.astype(np.float32) - zero_point) * scale # re-scale\n y[..., 0] *= w # x\n y[..., 1] *= h # y\n y[..., 2] *= w # w\n y[..., 3] *= h # h\n y = torch.tensor(y) if isinstance(y, np.ndarray) else y\n return (y, []) if val else y\n\n def warmup(self, imgsz=(1, 3, 640, 640), half=False):\n # Warmup model by running inference once\n if self.pt or self.engine or self.onnx: # warmup types\n if isinstance(self.device, torch.device) and self.device.type != 'cpu': # only warmup GPU models\n im = torch.zeros(*imgsz).to(self.device).type(torch.half if half else torch.float) # input image\n self.forward(im) # warmup" }, { "identifier": "Callbacks", "path": "utils/callbacks.py", "snippet": "class Callbacks:\n \"\"\"\"\n Handles all registered callbacks for YOLOv5 Hooks\n \"\"\"\n\n def __init__(self):\n # Define the available callbacks\n self._callbacks = {\n 'on_pretrain_routine_start': [],\n 'on_pretrain_routine_end': [],\n\n 'on_train_start': [],\n 'on_train_epoch_start': [],\n 'on_train_batch_start': [],\n 'optimizer_step': [],\n 'on_before_zero_grad': [],\n 'on_train_batch_end': [],\n 'on_train_epoch_end': [],\n\n 'on_val_start': [],\n 'on_val_batch_start': [],\n 'on_val_image_end': [],\n 'on_val_batch_end': [],\n 'on_val_end': [],\n\n 'on_fit_epoch_end': [], # fit = train + val\n 'on_model_save': [],\n 'on_train_end': [],\n 'on_params_update': [],\n 'teardown': [],\n }\n\n def register_action(self, hook, name='', callback=None):\n \"\"\"\n Register a new action to a callback hook\n\n Args:\n hook The callback hook name to register the action to\n name The name of the action for later reference\n callback The callback to fire\n \"\"\"\n assert hook in self._callbacks, f\"hook '{hook}' not found in callbacks {self._callbacks}\"\n assert callable(callback), f\"callback '{callback}' is not callable\"\n self._callbacks[hook].append({'name': name, 'callback': callback})\n\n def get_registered_actions(self, hook=None):\n \"\"\"\"\n Returns all the registered actions by callback hook\n\n Args:\n hook The name of the hook to check, defaults to all\n \"\"\"\n if hook:\n return self._callbacks[hook]\n else:\n return self._callbacks\n\n def run(self, hook, *args, **kwargs):\n \"\"\"\n Loop through the registered actions and fire all callbacks\n\n Args:\n hook The name of the hook to check, defaults to all\n args Arguments to receive from YOLOv5\n kwargs Keyword Arguments to receive from YOLOv5\n \"\"\"\n\n assert hook in self._callbacks, f\"hook '{hook}' not found in callbacks {self._callbacks}\"\n\n for logger in self._callbacks[hook]:\n logger['callback'](*args, **kwargs)" }, { "identifier": "create_dataloader", "path": "utils/datasets.py", "snippet": "def create_dataloader(path, imgsz, batch_size, stride, names, single_cls=False, hyp=None, augment=False, cache=False, pad=0.0,\n rect=False, rank=-1, workers=8, image_weights=False, quad=False, prefix='', shuffle=False):\n if rect and shuffle:\n LOGGER.warning('WARNING: --rect is incompatible with DataLoader shuffle, setting shuffle=False')\n shuffle = False\n with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP\n dataset = LoadImagesAndLabels(path, names, imgsz, batch_size,\n augment=augment, # augmentation\n hyp=hyp, # hyperparameters\n rect=rect, # rectangular batches\n cache_images=cache,\n single_cls=single_cls,\n stride=int(stride),\n pad=pad,\n image_weights=image_weights,\n prefix=prefix)\n\n batch_size = min(batch_size, len(dataset))\n nw = min([os.cpu_count() // WORLD_SIZE, batch_size if batch_size > 1 else 0, workers]) # number of workers\n sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)\n loader = DataLoader if image_weights else InfiniteDataLoader # only DataLoader allows for attribute updates\n return loader(dataset,\n batch_size=batch_size,\n shuffle=shuffle and sampler is None,\n num_workers=nw,\n sampler=sampler,\n pin_memory=True,\n collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn), dataset" }, { "identifier": "LOGGER", "path": "utils/general.py", "snippet": "FILE = Path(__file__).resolve()\nROOT = FILE.parents[1] # YOLOv5 root directory\nNUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLOv5 multiprocessing threads\nLOGGER = set_logging(__name__) # define globally (used in train.py, val.py, detect.py, etc.)\nNCOLS = 0 if is_docker() else shutil.get_terminal_size().columns # terminal window size for tqdm\ndef set_logging(name=None, verbose=True):\n def __enter__(self):\n def __exit__(self, type, value, traceback):\n def __init__(self, seconds, *, timeout_msg='', suppress_timeout_errors=True):\n def _timeout_handler(self, signum, frame):\n def __enter__(self):\n def __exit__(self, exc_type, exc_val, exc_tb):\n def __init__(self, new_dir):\n def __enter__(self):\n def __exit__(self, exc_type, exc_val, exc_tb):\ndef try_except(func):\n def handler(*args, **kwargs):\ndef methods(instance):\ndef print_args(name, opt):\ndef init_seeds(seed=0):\ndef intersect_dicts(da, db, exclude=()):\ndef get_latest_run(search_dir='.'):\ndef user_config_dir(dir='Ultralytics', env_var='YOLOV5_CONFIG_DIR'):\ndef is_writeable(dir, test=False):\ndef is_docker():\ndef is_colab():\ndef is_pip():\ndef is_ascii(s=''):\ndef is_chinese(s='人工智能'):\ndef emojis(str=''):\ndef file_size(path):\ndef check_online():\ndef check_git_status():\ndef check_python(minimum='3.6.2'):\ndef check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False, hard=False, verbose=False):\ndef check_requirements(requirements=ROOT / 'requirements.txt', exclude=(), install=True):\ndef check_img_size(imgsz, s=32, floor=0):\ndef check_imshow():\ndef check_suffix(file='yolov5s.pt', suffix=('.pt',), msg=''):\ndef check_yaml(file, suffix=('.yaml', '.yml')):\ndef check_file(file, suffix=''):\ndef check_dataset(data, autodownload=True):\ndef url2file(url):\ndef download(url, dir='.', unzip=True, delete=True, curl=False, threads=1):\n def download_one(url, dir):\ndef make_divisible(x, divisor):\ndef clean_str(s):\ndef one_cycle(y1=0.0, y2=1.0, steps=100):\ndef colorstr(*input):\ndef labels_to_class_weights(labels, nc=80):\ndef labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):\ndef coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)\ndef xyxy2xywh(x):\ndef xywh2xyxy(x):\ndef xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):\ndef xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0):\ndef xyn2xy(x, w=640, h=640, padw=0, padh=0):\ndef segment2box(segment, width=640, height=640):\ndef segments2boxes(segments):\ndef resample_segments(segments, n=1000):\ndef scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):\ndef scale_polys(img1_shape, polys, img0_shape, ratio_pad=None):\ndef clip_polys(polys, shape):\ndef clip_coords(boxes, shape):\ndef non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,\n labels=(), max_det=300):\ndef non_max_suppression_obb(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,\n labels=(), max_det=1500):\ndef strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer()\ndef print_mutation(results, hyp, save_dir, bucket):\ndef apply_classifier(x, model, img, im0):\ndef increment_path(path, exist_ok=False, sep='', mkdir=False):\nclass Profile(contextlib.ContextDecorator):\nclass Timeout(contextlib.ContextDecorator):\nclass WorkingDirectory(contextlib.ContextDecorator):" }, { "identifier": "ConfusionMatrix", "path": "utils/metrics.py", "snippet": "class ConfusionMatrix:\n # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix\n def __init__(self, nc, conf=0.25, iou_thres=0.45):\n self.matrix = np.zeros((nc + 1, nc + 1))\n self.nc = nc # number of classes\n self.conf = conf\n self.iou_thres = iou_thres\n\n def process_batch(self, detections, labels):\n \"\"\"\n Return intersection-over-union (Jaccard index) of boxes.\n Both sets of boxes are expected to be in (x1, y1, x2, y2) format.\n Arguments:\n detections (Array[N, 6]), x1, y1, x2, y2, conf, class\n labels (Array[M, 5]), class, x1, y1, x2, y2\n Returns:\n None, updates confusion matrix accordingly\n \"\"\"\n detections = detections[detections[:, 4] > self.conf]\n gt_classes = labels[:, 0].int()\n detection_classes = detections[:, 5].int()\n iou = box_iou(labels[:, 1:], detections[:, :4])\n\n x = torch.where(iou > self.iou_thres)\n if x[0].shape[0]:\n matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()\n if x[0].shape[0] > 1:\n matches = matches[matches[:, 2].argsort()[::-1]]\n matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n matches = matches[matches[:, 2].argsort()[::-1]]\n matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n else:\n matches = np.zeros((0, 3))\n\n n = matches.shape[0] > 0\n m0, m1, _ = matches.transpose().astype(np.int16)\n for i, gc in enumerate(gt_classes):\n j = m0 == i\n if n and sum(j) == 1:\n self.matrix[detection_classes[m1[j]], gc] += 1 # correct\n else:\n self.matrix[self.nc, gc] += 1 # background FP\n\n if n:\n for i, dc in enumerate(detection_classes):\n if not any(m1 == i):\n self.matrix[dc, self.nc] += 1 # background FN\n\n def matrix(self):\n return self.matrix\n\n def tp_fp(self):\n tp = self.matrix.diagonal() # true positives\n fp = self.matrix.sum(1) - tp # false positives\n # fn = self.matrix.sum(0) - tp # false negatives (missed detections)\n return tp[:-1], fp[:-1] # remove background class\n\n def plot(self, normalize=True, save_dir='', names=()):\n try:\n import seaborn as sn\n\n array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-6) if normalize else 1) # normalize columns\n array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)\n\n fig = plt.figure(figsize=(12, 9), tight_layout=True)\n sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size\n labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels\n with warnings.catch_warnings():\n warnings.simplefilter('ignore') # suppress empty matrix RuntimeWarning: All-NaN slice encountered\n sn.heatmap(array, annot=self.nc < 30, annot_kws={\"size\": 8}, cmap='Blues', fmt='.2f', square=True,\n xticklabels=names + ['background FP'] if labels else \"auto\",\n yticklabels=names + ['background FN'] if labels else \"auto\").set_facecolor((1, 1, 1))\n fig.axes[0].set_xlabel('True')\n fig.axes[0].set_ylabel('Predicted')\n fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)\n plt.close()\n except Exception as e:\n print(f'WARNING: ConfusionMatrix plot failure: {e}')\n\n def print(self):\n for i in range(self.nc + 1):\n print(' '.join(map(str, self.matrix[i])))" }, { "identifier": "ap_per_class", "path": "utils/metrics.py", "snippet": "def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=(), eps=1e-16):\n \"\"\" Compute the average precision, given the recall and precision curves.\n Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.\n # Arguments\n tp: True positives (nparray, nx1 or nx10).\n conf: Objectness value from 0-1 (nparray).\n pred_cls: Predicted object classes (nparray).\n target_cls: True object classes (nparray).\n plot: Plot precision-recall curve at [email protected]\n save_dir: Plot save directory\n # Returns\n The average precision as computed in py-faster-rcnn.\n \"\"\"\n\n # Sort by objectness\n i = np.argsort(-conf)\n tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]\n\n # Find unique classes\n unique_classes, nt = np.unique(target_cls, return_counts=True)\n nc = unique_classes.shape[0] # number of classes, number of detections\n\n # Create Precision-Recall curve and compute AP for each class\n px, py = np.linspace(0, 1, 1000), [] # for plotting\n ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))\n for ci, c in enumerate(unique_classes):\n i = pred_cls == c\n n_l = nt[ci] # number of labels\n n_p = i.sum() # number of predictions\n\n if n_p == 0 or n_l == 0:\n continue\n else:\n # Accumulate FPs and TPs\n fpc = (1 - tp[i]).cumsum(0)\n tpc = tp[i].cumsum(0)\n\n # Recall\n recall = tpc / (n_l + eps) # recall curve\n r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases\n\n # Precision\n precision = tpc / (tpc + fpc) # precision curve\n p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score\n\n # AP from recall-precision curve\n for j in range(tp.shape[1]):\n ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])\n if plot and j == 0:\n py.append(np.interp(px, mrec, mpre)) # precision at [email protected]\n\n # Compute F1 (harmonic mean of precision and recall)\n f1 = 2 * p * r / (p + r + eps)\n names = [v for k, v in names.items() if k in unique_classes] # list: only classes that have data\n names = {i: v for i, v in enumerate(names)} # to dict\n if plot:\n plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)\n plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1')\n plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision')\n plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall')\n\n i = f1.mean(0).argmax() # max F1 index\n p, r, f1 = p[:, i], r[:, i], f1[:, i]\n tp = (r * nt).round() # true positives\n fp = (tp / (p + eps) - tp).round() # false positives\n return tp, fp, p, r, f1, ap, unique_classes.astype('int32')" }, { "identifier": "output_to_target", "path": "utils/plots.py", "snippet": "def output_to_target(output): #list*(n, [xylsθ, conf, cls]) θ ∈ [-pi/2, pi/2)\n # Convert model output to target format [batch_id, class_id, x, y, l, s, theta, conf]\n targets = []\n for i, o in enumerate(output):\n for *rbox, conf, cls in o.cpu().numpy():\n targets.append([i, cls, *list(*(np.array(rbox)[None])), conf])\n return np.array(targets)" }, { "identifier": "plot_images", "path": "utils/plots.py", "snippet": "def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=2048, max_subplots=4):\n \"\"\"\n Args:\n imgs (tensor): (b, 3, height, width)\n targets_train (tensor): (n_targets, [batch_id clsid cx cy l s theta gaussian_θ_labels]) θ∈[-pi/2, pi/2)\n targets_pred (array): (n, [batch_id, class_id, cx, cy, l, s, theta, conf]) θ∈[-pi/2, pi/2)\n paths (list[str,...]): (b)\n fname (str): (1) \n names :\n\n \"\"\"\n # Plot image grid with labels\n if isinstance(images, torch.Tensor):\n images = images.cpu().float().numpy()\n if isinstance(targets, torch.Tensor):\n targets = targets.cpu().numpy()\n if np.max(images[0]) <= 1:\n images *= 255 # de-normalise (optional)\n bs, _, h, w = images.shape # batch size, _, height, width\n bs = min(bs, max_subplots) # limit plot images\n ns = np.ceil(bs ** 0.5) # number of subplots (square)\n\n # Build Image\n mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init\n for i, im in enumerate(images):\n if i == max_subplots: # if last batch has fewer images than we expect\n break\n x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin\n im = im.transpose(1, 2, 0)\n mosaic[y:y + h, x:x + w, :] = im\n\n # Resize (optional)\n scale = max_size / ns / max(h, w)\n if scale < 1:\n h = math.ceil(scale * h)\n w = math.ceil(scale * w)\n mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))\n\n # Annotate\n fs = int((h + w) * ns * 0.01) # font size\n annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True)\n for i in range(i + 1):\n x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin\n annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2) # borders\n if paths:\n annotator.text((x + 5, y + 5 + h), text=Path(paths[i]).name[:40], txt_color=(220, 220, 220)) # filenames\n if len(targets) > 0:\n ti = targets[targets[:, 0] == i] # image targets, (n, [img_index clsid cx cy l s theta gaussian_θ_labels])\n # boxes = xywh2xyxy(ti[:, 2:6]).T\n rboxes = ti[:, 2:7]\n classes = ti[:, 1].astype('int')\n # labels = ti.shape[1] == 6 # labels if no conf column\n labels = ti.shape[1] == 187 # labels if no conf column\n # conf = None if labels else ti[:, 6] # check for confidence presence (label vs pred)\n conf = None if labels else ti[:, 7] # check for confidence presence (label vs pred)\n\n # if boxes.shape[1]:\n # if boxes.max() <= 1.01: # if normalized with tolerance 0.01\n # boxes[[0, 2]] *= w # scale to pixels\n # boxes[[1, 3]] *= h\n # elif scale < 1: # absolute coords need scale if image scales\n # boxes *= scale\n polys = rbox2poly(rboxes)\n if scale < 1:\n polys *= scale\n # boxes[[0, 2]] += x\n # boxes[[1, 3]] += y\n polys[:, [0, 2, 4, 6]] += x\n polys[:, [1, 3, 5, 7]] += y\n # for j, box in enumerate(boxes.T.tolist()):\n # cls = classes[j]\n # color = colors(cls)\n # cls = names[cls] if names else cls\n # if labels or conf[j] > 0.25: # 0.25 conf thresh\n # label = f'{cls}' if labels else f'{cls} {conf[j]:.1f}'\n # annotator.box_label(box, label, color=color)\n for j, poly in enumerate(polys.tolist()):\n cls = classes[j]\n color = colors(cls)\n cls = names[cls] if names else cls\n if labels or conf[j] > 0.25: # 0.25 conf thresh\n label = f'{cls}' if labels else f'{cls} {conf[j]:.1f}' \n annotator.poly_label(poly, label, color=color)\n annotator.im.save(fname) # save" }, { "identifier": "plot_val_study", "path": "utils/plots.py", "snippet": "def plot_val_study(file='', dir='', x=None): # from utils.plots import *; plot_val_study()\n # Plot file=study.txt generated by val.py (or plot all study*.txt in dir)\n save_dir = Path(file).parent if file else Path(dir)\n plot2 = False # plot additional results\n if plot2:\n ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)[1].ravel()\n\n fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)\n # for f in [save_dir / f'study_coco_{x}.txt' for x in ['yolov5n6', 'yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]:\n for f in sorted(save_dir.glob('study*.txt')):\n y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T\n x = np.arange(y.shape[1]) if x is None else np.array(x)\n if plot2:\n s = ['P', 'R', '[email protected]', '[email protected]:.95', 't_preprocess (ms/img)', 't_inference (ms/img)', 't_NMS (ms/img)']\n for i in range(7):\n ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)\n ax[i].set_title(s[i])\n\n j = y[3].argmax() + 1\n ax2.plot(y[5, 1:j], y[3, 1:j] * 1E2, '.-', linewidth=2, markersize=8,\n label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))\n\n ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],\n 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet')\n\n ax2.grid(alpha=0.2)\n ax2.set_yticks(np.arange(20, 60, 5))\n ax2.set_xlim(0, 57)\n ax2.set_ylim(25, 55)\n ax2.set_xlabel('GPU Speed (ms/img)')\n ax2.set_ylabel('COCO AP val')\n ax2.legend(loc='lower right')\n f = save_dir / 'study.png'\n print(f'Saving {f}...')\n plt.savefig(f, dpi=300)" }, { "identifier": "select_device", "path": "utils/torch_utils.py", "snippet": "def select_device(device='', batch_size=0, newline=True):\n # device = 'cpu' or '0' or '0,1,2,3'\n s = f'YOLOv5 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string\n device = str(device).strip().lower().replace('cuda:', '') # to string, 'cuda:0' to '0'\n cpu = device == 'cpu'\n if cpu:\n os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False\n elif device: # non-cpu device requested\n os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable\n assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability\n\n cuda = not cpu and torch.cuda.is_available()\n if cuda:\n devices = device.split(',') if device else '0' # range(torch.cuda.device_count()) # i.e. 0,1,6,7\n n = len(devices) # device count\n if n > 1 and batch_size > 0: # check batch_size is divisible by device_count\n assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'\n space = ' ' * (len(s) + 1)\n for i, d in enumerate(devices):\n p = torch.cuda.get_device_properties(i)\n s += f\"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2:.0f}MiB)\\n\" # bytes to MB\n else:\n s += 'CPU\\n'\n\n if not newline:\n s = s.rstrip()\n LOGGER.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe\n return torch.device('cuda:0' if cuda else 'cpu')" }, { "identifier": "time_sync", "path": "utils/torch_utils.py", "snippet": "def time_sync():\n # pytorch-accurate time\n if torch.cuda.is_available():\n torch.cuda.synchronize()\n return time.time()" } ]
import argparse import json import os import sys import numpy as np import torch from pathlib import Path from threading import Thread from tqdm import tqdm from utils.rboxs_utils import poly2hbb, rbox2poly from models.common import DetectMultiBackend from utils.callbacks import Callbacks from utils.datasets import create_dataloader from utils.general import (LOGGER, box_iou, check_dataset, check_img_size, check_requirements, check_yaml, coco80_to_coco91_class, colorstr, increment_path, non_max_suppression, print_args, scale_coords, scale_polys, xywh2xyxy, xyxy2xywh, non_max_suppression_obb) from utils.metrics import ConfusionMatrix, ap_per_class from utils.plots import output_to_target, plot_images, plot_val_study from utils.torch_utils import select_device, time_sync from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval
15,157
tbox = xywh2xyxy(poly2hbb(tpoly)) # target hbb boxes [xyxy] scale_coords(im[si].shape[1:], tbox, shape, shapes[si][1]) # native-space labels labels_hbbn = torch.cat((labels[:, 0:1], tbox), 1) # native-space labels (n, [cls xyxy]) correct = process_batch(pred_hbbn, labels_hbbn, iouv) if plots: confusion_matrix.process_batch(pred_hbbn, labels_hbbn) else: correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool) # stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls)) # (correct, conf, pcls, tcls) stats.append((correct.cpu(), pred_poly[:, 8].cpu(), pred_poly[:, 9].cpu(), tcls)) # (correct, conf, pcls, tcls) # Save/log if save_txt: # just save hbb pred results! save_one_txt(pred_hbbn, save_conf, shape, file=save_dir / 'labels' / (path.stem + '.txt')) # LOGGER.info('The horizontal prediction results has been saved in txt, which format is [cls cx cy w h /conf/]') if save_json: # save hbb pred results and poly pred results. save_one_json(pred_hbbn, pred_polyn, jdict, path, class_map) # append to COCO-JSON dictionary # LOGGER.info('The hbb and obb results has been saved in json file') callbacks.run('on_val_image_end', pred_hbb, pred_hbbn, path, names, im[si]) # Plot images if plots and batch_i < 3: f = save_dir / f'val_batch{batch_i}_labels.jpg' # labels Thread(target=plot_images, args=(im, targets, paths, f, names), daemon=True).start() f = save_dir / f'val_batch{batch_i}_pred.jpg' # predictions Thread(target=plot_images, args=(im, output_to_target(out), paths, f, names), daemon=True).start() # Compute metrics stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy if len(stats) and stats[0].any(): tp, fp, p, r, f1, ap, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names) ap50, ap = ap[:, 0], ap.mean(1) # [email protected], [email protected]:0.95 mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean() nt = np.bincount(stats[3].astype(int), minlength=nc) # number of targets per class else: nt = torch.zeros(1) # Print results pf = '%20s' + '%11i' * 2 + '%11.3g' * 4 # print format LOGGER.info(pf % ('all', seen, nt.sum(), mp, mr, map50, map)) # Print results per class if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats): for i, c in enumerate(ap_class): LOGGER.info(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i])) # Print speeds t = tuple(x / seen * 1E3 for x in dt) # speeds per image if not training: shape = (batch_size, 3, imgsz, imgsz) LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {shape}' % t) # Plots if plots: confusion_matrix.plot(save_dir=save_dir, names=list(names.values())) callbacks.run('on_val_end') # Save JSON if save_json and len(jdict): w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights anno_json = str(Path(data.get('path', '../coco')) / 'annotations/instances_val2017.json') # annotations json pred_json = str(save_dir / f"{w}_obb_predictions.json") # predictions json LOGGER.info(f'\nEvaluating pycocotools mAP... saving {pred_json}...') with open(pred_json, 'w') as f: json.dump(jdict, f) LOGGER.info('---------------------The hbb and obb results has been saved in json file-----------------------') try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb check_requirements(['pycocotools']) anno = COCO(anno_json) # init annotations api pred = anno.loadRes(pred_json) # init predictions api eval = COCOeval(anno, pred, 'bbox') if is_coco: eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.img_files] # image IDs to evaluate eval.evaluate() eval.accumulate() eval.summarize() map, map50 = eval.stats[:2] # update results ([email protected]:0.95, [email protected]) except Exception as e: LOGGER.info(f'pycocotools unable to run: {e}') # Return results model.float() # for training if not training: s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}") maps = np.zeros(nc) + map for i, c in enumerate(ap_class): maps[c] = ap[i] return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t def parse_opt(): parser = argparse.ArgumentParser() parser.add_argument('--data', type=str, default=ROOT / 'data/DroneVehicle_poly.yaml', help='dataset.yaml path') parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'runs/train/yolov5n_DroneVehicle/weights/best.pt', help='model.pt path(s)') parser.add_argument('--batch-size', type=int, default=8, help='batch size') parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=1024, help='inference size (pixels)') parser.add_argument('--conf-thres', type=float, default=0.01, help='confidence threshold') parser.add_argument('--iou-thres', type=float, default=0.4, help='NMS IoU threshold') parser.add_argument('--task', default='val', help='train, val, test, speed or study') parser.add_argument('--device', default='1', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)') parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset') parser.add_argument('--augment', action='store_true', help='augmented inference') parser.add_argument('--verbose', action='store_true', help='report mAP by class') parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt') parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') parser.add_argument('--save-json', action='store_true', help='save a COCO-JSON results file') parser.add_argument('--project', default=ROOT / 'runs/val', help='save to project/name') parser.add_argument('--name', default='exp', help='save to project/name') parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference') parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference') opt = parser.parse_args() opt.data = check_yaml(opt.data) # check YAML opt.save_json |= opt.data.endswith('coco.yaml') opt.save_txt |= opt.save_hybrid
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ Validate a trained YOLOv5 model accuracy on a custom dataset Usage: $ python path/to/val.py --data coco128.yaml --weights yolov5s.pt --img 640 """ FILE = Path(__file__).resolve() ROOT = FILE.parents[0] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) # add ROOT to PATH ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative def save_one_txt(predn, save_conf, shape, file): # Save one txt result gn = torch.tensor(shape)[[1, 0, 1, 0]] # normalization gain whwh for *xyxy, conf, cls in predn.tolist(): xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format with open(file, 'a') as f: f.write(('%g ' * len(line)).rstrip() % line + '\n') # def save_one_json(predn, jdict, path, class_map): def save_one_json(pred_hbbn, pred_polyn, jdict, path, class_map): """ Save one JSON result {"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236, "poly": [...]} Args: pred_hbbn (tensor): (n, [poly, conf, cls]) pred_polyn (tensor): (n, [xyxy, conf, cls]) """ image_id = int(path.stem) if path.stem.isnumeric() else path.stem box = xyxy2xywh(pred_hbbn[:, :4]) # xywh box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner for p, b in zip(pred_polyn.tolist(), box.tolist()): jdict.append({'image_id': image_id, 'category_id': class_map[int(p[-1]) + 1], # COCO's category_id start from 1, not 0 'bbox': [round(x, 1) for x in b], 'score': round(p[-2], 5), 'poly': [round(x, 1) for x in p[:8]], 'file_name': path.stem}) def process_batch(detections, labels, iouv): """ Return correct predictions matrix. Both sets of boxes are in (x1, y1, x2, y2) format. Arguments: detections (Array[N, 6]), x1, y1, x2, y2, conf, class labels (Array[M, 5]), class, x1, y1, x2, y2 Returns: correct (Array[N, 10]), for 10 IoU levels """ correct = torch.zeros(detections.shape[0], iouv.shape[0], dtype=torch.bool, device=iouv.device) iou = box_iou(labels[:, 1:], detections[:, :4]) x = torch.where((iou >= iouv[0]) & (labels[:, 0:1] == detections[:, 5])) # IoU above threshold and classes match if x[0].shape[0]: matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() # [label, detection, iou] if x[0].shape[0] > 1: matches = matches[matches[:, 2].argsort()[::-1]] matches = matches[np.unique(matches[:, 1], return_index=True)[1]] # matches = matches[matches[:, 2].argsort()[::-1]] matches = matches[np.unique(matches[:, 0], return_index=True)[1]] matches = torch.Tensor(matches).to(iouv.device) correct[matches[:, 1].long()] = matches[:, 2:3] >= iouv return correct @torch.no_grad() def run(data, weights=None, # model.pt path(s) batch_size=32, # batch size imgsz=640, # inference size (pixels) conf_thres=0.01, # confidence threshold iou_thres=0.4, # NMS IoU threshold task='val', # train, val, test, speed or study device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu workers=8, # max dataloader workers (per RANK in DDP mode) single_cls=False, # treat as single-class dataset augment=False, # augmented inference verbose=False, # verbose output save_txt=False, # save results to *.txt save_hybrid=False, # save label+prediction hybrid results to *.txt save_conf=False, # save confidences in --save-txt labels save_json=False, # save a COCO-JSON results file project=ROOT / 'runs/val', # save to project/name name='exp', # save to project/name exist_ok=False, # existing project/name ok, do not increment half=True, # use FP16 half-precision inference dnn=False, # use OpenCV DNN for ONNX inference model=None, dataloader=None, save_dir=Path(''), plots=True, callbacks=Callbacks(), compute_loss=None, ): # Initialize/load model and set device training = model is not None if training: # called by train.py device, pt, jit, engine = next(model.parameters()).device, True, False, False # get model device, PyTorch model half &= device.type != 'cpu' # half precision only supported on CUDA model.half() if half else model.float() else: # called directly device = select_device(device, batch_size=batch_size) # Directories save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir # Load model model = DetectMultiBackend(weights, device=device, dnn=dnn) stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine imgsz = check_img_size(imgsz, s=stride) # check image size half &= (pt or jit or engine) and device.type != 'cpu' # half precision only supported by PyTorch on CUDA if pt or jit: model.model.half() if half else model.model.float() elif engine: batch_size = model.batch_size else: half = False batch_size = 1 # export.py models default to batch-size 1 device = torch.device('cpu') LOGGER.info(f'Forcing --batch-size 1 square inference shape(1,3,{imgsz},{imgsz}) for non-PyTorch backends') # Data data = check_dataset(data) # check # Configure model.eval() is_coco = isinstance(data.get('val'), str) and data['val'].endswith('coco/val2017.txt') # COCO dataset nc = 1 if single_cls else int(data['nc']) # number of classes iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for [email protected]:0.95 niou = iouv.numel() names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)} # Dataloader if not training: model.warmup(imgsz=(1, 3, imgsz, imgsz), half=half) # warmup pad = 0.0 if task == 'speed' else 0.5 task = task if task in ('train', 'val', 'test') else 'val' # path to train/val/test images dataloader = create_dataloader(data[task], imgsz, batch_size, stride, names, single_cls, pad=pad, rect=pt, workers=workers, prefix=colorstr(f'{task}: '))[0] seen = 0 confusion_matrix = ConfusionMatrix(nc=nc) # names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)} class_map = coco80_to_coco91_class() if is_coco else list(range(1000)) s = ('%20s' + '%11s' * 6) % ('Class', 'Images', 'Labels', 'P', 'R', '[email protected]', ' [email protected]:.95') dt, p, r, f1, mp, mr, map50, map = [0.0, 0.0, 0.0], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 # loss = torch.zeros(3, device=device) loss = torch.zeros(4, device=device) jdict, stats, ap, ap_class = [], [], [], [] pbar = tqdm(dataloader, desc=s, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar for batch_i, (im, targets, paths, shapes) in enumerate(pbar): # targets (tensor): (n_gt_all_batch, [img_index clsid cx cy l s theta gaussian_θ_labels]) θ ∈ [-pi/2, pi/2) # shapes (tensor): (b, [(h_raw, w_raw), (hw_ratios, wh_paddings)]) t1 = time_sync() if pt or jit or engine: im = im.to(device, non_blocking=True) targets = targets.to(device) im = im.half() if half else im.float() # uint8 to fp16/32 im /= 255 # 0 - 255 to 0.0 - 1.0 nb, _, height, width = im.shape # batch size, channels, height, width t2 = time_sync() dt[0] += t2 - t1 # Inference out, train_out = model(im) if training else model(im, augment=augment, val=True) # inference, loss outputs dt[1] += time_sync() - t2 # Loss if compute_loss: loss += compute_loss([x.float() for x in train_out], targets)[1] # box, obj, cls, theta # NMS # targets[:, 2:] *= torch.Tensor([width, height, width, height]).to(device) # to pixels lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling t3 = time_sync() # out = non_max_suppression(out, conf_thres, iou_thres, labels=lb, multi_label=True, agnostic=single_cls) out = non_max_suppression_obb(out, conf_thres, iou_thres, labels=lb, multi_label=True, agnostic=single_cls) # list*(n, [xylsθ, conf, cls]) θ ∈ [-pi/2, pi/2) dt[2] += time_sync() - t3 # Metrics for si, pred in enumerate(out): # pred (tensor): (n, [xylsθ, conf, cls]) labels = targets[targets[:, 0] == si, 1:7] # labels (tensor):(n_gt, [clsid cx cy l s theta]) θ[-pi/2, pi/2) nl = len(labels) tcls = labels[:, 0].tolist() if nl else [] # target class path, shape = Path(paths[si]), shapes[si][0] # shape (tensor): (h_raw, w_raw) seen += 1 if len(pred) == 0: if nl: stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls)) continue # Predictions if single_cls: # pred[:, 5] = 0 pred[:, 6] = 0 poly = rbox2poly(pred[:, :5]) # (n, 8) pred_poly = torch.cat((poly, pred[:, -2:]), dim=1) # (n, [poly, conf, cls]) hbbox = xywh2xyxy(poly2hbb(pred_poly[:, :8])) # (n, [x1 y1 x2 y2]) pred_hbb = torch.cat((hbbox, pred_poly[:, -2:]), dim=1) # (n, [xyxy, conf, cls]) pred_polyn = pred_poly.clone() # predn (tensor): (n, [poly, conf, cls]) scale_polys(im[si].shape[1:], pred_polyn[:, :8], shape, shapes[si][1]) # native-space pred hbboxn = xywh2xyxy(poly2hbb(pred_polyn[:, :8])) # (n, [x1 y1 x2 y2]) pred_hbbn = torch.cat((hbboxn, pred_polyn[:, -2:]), dim=1) # (n, [xyxy, conf, cls]) native-space pred # Evaluate if nl: # tbox = xywh2xyxy(labels[:, 1:5]) # target boxes tpoly = rbox2poly(labels[:, 1:6]) # target poly tbox = xywh2xyxy(poly2hbb(tpoly)) # target hbb boxes [xyxy] scale_coords(im[si].shape[1:], tbox, shape, shapes[si][1]) # native-space labels labels_hbbn = torch.cat((labels[:, 0:1], tbox), 1) # native-space labels (n, [cls xyxy]) correct = process_batch(pred_hbbn, labels_hbbn, iouv) if plots: confusion_matrix.process_batch(pred_hbbn, labels_hbbn) else: correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool) # stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls)) # (correct, conf, pcls, tcls) stats.append((correct.cpu(), pred_poly[:, 8].cpu(), pred_poly[:, 9].cpu(), tcls)) # (correct, conf, pcls, tcls) # Save/log if save_txt: # just save hbb pred results! save_one_txt(pred_hbbn, save_conf, shape, file=save_dir / 'labels' / (path.stem + '.txt')) # LOGGER.info('The horizontal prediction results has been saved in txt, which format is [cls cx cy w h /conf/]') if save_json: # save hbb pred results and poly pred results. save_one_json(pred_hbbn, pred_polyn, jdict, path, class_map) # append to COCO-JSON dictionary # LOGGER.info('The hbb and obb results has been saved in json file') callbacks.run('on_val_image_end', pred_hbb, pred_hbbn, path, names, im[si]) # Plot images if plots and batch_i < 3: f = save_dir / f'val_batch{batch_i}_labels.jpg' # labels Thread(target=plot_images, args=(im, targets, paths, f, names), daemon=True).start() f = save_dir / f'val_batch{batch_i}_pred.jpg' # predictions Thread(target=plot_images, args=(im, output_to_target(out), paths, f, names), daemon=True).start() # Compute metrics stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy if len(stats) and stats[0].any(): tp, fp, p, r, f1, ap, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names) ap50, ap = ap[:, 0], ap.mean(1) # [email protected], [email protected]:0.95 mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean() nt = np.bincount(stats[3].astype(int), minlength=nc) # number of targets per class else: nt = torch.zeros(1) # Print results pf = '%20s' + '%11i' * 2 + '%11.3g' * 4 # print format LOGGER.info(pf % ('all', seen, nt.sum(), mp, mr, map50, map)) # Print results per class if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats): for i, c in enumerate(ap_class): LOGGER.info(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i])) # Print speeds t = tuple(x / seen * 1E3 for x in dt) # speeds per image if not training: shape = (batch_size, 3, imgsz, imgsz) LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {shape}' % t) # Plots if plots: confusion_matrix.plot(save_dir=save_dir, names=list(names.values())) callbacks.run('on_val_end') # Save JSON if save_json and len(jdict): w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights anno_json = str(Path(data.get('path', '../coco')) / 'annotations/instances_val2017.json') # annotations json pred_json = str(save_dir / f"{w}_obb_predictions.json") # predictions json LOGGER.info(f'\nEvaluating pycocotools mAP... saving {pred_json}...') with open(pred_json, 'w') as f: json.dump(jdict, f) LOGGER.info('---------------------The hbb and obb results has been saved in json file-----------------------') try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb check_requirements(['pycocotools']) anno = COCO(anno_json) # init annotations api pred = anno.loadRes(pred_json) # init predictions api eval = COCOeval(anno, pred, 'bbox') if is_coco: eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.img_files] # image IDs to evaluate eval.evaluate() eval.accumulate() eval.summarize() map, map50 = eval.stats[:2] # update results ([email protected]:0.95, [email protected]) except Exception as e: LOGGER.info(f'pycocotools unable to run: {e}') # Return results model.float() # for training if not training: s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}") maps = np.zeros(nc) + map for i, c in enumerate(ap_class): maps[c] = ap[i] return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t def parse_opt(): parser = argparse.ArgumentParser() parser.add_argument('--data', type=str, default=ROOT / 'data/DroneVehicle_poly.yaml', help='dataset.yaml path') parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'runs/train/yolov5n_DroneVehicle/weights/best.pt', help='model.pt path(s)') parser.add_argument('--batch-size', type=int, default=8, help='batch size') parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=1024, help='inference size (pixels)') parser.add_argument('--conf-thres', type=float, default=0.01, help='confidence threshold') parser.add_argument('--iou-thres', type=float, default=0.4, help='NMS IoU threshold') parser.add_argument('--task', default='val', help='train, val, test, speed or study') parser.add_argument('--device', default='1', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)') parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset') parser.add_argument('--augment', action='store_true', help='augmented inference') parser.add_argument('--verbose', action='store_true', help='report mAP by class') parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt') parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') parser.add_argument('--save-json', action='store_true', help='save a COCO-JSON results file') parser.add_argument('--project', default=ROOT / 'runs/val', help='save to project/name') parser.add_argument('--name', default='exp', help='save to project/name') parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference') parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference') opt = parser.parse_args() opt.data = check_yaml(opt.data) # check YAML opt.save_json |= opt.data.endswith('coco.yaml') opt.save_txt |= opt.save_hybrid
print_args(FILE.stem, opt)
5
2023-10-31 06:06:41+00:00
24k
serengil/LightPHE
lightphe/models/Ciphertext.py
[ { "identifier": "Homomorphic", "path": "lightphe/models/Homomorphic.py", "snippet": "class Homomorphic(ABC):\n keys: dict\n plaintext_modulo: int\n ciphertext_modulo: int\n\n @abstractmethod\n def generate_keys(self, key_size: int, s: Optional[int] = None) -> dict:\n pass\n\n @abstractmethod\n def generate_random_key(self) -> int:\n pass\n\n @abstractmethod\n def encrypt(\n self, plaintext: int, random_key: Union[Optional[int], Optional[list]] = None\n ) -> Union[int, tuple, list]:\n pass\n\n @abstractmethod\n def decrypt(self, ciphertext: Union[int, tuple, list]) -> int:\n pass\n\n @abstractmethod\n def add(\n self, ciphertext1: Union[int, tuple, list], ciphertext2: Union[int, tuple, list]\n ) -> Union[int, tuple, list]:\n pass\n\n @abstractmethod\n def multiply(\n self, ciphertext1: Union[int, tuple, list], ciphertext2: Union[int, tuple, list]\n ) -> Union[int, tuple]:\n pass\n\n @abstractmethod\n def xor(self, ciphertext1: list, ciphertext2: list) -> list:\n pass\n\n @abstractmethod\n def multiply_by_contant(self, ciphertext: Union[int, tuple, list], constant: int) -> int:\n pass\n\n @abstractmethod\n def reencrypt(self, ciphertext: Union[int, tuple, list]) -> Union[int, tuple, list]:\n pass" }, { "identifier": "Algorithm", "path": "lightphe/models/Algorithm.py", "snippet": "class Algorithm:\n RSA = \"RSA\"\n ElGamal = \"ElGamal\"\n ExponentialElGamal = \"Exponential-ElGamal\"\n EllipticCurveElGamal = \"EllipticCurve-ElGamal\"\n Paillier = \"Paillier\"\n DamgardJurik = \"Damgard-Jurik\"\n OkamotoUchiyama = \"Okamoto-Uchiyama\"\n Benaloh = \"Benaloh\"\n NaccacheStern = \"Naccache-Stern\"\n GoldwasserMicali = \"Goldwasser-Micali\"" }, { "identifier": "RSA", "path": "lightphe/cryptosystems/RSA.py", "snippet": "class RSA(Homomorphic):\n \"\"\"\n RSA algorithm is partially homomorphic with respect to the multiplication\n Ref: https://sefiks.com/2023/03/06/a-step-by-step-partially-homomorphic-encryption-example-with-rsa-in-python/\n \"\"\"\n\n def __init__(self, keys: Optional[dict] = None, key_size: int = 1024, encrypt_with_public=True):\n \"\"\"\n Args:\n keys (dict): private - public key pair.\n set this to None if you want to generate random keys.\n key_size (int): key size in bits\n encrypt_with_public (boolean): RSA has two keys: private (d) and public (e).\n If you encrypt a message with smo's public, then just that person can decrypt it\n with his private (secure message). Otherwise, if you encrypt it with your private,\n one can decrypt it with your public (digital signatures).\n Set this arg to True if you want to do encryption with public key e,\n and do decryption with private key d.\n \"\"\"\n self.keys = keys or self.generate_keys(key_size)\n self.plaintext_modulo = self.keys[\"public_key\"][\"n\"]\n self.ciphertext_modulo = self.keys[\"public_key\"][\"n\"]\n self.encrypt_with_public = encrypt_with_public\n\n def generate_keys(self, key_size: int) -> dict:\n \"\"\"\n Generate public and private keys of RSA cryptosystem\n Args:\n key_size (int): key size in bits\n Returns:\n keys (dict): having private_key and public_key keys\n \"\"\"\n keys = {}\n keys[\"private_key\"] = {}\n keys[\"public_key\"] = {}\n\n while True:\n try:\n # picking a prime modulus p and q\n p = sympy.randprime(200, 2 ** int(key_size / 2) - 1)\n q = sympy.randprime(200, 2 ** int(key_size / 2) - 1)\n\n n = p * q\n phi = (p - 1) * (q - 1)\n\n # select public exponent e\n while True:\n e = random.randint(1, phi - 1)\n if math.gcd(e, n) == 1:\n break\n\n d = pow(e, -1, phi)\n break\n except:\n pass\n\n keys[\"public_key\"][\"n\"] = n\n keys[\"public_key\"][\"e\"] = e\n keys[\"private_key\"][\"d\"] = d\n return keys\n\n def generate_random_key(self) -> int:\n pass\n\n def encrypt(self, plaintext: int) -> int:\n \"\"\"\n Encrypt plain messages with RSA\n Args:\n plaintext (int): plain message\n Returns:\n ciphertext (int): ciphertext encrypted with RSA\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n\n if plaintext > n:\n plaintext = plaintext % n\n logger.debug(\n f\"RSA can encrypt messages [1, {n}]. \"\n f\"Seems you exceeded this limit. New plaintext is {plaintext}\"\n )\n\n if self.encrypt_with_public is True:\n e = self.keys[\"public_key\"][\"e\"]\n c = pow(plaintext, e, n)\n else:\n d = self.keys[\"private_key\"][\"d\"]\n c = pow(plaintext, d, n)\n\n return c\n\n def decrypt(self, ciphertext: int) -> int:\n \"\"\"\n Decrypt ciphertexts with RSA\n Args:\n ciphertext (int): encrypted message\n decrypt_with_private (int): RSA has two keys: private (d) and public (e).\n If you encrypt a message with smo's public, then just that person can decrypt it\n with his private (secure message). Otherwise, if you encrypt it with your private,\n one can decrypt it with your public (digital signatures).\n Set this arg to True if you want to do encryption with public key e,\n and do decryption with private key d.\n Returns:\n plaintext (int): restored message\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n if self.encrypt_with_public is True:\n d = self.keys[\"private_key\"][\"d\"]\n p = pow(ciphertext, d, n)\n else:\n e = self.keys[\"public_key\"][\"e\"]\n p = pow(ciphertext, e, n)\n\n return p\n\n def multiply(self, ciphertext1: int, ciphertext2: int) -> int:\n \"\"\"\n Perform homomorphic multiplication on encrypted data.\n Result of this must be equal to E(m1 * m2)\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n return (ciphertext1 * ciphertext2) % n\n\n def add(self, ciphertext1: int, ciphertext2: int) -> int:\n raise ValueError(\"RSA is not homomorphic with respect to the addition\")\n\n def xor(self, ciphertext1: int, ciphertext2: int) -> int:\n raise ValueError(\"RSA is not homomorphic with respect to the exclusive or\")\n\n def multiply_by_contant(self, ciphertext: int, constant: int) -> int:\n raise ValueError(\"RSA is not supporting multiplying ciphertext by a known constant\")\n\n def reencrypt(self, ciphertext: int) -> int:\n raise ValueError(\"RSA does not support re-encryption\")" }, { "identifier": "ElGamal", "path": "lightphe/cryptosystems/ElGamal.py", "snippet": "class ElGamal(Homomorphic):\n \"\"\"\n ElGamal algorithm is either multiplicatively or additively homomorphic\n Ref: https://sefiks.com/2023/03/27/a-step-by-step-partially-homomorphic-encryption-example-with-elgamal-in-python/\n \"\"\"\n\n def __init__(self, keys: Optional[dict] = None, exponential=False, key_size: int = 1024):\n \"\"\"\n Args:\n keys (dict): private - public key pair.\n set this to None if you want to generate random keys.\n key_size (int): key size in bits\n exponential (boolean): set this to True to make cryptosystem exponential ElGamal.\n Regular ElGamal is homomorphic with respect to the multiplication whereas\n exponential ElGamal is homomorphic with respect to the addition\n \"\"\"\n self.exponential = exponential\n self.keys = keys or self.generate_keys(key_size)\n self.plaintext_modulo = self.keys[\"public_key\"][\"p\"]\n self.ciphertext_modulo = self.keys[\"public_key\"][\"p\"]\n\n def generate_keys(self, key_size: int):\n \"\"\"\n Generate public and private keys of ElGamal cryptosystem\n Args:\n key_size (int): key size in bits\n Returns:\n keys (dict): having private_key and public_key keys\n \"\"\"\n keys = {}\n keys[\"private_key\"] = {}\n keys[\"public_key\"] = {}\n\n # picking a prime modulus p\n p = sympy.randprime(100, 2 ** int(key_size / 2) - 1)\n\n # picking a generator g\n g = random.randint(2, int(math.sqrt(p)))\n\n # picking a private key x\n x = random.randint(1, p - 2)\n\n # public key\n y = pow(g, x, p)\n\n keys[\"public_key\"] = {\n \"p\": p,\n \"g\": g,\n \"y\": y,\n }\n\n keys[\"private_key\"] = {\"x\": x}\n\n return keys\n\n def generate_random_key(self) -> int:\n \"\"\"\n ElGamal requires to generate one-time random key per encryption\n Returns:\n random key (int): one time random key for encryption\n \"\"\"\n p = self.keys[\"public_key\"][\"p\"]\n return random.randint(1, p - 1)\n\n def encrypt(self, plaintext: int, random_key: Optional[int] = None) -> tuple:\n \"\"\"\n Encrypt plaintext with ElGamal\n Args:\n plaintext (int): message to encrypt\n random_key (int): random key for encryption. Do not set this to a static value.\n Returns\n ciphertext (tuple): c1 and c2\n \"\"\"\n p = self.keys[\"public_key\"][\"p\"]\n g = self.keys[\"public_key\"][\"g\"]\n y = self.keys[\"public_key\"][\"y\"]\n r = random_key or self.generate_random_key()\n\n if plaintext > p:\n plaintext = plaintext % p\n logger.debug(\n f\"ElGamal can encrypt messages [1, {p}]. \"\n f\"Seems you exceeded this limit. New plaintext is {plaintext}\"\n )\n\n c1 = pow(g, r, p)\n if self.exponential is False:\n c2 = (plaintext * pow(y, r, p)) % p\n else:\n c2 = (pow(g, plaintext, p) * pow(y, r, p)) % p\n\n return c1, c2\n\n def decrypt(self, ciphertext: tuple) -> int:\n \"\"\"\n Decrypt ciphertext with ElGamal\n Args:\n ciphertext (tuple): c1 and c2\n Returns:\n plaintext (int): restored message\n \"\"\"\n c1, c2 = ciphertext\n\n x = self.keys[\"private_key\"][\"x\"]\n p = self.keys[\"public_key\"][\"p\"]\n g = self.keys[\"public_key\"][\"g\"]\n\n m_prime = (c2 * pow(c1, -1 * x, p)) % p\n\n if self.exponential is False:\n return m_prime\n\n if self.exponential is True:\n # m_prime = g^m . Find m for known m_prime and known g (DLP).\n m = 0\n while True:\n if pow(g, m, p) == m_prime:\n return m\n m += 1\n if m > p:\n raise ValueError(f\"Cannot restore the message in [0, {p}]\")\n\n return -1\n\n def multiply(self, ciphertext1: tuple, ciphertext2: tuple) -> tuple:\n \"\"\"\n Perform homomorphic multiplication on encrypted data\n Result of this must be equal to E(m1 * m2)\n Args:\n ciphertext1 (dict): ElGamal ciphertext consisting of c1 and c2 keys\n ciphertext2 (dict): ElGamal ciphertext consisting of c1 and c2 keys\n Returns\n ciphertext (dict): ElGamal ciphertext consisting of c1 and c2 keys\n \"\"\"\n if self.exponential is True:\n raise ValueError(\"Exponential ElGamal is not homomorphic with respect to the addition\")\n p = self.keys[\"public_key\"][\"p\"]\n return (ciphertext1[0] * ciphertext2[0]) % p, (ciphertext1[1] * ciphertext2[1]) % p\n\n def add(self, ciphertext1: tuple, ciphertext2: tuple) -> tuple:\n \"\"\"\n Perform homomorphic addition on encrypted data\n Result of this must be equal to E(m1 + m2)\n Args:\n ciphertext1 (dict): ElGamal ciphertext consisting of c1 and c2 keys\n ciphertext2 (dict): ElGamal ciphertext consisting of c1 and c2 keys\n Returns\n ciphertext (dict): ElGamal ciphertext consisting of c1 and c2 keys\n \"\"\"\n if self.exponential is False:\n raise ValueError(\"Regular ElGamal is not homomorphic with respect to the addition\")\n p = self.keys[\"public_key\"][\"p\"]\n return (ciphertext1[0] * ciphertext2[0]) % p, (ciphertext1[1] * ciphertext2[1]) % p\n\n def xor(self, ciphertext1: tuple, ciphertext2: tuple) -> int:\n raise ValueError(\"ElGamal is not homomorphic with respect to the exclusive or\")\n\n def multiply_by_contant(self, ciphertext: tuple, constant: int) -> tuple:\n if self.exponential is False:\n raise ValueError(\"ElGamal is not supporting multiplying ciphertext by a known constant\")\n p = self.keys[\"public_key\"][\"p\"]\n if constant > p:\n constant = constant % p\n logger.debug(\n f\"ElGamal can encrypt messages [1, {p}]. \"\n f\"Seems constant exceeded this limit. New constant is {constant}\"\n )\n\n return pow(ciphertext[0], constant, p), pow(ciphertext[1], constant, p)\n\n def reencrypt(self, ciphertext: tuple) -> tuple:\n \"\"\"\n Re-generate ciphertext with re-encryption. Many ciphertext will be decrypted to same plaintext.\n Args:\n ciphertext (int): given ciphertext\n Returns:\n new ciphertext (int): different ciphertext for same plaintext\n \"\"\"\n if self.exponential is True:\n # then this is additively homomorphic\n neutral_element = 0\n else:\n # then this is multiplicatively homomorphic\n neutral_element = 1\n\n neutral_encrypted = self.encrypt(plaintext=neutral_element)\n\n if self.exponential is True:\n reencrypted_value = self.add(ciphertext1=ciphertext, ciphertext2=neutral_encrypted)\n else:\n reencrypted_value = self.multiply(ciphertext1=ciphertext, ciphertext2=neutral_encrypted)\n\n return reencrypted_value" }, { "identifier": "Paillier", "path": "lightphe/cryptosystems/Paillier.py", "snippet": "class Paillier(Homomorphic):\n \"\"\"\n Paillier algorithm is homomorphic with respect to the addition.\n Also, it supports power operation for ciphertext base and plaintext exponent\n Ref: https://sefiks.com/2023/04/03/a-step-by-step-partially-homomorphic-encryption-example-with-paillier-in-python/\n \"\"\"\n\n def __init__(self, keys: Optional[dict] = None, key_size=1024):\n \"\"\"\n Args:\n keys (dict): private - public key pair.\n set this to None if you want to generate random keys.\n key_size (int): key size in bits\n \"\"\"\n self.keys = keys or self.generate_keys(key_size)\n n = self.keys[\"public_key\"][\"n\"]\n self.plaintext_modulo = n\n self.ciphertext_modulo = n * n\n\n def generate_keys(self, key_size: int):\n \"\"\"\n Generate public and private keys of Paillier cryptosystem\n Args:\n key_size (int): key size in bits\n Returns:\n keys (dict): having private_key and public_key keys\n \"\"\"\n keys = {}\n keys[\"private_key\"] = {}\n keys[\"public_key\"] = {}\n\n # picking a prime modulus p\n p = sympy.randprime(200, 2 ** int(key_size / 2) - 1)\n\n # picking a prime modulus q\n q = sympy.randprime(200, 2 ** int(key_size / 2) - 1)\n\n n = p * q\n phi = (p - 1) * (q - 1)\n g = 1 + n\n\n keys[\"private_key\"][\"phi\"] = phi\n keys[\"public_key\"][\"g\"] = g\n keys[\"public_key\"][\"n\"] = n\n\n return keys\n\n def generate_random_key(self) -> int:\n \"\"\"\n Paillier requires to generate one-time random key per encryption\n Returns:\n random key (int): one time random key for encryption\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n while True:\n r = random.randint(0, n)\n if math.gcd(r, n) == 1:\n break\n return r\n\n def encrypt(self, plaintext: int, random_key: Optional[int] = None) -> int:\n \"\"\"\n Encrypt a given plaintext for optionally given random key with Paillier\n Args:\n plaintext (int): message to encrypt\n random_key (int): Paillier requires a random key that co-prime to n.\n Random key will be generated automatically if you do not set this.\n Returns:\n ciphertext (int): encrypted message\n \"\"\"\n g = self.keys[\"public_key\"][\"g\"]\n n = self.keys[\"public_key\"][\"n\"]\n r = random_key or self.generate_random_key()\n assert math.gcd(r, n) == 1\n return (pow(g, plaintext, n * n) * pow(r, n, n * n)) % (n * n)\n\n def decrypt(self, ciphertext: int):\n \"\"\"\n Decrypt a given ciphertext with Paillier\n Args:\n ciphertext (int): encrypted message\n Returns:\n plaintext (int): restored message\n \"\"\"\n phi = self.keys[\"private_key\"][\"phi\"]\n n = self.keys[\"public_key\"][\"n\"]\n mu = pow(phi, -1, n)\n\n return (self.lx(pow(ciphertext, phi, n * n)) * mu) % (n)\n\n def add(self, ciphertext1: int, ciphertext2: int) -> int:\n \"\"\"\n Perform homomorphic addition on encrypted data.\n Result of this must be equal to E(m1 + m2)\n Encryption calculations are done in module n squared.\n Args:\n ciphertext1 (int): 1st ciphertext created with Paillier\n ciphertext2 (int): 2nd ciphertext created with Paillier\n Returns:\n ciphertext3 (int): 3rd ciphertext created with Paillier\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n return (ciphertext1 * ciphertext2) % (n * n)\n\n def multiply(self, ciphertext1: int, ciphertext2: int) -> int:\n raise ValueError(\"Paillier is not homomorphic with respect to the multiplication\")\n\n def xor(self, ciphertext1: int, ciphertext2: int) -> int:\n raise ValueError(\"Paillier is not homomorphic with respect to the exclusive or\")\n\n def multiply_by_contant(self, ciphertext: int, constant: int) -> int:\n \"\"\"\n Multiply a ciphertext with a plain constant.\n Result of this must be equal to E(m1 * m2) where E(m1) = ciphertext\n Encryption calculations are done in module n squared.\n Args:\n ciphertext (int): ciphertext created with Paillier\n constant (int): known plain constant\n Returns:\n ciphertext (int): new ciphertext created with Paillier\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n\n if constant > self.plaintext_modulo:\n constant = constant % self.plaintext_modulo\n logger.debug(\n f\"Paillier can encrypt messages [1, {n}]. \"\n f\"Seems constant exceeded this limit. New constant is {constant}\"\n )\n\n return pow(ciphertext, constant, n * n)\n\n def reencrypt(self, ciphertext: int) -> int:\n \"\"\"\n Re-generate ciphertext with re-encryption. Many ciphertext will be decrypted to same plaintext.\n Args:\n ciphertext (int): given ciphertext\n Returns:\n new ciphertext (int): different ciphertext for same plaintext\n \"\"\"\n neutral_element = 0\n neutral_encrypted = self.encrypt(plaintext=neutral_element)\n return self.add(ciphertext1=ciphertext, ciphertext2=neutral_encrypted)\n\n def lx(self, x: int) -> int:\n \"\"\"\n Find logarithm over cyclic group\n Args:\n x (int): some integer\n Returns:\n lx (int): (x-1) / n\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n y = (x - 1) // n\n assert y - int(y) == 0\n return int(y)" }, { "identifier": "DamgardJurik", "path": "lightphe/cryptosystems/DamgardJurik.py", "snippet": "class DamgardJurik(Homomorphic):\n \"\"\"\n Damgard-Jurik algorithm is a generalization of Paillier.\n It is homomorphic with respect to the addition.\n Ref: https://sefiks.com/2023/10/20/a-step-by-step-partially-homomorphic-encryption-example-with-damgard-jurik-in-python/\n \"\"\"\n\n def __init__(self, s: int = 2, keys: Optional[dict] = None, key_size: int = 1024):\n \"\"\"\n Args:\n s (int): cryptosystem's module is going to be n^(s+1). if s == 1 then this is Paillier\n keys (dict): private - public key pair.\n set this to None if you want to generate random keys.\n key_size (int): key size in bits\n \"\"\"\n self.keys = keys or self.generate_keys(key_size=key_size, s=s)\n n = self.keys[\"public_key\"][\"n\"]\n self.plaintext_modulo = n\n self.ciphertext_modulo = pow(n, s + 1)\n\n def generate_keys(self, key_size: int, s: Optional[int] = None):\n \"\"\"\n Generate public and private keys of Paillier cryptosystem\n Args:\n s (int): cryptosystem's module is going to be n^(s+1). if s == 1 then this is Paillier\n key_size (int): key size in bits\n Returns:\n keys (dict): having private_key and public_key keys\n \"\"\"\n keys = {}\n keys[\"private_key\"] = {}\n keys[\"public_key\"] = {}\n\n # picking a prime modulus p\n p = sympy.randprime(200, 2 ** int(key_size / 2) - 1)\n\n # picking a prime modulus q\n q = sympy.randprime(200, 2 ** int(key_size / 2) - 1)\n\n n = p * q\n phi = (p - 1) * (q - 1)\n g = 1 + n\n\n keys[\"private_key\"][\"phi\"] = phi\n keys[\"public_key\"][\"g\"] = g\n keys[\"public_key\"][\"n\"] = n\n keys[\"public_key\"][\"s\"] = s\n\n return keys\n\n def generate_random_key(self) -> int:\n \"\"\"\n Paillier requires to generate one-time random key per encryption\n Returns:\n random key (int): one time random key for encryption\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n while True:\n r = random.randint(0, n)\n if math.gcd(r, n) == 1:\n break\n return r\n\n def encrypt(self, plaintext: int, random_key: Optional[int] = None) -> int:\n \"\"\"\n Encrypt a given plaintext for optionally given random key with Paillier\n Args:\n plaintext (int): message to encrypt\n random_key (int): Paillier requires a random key that co-prime to n.\n Random key will be generated automatically if you do not set this.\n Returns:\n ciphertext (int): encrypted message\n \"\"\"\n g = self.keys[\"public_key\"][\"g\"]\n n = self.keys[\"public_key\"][\"n\"]\n s = self.keys[\"public_key\"][\"s\"]\n r = random_key or self.generate_random_key()\n modulo = pow(n, s + 1)\n\n # assert math.gcd(r, n) == 1\n c = (pow(g, plaintext, modulo) * pow(r, n, modulo)) % modulo\n # c = (pow(g, plaintext, modulo) * pow(r, pow(n, s), modulo)) % modulo\n if math.gcd(c, modulo) != 1:\n logger.info(f\"WARNING! gcd({c=}, {modulo=}) != 1\")\n return c\n\n def decrypt(self, ciphertext: int):\n \"\"\"\n Decrypt a given ciphertext with Paillier\n Args:\n ciphertext (int): encrypted message\n Returns:\n plaintext (int): restored message\n \"\"\"\n phi = self.keys[\"private_key\"][\"phi\"]\n n = self.keys[\"public_key\"][\"n\"]\n s = self.keys[\"public_key\"][\"s\"]\n mu = pow(phi, -1, n)\n modulo = pow(n, s + 1)\n return (self.lx(pow(ciphertext, phi, modulo)) * mu) % (n)\n\n def add(self, ciphertext1: int, ciphertext2: int) -> int:\n \"\"\"\n Perform homomorphic addition on encrypted data.\n Result of this must be equal to E(m1 + m2)\n Encryption calculations are done in module n squared.\n Args:\n ciphertext1 (int): 1st ciphertext created with Paillier\n ciphertext2 (int): 2nd ciphertext created with Paillier\n Returns:\n ciphertext3 (int): 3rd ciphertext created with Paillier\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n s = self.keys[\"public_key\"][\"s\"]\n modulo = pow(n, s + 1)\n return (ciphertext1 * ciphertext2) % modulo\n\n def multiply(self, ciphertext1: int, ciphertext2: int) -> int:\n raise ValueError(\"Damgard-Jurik is not homomorphic with respect to the multiplication\")\n\n def xor(self, ciphertext1: int, ciphertext2: int) -> int:\n raise ValueError(\"Damgard-Jurik is not homomorphic with respect to the exclusive or\")\n\n def multiply_by_contant(self, ciphertext: int, constant: int) -> int:\n \"\"\"\n Multiply a ciphertext by a known plain constant\n Result of this must be equal to E(m1 * m2), where E(m1) = ciphertext\n Encryption calculations are done in module n squared.\n Args:\n ciphertext (int): ciphertext created with Damgard-Jurik\n constant (int): a known plain constant\n Returns:\n ciphertext (int): new ciphertext created with Damgard-Jurik\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n if constant > self.plaintext_modulo:\n constant = constant % self.plaintext_modulo\n logger.debug(\n f\"Damgard-Jurik can encrypt messages [1, {n}]. \"\n f\"Seems constant exceeded this limit. New constant is {constant}\"\n )\n return pow(ciphertext, constant, self.ciphertext_modulo)\n\n def reencrypt(self, ciphertext: int) -> int:\n \"\"\"\n Re-generate ciphertext with re-encryption. Many ciphertext will be decrypted to same plaintext.\n Args:\n ciphertext (int): given ciphertext\n Returns:\n new ciphertext (int): different ciphertext for same plaintext\n \"\"\"\n neutral_element = 0\n neutral_encrypted = self.encrypt(plaintext=neutral_element)\n return self.add(ciphertext1=ciphertext, ciphertext2=neutral_encrypted)\n\n def lx(self, x: int) -> int:\n \"\"\"\n Find logarithm over cyclic group\n Args:\n x (int): some integer\n Returns:\n lx (int): (x-1) / n\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n y = (x - 1) // n\n assert y - int(y) == 0\n return int(y)" }, { "identifier": "OkamotoUchiyama", "path": "lightphe/cryptosystems/OkamotoUchiyama.py", "snippet": "class OkamotoUchiyama(Homomorphic):\n \"\"\"\n Okamoto-Uchiyama algorithm is homomorphic with respect to the addition.\n Ref: https://sefiks.com/2023/10/20/a-step-by-step-partially-homomorphic-encryption-example-with-okamoto-uchiyama-in-python/\n \"\"\"\n\n def __init__(self, keys: Optional[dict] = None, key_size=1024):\n \"\"\"\n Args:\n keys (dict): private - public key pair.\n set this to None if you want to generate random keys.\n key_size (int): key size in bits\n \"\"\"\n self.keys = keys or self.generate_keys(key_size)\n self.plaintext_modulo = self.keys[\"private_key\"][\"p\"]\n self.ciphertext_modulo = self.keys[\"public_key\"][\"n\"]\n\n def generate_keys(self, key_size: int) -> dict:\n \"\"\"\n Generate public and private keys of OkamotoUchiyama cryptosystem\n Args:\n key_size (int): key size in bits\n Returns:\n keys (dict): having private_key and public_key keys\n \"\"\"\n keys = {}\n keys[\"private_key\"] = {}\n keys[\"public_key\"] = {}\n\n # picking a prime modulus p\n p = sympy.randprime(200, 2 ** int(key_size / 2) - 1)\n\n # picking a prime modulus q\n q = sympy.randprime(200, 2 ** int(key_size / 2) - 1)\n\n # modulo\n n = p * p * q\n\n # generator\n g = random.randint(2, n)\n\n if pow(g, p - 1, p * p) == 1:\n raise ValueError(\"Fermat's Little Theorem must be satisfied\")\n\n h = pow(g, n, n)\n\n keys[\"public_key\"][\"n\"] = n\n keys[\"public_key\"][\"g\"] = g\n keys[\"public_key\"][\"h\"] = h\n keys[\"private_key\"][\"p\"] = p\n keys[\"private_key\"][\"q\"] = q\n\n return keys\n\n def generate_random_key(self) -> int:\n \"\"\"\n Okamoto-Uchiyama requires to generate one-time random key per encryption\n Returns:\n random key (int): one time random key for encryption\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n return random.randint(1, n - 1)\n\n def encrypt(self, plaintext: int, random_key: Optional[int] = None) -> int:\n \"\"\"\n Encrypt a given plaintext for optionally given random key with OkamotoUchiyama\n Args:\n plaintext (int): message to encrypt\n random_key (int): OkamotoUchiyama requires a random key\n Random key will be generated automatically if you do not set this.\n Returns:\n ciphertext (int): encrypted message\n \"\"\"\n p = self.keys[\"private_key\"][\"p\"]\n g = self.keys[\"public_key\"][\"g\"]\n n = self.keys[\"public_key\"][\"n\"]\n h = self.keys[\"public_key\"][\"h\"]\n r = random_key or self.generate_random_key()\n\n if plaintext > p:\n plaintext = plaintext % p\n logger.debug(\n f\"plaintext must be in scale [0, {p=}] but this is exceeded.\"\n \"New plaintext is {plaintext}\"\n )\n return (pow(g, plaintext, n) * pow(h, r, n)) % n\n\n def decrypt(self, ciphertext: int):\n \"\"\"\n Decrypt a given ciphertext with Okamoto-Uchiyama\n Args:\n ciphertext (int): encrypted message\n Returns:\n plaintext (int): restored message\n \"\"\"\n p = self.keys[\"private_key\"][\"p\"]\n g = self.keys[\"public_key\"][\"g\"]\n\n a = self.lx(pow(ciphertext, p - 1, p * p))\n b = self.lx(pow(g, p - 1, p * p))\n return (a * pow(b, -1, p)) % p\n\n def add(self, ciphertext1: int, ciphertext2: int) -> int:\n \"\"\"\n Perform homomorphic addition on encrypted data.\n Result of this must be equal to E(m1 + m2)\n Encryption calculations are done in module n\n Args:\n ciphertext1 (int): 1st ciphertext created with OkamotoUchiyama\n ciphertext2 (int): 2nd ciphertext created with OkamotoUchiyama\n Returns:\n ciphertext3 (int): 3rd ciphertext created with OkamotoUchiyama\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n return (ciphertext1 * ciphertext2) % n\n\n def multiply(self, ciphertext1: int, ciphertext2: int) -> int:\n raise ValueError(\"Okamoto-Uchiyama is not homomorphic with respect to the multiplication\")\n\n def xor(self, ciphertext1: int, ciphertext2: int) -> int:\n raise ValueError(\"Okamoto-Uchiyama is not homomorphic with respect to the exclusive or\")\n\n def multiply_by_contant(self, ciphertext: int, constant: int) -> int:\n \"\"\"\n Multiply a ciphertext with a plain constant.\n Result of this must be equal to E(m1 * constant) where E(m1) = ciphertext\n Encryption calculations are done in module n squared.\n Args:\n ciphertext (int): ciphertext created with Okamoto-Uchiyama\n constant (int): known plain constant\n Returns:\n ciphertext (int): new ciphertext created with Okamoto-Uchiyama\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n if constant > self.plaintext_modulo:\n constant = constant % self.plaintext_modulo\n logger.debug(\n f\"Okamoto-Uchiyama can encrypt messages [1, {n}]. \"\n f\"Seems constant exceeded this limit. New constant is {constant}\"\n )\n return pow(ciphertext, constant, n)\n\n def reencrypt(self, ciphertext: int) -> int:\n \"\"\"\n Re-generate ciphertext with re-encryption. Many ciphertext will be decrypted to same plaintext.\n Args:\n ciphertext (int): given ciphertext\n Returns:\n new ciphertext (int): different ciphertext for same plaintext\n \"\"\"\n neutral_element = 0\n neutral_encrypted = self.encrypt(plaintext=neutral_element)\n return self.add(ciphertext1=ciphertext, ciphertext2=neutral_encrypted)\n\n def lx(self, x: int) -> int:\n \"\"\"\n Find logarithm over cyclic group\n Args:\n x (int): some integer\n Returns:\n lx (int): (x-1) / p\n \"\"\"\n p = self.keys[\"private_key\"][\"p\"]\n if x % p != 1:\n raise ValueError(f\"Input passed to lx ({x}) must be identical to 1 in modulo {p}\")\n if math.gcd(x, p * p) != 1:\n raise ValueError(f\"gcd({x}, {p}^2) must be equal to 1\")\n y = (x - 1) // p\n assert y - int(y) == 0\n return int(y)" }, { "identifier": "Benaloh", "path": "lightphe/cryptosystems/Benaloh.py", "snippet": "class Benaloh(Homomorphic):\n def __init__(self, keys: Optional[dict] = None, key_size: int = 50):\n \"\"\"\n Args:\n keys (dict): private - public key pair.\n set this to None if you want to generate random keys.\n key_size (int): key size in bits. default is less than other cryptosystems\n because decryption of Benaloh requires to solve DLP :/\n \"\"\"\n self.keys = keys or self.generate_keys(key_size)\n self.plaintext_modulo = self.keys[\"public_key\"][\"r\"]\n self.ciphertext_modulo = self.keys[\"public_key\"][\"n\"]\n\n def generate_keys(self, key_size: int) -> dict:\n \"\"\"\n Generate public and private keys of Paillier cryptosystem\n Args:\n key_size (int): key size in bits\n Returns:\n keys (dict): having private_key and public_key keys\n \"\"\"\n keys = {}\n keys[\"private_key\"] = {}\n keys[\"public_key\"] = {}\n\n x = 1\n while x == 1:\n # picking a prime p\n p = sympy.randprime(200, 2**key_size)\n\n # picking a prime q\n q = sympy.randprime(100, p)\n\n n = p * q\n phi = (p - 1) * (q - 1)\n\n r = p - 1\n while gcd(q - 1, r) != 1:\n r = int(r / gcd(q - 1, r))\n\n if not (\n # r should divide p-1 without remainder\n (p - 1) % r == 0\n # r and (p - 1) / r must be coprimes\n and gcd(r, int((p - 1) / r)) == 1\n # r and q-1 must be coprimes\n and gcd(r, q - 1) == 1\n ):\n continue\n\n y = random.randint(2, n)\n if gcd(y, n) != 1:\n continue\n\n # to guarantee correct decryption\n prime_factors = sympy.factorint(r).keys()\n decryption_guaranteed = True\n for prime_factor in prime_factors:\n # none of r's prime factor should satisfy the condition\n if pow(y, int(phi / prime_factor), n) == 1:\n decryption_guaranteed = False\n\n if decryption_guaranteed is False:\n continue\n\n x = pow(y, int(phi / r), n)\n if x != 1:\n break\n\n keys[\"public_key\"][\"y\"] = y\n keys[\"public_key\"][\"r\"] = r\n keys[\"public_key\"][\"n\"] = n\n\n keys[\"private_key\"][\"p\"] = p\n keys[\"private_key\"][\"q\"] = q\n keys[\"private_key\"][\"phi\"] = phi\n keys[\"private_key\"][\"x\"] = x\n\n return keys\n\n def generate_random_key(self) -> int:\n \"\"\"\n Generate random key for encryption\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n while True:\n u = random.randint(1, n)\n if gcd(u, n) == 1:\n break\n return u\n\n def encrypt(self, plaintext: int, random_key: Optional[int] = None) -> int:\n \"\"\"\n Encrypt a given plaintext for optionally given random key with Benaloh\n Args:\n plaintext (int): message to encrypt\n random_key (int): Benaloh requires a random key\n Random key will be generated automatically if you do not set this.\n Returns:\n ciphertext (int): encrypted message\n \"\"\"\n y = self.keys[\"public_key\"][\"y\"]\n r = self.keys[\"public_key\"][\"r\"]\n n = self.keys[\"public_key\"][\"n\"]\n\n u = random_key or self.generate_random_key()\n\n if plaintext > r:\n plaintext = plaintext % r\n logger.debug(\n f\"Benaloh lets you to encrypt messages in [0, {r=}].\"\n f\"But your plaintext exceeds this limit.\"\n f\"New plaintext is {plaintext}\"\n )\n\n c = (pow(y, plaintext, n) * pow(u, r, n)) % n\n\n if gcd(c, n) != 1:\n logger.debug(\"ciphertext is not co-prime with n!\")\n\n return c\n\n def decrypt(self, ciphertext: int) -> int:\n \"\"\"\n Decrypt a given ciphertext with Benaloh\n Args:\n ciphertext (int): encrypted message\n Returns:\n plaintext (int): restored message\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n r = self.keys[\"public_key\"][\"r\"]\n phi = self.keys[\"private_key\"][\"phi\"]\n x = self.keys[\"private_key\"][\"x\"]\n\n a = pow(ciphertext, int(phi / r), n)\n\n md = 0\n while True:\n if pow(x, md, n) == a:\n break\n md = md + 1\n if md > r:\n raise ValueError(f\"Message cannot be restored in [{0}, {n}]\")\n return md\n\n def add(self, ciphertext1: int, ciphertext2: int) -> int:\n \"\"\"\n Perform homomorphic addition on encrypted data.\n Result of this must be equal to E(m1 + m2)\n Encryption calculations are done in module n\n Args:\n ciphertext1 (int): 1st ciphertext created with Benaloh\n ciphertext2 (int): 2nd ciphertext created with Benaloh\n Returns:\n ciphertext3 (int): 3rd ciphertext created with Benaloh\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n return (ciphertext1 * ciphertext2) % n\n\n def multiply(self, ciphertext1: int, ciphertext2: int) -> int:\n raise ValueError(\"Benaloh is not homomorphic with respect to the multiplication\")\n\n def xor(self, ciphertext1: int, ciphertext2: int) -> int:\n raise ValueError(\"Benaloh is not homomorphic with respect to the exclusive or\")\n\n def multiply_by_contant(self, ciphertext: int, constant: int) -> int:\n \"\"\"\n Multiply a ciphertext with a plain constant.\n Result of this must be equal to E(m1 * constant) where E(m1) = ciphertext\n Encryption calculations are done in module n squared.\n Args:\n ciphertext (int): ciphertext created with Benaloh\n constant (int): known plain constant\n Returns:\n ciphertext (int): new ciphertext created with Benaloh\n \"\"\"\n # raise ValueError(\"Benaloh is not supporting multiplying by a constant\")\n n = self.keys[\"public_key\"][\"n\"]\n if constant > self.plaintext_modulo:\n constant = constant % self.plaintext_modulo\n logger.debug(\n f\"Benaloh can encrypt messages [1, {self.plaintext_modulo}]. \"\n f\"Seems constant exceeded this limit. New constant is {constant}\"\n )\n return pow(ciphertext, constant, n)\n\n def reencrypt(self, ciphertext: int) -> int:\n \"\"\"\n Re-generate ciphertext with re-encryption. Many ciphertext will be decrypted to same plaintext.\n Args:\n ciphertext (int): given ciphertext\n Returns:\n new ciphertext (int): different ciphertext for same plaintext\n \"\"\"\n neutral_element = 0\n neutral_encrypted = self.encrypt(plaintext=neutral_element)\n return self.add(ciphertext1=ciphertext, ciphertext2=neutral_encrypted)" }, { "identifier": "NaccacheStern", "path": "lightphe/cryptosystems/NaccacheStern.py", "snippet": "class NaccacheStern(Homomorphic):\n \"\"\"\n Naccache-Stern algorithm is homomorphic with respect to the addition.\n It is a generaliation of Benaloh cryptosystem\n Ref: https://sefiks.com/2023/10/26/a-step-by-step-partially-homomorphic-encryption-example-with-naccache-stern-in-python/\n Original paper: https://dl.acm.org/doi/pdf/10.1145/288090.288106\n \"\"\"\n\n def __init__(self, keys: Optional[dict] = None, key_size=37, deterministic: bool = False):\n \"\"\"\n Args:\n keys (dict): private - public key pair.\n set this to None if you want to generate random keys.\n key_size (int): key size in bits. Less than many cryptosystems because\n decryption requires to solve DLP.\n deterministic (boolean): deterministic or probabilistic version of\n cryptosystem\n \"\"\"\n self.keys = keys or self.generate_keys(key_size)\n self.plaintext_modulo = self.keys[\"public_key\"][\"sigma\"]\n self.ciphertext_modulo = self.keys[\"public_key\"][\"n\"]\n self.deterministic = deterministic\n\n def generate_keys(self, key_size: int) -> dict:\n \"\"\"\n Generate public and private keys of Naccache-Stern cryptosystem\n Args:\n key_size (int): key size in bits\n Returns:\n keys (dict): having private_key and public_key keys\n \"\"\"\n keys = {}\n keys[\"private_key\"] = {}\n keys[\"public_key\"] = {}\n\n # pick a family of small primes. the largest one is 10-bits\n # TODO: do something generic instead of constant primes\n prime_set = [3, 5, 7, 11, 13, 17]\n k = len(prime_set)\n\n if all(sympy.isprime(prime) is True for prime in prime_set) is False:\n raise ValueError(\"All items of prime set must be prime!\")\n\n # divide the set in half and find products of primes\n u = 1\n v = 1\n\n for i, prime in enumerate(prime_set):\n if i < len(prime_set) / 2:\n u = u * prime\n else:\n v = v * prime\n\n # product of all primes\n sigma = u * v\n\n # pick large prime numbers\n while True:\n a = sympy.randprime(200, 2 ** int(key_size / 2) - 1)\n b = sympy.randprime(100, a)\n\n # calculate two primes from chosen ones\n p = (2 * a * u) + 1\n q = (2 * b * v) + 1\n\n # recommended n is 768 bits\n n = p * q\n phi = (p - 1) * (q - 1)\n\n if phi % sigma != 0:\n logger.debug(\"canceled because phi cannot be divisible by sigma\")\n continue\n\n if math.gcd(sigma, int(phi // sigma)) != 1:\n logger.debug(\"canceled because sigma and phi/sigma are not coprime\")\n continue\n\n p_conditions = []\n for i in range(0, int(k / 2)):\n pi = prime_set[i]\n if (\n (p - 1) % pi == 0\n and math.gcd(pi, int((p - 1) / pi)) == 1\n and math.gcd(pi, q - 1) == 1\n ):\n p_conditions.append(1)\n else:\n p_conditions.append(0)\n p_satisfied = True if len(p_conditions) == sum(p_conditions) else False\n if p_satisfied is False:\n logger.debug(\"canceled because p_conditions are not satisfied\")\n continue\n\n q_conditions = []\n for i in range(int(k / 2), k):\n pi = prime_set[i]\n if (\n (q - 1) % pi == 0\n and math.gcd(pi, int((q - 1) / pi)) == 1\n and math.gcd(pi, p - 1)\n ):\n q_conditions.append(1)\n else:\n q_conditions.append(0)\n\n q_satisfied = True if len(q_conditions) == sum(q_conditions) else False\n if q_satisfied is False:\n logger.debug(\"canceled because q_conditions are not satisfied\")\n continue\n\n # p and q must be primes\n if not (sympy.isprime(p) and sympy.isprime(q)):\n continue\n\n # choose a generator g\n g = random.randint(2, n)\n # it must be co-prime to n\n if math.gcd(g, n) != 1:\n logger.debug(\"canceled becuase g is not co-prime with ne\")\n continue\n # guarantee it is not pi-th power.\n for pi in prime_set:\n logger.debug(\"canceled because g is a pi-th power\")\n if pow(g, int(phi / pi), n) == 1:\n continue\n\n # the order of g modulo n must be phi/4\n if pow(g, int(phi / 4), n) != 1:\n continue\n\n # check decryption is guaranteed similar to benaloh\n # ps: this is not mentioned in the original paper\n is_decryption_guaranteed = True\n for pi in prime_set:\n prime_factors = sympy.factorint(pi).keys()\n for prime_factor in prime_factors:\n if pow(g, int(phi / prime_factor), n) == 1:\n is_decryption_guaranteed = False\n if is_decryption_guaranteed is True:\n break\n\n logger.debug(f\"n bits is {len(bin(n)[2:])}\")\n\n keys[\"public_key\"][\"g\"] = g\n keys[\"public_key\"][\"n\"] = n\n # sigma can optionally be secret in deterministic version\n keys[\"public_key\"][\"sigma\"] = sigma\n\n keys[\"private_key\"][\"p\"] = p\n keys[\"private_key\"][\"q\"] = q\n keys[\"private_key\"][\"phi\"] = phi\n keys[\"private_key\"][\"prime_set\"] = prime_set\n\n return keys\n\n def generate_random_key(self) -> int:\n \"\"\"\n Naccache-Stern requires to generate one-time random key per encryption\n Returns:\n random key (int): one time random key for encryption\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n return random.randint(1, n - 1)\n\n def encrypt(self, plaintext: int, random_key: Optional[int] = None) -> int:\n \"\"\"\n Encrypt a given plaintext for optionally given random key with Naccache-Stern\n Args:\n plaintext (int): message to encrypt\n random_key (int): Naccache-Stern requires a random key\n Random key will be generated automatically if you do not set this.\n Returns:\n ciphertext (int): encrypted message\n \"\"\"\n g = self.keys[\"public_key\"][\"g\"]\n n = self.keys[\"public_key\"][\"n\"]\n r = random_key or self.generate_random_key()\n sigma = self.keys[\"public_key\"][\"sigma\"]\n if plaintext > self.plaintext_modulo:\n plaintext = plaintext % self.plaintext_modulo\n logger.debug(\n f\"plaintext must be in scale [0, {self.plaintext_modulo}] \"\n \"but this is exceeded. New plaintext is {plaintext}\"\n )\n\n if self.deterministic is True:\n return pow(g, plaintext, n)\n\n # Probabilistic\n return (pow(r, sigma, n) * pow(g, plaintext, n)) % n\n\n def decrypt(self, ciphertext: int):\n \"\"\"\n Decrypt a given ciphertext with Naccache-Stern\n Args:\n ciphertext (int): encrypted message\n Returns:\n plaintext (int): restored message\n \"\"\"\n phi = self.keys[\"private_key\"][\"phi\"]\n n = self.keys[\"public_key\"][\"n\"]\n g = self.keys[\"public_key\"][\"g\"]\n prime_set = self.keys[\"private_key\"][\"prime_set\"]\n\n remainders = []\n for i, prime in enumerate(prime_set):\n ci = pow(ciphertext, int(phi / prime), n)\n logger.debug(f\"c_{i} = {ci}\")\n\n j = 0\n while True:\n if ci == pow(g, int((j * phi) / prime), n):\n logger.debug(f\"m_{i} = {j}\")\n remainders.append(j)\n break\n j = j + 1\n if j > prime**2:\n raise ValueError(\n f\"c_{i} cannot be restored from {ci} = {g}^(j*{phi}/{prime}) mod {n}\"\n )\n\n congruences = []\n for i in range(0, len(prime_set)):\n logger.debug(f\"m mod {prime_set[i]} = {remainders[i]}\")\n congruences.append((remainders[i], prime_set[i]))\n\n # chinese remainder problem\n ms = solve_congruence(*congruences)\n if not ms:\n raise ValueError(\"message cannot be restored with Chinese Remainder!\")\n return ms[0]\n\n def add(self, ciphertext1: int, ciphertext2: int) -> int:\n \"\"\"\n Perform homomorphic addition on encrypted data.\n Result of this must be equal to E(m1 + m2)\n Encryption calculations are done in module n\n Args:\n ciphertext1 (int): 1st ciphertext created with Naccache-Stern\n ciphertext2 (int): 2nd ciphertext created with Naccache-Stern\n Returns:\n ciphertext3 (int): 3rd ciphertext created with Naccache-Stern\n \"\"\"\n return (ciphertext1 * ciphertext2) % self.ciphertext_modulo\n\n def multiply(self, ciphertext1: int, ciphertext2: int) -> int:\n raise ValueError(\"Naccache-Stern is not homomorphic with respect to the multiplication\")\n\n def xor(self, ciphertext1: int, ciphertext2: int) -> int:\n raise ValueError(\"Naccache-Stern is not homomorphic with respect to the exclusive or\")\n\n def multiply_by_contant(self, ciphertext: int, constant: int) -> int:\n \"\"\"\n Multiply a ciphertext with a plain constant.\n Result of this must be equal to E(m1 * constant) where E(m1) = ciphertext\n Encryption calculations are done in module n squared.\n Args:\n ciphertext (int): ciphertext created with Naccache-Stern\n constant (int): known plain constant\n Returns:\n ciphertext (int): new ciphertext created with Naccache-Stern\n \"\"\"\n if constant > self.plaintext_modulo:\n constant = constant % self.plaintext_modulo\n logger.debug(\n f\"Naccache-Stern can encrypt messages [1, {self.plaintext_modulo}]. \"\n f\"Seems constant exceeded this limit. New constant is {constant}\"\n )\n\n return pow(ciphertext, constant, self.ciphertext_modulo)\n\n def reencrypt(self, ciphertext: int) -> int:\n \"\"\"\n Re-generate ciphertext with re-encryption. Many ciphertext will be decrypted to same plaintext.\n Args:\n ciphertext (int): given ciphertext\n Returns:\n new ciphertext (int): different ciphertext for same plaintext\n \"\"\"\n if self.deterministic is True:\n raise ValueError(\n \"Deterministic version of Naccache-Stern does not support reencryption.\"\n \"If you still want to perform ciphertext regeneration, then you may \"\n \"consider to use its probabilistic version.\"\n )\n neutral_element = 0\n neutral_encrypted = self.encrypt(plaintext=neutral_element)\n return self.add(ciphertext1=ciphertext, ciphertext2=neutral_encrypted)" }, { "identifier": "GoldwasserMicali", "path": "lightphe/cryptosystems/GoldwasserMicali.py", "snippet": "class GoldwasserMicali(Homomorphic):\n \"\"\"\n Goldwasser-Micali algorithm is homomorphic with respect to the Exclusively OR (XOR).\n Ref: https://sefiks.com/2023/10/27/a-step-by-step-partially-homomorphic-encryption-example-with-goldwasser-micali-in-python/\n \"\"\"\n\n def __init__(self, keys: Optional[dict] = None, key_size=100):\n \"\"\"\n Args:\n keys (dict): private - public key pair.\n set this to None if you want to generate random keys.\n key_size (int): key size in bits\n \"\"\"\n self.keys = keys or self.generate_keys(key_size)\n self.ciphertext_modulo = self.keys[\"public_key\"][\"n\"]\n # TODO: not sure about the plaintext modulo\n self.plaintext_modulo = self.keys[\"public_key\"][\"n\"]\n\n def generate_keys(self, key_size: int) -> dict:\n \"\"\"\n Generate public and private keys of Goldwasser-Micali cryptosystem\n Args:\n key_size (int): key size in bits\n Returns:\n keys (dict): having private_key and public_key keys\n \"\"\"\n keys = {}\n keys[\"private_key\"] = {}\n keys[\"public_key\"] = {}\n\n # picking a prime p\n p = sympy.randprime(200, 2 ** int(key_size / 2) - 1)\n\n # picking a prime q\n q = sympy.randprime(200, 2 ** int(key_size / 2) - 1)\n\n n = p * q\n\n # find non-residue x\n while True:\n x = random.randint(1, n - 1)\n if math.gcd(x, n) == 1 and jacobi_symbol(x, p) == -1 and jacobi_symbol(x, q) == -1:\n break\n\n keys[\"public_key\"][\"n\"] = n\n keys[\"public_key\"][\"x\"] = x\n\n keys[\"private_key\"][\"p\"] = p\n keys[\"private_key\"][\"q\"] = q\n\n return keys\n\n def generate_random_key(self) -> int:\n \"\"\"\n Goldwasser-Micali requires to generate one-time random key that co-prime to n\n Returns:\n random key (int): one time random key for encryption\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n while True:\n r = random.randint(1, n)\n if math.gcd(r, n) == 1:\n break\n return r\n\n def encrypt(self, plaintext: int, random_key: Optional[int] = None) -> list:\n \"\"\"\n Encrypt a given plaintext for optionally given random key with Goldwasser-Micali\n Args:\n plaintext (int): message to encrypt\n random_key (int): Goldwasser-Micali requires a random key\n Random key will be generated automatically if you do not set this.\n Returns:\n ciphertext (int): encrypted message\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n x = self.keys[\"public_key\"][\"x\"]\n\n m_binary = bin(plaintext)[2:]\n\n # number of bits\n k = len(m_binary)\n\n if random_key and len(random_key) != k:\n raise ValueError(f\"Random key must be length of {k}\")\n\n c = []\n for i in range(0, k):\n mi = int(m_binary[i])\n\n if random_key:\n ri = random_key[i]\n else:\n ri = self.generate_random_key()\n\n ci = (pow(ri, 2, n) * pow(x, mi, n)) % n\n c.append(ci)\n\n return c\n\n def decrypt(self, ciphertext: list) -> int:\n \"\"\"\n Decrypt a given ciphertext with Goldwasser-Micali\n Args:\n ciphertext (int): encrypted message\n Returns:\n plaintext (int): restored message\n \"\"\"\n m_binaries = []\n\n p = self.keys[\"private_key\"][\"p\"]\n q = self.keys[\"private_key\"][\"q\"]\n\n for i in ciphertext:\n xp = i % p\n xq = i % q\n\n if pow(xp, int((p - 1) / 2), p) == 1 and pow(xq, int((q - 1) / 2), q) == 1:\n m_binaries.append(\"0\")\n else:\n m_binaries.append(\"1\")\n\n m_binary = \"\".join(m_binaries)\n return int(m_binary, 2)\n\n def add(self, ciphertext1: list, ciphertext2: list) -> list:\n raise ValueError(\"Goldwasser-Micali is not homomorphic with respect to the addition\")\n\n def multiply(self, ciphertext1: int, ciphertext2: int) -> int:\n raise ValueError(\"Goldwasser-Micali is not homomorphic with respect to the multiplication\")\n\n def xor(self, ciphertext1: int, ciphertext2: int) -> list:\n \"\"\"\n Perform homomorphic xor on encrypted data.\n Result of this must be equal to E(m1 ^ m2) = E(m1) ^ E(m2)\n Encryption calculations are done in module n\n Args:\n ciphertext1 (int): 1st ciphertext created with Goldwasser-Micali\n ciphertext2 (int): 2nd ciphertext created with Goldwasser-Micali\n Returns:\n ciphertext3 (int): 3rd ciphertext created with Goldwasser-Micali\n \"\"\"\n ciphertext3 = []\n for i in range(0, len(ciphertext1)):\n c1 = ciphertext1[i]\n c2 = ciphertext2[i]\n ciphertext3.append((c1 * c2) % self.ciphertext_modulo)\n\n return ciphertext3\n\n def multiply_by_contant(self, ciphertext: int, constant: int):\n raise ValueError(\"Goldwasser-Micali does not support multiplying with constant\")\n\n def reencrypt(self, ciphertext: int):\n raise ValueError(\"Goldwasser-Micali does not support re-encryption\")" }, { "identifier": "EllipticCurveElGamal", "path": "lightphe/cryptosystems/EllipticCurveElGamal.py", "snippet": "class EllipticCurveElGamal(Homomorphic):\n \"\"\"\n Elliptic Curve ElGamal algorithm is an additively homomorphic algorithm\n Unluckily, it requires to solve (EC)DLP to restore plaintext in decryption\n However it is easy to restore plaintext while plaintext is not very large\n unsimilar to Benaloh or Naccache-Stern\n Ref: https://sefiks.com/2018/08/21/elliptic-curve-elgamal-encryption/\n \"\"\"\n\n def __init__(self, keys: Optional[dict] = None, key_size: int = 160):\n \"\"\"\n Args:\n keys (dict): private - public key pair.\n set this to None if you want to generate random keys.\n key_size (int): key size in bits. default is 160.\n this is equivalent to 1024 bit RSA.\n \"\"\"\n # TODO: add different forms and curves. e.g. Koblitz, Edwards (Ed25519)\n self.curve = Weierstrass()\n self.keys = keys or self.generate_keys(key_size)\n self.plaintext_modulo = self.curve.p\n self.ciphertext_modulo = self.curve.p\n\n def generate_keys(self, key_size: int):\n \"\"\"\n Generate public and private keys of Elliptic Curve ElGamal cryptosystem\n Args:\n key_size (int): key size in bits\n Returns:\n keys (dict): having private_key and public_key keys\n \"\"\"\n keys = {}\n keys[\"private_key\"] = {}\n keys[\"public_key\"] = {}\n\n # private key\n ka = random.getrandbits(key_size)\n\n # public key\n Qa = self.curve.apply_double_and_add_method(G=self.curve.G, k=ka, p=self.curve.p)\n\n keys[\"public_key\"][\"Qa\"] = Qa\n keys[\"private_key\"][\"ka\"] = ka\n\n return keys\n\n def generate_random_key(self) -> int:\n \"\"\"\n Elliptic Curve ElGamal requires to generate one-time random key per encryption\n Returns:\n random key (int): one time random key for encryption\n \"\"\"\n return random.getrandbits(128)\n\n def encrypt(self, plaintext: int, random_key: Optional[int] = None) -> tuple:\n \"\"\"\n Encrypt plaintext with Elliptic Curve ElGamal\n Args:\n plaintext (int): message to encrypt\n random_key (int): random key for encryption. Do not set this to a static value.\n Returns\n ciphertext (tuple): c1 and c2\n \"\"\"\n # modulo\n p = self.curve.p\n\n # base point\n G = self.curve.G\n\n # public key\n Qa = self.keys[\"public_key\"][\"Qa\"]\n\n # random key\n r = random_key or self.generate_random_key()\n\n s = self.curve.apply_double_and_add_method(G=G, k=plaintext, p=p)\n\n c1 = self.curve.apply_double_and_add_method(G=G, k=r, p=p)\n\n c2 = self.curve.apply_double_and_add_method(G=Qa, k=r, p=p)\n c2 = self.curve.add_points(c2, s, p)\n\n return c1, c2\n\n def decrypt(self, ciphertext: tuple) -> int:\n \"\"\"\n Decrypt ciphertext with Elliptic Curve ElGamal\n Args:\n ciphertext (tuple): c1 and c2\n Returns:\n plaintext (int): restored message\n \"\"\"\n # modulo\n p = self.curve.p\n\n # private key\n ka = self.keys[\"private_key\"][\"ka\"]\n\n c1, c2 = ciphertext\n c1_prime = (c1[0], (-1 * c1[1]) % p)\n s_prime = self.curve.apply_double_and_add_method(G=c1_prime, k=ka, p=p)\n s_prime = self.curve.add_points(P=c2, Q=s_prime, p=p)\n\n # s_prime is a point on the elliptic curve\n # s_prime = k x G\n # we need to find k from known s_prime and G\n # this requires to solve ECDLP\n\n # base point\n G = self.curve.G\n k = 2\n while True:\n G = self.curve.add_points(P=G, Q=self.curve.G, p=p)\n if G[0] == s_prime[0] and G[1] == s_prime[1]:\n return k\n k = k + 1\n if k > self.curve.n:\n raise ValueError(f\"Cannot restore scalar from {s_prime} = k x {self.curve.G}\")\n\n def multiply(self, ciphertext1: tuple, ciphertext2: tuple) -> tuple:\n raise ValueError(\n \"Elliptic Curve ElGamal is not homomorphic with respect to the multiplication\"\n )\n\n def add(self, ciphertext1: tuple, ciphertext2: tuple) -> tuple:\n \"\"\"\n Perform homomorphic addition on encrypted data\n Result of this must be equal to E(m1 + m2)\n Args:\n ciphertext1 (dict): Elliptic Curve ElGamal ciphertext consisting of c1 and c2 keys\n ciphertext2 (dict): Elliptic Curve ElGamal ciphertext consisting of c1 and c2 keys\n Returns\n ciphertext (dict): Elliptic Curve ElGamal ciphertext consisting of c1 and c2 keys\n \"\"\"\n a = self.curve.add_points(P=ciphertext1[0], Q=ciphertext2[0], p=self.curve.p)\n b = self.curve.add_points(P=ciphertext1[1], Q=ciphertext2[1], p=self.curve.p)\n return a, b\n\n def xor(self, ciphertext1: tuple, ciphertext2: tuple) -> int:\n raise ValueError(\n \"Elliptic Curve ElGamal is not homomorphic with respect to the exclusive or\"\n )\n\n def multiply_by_contant(self, ciphertext: tuple, constant: int) -> tuple:\n \"\"\"\n Multiply a ciphertext with a plain constant.\n Result of this must be equal to k x E(m1) = E(m1 * k)\n where E(m1) = ciphertext\n Args:\n ciphertext (int): ciphertext created with Elliptic Curve ElGamal\n constant (int): known plain constant\n Returns:\n ciphertext (int): new ciphertext created with Elliptic Curve ElGamal\n \"\"\"\n return self.curve.apply_double_and_add_method(\n G=ciphertext[0], k=constant, p=self.curve.p\n ), self.curve.apply_double_and_add_method(G=ciphertext[1], k=constant, p=self.curve.p)\n\n def reencrypt(self, ciphertext: tuple) -> tuple:\n raise ValueError(\"Elliptic Curve ElGamal does not support regeneration of ciphertext\")" }, { "identifier": "phe_utils", "path": "lightphe/commons/phe_utils.py", "snippet": "def parse_int(value: Union[int, float], modulo: int) -> int:\ndef fractionize(value: float, modulo: int, precision: Optional[int] = None) -> Tuple[int, int]:\ndef solve_dlp():" }, { "identifier": "Logger", "path": "lightphe/commons/logger.py", "snippet": "class Logger:\n def __init__(self, module):\n self.module = module\n log_level = os.environ.get(\"LIGHTPHE_LOG_LEVEL\", str(logging.INFO))\n try:\n self.log_level = int(log_level)\n except Exception as err:\n self.dump_log(\n f\"Exception while parsing $LIGHTPHE_LOG_LEVEL.\"\n f\"Expected int but it is {log_level} ({str(err)})\"\n )\n self.log_level = logging.INFO\n\n def info(self, message):\n if self.log_level <= logging.INFO:\n self.dump_log(message)\n\n def debug(self, message):\n if self.log_level <= logging.DEBUG:\n self.dump_log(f\"🕷️ {message}\")\n\n def warn(self, message):\n if self.log_level <= logging.WARNING:\n self.dump_log(f\"⚠️ {message}\")\n\n def error(self, message):\n if self.log_level <= logging.ERROR:\n self.dump_log(f\"🔴 {message}\")\n\n def critical(self, message):\n if self.log_level <= logging.CRITICAL:\n self.dump_log(f\"💥 {message}\")\n\n def dump_log(self, message):\n print(f\"{str(datetime.now())[2:-7]} - {message}\")" } ]
from typing import Union from lightphe.models.Homomorphic import Homomorphic from lightphe.models.Algorithm import Algorithm from lightphe.cryptosystems.RSA import RSA from lightphe.cryptosystems.ElGamal import ElGamal from lightphe.cryptosystems.Paillier import Paillier from lightphe.cryptosystems.DamgardJurik import DamgardJurik from lightphe.cryptosystems.OkamotoUchiyama import OkamotoUchiyama from lightphe.cryptosystems.Benaloh import Benaloh from lightphe.cryptosystems.NaccacheStern import NaccacheStern from lightphe.cryptosystems.GoldwasserMicali import GoldwasserMicali from lightphe.cryptosystems.EllipticCurveElGamal import EllipticCurveElGamal from lightphe.commons import phe_utils from lightphe.commons.logger import Logger
17,571
logger = Logger(module="lightphe/models/Ciphertext.py") # pylint: disable=too-few-public-methods, no-else-return class Ciphertext: def __init__(self, algorithm_name: str, keys: dict, value: Union[int, tuple, list]): self.algorithm_name = algorithm_name self.keys = keys self.value = value if algorithm_name == Algorithm.RSA: cs = RSA(keys=keys) elif algorithm_name == Algorithm.ElGamal: cs = ElGamal(keys=keys) elif algorithm_name == Algorithm.ExponentialElGamal: cs = ElGamal(keys=keys, exponential=True) elif algorithm_name == Algorithm.EllipticCurveElGamal: cs = EllipticCurveElGamal(keys=keys) elif algorithm_name == Algorithm.Paillier: cs = Paillier(keys=keys) elif algorithm_name == Algorithm.DamgardJurik: cs = DamgardJurik(keys=keys) elif algorithm_name == Algorithm.OkamotoUchiyama: cs = OkamotoUchiyama(keys=keys)
logger = Logger(module="lightphe/models/Ciphertext.py") # pylint: disable=too-few-public-methods, no-else-return class Ciphertext: def __init__(self, algorithm_name: str, keys: dict, value: Union[int, tuple, list]): self.algorithm_name = algorithm_name self.keys = keys self.value = value if algorithm_name == Algorithm.RSA: cs = RSA(keys=keys) elif algorithm_name == Algorithm.ElGamal: cs = ElGamal(keys=keys) elif algorithm_name == Algorithm.ExponentialElGamal: cs = ElGamal(keys=keys, exponential=True) elif algorithm_name == Algorithm.EllipticCurveElGamal: cs = EllipticCurveElGamal(keys=keys) elif algorithm_name == Algorithm.Paillier: cs = Paillier(keys=keys) elif algorithm_name == Algorithm.DamgardJurik: cs = DamgardJurik(keys=keys) elif algorithm_name == Algorithm.OkamotoUchiyama: cs = OkamotoUchiyama(keys=keys)
elif algorithm_name == Algorithm.Benaloh:
7
2023-10-28 14:57:59+00:00
24k
chenran-li/RQL-release
stable_baselines3/dqn_ME/dqn_ME.py
[ { "identifier": "ReplayBuffer", "path": "stable_baselines3/common/buffers.py", "snippet": "class ReplayBuffer(BaseBuffer):\n \"\"\"\n Replay buffer used in off-policy algorithms like SAC/TD3.\n\n :param buffer_size: Max number of element in the buffer\n :param observation_space: Observation space\n :param action_space: Action space\n :param device: PyTorch device\n :param n_envs: Number of parallel environments\n :param optimize_memory_usage: Enable a memory efficient variant\n of the replay buffer which reduces by almost a factor two the memory used,\n at a cost of more complexity.\n See https://github.com/DLR-RM/stable-baselines3/issues/37#issuecomment-637501195\n and https://github.com/DLR-RM/stable-baselines3/pull/28#issuecomment-637559274\n Cannot be used in combination with handle_timeout_termination.\n :param handle_timeout_termination: Handle timeout termination (due to timelimit)\n separately and treat the task as infinite horizon task.\n https://github.com/DLR-RM/stable-baselines3/issues/284\n \"\"\"\n\n def __init__(\n self,\n buffer_size: int,\n observation_space: spaces.Space,\n action_space: spaces.Space,\n device: Union[th.device, str] = \"auto\",\n n_envs: int = 1,\n optimize_memory_usage: bool = False,\n handle_timeout_termination: bool = True,\n ):\n super().__init__(buffer_size, observation_space, action_space, device, n_envs=n_envs)\n\n # Adjust buffer size\n self.buffer_size = max(buffer_size // n_envs, 1)\n\n # Check that the replay buffer can fit into the memory\n if psutil is not None:\n mem_available = psutil.virtual_memory().available\n\n # there is a bug if both optimize_memory_usage and handle_timeout_termination are true\n # see https://github.com/DLR-RM/stable-baselines3/issues/934\n if optimize_memory_usage and handle_timeout_termination:\n raise ValueError(\n \"ReplayBuffer does not support optimize_memory_usage = True \"\n \"and handle_timeout_termination = True simultaneously.\"\n )\n self.optimize_memory_usage = optimize_memory_usage\n\n self.observations = np.zeros((self.buffer_size, self.n_envs) + self.obs_shape, dtype=observation_space.dtype)\n\n if optimize_memory_usage:\n # `observations` contains also the next observation\n self.next_observations = None\n else:\n self.next_observations = np.zeros((self.buffer_size, self.n_envs) + self.obs_shape, dtype=observation_space.dtype)\n\n self.actions = np.zeros((self.buffer_size, self.n_envs, self.action_dim), dtype=action_space.dtype)\n\n self.rewards = np.zeros((self.buffer_size, self.n_envs), dtype=np.float32)\n self.dones = np.zeros((self.buffer_size, self.n_envs), dtype=np.float32)\n # Handle timeouts termination properly if needed\n # see https://github.com/DLR-RM/stable-baselines3/issues/284\n self.handle_timeout_termination = handle_timeout_termination\n self.timeouts = np.zeros((self.buffer_size, self.n_envs), dtype=np.float32)\n\n if psutil is not None:\n total_memory_usage = self.observations.nbytes + self.actions.nbytes + self.rewards.nbytes + self.dones.nbytes\n\n if self.next_observations is not None:\n total_memory_usage += self.next_observations.nbytes\n\n if total_memory_usage > mem_available:\n # Convert to GB\n total_memory_usage /= 1e9\n mem_available /= 1e9\n warnings.warn(\n \"This system does not have apparently enough memory to store the complete \"\n f\"replay buffer {total_memory_usage:.2f}GB > {mem_available:.2f}GB\"\n )\n\n def add(\n self,\n obs: np.ndarray,\n next_obs: np.ndarray,\n action: np.ndarray,\n reward: np.ndarray,\n done: np.ndarray,\n infos: List[Dict[str, Any]],\n ) -> None:\n\n # Reshape needed when using multiple envs with discrete observations\n # as numpy cannot broadcast (n_discrete,) to (n_discrete, 1)\n if isinstance(self.observation_space, spaces.Discrete):\n obs = obs.reshape((self.n_envs,) + self.obs_shape)\n next_obs = next_obs.reshape((self.n_envs,) + self.obs_shape)\n\n # Same, for actions\n action = action.reshape((self.n_envs, self.action_dim))\n\n # Copy to avoid modification by reference\n self.observations[self.pos] = np.array(obs).copy()\n\n if self.optimize_memory_usage:\n self.observations[(self.pos + 1) % self.buffer_size] = np.array(next_obs).copy()\n else:\n self.next_observations[self.pos] = np.array(next_obs).copy()\n\n self.actions[self.pos] = np.array(action).copy()\n self.rewards[self.pos] = np.array(reward).copy()\n self.dones[self.pos] = np.array(done).copy()\n\n if self.handle_timeout_termination:\n self.timeouts[self.pos] = np.array([info.get(\"TimeLimit.truncated\", False) for info in infos])\n\n self.pos += 1\n if self.pos == self.buffer_size:\n self.full = True\n self.pos = 0\n\n def sample(self, batch_size: int, env: Optional[VecNormalize] = None) -> ReplayBufferSamples:\n \"\"\"\n Sample elements from the replay buffer.\n Custom sampling when using memory efficient variant,\n as we should not sample the element with index `self.pos`\n See https://github.com/DLR-RM/stable-baselines3/pull/28#issuecomment-637559274\n\n :param batch_size: Number of element to sample\n :param env: associated gym VecEnv\n to normalize the observations/rewards when sampling\n :return:\n \"\"\"\n if not self.optimize_memory_usage:\n return super().sample(batch_size=batch_size, env=env)\n # Do not sample the element with index `self.pos` as the transitions is invalid\n # (we use only one array to store `obs` and `next_obs`)\n if self.full:\n batch_inds = (np.random.randint(1, self.buffer_size, size=batch_size) + self.pos) % self.buffer_size\n else:\n batch_inds = np.random.randint(0, self.pos, size=batch_size)\n return self._get_samples(batch_inds, env=env)\n\n def _get_samples(self, batch_inds: np.ndarray, env: Optional[VecNormalize] = None) -> ReplayBufferSamples:\n # Sample randomly the env idx\n env_indices = np.random.randint(0, high=self.n_envs, size=(len(batch_inds),))\n\n if self.optimize_memory_usage:\n next_obs = self._normalize_obs(self.observations[(batch_inds + 1) % self.buffer_size, env_indices, :], env)\n else:\n next_obs = self._normalize_obs(self.next_observations[batch_inds, env_indices, :], env)\n\n data = (\n self._normalize_obs(self.observations[batch_inds, env_indices, :], env),\n self.actions[batch_inds, env_indices, :],\n next_obs,\n # Only use dones that are not due to timeouts\n # deactivated by default (timeouts is initialized as an array of False)\n (self.dones[batch_inds, env_indices] * (1 - self.timeouts[batch_inds, env_indices])).reshape(-1, 1),\n self._normalize_reward(self.rewards[batch_inds, env_indices].reshape(-1, 1), env),\n )\n return ReplayBufferSamples(*tuple(map(self.to_torch, data)))" }, { "identifier": "OffPolicyAlgorithm", "path": "stable_baselines3/common/off_policy_algorithm.py", "snippet": "class OffPolicyAlgorithm(BaseAlgorithm):\n \"\"\"\n The base for Off-Policy algorithms (ex: SAC/TD3)\n\n :param policy: The policy model to use (MlpPolicy, CnnPolicy, ...)\n :param env: The environment to learn from\n (if registered in Gym, can be str. Can be None for loading trained models)\n :param learning_rate: learning rate for the optimizer,\n it can be a function of the current progress remaining (from 1 to 0)\n :param buffer_size: size of the replay buffer\n :param learning_starts: how many steps of the model to collect transitions for before learning starts\n :param batch_size: Minibatch size for each gradient update\n :param tau: the soft update coefficient (\"Polyak update\", between 0 and 1)\n :param gamma: the discount factor\n :param train_freq: Update the model every ``train_freq`` steps. Alternatively pass a tuple of frequency and unit\n like ``(5, \"step\")`` or ``(2, \"episode\")``.\n :param gradient_steps: How many gradient steps to do after each rollout (see ``train_freq``)\n Set to ``-1`` means to do as many gradient steps as steps done in the environment\n during the rollout.\n :param action_noise: the action noise type (None by default), this can help\n for hard exploration problem. Cf common.noise for the different action noise type.\n :param replay_buffer_class: Replay buffer class to use (for instance ``HerReplayBuffer``).\n If ``None``, it will be automatically selected.\n :param replay_buffer_kwargs: Keyword arguments to pass to the replay buffer on creation.\n :param optimize_memory_usage: Enable a memory efficient variant of the replay buffer\n at a cost of more complexity.\n See https://github.com/DLR-RM/stable-baselines3/issues/37#issuecomment-637501195\n :param policy_kwargs: Additional arguments to be passed to the policy on creation\n :param tensorboard_log: the log location for tensorboard (if None, no logging)\n :param verbose: Verbosity level: 0 for no output, 1 for info messages (such as device or wrappers used), 2 for\n debug messages\n :param device: Device on which the code should run.\n By default, it will try to use a Cuda compatible device and fallback to cpu\n if it is not possible.\n :param support_multi_env: Whether the algorithm supports training\n with multiple environments (as in A2C)\n :param monitor_wrapper: When creating an environment, whether to wrap it\n or not in a Monitor wrapper.\n :param seed: Seed for the pseudo random generators\n :param use_sde: Whether to use State Dependent Exploration (SDE)\n instead of action noise exploration (default: False)\n :param sde_sample_freq: Sample a new noise matrix every n steps when using gSDE\n Default: -1 (only sample at the beginning of the rollout)\n :param use_sde_at_warmup: Whether to use gSDE instead of uniform sampling\n during the warm up phase (before learning starts)\n :param sde_support: Whether the model support gSDE or not\n :param supported_action_spaces: The action spaces supported by the algorithm.\n \"\"\"\n\n def __init__(\n self,\n policy: Union[str, Type[BasePolicy]],\n env: Union[GymEnv, str],\n learning_rate: Union[float, Schedule],\n buffer_size: int = 1_000_000, # 1e6\n learning_starts: int = 100,\n batch_size: int = 256,\n tau: float = 0.005,\n gamma: float = 0.99,\n train_freq: Union[int, Tuple[int, str]] = (1, \"step\"),\n gradient_steps: int = 1,\n action_noise: Optional[ActionNoise] = None,\n replay_buffer_class: Optional[Type[ReplayBuffer]] = None,\n replay_buffer_kwargs: Optional[Dict[str, Any]] = None,\n optimize_memory_usage: bool = False,\n policy_kwargs: Optional[Dict[str, Any]] = None,\n tensorboard_log: Optional[str] = None,\n verbose: int = 0,\n device: Union[th.device, str] = \"auto\",\n support_multi_env: bool = False,\n monitor_wrapper: bool = True,\n seed: Optional[int] = None,\n use_sde: bool = False,\n sde_sample_freq: int = -1,\n use_sde_at_warmup: bool = False,\n sde_support: bool = True,\n supported_action_spaces: Optional[Tuple[spaces.Space, ...]] = None,\n ):\n\n super().__init__(\n policy=policy,\n env=env,\n learning_rate=learning_rate,\n policy_kwargs=policy_kwargs,\n tensorboard_log=tensorboard_log,\n verbose=verbose,\n device=device,\n support_multi_env=support_multi_env,\n monitor_wrapper=monitor_wrapper,\n seed=seed,\n use_sde=use_sde,\n sde_sample_freq=sde_sample_freq,\n supported_action_spaces=supported_action_spaces,\n )\n self.buffer_size = buffer_size\n self.batch_size = batch_size\n self.learning_starts = learning_starts\n self.tau = tau\n self.gamma = gamma\n self.gradient_steps = gradient_steps\n self.action_noise = action_noise\n self.optimize_memory_usage = optimize_memory_usage\n self.replay_buffer_class = replay_buffer_class\n if replay_buffer_kwargs is None:\n replay_buffer_kwargs = {}\n self.replay_buffer_kwargs = replay_buffer_kwargs\n self._episode_storage = None\n\n # Save train freq parameter, will be converted later to TrainFreq object\n self.train_freq = train_freq\n\n self.actor = None # type: Optional[th.nn.Module]\n self.replay_buffer = None # type: Optional[ReplayBuffer]\n # Update policy keyword arguments\n if sde_support:\n self.policy_kwargs[\"use_sde\"] = self.use_sde\n # For gSDE only\n self.use_sde_at_warmup = use_sde_at_warmup\n\n def _convert_train_freq(self) -> None:\n \"\"\"\n Convert `train_freq` parameter (int or tuple)\n to a TrainFreq object.\n \"\"\"\n if not isinstance(self.train_freq, TrainFreq):\n train_freq = self.train_freq\n\n # The value of the train frequency will be checked later\n if not isinstance(train_freq, tuple):\n train_freq = (train_freq, \"step\")\n\n try:\n train_freq = (train_freq[0], TrainFrequencyUnit(train_freq[1]))\n except ValueError as e:\n raise ValueError(\n f\"The unit of the `train_freq` must be either 'step' or 'episode' not '{train_freq[1]}'!\"\n ) from e\n\n if not isinstance(train_freq[0], int):\n raise ValueError(f\"The frequency of `train_freq` must be an integer and not {train_freq[0]}\")\n\n self.train_freq = TrainFreq(*train_freq)\n\n def _setup_model(self) -> None:\n self._setup_lr_schedule()\n self.set_random_seed(self.seed)\n\n # Use DictReplayBuffer if needed\n if self.replay_buffer_class is None:\n if isinstance(self.observation_space, spaces.Dict):\n self.replay_buffer_class = DictReplayBuffer\n else:\n self.replay_buffer_class = ReplayBuffer\n\n elif self.replay_buffer_class == HerReplayBuffer:\n assert self.env is not None, \"You must pass an environment when using `HerReplayBuffer`\"\n\n # If using offline sampling, we need a classic replay buffer too\n if self.replay_buffer_kwargs.get(\"online_sampling\", True):\n replay_buffer = None\n else:\n replay_buffer = DictReplayBuffer(\n self.buffer_size,\n self.observation_space,\n self.action_space,\n device=self.device,\n optimize_memory_usage=self.optimize_memory_usage,\n )\n\n self.replay_buffer = HerReplayBuffer(\n self.env,\n self.buffer_size,\n device=self.device,\n replay_buffer=replay_buffer,\n **self.replay_buffer_kwargs,\n )\n\n if self.replay_buffer is None:\n self.replay_buffer = self.replay_buffer_class(\n self.buffer_size,\n self.observation_space,\n self.action_space,\n device=self.device,\n n_envs=self.n_envs,\n optimize_memory_usage=self.optimize_memory_usage,\n **self.replay_buffer_kwargs,\n )\n\n self.policy = self.policy_class( # pytype:disable=not-instantiable\n self.observation_space,\n self.action_space,\n self.lr_schedule,\n **self.policy_kwargs, # pytype:disable=not-instantiable\n )\n self.policy = self.policy.to(self.device)\n\n # Convert train freq parameter to TrainFreq object\n self._convert_train_freq()\n\n def save_replay_buffer(self, path: Union[str, pathlib.Path, io.BufferedIOBase]) -> None:\n \"\"\"\n Save the replay buffer as a pickle file.\n\n :param path: Path to the file where the replay buffer should be saved.\n if path is a str or pathlib.Path, the path is automatically created if necessary.\n \"\"\"\n assert self.replay_buffer is not None, \"The replay buffer is not defined\"\n save_to_pkl(path, self.replay_buffer, self.verbose)\n\n def load_replay_buffer(\n self,\n path: Union[str, pathlib.Path, io.BufferedIOBase],\n truncate_last_traj: bool = True,\n ) -> None:\n \"\"\"\n Load a replay buffer from a pickle file.\n\n :param path: Path to the pickled replay buffer.\n :param truncate_last_traj: When using ``HerReplayBuffer`` with online sampling:\n If set to ``True``, we assume that the last trajectory in the replay buffer was finished\n (and truncate it).\n If set to ``False``, we assume that we continue the same trajectory (same episode).\n \"\"\"\n self.replay_buffer = load_from_pkl(path, self.verbose)\n assert isinstance(self.replay_buffer, ReplayBuffer), \"The replay buffer must inherit from ReplayBuffer class\"\n\n # Backward compatibility with SB3 < 2.1.0 replay buffer\n # Keep old behavior: do not handle timeout termination separately\n if not hasattr(self.replay_buffer, \"handle_timeout_termination\"): # pragma: no cover\n self.replay_buffer.handle_timeout_termination = False\n self.replay_buffer.timeouts = np.zeros_like(self.replay_buffer.dones)\n\n if isinstance(self.replay_buffer, HerReplayBuffer):\n assert self.env is not None, \"You must pass an environment at load time when using `HerReplayBuffer`\"\n self.replay_buffer.set_env(self.get_env())\n if truncate_last_traj:\n self.replay_buffer.truncate_last_trajectory()\n\n def _setup_learn(\n self,\n total_timesteps: int,\n callback: MaybeCallback = None,\n reset_num_timesteps: bool = True,\n tb_log_name: str = \"run\",\n progress_bar: bool = False,\n ) -> Tuple[int, BaseCallback]:\n \"\"\"\n cf `BaseAlgorithm`.\n \"\"\"\n # Prevent continuity issue by truncating trajectory\n # when using memory efficient replay buffer\n # see https://github.com/DLR-RM/stable-baselines3/issues/46\n\n # Special case when using HerReplayBuffer,\n # the classic replay buffer is inside it when using offline sampling\n if isinstance(self.replay_buffer, HerReplayBuffer):\n replay_buffer = self.replay_buffer.replay_buffer\n else:\n replay_buffer = self.replay_buffer\n\n truncate_last_traj = (\n self.optimize_memory_usage\n and reset_num_timesteps\n and replay_buffer is not None\n and (replay_buffer.full or replay_buffer.pos > 0)\n )\n\n if truncate_last_traj:\n warnings.warn(\n \"The last trajectory in the replay buffer will be truncated, \"\n \"see https://github.com/DLR-RM/stable-baselines3/issues/46.\"\n \"You should use `reset_num_timesteps=False` or `optimize_memory_usage=False`\"\n \"to avoid that issue.\"\n )\n # Go to the previous index\n pos = (replay_buffer.pos - 1) % replay_buffer.buffer_size\n replay_buffer.dones[pos] = True\n\n return super()._setup_learn(\n total_timesteps,\n callback,\n reset_num_timesteps,\n tb_log_name,\n progress_bar,\n )\n\n def learn(\n self: SelfOffPolicyAlgorithm,\n total_timesteps: int,\n callback: MaybeCallback = None,\n log_interval: int = 4,\n tb_log_name: str = \"run\",\n reset_num_timesteps: bool = True,\n progress_bar: bool = False,\n ) -> SelfOffPolicyAlgorithm:\n\n total_timesteps, callback = self._setup_learn(\n total_timesteps,\n callback,\n reset_num_timesteps,\n tb_log_name,\n progress_bar,\n )\n\n callback.on_training_start(locals(), globals())\n\n while self.num_timesteps < total_timesteps:\n rollout = self.collect_rollouts(\n self.env,\n train_freq=self.train_freq,\n action_noise=self.action_noise,\n callback=callback,\n learning_starts=self.learning_starts,\n replay_buffer=self.replay_buffer,\n log_interval=log_interval,\n )\n\n if rollout.continue_training is False:\n break\n\n if self.num_timesteps > 0 and self.num_timesteps > self.learning_starts:\n # If no `gradient_steps` is specified,\n # do as many gradients steps as steps performed during the rollout\n gradient_steps = self.gradient_steps if self.gradient_steps >= 0 else rollout.episode_timesteps\n # Special case when the user passes `gradient_steps=0`\n if gradient_steps > 0:\n self.train(batch_size=self.batch_size, gradient_steps=gradient_steps)\n\n callback.on_training_end()\n\n return self\n\n def train(self, gradient_steps: int, batch_size: int) -> None:\n \"\"\"\n Sample the replay buffer and do the updates\n (gradient descent and update target networks)\n \"\"\"\n raise NotImplementedError()\n\n def _sample_action(\n self,\n learning_starts: int,\n action_noise: Optional[ActionNoise] = None,\n n_envs: int = 1,\n ) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Sample an action according to the exploration policy.\n This is either done by sampling the probability distribution of the policy,\n or sampling a random action (from a uniform distribution over the action space)\n or by adding noise to the deterministic output.\n\n :param action_noise: Action noise that will be used for exploration\n Required for deterministic policy (e.g. TD3). This can also be used\n in addition to the stochastic policy for SAC.\n :param learning_starts: Number of steps before learning for the warm-up phase.\n :param n_envs:\n :return: action to take in the environment\n and scaled action that will be stored in the replay buffer.\n The two differs when the action space is not normalized (bounds are not [-1, 1]).\n \"\"\"\n # Select action randomly or according to policy\n if self.num_timesteps < learning_starts and not (self.use_sde and self.use_sde_at_warmup):\n # Warmup phase\n unscaled_action = np.array([self.action_space.sample() for _ in range(n_envs)])\n else:\n # Note: when using continuous actions,\n # we assume that the policy uses tanh to scale the action\n # We use non-deterministic action in the case of SAC, for TD3, it does not matter\n unscaled_action, _ = self.predict(self._last_obs, deterministic=False)\n\n # Rescale the action from [low, high] to [-1, 1]\n if isinstance(self.action_space, spaces.Box):\n scaled_action = self.policy.scale_action(unscaled_action)\n\n # Add noise to the action (improve exploration)\n if action_noise is not None:\n scaled_action = np.clip(scaled_action + action_noise(), -1, 1)\n\n # We store the scaled action in the buffer\n buffer_action = scaled_action\n action = self.policy.unscale_action(scaled_action)\n else:\n # Discrete case, no need to normalize or clip\n buffer_action = unscaled_action\n action = buffer_action\n return action, buffer_action\n\n def _dump_logs(self) -> None:\n \"\"\"\n Write log.\n \"\"\"\n time_elapsed = max((time.time_ns() - self.start_time) / 1e9, sys.float_info.epsilon)\n fps = int((self.num_timesteps - self._num_timesteps_at_start) / time_elapsed)\n self.logger.record(\"time/episodes\", self._episode_num, exclude=\"tensorboard\")\n if len(self.ep_info_buffer) > 0 and len(self.ep_info_buffer[0]) > 0:\n self.logger.record(\"rollout/ep_rew_mean\", safe_mean([ep_info[\"r\"] for ep_info in self.ep_info_buffer]))\n self.logger.record(\"rollout/ep_len_mean\", safe_mean([ep_info[\"l\"] for ep_info in self.ep_info_buffer]))\n self.logger.record(\"time/fps\", fps)\n self.logger.record(\"time/time_elapsed\", int(time_elapsed), exclude=\"tensorboard\")\n self.logger.record(\"time/total_timesteps\", self.num_timesteps, exclude=\"tensorboard\")\n if self.use_sde:\n self.logger.record(\"train/std\", (self.actor.get_std()).mean().item())\n\n if len(self.ep_success_buffer) > 0:\n self.logger.record(\"rollout/success_rate\", safe_mean(self.ep_success_buffer))\n # Pass the number of timesteps for tensorboard\n self.logger.dump(step=self.num_timesteps)\n\n def _on_step(self) -> None:\n \"\"\"\n Method called after each step in the environment.\n It is meant to trigger DQN target network update\n but can be used for other purposes\n \"\"\"\n pass\n\n def _store_transition(\n self,\n replay_buffer: ReplayBuffer,\n buffer_action: np.ndarray,\n new_obs: Union[np.ndarray, Dict[str, np.ndarray]],\n reward: np.ndarray,\n dones: np.ndarray,\n infos: List[Dict[str, Any]],\n ) -> None:\n \"\"\"\n Store transition in the replay buffer.\n We store the normalized action and the unnormalized observation.\n It also handles terminal observations (because VecEnv resets automatically).\n\n :param replay_buffer: Replay buffer object where to store the transition.\n :param buffer_action: normalized action\n :param new_obs: next observation in the current episode\n or first observation of the episode (when dones is True)\n :param reward: reward for the current transition\n :param dones: Termination signal\n :param infos: List of additional information about the transition.\n It may contain the terminal observations and information about timeout.\n \"\"\"\n # Store only the unnormalized version\n if self._vec_normalize_env is not None:\n new_obs_ = self._vec_normalize_env.get_original_obs()\n reward_ = self._vec_normalize_env.get_original_reward()\n else:\n # Avoid changing the original ones\n self._last_original_obs, new_obs_, reward_ = self._last_obs, new_obs, reward\n\n # Avoid modification by reference\n next_obs = deepcopy(new_obs_)\n # As the VecEnv resets automatically, new_obs is already the\n # first observation of the next episode\n for i, done in enumerate(dones):\n if done and infos[i].get(\"terminal_observation\") is not None:\n if isinstance(next_obs, dict):\n next_obs_ = infos[i][\"terminal_observation\"]\n # VecNormalize normalizes the terminal observation\n if self._vec_normalize_env is not None:\n next_obs_ = self._vec_normalize_env.unnormalize_obs(next_obs_)\n # Replace next obs for the correct envs\n for key in next_obs.keys():\n next_obs[key][i] = next_obs_[key]\n else:\n next_obs[i] = infos[i][\"terminal_observation\"]\n # VecNormalize normalizes the terminal observation\n if self._vec_normalize_env is not None:\n next_obs[i] = self._vec_normalize_env.unnormalize_obs(next_obs[i, :])\n\n replay_buffer.add(\n self._last_original_obs,\n next_obs,\n buffer_action,\n reward_,\n dones,\n infos,\n )\n\n self._last_obs = new_obs\n # Save the unnormalized observation\n if self._vec_normalize_env is not None:\n self._last_original_obs = new_obs_\n\n def collect_rollouts(\n self,\n env: VecEnv,\n callback: BaseCallback,\n train_freq: TrainFreq,\n replay_buffer: ReplayBuffer,\n action_noise: Optional[ActionNoise] = None,\n learning_starts: int = 0,\n log_interval: Optional[int] = None,\n ) -> RolloutReturn:\n \"\"\"\n Collect experiences and store them into a ``ReplayBuffer``.\n\n :param env: The training environment\n :param callback: Callback that will be called at each step\n (and at the beginning and end of the rollout)\n :param train_freq: How much experience to collect\n by doing rollouts of current policy.\n Either ``TrainFreq(<n>, TrainFrequencyUnit.STEP)``\n or ``TrainFreq(<n>, TrainFrequencyUnit.EPISODE)``\n with ``<n>`` being an integer greater than 0.\n :param action_noise: Action noise that will be used for exploration\n Required for deterministic policy (e.g. TD3). This can also be used\n in addition to the stochastic policy for SAC.\n :param learning_starts: Number of steps before learning for the warm-up phase.\n :param replay_buffer:\n :param log_interval: Log data every ``log_interval`` episodes\n :return:\n \"\"\"\n # Switch to eval mode (this affects batch norm / dropout)\n self.policy.set_training_mode(False)\n\n num_collected_steps, num_collected_episodes = 0, 0\n\n assert isinstance(env, VecEnv), \"You must pass a VecEnv\"\n assert train_freq.frequency > 0, \"Should at least collect one step or episode.\"\n\n if env.num_envs > 1:\n assert train_freq.unit == TrainFrequencyUnit.STEP, \"You must use only one env when doing episodic training.\"\n\n # Vectorize action noise if needed\n if action_noise is not None and env.num_envs > 1 and not isinstance(action_noise, VectorizedActionNoise):\n action_noise = VectorizedActionNoise(action_noise, env.num_envs)\n\n if self.use_sde:\n self.actor.reset_noise(env.num_envs)\n\n callback.on_rollout_start()\n continue_training = True\n\n while should_collect_more_steps(train_freq, num_collected_steps, num_collected_episodes):\n if self.use_sde and self.sde_sample_freq > 0 and num_collected_steps % self.sde_sample_freq == 0:\n # Sample a new noise matrix\n self.actor.reset_noise(env.num_envs)\n\n # Select action randomly or according to policy\n actions, buffer_actions = self._sample_action(learning_starts, action_noise, env.num_envs)\n\n # Rescale and perform action\n new_obs, rewards, dones, infos = env.step(actions)\n\n self.num_timesteps += env.num_envs\n num_collected_steps += 1\n\n # Give access to local variables\n callback.update_locals(locals())\n # Only stop training if return value is False, not when it is None.\n if callback.on_step() is False:\n return RolloutReturn(num_collected_steps * env.num_envs, num_collected_episodes, continue_training=False)\n\n # Retrieve reward and episode length if using Monitor wrapper\n self._update_info_buffer(infos, dones)\n\n # Store data in replay buffer (normalized action and unnormalized observation)\n self._store_transition(replay_buffer, buffer_actions, new_obs, rewards, dones, infos)\n\n self._update_current_progress_remaining(self.num_timesteps, self._total_timesteps)\n\n # For DQN, check if the target network should be updated\n # and update the exploration schedule\n # For SAC/TD3, the update is dones as the same time as the gradient update\n # see https://github.com/hill-a/stable-baselines/issues/900\n self._on_step()\n\n for idx, done in enumerate(dones):\n if done:\n # Update stats\n num_collected_episodes += 1\n self._episode_num += 1\n\n if action_noise is not None:\n kwargs = dict(indices=[idx]) if env.num_envs > 1 else {}\n action_noise.reset(**kwargs)\n\n # Log training infos\n if log_interval is not None and self._episode_num % log_interval == 0:\n self._dump_logs()\n callback.on_rollout_end()\n\n return RolloutReturn(num_collected_steps * env.num_envs, num_collected_episodes, continue_training)" }, { "identifier": "BasePolicy", "path": "stable_baselines3/common/policies.py", "snippet": "class BasePolicy(BaseModel, ABC):\n \"\"\"The base policy object.\n\n Parameters are mostly the same as `BaseModel`; additions are documented below.\n\n :param args: positional arguments passed through to `BaseModel`.\n :param kwargs: keyword arguments passed through to `BaseModel`.\n :param squash_output: For continuous actions, whether the output is squashed\n or not using a ``tanh()`` function.\n \"\"\"\n\n def __init__(self, *args, squash_output: bool = False, **kwargs):\n super().__init__(*args, **kwargs)\n self._squash_output = squash_output\n\n @staticmethod\n def _dummy_schedule(progress_remaining: float) -> float:\n \"\"\"(float) Useful for pickling policy.\"\"\"\n del progress_remaining\n return 0.0\n\n @property\n def squash_output(self) -> bool:\n \"\"\"(bool) Getter for squash_output.\"\"\"\n return self._squash_output\n\n @staticmethod\n def init_weights(module: nn.Module, gain: float = 1) -> None:\n \"\"\"\n Orthogonal initialization (used in PPO and A2C)\n \"\"\"\n if isinstance(module, (nn.Linear, nn.Conv2d)):\n nn.init.orthogonal_(module.weight, gain=gain)\n if module.bias is not None:\n module.bias.data.fill_(0.0)\n\n @abstractmethod\n def _predict(self, observation: th.Tensor, deterministic: bool = False) -> th.Tensor:\n \"\"\"\n Get the action according to the policy for a given observation.\n\n By default provides a dummy implementation -- not all BasePolicy classes\n implement this, e.g. if they are a Critic in an Actor-Critic method.\n\n :param observation:\n :param deterministic: Whether to use stochastic or deterministic actions\n :return: Taken action according to the policy\n \"\"\"\n\n def predict(\n self,\n observation: Union[np.ndarray, Dict[str, np.ndarray]],\n state: Optional[Tuple[np.ndarray, ...]] = None,\n episode_start: Optional[np.ndarray] = None,\n deterministic: bool = False,\n ) -> Tuple[np.ndarray, Optional[Tuple[np.ndarray, ...]]]:\n \"\"\"\n Get the policy action from an observation (and optional hidden state).\n Includes sugar-coating to handle different observations (e.g. normalizing images).\n\n :param observation: the input observation\n :param state: The last hidden states (can be None, used in recurrent policies)\n :param episode_start: The last masks (can be None, used in recurrent policies)\n this correspond to beginning of episodes,\n where the hidden states of the RNN must be reset.\n :param deterministic: Whether or not to return deterministic actions.\n :return: the model's action and the next hidden state\n (used in recurrent policies)\n \"\"\"\n # TODO (GH/1): add support for RNN policies\n # if state is None:\n # state = self.initial_state\n # if episode_start is None:\n # episode_start = [False for _ in range(self.n_envs)]\n # Switch to eval mode (this affects batch norm / dropout)\n self.set_training_mode(False)\n\n observation, vectorized_env = self.obs_to_tensor(observation)\n\n with th.no_grad():\n actions = self._predict(observation, deterministic=deterministic)\n # Convert to numpy, and reshape to the original action shape\n actions = actions.cpu().numpy().reshape((-1,) + self.action_space.shape)\n\n if isinstance(self.action_space, spaces.Box):\n if self.squash_output:\n # Rescale to proper domain when using squashing\n actions = self.unscale_action(actions)\n else:\n # Actions could be on arbitrary scale, so clip the actions to avoid\n # out of bound error (e.g. if sampling from a Gaussian distribution)\n actions = np.clip(actions, self.action_space.low, self.action_space.high)\n\n # Remove batch dimension if needed\n if not vectorized_env:\n actions = actions.squeeze(axis=0)\n\n return actions, state\n\n def scale_action(self, action: np.ndarray) -> np.ndarray:\n \"\"\"\n Rescale the action from [low, high] to [-1, 1]\n (no need for symmetric action space)\n\n :param action: Action to scale\n :return: Scaled action\n \"\"\"\n low, high = self.action_space.low, self.action_space.high\n return 2.0 * ((action - low) / (high - low)) - 1.0\n\n def unscale_action(self, scaled_action: np.ndarray) -> np.ndarray:\n \"\"\"\n Rescale the action from [-1, 1] to [low, high]\n (no need for symmetric action space)\n\n :param scaled_action: Action to un-scale\n \"\"\"\n low, high = self.action_space.low, self.action_space.high\n return low + (0.5 * (scaled_action + 1.0) * (high - low))" }, { "identifier": "maybe_transpose", "path": "stable_baselines3/common/preprocessing.py", "snippet": "def maybe_transpose(observation: np.ndarray, observation_space: spaces.Space) -> np.ndarray:\n \"\"\"\n Handle the different cases for images as PyTorch use channel first format.\n\n :param observation:\n :param observation_space:\n :return: channel first observation if observation is an image\n \"\"\"\n # Avoid circular import\n from stable_baselines3.common.vec_env import VecTransposeImage\n\n if is_image_space(observation_space):\n if not (observation.shape == observation_space.shape or observation.shape[1:] == observation_space.shape):\n # Try to re-order the channels\n transpose_obs = VecTransposeImage.transpose_image(observation)\n if transpose_obs.shape == observation_space.shape or transpose_obs.shape[1:] == observation_space.shape:\n observation = transpose_obs\n return observation" }, { "identifier": "GymEnv", "path": "stable_baselines3/common/type_aliases.py", "snippet": "class RolloutBufferSamples(NamedTuple):\nclass DictRolloutBufferSamples(NamedTuple):\nclass ReplayBufferSamples(NamedTuple):\nclass DictReplayBufferSamples(NamedTuple):\nclass RolloutReturn(NamedTuple):\nclass TrainFrequencyUnit(Enum):\nclass TrainFreq(NamedTuple):\nclass PolicyPredictor(Protocol):\n STEP = \"step\"\n EPISODE = \"episode\"\n def predict(\n self,\n observation: Union[np.ndarray, Dict[str, np.ndarray]],\n state: Optional[Tuple[np.ndarray, ...]] = None,\n episode_start: Optional[np.ndarray] = None,\n deterministic: bool = False,\n ) -> Tuple[np.ndarray, Optional[Tuple[np.ndarray, ...]]]:" }, { "identifier": "get_linear_fn", "path": "stable_baselines3/common/utils.py", "snippet": "def get_linear_fn(start: float, end: float, end_fraction: float) -> Schedule:\n \"\"\"\n Create a function that interpolates linearly between start and end\n between ``progress_remaining`` = 1 and ``progress_remaining`` = ``end_fraction``.\n This is used in DQN for linearly annealing the exploration fraction\n (epsilon for the epsilon-greedy strategy).\n\n :params start: value to start with if ``progress_remaining`` = 1\n :params end: value to end with if ``progress_remaining`` = 0\n :params end_fraction: fraction of ``progress_remaining``\n where end is reached e.g 0.1 then end is reached after 10%\n of the complete training process.\n :return: Linear schedule function.\n \"\"\"\n\n def func(progress_remaining: float) -> float:\n if (1 - progress_remaining) > end_fraction:\n return end\n else:\n return start + (1 - progress_remaining) * (end - start) / end_fraction\n\n return func" }, { "identifier": "get_parameters_by_name", "path": "stable_baselines3/common/utils.py", "snippet": "def get_parameters_by_name(model: th.nn.Module, included_names: Iterable[str]) -> List[th.Tensor]:\n \"\"\"\n Extract parameters from the state dict of ``model``\n if the name contains one of the strings in ``included_names``.\n\n :param model: the model where the parameters come from.\n :param included_names: substrings of names to include.\n :return: List of parameters values (Pytorch tensors)\n that matches the queried names.\n \"\"\"\n return [param for name, param in model.state_dict().items() if any([key in name for key in included_names])]" }, { "identifier": "is_vectorized_observation", "path": "stable_baselines3/common/utils.py", "snippet": "def is_vectorized_observation(observation: Union[int, np.ndarray], observation_space: spaces.Space) -> bool:\n \"\"\"\n For every observation type, detects and validates the shape,\n then returns whether or not the observation is vectorized.\n\n :param observation: the input observation to validate\n :param observation_space: the observation space\n :return: whether the given observation is vectorized or not\n \"\"\"\n\n is_vec_obs_func_dict = {\n spaces.Box: is_vectorized_box_observation,\n spaces.Discrete: is_vectorized_discrete_observation,\n spaces.MultiDiscrete: is_vectorized_multidiscrete_observation,\n spaces.MultiBinary: is_vectorized_multibinary_observation,\n spaces.Dict: is_vectorized_dict_observation,\n }\n\n for space_type, is_vec_obs_func in is_vec_obs_func_dict.items():\n if isinstance(observation_space, space_type):\n return is_vec_obs_func(observation, observation_space)\n else:\n # for-else happens if no break is called\n raise ValueError(f\"Error: Cannot determine if the observation is vectorized with the space type {observation_space}.\")" }, { "identifier": "polyak_update", "path": "stable_baselines3/common/utils.py", "snippet": "def polyak_update(\n params: Iterable[th.Tensor],\n target_params: Iterable[th.Tensor],\n tau: float,\n) -> None:\n \"\"\"\n Perform a Polyak average update on ``target_params`` using ``params``:\n target parameters are slowly updated towards the main parameters.\n ``tau``, the soft update coefficient controls the interpolation:\n ``tau=1`` corresponds to copying the parameters to the target ones whereas nothing happens when ``tau=0``.\n The Polyak update is done in place, with ``no_grad``, and therefore does not create intermediate tensors,\n or a computation graph, reducing memory cost and improving performance. We scale the target params\n by ``1-tau`` (in-place), add the new weights, scaled by ``tau`` and store the result of the sum in the target\n params (in place).\n See https://github.com/DLR-RM/stable-baselines3/issues/93\n\n :param params: parameters to use to update the target params\n :param target_params: parameters to update\n :param tau: the soft update coefficient (\"Polyak update\", between 0 and 1)\n \"\"\"\n with th.no_grad():\n # zip does not raise an exception if length of parameters does not match.\n for param, target_param in zip_strict(params, target_params):\n target_param.data.mul_(1 - tau)\n th.add(target_param.data, param.data, alpha=tau, out=target_param.data)" }, { "identifier": "CnnPolicy", "path": "stable_baselines3/dqn_ME/policies_ME.py", "snippet": "class QNetwork(BasePolicy):\nclass DQNPolicy(BasePolicy):\nclass CnnPolicy(DQNPolicy):\nclass MultiInputPolicy(DQNPolicy):\n def __init__(\n self,\n observation_space: spaces.Space,\n action_space: spaces.Space,\n features_extractor: nn.Module,\n features_dim: int,\n net_arch: Optional[List[int]] = None,\n activation_fn: Type[nn.Module] = nn.ReLU,\n normalize_images: bool = True,\n ):\n def forward(self, obs: th.Tensor) -> th.Tensor:\n def _predict(self, observation: th.Tensor, deterministic: bool = False) -> th.Tensor:\n def _get_constructor_parameters(self) -> Dict[str, Any]:\n def __init__(\n self,\n observation_space: spaces.Space,\n action_space: spaces.Space,\n lr_schedule: Schedule,\n net_arch: Optional[List[int]] = None,\n activation_fn: Type[nn.Module] = nn.ReLU,\n features_extractor_class: Type[BaseFeaturesExtractor] = FlattenExtractor,\n features_extractor_kwargs: Optional[Dict[str, Any]] = None,\n normalize_images: bool = True,\n optimizer_class: Type[th.optim.Optimizer] = th.optim.Adam,\n optimizer_kwargs: Optional[Dict[str, Any]] = None,\n ):\n def _build(self, lr_schedule: Schedule) -> None:\n def make_q_net(self) -> QNetwork:\n def forward(self, obs: th.Tensor, deterministic: bool = True) -> th.Tensor:\n def _predict(self, obs: th.Tensor, deterministic: bool = True) -> th.Tensor:\n def _get_constructor_parameters(self) -> Dict[str, Any]:\n def predict_logprob(self, observation: th.Tensor) -> th.Tensor:\n def set_training_mode(self, mode: bool) -> None:\n def __init__(\n self,\n observation_space: spaces.Space,\n action_space: spaces.Space,\n lr_schedule: Schedule,\n net_arch: Optional[List[int]] = None,\n activation_fn: Type[nn.Module] = nn.ReLU,\n features_extractor_class: Type[BaseFeaturesExtractor] = NatureCNN,\n features_extractor_kwargs: Optional[Dict[str, Any]] = None,\n normalize_images: bool = True,\n optimizer_class: Type[th.optim.Optimizer] = th.optim.Adam,\n optimizer_kwargs: Optional[Dict[str, Any]] = None,\n ):\n def __init__(\n self,\n observation_space: spaces.Dict,\n action_space: spaces.Space,\n lr_schedule: Schedule,\n net_arch: Optional[List[int]] = None,\n activation_fn: Type[nn.Module] = nn.ReLU,\n features_extractor_class: Type[BaseFeaturesExtractor] = CombinedExtractor,\n features_extractor_kwargs: Optional[Dict[str, Any]] = None,\n normalize_images: bool = True,\n optimizer_class: Type[th.optim.Optimizer] = th.optim.Adam,\n optimizer_kwargs: Optional[Dict[str, Any]] = None,\n ):" }, { "identifier": "DQN", "path": "stable_baselines3/dqn/dqn.py", "snippet": "class DQN(OffPolicyAlgorithm):\n \"\"\"\n Deep Q-Network (DQN)\n\n Paper: https://arxiv.org/abs/1312.5602, https://www.nature.com/articles/nature14236\n Default hyperparameters are taken from the Nature paper,\n except for the optimizer and learning rate that were taken from Stable Baselines defaults.\n\n :param policy: The policy model to use (MlpPolicy, CnnPolicy, ...)\n :param env: The environment to learn from (if registered in Gym, can be str)\n :param learning_rate: The learning rate, it can be a function\n of the current progress remaining (from 1 to 0)\n :param buffer_size: size of the replay buffer\n :param learning_starts: how many steps of the model to collect transitions for before learning starts\n :param batch_size: Minibatch size for each gradient update\n :param tau: the soft update coefficient (\"Polyak update\", between 0 and 1) default 1 for hard update\n :param gamma: the discount factor\n :param train_freq: Update the model every ``train_freq`` steps. Alternatively pass a tuple of frequency and unit\n like ``(5, \"step\")`` or ``(2, \"episode\")``.\n :param gradient_steps: How many gradient steps to do after each rollout (see ``train_freq``)\n Set to ``-1`` means to do as many gradient steps as steps done in the environment\n during the rollout.\n :param replay_buffer_class: Replay buffer class to use (for instance ``HerReplayBuffer``).\n If ``None``, it will be automatically selected.\n :param replay_buffer_kwargs: Keyword arguments to pass to the replay buffer on creation.\n :param optimize_memory_usage: Enable a memory efficient variant of the replay buffer\n at a cost of more complexity.\n See https://github.com/DLR-RM/stable-baselines3/issues/37#issuecomment-637501195\n :param target_update_interval: update the target network every ``target_update_interval``\n environment steps.\n :param exploration_fraction: fraction of entire training period over which the exploration rate is reduced\n :param exploration_initial_eps: initial value of random action probability\n :param exploration_final_eps: final value of random action probability\n :param max_grad_norm: The maximum value for the gradient clipping\n :param tensorboard_log: the log location for tensorboard (if None, no logging)\n :param policy_kwargs: additional arguments to be passed to the policy on creation\n :param verbose: Verbosity level: 0 for no output, 1 for info messages (such as device or wrappers used), 2 for\n debug messages\n :param seed: Seed for the pseudo random generators\n :param device: Device (cpu, cuda, ...) on which the code should be run.\n Setting it to auto, the code will be run on the GPU if possible.\n :param _init_setup_model: Whether or not to build the network at the creation of the instance\n \"\"\"\n\n policy_aliases: Dict[str, Type[BasePolicy]] = {\n \"MlpPolicy\": MlpPolicy,\n \"CnnPolicy\": CnnPolicy,\n \"MultiInputPolicy\": MultiInputPolicy,\n }\n\n def __init__(\n self,\n policy: Union[str, Type[DQNPolicy]],\n env: Union[GymEnv, str],\n learning_rate: Union[float, Schedule] = 1e-4,\n buffer_size: int = 1_000_000, # 1e6\n learning_starts: int = 50000,\n batch_size: int = 32,\n tau: float = 1.0,\n gamma: float = 0.99,\n train_freq: Union[int, Tuple[int, str]] = 4,\n gradient_steps: int = 1,\n replay_buffer_class: Optional[Type[ReplayBuffer]] = None,\n replay_buffer_kwargs: Optional[Dict[str, Any]] = None,\n optimize_memory_usage: bool = False,\n target_update_interval: int = 10000,\n exploration_fraction: float = 0.1,\n exploration_initial_eps: float = 1.0,\n exploration_final_eps: float = 0.05,\n max_grad_norm: float = 10,\n tensorboard_log: Optional[str] = None,\n policy_kwargs: Optional[Dict[str, Any]] = None,\n verbose: int = 0,\n seed: Optional[int] = None,\n device: Union[th.device, str] = \"auto\",\n _init_setup_model: bool = True,\n ):\n\n super().__init__(\n policy,\n env,\n learning_rate,\n buffer_size,\n learning_starts,\n batch_size,\n tau,\n gamma,\n train_freq,\n gradient_steps,\n action_noise=None, # No action noise\n replay_buffer_class=replay_buffer_class,\n replay_buffer_kwargs=replay_buffer_kwargs,\n policy_kwargs=policy_kwargs,\n tensorboard_log=tensorboard_log,\n verbose=verbose,\n device=device,\n seed=seed,\n sde_support=False,\n optimize_memory_usage=optimize_memory_usage,\n supported_action_spaces=(spaces.Discrete,),\n support_multi_env=True,\n )\n\n self.exploration_initial_eps = exploration_initial_eps\n self.exploration_final_eps = exploration_final_eps\n self.exploration_fraction = exploration_fraction\n self.target_update_interval = target_update_interval\n # For updating the target network with multiple envs:\n self._n_calls = 0\n self.max_grad_norm = max_grad_norm\n # \"epsilon\" for the epsilon-greedy exploration\n self.exploration_rate = 0.0\n # Linear schedule will be defined in `_setup_model()`\n self.exploration_schedule = None\n self.q_net, self.q_net_target = None, None\n\n if _init_setup_model:\n self._setup_model()\n\n def _setup_model(self) -> None:\n super()._setup_model()\n self._create_aliases()\n # Copy running stats, see GH issue #996\n self.batch_norm_stats = get_parameters_by_name(self.q_net, [\"running_\"])\n self.batch_norm_stats_target = get_parameters_by_name(self.q_net_target, [\"running_\"])\n self.exploration_schedule = get_linear_fn(\n self.exploration_initial_eps,\n self.exploration_final_eps,\n self.exploration_fraction,\n )\n # Account for multiple environments\n # each call to step() corresponds to n_envs transitions\n if self.n_envs > 1:\n if self.n_envs > self.target_update_interval:\n warnings.warn(\n \"The number of environments used is greater than the target network \"\n f\"update interval ({self.n_envs} > {self.target_update_interval}), \"\n \"therefore the target network will be updated after each call to env.step() \"\n f\"which corresponds to {self.n_envs} steps.\"\n )\n\n self.target_update_interval = max(self.target_update_interval // self.n_envs, 1)\n\n def _create_aliases(self) -> None:\n self.q_net = self.policy.q_net\n self.q_net_target = self.policy.q_net_target\n\n def _on_step(self) -> None:\n \"\"\"\n Update the exploration rate and target network if needed.\n This method is called in ``collect_rollouts()`` after each step in the environment.\n \"\"\"\n self._n_calls += 1\n if self._n_calls % self.target_update_interval == 0:\n polyak_update(self.q_net.parameters(), self.q_net_target.parameters(), self.tau)\n # Copy running stats, see GH issue #996\n polyak_update(self.batch_norm_stats, self.batch_norm_stats_target, 1.0)\n\n self.exploration_rate = self.exploration_schedule(self._current_progress_remaining)\n self.logger.record(\"rollout/exploration_rate\", self.exploration_rate)\n\n def train(self, gradient_steps: int, batch_size: int = 100) -> None:\n # Switch to train mode (this affects batch norm / dropout)\n self.policy.set_training_mode(True)\n # Update learning rate according to schedule\n self._update_learning_rate(self.policy.optimizer)\n\n losses = []\n for _ in range(gradient_steps):\n # Sample replay buffer\n replay_data = self.replay_buffer.sample(batch_size, env=self._vec_normalize_env)\n\n with th.no_grad():\n # Compute the next Q-values using the target network\n next_q_values = self.q_net_target(replay_data.next_observations)\n # Follow greedy policy: use the one with the highest value\n next_q_values, _ = next_q_values.max(dim=1)\n # Avoid potential broadcast issue\n next_q_values = next_q_values.reshape(-1, 1)\n # 1-step TD target\n target_q_values = replay_data.rewards + (1 - replay_data.dones) * self.gamma * next_q_values\n\n # Get current Q-values estimates\n current_q_values = self.q_net(replay_data.observations)\n\n # Retrieve the q-values for the actions from the replay buffer\n current_q_values = th.gather(current_q_values, dim=1, index=replay_data.actions.long())\n\n # Compute Huber loss (less sensitive to outliers)\n loss = F.smooth_l1_loss(current_q_values, target_q_values)\n losses.append(loss.item())\n\n # Optimize the policy\n self.policy.optimizer.zero_grad()\n loss.backward()\n # Clip gradient norm\n th.nn.utils.clip_grad_norm_(self.policy.parameters(), self.max_grad_norm)\n self.policy.optimizer.step()\n\n # Increase update counter\n self._n_updates += gradient_steps\n\n self.logger.record(\"train/n_updates\", self._n_updates, exclude=\"tensorboard\")\n self.logger.record(\"train/loss\", np.mean(losses))\n\n def predict(\n self,\n observation: Union[np.ndarray, Dict[str, np.ndarray]],\n state: Optional[Tuple[np.ndarray, ...]] = None,\n episode_start: Optional[np.ndarray] = None,\n deterministic: bool = False,\n ) -> Tuple[np.ndarray, Optional[Tuple[np.ndarray, ...]]]:\n \"\"\"\n Overrides the base_class predict function to include epsilon-greedy exploration.\n\n :param observation: the input observation\n :param state: The last states (can be None, used in recurrent policies)\n :param episode_start: The last masks (can be None, used in recurrent policies)\n :param deterministic: Whether or not to return deterministic actions.\n :return: the model's action and the next state\n (used in recurrent policies)\n \"\"\"\n if not deterministic and np.random.rand() < self.exploration_rate:\n if is_vectorized_observation(maybe_transpose(observation, self.observation_space), self.observation_space):\n if isinstance(observation, dict):\n n_batch = observation[list(observation.keys())[0]].shape[0]\n else:\n n_batch = observation.shape[0]\n action = np.array([self.action_space.sample() for _ in range(n_batch)])\n else:\n action = np.array(self.action_space.sample())\n else:\n action, state = self.policy.predict(observation, state, episode_start, deterministic)\n return action, state\n\n def learn(\n self: SelfDQN,\n total_timesteps: int,\n callback: MaybeCallback = None,\n log_interval: int = 4,\n tb_log_name: str = \"DQN\",\n reset_num_timesteps: bool = True,\n progress_bar: bool = False,\n ) -> SelfDQN:\n\n return super().learn(\n total_timesteps=total_timesteps,\n callback=callback,\n log_interval=log_interval,\n tb_log_name=tb_log_name,\n reset_num_timesteps=reset_num_timesteps,\n progress_bar=progress_bar,\n )\n\n def _excluded_save_params(self) -> List[str]:\n return super()._excluded_save_params() + [\"q_net\", \"q_net_target\"]\n\n def _get_torch_save_params(self) -> Tuple[List[str], List[str]]:\n state_dicts = [\"policy\", \"policy.optimizer\"]\n\n return state_dicts, []" } ]
import warnings import numpy as np import torch as th from typing import Any, Dict, List, Optional, Tuple, Type, TypeVar, Union from gym import spaces from torch.nn import functional as F from stable_baselines3.common.buffers import ReplayBuffer from stable_baselines3.common.off_policy_algorithm import OffPolicyAlgorithm from stable_baselines3.common.policies import BasePolicy from stable_baselines3.common.preprocessing import maybe_transpose from stable_baselines3.common.type_aliases import GymEnv, MaybeCallback, Schedule from stable_baselines3.common.utils import get_linear_fn, get_parameters_by_name, is_vectorized_observation, polyak_update from stable_baselines3.dqn_ME.policies_ME import CnnPolicy, DQNPolicy, MlpPolicy, MultiInputPolicy from stable_baselines3.dqn.dqn import DQN
16,038
:param exploration_final_eps: final value of random action probability :param max_grad_norm: The maximum value for the gradient clipping :param tensorboard_log: the lonext_q_valuesg location for tensorboard (if None, no logging) :param policy_kwargs: additionnext_q_valuesal arguments to be passed to the policy on creation :param verbose: Verbosity levenext_q_valuesl: 0 for no output, 1 for info messages (such as device or wrappers used), 2 for debug messagesnext_q_values :param seed: Seed for the pseunext_q_valuesdo random generators :param device: Device (cpu, cuda, ...) on which the code should be run. Setting it to auto, the code will be run on the GPU if possible. :param _init_setup_model: Whether or not to build the network at the creation of the instance """ policy_aliases: Dict[str, Type[BasePolicy]] = { "MlpPolicy": MlpPolicy, "CnnPolicy": CnnPolicy, "MultiInputPolicy": MultiInputPolicy, } def __init__( self, policy: Union[str, Type[DQNPolicy]], env: Union[GymEnv, str], learning_rate: Union[float, Schedule] = 1e-4, buffer_size: int = 1_000_000, # 1e6 learning_starts: int = 50000, batch_size: int = 32, tau: float = 1.0, gamma: float = 0.99, train_freq: Union[int, Tuple[int, str]] = 4, gradient_steps: int = 1, replay_buffer_class: Optional[Type[ReplayBuffer]] = None, replay_buffer_kwargs: Optional[Dict[str, Any]] = None, optimize_memory_usage: bool = False, target_update_interval: int = 10000, exploration_fraction: float = 0.1, exploration_initial_eps: float = 1.0, exploration_final_eps: float = 0.05, max_grad_norm: float = 10, tensorboard_log: Optional[str] = None, policy_kwargs: Optional[Dict[str, Any]] = None, verbose: int = 0, seed: Optional[int] = None, device: Union[th.device, str] = "auto", _init_setup_model: bool = True, ): super().__init__( policy, env, learning_rate, buffer_size, learning_starts, batch_size, tau, gamma, train_freq, gradient_steps, replay_buffer_class=replay_buffer_class, replay_buffer_kwargs=replay_buffer_kwargs, optimize_memory_usage=optimize_memory_usage, target_update_interval=target_update_interval, exploration_fraction=exploration_fraction, exploration_initial_eps=exploration_initial_eps, exploration_final_eps=exploration_final_eps, max_grad_norm=max_grad_norm, tensorboard_log=tensorboard_log, policy_kwargs=policy_kwargs, verbose=verbose, seed=seed, device=device, _init_setup_model=_init_setup_model, ) def train(self, gradient_steps: int, batch_size: int = 100) -> None: # Switch to train mode (this affects batch norm / dropout) self.policy.set_training_mode(True) # Update learning rate according to schedule self._update_learning_rate(self.policy.optimizer) losses = [] for _ in range(gradient_steps): # Sample replay buffer replay_data = self.replay_buffer.sample(batch_size, env=self._vec_normalize_env) with th.no_grad(): # Compute the next Q-values using the target network next_q_values = self.q_net_target(replay_data.next_observations) # Compute the next soft value function by taking the log-sum-exp of the next Q-values next_q_values = th.logsumexp(next_q_values, 1) # Avoid potential broadcast issue next_q_values = next_q_values.reshape(-1, 1) # 1-step TD target target_q_values = replay_data.rewards + (1 - replay_data.dones) * self.gamma * next_q_values # Get current Q-values estimates current_q_values = self.q_net(replay_data.observations) # Retrieve the q-values for the actions from the replay buffer current_q_values = th.gather(current_q_values, dim=1, index=replay_data.actions.long()) # Compute Huber loss (less sensitive to outliers) loss = F.smooth_l1_loss(current_q_values, target_q_values) losses.append(loss.item()) # Optimize the policy self.policy.optimizer.zero_grad() loss.backward() # Clip gradient norm th.nn.utils.clip_grad_norm_(self.policy.parameters(), self.max_grad_norm) self.policy.optimizer.step() # Increase update counter self._n_updates += gradient_steps self.logger.record("train/n_updates", self._n_updates, exclude="tensorboard") self.logger.record("train/loss", np.mean(losses)) def learn( self: SelfDQN_ME, total_timesteps: int,
SelfDQN_ME = TypeVar("SelfDQN_ME", bound="DQN_ME") class DQN_ME(DQN): """ Soft Deep Q-Network (i.e. entropy-regularized DQN) Paper: https://arxiv.org/abs/1312.5602, https://www.nature.com/articles/nature14236, https://arxiv.org/abs/1702.08165 Default hyperparameters are taken from the Nature paper, except for the optimizer and learning rate that were taken from Stable Baselines defaults. :param policy: The policy model to use (MlpPolicy, CnnPolicy, ...) :param env: The environment to learn from (if registered in Gym, can be str) :param learning_rate: The learning rate, it can be a function of the current progress remaining (from 1 to 0) :param buffer_size: size of the replay buffer :param learning_starts: how many steps of the model to collect transitions for before learning starts :param batch_size: Minibatch size for each gradient update :param tau: the soft update coefficient ("Polyak update", between 0 and 1) default 1 for hard update :param gamma: the discount factor :param train_freq: Update the model every ``train_freq`` steps. Alternatively pass a tuple of frequency and unit like ``(5, "step")`` or ``(2, "episode")``. :param gradient_steps: How many gradient steps to do after each rollout (see ``train_freq``) Set to ``-1`` means to do as many gradient steps as steps done in the environment during the rollout. :param replay_buffer_class: Replay buffer class to use (for instance ``HerReplayBuffer``). If ``None``, it will be automatically selected. :param replay_buffer_kwargs: Keyword arguments to pass to the replay buffer on creation. :param optimize_memory_usage: Enable a memory efficient variant of the replay buffer at a cost of more complexity. See https://github.com/DLR-RM/stable-baselines3/issues/37#issuecomment-637501195 :param target_update_interval: update the target network every ``target_update_interval`` environment steps. :param exploration_fraction: fraction of entire training period over which the exploration rate is reduced :param exploration_initial_eps: initial value of random action probability :param exploration_final_eps: final value of random action probability :param max_grad_norm: The maximum value for the gradient clipping :param tensorboard_log: the lonext_q_valuesg location for tensorboard (if None, no logging) :param policy_kwargs: additionnext_q_valuesal arguments to be passed to the policy on creation :param verbose: Verbosity levenext_q_valuesl: 0 for no output, 1 for info messages (such as device or wrappers used), 2 for debug messagesnext_q_values :param seed: Seed for the pseunext_q_valuesdo random generators :param device: Device (cpu, cuda, ...) on which the code should be run. Setting it to auto, the code will be run on the GPU if possible. :param _init_setup_model: Whether or not to build the network at the creation of the instance """ policy_aliases: Dict[str, Type[BasePolicy]] = { "MlpPolicy": MlpPolicy, "CnnPolicy": CnnPolicy, "MultiInputPolicy": MultiInputPolicy, } def __init__( self, policy: Union[str, Type[DQNPolicy]], env: Union[GymEnv, str], learning_rate: Union[float, Schedule] = 1e-4, buffer_size: int = 1_000_000, # 1e6 learning_starts: int = 50000, batch_size: int = 32, tau: float = 1.0, gamma: float = 0.99, train_freq: Union[int, Tuple[int, str]] = 4, gradient_steps: int = 1, replay_buffer_class: Optional[Type[ReplayBuffer]] = None, replay_buffer_kwargs: Optional[Dict[str, Any]] = None, optimize_memory_usage: bool = False, target_update_interval: int = 10000, exploration_fraction: float = 0.1, exploration_initial_eps: float = 1.0, exploration_final_eps: float = 0.05, max_grad_norm: float = 10, tensorboard_log: Optional[str] = None, policy_kwargs: Optional[Dict[str, Any]] = None, verbose: int = 0, seed: Optional[int] = None, device: Union[th.device, str] = "auto", _init_setup_model: bool = True, ): super().__init__( policy, env, learning_rate, buffer_size, learning_starts, batch_size, tau, gamma, train_freq, gradient_steps, replay_buffer_class=replay_buffer_class, replay_buffer_kwargs=replay_buffer_kwargs, optimize_memory_usage=optimize_memory_usage, target_update_interval=target_update_interval, exploration_fraction=exploration_fraction, exploration_initial_eps=exploration_initial_eps, exploration_final_eps=exploration_final_eps, max_grad_norm=max_grad_norm, tensorboard_log=tensorboard_log, policy_kwargs=policy_kwargs, verbose=verbose, seed=seed, device=device, _init_setup_model=_init_setup_model, ) def train(self, gradient_steps: int, batch_size: int = 100) -> None: # Switch to train mode (this affects batch norm / dropout) self.policy.set_training_mode(True) # Update learning rate according to schedule self._update_learning_rate(self.policy.optimizer) losses = [] for _ in range(gradient_steps): # Sample replay buffer replay_data = self.replay_buffer.sample(batch_size, env=self._vec_normalize_env) with th.no_grad(): # Compute the next Q-values using the target network next_q_values = self.q_net_target(replay_data.next_observations) # Compute the next soft value function by taking the log-sum-exp of the next Q-values next_q_values = th.logsumexp(next_q_values, 1) # Avoid potential broadcast issue next_q_values = next_q_values.reshape(-1, 1) # 1-step TD target target_q_values = replay_data.rewards + (1 - replay_data.dones) * self.gamma * next_q_values # Get current Q-values estimates current_q_values = self.q_net(replay_data.observations) # Retrieve the q-values for the actions from the replay buffer current_q_values = th.gather(current_q_values, dim=1, index=replay_data.actions.long()) # Compute Huber loss (less sensitive to outliers) loss = F.smooth_l1_loss(current_q_values, target_q_values) losses.append(loss.item()) # Optimize the policy self.policy.optimizer.zero_grad() loss.backward() # Clip gradient norm th.nn.utils.clip_grad_norm_(self.policy.parameters(), self.max_grad_norm) self.policy.optimizer.step() # Increase update counter self._n_updates += gradient_steps self.logger.record("train/n_updates", self._n_updates, exclude="tensorboard") self.logger.record("train/loss", np.mean(losses)) def learn( self: SelfDQN_ME, total_timesteps: int,
callback: MaybeCallback = None,
4
2023-10-28 01:09:21+00:00
24k
hyperspy/exspy
exspy/tests/signals/test_kramers_kronig_transform.py
[ { "identifier": "VolumePlasmonDrude", "path": "exspy/components/volume_plasmon_drude.py", "snippet": "class VolumePlasmonDrude(hs.model.components1D.Expression):\n r\"\"\"\n Drude volume plasmon energy loss function component, the energy loss\n function is defined as:\n\n .. math::\n\n f(E) = I_0 \\frac{E(\\Delta E_p)E_p^2}{(E^2-E_p^2)^2+(E\\Delta E_p)^2}\n\n ================== ===============\n Variable Parameter\n ================== ===============\n :math:`I_0` intensity\n :math:`E_p` plasmon_energy\n :math:`\\Delta E_p` fwhm\n ================== ===============\n\n Parameters\n ----------\n intensity : float\n plasmon_energy : float\n fwhm : float\n **kwargs\n Extra keyword arguments are passed to the\n :py:class:`hyperspy._components.expression.Expression` component.\n\n Notes\n -----\n Refer to Egerton, R. F., Electron Energy-Loss Spectroscopy in the\n Electron Microscope, 2nd edition, Plenum Press 1996, pp. 154-158\n for details, including original equations.\n \"\"\"\n\n def __init__(\n self,\n intensity=1.0,\n plasmon_energy=15.0,\n fwhm=1.5,\n module=\"numexpr\",\n compute_gradients=False,\n **kwargs,\n ):\n super().__init__(\n expression=\"where(x > 0, intensity * (pe2 * x * fwhm) \\\n / ((x ** 2 - pe2) ** 2 + (x * fwhm) ** 2), 0); \\\n pe2 = plasmon_energy ** 2\",\n name=\"VolumePlasmonDrude\",\n intensity=intensity,\n plasmon_energy=plasmon_energy,\n fwhm=fwhm,\n position=\"plasmon_energy\",\n module=module,\n autodoc=False,\n compute_gradients=compute_gradients,\n linear_parameter_list=[\"intensity\"],\n check_parameter_linearity=False,\n **kwargs,\n )\n\n # Partial derivative with respect to the plasmon energy E_p\n def grad_plasmon_energy(self, x):\n plasmon_energy = self.plasmon_energy.value\n fwhm = self.fwhm.value\n intensity = self.intensity.value\n\n return np.where(\n x > 0,\n 2\n * x\n * fwhm\n * plasmon_energy\n * intensity\n * (\n (x**4 + (x * fwhm) ** 2 - plasmon_energy**4)\n / (\n x**4\n + x**2 * (fwhm**2 - 2 * plasmon_energy**2)\n + plasmon_energy**4\n )\n ** 2\n ),\n 0,\n )\n\n # Partial derivative with respect to the plasmon linewidth delta_E_p\n def grad_fwhm(self, x):\n plasmon_energy = self.plasmon_energy.value\n fwhm = self.fwhm.value\n intensity = self.intensity.value\n\n return np.where(\n x > 0,\n x\n * plasmon_energy\n * intensity\n * (\n (\n x**4\n - x**2 * (2 * plasmon_energy**2 + fwhm**2)\n + plasmon_energy**4\n )\n / (\n x**4\n + x**2 * (fwhm**2 - 2 * plasmon_energy**2)\n + plasmon_energy**4\n )\n ** 2\n ),\n 0,\n )\n\n def grad_intensity(self, x):\n return self.function(x) / self.intensity.value" }, { "identifier": "eels_constant", "path": "exspy/misc/eels/tools.py", "snippet": "def eels_constant(s, zlp, t):\n r\"\"\"Calculate the constant of proportionality (k) in the relationship\n between the EELS signal and the dielectric function.\n dielectric function from a single scattering distribution (SSD) using\n the Kramers-Kronig relations.\n\n .. math::\n\n S(E)=\\frac{I_{0}t}{\\pi a_{0}m_{0}v^{2}}\\ln\\left[1+\\left(\\frac{\\beta}\n {\\theta_{E}}\\right)^{2}\\right]\\Im(\\frac{-1}{\\epsilon(E)})=\n k\\Im(\\frac{-1}{\\epsilon(E)})\n\n\n Parameters\n ----------\n zlp: {number, BaseSignal}\n If the ZLP is the same for all spectra, the intengral of the ZLP\n can be provided as a number. Otherwise, if the ZLP intensity is not\n the same for all spectra, it can be provided as i) a Signal\n of the same dimensions as the current signal containing the ZLP\n spectra for each location ii) a Signal of signal dimension 0\n and navigation_dimension equal to the current signal containing the\n integrated ZLP intensity.\n t: {None, number, BaseSignal}\n The sample thickness in nm. If the thickness is the same for all\n spectra it can be given by a number. Otherwise, it can be provided\n as a Signal with signal dimension 0 and navigation_dimension equal\n to the current signal.\n\n Returns\n -------\n k: Signal instance\n\n \"\"\"\n\n # Constants and units\n me = constants.value(\"electron mass energy equivalent in MeV\") * 1e3 # keV\n\n # Mapped parameters\n try:\n e0 = s.metadata.Acquisition_instrument.TEM.beam_energy\n except BaseException:\n raise AttributeError(\n \"Please define the beam energy.\"\n \"You can do this e.g. by using the \"\n \"set_microscope_parameters method\"\n )\n try:\n beta = s.metadata.Acquisition_instrument.TEM.Detector.EELS.collection_angle\n except BaseException:\n raise AttributeError(\n \"Please define the collection semi-angle.\"\n \"You can do this e.g. by using the \"\n \"set_microscope_parameters method\"\n )\n\n axis = s.axes_manager.signal_axes[0]\n eaxis = axis.axis.copy()\n if eaxis[0] == 0:\n # Avoid singularity at E=0\n eaxis[0] = 1e-10\n\n if isinstance(zlp, hyperspy.signal.BaseSignal):\n if zlp.axes_manager.navigation_dimension == s.axes_manager.navigation_dimension:\n if zlp.axes_manager.signal_dimension == 0:\n i0 = zlp.data\n else:\n i0 = zlp.integrate1D(axis.index_in_axes_manager).data\n else:\n raise ValueError(\n \"The ZLP signal dimensions are not \"\n \"compatible with the dimensions of the \"\n \"low-loss signal\"\n )\n # The following prevents errors if the signal is a single spectrum\n if len(i0) != 1:\n i0 = i0.reshape(np.insert(i0.shape, axis.index_in_array, 1))\n elif isinstance(zlp, numbers.Number):\n i0 = zlp\n else:\n raise ValueError(\n \"The zero-loss peak input is not valid, it must be\\\n in the BaseSignal class or a Number.\"\n )\n\n if isinstance(t, hyperspy.signal.BaseSignal):\n if (\n t.axes_manager.navigation_dimension == s.axes_manager.navigation_dimension\n ) and (t.axes_manager.signal_dimension == 0):\n t = t.data\n t = t.reshape(np.insert(t.shape, axis.index_in_array, 1))\n else:\n raise ValueError(\n \"The thickness signal dimensions are not \"\n \"compatible with the dimensions of the \"\n \"low-loss signal\"\n )\n\n # Kinetic definitions\n ke = e0 * (1 + e0 / 2.0 / me) / (1 + e0 / me) ** 2\n tgt = e0 * (2 * me + e0) / (me + e0)\n k = s.__class__(\n data=(t * i0 / (332.5 * ke)) * np.log(1 + (beta * tgt / eaxis) ** 2)\n )\n k.metadata.General.title = \"EELS proportionality constant K\"\n return k" }, { "identifier": "EELSSpectrum", "path": "exspy/signals/eels.py", "snippet": "class EELSSpectrum(Signal1D):\n\n \"\"\"Signal class for EELS spectra.\"\"\"\n\n _signal_type = \"EELS\"\n _alias_signal_types = [\"TEM EELS\"]\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # Attributes defaults\n self.subshells = set()\n self.elements = set()\n self.edges = list()\n if hasattr(self.metadata, \"Sample\") and hasattr(\n self.metadata.Sample, \"elements\"\n ):\n self.add_elements(self.metadata.Sample.elements)\n self.axes_manager.signal_axes[0].is_binned = True\n self._edge_markers = {\"names\": [], \"lines\": None, \"texts\": None}\n\n def add_elements(self, elements, include_pre_edges=False):\n \"\"\"Declare the elemental composition of the sample.\n\n The ionisation edges of the elements present in the current\n energy range will be added automatically.\n\n Parameters\n ----------\n elements : tuple of strings\n The symbol of the elements. Note this input must always be\n in the form of a tuple. Meaning: add_elements(('C',)) will\n work, while add_elements(('C')) will NOT work.\n include_pre_edges : bool\n If True, the ionization edges with an onset below the lower\n energy limit of the SI will be included\n\n Examples\n --------\n\n >>> s = hs.signals.EELSSpectrum(np.arange(1024))\n >>> s.add_elements(('C', 'O'))\n\n Raises\n ------\n ValueError\n\n \"\"\"\n if not isiterable(elements) or isinstance(elements, str):\n raise ValueError(\n \"Input must be in the form of a tuple. For example, \"\n \"if `s` is the variable containing this EELS spectrum:\\n \"\n \">>> s.add_elements(('C',))\\n\"\n \"See the docstring for more information.\"\n )\n\n for element in elements:\n if isinstance(element, bytes):\n element = element.decode()\n if element in elements_db:\n self.elements.add(element)\n else:\n raise ValueError(\n \"%s is not a valid symbol of a chemical element\" % element\n )\n if not hasattr(self.metadata, \"Sample\"):\n self.metadata.add_node(\"Sample\")\n self.metadata.Sample.elements = list(self.elements)\n if self.elements:\n self.generate_subshells(include_pre_edges)\n\n def generate_subshells(self, include_pre_edges=False):\n \"\"\"Calculate the subshells for the current energy range for the\n elements present in self.elements\n\n Parameters\n ----------\n include_pre_edges : bool\n If True, the ionization edges with an onset below the lower\n energy limit of the SI will be included\n\n \"\"\"\n Eaxis = self.axes_manager.signal_axes[0].axis\n if not include_pre_edges:\n start_energy = Eaxis[0]\n else:\n start_energy = 0.0\n end_energy = Eaxis[-1]\n for element in self.elements:\n e_shells = list()\n for shell in elements_db[element][\"Atomic_properties\"][\"Binding_energies\"]:\n if shell[-1] != \"a\":\n energy = elements_db[element][\"Atomic_properties\"][\n \"Binding_energies\"\n ][shell][\"onset_energy (eV)\"]\n if start_energy <= energy <= end_energy:\n subshell = \"%s_%s\" % (element, shell)\n if subshell not in self.subshells:\n self.subshells.add(\"%s_%s\" % (element, shell))\n e_shells.append(subshell)\n\n def edges_at_energy(\n self,\n energy=\"interactive\",\n width=10,\n only_major=False,\n order=\"closest\",\n display=True,\n toolkit=None,\n ):\n \"\"\"Show EELS edges according to an energy range selected from the\n spectrum or within a provided energy window\n\n Parameters\n ----------\n energy : 'interactive' or float\n If it is 'interactive', a table with edges are shown and it depends\n on the energy range selected in the spectrum. If it is a float, a\n table with edges are shown and it depends on the energy window\n defined by energy +/- (width/2). The default is 'interactive'.\n width : float\n Width of window, in eV, around energy in which to find nearby\n energies, i.e. a value of 10 eV (the default) means to\n search +/- 5 eV. The default is 10.\n only_major : bool\n Whether to show only the major edges. The default is False.\n order : str\n Sort the edges, if 'closest', return in the order of energy\n difference, if 'ascending', return in ascending order, similarly\n for 'descending'. The default is 'closest'.\n\n Returns\n -------\n An interactive widget if energy is 'interactive', or a html-format\n table or ASCII table, depends on the environment.\n \"\"\"\n\n if energy == \"interactive\":\n er = EdgesRange(self, interactive=True)\n return er.gui(display=display, toolkit=toolkit)\n else:\n self.print_edges_near_energy(energy, width, only_major, order)\n\n @staticmethod\n def print_edges_near_energy(\n energy=None, width=10, only_major=False, order=\"closest\", edges=None\n ):\n \"\"\"Find and print a table of edges near a given energy that are within\n the given energy window.\n\n Parameters\n ----------\n energy : float\n Energy to search, in eV\n width : float\n Width of window, in eV, around energy in which to find nearby\n energies, i.e. a value of 10 eV (the default) means to\n search +/- 5 eV. The default is 10.\n only_major : bool\n Whether to show only the major edges. The default is False.\n order : str\n Sort the edges, if 'closest', return in the order of energy\n difference, if 'ascending', return in ascending order, similarly\n for 'descending'. The default is 'closest'.\n edges : iterable\n A sequence of edges, if provided, it overrides energy, width,\n only_major and order.\n\n Returns\n -------\n A PrettyText object where its representation is ASCII in terminal and\n html-formatted in Jupyter notebook\n \"\"\"\n\n if edges is None and energy is not None:\n edges = get_edges_near_energy(\n energy=energy, width=width, only_major=only_major, order=order\n )\n elif edges is None and energy is None:\n raise ValueError(\"Either energy or edges should be provided.\")\n\n table = PrettyTable()\n table.field_names = [\"edge\", \"onset energy (eV)\", \"relevance\", \"description\"]\n\n for edge in edges:\n element, shell = edge.split(\"_\")\n shell_dict = elements_db[element][\"Atomic_properties\"][\"Binding_energies\"][\n shell\n ]\n\n onset = shell_dict[\"onset_energy (eV)\"]\n relevance = shell_dict[\"relevance\"]\n threshold = shell_dict[\"threshold\"]\n edge_ = shell_dict[\"edge\"]\n description = threshold + \". \" * (threshold != \"\" and edge_ != \"\") + edge_\n\n table.add_row([edge, onset, relevance, description])\n\n # this ensures the html version try its best to mimick the ASCII one\n table.format = True\n\n display(table)\n\n def estimate_zero_loss_peak_centre(self, mask=None):\n \"\"\"Estimate the position of the zero-loss peak.\n\n This function provides just a coarse estimation of the position\n of the zero-loss peak centre by computing the position of the maximum\n of the spectra. For subpixel accuracy use `estimate_shift1D`.\n\n Parameters\n ----------\n mask : Signal1D of bool data type or bool array\n It must have signal_dimension = 0 and navigation_shape equal to the\n navigation shape of the current signal. Where mask is True the\n shift is not computed and set to nan.\n\n Returns\n -------\n zlpc : Signal1D subclass\n The estimated position of the maximum of the ZLP peak.\n\n Notes\n -----\n This function only works when the zero-loss peak is the most\n intense feature in the spectrum. If it is not in most cases\n the spectrum can be cropped to meet this criterion.\n Alternatively use `estimate_shift1D`.\n\n See Also\n --------\n estimate_shift1D, align_zero_loss_peak\n\n \"\"\"\n self._check_signal_dimension_equals_one()\n self._check_navigation_mask(mask)\n if isinstance(mask, BaseSignal):\n mask = mask.data\n zlpc = self.valuemax(-1)\n if mask is not None:\n zlpc.data = np.where(mask, np.nan, zlpc.data)\n zlpc.set_signal_type(\"\")\n title = self.metadata.General.title\n zlpc.metadata.General.title = \"ZLP(%s)\" % title\n return zlpc\n\n def align_zero_loss_peak(\n self,\n calibrate=True,\n also_align=[],\n print_stats=True,\n subpixel=True,\n mask=None,\n signal_range=None,\n show_progressbar=None,\n crop=True,\n **kwargs,\n ):\n \"\"\"Align the zero-loss peak.\n\n This function first aligns the spectra using the result of\n `estimate_zero_loss_peak_centre` which finds the maximum in the\n given energy range, then if subpixel is True,\n proceeds to align with subpixel accuracy using `align1D`. The offset\n is automatically correct if `calibrate` is True.\n\n Parameters\n ----------\n calibrate : bool\n If True, set the offset of the spectral axis so that the\n zero-loss peak is at position zero.\n also_align : list of signals\n A list containing other spectra of identical dimensions to\n align using the shifts applied to the current spectrum.\n If `calibrate` is True, the calibration is also applied to\n the spectra in the list.\n print_stats : bool\n If True, print summary statistics of the ZLP maximum before\n the alignment.\n subpixel : bool\n If True, perform the alignment with subpixel accuracy\n using cross-correlation.\n mask : Signal1D of bool data type or bool array.\n It must have signal_dimension = 0 and navigation_shape equal to\n the shape of the current signal. Where mask is True the shift is\n not computed and set to nan.\n signal_range : tuple of integers, tuple of floats. Optional\n Will only search for the ZLP within the signal_range. If given\n in integers, the range will be in index values. If given floats,\n the range will be in spectrum values. Useful if there are features\n in the spectrum which are more intense than the ZLP.\n Default is searching in the whole signal. Note that ROIs can be used\n in place of a tuple.\n %s\n %s\n\n Raises\n ------\n NotImplementedError\n If the signal axis is a non-uniform axis.\n\n Examples\n --------\n >>> s_ll = hs.signals.EELSSpectrum(np.zeros(1000))\n >>> s_ll.data[100] = 100\n >>> s_ll.align_zero_loss_peak()\n\n Aligning both the lowloss signal and another signal\n\n >>> s = hs.signals.EELSSpectrum(np.range(1000))\n >>> s_ll.align_zero_loss_peak(also_align=[s])\n\n Aligning within a narrow range of the lowloss signal\n\n >>> s_ll.align_zero_loss_peak(signal_range=(-10.,10.))\n\n\n See Also\n --------\n estimate_zero_loss_peak_centre, align1D, estimate_shift1D.\n\n Notes\n -----\n Any extra keyword arguments are passed to `align1D`. For\n more information read its docstring.\n\n \"\"\"\n\n def substract_from_offset(value, signals):\n # Test that axes is uniform\n if not self.axes_manager[-1].is_uniform:\n raise NotImplementedError(\n \"Support for EELS signals with \"\n \"non-uniform signal axes is not yet implemented.\"\n )\n if isinstance(value, da.Array):\n value = value.compute()\n for signal in signals:\n signal.axes_manager[-1].offset -= value\n signal.events.data_changed.trigger(signal)\n\n def estimate_zero_loss_peak_centre(s, mask, signal_range):\n if signal_range:\n zlpc = s.isig[\n signal_range[0] : signal_range[1]\n ].estimate_zero_loss_peak_centre(mask=mask)\n else:\n zlpc = s.estimate_zero_loss_peak_centre(mask=mask)\n return zlpc\n\n zlpc = estimate_zero_loss_peak_centre(\n self, mask=mask, signal_range=signal_range\n )\n\n mean_ = np.nanmean(zlpc.data)\n\n if print_stats is True:\n print(underline(\"Initial ZLP position statistics\"))\n zlpc.print_summary_statistics()\n\n for signal in also_align + [self]:\n shift_array = -zlpc.data + mean_\n if zlpc._lazy:\n # We must compute right now because otherwise any changes to the\n # axes_manager of the signal later in the workflow may result in\n # a wrong shift_array\n shift_array = shift_array.compute()\n signal.shift1D(shift_array, crop=crop, show_progressbar=show_progressbar)\n\n if calibrate is True:\n zlpc = estimate_zero_loss_peak_centre(\n self, mask=mask, signal_range=signal_range\n )\n substract_from_offset(np.nanmean(zlpc.data), also_align + [self])\n\n if subpixel is False:\n return\n\n start, end = signal_range or (-3.0, 3.0)\n\n if calibrate is False:\n start += mean_\n end += mean_\n\n start = (\n start\n if start > self.axes_manager[-1].axis[0]\n else self.axes_manager[-1].axis[0]\n )\n end = (\n end\n if end < self.axes_manager[-1].axis[-1]\n else self.axes_manager[-1].axis[-1]\n )\n\n if self.axes_manager.navigation_size > 1:\n self.align1D(\n start,\n end,\n also_align=also_align,\n show_progressbar=show_progressbar,\n mask=mask,\n crop=crop,\n **kwargs,\n )\n if calibrate is True:\n zlpc = estimate_zero_loss_peak_centre(\n self, mask=mask, signal_range=signal_range\n )\n substract_from_offset(np.nanmean(zlpc.data), also_align + [self])\n\n align_zero_loss_peak.__doc__ %= (SHOW_PROGRESSBAR_ARG, CROP_PARAMETER_DOC)\n\n def get_zero_loss_peak_mask(self, zero_loss_peak_mask_width=5.0, signal_mask=None):\n \"\"\"Return boolean array with True value at the position of the zero\n loss peak. This mask can be used to restrict operation to the signal\n locations not marked as True (masked).\n\n Parameters\n ----------\n zero_loss_peak_mask_width: float\n Width of the zero loss peak mask.\n %s\n\n Returns\n -------\n bool array\n \"\"\"\n zlpc = self.estimate_zero_loss_peak_centre()\n (signal_axis,) = self.axes_manager[self.axes_manager.signal_axes]\n axis = signal_axis.axis\n mini_value = zlpc.data.mean() - zero_loss_peak_mask_width / 2\n maxi_value = zlpc.data.mean() + zero_loss_peak_mask_width / 2\n mask = np.logical_and(mini_value <= axis, axis <= maxi_value)\n if signal_mask is not None:\n signal_mask = np.logical_or(mask, signal_mask)\n else:\n signal_mask = mask\n return signal_mask\n\n get_zero_loss_peak_mask.__doc__ %= SIGNAL_MASK_ARG\n\n def spikes_diagnosis(\n self,\n signal_mask=None,\n navigation_mask=None,\n zero_loss_peak_mask_width=None,\n **kwargs,\n ):\n if zero_loss_peak_mask_width is not None:\n signal_mask = self.get_zero_loss_peak_mask(\n zero_loss_peak_mask_width, signal_mask\n )\n super().spikes_diagnosis(\n signal_mask=signal_mask, navigation_mask=None, **kwargs\n )\n\n spikes_diagnosis.__doc__ = SPIKES_DIAGNOSIS_DOCSTRING % MASK_ZERO_LOSS_PEAK_WIDTH\n\n def spikes_removal_tool(\n self,\n signal_mask=None,\n navigation_mask=None,\n threshold=\"auto\",\n zero_loss_peak_mask_width=None,\n interactive=True,\n display=True,\n toolkit=None,\n ):\n if zero_loss_peak_mask_width is not None:\n axis = self.axes_manager.signal_axes[0].axis\n # check the zero_loss is in the signal\n if (\n axis[0] - zero_loss_peak_mask_width / 2 > 0\n or axis[-1] + zero_loss_peak_mask_width / 2 < 0\n ):\n raise ValueError(\"The zero loss peaks isn't in the energy range.\")\n signal_mask = self.get_zero_loss_peak_mask(\n zero_loss_peak_mask_width, signal_mask\n )\n super().spikes_removal_tool(\n signal_mask=signal_mask,\n navigation_mask=navigation_mask,\n threshold=threshold,\n interactive=interactive,\n display=display,\n toolkit=toolkit,\n )\n\n spikes_removal_tool.__doc__ = SPIKES_REMOVAL_TOOL_DOCSTRING % (\n SIGNAL_MASK_ARG,\n NAVIGATION_MASK_ARG,\n MASK_ZERO_LOSS_PEAK_WIDTH,\n DISPLAY_DT,\n TOOLKIT_DT,\n )\n\n def estimate_elastic_scattering_intensity(self, threshold, show_progressbar=None):\n \"\"\"Rough estimation of the elastic scattering intensity by\n truncation of a EELS low-loss spectrum.\n\n Parameters\n ----------\n threshold : {Signal1D, float, int}\n Truncation energy to estimate the intensity of the elastic\n scattering. The threshold can be provided as a signal of the same\n dimension as the input spectrum navigation space containing the\n threshold value in the energy units. Alternatively a constant\n threshold can be specified in energy/index units by passing\n float/int.\n %s\n\n Returns\n -------\n I0: Signal1D\n The elastic scattering intensity.\n\n See Also\n --------\n estimate_elastic_scattering_threshold\n\n \"\"\"\n # TODO: Write units tests\n self._check_signal_dimension_equals_one()\n\n if show_progressbar is None:\n show_progressbar = hs.preferences.General.show_progressbar\n\n if isinstance(threshold, numbers.Number):\n I0 = self.isig[:threshold].integrate1D(-1)\n else:\n ax = self.axes_manager.signal_axes[0]\n # I0 = self._get_navigation_signal()\n # I0 = I0.transpose(signal_axes=[])\n threshold = threshold.transpose(signal_axes=[])\n binned = ax.is_binned\n\n def estimating_function(data, threshold=None):\n if np.isnan(threshold):\n return np.nan\n else:\n # the object is just an array, so have to reimplement\n # integrate1D. However can make certain assumptions, for\n # example 1D signal and pretty much always binned. Should\n # probably at some point be joint\n ind = ax.value2index(threshold)\n data = data[:ind]\n if binned:\n return data.sum()\n else:\n from scipy.integrate import simps\n\n axis = ax.axis[:ind]\n return simps(y=data, x=axis)\n\n I0 = self.map(\n estimating_function,\n threshold=threshold,\n ragged=False,\n show_progressbar=show_progressbar,\n inplace=False,\n )\n I0.metadata.General.title = self.metadata.General.title + \" elastic intensity\"\n I0.set_signal_type(\"\")\n if self.tmp_parameters.has_item(\"filename\"):\n I0.tmp_parameters.filename = (\n self.tmp_parameters.filename + \"_elastic_intensity\"\n )\n I0.tmp_parameters.folder = self.tmp_parameters.folder\n I0.tmp_parameters.extension = self.tmp_parameters.extension\n return I0\n\n estimate_elastic_scattering_intensity.__doc__ %= SHOW_PROGRESSBAR_ARG\n\n def estimate_elastic_scattering_threshold(\n self, window=10.0, tol=None, window_length=5, polynomial_order=3, start=1.0\n ):\n \"\"\"Calculate the first inflexion point of the spectrum derivative\n within a window.\n\n This method assumes that the zero-loss peak is located at position zero\n in all the spectra. Currently it looks for an inflexion point, that can\n be a local maximum or minimum. Therefore, to estimate the elastic\n scattering threshold `start` + `window` must be less than the first\n maximum for all spectra (often the bulk plasmon maximum). If there is\n more than one inflexion point in energy the window it selects the\n smoother one what, often, but not always, is a good choice in this\n case.\n\n Parameters\n ----------\n window : {None, float}\n If None, the search for the local inflexion point is performed\n using the full energy range. A positive float will restrict\n the search to the (0,window] energy window, where window is given\n in the axis units. If no inflexion point is found in this\n spectral range the window value is returned instead.\n tol : {None, float}\n The threshold tolerance for the derivative. If \"auto\" it is\n automatically calculated as the minimum value that guarantees\n finding an inflexion point in all the spectra in given energy\n range.\n window_length : int\n If non zero performs order three Savitzky-Golay smoothing\n to the data to avoid falling in local minima caused by\n the noise. It must be an odd integer.\n polynomial_order : int\n Savitzky-Golay filter polynomial order.\n start : float\n Position from the zero-loss peak centre from where to start\n looking for the inflexion point.\n\n\n Returns\n -------\n\n threshold : Signal1D\n A Signal1D of the same dimension as the input spectrum\n navigation space containing the estimated threshold. Where the\n threshold couldn't be estimated the value is set to nan.\n\n See Also\n --------\n\n estimate_elastic_scattering_intensity,align_zero_loss_peak,\n find_peaks1D_ohaver, fourier_ratio_deconvolution.\n\n Notes\n -----\n\n The main purpose of this method is to be used as input for\n `estimate_elastic_scattering_intensity`. Indeed, for currently\n achievable energy resolutions, there is not such a thing as a elastic\n scattering threshold. Therefore, please be aware of the limitations of\n this method when using it.\n\n \"\"\"\n self._check_signal_dimension_equals_one()\n # Create threshold with the same shape as the navigation dims.\n threshold = self._get_navigation_signal().transpose(signal_axes=0)\n\n # Progress Bar\n axis = self.axes_manager.signal_axes[0]\n min_index, max_index = axis.value_range_to_indices(start, start + window)\n if max_index < min_index + 10:\n raise ValueError(\"Please select a bigger window\")\n s = self.isig[min_index:max_index].deepcopy()\n if window_length:\n s.smooth_savitzky_golay(\n polynomial_order=polynomial_order,\n window_length=window_length,\n differential_order=1,\n )\n else:\n s = s.derivative(-1)\n if tol is None:\n tol = np.max(abs(s.data).min(axis.index_in_array))\n saxis = s.axes_manager[-1]\n inflexion = (abs(s.data) <= tol).argmax(saxis.index_in_array)\n if isinstance(inflexion, da.Array):\n inflexion = inflexion.compute()\n threshold.data[:] = saxis.index2value(inflexion)\n if isinstance(inflexion, np.ndarray):\n threshold.data[inflexion == 0] = np.nan\n else: # Single spectrum\n if inflexion == 0:\n threshold.data[:] = np.nan\n del s\n if np.isnan(threshold.data).any():\n _logger.warning(\n \"No inflexion point could be found in some positions \"\n \"that have been marked with nans.\"\n )\n # Create spectrum image, stop and return value\n threshold.metadata.General.title = (\n self.metadata.General.title + \" elastic scattering threshold\"\n )\n if self.tmp_parameters.has_item(\"filename\"):\n threshold.tmp_parameters.filename = (\n self.tmp_parameters.filename + \"_elastic_scattering_threshold\"\n )\n threshold.tmp_parameters.folder = self.tmp_parameters.folder\n threshold.tmp_parameters.extension = self.tmp_parameters.extension\n threshold.set_signal_type(\"\")\n return threshold\n\n def estimate_thickness(\n self,\n threshold=None,\n zlp=None,\n density=None,\n mean_free_path=None,\n ):\n \"\"\"Estimates the thickness (relative and absolute)\n of a sample using the log-ratio method.\n\n The current EELS spectrum must be a low-loss spectrum containing\n the zero-loss peak. The hyperspectrum must be well calibrated\n and aligned. To obtain the thickness relative to the mean free path\n don't set the `density` and the `mean_free_path`.\n\n Parameters\n ----------\n threshold : {BaseSignal, float}, optional\n If the zero-loss-peak is not provided, use this energy threshold\n to roughly estimate its intensity by truncation.\n If the threshold is constant across the dataset use a float. Otherwise,\n provide a signal of\n the same dimension as the input spectrum navigation space\n containing the threshold value in the energy units.\n zlp : BaseSignal, optional\n If not None the zero-loss peak intensity is calculated from the ZLP\n spectrum supplied by integration.\n mean_free_path : float, optional\n The mean free path of the material in nanometers.\n If not provided, the thickness\n is given relative to the mean free path.\n density : float, optional\n The density of the material in g/cm**3. This is used to estimate the mean\n free path when the mean free path is not known and to perform the\n angular corrections.\n\n Returns\n -------\n s : BaseSignal\n The thickness relative to the MFP. It returns a Signal1D,\n Signal2D or a BaseSignal, depending on the current navigation\n dimensions.\n\n Notes\n -----\n For details see Egerton, R. Electron Energy-Loss Spectroscopy in the Electron\n Microscope. Springer-Verlag, 2011.\n \"\"\"\n axis = self.axes_manager.signal_axes[0]\n total_intensity = self.integrate1D(axis.index_in_array).data\n if threshold is None and zlp is None:\n raise ValueError(\n \"Please provide one of the following keywords: \" \"`threshold`, `zlp`\"\n )\n if zlp is not None:\n I0 = zlp.integrate1D(axis.index_in_array).data\n else:\n I0 = self.estimate_elastic_scattering_intensity(\n threshold=threshold,\n ).data\n\n t_over_lambda = np.log(total_intensity / I0)\n\n if density is not None:\n if self._are_microscope_parameters_missing():\n raise RuntimeError(\n \"Some microscope parameters are missing. Please use the \"\n \"`set_microscope_parameters()` method to set them. \"\n \"If you don't know them, don't set the `density` keyword.\"\n )\n else:\n md = self.metadata.Acquisition_instrument.TEM\n t_over_lambda *= iMFP_angular_correction(\n beam_energy=md.beam_energy,\n alpha=md.convergence_angle,\n beta=md.Detector.EELS.collection_angle,\n density=density,\n )\n if mean_free_path is None:\n mean_free_path = iMFP_Iakoubovskii(\n electron_energy=self.metadata.Acquisition_instrument.TEM.beam_energy,\n density=density,\n )\n _logger.info(f\"The estimated iMFP is {mean_free_path} nm\")\n else:\n _logger.warning(\n \"Computing the thickness without taking into account the effect of \"\n \"the limited collection angle, what usually leads to underestimating \"\n \"the thickness. To perform the angular corrections you must provide \"\n \"the density of the material.\"\n )\n\n s = self._get_navigation_signal(data=t_over_lambda)\n if mean_free_path is not None:\n s.data *= mean_free_path\n s.metadata.General.title = self.metadata.General.title + \" thickness (nm)\"\n s.metadata.Signal.quantity = \"thickness (nm)\"\n else:\n _logger.warning(\n \"Computing the relative thickness. To compute the absolute \"\n \"thickness provide the `mean_free_path` and/or the `density`\"\n )\n s.metadata.General.title = (\n self.metadata.General.title + \" $\\\\frac{t}{\\\\lambda}$\"\n )\n s.metadata.Signal.quantity = \"$\\\\frac{t}{\\\\lambda}$\"\n if self.tmp_parameters.has_item(\"filename\"):\n s.tmp_parameters.filename = self.tmp_parameters.filename + \"_thickness\"\n s.tmp_parameters.folder = self.tmp_parameters.folder\n s.tmp_parameters.extension = self.tmp_parameters.extension\n s = s.transpose(signal_axes=[])\n s.set_signal_type(\"\")\n return s\n\n def fourier_log_deconvolution(self, zlp, add_zlp=False, crop=False):\n \"\"\"Performs fourier-log deconvolution.\n\n Parameters\n ----------\n zlp : EELSSpectrum\n The corresponding zero-loss peak.\n\n add_zlp : bool\n If True, adds the ZLP to the deconvolved spectrum\n crop : bool\n If True crop the spectrum to leave out the channels that\n have been modified to decay smoothly to zero at the sides\n of the spectrum.\n\n Returns\n -------\n An EELSSpectrum containing the current data deconvolved.\n\n Raises\n ------\n NotImplementedError\n If the signal axis is a non-uniform axis.\n\n Notes\n -----\n For details see: Egerton, R. Electron Energy-Loss\n Spectroscopy in the Electron Microscope. Springer-Verlag, 2011.\n\n \"\"\"\n self._check_signal_dimension_equals_one()\n if not self.axes_manager.signal_axes[0].is_uniform:\n raise NotImplementedError(\n \"This operation is not yet implemented for non-uniform energy axes\"\n )\n s = self.deepcopy()\n zlp_size = zlp.axes_manager.signal_axes[0].size\n self_size = self.axes_manager.signal_axes[0].size\n tapped_channels = s.hanning_taper()\n # Conservative new size to solve the wrap-around problem\n size = zlp_size + self_size - 1\n # Calculate optimal FFT padding for performance\n complex_result = zlp.data.dtype.kind == \"c\" or s.data.dtype.kind == \"c\"\n size = optimal_fft_size(size, not complex_result)\n\n axis = self.axes_manager.signal_axes[0]\n\n z = np.fft.rfft(zlp.data, n=size, axis=axis.index_in_array)\n j = np.fft.rfft(s.data, n=size, axis=axis.index_in_array)\n if self._lazy or zlp._lazy:\n j1 = z * da.log(j / z).map_blocks(np.nan_to_num)\n else:\n j1 = z * np.nan_to_num(np.log(j / z))\n sdata = np.fft.irfft(j1, axis=axis.index_in_array)\n\n s.data = sdata[\n s.axes_manager._get_data_slice(\n [\n (axis.index_in_array, slice(None, self_size)),\n ]\n )\n ]\n if add_zlp is True:\n if self_size >= zlp_size:\n if self._lazy:\n _slices_before = s.axes_manager._get_data_slice(\n [\n (axis.index_in_array, slice(None, zlp_size)),\n ]\n )\n _slices_after = s.axes_manager._get_data_slice(\n [\n (axis.index_in_array, slice(zlp_size, None)),\n ]\n )\n s.data = da.stack(\n (s.data[_slices_before] + zlp.data, s.data[_slices_after]),\n axis=axis.index_in_array,\n )\n else:\n s.data[\n s.axes_manager._get_data_slice(\n [\n (axis.index_in_array, slice(None, zlp_size)),\n ]\n )\n ] += zlp.data\n else:\n s.data += zlp.data[\n s.axes_manager._get_data_slice(\n [\n (axis.index_in_array, slice(None, self_size)),\n ]\n )\n ]\n\n s.metadata.General.title = (\n s.metadata.General.title + \" after Fourier-log deconvolution\"\n )\n if s.tmp_parameters.has_item(\"filename\"):\n s.tmp_parameters.filename = (\n self.tmp_parameters.filename + \"_after_fourier_log_deconvolution\"\n )\n if crop is True:\n s.crop(axis.index_in_axes_manager, None, int(-tapped_channels))\n return s\n\n def fourier_ratio_deconvolution(\n self,\n ll,\n fwhm=None,\n threshold=None,\n extrapolate_lowloss=True,\n extrapolate_coreloss=True,\n ):\n \"\"\"Performs Fourier-ratio deconvolution.\n\n The core-loss should have the background removed. To reduce the noise\n amplification the result is convolved with a Gaussian function.\n\n Parameters\n ----------\n ll: EELSSpectrum\n The corresponding low-loss (ll) EELSSpectrum.\n fwhm : float or None\n Full-width half-maximum of the Gaussian function by which\n the result of the deconvolution is convolved. It can be\n used to select the final SNR and spectral resolution. If\n None, the FWHM of the zero-loss peak of the low-loss is\n estimated and used.\n threshold : {None, float}\n Truncation energy to estimate the intensity of the\n elastic scattering. If None the threshold is taken as the\n first minimum after the ZLP centre.\n extrapolate_lowloss, extrapolate_coreloss : bool\n If True the signals are extrapolated using a power law,\n\n Raises\n ------\n NotImplementedError\n If the signal axis is a non-uniform axis.\n\n Notes\n -----\n For details see: Egerton, R. Electron Energy-Loss\n Spectroscopy in the Electron Microscope. Springer-Verlag, 2011.\n\n \"\"\"\n self._check_signal_dimension_equals_one()\n if not self.axes_manager.signal_axes[0].is_uniform:\n raise NotImplementedError(\n \"This operation is not yet implemented for non-uniform energy axes.\"\n )\n if not ll.axes_manager.signal_axes[0].is_uniform:\n raise NotImplementedError(\n \"The low-loss energy axis is non-uniform. \"\n \"This operation is not yet implemented for non-uniform energy axes\"\n )\n orig_cl_size = self.axes_manager.signal_axes[0].size\n\n if threshold is None:\n threshold = ll.estimate_elastic_scattering_threshold()\n\n if extrapolate_coreloss is True:\n cl = self.power_law_extrapolation(window_size=20, extrapolation_size=100)\n else:\n cl = self.deepcopy()\n\n if extrapolate_lowloss is True:\n ll = ll.power_law_extrapolation(window_size=100, extrapolation_size=100)\n else:\n ll = ll.deepcopy()\n\n ll.hanning_taper()\n cl.hanning_taper()\n\n ll_size = ll.axes_manager.signal_axes[0].size\n cl_size = self.axes_manager.signal_axes[0].size\n # Conservative new size to solve the wrap-around problem\n size = ll_size + cl_size - 1\n # Calculate the optimal FFT size\n size = optimal_fft_size(size)\n\n axis = ll.axes_manager.signal_axes[0]\n if fwhm is None:\n fwhm = float(\n ll.get_current_signal().estimate_peak_width()._get_current_data()\n )\n _logger.info(\"FWHM = %1.2f\" % fwhm)\n\n I0 = ll.estimate_elastic_scattering_intensity(threshold=threshold)\n I0 = I0.data\n if ll.axes_manager.navigation_size > 0:\n I0_shape = list(I0.shape)\n I0_shape.insert(axis.index_in_array, 1)\n I0 = I0.reshape(I0_shape)\n\n from hyperspy.components1d import Gaussian\n\n g = Gaussian()\n g.sigma.value = fwhm / 2.3548\n g.A.value = 1\n g.centre.value = 0\n zl = g.function(\n np.linspace(axis.offset, axis.offset + axis.scale * (size - 1), size)\n )\n z = np.fft.rfft(zl)\n jk = np.fft.rfft(cl.data, n=size, axis=axis.index_in_array)\n jl = np.fft.rfft(ll.data, n=size, axis=axis.index_in_array)\n zshape = [\n 1,\n ] * len(cl.data.shape)\n zshape[axis.index_in_array] = jk.shape[axis.index_in_array]\n cl.data = np.fft.irfft(z.reshape(zshape) * jk / jl, axis=axis.index_in_array)\n cl.data *= I0\n cl.crop(-1, None, int(orig_cl_size))\n cl.metadata.General.title = (\n self.metadata.General.title + \" after Fourier-ratio deconvolution\"\n )\n if cl.tmp_parameters.has_item(\"filename\"):\n cl.tmp_parameters.filename = (\n self.tmp_parameters.filename + \"after_fourier_ratio_deconvolution\"\n )\n return cl\n\n def richardson_lucy_deconvolution(\n self, psf, iterations=15, show_progressbar=None, num_workers=None\n ):\n \"\"\"1D Richardson-Lucy Poissonian deconvolution of\n the spectrum by the given kernel.\n\n Parameters\n ----------\n psf : EELSSpectrum\n It must have the same signal dimension as the current\n spectrum and a spatial dimension of 0 or the same as the\n current spectrum.\n iterations : int\n Number of iterations of the deconvolution. Note that\n increasing the value will increase the noise amplification.\n %s\n %s\n\n Raises\n ------\n NotImplementedError\n If the signal axis is a non-uniform axis.\n\n Notes\n -----\n For details on the algorithm see Gloter, A., A. Douiri,\n M. Tence, and C. Colliex. “Improving Energy Resolution of\n EELS Spectra: An Alternative to the Monochromator Solution.”\n Ultramicroscopy 96, no. 3–4 (September 2003): 385–400.\n\n \"\"\"\n if not self.axes_manager.signal_axes[0].is_uniform:\n raise NotImplementedError(\n \"This operation is not yet implemented for non-uniform energy axes.\"\n )\n if show_progressbar is None:\n show_progressbar = hs.preferences.General.show_progressbar\n self._check_signal_dimension_equals_one()\n psf_size = psf.axes_manager.signal_axes[0].size\n maxval = self.axes_manager.navigation_size\n show_progressbar = show_progressbar and (maxval > 0)\n\n def deconv_function(signal, kernel=None, iterations=15, psf_size=None):\n imax = kernel.argmax()\n result = np.array(signal).copy()\n mimax = psf_size - 1 - imax\n for _ in range(iterations):\n first = np.convolve(kernel, result)[imax : imax + psf_size]\n result *= np.convolve(kernel[::-1], signal / first)[\n mimax : mimax + psf_size\n ]\n return result\n\n ds = self.map(\n deconv_function,\n kernel=psf,\n iterations=iterations,\n psf_size=psf_size,\n show_progressbar=show_progressbar,\n num_workers=num_workers,\n ragged=False,\n inplace=False,\n )\n\n ds.metadata.General.title += (\n \" after Richardson-Lucy deconvolution %i iterations\" % iterations\n )\n if ds.tmp_parameters.has_item(\"filename\"):\n ds.tmp_parameters.filename += \"_after_R-L_deconvolution_%iiter\" % iterations\n return ds\n\n richardson_lucy_deconvolution.__doc__ %= (SHOW_PROGRESSBAR_ARG, NUM_WORKERS_ARG)\n\n def _are_microscope_parameters_missing(self, ignore_parameters=[]):\n \"\"\"\n Check if the EELS parameters necessary to calculate the GOS\n are defined in metadata. If not, in interactive mode\n raises an UI item to fill the values.\n The `ignore_parameters` list can be to ignore parameters.\n \"\"\"\n must_exist = (\n \"Acquisition_instrument.TEM.convergence_angle\",\n \"Acquisition_instrument.TEM.beam_energy\",\n \"Acquisition_instrument.TEM.Detector.EELS.collection_angle\",\n )\n missing_parameters = []\n for item in must_exist:\n exists = self.metadata.has_item(item)\n if exists is False and item.split(\".\")[-1] not in ignore_parameters:\n missing_parameters.append(item)\n if missing_parameters:\n _logger.info(\"Missing parameters {}\".format(missing_parameters))\n return True\n else:\n return False\n\n def set_microscope_parameters(\n self,\n beam_energy=None,\n convergence_angle=None,\n collection_angle=None,\n toolkit=None,\n display=True,\n ):\n if set((beam_energy, convergence_angle, collection_angle)) == {None}:\n tem_par = EELSTEMParametersUI(self)\n return tem_par.gui(toolkit=toolkit, display=display)\n mp = self.metadata\n if beam_energy is not None:\n mp.set_item(\"Acquisition_instrument.TEM.beam_energy\", beam_energy)\n if convergence_angle is not None:\n mp.set_item(\n \"Acquisition_instrument.TEM.convergence_angle\", convergence_angle\n )\n if collection_angle is not None:\n mp.set_item(\n \"Acquisition_instrument.TEM.Detector.EELS.collection_angle\",\n collection_angle,\n )\n\n set_microscope_parameters.__doc__ = \"\"\"\n Set the microscope parameters that are necessary to calculate\n the GOS.\n\n If not all of them are defined, in interactive mode\n raises an UI item to fill the values.\n\n beam_energy: float\n The energy of the electron beam in keV.\n convergence_angle : float\n The microscope convergence semi-angle in mrad.\n collection_angle : float\n The collection semi-angle in mrad.\n {}\n {}\n \"\"\".format(\n TOOLKIT_DT, DISPLAY_DT\n )\n\n def power_law_extrapolation(\n self, window_size=20, extrapolation_size=1024, add_noise=False, fix_neg_r=False\n ):\n \"\"\"\n Extrapolate the spectrum to the right using a powerlaw.\n\n Parameters\n ----------\n window_size : int\n The number of channels from the right side of the\n spectrum that are used to estimate the power law\n parameters.\n extrapolation_size : int\n Size of the extrapolation in number of channels\n add_noise : bool\n If True, add poissonian noise to the extrapolated spectrum.\n fix_neg_r : bool\n If True, the negative values for the \"components.PowerLaw\"\n parameter r will be flagged and the extrapolation will be\n done with a constant zero-value.\n\n Returns\n -------\n A new spectrum, with the extrapolation.\n\n \"\"\"\n self._check_signal_dimension_equals_one()\n axis = self.axes_manager.signal_axes[0]\n s = self.deepcopy()\n s.metadata.General.title += \" %i channels extrapolated\" % extrapolation_size\n if s.tmp_parameters.has_item(\"filename\"):\n s.tmp_parameters.filename += (\n \"_%i_channels_extrapolated\" % extrapolation_size\n )\n new_shape = list(self.data.shape)\n new_shape[axis.index_in_array] += extrapolation_size\n if self._lazy:\n left_data = s.data\n right_shape = list(self.data.shape)\n right_shape[axis.index_in_array] = extrapolation_size\n right_chunks = list(self.data.chunks)\n right_chunks[axis.index_in_array] = (extrapolation_size,)\n right_data = da.zeros(\n shape=tuple(right_shape),\n chunks=tuple(right_chunks),\n dtype=self.data.dtype,\n )\n s.data = da.concatenate([left_data, right_data], axis=axis.index_in_array)\n else:\n # just old code\n s.data = np.zeros(new_shape)\n s.data[..., : axis.size] = self.data\n s.get_dimensions_from_data()\n pl = PowerLaw()\n pl._axes_manager = self.axes_manager\n A, r = pl.estimate_parameters(\n s,\n axis.index2value(axis.size - window_size),\n axis.index2value(axis.size - 1),\n out=True,\n )\n if fix_neg_r is True:\n A = np.where(r <= 0, 0, A)\n # If the signal is binned we need to bin the extrapolated power law\n # what, in a first approximation, can be done by multiplying by the\n # axis step size.\n if self.axes_manager[-1].is_binned:\n factor = s.axes_manager[-1].scale\n else:\n factor = 1\n if self._lazy:\n # only need new axes if the navigation dimension is not 0\n if s.axes_manager.navigation_dimension:\n rightslice = (..., None)\n axisslice = (None, slice(axis.size, None))\n else:\n rightslice = (...,)\n axisslice = (slice(axis.size, None),)\n right_chunks[axis.index_in_array] = 1\n x = da.from_array(\n s.axes_manager.signal_axes[0].axis[axisslice],\n chunks=(extrapolation_size,),\n )\n A = A[rightslice]\n r = r[rightslice]\n right_data = factor * A * x ** (-r)\n s.data = da.concatenate([left_data, right_data], axis=axis.index_in_array)\n else:\n s.data[..., axis.size :] = (\n factor\n * A[..., np.newaxis]\n * s.axes_manager.signal_axes[0].axis[np.newaxis, axis.size :]\n ** (-r[..., np.newaxis])\n )\n return s\n\n def kramers_kronig_analysis(\n self, zlp=None, iterations=1, n=None, t=None, delta=0.5, full_output=False\n ):\n r\"\"\"\n Calculate the complex dielectric function from a single scattering\n distribution (SSD) using the Kramers-Kronig relations.\n\n It uses the FFT method as in [1]_. The SSD is an\n EELSSpectrum instance containing SSD low-loss EELS with no zero-loss\n peak. The internal loop is devised to approximately subtract the\n surface plasmon contribution supposing an unoxidized planar surface and\n neglecting coupling between the surfaces. This method does not account\n for retardation effects, instrumental broadening and surface plasmon\n excitation in particles.\n\n Note that either refractive index or thickness are required.\n If both are None or if both are provided an exception is raised.\n\n Parameters\n ----------\n zlp : {None, number, Signal1D}\n ZLP intensity. It is optional (can be None) if `t` is None and `n`\n is not None and the thickness estimation is not required. If `t`\n is not None, the ZLP is required to perform the normalization and\n if `t` is not None, the ZLP is required to calculate the thickness.\n If the ZLP is the same for all spectra, the integral of the ZLP\n can be provided as a number. Otherwise, if the ZLP intensity is not\n the same for all spectra, it can be provided as i) a Signal1D\n of the same dimensions as the current signal containing the ZLP\n spectra for each location ii) a BaseSignal of signal dimension 0\n and navigation_dimension equal to the current signal containing the\n integrated ZLP intensity.\n iterations : int\n Number of the iterations for the internal loop to remove the\n surface plasmon contribution. If 1 the surface plasmon contribution\n is not estimated and subtracted (the default is 1).\n n : {None, float}\n The medium refractive index. Used for normalization of the\n SSD to obtain the energy loss function. If given the thickness\n is estimated and returned. It is only required when `t` is None.\n t : {None, number, Signal1D}\n The sample thickness in nm. Used for normalization of the SSD\n to obtain the energy loss function. It is only required when\n `n` is None. If the thickness is the same for all spectra it can be\n given by a number. Otherwise, it can be provided as a BaseSignal\n with signal dimension 0 and navigation_dimension equal to the\n current signal.\n delta : float\n A small number (0.1-0.5 eV) added to the energy axis in\n specific steps of the calculation the surface loss correction to\n improve stability.\n full_output : bool\n If True, return a dictionary that contains the estimated\n thickness if `t` is None and the estimated surface plasmon\n excitation and the spectrum corrected from surface plasmon\n excitations if `iterations` > 1.\n\n Returns\n -------\n eps: DielectricFunction instance\n The complex dielectric function results,\n\n .. math::\n \\epsilon = \\epsilon_1 + i*\\epsilon_2,\n\n contained in an DielectricFunction instance.\n output: Dictionary (optional)\n A dictionary of optional outputs with the following keys\n\n * ``thickness``: the estimated thickness in nm calculated by\n normalization of the SSD (only when ``t`` is None)\n * ``surface plasmon estimation``: the estimated surface plasmon\n excitation (only if ``iterations`` > 1.)\n\n Raises\n ------\n ValueError\n If both `n` and `t` are undefined (None).\n AttributeError\n If the beam_energy or the collection semi-angle are not defined in\n metadata.\n NotImplementedError\n If the signal axis is a non-uniform axis.\n\n Notes\n -----\n This method is based in Egerton's Matlab code [1]_ with a\n minor difference: the wrap-around problem when computing the FFTs is\n workarounded by padding the signal instead of subtracting the\n reflected tail.\n\n .. [1] Ray Egerton, \"Electron Energy-Loss Spectroscopy in the Electron\n Microscope\", Springer-Verlag, 2011.\n\n \"\"\"\n if not self.axes_manager.signal_axes[0].is_uniform:\n raise NotImplementedError(\n \"This operation is not yet implemented for non-uniform energy axes.\"\n )\n output = {}\n if iterations == 1:\n # In this case s.data is not modified so there is no need to make\n # a deep copy.\n s = self.isig[0.0:]\n else:\n s = self.isig[0.0:].deepcopy()\n\n sorig = self.isig[0.0:]\n # Avoid singularity at 0\n if s.axes_manager.signal_axes[0].axis[0] == 0:\n s = s.isig[1:]\n sorig = self.isig[1:]\n\n # Constants and units\n me = constants.value(\"electron mass energy equivalent in MeV\") * 1e3 # keV\n\n # Mapped parameters\n self._are_microscope_parameters_missing(ignore_parameters=[\"convergence_angle\"])\n e0 = s.metadata.Acquisition_instrument.TEM.beam_energy\n beta = s.metadata.Acquisition_instrument.TEM.Detector.EELS.collection_angle\n\n axis = s.axes_manager.signal_axes[0]\n eaxis = axis.axis.copy()\n\n if isinstance(zlp, hyperspy.signal.BaseSignal):\n if (\n zlp.axes_manager.navigation_dimension\n == self.axes_manager.navigation_dimension\n ):\n if zlp.axes_manager.signal_dimension == 0:\n i0 = zlp.data\n else:\n i0 = zlp.integrate1D(axis.index_in_axes_manager).data\n else:\n raise ValueError(\n \"The ZLP signal dimensions are not \"\n \"compatible with the dimensions of the \"\n \"low-loss signal\"\n )\n # The following prevents errors if the signal is a single spectrum\n if len(i0) != 1:\n i0 = i0.reshape(np.insert(i0.shape, axis.index_in_array, 1))\n elif isinstance(zlp, numbers.Number):\n i0 = zlp\n else:\n raise ValueError(\n \"The zero-loss peak input is not valid, it must be\\\n in the BaseSignal class or a Number.\"\n )\n\n if isinstance(t, hyperspy.signal.BaseSignal):\n if (\n t.axes_manager.navigation_dimension\n == self.axes_manager.navigation_dimension\n ) and (t.axes_manager.signal_dimension == 0):\n t = t.data\n t = t.reshape(np.insert(t.shape, axis.index_in_array, 1))\n else:\n raise ValueError(\n \"The thickness signal dimensions are not \"\n \"compatible with the dimensions of the \"\n \"low-loss signal\"\n )\n elif isinstance(t, np.ndarray) and t.shape and t.shape != (1,):\n raise ValueError(\n \"thickness must be a HyperSpy signal or a number,\" \" not a NumPy array.\"\n )\n\n # Slicer to get the signal data from 0 to axis.size\n slicer = s.axes_manager._get_data_slice(\n [\n (axis.index_in_array, slice(None, axis.size)),\n ]\n )\n\n # Kinetic definitions\n ke = e0 * (1 + e0 / 2.0 / me) / (1 + e0 / me) ** 2\n tgt = e0 * (2 * me + e0) / (me + e0)\n rk0 = 2590 * (1 + e0 / me) * np.sqrt(2 * ke / me)\n\n for io in range(iterations):\n # Calculation of the ELF by normalization of the SSD\n # Norm(SSD) = Imag(-1/epsilon) (Energy Loss Function, ELF)\n\n # We start by the \"angular corrections\"\n Im = s.data / (np.log(1 + (beta * tgt / eaxis) ** 2)) / axis.scale\n if n is None and t is None:\n raise ValueError(\n \"The thickness and the refractive index are \"\n \"not defined. Please provide one of them.\"\n )\n elif n is not None and t is not None:\n raise ValueError(\n \"Please provide the refractive index OR the \"\n \"thickness information, not both\"\n )\n elif n is not None:\n # normalize using the refractive index.\n K = (Im / eaxis).sum(\n axis=axis.index_in_array, keepdims=True\n ) * axis.scale\n K = K / (np.pi / 2) / (1 - 1.0 / n**2)\n # K = (K / (np.pi / 2) / (1 - 1. / n ** 2)).reshape(\n # np.insert(K.shape, axis.index_in_array, 1))\n # Calculate the thickness only if possible and required\n if zlp is not None and (full_output is True or iterations > 1):\n te = 332.5 * K * ke / i0\n if full_output is True:\n output[\"thickness\"] = te\n elif t is not None:\n if zlp is None:\n raise ValueError(\n \"The ZLP must be provided when the \"\n \"thickness is used for normalization.\"\n )\n # normalize using the thickness\n K = t * i0 / (332.5 * ke)\n te = t\n Im = Im / K\n\n # Kramers Kronig Transform:\n # We calculate KKT(Im(-1/epsilon))=1+Re(1/epsilon) with FFT\n # Follows: D W Johnson 1975 J. Phys. A: Math. Gen. 8 490\n # Use an optimal FFT size to speed up the calculation, and\n # make it double the closest upper value to workaround the\n # wrap-around problem.\n esize = optimal_fft_size(2 * axis.size)\n q = -2 * np.fft.fft(Im, esize, axis.index_in_array).imag / esize\n\n q[slicer] *= -1\n q = np.fft.fft(q, axis=axis.index_in_array)\n # Final touch, we have Re(1/eps)\n Re = q[slicer].real + 1\n\n # Egerton does this to correct the wrap-around problem, but in our\n # case this is not necessary because we compute the fft on an\n # extended and padded spectrum to avoid this problem.\n # Re=real(q)\n # Tail correction\n # vm=Re[axis.size-1]\n # Re[:(axis.size-1)]=Re[:(axis.size-1)]+1-(0.5*vm*((axis.size-1) /\n # (axis.size*2-arange(0,axis.size-1)))**2)\n # Re[axis.size:]=1+(0.5*vm*((axis.size-1) /\n # (axis.size+arange(0,axis.size)))**2)\n\n # Epsilon appears:\n # We calculate the real and imaginary parts of the CDF\n e1 = Re / (Re**2 + Im**2)\n e2 = Im / (Re**2 + Im**2)\n\n if iterations > 1 and zlp is not None:\n # Surface losses correction:\n # Calculates the surface ELF from a vacuum border effect\n # A simulated surface plasmon is subtracted from the ELF\n Srfelf = 4 * e2 / ((e1 + 1) ** 2 + e2**2) - Im\n adep = tgt / (eaxis + delta) * np.arctan(\n beta * tgt / axis.axis\n ) - beta / 1000.0 / (beta**2 + axis.axis**2.0 / tgt**2)\n Srfint = 2000 * K * adep * Srfelf / rk0 / te * axis.scale\n s.data = sorig.data - Srfint\n _logger.debug(\"Iteration number: %d / %d\", io + 1, iterations)\n if iterations == io + 1 and full_output is True:\n sp = sorig._deepcopy_with_new_data(Srfint)\n sp.metadata.General.title += (\n \" estimated surface plasmon excitation.\"\n )\n output[\"surface plasmon estimation\"] = sp\n del sp\n del Srfint\n\n eps = s._deepcopy_with_new_data(e1 + e2 * 1j)\n del s\n eps.set_signal_type(\"DielectricFunction\")\n eps.metadata.General.title = (\n self.metadata.General.title + \"dielectric function \"\n \"(from Kramers-Kronig analysis)\"\n )\n if eps.tmp_parameters.has_item(\"filename\"):\n eps.tmp_parameters.filename = (\n self.tmp_parameters.filename + \"_CDF_after_Kramers_Kronig_transform\"\n )\n if \"thickness\" in output:\n # As above,prevent errors if the signal is a single spectrum\n if len(te) != 1:\n te = te[self.axes_manager._get_data_slice([(axis.index_in_array, 0)])]\n thickness = eps._get_navigation_signal(data=te)\n thickness.metadata.General.title = (\n self.metadata.General.title + \" thickness \"\n \"(calculated using Kramers-Kronig analysis)\"\n )\n output[\"thickness\"] = thickness\n if full_output is False:\n return eps\n else:\n return eps, output\n\n def create_model(\n self,\n low_loss=None,\n auto_background=True,\n auto_add_edges=True,\n GOS=\"gosh\",\n gos_file_path=None,\n dictionary=None,\n ):\n \"\"\"Create a model for the current EELS data.\n\n Parameters\n ----------\n %s\n\n Returns\n -------\n model : :class:`~.models.eelsmodel.EELSModel` instance.\n\n Raises\n ------\n NotImplementedError\n If the signal axis is a non-uniform axis.\n \"\"\"\n from exspy.models.eelsmodel import EELSModel\n\n if low_loss is not None and not self.axes_manager.signal_axes[0].is_uniform:\n raise NotImplementedError(\n \"Multiple scattering is not implemented for spectra with a \"\n \"non-uniform energy axis. To create a model that does not \"\n \"account for multiple-scattering do not set the `ll` keyword.\"\n )\n model = EELSModel(\n self,\n low_loss=low_loss,\n auto_background=auto_background,\n auto_add_edges=auto_add_edges,\n GOS=GOS,\n dictionary=dictionary,\n )\n return model\n\n create_model.__doc__ %= EELSMODEL_PARAMETERS\n\n def plot(self, plot_edges=False, only_edges=(\"Major\", \"Minor\"), **kwargs):\n \"\"\"\n Plot the EELS spectrum. Markers indicating the position of the\n EELS edges can be added.\n\n Parameters\n ----------\n plot_edges : {False, True, list of string or string}\n If True, draws on s.metadata.Sample.elements for edges.\n Alternatively, provide a string of a single edge, or an iterable\n containing a list of valid elements, EELS families or edges. For\n example, an element should be 'Zr', an element edge family should\n be 'Zr_L' or an EELS edge 'Zr_L3'.\n only_edges : tuple of string\n Either 'Major' or 'Minor'. Defaults to both.\n kwargs\n The extra keyword arguments for plot()\n \"\"\"\n\n super().plot(**kwargs)\n\n if plot_edges:\n # edges is a mapping {edge_name:edge_energy}\n edges = self._get_edges_to_plot(plot_edges, only_edges)\n self._plot_edge_labels(edges)\n\n self._plot.signal_plot.events.closed.connect(self._on_signal_plot_closing, [])\n\n def _on_signal_plot_closing(self):\n self._edge_markers = {\"lines\": None, \"texts\": None, \"names\": []}\n\n def _get_offsets_and_segments(self, edges):\n index = np.array([float(v) for v in edges.values()]) # dictionaries\n segments = np.empty((len(index), 2, 2))\n offsets = np.empty((len(index), 2))\n for i, ind in enumerate(index):\n segments[i] = [[ind, 1], [ind, 1.1]]\n offsets[i] = [ind, 1.1]\n return offsets, segments\n\n def _initialise_markers(self):\n self._edge_markers[\"lines\"] = Lines(\n segments=np.empty((0, 2, 2)),\n transform=\"relative\",\n color=\"black\",\n shift=np.array([0.0, 0.19]),\n )\n self._edge_markers[\"texts\"] = Texts(\n offsets=np.empty((0, 2)),\n texts=np.empty((0,)),\n offset_transform=\"relative\",\n rotation=np.pi / 2,\n horizontalalignment=\"left\",\n verticalalignment=\"bottom\",\n facecolor=\"black\",\n shift=0.2,\n )\n for key in [\"lines\", \"texts\"]:\n self.add_marker(self._edge_markers[key], render_figure=False)\n\n def _plot_edge_labels(self, edges):\n \"\"\"\n Plot the EELS edge label (vertical line segment and text box) on\n the signal\n\n Parameters\n ----------\n edges : dictionary\n A dictionary with the labels as keys and their energies as values.\n For example, {'Fe_L2': 721.0, 'O_K': 532.0}\n\n \"\"\"\n # the object is needed to connect replot method when axes_manager\n # indices changed\n _ = EdgesRange(self, interactive=False)\n self._add_edge_labels(edges)\n\n def _get_edges_to_plot(self, plot_edges, only_edges):\n # get the dictionary of the edge to be shown\n extra_element_edge_family = []\n if plot_edges is True:\n try:\n elements = self.metadata.Sample.elements\n except AttributeError:\n raise ValueError(\n \"No elements defined. Add them with \"\n \"s.add_elements, or specify elements, edge \"\n \"families or edges directly\"\n )\n else:\n extra_element_edge_family.extend(np.atleast_1d(plot_edges))\n try:\n elements = self.metadata.Sample.elements\n except:\n elements = []\n\n element_edge_family = elements + extra_element_edge_family\n edges_dict = self._get_edges(element_edge_family, only_edges)\n\n return edges_dict\n\n def _get_edges(self, element_edge_family, only_edges):\n # get corresponding information depending on whether it is an element\n # a particular edge or a family of edge\n axis_min = self.axes_manager[-1].low_value\n axis_max = self.axes_manager[-1].high_value\n\n names_and_energies = {}\n shells = [\"K\", \"L\", \"M\", \"N\", \"O\"]\n\n errmsg = \"Edge family '{}' is not supported. Supported edge family \" \"is {}.\"\n for member in element_edge_family:\n try:\n element, ss = member.split(\"_\")\n\n if len(ss) == 1:\n memtype = \"family\"\n if ss not in shells:\n raise AttributeError(errmsg.format(ss, shells))\n if len(ss) == 2:\n memtype = \"edge\"\n if ss[0] not in shells:\n raise AttributeError(errmsg.format(ss[0], shells))\n except ValueError:\n element = member\n ss = \"\"\n memtype = \"element\"\n\n try:\n Binding_energies = elements_db[element][\"Atomic_properties\"][\n \"Binding_energies\"\n ]\n except KeyError as err:\n raise ValueError(\"'{}' is not a valid element\".format(element)) from err\n\n for edge in Binding_energies.keys():\n relevance = Binding_energies[edge][\"relevance\"]\n energy = Binding_energies[edge][\"onset_energy (eV)\"]\n\n isInRel = relevance in only_edges\n isInRng = axis_min < energy < axis_max\n isSameFamily = ss in edge\n\n if memtype == \"element\":\n flag = isInRel & isInRng\n edge_key = element + \"_\" + edge\n elif memtype == \"edge\":\n flag = isInRng & (edge == ss)\n edge_key = member\n elif memtype == \"family\":\n flag = isInRel & isInRng & isSameFamily\n edge_key = element + \"_\" + edge\n\n if flag:\n names_and_energies[edge_key] = energy\n\n return names_and_energies\n\n def _remove_edge_labels(self, edge_names=None, render_figure=True):\n \"\"\"\n Remove EELS edges markers to the signal\n\n Parameters\n ----------\n edge_names : str, list of str or None\n The string must be the name of edges, e. g. 'Fe_L2'.\n If ``None`` (default), remove all edges.\n render_figure : bool\n If True, render the figure after adding the markers\n \"\"\"\n if edge_names is None:\n edge_names = self._edge_markers[\"names\"]\n if isinstance(edge_names, set):\n # convert to list to find the index\n edge_names = list(edge_names)\n if not isinstance(edge_names, (list, tuple, np.ndarray)):\n edge_names = [edge_names]\n\n ind = np.where(np.isin(self._edge_markers[\"names\"], edge_names))\n\n if self._edge_markers[\"lines\"] is not None:\n self._edge_markers[\"lines\"].remove_items(ind)\n if self._edge_markers[\"texts\"] is not None:\n self._edge_markers[\"texts\"].remove_items(ind)\n if self._edge_markers[\"names\"] is not []:\n self._edge_markers[\"names\"] = np.delete(self._edge_markers[\"names\"], ind)\n\n if render_figure:\n self._render_figure(plot=[\"signal_plot\"])\n\n def _add_edge_labels(self, edges, render_figure=True):\n \"\"\"\n Add EELS edges markers to the signal\n\n Parameters\n ----------\n edge_name : dictionary or set\n If dictionary must be the name of edge as key and energy as values,\n e.g. {'Cr_L2': 584.0}. If list or set, must the name of the edge,\n e.g. set('Cr_L2', )\n render_figure : bool\n If True, render the figure after adding the markers\n \"\"\"\n if isinstance(edges, set):\n edges_dict = {}\n for edge in edges:\n element, ss = edge.split(\"_\")\n Binding_energies = elements_db[element][\"Atomic_properties\"][\n \"Binding_energies\"\n ]\n edges_dict[edge] = Binding_energies[ss][\"onset_energy (eV)\"]\n edges = edges_dict\n\n offsets, segments = self._get_offsets_and_segments(edges)\n names = list(edges.keys())\n\n self._edge_markers[\"lines\"].add_items(segments=segments)\n self._edge_markers[\"lines\"].update()\n self._edge_markers[\"texts\"].add_items(offsets=offsets, texts=names)\n self._edge_markers[\"lines\"].update()\n self._edge_markers[\"names\"] = np.append(self._edge_markers[\"names\"], names)\n\n if render_figure:\n self._render_figure(plot=[\"signal_plot\"])\n\n def _get_complementary_edges(self, edges, only_major=False):\n \"\"\"\n Get other edges of the same element present within the energy\n range of the axis\n\n Parameters\n ----------\n edges : iterable\n A sequence of strings contains edges in the format of\n element_subshell for EELS. For example, ['Fe_L2', 'O_K']\n only_major : bool\n Whether to show only the major edges. The default is False.\n\n Returns\n -------\n complmt_edges : list\n A list containing all the complementary edges of the same element\n present within the energy range of the axis\n \"\"\"\n\n emin = self.axes_manager[-1].low_value\n emax = self.axes_manager[-1].high_value\n complmt_edges = []\n\n elements = set()\n for edge in edges:\n element, _ = edge.split(\"_\")\n elements.update([element])\n\n for element in elements:\n ss_info = elements_db[element][\"Atomic_properties\"][\"Binding_energies\"]\n\n for subshell in ss_info:\n sse = ss_info[subshell][\"onset_energy (eV)\"]\n ssr = ss_info[subshell][\"relevance\"]\n\n if only_major:\n if ssr != \"Major\":\n continue\n\n edge = element + \"_\" + subshell\n if (\n (emin <= sse <= emax)\n and (subshell[-1] != \"a\")\n and (edge not in edges)\n ):\n complmt_edges.append(edge)\n\n return complmt_edges\n\n def rebin(self, new_shape=None, scale=None, crop=True, dtype=None, out=None):\n factors = self._validate_rebin_args_and_get_factors(\n new_shape=new_shape, scale=scale\n )\n m = super().rebin(\n new_shape=new_shape, scale=scale, crop=crop, dtype=dtype, out=out\n )\n m = out or m\n time_factor = np.prod(\n [factors[axis.index_in_array] for axis in m.axes_manager.navigation_axes]\n )\n mdeels = m.metadata\n m.get_dimensions_from_data()\n if m.metadata.get_item(\"Acquisition_instrument.TEM.Detector.EELS\"):\n mdeels = m.metadata.Acquisition_instrument.TEM.Detector.EELS\n if \"dwell_time\" in mdeels:\n mdeels.dwell_time *= time_factor\n if \"exposure\" in mdeels:\n mdeels.exposure *= time_factor\n else:\n _logger.info(\n \"No dwell_time could be found in the metadata so \"\n \"this has not been updated.\"\n )\n if out is None:\n return m\n else:\n out.events.data_changed.trigger(obj=out)\n return m\n\n rebin.__doc__ = hyperspy.signal.BaseSignal.rebin.__doc__\n\n def vacuum_mask(\n self, threshold=10.0, start_energy=None, closing=True, opening=False\n ):\n \"\"\"\n Generate mask of the vacuum region\n\n Parameters\n ----------\n threshold: float\n For a given navigation coordinate, mean value in the energy axis\n below which the pixel is considered as vacuum.\n start_energy: float, None\n Minimum energy included in the calculation of the mean intensity.\n If None, consider only the last quarter of the spectrum to\n calculate the mask.\n closing: bool\n If True, a morphological closing is applied to the mask.\n opening: bool\n If True, a morphological opening is applied to the mask.\n\n Returns\n -------\n mask: signal\n The mask of the region.\n \"\"\"\n if self.axes_manager.navigation_dimension == 0:\n raise RuntimeError(\n \"Navigation dimenstion must be higher than 0 \"\n \"to estimate a vacuum mask.\"\n )\n signal_axis = self.axes_manager.signal_axes[0]\n if start_energy is None:\n start_energy = 0.75 * signal_axis.high_value\n\n mask = self.isig[start_energy:].mean(-1) <= threshold\n\n from scipy.ndimage import binary_dilation, binary_erosion\n\n if closing:\n mask.data = binary_dilation(mask.data, border_value=0)\n mask.data = binary_erosion(mask.data, border_value=1)\n if opening:\n mask.data = binary_erosion(mask.data, border_value=1)\n mask.data = binary_dilation(mask.data, border_value=0)\n return mask" } ]
import numpy as np import pytest import hyperspy.api as hs from hyperspy.components1d import Lorentzian from exspy.components import VolumePlasmonDrude from exspy.misc.eels.tools import eels_constant from exspy.signals import EELSSpectrum
20,793
# -*- coding: utf-8 -*- # Copyright 2007-2023 The exSpy developers # # This file is part of exSpy. # # exSpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # exSpy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with exSpy. If not, see <https://www.gnu.org/licenses/#GPL>. class Test2D: def setup_method(self, method): """To test the kramers_kronig_analysis we will generate 3 EELSSpectrum instances. First a model energy loss function(ELF), in our case following the Drude bulk plasmon peak. Second, we simulate the inelastic scattering to generate a model scattering distribution (SPC). Finally, we use a lorentzian peak with integral equal to 1 to simulate a ZLP. """ # Parameters i0 = 1.0 t = hs.signals.BaseSignal(np.arange(10, 70, 10).reshape((2, 3))) t = t.transpose(signal_axes=0) scale = 0.02 # Create an 3x2x2048 spectrum with Drude plasmon s = EELSSpectrum(np.zeros((2, 3, 2 * 2048))) s.set_microscope_parameters( beam_energy=300.0, convergence_angle=5, collection_angle=10.0 ) s.axes_manager.signal_axes[0].scale = scale
# -*- coding: utf-8 -*- # Copyright 2007-2023 The exSpy developers # # This file is part of exSpy. # # exSpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # exSpy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with exSpy. If not, see <https://www.gnu.org/licenses/#GPL>. class Test2D: def setup_method(self, method): """To test the kramers_kronig_analysis we will generate 3 EELSSpectrum instances. First a model energy loss function(ELF), in our case following the Drude bulk plasmon peak. Second, we simulate the inelastic scattering to generate a model scattering distribution (SPC). Finally, we use a lorentzian peak with integral equal to 1 to simulate a ZLP. """ # Parameters i0 = 1.0 t = hs.signals.BaseSignal(np.arange(10, 70, 10).reshape((2, 3))) t = t.transpose(signal_axes=0) scale = 0.02 # Create an 3x2x2048 spectrum with Drude plasmon s = EELSSpectrum(np.zeros((2, 3, 2 * 2048))) s.set_microscope_parameters( beam_energy=300.0, convergence_angle=5, collection_angle=10.0 ) s.axes_manager.signal_axes[0].scale = scale
k = eels_constant(s, i0, t)
1
2023-10-28 20:04:10+00:00
24k
Elfenreigen/UniChest
train.py
[ { "identifier": "utils", "path": "factory/utils.py", "snippet": "class SmoothedValue(object):\nclass MetricLogger(object):\nclass AttrDict(dict):\n def __init__(self, window_size=20, fmt=None):\n def update(self, value, n=1):\n def synchronize_between_processes(self):\n def median(self):\n def avg(self):\n def global_avg(self):\n def max(self):\n def value(self):\n def __str__(self):\n def __init__(self, delimiter=\"\\t\"):\n def update(self, **kwargs):\n def __getattr__(self, attr):\n def __str__(self):\n def global_avg(self):\n def synchronize_between_processes(self):\n def add_meter(self, name, meter):\n def log_every(self, iterable, print_freq, header=None):\n def __init__(self, *args, **kwargs):\ndef compute_acc(logits, label, reduction='mean'):\ndef compute_n_params(model, return_str=True):\ndef setup_for_distributed(is_master):\n def print(*args, **kwargs):\ndef seed_worker(worker_id):\ndef is_dist_avail_and_initialized():\ndef get_world_size():\ndef get_rank():\ndef is_main_process():\ndef save_on_master(*args, **kwargs):\ndef init_distributed_mode(args):\n MB = 1024.0 * 1024.0" }, { "identifier": "create_scheduler", "path": "scheduler/scheduler_factory.py", "snippet": "def create_scheduler(args, optimizer):\n num_epochs = args.epochs\n\n if getattr(args, 'lr_noise', None) is not None:\n lr_noise = getattr(args, 'lr_noise')\n if isinstance(lr_noise, (list, tuple)):\n noise_range = [n * num_epochs for n in lr_noise]\n if len(noise_range) == 1:\n noise_range = noise_range[0]\n else:\n noise_range = lr_noise * num_epochs\n else:\n noise_range = None\n\n lr_scheduler = None\n if args.sched == 'cosine':\n lr_scheduler = CosineLRScheduler(\n optimizer,\n t_initial=num_epochs,\n t_mul=getattr(args, 'lr_cycle_mul', 1.),\n lr_min=args.min_lr,\n decay_rate=args.decay_rate,\n warmup_lr_init=args.warmup_lr,\n warmup_t=args.warmup_epochs,\n cycle_limit=getattr(args, 'lr_cycle_limit', 1),\n t_in_epochs=True,\n noise_range_t=noise_range,\n noise_pct=getattr(args, 'lr_noise_pct', 0.67),\n noise_std=getattr(args, 'lr_noise_std', 1.),\n noise_seed=getattr(args, 'seed', 42),\n )\n num_epochs = lr_scheduler.get_cycle_length() + args.cooldown_epochs\n elif args.sched == 'tanh':\n lr_scheduler = TanhLRScheduler(\n optimizer,\n t_initial=num_epochs,\n t_mul=getattr(args, 'lr_cycle_mul', 1.),\n lr_min=args.min_lr,\n warmup_lr_init=args.warmup_lr,\n warmup_t=args.warmup_epochs,\n cycle_limit=getattr(args, 'lr_cycle_limit', 1),\n t_in_epochs=True,\n noise_range_t=noise_range,\n noise_pct=getattr(args, 'lr_noise_pct', 0.67),\n noise_std=getattr(args, 'lr_noise_std', 1.),\n noise_seed=getattr(args, 'seed', 42),\n )\n num_epochs = lr_scheduler.get_cycle_length() + args.cooldown_epochs\n elif args.sched == 'step':\n lr_scheduler = StepLRScheduler(\n optimizer,\n decay_t=args.decay_epochs,\n decay_rate=args.decay_rate,\n warmup_lr_init=args.warmup_lr,\n warmup_t=args.warmup_epochs,\n noise_range_t=noise_range,\n noise_pct=getattr(args, 'lr_noise_pct', 0.67),\n noise_std=getattr(args, 'lr_noise_std', 1.),\n noise_seed=getattr(args, 'seed', 42),\n )\n elif args.sched == 'plateau':\n mode = 'min' if 'loss' in getattr(args, 'eval_metric', '') else 'max'\n lr_scheduler = PlateauLRScheduler(\n optimizer,\n decay_rate=args.decay_rate,\n patience_t=args.patience_epochs,\n lr_min=args.min_lr,\n mode=mode,\n warmup_lr_init=args.warmup_lr,\n warmup_t=args.warmup_epochs,\n cooldown_t=0,\n noise_range_t=noise_range,\n noise_pct=getattr(args, 'lr_noise_pct', 0.67),\n noise_std=getattr(args, 'lr_noise_std', 1.),\n noise_seed=getattr(args, 'seed', 42),\n )\n\n return lr_scheduler, num_epochs" }, { "identifier": "create_optimizer", "path": "optim/optim_factory.py", "snippet": "def create_optimizer(args, model, image_encoder,text_encoder, filter_bias_and_bn=True):\n opt_lower = args.opt.lower()\n weight_decay = args.weight_decay\n if weight_decay and filter_bias_and_bn:\n skip = {}\n if hasattr(model, 'no_weight_decay'):\n skip = model.no_weight_decay()\n parameters = add_weight_decay(model,image_encoder,text_encoder, weight_decay, skip)\n weight_decay = 0.\n else:\n parameters = [filter(lambda p: p.requires_grad, model.parameters()),filter(lambda p: p.requires_grad, image_encoder.parameters()),filter(lambda p: p.requires_grad, text_encoder.parameters())]\n #model.parameters()\n\n # print(parameters)\n if 'fused' in opt_lower:\n assert has_apex and torch.cuda.is_available(), 'APEX and CUDA required for fused optimizers'\n\n opt_args = dict(lr=args.lr, weight_decay=weight_decay)\n if hasattr(args, 'opt_eps') and args.opt_eps is not None:\n opt_args['eps'] = args.opt_eps\n if hasattr(args, 'opt_betas') and args.opt_betas is not None:\n opt_args['betas'] = args.opt_betas\n if hasattr(args, 'opt_args') and args.opt_args is not None:\n opt_args.update(args.opt_args)\n\n opt_split = opt_lower.split('_')\n opt_lower = opt_split[-1]\n if opt_lower == 'sgd' or opt_lower == 'nesterov':\n opt_args.pop('eps', None)\n optimizer = optim.SGD(parameters, momentum=args.momentum, nesterov=True, **opt_args)\n elif opt_lower == 'momentum':\n opt_args.pop('eps', None)\n optimizer = optim.SGD(parameters, momentum=args.momentum, nesterov=False, **opt_args)\n elif opt_lower == 'adam':\n optimizer = optim.Adam(parameters, **opt_args)\n elif opt_lower == 'adamw':\n optimizer = optim.AdamW(parameters, **opt_args)\n elif opt_lower == 'nadam':\n optimizer = Nadam(parameters, **opt_args)\n elif opt_lower == 'radam':\n optimizer = RAdam(parameters, **opt_args)\n elif opt_lower == 'adamp': \n optimizer = AdamP(parameters, wd_ratio=0.01, nesterov=True, **opt_args)\n elif opt_lower == 'sgdp': \n optimizer = SGDP(parameters, momentum=args.momentum, nesterov=True, **opt_args)\n elif opt_lower == 'adadelta':\n optimizer = optim.Adadelta(parameters, **opt_args)\n elif opt_lower == 'adafactor':\n if not args.lr:\n opt_args['lr'] = None\n optimizer = Adafactor(parameters, **opt_args)\n elif opt_lower == 'adahessian':\n optimizer = Adahessian(parameters, **opt_args)\n elif opt_lower == 'rmsprop':\n optimizer = optim.RMSprop(parameters, alpha=0.9, momentum=args.momentum, **opt_args)\n elif opt_lower == 'rmsproptf':\n optimizer = RMSpropTF(parameters, alpha=0.9, momentum=args.momentum, **opt_args)\n elif opt_lower == 'novograd':\n optimizer = NovoGrad(parameters, **opt_args)\n elif opt_lower == 'nvnovograd':\n optimizer = NvNovoGrad(parameters, **opt_args)\n elif opt_lower == 'fusedsgd':\n opt_args.pop('eps', None)\n optimizer = FusedSGD(parameters, momentum=args.momentum, nesterov=True, **opt_args)\n elif opt_lower == 'fusedmomentum':\n opt_args.pop('eps', None)\n optimizer = FusedSGD(parameters, momentum=args.momentum, nesterov=False, **opt_args)\n elif opt_lower == 'fusedadam':\n optimizer = FusedAdam(parameters, adam_w_mode=False, **opt_args)\n elif opt_lower == 'fusedadamw':\n optimizer = FusedAdam(parameters, adam_w_mode=True, **opt_args)\n elif opt_lower == 'fusedlamb':\n optimizer = FusedLAMB(parameters, **opt_args)\n elif opt_lower == 'fusednovograd':\n opt_args.setdefault('betas', (0.95, 0.98))\n optimizer = FusedNovoGrad(parameters, **opt_args)\n else:\n assert False and \"Invalid optimizer\"\n raise ValueError\n\n if len(opt_split) > 1:\n if opt_split[0] == 'lookahead':\n optimizer = Lookahead(optimizer)\n\n return optimizer" }, { "identifier": "train", "path": "engine/train.py", "snippet": "def train(model, image_encoder, text_encoder, tokenizer, data_loader, optimizer, epoch, warmup_steps, device, scheduler, args, config, writer):\n clip_loss = ClipLoss()\n ce_loss = nn.CrossEntropyLoss(ignore_index=-1)\n \n if args.add_dataset:\n ASL_loss = AsymmetricLossAdd(gamma_neg=6, gamma_pos=0, clip=0.05, disable_torch_grad_focal_loss=True)\n else:\n ASL_loss = AsymmetricLoss(gamma_neg=6, gamma_pos=0, clip=0.05, disable_torch_grad_focal_loss=True)\n\n loss_m = AverageMeter()\n loss_clip_m = AverageMeter()\n loss_ce_m = AverageMeter()\n loss_ce_image_m = AverageMeter()\n loss_ce_text_m = AverageMeter()\n batch_time_m = AverageMeter()\n data_time_m = AverageMeter()\n end = time.time()\n\n model.train() \n image_encoder.train() \n text_encoder.train()\n metric_logger = utils.MetricLogger(delimiter=\" \")\n metric_logger.add_meter('lr', utils.SmoothedValue(window_size=50, fmt='{value:.6f}'))\n metric_logger.add_meter('loss', utils.SmoothedValue(window_size=50, fmt='{value:.6f}'))\n metric_logger.add_meter('loss_ce', utils.SmoothedValue(window_size=50, fmt='{value:.6f}'))\n metric_logger.add_meter('loss_ce_image', utils.SmoothedValue(window_size=50, fmt='{value:.6f}'))\n if args.use_entity_features:\n metric_logger.add_meter('loss_ce_text', utils.SmoothedValue(window_size=50, fmt='{value:.6f}'))\n metric_logger.add_meter('loss_clip', utils.SmoothedValue(window_size=50, fmt='{value:.6f}'))\n metric_logger.update(loss=1.0)\n metric_logger.update(lr = scheduler._get_lr(epoch)[0])\n\n header = 'Train Epoch: [{}]'.format(epoch)\n print_freq = 50 \n step_size = 100\n warmup_iterations = warmup_steps*step_size \n scalar_step = epoch*len(data_loader)\n num_batches_per_epoch = data_loader.num_batches\n sample_digits = math.ceil(math.log(data_loader.num_samples + 1, 10))\n\n for i, sample in enumerate(metric_logger.log_every(data_loader, print_freq, header)):\n if args.fourier:\n image = fourier_aug(sample['image'].to(device))\n else:\n image = sample['image'].to(device) \n label = sample['label'].long().to(device)\n\n if args.ignore_index:\n pass\n else:\n label[label==-1]=0\n entity = sample['entity']\n\n if args.add_dataset:\n dataset_label = sample['label_dataset']\n\n data_time_m.update(time.time() - end)\n\n optimizer.zero_grad()\n\n if args.add_dataset:\n text_list = ['normal', 'pleural effusion', 'opacity', 'pneumothorax', 'edema', 'atelectasis', 'tube', 'consolidation','enlarged cardiomediastinum','tip', 'pneumonia','line','cardiomegaly', 'fracture','calcification',\n 'device','engorgement', 'nodule', 'wire', 'pacemaker', 'pleural thicken', 'marking', 'scar', 'hyperinflate', 'blunt', 'collapse', 'emphysema', 'aerate', 'mass','infiltration', 'obscure', 'deformity', 'hernia',\n 'drainage', 'distention', 'shift', 'stent', 'lesion', 'hardware', 'dilation', 'aspiration',\n 'fibrosis',\t'No Finding', 'Pleural Other', 'Support Devices', 'Aortic enlargement',\n 'Clavicle fracture', 'Enlarged PA', 'ILD', 'Lung cavity', 'Lung cyst', 'Mediastinal shift',\t\n 'Nodule/Mass', 'Pulmonary fibrosis', 'Rib fracture', 'Other lesion', 'COPD', 'Lung tumor', 'Tuberculosis',\n 'Other diseases']\n\n else:\n\n text_list = ['normal', 'pleural effusion', 'opacity', 'pneumothorax', 'edema', 'atelectasis', 'tube', 'consolidation','enlarged cardiomediastinum','tip', 'pneumonia','line','cardiomegaly', 'fracture','calcification',\n 'device','engorgement', 'nodule', 'wire', 'pacemaker', 'pleural thicken', 'marking', 'scar', 'hyperinflate', 'blunt', 'collapse', 'emphysema', 'aerate', 'mass','infiltration', 'obscure', 'deformity', 'hernia',\n 'drainage', 'distention', 'shift', 'stent', 'lesion', 'hardware', 'dilation', 'aspiration']\n \n \n text_features = get_text_features(text_encoder,text_list,tokenizer,device,max_length=args.max_length)\n entity_features = get_text_features(text_encoder,entity,tokenizer,device,max_length=args.max_length)\n\n image_features,image_features_pool = image_encoder(image)\n if args.add_dataset:\n pred_class_image, moe_img = model(image_features,text_features,args)\n else:\n pred_class_image = model(image_features,text_features)\n\n\n if args.bce or args.asl:\n label = label.float()\n\n label_mask = (label != -1).squeeze()\n\n\n\n if args.add_dataset:\n loss_moe_img = moe_cl_loss(moe_img, dataset_label)\n\n if args.asl:\n pred_class_image = pred_class_image[label_mask]\n label_image = label[label_mask] \n loss_ce_image = ASL_loss(pred_class_image.view(-1,1),label_image.view(-1,1))\n elif args.bce:\n pred_class_image = pred_class_image[label_mask]\n label_image = label[label_mask] \n loss_ce_image = F.binary_cross_entropy(pred_class_image.view(-1,1),label_image.view(-1,1))\n else:\n if args.asl:\n loss_ce_image = ASL_loss(pred_class_image.view(-1,1),label.view(-1,1))\n elif args.bce:\n loss_ce_image = F.binary_cross_entropy_with_logits(pred_class_image.view(-1,1),label.view(-1,1)) \n else:\n loss_ce_image = ce_loss(pred_class_image.view(-1,2),label.view(-1)) \n\n if args.use_entity_features:\n if args.add_dataset:\n pred_class_text, moe_txt = model(entity_features.unsqueeze(1),text_features,args)\n loss_moe_txt = moe_cl_loss(moe_txt, dataset_label)\n else:\n pred_class_text = model(entity_features.unsqueeze(1),text_features)\n\n if args.add_dataset:\n if args.asl:\n pred_class_text = pred_class_text[label_mask]\n label_text = label[label_mask] \n loss_ce_text = ASL_loss(pred_class_text.view(-1,1),label_text.view(-1,1))\n \n elif args.bce:\n pred_class_text = pred_class_text[label_mask]\n label_text = label[label_mask] \n loss_ce_text = F.binary_cross_entropy(pred_class_text.view(-1,1),label_text.view(-1,1))\n\n else:\n if args.asl:\n loss_ce_text = ASL_loss(pred_class_text.view(-1,1),label.view(-1,1))\n elif args.bce:\n loss_ce_text = F.binary_cross_entropy_with_logits(pred_class_text.view(-1,1),label.view(-1,1)) \n else:\n loss_ce_text = ce_loss(pred_class_text.view(-1,2),label.view(-1))\n\n loss_ce = loss_ce_image + loss_ce_text\n if args.add_dataset:\n loss_moe = loss_moe_img + loss_moe_txt\n\n else:\n loss_ce = loss_ce_image\n if args.add_dataset:\n loss_moe = loss_moe_img\n\n\n loss_clip = clip_loss(image_features_pool,entity_features)\n if args.add_dataset:\n loss = loss_ce + loss_clip * args.loss_ratio + args.moe_ratio * loss_moe\n else:\n loss = loss_ce + loss_clip * args.loss_ratio\n \n\n loss.backward()\n optimizer.step() \n \n writer.add_scalar('loss/loss', loss, scalar_step)\n writer.add_scalar('loss/loss_ce', loss_ce, scalar_step)\n writer.add_scalar('loss/loss_ce_image', loss_ce_image, scalar_step)\n if args.use_entity_features:\n writer.add_scalar('loss/loss_ce_text', loss_ce_text, scalar_step)\n writer.add_scalar('loss/loss_clip', loss_clip, scalar_step)\n scalar_step += 1\n\n metric_logger.update(loss=loss.item())\n metric_logger.update(loss_ce=loss_ce.item())\n metric_logger.update(loss_ce_image=loss_ce_image.item())\n if args.use_entity_features:\n metric_logger.update(loss_ce_text=loss_ce_text.item())\n metric_logger.update(loss_clip=loss_clip.item())\n\n\n if epoch==0 and i%step_size==0 and i<=warmup_iterations: \n scheduler.step(i//step_size) \n metric_logger.update(lr = scheduler._get_lr(epoch)[0])\n\n batch_time_m.update(time.time() - end)\n end = time.time()\n batch_count = i + 1\n if i % 100 == 0:\n batch_size = len(image)\n num_samples = batch_count * batch_size\n samples_per_epoch = data_loader.num_samples\n percent_complete = 100.0 * batch_count / num_batches_per_epoch\n\n # NOTE loss is coarsely sampled, just master node and per log update\n loss_m.update(loss.item(), batch_size)\n loss_clip_m.update(loss_clip.item(), batch_size)\n loss_ce_m.update(loss_ce.item(), batch_size)\n loss_ce_image_m.update(loss_ce_image.item(), batch_size)\n if args.use_entity_features:\n loss_ce_text_m.update(loss_ce_text.item(), batch_size)\n logging.info(\n f\"Train Epoch: {epoch} [{num_samples:>{sample_digits}}/{samples_per_epoch} ({percent_complete:.0f}%)] \"\n f\"Loss: {loss_m.val:#.5g} ({loss_m.avg:#.4g}) \"\n f\"Loss_clip: {loss_clip_m.val:#.5g} ({loss_clip_m.avg:#.4g}) \"\n f\"Loss_ce: {loss_ce_m.val:#.5g} ({loss_ce_m.avg:#.4g}) \"\n f\"Loss_ce_image: {loss_ce_image_m.val:#.5g} ({loss_ce_image_m.avg:#.4g}) \"\n f\"Loss_ce_text: {loss_ce_text_m.val:#.5g} ({loss_ce_text_m.avg:#.4g}) \"\n f\"Data (t): {data_time_m.avg:.3f} \"\n f\"Batch (t): {batch_time_m.avg:.3f}, {batch_size/ batch_time_m.val:#g}/s \"\n f\"LR: { scheduler._get_lr(epoch)[0]:5f} \"\n )\n else:\n logging.info(\n f\"Train Epoch: {epoch} [{num_samples:>{sample_digits}}/{samples_per_epoch} ({percent_complete:.0f}%)] \"\n f\"Loss: {loss_m.val:#.5g} ({loss_m.avg:#.4g}) \"\n f\"Loss_clip: {loss_clip_m.val:#.5g} ({loss_clip_m.avg:#.4g}) \"\n f\"Loss_ce: {loss_ce_m.val:#.5g} ({loss_ce_m.avg:#.4g}) \"\n f\"Loss_ce_image: {loss_ce_image_m.val:#.5g} ({loss_ce_image_m.avg:#.4g}) \"\n f\"Data (t): {data_time_m.avg:.3f} \"\n f\"Batch (t): {batch_time_m.avg:.3f}, {batch_size/ batch_time_m.val:#g}/s \"\n f\"LR: { scheduler._get_lr(epoch)[0]:5f} \"\n )\n\n # gather the stats from all processes\n metric_logger.synchronize_between_processes()\n print(\"Averaged stats:\", metric_logger.global_avg()) \n return {k: \"{:.6f}\".format(meter.global_avg) for k, meter in metric_logger.meters.items()} #,loss_epoch.mean()" }, { "identifier": "valid_on_cheXpert", "path": "engine/train.py", "snippet": "def valid_on_cheXpert(model,image_encoder,text_encoder,tokenizer,data_loader, epoch, device, args, config, writer):\n criterion = nn.CrossEntropyLoss()\n model.eval()\n image_encoder.eval()\n text_encoder.eval()\n text_list = ['atelectasis', 'cardiomegaly', 'consolidation', 'edema', 'pleural effusion']\n text_features = get_text_features(text_encoder,text_list,tokenizer,device,max_length=args.max_length)\n \n val_scalar_step = epoch*len(data_loader)\n val_losses = []\n\n # initialize the ground truth and output tensor\n gt = torch.FloatTensor()\n gt = gt.cuda()\n pred = torch.FloatTensor()\n pred = pred.cuda()\n\n for i, sample in enumerate(data_loader):\n image = sample['image'].to(device,non_blocking=True) \n label = sample['label'].long().to(device)\n if args.bce or args.asl:\n label = label.float()\n\n gt = torch.cat((gt, label), 0)\n with torch.no_grad():\n image_features,image_features_pool = image_encoder(image)\n \n # \n if args.add_dataset:\n pred_class,_ = model(image_features,text_features,args)#b,14,2/1\n val_loss = F.binary_cross_entropy(pred_class.view(-1,1),label.view(-1, 1))\n pred = torch.cat((pred, pred_class[:,:,0]), 0)\n else:\n pred_class = model(image_features,text_features)#b,14,2/1\n if args.bce or args.asl:\n val_loss = F.binary_cross_entropy_with_logits(pred_class.view(-1,1),label.view(-1, 1))\n pred_class = torch.sigmoid(pred_class)\n pred = torch.cat((pred, pred_class[:,:,0]), 0)\n else:\n val_loss = criterion(pred_class.view(-1,2),label.view(-1))\n pred_class = torch.softmax(pred_class, dim=-1)\n pred = torch.cat((pred, pred_class[:,:,1]), 0)\n \n val_losses.append(val_loss.item())\n writer.add_scalar('val_loss/loss', val_loss, val_scalar_step)\n val_scalar_step += 1\n metrics = compute_AUCs(gt, pred, n_class=5)\n AUROC_avg = metrics['mean_auc']\n avg_val_loss = np.array(val_losses).mean()\n return avg_val_loss,AUROC_avg,metrics" }, { "identifier": "valid_on_chestxray14", "path": "engine/train.py", "snippet": "def valid_on_chestxray14(model, image_encoder, text_encoder, tokenizer, data_loader, epoch, device, args, config, writer):\n criterion = nn.CrossEntropyLoss()\n model.eval()\n image_encoder.eval()\n text_encoder.eval()\n text_list = [\"atelectasis\",\"cardiomegaly\",\"pleural effusion\",\"infiltration\",\"lung mass\",\"lung nodule\",\"pneumonia\",\"pneumothorax\",\"consolidation\",\"edema\",\"emphysema\",\"fibrosis\",\"pleural thicken\",\"hernia\"]\n text_features = get_text_features(text_encoder,text_list,tokenizer,device,max_length=args.max_length)\n \n val_scalar_step = epoch*len(data_loader)\n val_losses = []\n\n gt = torch.FloatTensor()\n gt = gt.cuda()\n pred = torch.FloatTensor()\n pred = pred.cuda()\n\n for i, sample in enumerate(data_loader):\n image = sample['image'].to(device,non_blocking=True) \n label = sample['label'].long().to(device)\n if args.bce or args.asl:\n label = label.float()\n\n gt = torch.cat((gt, label), 0)\n with torch.no_grad():\n image_features,image_features_pool = image_encoder(image)\n\n if args.add_dataset:\n pred_class,_ = model(image_features,text_features,args)#b,14,2/1\n val_loss = F.binary_cross_entropy(pred_class.view(-1,1),label.view(-1, 1))\n pred = torch.cat((pred, pred_class[:,:,0]), 0)\n else:\n pred_class = model(image_features,text_features)#b,14,2/1\n if args.bce or args.asl:\n val_loss = F.binary_cross_entropy_with_logits(pred_class.view(-1,1),label.view(-1, 1))\n pred_class = torch.sigmoid(pred_class)\n pred = torch.cat((pred, pred_class[:,:,0]), 0)\n else:\n val_loss = criterion(pred_class.view(-1,2),label.view(-1))\n pred_class = torch.softmax(pred_class, dim=-1)\n pred = torch.cat((pred, pred_class[:,:,1]), 0)\n\n\n\n val_losses.append(val_loss.item())\n writer.add_scalar('val_loss/loss', val_loss, val_scalar_step)\n val_scalar_step += 1\n metrics = compute_AUCs(gt, pred, n_class = 14)\n AUROC_avg = metrics['mean_auc']\n avg_val_loss = np.array(val_losses).mean()\n return avg_val_loss,AUROC_avg,metrics" }, { "identifier": "CLP_clinical", "path": "models/clip_tqn.py", "snippet": "class CLP_clinical(nn.Module):\n def __init__(self,\n bert_model_name: str,\n embed_dim: int = 768,\n freeze_layers:Union[Tuple[int, int], int] = None):\n super().__init__()\n self.bert_model = self._get_bert_basemodel(bert_model_name=bert_model_name, freeze_layers=freeze_layers)\n self.mlp_embed = nn.Sequential(\n nn.Linear(embed_dim, embed_dim),\n nn.GELU(),\n nn.Linear(embed_dim, embed_dim)\n )\n self.embed_dim = embed_dim\n self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))\n self.init_parameters()\n \n def init_parameters(self):\n nn.init.constant_(self.logit_scale, np.log(1 / 0.07))\n for m in self.mlp_embed:\n if isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, std=self.embed_dim ** -0.5)\n\n def _get_bert_basemodel(self, bert_model_name, freeze_layers=None):#12\n try:\n print(bert_model_name)\n config = BertConfig.from_pretrained(bert_model_name, output_hidden_states=True)#bert-base-uncased\n model = AutoModel.from_pretrained(bert_model_name, config=config)#, return_dict=True)\n print(\"Text feature extractor:\", bert_model_name)\n print(\"bert encoder layers:\",len(model.encoder.layer))\n except:\n raise (\"Invalid model name. Check the config file and pass a BERT model from transformers lybrary\")\n\n if freeze_layers is not None:\n for layer_idx in freeze_layers:\n for param in list(model.encoder.layer[layer_idx].parameters()):\n param.requires_grad = False\n return model\n\n def encode_text(self, text):\n #input batch_size,token, return batch_size,dim \n output = self.bert_model(input_ids = text['input_ids'],attention_mask = text['attention_mask'] )\n last_hidden_state, pooler_output, hidden_states = output[0],output[1],output[2]\n encode_out = self.mlp_embed(pooler_output)\n # encode_out = pooler_output\n return encode_out\n \n def forward(self,text1,text2):\n text1_features = self.encode_text(text1)\n text2_features = self.encode_text(text2)\n text1_features = F.normalize(text1_features, dim=-1)\n text2_features = F.normalize(text2_features, dim=-1)\n return text1_features, text2_features, self.logit_scale.exp()" }, { "identifier": "ModelRes", "path": "models/clip_tqn.py", "snippet": "class ModelRes(nn.Module):\n def __init__(self, res_base_model):\n super(ModelRes, self).__init__()\n self.resnet_dict = {\"resnet50\": models.resnet50(pretrained=True)}\n self.resnet = self._get_res_basemodel(res_base_model)\n\n num_ftrs = int(self.resnet.fc.in_features)\n self.res_features = nn.Sequential(*list(self.resnet.children())[:-2])\n\n self.res_l1 = nn.Linear(num_ftrs, num_ftrs)\n self.res_l2 = nn.Linear(num_ftrs, 768)\n\n def _get_res_basemodel(self, res_model_name):\n try:\n res_model = self.resnet_dict[res_model_name]\n print(\"Image feature extractor:\", res_model_name)\n return res_model\n except:\n raise (\"Invalid model name. Check the config file and pass one of: resnet18 or resnet50\")\n\n def forward(self, img):\n batch_size = img.shape[0]\n res_fea = self.res_features(img)\n\n res_fea = rearrange(res_fea,'b d n1 n2 -> b (n1 n2) d')\n h = rearrange(res_fea,'b n d -> (b n) d')\n x = self.res_l1(h)\n x = F.relu(x)\n x = self.res_l2(x)\n out_emb = rearrange(x,'(b n) d -> b n d',b=batch_size)\n out_pool = torch.mean(out_emb,dim=1)\n return out_emb,out_pool" }, { "identifier": "TQN_Model", "path": "models/clip_tqn.py", "snippet": "class TQN_Model(nn.Module):\n def __init__(self, \n embed_dim: int = 768, \n class_num: int = 1, \n lam: list = [1, 0]\n ):\n super().__init__()\n self.d_model = embed_dim\n self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))\n decoder_layer = TransformerDecoderLayer(self.d_model, 4, 1024,\n 0.1, 'relu',normalize_before=True)\n decoder_layerV1 = TransformerDecoderLayerV1(self.d_model, 4, 1024,\n 0.1, 'relu', True, lam)\n self.decoder_norm = nn.LayerNorm(self.d_model)\n self.decoder = TransformerDecoder(decoder_layer, 4, self.decoder_norm,\n return_intermediate=False)\n self.decoderV1 = TransformerDecoderV1(decoder_layerV1, 4, self.decoder_norm,\n return_intermediate=False)\n \n self.dropout_feas = nn.Dropout(0.1)\n\n self.mlp_head = nn.Sequential( # nn.LayerNorm(768),\n nn.Linear(embed_dim, class_num)\n )\n self.apply(self._init_weights)\n \n @staticmethod\n def _init_weights(module):\n if isinstance(module, nn.Linear):\n module.weight.data.normal_(mean=0.0, std=0.02)\n\n elif isinstance(module, nn.MultiheadAttention):\n module.in_proj_weight.data.normal_(mean=0.0, std=0.02)\n module.out_proj.weight.data.normal_(mean=0.0, std=0.02)\n\n elif isinstance(module, nn.Embedding):\n module.weight.data.normal_(mean=0.0, std=0.02)\n if module.padding_idx is not None:\n module.weight.data[module.padding_idx].zero_()\n \n def forward(self, image_features, text_features):\n\n batch_size = image_features.shape[0]\n image_features = image_features.transpose(0,1)\n text_features = text_features.unsqueeze(1).repeat(1, batch_size, 1)\n image_features = self.decoder_norm(image_features)\n text_features = self.decoder_norm(text_features)\n \n image_features_pool = torch.mean(image_features,dim=0).unsqueeze(0)\n features = self.decoderV1(text_features, image_features, image_features_pool,\n memory_key_padding_mask=None, pos=None, query_pos=None) \n \n features = self.dropout_feas(features).transpose(0,1) #b,embed_dim\n out = self.mlp_head(features) #(batch_size, query_num)\n return out" }, { "identifier": "TQN_Model_Add", "path": "models/clip_tqn.py", "snippet": "class TQN_Model_Add(nn.Module):\n def __init__(self, \n embed_dim: int = 768, \n class_num: int = 1, \n gate_num: int = 3,\n high_dim: int = 32,\n lam: list = [1, 0]\n ):\n super().__init__()\n self.d_model = embed_dim\n self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))\n decoder_layer = TransformerDecoderLayer(self.d_model, 4, 1024,\n 0.1, 'relu',normalize_before=True)\n decoder_layerV1 = TransformerDecoderLayerV1(self.d_model, 4, 1024,\n 0.1, 'relu', True, lam)\n self.decoder_norm = nn.LayerNorm(self.d_model)\n self.decoder = TransformerDecoder(decoder_layer, 4, self.decoder_norm,\n return_intermediate=False)\n self.decoderV1 = TransformerDecoderV1(decoder_layerV1, 4, self.decoder_norm,\n return_intermediate=False)\n \n self.decoderV1_1 = TransformerDecoderV1(decoder_layerV1, 4, self.decoder_norm,\n return_intermediate=False)\n self.decoderV1_2 = TransformerDecoderV1(decoder_layerV1, 4, self.decoder_norm,\n return_intermediate=False)\n self.decoderV1_3 = TransformerDecoderV1(decoder_layerV1, 4, self.decoder_norm,\n return_intermediate=False)\n\n self.dropout_feas = nn.Dropout(0.1)\n\n self.mlp_head = nn.Sequential( # nn.LayerNorm(768),\n nn.Linear(embed_dim, class_num)\n )\n self.mlp_head_1 = nn.Sequential( # nn.LayerNorm(768),\n nn.Linear(embed_dim, class_num)\n )\n self.mlp_head_2 = nn.Sequential( # nn.LayerNorm(768),\n nn.Linear(embed_dim, class_num)\n )\n self.mlp_head_3 = nn.Sequential( # nn.LayerNorm(768),\n nn.Linear(embed_dim, class_num)\n ) \n \n self.gate_head = nn.Sequential(\n nn.Linear(embed_dim, gate_num)\n )\n self.cl_head = nn.Sequential(\n nn.Linear(gate_num, high_dim)\n )\n\n self.apply(self._init_weights)\n \n @staticmethod\n def _init_weights(module):\n if isinstance(module, nn.Linear):\n module.weight.data.normal_(mean=0.0, std=0.02)\n\n elif isinstance(module, nn.MultiheadAttention):\n module.in_proj_weight.data.normal_(mean=0.0, std=0.02)\n module.out_proj.weight.data.normal_(mean=0.0, std=0.02)\n\n elif isinstance(module, nn.Embedding):\n module.weight.data.normal_(mean=0.0, std=0.02)\n if module.padding_idx is not None:\n module.weight.data[module.padding_idx].zero_()\n \n def forward(self, image_features, text_features, args):\n\n batch_size = image_features.shape[0]\n image_features = image_features.transpose(0,1)\n text_features = text_features.unsqueeze(1).repeat(1, batch_size, 1)\n image_features = self.decoder_norm(image_features)\n text_features = self.decoder_norm(text_features)\n \n image_features_pool = torch.mean(image_features,dim=0).unsqueeze(0)\n features = self.decoderV1(text_features, image_features, image_features_pool,\n memory_key_padding_mask=None, pos=None, query_pos=None)\n gate_weight = self.gate_head(image_features_pool.squeeze(0)) \n \n features = self.dropout_feas(features).transpose(0,1) #b,embed_dim\n \n \n if args.finetune:\n features_1 = self.decoderV1_1(text_features, image_features, image_features_pool,\n memory_key_padding_mask=None, pos=None, query_pos=None)\n features_1 = self.dropout_feas(features_1).transpose(0,1) \n features_2 = self.decoderV1_2(text_features, image_features, image_features_pool,\n memory_key_padding_mask=None, pos=None, query_pos=None)\n features_2 = self.dropout_feas(features_2).transpose(0,1) \n features_3 = self.decoderV1_3(text_features, image_features, image_features_pool,\n memory_key_padding_mask=None, pos=None, query_pos=None)\n features_3 = self.dropout_feas(features_3).transpose(0,1) \n \n out_1 = torch.sigmoid(self.mlp_head_1(features_1))\n out_2 = torch.sigmoid(self.mlp_head_2(features_2))\n out_3 = torch.sigmoid(self.mlp_head_3(features_3))\n\n\n out = self.mlp_head(features)\n \n gate_weight = torch.softmax(gate_weight, dim=1)\n out = torch.sigmoid(out)\n\n high_dimension = self.cl_head(gate_weight)\n out_bias = gate_weight[:,0].unsqueeze(1).unsqueeze(2) * out_1 + gate_weight[:,1].unsqueeze(1).unsqueeze(2) * out_2 + gate_weight[:,2].unsqueeze(1).unsqueeze(2) * out_3\n\n out = args.main_ratio * out + args.bias_ratio * out_bias\n\n return out, high_dimension" }, { "identifier": "ModelDense", "path": "models/clip_tqn.py", "snippet": "class ModelDense(nn.Module):\n def __init__(self, dense_base_model):\n super(ModelDense, self).__init__()\n \n self.densenet_dict = {\"densenet121\": models.densenet121(pretrained=True)}#,\n # \"densenet161\": models.densenet161(pretrained=True)}\n self.densenet = self._get_dense_basemodel(dense_base_model)\n num_ftrs = int(self.densenet.classifier.in_features)\n self.dense_features = self.densenet.features\n self.dense_l1 = nn.Linear(num_ftrs, num_ftrs)\n self.dense_l2 = nn.Linear(num_ftrs, 768)\n\n def _get_dense_basemodel(self, dense_base_model):\n try:\n dense_model = self.densenet_dict[dense_base_model]\n print(\"Image feature extractor:\", dense_base_model)\n return dense_model\n except:\n raise (\"Invalid model name. Check the config file and pass one of: densenet121 or densenet161\")\n\n def forward(self, img):\n batch_size = img.shape[0]\n dense_fea = self.dense_features(img)#N, 1024, 7,7\n dense_fea = rearrange(dense_fea,'b d n1 n2 -> b (n1 n2) d')\n h = rearrange(dense_fea,'b n d -> (b n) d')\n x = self.dense_l1(h)\n x = F.relu(x)\n x = self.dense_l2(x)\n out_emb = rearrange(x,'(b n) d -> b n d',b=batch_size)\n out_pool = torch.mean(out_emb,dim=1)\n return out_emb,out_pool" }, { "identifier": "CLP_clinical2", "path": "models/clip_tqn.py", "snippet": "class CLP_clinical2(nn.Module):\n def __init__(self,\n bert_model_name: str,\n embed_dim: int = 768,\n freeze_layers:Union[Tuple[int, int], int] = None):\n super().__init__()\n self.bert_model = self._get_bert_basemodel(bert_model_name=bert_model_name, freeze_layers=freeze_layers)\n\n\n def _get_bert_basemodel(self, bert_model_name, freeze_layers=None):#12\n try:\n print(bert_model_name)\n model = AutoModel.from_pretrained(bert_model_name)\n print(\"Text feature extractor:\", bert_model_name)\n print(\"bert encoder layers:\",len(model.encoder.layer))\n except:\n raise (\"Invalid model name. Check the config file and pass a BERT model from transformers lybrary\")\n\n if freeze_layers is not None:\n for layer_idx in freeze_layers:\n for param in list(model.encoder.layer[layer_idx].parameters()):\n param.requires_grad = False\n return model\n\n def encode_text(self, text):\n output = self.bert_model(input_ids = text['input_ids'],attention_mask = text['attention_mask'] )\n encode_out = output.last_hidden_state[:,0,:]\n return encode_out\n \n def forward(self,text1,text2):\n text1_features = self.encode_text(text1)\n text2_features = self.encode_text(text2)\n text1_features = F.normalize(text1_features, dim=-1)\n text2_features = F.normalize(text2_features, dim=-1)\n return text1_features, text2_features, self.logit_scale.exp()" }, { "identifier": "BertTokenizer", "path": "models/tokenization_bert.py", "snippet": "class BertTokenizer(PreTrainedTokenizer):\n r\"\"\"\n Construct a BERT tokenizer. Based on WordPiece.\n This tokenizer inherits from :class:`~transformers.PreTrainedTokenizer` which contains most of the main methods.\n Users should refer to this superclass for more information regarding those methods.\n Args:\n vocab_file (:obj:`str`):\n File containing the vocabulary.\n do_lower_case (:obj:`bool`, `optional`, defaults to :obj:`True`):\n Whether or not to lowercase the input when tokenizing.\n do_basic_tokenize (:obj:`bool`, `optional`, defaults to :obj:`True`):\n Whether or not to do basic tokenization before WordPiece.\n never_split (:obj:`Iterable`, `optional`):\n Collection of tokens which will never be split during tokenization. Only has an effect when\n :obj:`do_basic_tokenize=True`\n unk_token (:obj:`str`, `optional`, defaults to :obj:`\"[UNK]\"`):\n The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this\n token instead.\n sep_token (:obj:`str`, `optional`, defaults to :obj:`\"[SEP]\"`):\n The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for\n sequence classification or for a text and a question for question answering. It is also used as the last\n token of a sequence built with special tokens.\n pad_token (:obj:`str`, `optional`, defaults to :obj:`\"[PAD]\"`):\n The token used for padding, for example when batching sequences of different lengths.\n cls_token (:obj:`str`, `optional`, defaults to :obj:`\"[CLS]\"`):\n The classifier token which is used when doing sequence classification (classification of the whole sequence\n instead of per-token classification). It is the first token of the sequence when built with special tokens.\n mask_token (:obj:`str`, `optional`, defaults to :obj:`\"[MASK]\"`):\n The token used for masking values. This is the token used when training this model with masked language\n modeling. This is the token which the model will try to predict.\n tokenize_chinese_chars (:obj:`bool`, `optional`, defaults to :obj:`True`):\n Whether or not to tokenize Chinese characters.\n This should likely be deactivated for Japanese (see this `issue\n <https://github.com/huggingface/transformers/issues/328>`__).\n strip_accents: (:obj:`bool`, `optional`):\n Whether or not to strip all accents. If this option is not specified, then it will be determined by the\n value for :obj:`lowercase` (as in the original BERT).\n \"\"\"\n\n vocab_files_names = VOCAB_FILES_NAMES\n pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP\n pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION\n max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES\n\n def __init__(\n self,\n vocab_file,\n do_lower_case=True,\n do_basic_tokenize=True,\n never_split=None,\n unk_token=\"[UNK]\",\n sep_token=\"[SEP]\",\n pad_token=\"[PAD]\",\n cls_token=\"[CLS]\",\n mask_token=\"[MASK]\",\n tokenize_chinese_chars=True,\n strip_accents=None,\n **kwargs\n ):\n super().__init__(\n do_lower_case=do_lower_case,\n do_basic_tokenize=do_basic_tokenize,\n never_split=never_split,\n unk_token=unk_token,\n sep_token=sep_token,\n pad_token=pad_token,\n cls_token=cls_token,\n mask_token=mask_token,\n tokenize_chinese_chars=tokenize_chinese_chars,\n strip_accents=strip_accents,\n **kwargs,\n )\n\n if not os.path.isfile(vocab_file):\n raise ValueError(\n \"Can't find a vocabulary file at path '{}'. To load the vocabulary from a Google pretrained \"\n \"model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`\".format(vocab_file)\n )\n self.vocab = load_vocab(vocab_file)\n self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])\n self.do_basic_tokenize = do_basic_tokenize\n if do_basic_tokenize:\n self.basic_tokenizer = BasicTokenizer(\n do_lower_case=do_lower_case,\n never_split=never_split,\n tokenize_chinese_chars=tokenize_chinese_chars,\n strip_accents=strip_accents,\n )\n self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=self.unk_token)\n\n @property\n def do_lower_case(self):\n return self.basic_tokenizer.do_lower_case\n\n @property\n def vocab_size(self):\n return len(self.vocab)\n\n def get_vocab(self):\n return dict(self.vocab, **self.added_tokens_encoder)\n\n def _tokenize(self, text):\n split_tokens = []\n if self.do_basic_tokenize:\n for token in self.basic_tokenizer.tokenize(text, never_split=self.all_special_tokens):\n\n # If the token is part of the never_split set\n if token in self.basic_tokenizer.never_split:\n split_tokens.append(token)\n else:\n split_tokens += self.wordpiece_tokenizer.tokenize(token)\n else:\n split_tokens = self.wordpiece_tokenizer.tokenize(text)\n return split_tokens\n\n def _convert_token_to_id(self, token):\n \"\"\" Converts a token (str) in an id using the vocab. \"\"\"\n return self.vocab.get(token, self.vocab.get(self.unk_token))\n\n def _convert_id_to_token(self, index):\n \"\"\"Converts an index (integer) in a token (str) using the vocab.\"\"\"\n return self.ids_to_tokens.get(index, self.unk_token)\n\n def convert_tokens_to_string(self, tokens):\n \"\"\" Converts a sequence of tokens (string) in a single string. \"\"\"\n out_string = \" \".join(tokens).replace(\" ##\", \"\").strip()\n return out_string\n\n def build_inputs_with_special_tokens(\n self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None\n ) -> List[int]:\n \"\"\"\n Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and\n adding special tokens. A BERT sequence has the following format:\n - single sequence: ``[CLS] X ``\n - pair of sequences: ``[CLS] A [SEP] B [SEP]``\n Args:\n token_ids_0 (:obj:`List[int]`):\n List of IDs to which the special tokens will be added.\n token_ids_1 (:obj:`List[int]`, `optional`):\n Optional second list of IDs for sequence pairs.\n Returns:\n :obj:`List[int]`: List of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens.\n \"\"\"\n if token_ids_1 is None:\n return [self.cls_token_id] + token_ids_0\n cls = [self.cls_token_id]\n sep = [self.sep_token_id]\n return cls + token_ids_0 + sep + token_ids_1 + sep\n\n def get_special_tokens_mask(\n self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False\n ) -> List[int]:\n \"\"\"\n Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding\n special tokens using the tokenizer ``prepare_for_model`` method.\n Args:\n token_ids_0 (:obj:`List[int]`):\n List of IDs.\n token_ids_1 (:obj:`List[int]`, `optional`):\n Optional second list of IDs for sequence pairs.\n already_has_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`):\n Whether or not the token list is already formatted with special tokens for the model.\n Returns:\n :obj:`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.\n \"\"\"\n\n if already_has_special_tokens:\n if token_ids_1 is not None:\n raise ValueError(\n \"You should not supply a second sequence if the provided sequence of \"\n \"ids is already formatted with special tokens for the model.\"\n )\n return list(map(lambda x: 1 if x in [self.sep_token_id, self.cls_token_id] else 0, token_ids_0))\n\n if token_ids_1 is not None:\n return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]\n return [1] + ([0] * len(token_ids_0)) + [1]\n\n def create_token_type_ids_from_sequences(\n self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None\n ) -> List[int]:\n \"\"\"\n Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence\n pair mask has the following format:\n ::\n 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1\n | first sequence | second sequence |\n If :obj:`token_ids_1` is :obj:`None`, this method only returns the first portion of the mask (0s).\n Args:\n token_ids_0 (:obj:`List[int]`):\n List of IDs.\n token_ids_1 (:obj:`List[int]`, `optional`):\n Optional second list of IDs for sequence pairs.\n Returns:\n :obj:`List[int]`: List of `token type IDs <../glossary.html#token-type-ids>`_ according to the given\n sequence(s).\n \"\"\"\n sep = [self.sep_token_id]\n cls = [self.cls_token_id]\n if token_ids_1 is None:\n return len(cls + token_ids_0 + sep) * [0]\n return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]\n\n def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:\n index = 0\n if os.path.isdir(save_directory):\n vocab_file = os.path.join(\n save_directory, (filename_prefix + \"-\" if filename_prefix else \"\") + VOCAB_FILES_NAMES[\"vocab_file\"]\n )\n else:\n vocab_file = (filename_prefix + \"-\" if filename_prefix else \"\") + save_directory\n with open(vocab_file, \"w\", encoding=\"utf-8\") as writer:\n for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):\n if index != token_index:\n logger.warning(\n \"Saving vocabulary to {}: vocabulary indices are not consecutive.\"\n \" Please check that the vocabulary is not corrupted!\".format(vocab_file)\n )\n index = token_index\n writer.write(token + \"\\n\")\n index += 1\n return (vocab_file,)" }, { "identifier": "MIMIC_Dataset", "path": "dataset/dataset_entity.py", "snippet": "class MIMIC_Dataset(Dataset):\n def __init__(self, json_path, csv_path, sty_path,image_res,args):\n self.json_info = json.load(open(json_path,'r'))\n data_info = pd.read_csv(csv_path)\n self.img_path_list = np.asarray(data_info.iloc[:,0])\n self.class_list = np.asarray(data_info.iloc[:,1:])#40 class for fine-grained query list\n sty_info = pd.read_csv(sty_path)\n self.sty_dict_info = self.csv_to_dict(sty_info)\n\n normalize = transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))\n\n if args.colourjitter:\n self.transform = transforms.Compose([ \n transforms.RandomResizedCrop(image_res,scale=(0.2, 1.0), interpolation=transforms.InterpolationMode.BICUBIC),\n transforms.RandomHorizontalFlip(),\n\n transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4, hue=0.4),\n transforms.RandomGrayscale(),\n\n RandomAugment(2,7,isPIL=True,augs=['Identity','AutoContrast','Equalize','Brightness','Sharpness',\n 'ShearX', 'ShearY', 'TranslateX', 'TranslateY', 'Rotate']), \n transforms.ToTensor(),\n normalize,\n ])\n\n else:\n self.transform = transforms.Compose([ \n transforms.RandomResizedCrop(image_res,scale=(0.2, 1.0), interpolation=transforms.InterpolationMode.BICUBIC),\n transforms.RandomHorizontalFlip(),\n RandomAugment(2,7,isPIL=True,augs=['Identity','AutoContrast','Equalize','Brightness','Sharpness',\n 'ShearX', 'ShearY', 'TranslateX', 'TranslateY', 'Rotate']), \n transforms.ToTensor(),\n normalize,\n ]) \n\n \n def csv_to_dict(self,sty_info):\n tui_list = sty_info.iloc[:,0]\n sty_list = sty_info.iloc[:,1]\n sty_dict = defaultdict(list)\n for idx in tqdm(range(len(tui_list))):\n tui_idx = tui_list[idx]\n sty_idx = sty_list[idx]\n sty_dict[tui_idx] = sty_idx\n return sty_dict\n \n def __len__(self):\n return len(self.img_path_list)\n \n def __getitem__(self, index):\n img_path = self.img_path_list[index].replace(\"/nvme/zhangruipeng/zhangxiaoman/dataset/MIMIC-CXR-DCM/files\", '/remote-home/share/medical/public/MIMIC-CXR-JPG/MIMIC-CXR/small/files')\n class_label = self.class_list[index] \n\n # index_transit = np.load(\"/remote-home/tianjiedai/KAD/R1_CLIP_LR/A1_DATA/small/index0626.npy\")\n # new_index_json = index_transit[index]\n # entities = self.json_info[new_index_json]['entities']\n # captions = self.json_info[new_index_json]['caption']\n \n entities = self.json_info[index]['entities']\n captions = self.json_info[index]['caption']\n\n\n if len(entities) != 0:\n caption_list = ''\n entity_details = ''\n for entity in entities:\n sub_caption = entity['caption']\n sub_entities = entity['entity']#搞错了 还不是list\n sub_entity_details = ''\n for sub_entity in sub_entities:\n try:\n sub_entity_details += ' [ENT] ' + sub_entity['Entity'] \n except:\n sub_entity_details += ' [ENT] ' + sub_entity['Entity'] \n entity_details = entity_details + sub_entity_details + ' [SEP] '\n caption_list = caption_list + sub_caption + ' [SEP] '\n else:\n caption_list = ''\n entity_details = ''\n for sub_caption in captions:\n caption_list = caption_list + sub_caption + ' [SEP] '\n entity_details = caption_list\n \n # img = open_jpg(img_path).convert('RGB') \n img = Image.open(img_path).convert('RGB') \n image = self.transform(img)\n return {\n \"image\": image,\n \"label\": class_label,\n \"caption\": caption_list,\n \"entity\": entity_details\n }" }, { "identifier": "Mergetrain_Dataset", "path": "dataset/dataset_entity.py", "snippet": "class Mergetrain_Dataset(Dataset):\n def __init__(self, json_path, csv_path, sty_path,image_res,args):\n self.json_info = json.load(open(json_path,'r'))\n data_info = pd.read_csv(csv_path)\n self.img_path_list = np.asarray(data_info.iloc[:,0])\n self.class_list = np.asarray(data_info.iloc[:,2:])#60 class for fine-grained query list\n self.label_dataset_list = np.asarray(data_info.iloc[:,1])\n\n sty_info = pd.read_csv(sty_path)\n self.sty_dict_info = self.csv_to_dict(sty_info)\n\n normalize = transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))\n\n if args.colourjitter:\n self.transform = transforms.Compose([ \n transforms.RandomResizedCrop(image_res,scale=(0.2, 1.0), interpolation=transforms.InterpolationMode.BICUBIC),\n transforms.RandomHorizontalFlip(),\n\n transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4, hue=0.4),\n transforms.RandomGrayscale(),\n\n RandomAugment(2,7,isPIL=True,augs=['Identity','AutoContrast','Equalize','Brightness','Sharpness',\n 'ShearX', 'ShearY', 'TranslateX', 'TranslateY', 'Rotate']), \n transforms.ToTensor(),\n normalize,\n ])\n\n else:\n self.transform = transforms.Compose([ \n transforms.RandomResizedCrop(image_res,scale=(0.2, 1.0), interpolation=transforms.InterpolationMode.BICUBIC),\n transforms.RandomHorizontalFlip(),\n RandomAugment(2,7,isPIL=True,augs=['Identity','AutoContrast','Equalize','Brightness','Sharpness',\n 'ShearX', 'ShearY', 'TranslateX', 'TranslateY', 'Rotate']), \n transforms.ToTensor(),\n normalize,\n ]) \n\n \n def csv_to_dict(self,sty_info):\n tui_list = sty_info.iloc[:,0]\n sty_list = sty_info.iloc[:,1]\n sty_dict = defaultdict(list)\n for idx in tqdm(range(len(tui_list))):\n tui_idx = tui_list[idx]\n sty_idx = sty_list[idx]\n sty_dict[tui_idx] = sty_idx\n return sty_dict\n \n def __len__(self):\n return len(self.img_path_list)\n \n def __getitem__(self, index):\n\n if self.label_dataset_list[index] == 0:\n img_path = self.img_path_list[index].replace(\"/nvme/zhangruipeng/zhangxiaoman/dataset/MIMIC-CXR-DCM/files\", '/remote-home/share/medical/public/MIMIC-CXR-JPG/MIMIC-CXR/small/files')\n class_label = self.class_list[index] \n\n # index_transit = np.load(\"/remote-home/tianjiedai/KAD/R1_CLIP_LR/A1_DATA/small/index0626.npy\")\n # new_index_json = index_transit[index]\n # entities = self.json_info[new_index_json]['entities']\n # captions = self.json_info[new_index_json]['caption']\n \n entities = self.json_info[index]['entities']\n captions = self.json_info[index]['caption']\n\n\n if len(entities) != 0:\n caption_list = ''\n entity_details = ''\n for entity in entities:\n sub_caption = entity['caption']\n sub_entities = entity['entity']#搞错了 还不是list\n sub_entity_details = ''\n for sub_entity in sub_entities:\n try:\n sub_entity_details += ' [ENT] ' + sub_entity['Entity'] \n except:\n sub_entity_details += ' [ENT] ' + sub_entity['Entity'] \n entity_details = entity_details + sub_entity_details + ' [SEP] '\n caption_list = caption_list + sub_caption + ' [SEP] '\n else:\n caption_list = ''\n entity_details = ''\n for sub_caption in captions:\n caption_list = caption_list + sub_caption + ' [SEP] '\n entity_details = caption_list\n \n # img = open_jpg(img_path).convert('RGB') \n # img = Image.open(img_path).convert('RGB') \n # image = self.transform(img)\n # return {\n # \"image\": image,\n # \"label\": class_label,\n # \"caption\": caption_list,\n # \"entity\": entity_details\n # }\n \n else:\n img_path = self.img_path_list[index]\n class_label = self.class_list[index] \n caption_list = ''\n head = ['normal', 'pleural effusion', 'opacity', 'pneumothorax', 'edema', 'atelectasis', 'tube', 'consolidation','enlarged cardiomediastinum','tip', 'pneumonia','line','cardiomegaly', 'fracture','calcification',\n 'device','engorgement', 'nodule', 'wire', 'pacemaker', 'pleural thicken', 'marking', 'scar', 'hyperinflate', 'blunt', 'collapse', 'emphysema', 'aerate', 'mass','infiltration', 'obscure', 'deformity', 'hernia',\n 'drainage', 'distention', 'shift', 'stent', 'lesion', 'hardware', 'dilation', 'aspiration',\n 'fibrosis',\t'No Finding', 'Pleural Other', 'Support Devices', 'Aortic enlargement',\n 'Clavicle fracture', 'Enlarged PA', 'ILD', 'Lung cavity', 'Lung cyst', 'Mediastinal shift',\t\n 'Nodule/Mass', 'Pulmonary fibrosis', 'Rib fracture', 'Other lesion', 'COPD', 'Lung tumor', 'Tuberculosis',\n 'Other diseases']\n index_positive = np.where(class_label == 1)\n entity = np.array(head)[index_positive]\n entity_details = ''\n for sub_entity in entity:\n entity_details = entity_details + sub_entity + ' [SEP] '\n\n img = Image.open(img_path).convert('RGB') \n image = self.transform(img)\n label_dataset = self.label_dataset_list[index]\n\n return {\n \"image\": image,\n \"label\": class_label,\n \"label_dataset\": label_dataset,\n \"caption\": caption_list,\n \"entity\": entity_details\n }" }, { "identifier": "Chestxray14_Dataset", "path": "dataset/dataset_entity.py", "snippet": "class Chestxray14_Dataset(Dataset):\n def __init__(self, csv_path,image_res):\n data_info = pd.read_csv(csv_path)\n self.img_path_list = np.asarray(data_info.iloc[:,0])\n self.class_list = np.asarray(data_info.iloc[:,3:])\n\n normalize = transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))\n self.transform = transforms.Compose([ \n transforms.Resize(image_res, interpolation=transforms.InterpolationMode.BICUBIC),\n transforms.ToTensor(),\n normalize,\n ])\n \n def __getitem__(self, index):\n img_path = self.img_path_list[index].replace('/mnt/petrelfs/zhangxiaoman/DATA/Chestxray/ChestXray8/','/remote-home/share/medical/public/ChestXray8/')\n class_label = self.class_list[index] \n img = Image.open(img_path).convert('RGB') \n image = self.transform(img)\n return {\n \"image\": image,\n \"label\": class_label\n }\n \n def __len__(self):\n return len(self.img_path_list)" }, { "identifier": "CheXpert_Dataset", "path": "dataset/dataset_entity.py", "snippet": "class CheXpert_Dataset(Dataset):\n def __init__(self, csv_path,image_res):\n data_info = pd.read_csv(csv_path)\n self.img_path_list = np.asarray(data_info.iloc[:,0])\n self.class_list = np.asarray(data_info.iloc[:,[13,7,11,10,15]])\n\n normalize = transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))\n self.transform = transforms.Compose([ \n transforms.Resize([image_res,image_res], interpolation=transforms.InterpolationMode.BICUBIC),\n transforms.ToTensor(),\n normalize,\n ]) \n \n def __getitem__(self, index):\n img_path = os.path.join('/remote-home/share/tianjiedai/',self.img_path_list[index])\n class_label = self.class_list[index] \n img = Image.open(img_path).convert('RGB') \n image = self.transform(img)\n return {\n \"image\": image,\n \"label\": class_label\n }\n \n def __len__(self):\n return len(self.img_path_list)" } ]
import argparse import os import logging import yaml import numpy as np import random import time import datetime import json import math import torch import torch.nn as nn import torch.nn.functional as F import torch.backends.cudnn as cudnn import torch.distributed as dist import socket from pathlib import Path from functools import partial from sklearn.metrics import roc_auc_score from collections import OrderedDict from torch.utils.data import DataLoader from tensorboardX import SummaryWriter from transformers import AutoModel,BertConfig,AutoTokenizer from factory import utils from scheduler import create_scheduler from optim import create_optimizer from engine.train import train,valid_on_cheXpert,valid_on_chestxray14 from models.clip_tqn import CLP_clinical,ModelRes,TQN_Model,TQN_Model_Add,ModelDense,CLP_clinical2 from models.tokenization_bert import BertTokenizer from dataset.dataset_entity import MIMIC_Dataset,Mergetrain_Dataset, Chestxray14_Dataset,CheXpert_Dataset from io import BytesIO
16,967
# import ruamel.yaml as yaml def main(args, config): torch.cuda.current_device() torch.cuda._initialized = True print("Total CUDA devices: ", torch.cuda.device_count()) torch.set_default_tensor_type('torch.FloatTensor') utils.init_distributed_mode(args) device = torch.device(args.device) # fix the seed for reproducibility seed = args.seed + utils.get_rank() torch.manual_seed(seed) np.random.seed(seed) random.seed(seed) cudnn.benchmark = True start_epoch = 0 max_epoch = config['schedular']['epochs'] warmup_steps = config['schedular']['warmup_epochs'] num_tasks = utils.get_world_size() global_rank = utils.get_rank() sampler_rank = global_rank print('sampler_rank',sampler_rank,'num_tasks',num_tasks) #### Dataset #### print("Creating dataset") if args.add_dataset == True: train_dataset = Mergetrain_Dataset(config['train_entity_file'], config['train_fg_query_file_v1'], config['mrsty_file'],config['image_res'], args) else: train_dataset = MIMIC_Dataset(config['train_entity_file'], config['train_fg_query_file_v1'], config['mrsty_file'],config['image_res'], args) train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset,num_replicas=num_tasks, rank=sampler_rank, shuffle=True) train_dataloader = DataLoader( train_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=train_sampler, collate_fn=None, worker_init_fn=utils.seed_worker, drop_last=True, ) train_dataloader.num_samples = len(train_dataset) train_dataloader.num_batches = len(train_dataloader) val_dataset = Chestxray14_Dataset(config['chestxray_valid_file'],config['image_res']) val_sampler = torch.utils.data.distributed.DistributedSampler(val_dataset,num_replicas=num_tasks, rank=sampler_rank, shuffle=True) val_dataloader =DataLoader( val_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=val_sampler, collate_fn=None, worker_init_fn=utils.seed_worker, drop_last=True, ) val_dataloader.num_samples = len(val_dataset) val_dataloader.num_batches = len(val_dataloader) test_dataset = Chestxray14_Dataset(config['chestxray_test_file'],config['image_res']) test_sampler = torch.utils.data.distributed.DistributedSampler(test_dataset,num_replicas=num_tasks, rank=sampler_rank, shuffle=True) test_dataloader =DataLoader( test_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=test_sampler, collate_fn=None, worker_init_fn=utils.seed_worker, drop_last=True, ) test_dataloader.num_samples = len(test_dataset) test_dataloader.num_batches = len(test_dataloader) test_dataset_chexpert = CheXpert_Dataset(config['chexpert_valid_file'],config['image_res']) test_sampler_chexpert = torch.utils.data.distributed.DistributedSampler(test_dataset_chexpert,num_replicas=num_tasks, rank=sampler_rank, shuffle=True) test_dataloader_chexpert =DataLoader( test_dataset_chexpert, batch_size=config['batch_size'], num_workers=4, pin_memory=True, sampler=test_sampler_chexpert, collate_fn=None, worker_init_fn=utils.seed_worker, drop_last=True, ) test_dataloader_chexpert.num_samples = len(test_dataset_chexpert) test_dataloader_chexpert.num_batches = len(test_dataloader_chexpert) if args.image_encoder_name == 'resnet':
# import ruamel.yaml as yaml def main(args, config): torch.cuda.current_device() torch.cuda._initialized = True print("Total CUDA devices: ", torch.cuda.device_count()) torch.set_default_tensor_type('torch.FloatTensor') utils.init_distributed_mode(args) device = torch.device(args.device) # fix the seed for reproducibility seed = args.seed + utils.get_rank() torch.manual_seed(seed) np.random.seed(seed) random.seed(seed) cudnn.benchmark = True start_epoch = 0 max_epoch = config['schedular']['epochs'] warmup_steps = config['schedular']['warmup_epochs'] num_tasks = utils.get_world_size() global_rank = utils.get_rank() sampler_rank = global_rank print('sampler_rank',sampler_rank,'num_tasks',num_tasks) #### Dataset #### print("Creating dataset") if args.add_dataset == True: train_dataset = Mergetrain_Dataset(config['train_entity_file'], config['train_fg_query_file_v1'], config['mrsty_file'],config['image_res'], args) else: train_dataset = MIMIC_Dataset(config['train_entity_file'], config['train_fg_query_file_v1'], config['mrsty_file'],config['image_res'], args) train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset,num_replicas=num_tasks, rank=sampler_rank, shuffle=True) train_dataloader = DataLoader( train_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=train_sampler, collate_fn=None, worker_init_fn=utils.seed_worker, drop_last=True, ) train_dataloader.num_samples = len(train_dataset) train_dataloader.num_batches = len(train_dataloader) val_dataset = Chestxray14_Dataset(config['chestxray_valid_file'],config['image_res']) val_sampler = torch.utils.data.distributed.DistributedSampler(val_dataset,num_replicas=num_tasks, rank=sampler_rank, shuffle=True) val_dataloader =DataLoader( val_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=val_sampler, collate_fn=None, worker_init_fn=utils.seed_worker, drop_last=True, ) val_dataloader.num_samples = len(val_dataset) val_dataloader.num_batches = len(val_dataloader) test_dataset = Chestxray14_Dataset(config['chestxray_test_file'],config['image_res']) test_sampler = torch.utils.data.distributed.DistributedSampler(test_dataset,num_replicas=num_tasks, rank=sampler_rank, shuffle=True) test_dataloader =DataLoader( test_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=test_sampler, collate_fn=None, worker_init_fn=utils.seed_worker, drop_last=True, ) test_dataloader.num_samples = len(test_dataset) test_dataloader.num_batches = len(test_dataloader) test_dataset_chexpert = CheXpert_Dataset(config['chexpert_valid_file'],config['image_res']) test_sampler_chexpert = torch.utils.data.distributed.DistributedSampler(test_dataset_chexpert,num_replicas=num_tasks, rank=sampler_rank, shuffle=True) test_dataloader_chexpert =DataLoader( test_dataset_chexpert, batch_size=config['batch_size'], num_workers=4, pin_memory=True, sampler=test_sampler_chexpert, collate_fn=None, worker_init_fn=utils.seed_worker, drop_last=True, ) test_dataloader_chexpert.num_samples = len(test_dataset_chexpert) test_dataloader_chexpert.num_batches = len(test_dataloader_chexpert) if args.image_encoder_name == 'resnet':
image_encoder = ModelRes(res_base_model='resnet50').cuda()
7
2023-10-30 00:24:16+00:00
24k
ifrit98/storage-subnet
neurons/miner.py
[ { "identifier": "hash_data", "path": "storage/shared/ecc.py", "snippet": "def hash_data(data):\n \"\"\"\n Compute a SHA3-256 hash of the input data and return its integer representation.\n\n The function handles both byte-like and non-byte-like inputs by converting non-byte inputs to\n strings and then encoding to bytes before hashing.\n\n Parameters:\n - data (bytes | bytearray | object): Data to be hashed.\n\n Returns:\n - int: Integer representation of the SHA3-256 hash of the input data.\n\n Raises:\n - TypeError: If the hashing operation encounters an incompatible data type.\n \"\"\"\n if not isinstance(data, (bytes, bytearray)):\n data_str = str(data)\n data = data_str.encode()\n h = hashlib.sha3_256(data).hexdigest()\n return int(h, 16)" }, { "identifier": "setup_CRS", "path": "storage/shared/ecc.py", "snippet": "def setup_CRS(curve=\"P-256\"):\n \"\"\"\n Generate a pair of random points to serve as a Common Reference String (CRS) for elliptic curve operations.\n\n The CRS is essential for various cryptographic protocols that rely on a shared reference\n between parties, typically for the purpose of ensuring consistent cryptographic operations.\n\n Parameters:\n - curve (str, optional): Name of the elliptic curve to use; defaults to \"P-256\".\n\n Returns:\n - tuple(ECC.EccPoint, ECC.EccPoint): A 2-tuple of ECC.EccPoint instances representing the base points (g, h).\n\n Raises:\n - ValueError: If the specified elliptic curve name is not recognized.\n \"\"\"\n curve_obj = ECC.generate(curve=curve)\n g = curve_obj.pointQ # Base point\n h = ECC.generate(curve=curve).pointQ # Another random point\n return g, h" }, { "identifier": "ECCommitment", "path": "storage/shared/ecc.py", "snippet": "class ECCommitment:\n \"\"\"\n Elliptic Curve based commitment scheme allowing one to commit to a chosen value while keeping it hidden to others.\n\n Attributes:\n g (ECC.EccPoint): The base point of the elliptic curve used as part of the commitment.\n h (ECC.EccPoint): Another random point on the elliptic curve used as part of the commitment.\n\n Methods:\n commit(m): Accepts a message, hashes it, and produces a commitment to the hashed message.\n open(c, m_val, r): Accepts a commitment, a hashed message, and a random value to verify the commitment.\n\n The `commit` method will print the commitment process, and the `open` method will print the verification process.\n \"\"\"\n\n def __init__(self, g, h, verbose=False):\n self.g = g # Base point of the curve\n self.h = h # Another random point on the curve\n self.verbose = verbose\n\n def commit(self, m): # AKA Seal.\n \"\"\"\n Create a cryptographic commitment to a message.\n\n The message is hashed, and the hash is used along with a random number to form the commitment\n using the public parameters g and h. The commitment can be verified with the `open` method.\n\n Parameters:\n - m (bytes | bytearray | object): The message to commit to.\n\n Returns:\n - tuple: A 3-tuple (commitment, hashed message value, random number used in the commitment).\n\n Side Effects:\n - This method will print the commitment details to the console.\n\n Raises:\n - Exception: If the commitment calculation fails.\n \"\"\"\n m_val = hash_data(m) # Compute hash of the data\n r = random.randint(1, 2**256)\n c1 = self.g.__mul__(m_val)\n c2 = self.h.__mul__(r)\n c = c1.__add__(c2)\n if self.verbose:\n print(\n f\"Committing: Data = {m}\\nHashed Value = {m_val}\\nRandom Value = {r}\\nComputed Commitment = {c}\\n\"\n )\n return c, m_val, r\n\n def open(self, c, m_val, r):\n \"\"\"\n Verify a commitment using the original message hash and randomness.\n\n This method recomputes the commitment using the public parameters and compares it with\n the provided commitment to check its validity.\n\n Parameters:\n - c (ECC.EccPoint): The commitment point to verify.\n - m_val (int): The integer value of the hashed message used in the commitment.\n - r (int): The random number used in the commitment.\n\n Returns:\n - bool: True if the verification succeeds (commitment is valid), False otherwise.\n\n Side Effects:\n - This method will print the verification details to the console.\n\n Raises:\n - Exception: If the verification calculation fails.\n \"\"\"\n c1 = self.g.__mul__(m_val)\n c2 = self.h.__mul__(r)\n computed_c = c1.__add__(c2)\n if self.verbose:\n print(\n f\"\\nOpening: Hashed Value = {m_val}\\nRandom Value = {r}\\nRecomputed Commitment = {computed_c}\\nOriginal Commitment = {c}\"\n )\n return computed_c == c" }, { "identifier": "ecc_point_to_hex", "path": "storage/shared/ecc.py", "snippet": "def ecc_point_to_hex(point):\n \"\"\"\n Convert an elliptic curve point to a hexadecimal string.\n\n This encoding is typically used for compact representation or for preparing the data\n to be transmitted over protocols that may not support binary data.\n\n Parameters:\n - point (ECC.EccPoint): An ECC point to convert.\n\n Returns:\n - str: Hexadecimal string representing the elliptic curve point.\n\n Raises:\n - AttributeError: If the input is not a valid ECC point with accessible x and y coordinates.\n \"\"\"\n point_str = \"{},{}\".format(point.x, point.y)\n return binascii.hexlify(point_str.encode()).decode()" }, { "identifier": "hex_to_ecc_point", "path": "storage/shared/ecc.py", "snippet": "def hex_to_ecc_point(hex_str, curve):\n \"\"\"\n Convert a hexadecimal string back into an elliptic curve point.\n\n This function is typically used to deserialize an ECC point that has been transmitted or stored as a hex string.\n\n Parameters:\n - hex_str (str): The hex string representing an elliptic curve point.\n - curve (str): The name of the elliptic curve the point belongs to.\n\n Returns:\n - ECC.EccPoint: The elliptic curve point represented by the hex string.\n\n Raises:\n - ValueError: If the hex string is not properly formatted or does not represent a valid point on the specified curve.\n \"\"\"\n point_str = binascii.unhexlify(hex_str).decode()\n x, y = map(int, point_str.split(\",\"))\n return ECC.EccPoint(x, y, curve=curve)" }, { "identifier": "MerkleTree", "path": "storage/shared/merkle.py", "snippet": "class MerkleTree(object):\n \"\"\"\n Represents a Merkle Tree, a data structure used for efficiently summarizing and verifying the\n integrity of large sets of data. The Merkle Tree is a binary tree where each leaf node is the hash\n of a data block and every non-leaf node is the hash of its children nodes.\n\n Attributes:\n hash_function (callable): The hash function used for generating hashes of the blocks\n and non-leaf nodes in the Merkle Tree.\n leaves (list): A list where each element is a bytearray representing the hashed value of a leaf.\n levels (list of lists): A list of lists where each sublist represents a level of the tree, starting\n from the leaves up to the root.\n is_ready (bool): Indicates whether the tree has been fully constructed and is ready to provide\n the Merkle root and proofs.\n\n Methods:\n add_leaf(values, do_hash=False): Adds one or multiple leaves to the tree. If `do_hash` is True,\n it will hash the values before adding them as leaves.\n get_leaf(index): Retrieves the hexadecimal string representation of a leaf at the given index.\n get_leaf_count(): Returns the total number of leaves in the tree.\n get_tree_ready_state(): Checks if the tree has been fully constructed.\n make_tree(): Constructs the Merkle Tree from the current leaves. This method must be called\n after all leaves are added and before retrieving the Merkle root or proofs.\n get_merkle_root(): Retrieves the Merkle root as a hexadecimal string if the tree is ready.\n get_proof(index): Generates a proof of inclusion for the leaf at the given index. This proof\n consists of a list of sibling hashes that, when combined with the target leaf,\n can reproduce the Merkle root.\n update_leaf(index, new_value): Updates the value of the leaf at the given index with `new_value`\n and recalculates the hashes up the tree to reflect this change.\n serialize(): Converts the Merkle Tree into a JSON-formatted string for storage or transmission.\n deserialize(json_data, hash_type=\"sha3_256\"): Reconstructs the Merkle Tree from a JSON string,\n using the specified hash function.\n\n Raises:\n Exception: If the `hash_type` provided during initialization is not supported or recognized.\n\n Example:\n # Create a Merkle tree using the SHA3-256 hash function\n merkle_tree = MerkleTree(hash_type='sha3_256')\n\n # Add data blocks (as leaves) to the tree\n merkle_tree.add_leaf(['block1', 'block2', 'block3'], do_hash=True)\n\n # Construct the tree\n merkle_tree.make_tree()\n\n # Retrieve the Merkle root\n root = merkle_tree.get_merkle_root()\n\n # Get proof of inclusion for the first data block\n proof = merkle_tree.get_proof(0)\n\n # Update the value of the first leaf and reconstruct the tree\n merkle_tree.update_leaf(0, 'new_block1_hashed_value')\n merkle_tree.make_tree()\n\n # Serialize the tree for storage\n serialized_tree = merkle_tree.serialize()\n\n # Deserialize the tree for later use\n deserialized_tree = MerkleTree.deserialize(serialized_tree, hash_type='sha3_256')\n\n Note:\n The hash_function attribute is determined by the hash_type parameter provided at initialization.\n Only hash types supported by the `hashlib` library can be used. Attempting to use an unsupported\n hash type will result in an exception.\n \"\"\"\n\n def __init__(self, hash_type=\"sha3_256\"):\n hash_type = hash_type.lower()\n if hash_type in [\"sha3_256\"]:\n self.hash_function = getattr(hashlib, hash_type)\n else:\n raise Exception(\"`hash_type` {} nor supported\".format(hash_type))\n\n self.reset_tree()\n\n def __eq__(self, other):\n if not isinstance(other, MerkleTree):\n return False\n return self.serialize() == other.serialize()\n\n def _to_hex(self, x):\n try: # python3\n return x.hex()\n except: # python2\n return binascii.hexlify(x)\n\n def reset_tree(self):\n self.leaves = list()\n self.levels = None\n self.is_ready = False\n\n def add_leaf(self, values, do_hash=False):\n self.is_ready = False\n # check if single leaf\n if not isinstance(values, tuple) and not isinstance(values, list):\n values = [values]\n for v in values:\n if do_hash:\n v = v.encode(\"utf-8\")\n v = self.hash_function(v).hexdigest()\n v = bytearray.fromhex(v)\n self.leaves.append(v)\n\n def get_leaf(self, index):\n return self._to_hex(self.leaves[index])\n\n def get_leaf_count(self):\n return len(self.leaves)\n\n def get_tree_ready_state(self):\n return self.is_ready\n\n def _calculate_next_level(self):\n solo_leave = None\n N = len(self.levels[0]) # number of leaves on the level\n if N % 2 == 1: # if odd number of leaves on the level\n solo_leave = self.levels[0][-1]\n N -= 1\n\n new_level = []\n for l, r in zip(self.levels[0][0:N:2], self.levels[0][1:N:2]):\n new_level.append(self.hash_function(l + r).digest())\n if solo_leave is not None:\n new_level.append(solo_leave)\n self.levels = [\n new_level,\n ] + self.levels # prepend new level\n\n def make_tree(self):\n \"\"\"\n Constructs the Merkle Tree from the leaves that have been added.\n\n This must be called after adding all the leaves and before calling\n get_merkle_root or get_proof to ensure the tree is constructed.\n \"\"\"\n self.is_ready = False\n if self.get_leaf_count() > 0:\n self.levels = [\n self.leaves,\n ]\n while len(self.levels[0]) > 1:\n self._calculate_next_level()\n self.is_ready = True\n\n def get_merkle_root(self):\n if self.is_ready:\n if self.levels is not None:\n return self._to_hex(self.levels[0][0])\n else:\n return None\n else:\n return None\n\n def get_proof(self, index):\n \"\"\"\n Generates the proof for the existence of a leaf at the specified index within the Merkle Tree.\n\n A Merkle proof is a collection of sibling hashes on the path from a leaf to the root of the tree.\n This proof can be used to independently verify that a leaf is indeed part of the Merkle tree without\n needing the entire tree. Each element of the proof shows the direction ('left' or 'right') and the\n corresponding hash that pairs with the path to the root.\n\n Parameters:\n index (int): The index of the target leaf for which to generate the Merkle proof. The index must\n correspond to the position of the leaf in the original list of leaves when the tree\n was constructed.\n\n Returns:\n list of dicts: A list where each dictionary contains a single key-value pair. The key is either\n 'left' or 'right', indicating the side of the sibling hash, and the value is a\n string representing the hexadecimal hash value of the sibling. If the tree is not\n ready or the index is out of bounds, None is returned.\n\n Raises:\n IndexError: If the index provided is not within the range of the leaves in the tree.\n ValueError: If the tree has not been constructed by calling `make_tree` method, or the index\n is not an integer.\n\n Example:\n # Assuming `merkle_tree` is an instance of `MerkleTree` and has been populated with leaves and made ready\n proof = merkle_tree.get_proof(2)\n print(proof) # Outputs something like [{'left': 'abcd...'}, {'right': 'ef01...'}]\n\n Note:\n The Merkle proof is only valid if the tree is in the ready state (`is_ready` attribute is True),\n which occurs after the `make_tree` method has been called. If the tree is not ready or the index\n is not valid, the method will return None.\n \"\"\"\n if self.levels is None:\n return None\n elif not self.is_ready or index > len(self.leaves) - 1 or index < 0:\n return None\n else:\n proof = []\n for x in range(len(self.levels) - 1, 0, -1):\n level_len = len(self.levels[x])\n if (index == level_len - 1) and (\n level_len % 2 == 1\n ): # skip if this is an odd end node\n index = int(index / 2.0)\n continue\n is_right_node = index % 2\n sibling_index = index - 1 if is_right_node else index + 1\n sibling_pos = \"left\" if is_right_node else \"right\"\n sibling_value = self._to_hex(self.levels[x][sibling_index])\n proof.append({sibling_pos: sibling_value})\n index = int(index / 2.0)\n return proof\n\n def update_leaf(self, index, new_value):\n \"\"\"\n Updates the value of a leaf at a given index in the Merkle Tree and recalculates the hashes along\n the path from the updated leaf to the root of the tree to reflect the change.\n\n This method allows the Merkle Tree to maintain integrity by ensuring that any updates to the leaf\n nodes are propagated upwards, resulting in a new Merkle root that represents the current state of\n the leaves.\n\n Parameters:\n index (int): The index of the leaf to update. The index is zero-based and must be less than\n the number of leaves in the tree.\n new_value (str): The new value in hexadecimal format to which the leaf should be updated. This\n value should be a valid hexadecimal string that represents the hashed data\n if hashing was applied to the leaves upon tree construction.\n\n Returns:\n None\n\n Raises:\n ValueError: If the tree is not ready for updates (i.e., `is_ready` is False), if the index is\n not an integer, if the new_value is not a hexadecimal string, or if the index is\n out of bounds (less than 0 or greater than or equal to the number of leaves).\n IndexError: If the index is out of the range of current leaves.\n\n Example:\n # Assuming `merkle_tree` is an instance of `MerkleTree`, populated with leaves and made ready.\n merkle_tree.update_leaf(0, 'a1b2c3d4e5f67890')\n # The leaf at index 0 is updated, and changes are propagated to the root.\n\n Note:\n The tree must have been constructed and be in a ready state before calling this method. If the\n tree has not been made by calling the `make_tree` method, or the index is invalid, this method\n will not perform an update and will return None.\n \"\"\"\n if not self.is_ready:\n return None\n new_value = bytearray.fromhex(new_value)\n self.levels[-1][index] = new_value\n for x in range(len(self.levels) - 1, 0, -1):\n parent_index = index // 2\n left_child = self.levels[x][parent_index * 2]\n try:\n right_child = self.levels[x][parent_index * 2 + 1]\n except IndexError:\n right_child = bytearray()\n self.levels[x - 1][parent_index] = self.hash_function(\n left_child + right_child\n ).digest()\n index = parent_index\n\n def serialize(self):\n \"\"\"\n Serializes the MerkleTree object into a JSON string.\n \"\"\"\n # Convert the bytearray leaves and levels to hex strings for serialization\n leaves = [self._to_hex(leaf) for leaf in self.leaves]\n levels = None\n if self.levels is not None:\n levels = []\n for level in self.levels:\n levels.append([self._to_hex(item) for item in level])\n\n # Construct a dictionary with the MerkleTree properties\n merkle_tree_data = {\n \"leaves\": leaves,\n \"levels\": levels,\n \"is_ready\": self.is_ready,\n }\n\n # Convert the dictionary to a JSON string\n return json.dumps(merkle_tree_data)\n\n @classmethod\n def deserialize(cls, json_data, hash_type=\"sha3_256\"):\n \"\"\"\n Deserializes the JSON string into a MerkleTree object.\n \"\"\"\n # Convert the JSON string back to a dictionary\n merkle_tree_data = json.loads(json_data)\n\n # Create a new MerkleTree object\n m_tree = cls(hash_type)\n\n # Convert the hex strings back to bytearrays and set the leaves and levels\n m_tree.leaves = [bytearray.fromhex(leaf) for leaf in merkle_tree_data[\"leaves\"]]\n if merkle_tree_data[\"levels\"] is not None:\n m_tree.levels = []\n for level in merkle_tree_data[\"levels\"]:\n m_tree.levels.append([bytearray.fromhex(item) for item in level])\n m_tree.is_ready = merkle_tree_data[\"is_ready\"]\n\n return m_tree" }, { "identifier": "b64_encode", "path": "storage/shared/utils.py", "snippet": "def b64_encode(data: Union[bytes, str, List[str], List[bytes], dict]) -> str:\n \"\"\"\n Encodes the given data into a base64 string. If the data is a list or dictionary of bytes, it converts\n the bytes into hexadecimal strings before encoding.\n\n Args:\n data (list or dict): The data to be base64 encoded. Can be a list of bytes or a dictionary with bytes values.\n\n Returns:\n str: The base64 encoded string of the input data.\n\n Raises:\n TypeError: If the input is not a list, dict, or bytes.\n \"\"\"\n if isinstance(data, bytes):\n data = data.hex()\n if isinstance(data, list) and len(data) and isinstance(data[0], bytes):\n data = [d.hex() for d in data]\n if isinstance(data, dict) and isinstance(data[list(data.keys())[0]], bytes):\n data = {k: v.hex() for k, v in data.items()}\n return base64.b64encode(json.dumps(data).encode()).decode(\"utf-8\")" }, { "identifier": "b64_decode", "path": "storage/shared/utils.py", "snippet": "def b64_decode(data: bytes, decode_hex: bool = False, encrypted: bool = False):\n \"\"\"\n Decodes a base64 string into a list or dictionary. If decode_hex is True, it converts any hexadecimal strings\n within the data back into bytes.\n\n Args:\n data (bytes or str): The base64 encoded data to be decoded.\n decode_hex (bool): A flag to indicate whether to decode hex strings into bytes. Defaults to False.\n\n Returns:\n list or dict: The decoded data. Returns a list if the original encoded data was a list, and a dict if it was a dict.\n\n Raises:\n ValueError: If the input is not properly base64 encoded or if hex decoding fails.\n \"\"\"\n data = data.decode(\"utf-8\") if isinstance(data, bytes) else data\n decoded_data = json.loads(\n base64.b64decode(data) if encrypted else base64.b64decode(data).decode(\"utf-8\")\n )\n if decode_hex:\n try:\n decoded_data = (\n [bytes.fromhex(d) for d in decoded_data]\n if isinstance(decoded_data, list)\n else {k: bytes.fromhex(v) for k, v in decoded_data.items()}\n )\n except:\n pass\n return decoded_data" }, { "identifier": "chunk_data", "path": "storage/shared/utils.py", "snippet": "def chunk_data(data: bytes, chunksize: int) -> List[bytes]:\n \"\"\"\n Generator function that chunks the given data into pieces of a specified size.\n\n Args:\n data (bytes): The binary data to be chunked.\n chunksize (int): The size of each chunk in bytes.\n\n Yields:\n bytes: A chunk of the data with the size equal to 'chunksize' or the remaining size of data.\n\n Raises:\n ValueError: If 'chunksize' is less than or equal to 0.\n \"\"\"\n for i in range(0, len(data), chunksize):\n yield data[i : i + chunksize]" }, { "identifier": "safe_key_search", "path": "storage/shared/utils.py", "snippet": "async def safe_key_search(database: aioredis.Redis, pattern: str) -> List[str]:\n \"\"\"\n Safely search for keys in the database that doesn't block.\n `scan_iter` uses cursor under the hood.\n \"\"\"\n return [key for key in await database.scan_iter(pattern)]" }, { "identifier": "run", "path": "storage/miner/run.py", "snippet": "def run(self):\n \"\"\"\n Initiates and manages the main loop for the miner on the Bittensor network.\n\n This function performs the following primary tasks:\n 1. Check for registration on the Bittensor network.\n 2. Attaches the miner's forward, blacklist, and priority functions to its axon.\n 3. Starts the miner's axon, making it active on the network.\n 4. Regularly updates the metagraph with the latest network state.\n 5. Optionally sets weights on the network, defining how much trust to assign to other nodes.\n 6. Handles graceful shutdown on keyboard interrupts and logs unforeseen errors.\n\n The miner continues its operations until `should_exit` is set to True or an external interruption occurs.\n During each epoch of its operation, the miner waits for new blocks on the Bittensor network, updates its\n knowledge of the network (metagraph), and sets its weights. This process ensures the miner remains active\n and up-to-date with the network's latest state.\n\n Note:\n - The function leverages the global configurations set during the initialization of the miner.\n - The miner's axon serves as its interface to the Bittensor network, handling incoming and outgoing requests.\n\n Raises:\n KeyboardInterrupt: If the miner is stopped by a manual interruption.\n Exception: For unforeseen errors during the miner's operation, which are logged for diagnosis.\n \"\"\"\n block_handler_substrate = SubstrateInterface(\n ss58_format=bt.__ss58_format__,\n use_remote_preset=True,\n url=self.subtensor.chain_endpoint,\n type_registry=bt.__type_registry__,\n )\n\n netuid = self.config.netuid\n\n # --- Check for registration.\n if not self.subtensor.is_hotkey_registered(\n netuid=netuid,\n hotkey_ss58=self.wallet.hotkey.ss58_address,\n ):\n bt.logging.error(\n f\"Wallet: {self.wallet} is not registered on netuid {netuid}\"\n f\"Please register the hotkey using `btcli subnets register` before trying again\"\n )\n exit()\n\n tempo = block_handler_substrate.query(\n module=\"SubtensorModule\", storage_function=\"Tempo\", params=[netuid]\n ).value\n\n last_extrinsic_hash = None\n checked_extrinsics_count = 0\n should_retry = False\n\n def handler(obj, update_nr, subscription_id):\n current_block = obj[\"header\"][\"number\"]\n block_hash = block_handler_substrate.get_block_hash(current_block)\n bt.logging.debug(f\"New block #{current_block}\")\n\n bt.logging.debug(\n f\"Blocks since epoch: {(current_block + netuid + 1) % (tempo + 1)}\"\n )\n\n nonlocal last_extrinsic_hash\n nonlocal checked_extrinsics_count\n nonlocal should_retry\n\n if last_extrinsic_hash != None:\n try:\n receipt = block_handler_substrate.retrieve_extrinsic_by_hash(\n block_hash, last_extrinsic_hash\n )\n bt.logging.debug(\n f\"Last set-weights call: {'Success' if receipt.is_success else format('Failure, reason: %s', receipt.error_message['name'] if receipt.error_message != None else 'nil')}\"\n )\n\n should_retry = False\n last_extrinsic_hash = None\n checked_extrinsics_count = 0\n except Exception as e:\n checked_extrinsics_count += 1\n bt.logging.debug(f\"An error occurred, extrinsic not found in block.\")\n finally:\n if checked_extrinsics_count >= 20:\n should_retry = True\n last_extrinsic_hash = None\n checked_extrinsics_count = 0\n\n if ((current_block + netuid + 1) % (tempo + 1) == 0) or should_retry:\n bt.logging.info(\n f\"New epoch started, setting weights at block {current_block}\"\n )\n with self.subtensor.substrate as substrate:\n call = substrate.compose_call(\n call_module=\"SubtensorModule\",\n call_function=\"set_weights\",\n call_params={\n \"dests\": [self.my_subnet_uid],\n \"weights\": [65535],\n \"netuid\": netuid,\n \"version_key\": 1,\n },\n )\n\n # Period dictates how long the extrinsic will stay as part of waiting pool\n extrinsic = substrate.create_signed_extrinsic(\n call=call, keypair=self.wallet.hotkey, era={\"period\": 1000}\n )\n\n dry_run = runtime_call(\n substrate=substrate,\n api=\"TaggedTransactionQueue\",\n method=\"validate_transaction\",\n params=[\"InBlock\", extrinsic, block_hash],\n block_hash=block_hash,\n )\n bt.logging.debug(dry_run)\n\n response = substrate.submit_extrinsic(\n extrinsic,\n wait_for_inclusion=False,\n wait_for_finalization=False,\n )\n\n result_data = substrate.rpc_request(\"author_pendingExtrinsics\", [])\n for extrinsic_data in result_data[\"result\"]:\n extrinsic = substrate.runtime_config.create_scale_object(\n \"Extrinsic\", metadata=substrate.metadata\n )\n extrinsic.decode(\n ScaleBytes(extrinsic_data),\n check_remaining=substrate.config.get(\"strict_scale_decode\"),\n )\n\n if extrinsic.value[\"extrinsic_hash\"] == response.extrinsic_hash:\n bt.logging.debug(\n \"Weights transaction is in the pending transaction pool\"\n )\n\n last_extrinsic_hash = response.extrinsic_hash\n should_retry = False\n\n # --- Update the miner storage information periodically.\n if not should_retry:\n update_storage_stats(self)\n bt.logging.debug(\"Storage statistics updated...\")\n\n if self.should_exit:\n return True\n\n block_handler_substrate.subscribe_block_headers(handler)" }, { "identifier": "set_weights", "path": "storage/miner/set_weights.py", "snippet": "def set_weights_for_miner(\n subtensor: \"bt.subtensor\",\n netuid: int,\n uid: int,\n wallet: \"bt.wallet\",\n metagraph: \"bt.metagraph\",\n wandb_on: bool = False,\n tempo: int = 360,\n wait_for_inclusion: bool = False,\n wait_for_finalization: bool = False,\n) -> bool:" }, { "identifier": "compute_subsequent_commitment", "path": "storage/miner/utils.py", "snippet": "def compute_subsequent_commitment(data, previous_seed, new_seed, verbose=False):\n \"\"\"\n Computes a new commitment based on provided data and a change from an old seed to a new seed.\n This function is typically used in cryptographic operations to update commitments without\n altering the underlying data.\n\n Parameters:\n - data: The original data for which the commitment is being updated.\n - previous_seed: The seed used in the previous commitment.\n - new_seed: The seed to be used for the new commitment.\n - verbose (bool): If True, additional debug information will be printed. Defaults to False.\n\n Returns:\n - A tuple containing the new commitment and the proof of the old commitment.\n\n If verbose is set to True, debug information about the types and contents of the parameters\n will be printed to aid in debugging.\n \"\"\"\n if verbose:\n bt.logging.debug(\"IN COMPUTE SUBESEQUENT COMMITMENT\")\n bt.logging.debug(\"type of data :\", type(data))\n bt.logging.debug(\"type of prev_seed:\", type(previous_seed))\n bt.logging.debug(\"type of new_seed :\", type(new_seed))\n proof = hash_data(data + previous_seed)\n return hash_data(str(proof).encode(\"utf-8\") + new_seed), proof" }, { "identifier": "save_data_to_filesystem", "path": "storage/miner/utils.py", "snippet": "def save_data_to_filesystem(data, directory, filename):\n \"\"\"\n Saves data to the filesystem at the specified directory and filename. If the directory does\n not exist, it is created.\n\n Parameters:\n - data: The data to be saved.\n - directory (str): The directory path where the data should be saved.\n - filename (str): The name of the file to save the data in.\n\n Returns:\n - file_path (str): The full path to the saved file.\n\n This function is useful for persisting data to the disk.\n \"\"\"\n # Ensure the directory exists\n directory = os.path.expanduser(directory)\n os.makedirs(directory, exist_ok=True)\n file_path = os.path.join(directory, filename)\n with open(file_path, \"wb\") as file:\n file.write(data)\n return file_path" }, { "identifier": "load_from_filesystem", "path": "storage/miner/utils.py", "snippet": "def load_from_filesystem(filepath):\n \"\"\"\n Loads data from a file in the filesystem.\n\n Parameters:\n - filepath (str): The path to the file from which data is to be loaded.\n\n Returns:\n - data: The data read from the file.\n\n This function is a straightforward utility for reading binary data from a file.\n \"\"\"\n with open(os.path.expanduser(filepath), \"rb\") as file:\n data = file.read()\n return data" }, { "identifier": "commit_data_with_seed", "path": "storage/miner/utils.py", "snippet": "def commit_data_with_seed(committer, data_chunks, n_chunks, seed):\n \"\"\"\n Commits chunks of data with a seed using a Merkle tree structure to create a proof of\n integrity for each chunk. This function is used in environments where the integrity\n and order of data need to be verifiable.\n\n Parameters:\n - committer: The committing object, which should have a commit method.\n - data_chunks (list): A list of data chunks to be committed.\n - n_chunks (int): The number of chunks expected to be committed.\n - seed: A seed value that is combined with data chunks before commitment.\n\n Returns:\n - randomness (list): A list of randomness values associated with each data chunk's commitment.\n - chunks (list): The list of original data chunks that were committed.\n - points (list): A list of commitment points in hex format.\n - merkle_tree (MerkleTree): A Merkle tree constructed from the commitment points.\n\n This function handles the conversion of commitment points to hex format and adds them to the\n Merkle tree. The completed tree represents the combined commitments.\n \"\"\"\n merkle_tree = MerkleTree()\n\n # Commit each chunk of data\n randomness, chunks, points = [None] * n_chunks, [None] * n_chunks, [None] * n_chunks\n for index, chunk in enumerate(data_chunks):\n c, m_val, r = committer.commit(chunk + str(seed).encode())\n c_hex = ecc_point_to_hex(c)\n randomness[index] = r\n chunks[index] = chunk\n points[index] = c_hex\n merkle_tree.add_leaf(c_hex)\n\n # Create the tree from the leaves\n merkle_tree.make_tree()\n return randomness, chunks, points, merkle_tree" }, { "identifier": "init_wandb", "path": "storage/miner/utils.py", "snippet": "def init_wandb(self, reinit=False):\n \"\"\"Starts a new wandb run.\"\"\"\n tags = [\n self.wallet.hotkey.ss58_address,\n storage.__version__,\n str(storage.__spec_version__),\n f\"netuid_{self.metagraph.netuid}\",\n ]\n\n if self.config.mock:\n tags.append(\"mock\")\n\n wandb_config = {\n key: copy.deepcopy(self.config.get(key, None))\n for key in (\"neuron\", \"reward\", \"netuid\", \"wandb\")\n }\n\n if wandb_config[\"neuron\"] is not None:\n wandb_config[\"neuron\"].pop(\"full_path\", None)\n\n self.wandb = wandb.init(\n anonymous=\"allow\",\n reinit=reinit,\n project=self.config.wandb.project_name,\n entity=self.config.wandb.entity,\n config=wandb_config,\n mode=\"offline\" if self.config.wandb.offline else \"online\",\n dir=self.config.neuron.full_path\n if self.config.neuron is not None\n else \"wandb_logs\",\n tags=tags,\n notes=self.config.wandb.notes,\n )\n bt.logging.success(\n prefix=\"Started a new wandb run\",\n sufix=f\"<blue> {self.wandb.name} </blue>\",\n )" }, { "identifier": "get_directory_size", "path": "storage/miner/utils.py", "snippet": "def get_directory_size(path):\n \"\"\"\n Calculates the total size of files in a specified directory.\n\n This function traverses the directory at the given path, including all subdirectories, and sums up the size\n of each file to calculate the total directory size.\n\n Args:\n path (str): The file path of the directory whose size is to be calculated.\n\n Returns:\n int: The total size of the directory in bytes (B).\n\n Usage:\n directory_size_gb = get_directory_size('/path/to/directory')\n \"\"\"\n total_size = 0\n path = os.path.expanduser(path)\n for dirpath, dirnames, filenames in os.walk(path):\n for f in filenames:\n fp = os.path.join(dirpath, f)\n if not os.path.islink(fp):\n total_size += os.path.getsize(fp)\n return total_size" }, { "identifier": "get_free_disk_space", "path": "storage/miner/utils.py", "snippet": "def get_free_disk_space(path=\".\"):\n \"\"\"\n Retrieves the free disk space for the drive containing the specified path.\n\n This function provides the free disk space of the drive on which the specified path resides.\n It's useful for understanding the storage capacity and usage of the system where the miner is running.\n\n Args:\n path (str): A file path on the drive whose free disk space is to be fetched. Typically, you can\n provide the root path ('/') to get the stats for the primary drive.\n\n Returns:\n int: The free space on the disk in bytes (B).\n\n Usage:\n free_disk_space_gb = get_free_disk_space('/')\n \"\"\"\n stats = get_disk_space_stats(path)\n free = stats.get(\"free_bytes\", 0)\n return free" }, { "identifier": "update_storage_stats", "path": "storage/miner/utils.py", "snippet": "def update_storage_stats(self):\n \"\"\"\n Updates the miner's storage statistics.\n\n This function updates the miner's storage statistics, including the free disk space, current storage usage,\n and percent disk usage. It's useful for understanding the storage capacity and usage of the system where\n the miner is running.\n \"\"\"\n\n self.free_memory = get_free_disk_space()\n bt.logging.info(f\"Free memory: {self.free_memory} bytes\")\n self.current_storage_usage = get_directory_size(self.config.database.directory)\n bt.logging.info(f\"Miner storage usage: {self.current_storage_usage} bytes\")\n self.percent_disk_usage = self.current_storage_usage / self.free_memory\n bt.logging.info(f\"Miner % disk usage : {100 * self.percent_disk_usage:.3f}%\")" }, { "identifier": "config", "path": "storage/miner/config.py", "snippet": "def config(cls):\n parser = argparse.ArgumentParser()\n bt.subtensor.add_args(parser)\n bt.logging.add_args(parser)\n bt.wallet.add_args(parser)\n bt.axon.add_args(parser)\n cls.add_args(parser)\n return bt.config(parser)" }, { "identifier": "check_config", "path": "storage/miner/config.py", "snippet": "def check_config(cls, config: \"bt.Config\"):\n r\"\"\"Checks/validates the config namespace object.\"\"\"\n bt.logging.check_config(config)\n\n if config.mock:\n config.wallet._mock = True\n\n timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n full_path = os.path.expanduser(\n \"{}/{}/{}/netuid{}/{}\".format(\n config.logging.logging_dir,\n config.wallet.name,\n config.wallet.hotkey,\n config.netuid,\n config.miner.name,\n )\n )\n log_path = os.path.join(full_path, \"logs\", timestamp)\n\n config.miner.log_path = os.path.expanduser(log_path)\n config.miner.full_path = os.path.expanduser(full_path)\n\n if not os.path.exists(config.miner.full_path):\n os.makedirs(config.miner.full_path, exist_ok=True)\n if not os.path.exists(config.miner.log_path):\n os.makedirs(config.miner.log_path, exist_ok=True)\n\n if not config.miner.dont_save_events:\n # Add custom event logger for the events.\n logger.level(\"EVENTS\", no=38, icon=\"📝\")\n logger.add(\n config.miner.full_path + \"/\" + \"EVENTS.log\",\n rotation=config.miner.events_retention_size,\n serialize=True,\n enqueue=True,\n backtrace=False,\n diagnose=False,\n level=\"EVENTS\",\n format=\"{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}\",\n )\n\n logger.add(\n config.miner.full_path + \"/\" + \"INFO.log\",\n rotation=config.miner.events_retention_size,\n serialize=True,\n enqueue=True,\n backtrace=False,\n diagnose=False,\n level=\"INFO\",\n format=\"{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}\",\n )\n\n logger.add(\n config.miner.full_path + \"/\" + \"DEBUG.log\",\n rotation=config.miner.events_retention_size,\n serialize=True,\n enqueue=True,\n backtrace=False,\n diagnose=False,\n level=\"DEBUG\",\n format=\"{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}\",\n )\n\n logger.add(\n config.miner.full_path + \"/\" + \"TRACE.log\",\n rotation=config.miner.events_retention_size,\n serialize=True,\n enqueue=True,\n backtrace=False,\n diagnose=False,\n level=\"TRACE\",\n format=\"{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}\",\n )" }, { "identifier": "add_args", "path": "storage/miner/config.py", "snippet": "def add_args(cls, parser):\n parser.add_argument(\"--netuid\", type=int, default=21, help=\"The chain subnet uid.\")\n parser.add_argument(\"--test\", default=False, action=\"store_true\")\n parser.add_argument(\n \"--miner.name\",\n type=str,\n help=\"Trials for this miner go in miner.root / (wallet_cold - wallet_hot) / miner.name. \",\n default=\"core_storage_miner\",\n )\n parser.add_argument(\n \"--miner.device\",\n type=str,\n help=\"Device to run the validator on.\",\n default=\"cuda\" if torch.cuda.is_available() else \"cpu\",\n )\n parser.add_argument(\"--miner.verbose\", default=False, action=\"store_true\")\n\n parser.add_argument(\n \"--database.host\", default=\"localhost\", help=\"The host of the redis database.\"\n )\n parser.add_argument(\n \"--database.port\",\n type=int,\n default=6379,\n help=\"The port of the redis database.\",\n )\n parser.add_argument(\n \"--database.index\",\n type=int,\n default=0,\n help=\"The index of the redis database.\",\n )\n parser.add_argument(\n \"--database.directory\",\n default=\"~/.data\",\n help=\"The directory to store data in.\",\n )\n\n # Run config.\n parser.add_argument(\n \"--miner.set_weights_wait_for_inclusion\",\n action=\"store_true\",\n help=\"Wether to wait for the set_weights extrinsic to enter a block\",\n default=False,\n )\n parser.add_argument(\n \"--miner.set_weights_wait_for_finalization\",\n action=\"store_true\",\n help=\"Wether to wait for the set_weights extrinsic to be finalized on the chain\",\n default=False,\n )\n parser.add_argument(\n \"--miner.seconds_to_wait_to_log_presence_message\",\n type=int,\n help=\"How many seconds to wait before logging a presence message.\",\n default=4,\n )\n\n # Blacklist.\n parser.add_argument(\n \"--miner.blacklist.blacklist\",\n type=str,\n required=False,\n nargs=\"*\",\n help=\"Blacklist certain hotkeys\",\n default=[],\n )\n parser.add_argument(\n \"--miner.blacklist.whitelist\",\n type=str,\n required=False,\n nargs=\"*\",\n help=\"Whitelist certain hotkeys\",\n default=[],\n )\n parser.add_argument(\n \"--miner.blacklist.force_validator_permit\",\n action=\"store_true\",\n help=\"Only allow requests from validators\",\n default=False,\n )\n parser.add_argument(\n \"--miner.blacklist.allow_non_registered\",\n action=\"store_true\",\n help=\"If True, the miner will allow non-registered hotkeys to mine.\",\n default=False,\n )\n parser.add_argument(\n \"--miner.blacklist.minimum_stake_requirement\",\n type=float,\n help=\"Minimum stake requirement\",\n default=0.0,\n )\n parser.add_argument(\n \"--miner.blacklist.min_request_period\",\n type=int,\n help=\"Time period (in minute) to serve a maximum of 50 requests for each hotkey\",\n default=5,\n )\n\n # Priority.\n parser.add_argument(\n \"--miner.priority.default\",\n type=float,\n help=\"Default priority of non-registered requests\",\n default=0.0,\n )\n parser.add_argument(\n \"--miner.priority.time_stake_multiplicate\",\n type=int,\n help=\"Time (in minute) it takes to make the stake twice more important in the priority queue\",\n default=10,\n )\n parser.add_argument(\n \"--miner.priority.len_request_timestamps\",\n type=int,\n help=\"Number of historic request timestamps to record\",\n default=50,\n )\n # Switches.\n parser.add_argument(\n \"--miner.no_set_weights\",\n action=\"store_true\",\n help=\"If True, the miner does not set weights.\",\n default=False,\n )\n parser.add_argument(\n \"--miner.no_serve\",\n action=\"store_true\",\n help=\"If True, the miner doesnt serve the axon.\",\n default=False,\n )\n parser.add_argument(\n \"--miner.no_start_axon\",\n action=\"store_true\",\n help=\"If True, the miner doesnt start the axon.\",\n default=False,\n )\n\n # Mocks.\n parser.add_argument(\n \"--miner.mock_subtensor\",\n action=\"store_true\",\n help=\"If True, the miner will allow non-registered hotkeys to mine.\",\n default=False,\n )\n\n # Wandb args\n parser.add_argument(\n \"--wandb.off\", action=\"store_true\", help=\"Turn off wandb.\", default=False\n )\n parser.add_argument(\n \"--wandb.project_name\",\n type=str,\n help=\"The name of the project where you are sending the new run.\",\n default=\"philanthropic-thunder\",\n )\n parser.add_argument(\n \"--wandb.entity\",\n type=str,\n help=\"An entity is a username or team name where youre sending runs.\",\n default=\"philanthrope\",\n )\n parser.add_argument(\n \"--wandb.offline\",\n action=\"store_true\",\n help=\"Runs wandb in offline mode.\",\n default=False,\n )\n parser.add_argument(\n \"--wandb.weights_step_length\",\n type=int,\n help=\"How many steps before we log the weights.\",\n default=10,\n )\n parser.add_argument(\n \"--wandb.run_step_length\",\n type=int,\n help=\"How many steps before we rollover to a new run.\",\n default=1500,\n )\n parser.add_argument(\n \"--wandb.notes\",\n type=str,\n help=\"Notes to add to the wandb run.\",\n default=\"\",\n )" }, { "identifier": "store_chunk_metadata", "path": "storage/miner/database.py", "snippet": "async def store_chunk_metadata(r, chunk_hash, filepath, hotkey, size, seed):\n \"\"\"\n Stores the metadata of a chunk in a Redis database.\n\n Args:\n r (redis.Redis): The Redis connection instance.\n chunk_hash (str): The unique hash identifying the chunk.\n hotkey (str): Miner hotkey associated with the chunk.\n size (int): The size of the chunk.\n seed (str): The seed associated with the chunk.\n\n This function stores the filepath, size (as a string), and seed for the given chunk hash.\n \"\"\"\n # Ensure that all data are in the correct format\n metadata = {\n \"filepath\": filepath,\n \"hotkey\": hotkey,\n \"size\": str(size), # Convert size to string\n \"seed\": seed, # Store seed directly\n }\n\n # Use hmset (or hset which is its modern equivalent) to store the hash\n for key, value in metadata.items():\n await r.hset(chunk_hash, key, value)" }, { "identifier": "update_seed_info", "path": "storage/miner/database.py", "snippet": "async def update_seed_info(r, chunk_hash, hotkey, seed):\n \"\"\"\n Updates the seed information for a specific chunk in the Redis database.\n\n Args:\n r (redis.Redis): The Redis connection instance.\n chunk_hash (str): The unique hash identifying the chunk.\n hotkey (str): The caller hotkey value to be updated.\n seed (str): The new seed value to be updated.\n\n This function updates the seed information for the specified chunk hash.\n \"\"\"\n # Update the existing seed information\n await r.hset(chunk_hash, \"seed\", seed)\n await r.hset(chunk_hash, \"hotkey\", hotkey)" }, { "identifier": "get_chunk_metadata", "path": "storage/miner/database.py", "snippet": "async def get_chunk_metadata(r, chunk_hash):\n \"\"\"\n Retrieves the metadata for a specific chunk from the Redis database.\n\n Args:\n r (redis.Redis): The Redis connection instance.\n chunk_hash (str): The unique hash identifying the chunk.\n\n Returns:\n dict: A dictionary containing the chunk's metadata, including filepath, size, and seed.\n Size is converted to an integer, and seed is decoded from bytes to a string.\n \"\"\"\n metadata = await r.hgetall(chunk_hash)\n if metadata:\n metadata[b\"size\"] = int(metadata[b\"size\"])\n metadata[b\"seed\"] = metadata[b\"seed\"].decode(\"utf-8\")\n return metadata" } ]
import os import sys import copy import json import time import torch import typing import base64 import asyncio import aioredis import argparse import threading import traceback import bittensor as bt import storage from collections import defaultdict from Crypto.Random import get_random_bytes from typing import Dict from pprint import pprint, pformat from storage.shared.ecc import ( hash_data, setup_CRS, ECCommitment, ecc_point_to_hex, hex_to_ecc_point, ) from storage.shared.merkle import ( MerkleTree, ) from storage.shared.utils import b64_encode, b64_decode, chunk_data, safe_key_search from storage.miner import ( run, set_weights, ) from storage.miner.utils import ( compute_subsequent_commitment, save_data_to_filesystem, load_from_filesystem, commit_data_with_seed, init_wandb, get_directory_size, get_free_disk_space, update_storage_stats, ) from storage.miner.config import ( config, check_config, add_args, ) from storage.miner.database import ( store_chunk_metadata, update_seed_info, get_chunk_metadata, )
15,138
f"stored data hash {data_hash} with commitment: {synapse.commitment}" ) # Don't send data back, no need. synapse.encrypted_data = base64.b64encode(b"").decode() # Empty b64 response return synapse async def challenge( self, synapse: storage.protocol.Challenge ) -> storage.protocol.Challenge: """ Handles a data challenge by providing cryptographic proof of data possession. This method retrieves the specified data from storage, calculates its commitment using elliptic curve cryptography, and constructs a Merkle proof. The response includes the requested data chunk, Merkle proof, root, and the commitment, which collectively serve as verifiable evidence of data possession. Args: synapse (storage.protocol.Challenge): An object representing the challenge request, which includes parameters such as the hash of the data to retrieve, chunk size, challenge index, and elliptic curve parameters for commitment calculation. Returns: storage.protocol.Challenge: The synapse object is updated with the response to the challenge, including the encrypted data chunk, commitment point, Merkle proof, and root hash. The method performs the following steps: 1. Fetches the encrypted data from storage using the hash provided in the challenge. 2. Splits the data into chunks based on the specified chunk size. 3. Computes a new commitment hash to provide a time-bound proof of possession. 4. Generates a Merkle tree from the committed data chunks and extracts a proof for the requested chunk. 5. Encodes the requested chunk and Merkle proof in base64 for transmission. 6. Updates the challenge synapse with the commitment, data chunk, randomness, and Merkle proof. 7. Records the updated commitment hash in storage for future challenges. This method ensures data integrity and allows the verification of data possession without disclosing the entire data set. It is designed to fulfill data verification requests in a secure and verifiable manner. Example usage: Assuming an initialized 'synapse' object with the challenge parameters: >>> updated_synapse = self.challenge(synapse) """ # Retrieve the data itself from miner storage bt.logging.info(f"received challenge hash: {synapse.challenge_hash}") self.request_count += 1 bt.logging.trace(f"entering get_chunk_metadata()") data = await get_chunk_metadata(self.database, synapse.challenge_hash) if data is None: bt.logging.error(f"No data found for {synapse.challenge_hash}") return synapse bt.logging.trace(f"retrieved data: {pformat(data)}") # Chunk the data according to the specified (random) chunk size filepath = data.get(b"filepath", None) if filepath is None: bt.logging.warning( f"No file found for {synapse.challenge_hash} in index, trying path construction..." ) # fallback to load the data from the filesystem via database path construction filepath = os.path.expanduser( f"{self.config.database.directory}/{synapse.challenge_hash}" ) if not os.path.isfile(filepath): bt.logging.error( f"No file found for {synapse.challenge_hash} in {self.config.database.directory}." ) return synapse bt.logging.trace(f"entering load_from_filesystem()") try: encrypted_data_bytes = load_from_filesystem(filepath) except Exception as e: bt.logging.error(f"Error loading file {filepath}: {e}") synapse.axon.status_code = 404 synapse.axon.status_message = "File not found" return synapse # Construct the next commitment hash using previous commitment and hash # of the data to prove storage over time prev_seed = data.get(b"seed", "").encode() if prev_seed == None: bt.logging.error(f"No seed found for {synapse.challenge_hash}") return synapse bt.logging.trace(f"entering comput_subsequent_commitment()...") new_seed = synapse.seed.encode() next_commitment, proof = compute_subsequent_commitment( encrypted_data_bytes, prev_seed, new_seed, verbose=self.config.miner.verbose ) if self.config.miner.verbose: bt.logging.debug(f"prev seed : {prev_seed}") bt.logging.debug(f"new seed : {new_seed}") bt.logging.debug(f"proof : {proof}") bt.logging.debug(f"commitment: {next_commitment}\n") synapse.commitment_hash = next_commitment synapse.commitment_proof = proof # update the commitment seed challenge hash in storage bt.logging.trace(f"udpating challenge miner storage: {pformat(data)}") await update_seed_info( self.database, synapse.challenge_hash, synapse.dendrite.hotkey, new_seed.decode("utf-8"), ) # Chunk the data according to the provided chunk_size bt.logging.trace(f"entering chunk_data()") data_chunks = chunk_data(encrypted_data_bytes, synapse.chunk_size) # Extract setup params g = hex_to_ecc_point(synapse.g, synapse.curve) h = hex_to_ecc_point(synapse.h, synapse.curve) # Commit the data chunks based on the provided curve points bt.logging.trace(f"entering ECCcommitment()") committer = ECCommitment(g, h) bt.logging.trace(f"entering commit_data_with_seed()")
# The MIT License (MIT) # Copyright © 2023 Yuma Rao # Copyright © 2023 philanthrope # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the “Software”), to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all copies or substantial portions of # the Software. # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO # THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # import this repo class miner: @classmethod def check_config(cls, config: "bt.Config"): """ Adds neuron-specific arguments to the argument parser. Args: parser (argparse.ArgumentParser): Parser to add arguments to. This class method enriches the argument parser with options specific to the neuron's configuration. """ check_config(cls, config) @classmethod def add_args(cls, parser): """ Adds neuron-specific arguments to the argument parser. Args: parser (argparse.ArgumentParser): Parser to add arguments to. This class method enriches the argument parser with options specific to the neuron's configuration. """ add_args(cls, parser) @classmethod def config(cls): """ Retrieves the configuration for the neuron. Returns: bt.Config: The configuration object for the neuron. This class method returns the neuron's configuration, which is used throughout the neuron's lifecycle for various functionalities and operations. """ return config(cls) subtensor: "bt.subtensor" wallet: "bt.wallet" metagraph: "bt.metagraph" def __init__(self): self.config = miner.config() self.check_config(self.config) bt.logging(config=self.config, logging_dir=self.config.miner.full_path) bt.logging.info(f"{self.config}") bt.logging.info("miner.__init__()") # Init device. bt.logging.debug("loading device") self.device = torch.device(self.config.miner.device) bt.logging.debug(str(self.device)) # Init subtensor bt.logging.debug("loading subtensor") self.subtensor = bt.subtensor(config=self.config) bt.logging.debug(str(self.subtensor)) self.current_block = self.subtensor.get_current_block() # Init wallet. bt.logging.debug("loading wallet") self.wallet = bt.wallet(config=self.config) self.wallet.create_if_non_existent() if not self.config.wallet._mock: if not self.subtensor.is_hotkey_registered_on_subnet( hotkey_ss58=self.wallet.hotkey.ss58_address, netuid=self.config.netuid ): raise Exception( f"Wallet not currently registered on netuid {self.config.netuid}, please first register wallet before running" ) bt.logging.debug(f"wallet: {str(self.wallet)}") # Init metagraph. bt.logging.debug("loading metagraph") self.metagraph = bt.metagraph( netuid=self.config.netuid, network=self.subtensor.network, sync=False ) # Make sure not to sync without passing subtensor self.metagraph.sync(subtensor=self.subtensor) # Sync metagraph with subtensor. bt.logging.debug(str(self.metagraph)) # Setup database self.database = aioredis.StrictRedis( host=self.config.database.host, port=self.config.database.port, db=self.config.database.index, socket_keepalive=True, socket_connect_timeout=300, ) self.my_subnet_uid = self.metagraph.hotkeys.index( self.wallet.hotkey.ss58_address ) bt.logging.info(f"Running miner on uid: {self.my_subnet_uid}") # Init wandb. if not self.config.wandb.off: bt.logging.debug("loading wandb") init_wandb(self) # The axon handles request processing, allowing validators to send this process requests. self.axon = bt.axon(wallet=self.wallet, config=self.config) bt.logging.info(f"Axon {self.axon}") # Attach determiners which functions are called when servicing a request. bt.logging.info(f"Attaching forward functions to axon.") self.axon.attach( forward_fn=self.store, blacklist_fn=self.store_blacklist_fn, priority_fn=self.store_priority_fn, ).attach( forward_fn=self.challenge, blacklist_fn=self.challenge_blacklist_fn, priority_fn=self.challenge_priority_fn, ).attach( forward_fn=self.retrieve, blacklist_fn=self.retrieve_blacklist_fn, priority_fn=self.retrieve_priority_fn, ) # Serve passes the axon information to the network + netuid we are hosting on. # This will auto-update if the axon port of external ip have changed. bt.logging.info( f"Serving axon {self.axon} on network: {self.subtensor.chain_endpoint} with netuid: {self.config.netuid}" ) self.axon.serve(netuid=self.config.netuid, subtensor=self.subtensor) # Start starts the miner's axon, making it active on the network. bt.logging.info(f"Starting axon server on port: {self.config.axon.port}") self.axon.start() # Init the event loop. self.loop = asyncio.get_event_loop() # Instantiate runners self.should_exit: bool = False self.is_running: bool = False self.thread: threading.Thread = None self.lock = asyncio.Lock() self.request_timestamps: Dict = {} self.step = 0 # Init the miner's storage request tracker self.request_count = 0 self.start_request_count_timer() self.requests_per_hour = [] self.average_requests_per_hour = 0 # Init the miner's storage usage tracker update_storage_stats(self) def start_request_count_timer(self): """ Initializes and starts a timer for tracking the number of requests received by the miner in an hour. This method sets up a one-hour timer that, upon expiration, calls the `reset_request_count` method to log the number of requests received and reset the count for the next hour. The timer is set to run in a separate thread to avoid blocking the main execution. Usage: Should be called during the initialization of the miner to start tracking requests per hour. """ self.request_count_timer = threading.Timer(3600, self.reset_request_count) self.request_count_timer.start() def reset_request_count(self): """ Logs the number of requests received in the last hour and resets the count. This method is automatically called when the one-hour timer set by `start_request_count_timer` expires. It logs the count of requests received in the last hour and then resets the count. Additionally, it restarts the timer for the next hour. Usage: This method is intended to be called automatically by a timer and typically should not be called directly. """ bt.logging.info( f"Number of requests received in the last hour: {self.request_count}" ) self.requests_per_hour.append(self.request_count) bt.logging.info(f"Requests per hour: {self.requests_per_hour}") self.average_requests_per_hour = sum(self.requests_per_hour) / len( self.requests_per_hour ) bt.logging.info(f"Average requests per hour: {self.average_requests_per_hour}") self.request_count = 0 self.start_request_count_timer() @property async def total_storage(self): """ Calculates the total size of data stored by the miner. This method fetches all data keys from the Redis database and sums up the size of each data object. It provides an estimate of the total amount of data currently held by the miner. Returns: int: Total size of data (in bytes) stored by the miner. Example: >>> miner.total_storage() 102400 # Example output indicating 102,400 bytes of data stored """ # Fetch all keys from Redis all_keys = await safe_key_search(self.database, "*") # Filter out keys that contain a period (temporary, remove later) filtered_keys = [key for key in all_keys if b"." not in key] # Get the size of each data object and sum them up total_size = sum( [ await get_chunk_metadata(self.database, key).get(b"size", 0) for key in filtered_keys ] ) return total_size def store_blacklist_fn( self, synapse: storage.protocol.Store ) -> typing.Tuple[bool, str]: """ Determines whether a given synapse should be blacklisted based on the recognition of the hotkey in the metagraph. This function is used to filter out requests from entities that are not part of the network's current state. Parameters: - synapse (bt.Synapse): The synapse object which contains the dendrite information including the hotkey. Returns: - (bool, str): A tuple where the first element is a boolean indicating whether the synapse's hotkey is blacklisted, and the second element is a string message explaining the reason. If the hotkey is not recognized in the metagraph, the synapse is blacklisted, and the function returns (True, "Unrecognized hotkey"). Otherwise, it returns (False, "Hotkey recognized!"), allowing the synapse to interact with the network. Usage: This method is internally used by the network to ensure that only recognized entities can participate in communication or transactions. """ if synapse.dendrite.hotkey not in self.metagraph.hotkeys: # Ignore requests from unrecognized entities. bt.logging.trace( f"Blacklisting unrecognized hotkey {synapse.dendrite.hotkey}" ) return True, "Unrecognized hotkey" bt.logging.trace( f"Not Blacklisting recognized hotkey {synapse.dendrite.hotkey}" ) return False, "Hotkey recognized!" def store_priority_fn(self, synapse: storage.protocol.Store) -> float: """ Assigns a priority to a given synapse based on the stake of the calling entity in the metagraph. This function is crucial for prioritizing network requests and ensuring that higher-stake entities are given precedence in processing. Parameters: - synapse (bt.Synapse): The synapse object which contains the dendrite information including the hotkey of the caller. Returns: - float: The priority value assigned to the synapse, derived from the stake of the calling hotkey in the metagraph. The priority is determined by the stake associated with the caller's UID in the metagraph. A higher stake results in a higher priority. Usage: This method is used within the network's request handling mechanism to allocate resources and processing time based on the stake-based priority of each request. """ caller_uid = self.metagraph.hotkeys.index( synapse.dendrite.hotkey ) # Get the caller index. prirority = float( self.metagraph.S[caller_uid] ) # Return the stake as the priority. bt.logging.trace( f"Prioritizing {synapse.dendrite.hotkey} with value: ", prirority ) return prirority def challenge_blacklist_fn( self, synapse: storage.protocol.Challenge ) -> typing.Tuple[bool, str]: """ Determines whether a given synapse should be blacklisted based on the recognition of the hotkey in the metagraph. This function is used to filter out requests from entities that are not part of the network's current state. Parameters: - synapse (bt.Synapse): The synapse object which contains the dendrite information including the hotkey. Returns: - (bool, str): A tuple where the first element is a boolean indicating whether the synapse's hotkey is blacklisted, and the second element is a string message explaining the reason. If the hotkey is not recognized in the metagraph, the synapse is blacklisted, and the function returns (True, "Unrecognized hotkey"). Otherwise, it returns (False, "Hotkey recognized!"), allowing the synapse to interact with the network. Usage: This method is internally used by the network to ensure that only recognized entities can participate in communication or transactions. """ if synapse.dendrite.hotkey not in self.metagraph.hotkeys: # Ignore requests from unrecognized entities. bt.logging.trace( f"Blacklisting unrecognized hotkey {synapse.dendrite.hotkey}" ) return True, "Unrecognized hotkey" bt.logging.trace( f"Not Blacklisting recognized hotkey {synapse.dendrite.hotkey}" ) return False, "Hotkey recognized!" def challenge_priority_fn(self, synapse: storage.protocol.Challenge) -> float: """ Assigns a priority to a given synapse based on the stake of the calling entity in the metagraph. This function is crucial for prioritizing network requests and ensuring that higher-stake entities are given precedence in processing. Parameters: - synapse (bt.Synapse): The synapse object which contains the dendrite information including the hotkey of the caller. Returns: - float: The priority value assigned to the synapse, derived from the stake of the calling hotkey in the metagraph. The priority is determined by the stake associated with the caller's UID in the metagraph. A higher stake results in a higher priority. Usage: This method is used within the network's request handling mechanism to allocate resources and processing time based on the stake-based priority of each request. """ caller_uid = self.metagraph.hotkeys.index( synapse.dendrite.hotkey ) # Get the caller index. prirority = float( self.metagraph.S[caller_uid] ) # Return the stake as the priority. bt.logging.trace( f"Prioritizing {synapse.dendrite.hotkey} with value: ", prirority ) return prirority def retrieve_blacklist_fn( self, synapse: storage.protocol.Retrieve ) -> typing.Tuple[bool, str]: """ Determines whether a given synapse should be blacklisted based on the recognition of the hotkey in the metagraph. This function is used to filter out requests from entities that are not part of the network's current state. Parameters: - synapse (bt.Synapse): The synapse object which contains the dendrite information including the hotkey. Returns: - (bool, str): A tuple where the first element is a boolean indicating whether the synapse's hotkey is blacklisted, and the second element is a string message explaining the reason. If the hotkey is not recognized in the metagraph, the synapse is blacklisted, and the function returns (True, "Unrecognized hotkey"). Otherwise, it returns (False, "Hotkey recognized!"), allowing the synapse to interact with the network. Usage: This method is internally used by the network to ensure that only recognized entities can participate in communication or transactions. """ if synapse.dendrite.hotkey not in self.metagraph.hotkeys: # Ignore requests from unrecognized entities. bt.logging.trace( f"Blacklisting unrecognized hotkey {synapse.dendrite.hotkey}" ) return True, "Unrecognized hotkey" bt.logging.trace( f"Not Blacklisting recognized hotkey {synapse.dendrite.hotkey}" ) return False, "Hotkey recognized!" def retrieve_priority_fn(self, synapse: storage.protocol.Retrieve) -> float: """ Assigns a priority to a given synapse based on the stake of the calling entity in the metagraph. This function is crucial for prioritizing network requests and ensuring that higher-stake entities are given precedence in processing. Parameters: - synapse (bt.Synapse): The synapse object which contains the dendrite information including the hotkey of the caller. Returns: - float: The priority value assigned to the synapse, derived from the stake of the calling hotkey in the metagraph. The priority is determined by the stake associated with the caller's UID in the metagraph. A higher stake results in a higher priority. Usage: This method is used within the network's request handling mechanism to allocate resources and processing time based on the stake-based priority of each request. """ caller_uid = self.metagraph.hotkeys.index( synapse.dendrite.hotkey ) # Get the caller index. prirority = float( self.metagraph.S[caller_uid] ) # Return the stake as the priority. bt.logging.trace( f"Prioritizing {synapse.dendrite.hotkey} with value: ", prirority ) return prirority async def store(self, synapse: storage.protocol.Store) -> storage.protocol.Store: """ Processes the storage request from a synapse by securely storing the provided data and returning a proof of storage. The data is committed using elliptic curve cryptography, stored on the filesystem, and the metadata is recorded in a Redis database. A cryptographic proof of the commitment, along with a digital signature from the server's hotkey, is returned in the synapse for verification by the requester. Args: synapse (storage.protocol.Store): An object containing the data to be stored, encoded in base64 format, along with associated metadata like the cryptographic curve parameters, a seed for the commitment, and the expected commitment group elements. Returns: storage.protocol.Store: The synapse is returned with additional fields populated, including the randomness used in the commitment, the commitment point itself, a signature from this storage server's hotkey, and a commitment hash that can be used for chained proofs. The method performs the following operations: 1. Decodes the base64-encoded data into raw bytes. 2. Commits to the data using the provided elliptic curve parameters and the seed to generate a commitment point. 3. Stores the raw byte data in the filesystem using a hash of the data as the filename. 4. Records metadata about the stored data in the Redis database, including the file path, previous seed, and data size. 5. Updates the synapse object with the commitment details and a digital signature. This process ensures the integrity and non-repudiation of the data storage, allowing clients to verify that their data has been stored correctly without the need to retrieve the full data set. Example usage: Assuming an initialized 'committer' object and 'synapse' with necessary data: >>> updated_synapse = self.store(synapse) """ bt.logging.info(f"received store request: {synapse.encrypted_data[:24]}") self.request_count += 1 # Decode the data from base64 to raw bytes encrypted_byte_data = base64.b64decode(synapse.encrypted_data) bt.logging.trace(f"store b64decrypted data: {encrypted_byte_data[:24]}") # Store the data with the hash as the key in the filesystem bt.logging.trace(f"entering hash_data()") data_hash = hash_data(encrypted_byte_data) # If already storing this hash, simply update the validator seeds and return challenge bt.logging.trace(f"checking if data already exists...") if await self.database.exists(data_hash): # update the validator seed challenge hash in storage await update_seed_info( self.database, data_hash, synapse.dendrite.hotkey, synapse.seed ) else: # Store the data in the filesystem filepath = save_data_to_filesystem( encrypted_byte_data, self.config.database.directory, str(data_hash) ) bt.logging.trace(f"stored data {data_hash} in filepath: {filepath}") # Add the initial chunk, size, and validator seed information await store_chunk_metadata( self.database, data_hash, filepath, synapse.dendrite.hotkey, sys.getsizeof(encrypted_byte_data), synapse.seed, ) # Commit to the entire data block bt.logging.trace(f"entering ECCommitment()") committer = ECCommitment( hex_to_ecc_point(synapse.g, synapse.curve), hex_to_ecc_point(synapse.h, synapse.curve), ) bt.logging.trace(f"entering commit()") c, m_val, r = committer.commit(encrypted_byte_data + str(synapse.seed).encode()) if self.config.miner.verbose: bt.logging.debug(f"committer: {committer}") bt.logging.debug(f"encrypted_byte_data: {encrypted_byte_data}") bt.logging.debug(f"c: {c}") bt.logging.debug(f"m_val: {m_val}") bt.logging.debug(f"r: {r}") # Send back some proof that we stored the data synapse.randomness = r synapse.commitment = ecc_point_to_hex(c) bt.logging.trace(f"signed commitment: {synapse.commitment}") # Initialize the commitment hash with the initial commitment for chained proofs synapse.commitment_hash = str(m_val) bt.logging.trace(f"initial commitment_hash: {synapse.commitment_hash}") if self.config.miner.verbose: bt.logging.debug(f"signed m_val: {synapse.signature.hex()}") bt.logging.debug(f"type(seed): {type(synapse.seed)}") bt.logging.debug(f"initial commitment_hash: {synapse.commitment_hash}") bt.logging.info( f"stored data hash {data_hash} with commitment: {synapse.commitment}" ) # Don't send data back, no need. synapse.encrypted_data = base64.b64encode(b"").decode() # Empty b64 response return synapse async def challenge( self, synapse: storage.protocol.Challenge ) -> storage.protocol.Challenge: """ Handles a data challenge by providing cryptographic proof of data possession. This method retrieves the specified data from storage, calculates its commitment using elliptic curve cryptography, and constructs a Merkle proof. The response includes the requested data chunk, Merkle proof, root, and the commitment, which collectively serve as verifiable evidence of data possession. Args: synapse (storage.protocol.Challenge): An object representing the challenge request, which includes parameters such as the hash of the data to retrieve, chunk size, challenge index, and elliptic curve parameters for commitment calculation. Returns: storage.protocol.Challenge: The synapse object is updated with the response to the challenge, including the encrypted data chunk, commitment point, Merkle proof, and root hash. The method performs the following steps: 1. Fetches the encrypted data from storage using the hash provided in the challenge. 2. Splits the data into chunks based on the specified chunk size. 3. Computes a new commitment hash to provide a time-bound proof of possession. 4. Generates a Merkle tree from the committed data chunks and extracts a proof for the requested chunk. 5. Encodes the requested chunk and Merkle proof in base64 for transmission. 6. Updates the challenge synapse with the commitment, data chunk, randomness, and Merkle proof. 7. Records the updated commitment hash in storage for future challenges. This method ensures data integrity and allows the verification of data possession without disclosing the entire data set. It is designed to fulfill data verification requests in a secure and verifiable manner. Example usage: Assuming an initialized 'synapse' object with the challenge parameters: >>> updated_synapse = self.challenge(synapse) """ # Retrieve the data itself from miner storage bt.logging.info(f"received challenge hash: {synapse.challenge_hash}") self.request_count += 1 bt.logging.trace(f"entering get_chunk_metadata()") data = await get_chunk_metadata(self.database, synapse.challenge_hash) if data is None: bt.logging.error(f"No data found for {synapse.challenge_hash}") return synapse bt.logging.trace(f"retrieved data: {pformat(data)}") # Chunk the data according to the specified (random) chunk size filepath = data.get(b"filepath", None) if filepath is None: bt.logging.warning( f"No file found for {synapse.challenge_hash} in index, trying path construction..." ) # fallback to load the data from the filesystem via database path construction filepath = os.path.expanduser( f"{self.config.database.directory}/{synapse.challenge_hash}" ) if not os.path.isfile(filepath): bt.logging.error( f"No file found for {synapse.challenge_hash} in {self.config.database.directory}." ) return synapse bt.logging.trace(f"entering load_from_filesystem()") try: encrypted_data_bytes = load_from_filesystem(filepath) except Exception as e: bt.logging.error(f"Error loading file {filepath}: {e}") synapse.axon.status_code = 404 synapse.axon.status_message = "File not found" return synapse # Construct the next commitment hash using previous commitment and hash # of the data to prove storage over time prev_seed = data.get(b"seed", "").encode() if prev_seed == None: bt.logging.error(f"No seed found for {synapse.challenge_hash}") return synapse bt.logging.trace(f"entering comput_subsequent_commitment()...") new_seed = synapse.seed.encode() next_commitment, proof = compute_subsequent_commitment( encrypted_data_bytes, prev_seed, new_seed, verbose=self.config.miner.verbose ) if self.config.miner.verbose: bt.logging.debug(f"prev seed : {prev_seed}") bt.logging.debug(f"new seed : {new_seed}") bt.logging.debug(f"proof : {proof}") bt.logging.debug(f"commitment: {next_commitment}\n") synapse.commitment_hash = next_commitment synapse.commitment_proof = proof # update the commitment seed challenge hash in storage bt.logging.trace(f"udpating challenge miner storage: {pformat(data)}") await update_seed_info( self.database, synapse.challenge_hash, synapse.dendrite.hotkey, new_seed.decode("utf-8"), ) # Chunk the data according to the provided chunk_size bt.logging.trace(f"entering chunk_data()") data_chunks = chunk_data(encrypted_data_bytes, synapse.chunk_size) # Extract setup params g = hex_to_ecc_point(synapse.g, synapse.curve) h = hex_to_ecc_point(synapse.h, synapse.curve) # Commit the data chunks based on the provided curve points bt.logging.trace(f"entering ECCcommitment()") committer = ECCommitment(g, h) bt.logging.trace(f"entering commit_data_with_seed()")
randomness, chunks, commitments, merkle_tree = commit_data_with_seed(
15
2023-10-26 18:54:47+00:00
24k
cpacker/MemGPT
memgpt/main.py
[ { "identifier": "logger", "path": "memgpt/log.py", "snippet": "" }, { "identifier": "CLIInterface", "path": "memgpt/interface.py", "snippet": "class CLIInterface(AgentInterface):\r\n \"\"\"Basic interface for dumping agent events to the command-line\"\"\"\r\n\r\n @staticmethod\r\n def important_message(msg):\r\n fstr = f\"{Fore.MAGENTA}{Style.BRIGHT}{{msg}}{Style.RESET_ALL}\"\r\n if STRIP_UI:\r\n fstr = \"{msg}\"\r\n print(fstr.format(msg=msg))\r\n\r\n @staticmethod\r\n def warning_message(msg):\r\n fstr = f\"{Fore.RED}{Style.BRIGHT}{{msg}}{Style.RESET_ALL}\"\r\n if STRIP_UI:\r\n fstr = \"{msg}\"\r\n else:\r\n print(fstr.format(msg=msg))\r\n\r\n @staticmethod\r\n def internal_monologue(msg):\r\n # ANSI escape code for italic is '\\x1B[3m'\r\n fstr = f\"\\x1B[3m{Fore.LIGHTBLACK_EX}💭 {{msg}}{Style.RESET_ALL}\"\r\n if STRIP_UI:\r\n fstr = \"{msg}\"\r\n print(fstr.format(msg=msg))\r\n\r\n @staticmethod\r\n def assistant_message(msg):\r\n fstr = f\"{Fore.YELLOW}{Style.BRIGHT}🤖 {Fore.YELLOW}{{msg}}{Style.RESET_ALL}\"\r\n if STRIP_UI:\r\n fstr = \"{msg}\"\r\n print(fstr.format(msg=msg))\r\n\r\n @staticmethod\r\n def memory_message(msg):\r\n fstr = f\"{Fore.LIGHTMAGENTA_EX}{Style.BRIGHT}🧠 {Fore.LIGHTMAGENTA_EX}{{msg}}{Style.RESET_ALL}\"\r\n if STRIP_UI:\r\n fstr = \"{msg}\"\r\n print(fstr.format(msg=msg))\r\n\r\n @staticmethod\r\n def system_message(msg):\r\n fstr = f\"{Fore.MAGENTA}{Style.BRIGHT}🖥️ [system] {Fore.MAGENTA}{msg}{Style.RESET_ALL}\"\r\n if STRIP_UI:\r\n fstr = \"{msg}\"\r\n print(fstr.format(msg=msg))\r\n\r\n @staticmethod\r\n def user_message(msg, raw=False, dump=False, debug=DEBUG):\r\n def print_user_message(icon, msg, printf=print):\r\n if STRIP_UI:\r\n printf(f\"{icon} {msg}\")\r\n else:\r\n printf(f\"{Fore.GREEN}{Style.BRIGHT}{icon} {Fore.GREEN}{msg}{Style.RESET_ALL}\")\r\n\r\n def printd_user_message(icon, msg):\r\n return print_user_message(icon, msg)\r\n\r\n if not (raw or dump or debug):\r\n # we do not want to repeat the message in normal use\r\n return\r\n\r\n if isinstance(msg, str):\r\n if raw:\r\n printd_user_message(\"🧑\", msg)\r\n return\r\n else:\r\n try:\r\n msg_json = json.loads(msg)\r\n except:\r\n printd(f\"{CLI_WARNING_PREFIX}failed to parse user message into json\")\r\n printd_user_message(\"🧑\", msg)\r\n return\r\n if msg_json[\"type\"] == \"user_message\":\r\n if dump:\r\n print_user_message(\"🧑\", msg_json[\"message\"])\r\n return\r\n msg_json.pop(\"type\")\r\n printd_user_message(\"🧑\", msg_json)\r\n elif msg_json[\"type\"] == \"heartbeat\":\r\n if debug:\r\n msg_json.pop(\"type\")\r\n printd_user_message(\"💓\", msg_json)\r\n elif dump:\r\n print_user_message(\"💓\", msg_json)\r\n return\r\n\r\n elif msg_json[\"type\"] == \"system_message\":\r\n msg_json.pop(\"type\")\r\n printd_user_message(\"🖥️\", msg_json)\r\n else:\r\n printd_user_message(\"🧑\", msg_json)\r\n\r\n @staticmethod\r\n def function_message(msg, debug=DEBUG):\r\n def print_function_message(icon, msg, color=Fore.RED, printf=print):\r\n if STRIP_UI:\r\n printf(f\"⚡{icon} [function] {msg}\")\r\n else:\r\n printf(f\"{color}{Style.BRIGHT}⚡{icon} [function] {color}{msg}{Style.RESET_ALL}\")\r\n\r\n def printd_function_message(icon, msg, color=Fore.RED):\r\n return print_function_message(icon, msg, color, printf=(print if debug else printd))\r\n\r\n if isinstance(msg, dict):\r\n printd_function_message(\"\", msg)\r\n return\r\n\r\n if msg.startswith(\"Success\"):\r\n printd_function_message(\"🟢\", msg)\r\n elif msg.startswith(\"Error: \"):\r\n printd_function_message(\"🔴\", msg)\r\n elif msg.startswith(\"Running \"):\r\n if debug:\r\n printd_function_message(\"\", msg)\r\n else:\r\n match = re.search(r\"Running (\\w+)\\((.*)\\)\", msg)\r\n if match:\r\n function_name = match.group(1)\r\n function_args = match.group(2)\r\n if function_name in [\"archival_memory_insert\", \"archival_memory_search\", \"core_memory_replace\", \"core_memory_append\"]:\r\n if function_name in [\"archival_memory_insert\", \"core_memory_append\", \"core_memory_replace\"]:\r\n print_function_message(\"🧠\", f\"updating memory with {function_name}\")\r\n elif function_name == \"archival_memory_search\":\r\n print_function_message(\"🧠\", f\"searching memory with {function_name}\")\r\n try:\r\n msg_dict = eval(function_args)\r\n if function_name == \"archival_memory_search\":\r\n output = f'\\tquery: {msg_dict[\"query\"]}, page: {msg_dict[\"page\"]}'\r\n if STRIP_UI:\r\n print(output)\r\n else:\r\n print(f\"{Fore.RED}{output}{Style.RESET_ALL}\")\r\n elif function_name == \"archival_memory_insert\":\r\n output = f'\\t→ {msg_dict[\"content\"]}'\r\n if STRIP_UI:\r\n print(output)\r\n else:\r\n print(f\"{Style.BRIGHT}{Fore.RED}{output}{Style.RESET_ALL}\")\r\n else:\r\n if STRIP_UI:\r\n print(f'\\t {msg_dict[\"old_content\"]}\\n\\t→ {msg_dict[\"new_content\"]}')\r\n else:\r\n print(\r\n f'{Style.BRIGHT}\\t{Fore.RED} {msg_dict[\"old_content\"]}\\n\\t{Fore.GREEN}→ {msg_dict[\"new_content\"]}{Style.RESET_ALL}'\r\n )\r\n except Exception as e:\r\n printd(str(e))\r\n printd(msg_dict)\r\n pass\r\n elif function_name in [\"conversation_search\", \"conversation_search_date\"]:\r\n print_function_message(\"🧠\", f\"searching memory with {function_name}\")\r\n try:\r\n msg_dict = eval(function_args)\r\n output = f'\\tquery: {msg_dict[\"query\"]}, page: {msg_dict[\"page\"]}'\r\n if STRIP_UI:\r\n print(output)\r\n else:\r\n print(f\"{Fore.RED}{output}{Style.RESET_ALL}\")\r\n except Exception as e:\r\n printd(str(e))\r\n printd(msg_dict)\r\n pass\r\n else:\r\n printd(f\"{CLI_WARNING_PREFIX}did not recognize function message\")\r\n printd_function_message(\"\", msg)\r\n else:\r\n try:\r\n msg_dict = json.loads(msg)\r\n if \"status\" in msg_dict and msg_dict[\"status\"] == \"OK\":\r\n printd_function_message(\"\", str(msg), color=Fore.GREEN)\r\n else:\r\n printd_function_message(\"\", str(msg), color=Fore.RED)\r\n except Exception:\r\n print(f\"{CLI_WARNING_PREFIX}did not recognize function message {type(msg)} {msg}\")\r\n printd_function_message(\"\", msg)\r\n\r\n @staticmethod\r\n def print_messages(message_sequence, dump=False):\r\n idx = len(message_sequence)\r\n for msg in message_sequence:\r\n if dump:\r\n print(f\"[{idx}] \", end=\"\")\r\n idx -= 1\r\n role = msg[\"role\"]\r\n content = msg[\"content\"]\r\n\r\n if role == \"system\":\r\n CLIInterface.system_message(content)\r\n elif role == \"assistant\":\r\n # Differentiate between internal monologue, function calls, and messages\r\n if msg.get(\"function_call\"):\r\n if content is not None:\r\n CLIInterface.internal_monologue(content)\r\n # I think the next one is not up to date\r\n # function_message(msg[\"function_call\"])\r\n args = json.loads(msg[\"function_call\"].get(\"arguments\"))\r\n CLIInterface.assistant_message(args.get(\"message\"))\r\n # assistant_message(content)\r\n else:\r\n CLIInterface.internal_monologue(content)\r\n elif role == \"user\":\r\n CLIInterface.user_message(content, dump=dump)\r\n elif role == \"function\":\r\n CLIInterface.function_message(content, debug=dump)\r\n else:\r\n print(f\"Unknown role: {content}\")\r\n\r\n @staticmethod\r\n def print_messages_simple(message_sequence):\r\n for msg in message_sequence:\r\n role = msg[\"role\"]\r\n content = msg[\"content\"]\r\n\r\n if role == \"system\":\r\n CLIInterface.system_message(content)\r\n elif role == \"assistant\":\r\n CLIInterface.assistant_message(content)\r\n elif role == \"user\":\r\n CLIInterface.user_message(content, raw=True)\r\n else:\r\n print(f\"Unknown role: {content}\")\r\n\r\n @staticmethod\r\n def print_messages_raw(message_sequence):\r\n for msg in message_sequence:\r\n print(msg)\r\n\r\n @staticmethod\r\n def step_yield():\r\n pass\r" }, { "identifier": "MemGPTConfig", "path": "memgpt/config.py", "snippet": "class MemGPTConfig:\n config_path: str = os.path.join(MEMGPT_DIR, \"config\")\n anon_clientid: str = None\n\n # preset\n preset: str = DEFAULT_PRESET\n\n # persona parameters\n persona: str = DEFAULT_PERSONA\n human: str = DEFAULT_HUMAN\n agent: str = None\n\n # model parameters\n default_llm_config: LLMConfig = field(default_factory=LLMConfig)\n\n # embedding parameters\n default_embedding_config: EmbeddingConfig = field(default_factory=EmbeddingConfig)\n\n # database configs: archival\n archival_storage_type: str = \"chroma\" # local, db\n archival_storage_path: str = os.path.join(MEMGPT_DIR, \"chroma\")\n archival_storage_uri: str = None # TODO: eventually allow external vector DB\n\n # database configs: recall\n recall_storage_type: str = \"sqlite\" # local, db\n recall_storage_path: str = MEMGPT_DIR\n recall_storage_uri: str = None # TODO: eventually allow external vector DB\n\n # database configs: metadata storage (sources, agents, data sources)\n metadata_storage_type: str = \"sqlite\"\n metadata_storage_path: str = MEMGPT_DIR\n metadata_storage_uri: str = None\n\n # database configs: agent state\n persistence_manager_type: str = None # in-memory, db\n persistence_manager_save_file: str = None # local file\n persistence_manager_uri: str = None # db URI\n\n # version (for backcompat)\n memgpt_version: str = None\n\n # user info\n policies_accepted: bool = False\n\n def __post_init__(self):\n # ensure types\n # self.embedding_chunk_size = int(self.embedding_chunk_size)\n # self.embedding_dim = int(self.embedding_dim)\n # self.context_window = int(self.context_window)\n pass\n\n @staticmethod\n def generate_uuid() -> str:\n return uuid.UUID(int=uuid.getnode()).hex\n\n @classmethod\n def load(cls) -> \"MemGPTConfig\":\n # avoid circular import\n from memgpt.migrate import config_is_compatible, VERSION_CUTOFF\n\n if not config_is_compatible(allow_empty=True):\n error_message = \" \".join(\n [\n f\"\\nYour current config file is incompatible with MemGPT versions later than {VERSION_CUTOFF}.\",\n f\"\\nTo use MemGPT, you must either downgrade your MemGPT version (<= {VERSION_CUTOFF}) or regenerate your config using `memgpt configure`, or `memgpt migrate` if you would like to migrate old agents.\",\n ]\n )\n raise ValueError(error_message)\n\n config = configparser.ConfigParser()\n\n # allow overriding with env variables\n if os.getenv(\"MEMGPT_CONFIG_PATH\"):\n config_path = os.getenv(\"MEMGPT_CONFIG_PATH\")\n else:\n config_path = MemGPTConfig.config_path\n\n # insure all configuration directories exist\n cls.create_config_dir()\n if os.path.exists(config_path):\n # read existing config\n config.read(config_path)\n\n # Handle extraction of nested LLMConfig and EmbeddingConfig\n llm_config_dict = {\n # Extract relevant LLM configuration from the config file\n \"model\": get_field(config, \"model\", \"model\"),\n \"model_endpoint\": get_field(config, \"model\", \"model_endpoint\"),\n \"model_endpoint_type\": get_field(config, \"model\", \"model_endpoint_type\"),\n \"model_wrapper\": get_field(config, \"model\", \"model_wrapper\"),\n \"context_window\": get_field(config, \"model\", \"context_window\"),\n }\n embedding_config_dict = {\n # Extract relevant Embedding configuration from the config file\n \"embedding_endpoint\": get_field(config, \"embedding\", \"embedding_endpoint\"),\n \"embedding_model\": get_field(config, \"embedding\", \"embedding_model\"),\n \"embedding_endpoint_type\": get_field(config, \"embedding\", \"embedding_endpoint_type\"),\n \"embedding_dim\": get_field(config, \"embedding\", \"embedding_dim\"),\n \"embedding_chunk_size\": get_field(config, \"embedding\", \"chunk_size\"),\n }\n # Correct the types that aren't strings\n if llm_config_dict[\"context_window\"] is not None:\n llm_config_dict[\"context_window\"] = int(llm_config_dict[\"context_window\"])\n if embedding_config_dict[\"embedding_dim\"] is not None:\n embedding_config_dict[\"embedding_dim\"] = int(embedding_config_dict[\"embedding_dim\"])\n if embedding_config_dict[\"embedding_chunk_size\"] is not None:\n embedding_config_dict[\"embedding_chunk_size\"] = int(embedding_config_dict[\"embedding_chunk_size\"])\n # Construct the inner properties\n llm_config = LLMConfig(**llm_config_dict)\n embedding_config = EmbeddingConfig(**embedding_config_dict)\n\n # Everything else\n config_dict = {\n # Two prepared configs\n \"default_llm_config\": llm_config,\n \"default_embedding_config\": embedding_config,\n # Agent related\n \"preset\": get_field(config, \"defaults\", \"preset\"),\n \"persona\": get_field(config, \"defaults\", \"persona\"),\n \"human\": get_field(config, \"defaults\", \"human\"),\n \"agent\": get_field(config, \"defaults\", \"agent\"),\n # Storage related\n \"archival_storage_type\": get_field(config, \"archival_storage\", \"type\"),\n \"archival_storage_path\": get_field(config, \"archival_storage\", \"path\"),\n \"archival_storage_uri\": get_field(config, \"archival_storage\", \"uri\"),\n \"recall_storage_type\": get_field(config, \"recall_storage\", \"type\"),\n \"recall_storage_path\": get_field(config, \"recall_storage\", \"path\"),\n \"recall_storage_uri\": get_field(config, \"recall_storage\", \"uri\"),\n \"metadata_storage_type\": get_field(config, \"metadata_storage\", \"type\"),\n \"metadata_storage_path\": get_field(config, \"metadata_storage\", \"path\"),\n \"metadata_storage_uri\": get_field(config, \"metadata_storage\", \"uri\"),\n # Misc\n \"anon_clientid\": get_field(config, \"client\", \"anon_clientid\"),\n \"config_path\": config_path,\n \"memgpt_version\": get_field(config, \"version\", \"memgpt_version\"),\n }\n\n # Don't include null values\n config_dict = {k: v for k, v in config_dict.items() if v is not None}\n\n return cls(**config_dict)\n\n # create new config\n anon_clientid = MemGPTConfig.generate_uuid()\n config = cls(anon_clientid=anon_clientid, config_path=config_path)\n config.create_config_dir() # create dirs\n config.save() # save updated config\n\n return config\n\n def save(self):\n import memgpt\n\n config = configparser.ConfigParser()\n\n # CLI defaults\n set_field(config, \"defaults\", \"preset\", self.preset)\n set_field(config, \"defaults\", \"persona\", self.persona)\n set_field(config, \"defaults\", \"human\", self.human)\n set_field(config, \"defaults\", \"agent\", self.agent)\n\n # model defaults\n set_field(config, \"model\", \"model\", self.default_llm_config.model)\n set_field(config, \"model\", \"model_endpoint\", self.default_llm_config.model_endpoint)\n set_field(config, \"model\", \"model_endpoint_type\", self.default_llm_config.model_endpoint_type)\n set_field(config, \"model\", \"model_wrapper\", self.default_llm_config.model_wrapper)\n set_field(config, \"model\", \"context_window\", str(self.default_llm_config.context_window))\n\n # embeddings\n set_field(config, \"embedding\", \"embedding_endpoint_type\", self.default_embedding_config.embedding_endpoint_type)\n set_field(config, \"embedding\", \"embedding_endpoint\", self.default_embedding_config.embedding_endpoint)\n set_field(config, \"embedding\", \"embedding_model\", self.default_embedding_config.embedding_model)\n set_field(config, \"embedding\", \"embedding_dim\", str(self.default_embedding_config.embedding_dim))\n set_field(config, \"embedding\", \"embedding_chunk_size\", str(self.default_embedding_config.embedding_chunk_size))\n\n # archival storage\n set_field(config, \"archival_storage\", \"type\", self.archival_storage_type)\n set_field(config, \"archival_storage\", \"path\", self.archival_storage_path)\n set_field(config, \"archival_storage\", \"uri\", self.archival_storage_uri)\n\n # recall storage\n set_field(config, \"recall_storage\", \"type\", self.recall_storage_type)\n set_field(config, \"recall_storage\", \"path\", self.recall_storage_path)\n set_field(config, \"recall_storage\", \"uri\", self.recall_storage_uri)\n\n # metadata storage\n set_field(config, \"metadata_storage\", \"type\", self.metadata_storage_type)\n set_field(config, \"metadata_storage\", \"path\", self.metadata_storage_path)\n set_field(config, \"metadata_storage\", \"uri\", self.metadata_storage_uri)\n\n # set version\n set_field(config, \"version\", \"memgpt_version\", memgpt.__version__)\n\n # client\n if not self.anon_clientid:\n self.anon_clientid = self.generate_uuid()\n set_field(config, \"client\", \"anon_clientid\", self.anon_clientid)\n\n # always make sure all directories are present\n self.create_config_dir()\n\n with open(self.config_path, \"w\") as f:\n config.write(f)\n logger.debug(f\"Saved Config: {self.config_path}\")\n\n @staticmethod\n def exists():\n # allow overriding with env variables\n if os.getenv(\"MEMGPT_CONFIG_PATH\"):\n config_path = os.getenv(\"MEMGPT_CONFIG_PATH\")\n else:\n config_path = MemGPTConfig.config_path\n\n assert not os.path.isdir(config_path), f\"Config path {config_path} cannot be set to a directory.\"\n return os.path.exists(config_path)\n\n @staticmethod\n def create_config_dir():\n if not os.path.exists(MEMGPT_DIR):\n os.makedirs(MEMGPT_DIR, exist_ok=True)\n\n folders = [\"personas\", \"humans\", \"archival\", \"agents\", \"functions\", \"system_prompts\", \"presets\", \"settings\"]\n\n for folder in folders:\n if not os.path.exists(os.path.join(MEMGPT_DIR, folder)):\n os.makedirs(os.path.join(MEMGPT_DIR, folder))" }, { "identifier": "run", "path": "memgpt/cli/cli.py", "snippet": "def run(\n persona: str = typer.Option(None, help=\"Specify persona\"),\n agent: str = typer.Option(None, help=\"Specify agent save file\"),\n human: str = typer.Option(None, help=\"Specify human\"),\n preset: str = typer.Option(None, help=\"Specify preset\"),\n # model flags\n model: str = typer.Option(None, help=\"Specify the LLM model\"),\n model_wrapper: str = typer.Option(None, help=\"Specify the LLM model wrapper\"),\n model_endpoint: str = typer.Option(None, help=\"Specify the LLM model endpoint\"),\n model_endpoint_type: str = typer.Option(None, help=\"Specify the LLM model endpoint type\"),\n context_window: int = typer.Option(None, help=\"The context window of the LLM you are using (e.g. 8k for most Mistral 7B variants)\"),\n # other\n first: bool = typer.Option(False, \"--first\", help=\"Use --first to send the first message in the sequence\"),\n strip_ui: bool = typer.Option(False, help=\"Remove all the bells and whistles in CLI output (helpful for testing)\"),\n debug: bool = typer.Option(False, \"--debug\", help=\"Use --debug to enable debugging output\"),\n no_verify: bool = typer.Option(False, help=\"Bypass message verification\"),\n yes: bool = typer.Option(False, \"-y\", help=\"Skip confirmation prompt and use defaults\"),\n):\n \"\"\"Start chatting with an MemGPT agent\n\n Example usage: `memgpt run --agent myagent --data-source mydata --persona mypersona --human myhuman --model gpt-3.5-turbo`\n\n :param persona: Specify persona\n :param agent: Specify agent name (will load existing state if the agent exists, or create a new one with that name)\n :param human: Specify human\n :param model: Specify the LLM model\n\n \"\"\"\n\n # setup logger\n # TODO: remove Utils Debug after global logging is complete.\n utils.DEBUG = debug\n # TODO: add logging command line options for runtime log level\n\n if debug:\n logger.setLevel(logging.DEBUG)\n else:\n logger.setLevel(logging.CRITICAL)\n\n from memgpt.migrate import config_is_compatible, wipe_config_and_reconfigure, VERSION_CUTOFF\n\n if not config_is_compatible(allow_empty=True):\n typer.secho(f\"\\nYour current config file is incompatible with MemGPT versions later than {VERSION_CUTOFF}\\n\", fg=typer.colors.RED)\n choices = [\n \"Run the full config setup (recommended)\",\n \"Create a new config using defaults\",\n \"Cancel\",\n ]\n selection = questionary.select(\n f\"To use MemGPT, you must either downgrade your MemGPT version (<= {VERSION_CUTOFF}), or regenerate your config. Would you like to proceed?\",\n choices=choices,\n default=choices[0],\n ).ask()\n if selection == choices[0]:\n try:\n wipe_config_and_reconfigure()\n except Exception as e:\n typer.secho(f\"Fresh config generation failed - error:\\n{e}\", fg=typer.colors.RED)\n raise\n elif selection == choices[1]:\n try:\n wipe_config_and_reconfigure(run_configure=False)\n except Exception as e:\n typer.secho(f\"Fresh config generation failed - error:\\n{e}\", fg=typer.colors.RED)\n raise\n else:\n typer.secho(\"Migration cancelled (to migrate old agents, run `memgpt migrate`)\", fg=typer.colors.RED)\n raise KeyboardInterrupt()\n\n if not MemGPTConfig.exists():\n # if no config, ask about quickstart\n # do you want to do:\n # - openai (run quickstart)\n # - memgpt hosted (run quickstart)\n # - other (run configure)\n if yes:\n # if user is passing '-y' to bypass all inputs, use memgpt hosted\n # since it can't fail out if you don't have an API key\n quickstart(backend=QuickstartChoice.memgpt_hosted)\n config = MemGPTConfig()\n\n else:\n config_choices = {\n \"memgpt\": \"Use the free MemGPT endpoints\",\n \"openai\": \"Use OpenAI (requires an OpenAI API key)\",\n \"other\": \"Other (OpenAI Azure, custom LLM endpoint, etc)\",\n }\n print()\n config_selection = questionary.select(\n \"How would you like to set up MemGPT?\",\n choices=list(config_choices.values()),\n default=config_choices[\"memgpt\"],\n ).ask()\n\n if config_selection == config_choices[\"memgpt\"]:\n print()\n quickstart(backend=QuickstartChoice.memgpt_hosted, debug=debug, terminal=False, latest=False)\n elif config_selection == config_choices[\"openai\"]:\n print()\n quickstart(backend=QuickstartChoice.openai, debug=debug, terminal=False, latest=False)\n elif config_selection == config_choices[\"other\"]:\n configure()\n else:\n raise ValueError(config_selection)\n\n config = MemGPTConfig.load()\n\n else: # load config\n config = MemGPTConfig.load()\n\n # force re-configuration is config is from old version\n if config.memgpt_version is None: # TODO: eventually add checks for older versions, if config changes again\n typer.secho(\"MemGPT has been updated to a newer version, so re-running configuration.\", fg=typer.colors.YELLOW)\n configure()\n config = MemGPTConfig.load()\n\n # read user id from config\n ms = MetadataStore(config)\n user_id = uuid.UUID(config.anon_clientid)\n user = ms.get_user(user_id=user_id)\n if user is None:\n ms.create_user(User(id=user_id))\n user = ms.get_user(user_id=user_id)\n if user is None:\n typer.secho(f\"Failed to create default user in database.\", fg=typer.colors.RED)\n sys.exit(1)\n\n # override with command line arguments\n if debug:\n config.debug = debug\n if no_verify:\n config.no_verify = no_verify\n # determine agent to use, if not provided\n if not yes and not agent:\n agents = ms.list_agents(user_id=user.id)\n agents = [a.name for a in agents]\n\n if len(agents) > 0 and not any([persona, human, model]):\n print()\n select_agent = questionary.confirm(\"Would you like to select an existing agent?\").ask()\n if select_agent is None:\n raise KeyboardInterrupt\n if select_agent:\n agent = questionary.select(\"Select agent:\", choices=agents).ask()\n\n # create agent config\n if agent and ms.get_agent(agent_name=agent, user_id=user.id): # use existing agent\n typer.secho(f\"\\n🔁 Using existing agent {agent}\", fg=typer.colors.GREEN)\n # agent_config = AgentConfig.load(agent)\n agent_state = ms.get_agent(agent_name=agent, user_id=user_id)\n printd(\"Loading agent state:\", agent_state.id)\n printd(\"Agent state:\", agent_state.state)\n # printd(\"State path:\", agent_config.save_state_dir())\n # printd(\"Persistent manager path:\", agent_config.save_persistence_manager_dir())\n # printd(\"Index path:\", agent_config.save_agent_index_dir())\n # persistence_manager = LocalStateManager(agent_config).load() # TODO: implement load\n # TODO: load prior agent state\n if persona and persona != agent_state.persona:\n typer.secho(f\"{CLI_WARNING_PREFIX}Overriding existing persona {agent_state.persona} with {persona}\", fg=typer.colors.YELLOW)\n agent_state.persona = persona\n # raise ValueError(f\"Cannot override {agent_state.name} existing persona {agent_state.persona} with {persona}\")\n if human and human != agent_state.human:\n typer.secho(f\"{CLI_WARNING_PREFIX}Overriding existing human {agent_state.human} with {human}\", fg=typer.colors.YELLOW)\n agent_state.human = human\n # raise ValueError(f\"Cannot override {agent_config.name} existing human {agent_config.human} with {human}\")\n\n # Allow overriding model specifics (model, model wrapper, model endpoint IP + type, context_window)\n if model and model != agent_state.llm_config.model:\n typer.secho(\n f\"{CLI_WARNING_PREFIX}Overriding existing model {agent_state.llm_config.model} with {model}\", fg=typer.colors.YELLOW\n )\n agent_state.llm_config.model = model\n if context_window is not None and int(context_window) != agent_state.llm_config.context_window:\n typer.secho(\n f\"{CLI_WARNING_PREFIX}Overriding existing context window {agent_state.llm_config.context_window} with {context_window}\",\n fg=typer.colors.YELLOW,\n )\n agent_state.llm_config.context_window = context_window\n if model_wrapper and model_wrapper != agent_state.llm_config.model_wrapper:\n typer.secho(\n f\"{CLI_WARNING_PREFIX}Overriding existing model wrapper {agent_state.llm_config.model_wrapper} with {model_wrapper}\",\n fg=typer.colors.YELLOW,\n )\n agent_state.llm_config.model_wrapper = model_wrapper\n if model_endpoint and model_endpoint != agent_state.llm_config.model_endpoint:\n typer.secho(\n f\"{CLI_WARNING_PREFIX}Overriding existing model endpoint {agent_state.llm_config.model_endpoint} with {model_endpoint}\",\n fg=typer.colors.YELLOW,\n )\n agent_state.llm_config.model_endpoint = model_endpoint\n if model_endpoint_type and model_endpoint_type != agent_state.llm_config.model_endpoint_type:\n typer.secho(\n f\"{CLI_WARNING_PREFIX}Overriding existing model endpoint type {agent_state.llm_config.model_endpoint_type} with {model_endpoint_type}\",\n fg=typer.colors.YELLOW,\n )\n agent_state.llm_config.model_endpoint_type = model_endpoint_type\n\n # Update the agent with any overrides\n ms.update_agent(agent_state)\n\n # create agent\n memgpt_agent = Agent(agent_state, interface=interface)\n\n else: # create new agent\n # create new agent config: override defaults with args if provided\n typer.secho(\"\\n🧬 Creating new agent...\", fg=typer.colors.WHITE)\n\n if agent is None:\n # determine agent name\n # agent_count = len(ms.list_agents(user_id=user.id))\n # agent = f\"agent_{agent_count}\"\n agent = utils.create_random_username()\n\n llm_config = config.default_llm_config\n embedding_config = config.default_embedding_config # TODO allow overriding embedding params via CLI run\n\n # Allow overriding model specifics (model, model wrapper, model endpoint IP + type, context_window)\n if model and model != llm_config.model:\n typer.secho(f\"{CLI_WARNING_PREFIX}Overriding default model {llm_config.model} with {model}\", fg=typer.colors.YELLOW)\n llm_config.model = model\n if context_window is not None and int(context_window) != llm_config.context_window:\n typer.secho(\n f\"{CLI_WARNING_PREFIX}Overriding default context window {llm_config.context_window} with {context_window}\",\n fg=typer.colors.YELLOW,\n )\n llm_config.context_window = context_window\n if model_wrapper and model_wrapper != llm_config.model_wrapper:\n typer.secho(\n f\"{CLI_WARNING_PREFIX}Overriding existing model wrapper {llm_config.model_wrapper} with {model_wrapper}\",\n fg=typer.colors.YELLOW,\n )\n llm_config.model_wrapper = model_wrapper\n if model_endpoint and model_endpoint != llm_config.model_endpoint:\n typer.secho(\n f\"{CLI_WARNING_PREFIX}Overriding existing model endpoint {llm_config.model_endpoint} with {model_endpoint}\",\n fg=typer.colors.YELLOW,\n )\n llm_config.model_endpoint = model_endpoint\n if model_endpoint_type and model_endpoint_type != llm_config.model_endpoint_type:\n typer.secho(\n f\"{CLI_WARNING_PREFIX}Overriding existing model endpoint type {llm_config.model_endpoint_type} with {model_endpoint_type}\",\n fg=typer.colors.YELLOW,\n )\n llm_config.model_endpoint_type = model_endpoint_type\n\n agent_state = AgentState(\n name=agent,\n user_id=user.id,\n persona=persona if persona else user.default_persona,\n human=human if human else user.default_human,\n preset=preset if preset else user.default_preset,\n llm_config=llm_config,\n embedding_config=embedding_config,\n )\n ms.create_agent(agent_state)\n\n typer.secho(f\"-> 🤖 Using persona profile '{agent_state.persona}'\", fg=typer.colors.WHITE)\n typer.secho(f\"-> 🧑 Using human profile '{agent_state.human}'\", fg=typer.colors.WHITE)\n\n # Supress llama-index noise\n # TODO(swooders) add persistence manager code? or comment out?\n # with suppress_stdout():\n # TODO: allow configrable state manager (only local is supported right now)\n # persistence_manager = LocalStateManager(agent_config) # TODO: insert dataset/pre-fill\n\n # create agent\n try:\n memgpt_agent = presets.create_agent_from_preset(\n agent_state=agent_state,\n interface=interface,\n )\n except ValueError as e:\n # TODO(swooders) what's the equivalent cleanup code for the new DB refactor?\n typer.secho(f\"Failed to create agent from provided information:\\n{e}\", fg=typer.colors.RED)\n # # Delete the directory of the failed agent\n # try:\n # # Path to the specific file\n # agent_config_file = agent_config.agent_config_path\n\n # # Check if the file exists\n # if os.path.isfile(agent_config_file):\n # # Delete the file\n # os.remove(agent_config_file)\n\n # # Now, delete the directory along with any remaining files in it\n # agent_save_dir = os.path.join(MEMGPT_DIR, \"agents\", agent_config.name)\n # shutil.rmtree(agent_save_dir)\n # except:\n # typer.secho(f\"Failed to delete agent directory during cleanup:\\n{e}\", fg=typer.colors.RED)\n sys.exit(1)\n typer.secho(f\"🎉 Created new agent '{agent_state.name}'\", fg=typer.colors.GREEN)\n\n # pretty print agent config\n # printd(json.dumps(vars(agent_config), indent=4, sort_keys=True, ensure_ascii=JSON_ENSURE_ASCII))\n # printd(json.dumps(agent_init_state), indent=4, sort_keys=True, ensure_ascii=JSON_ENSURE_ASCII))\n\n # configure llama index\n original_stdout = sys.stdout # unfortunate hack required to suppress confusing print statements from llama index\n sys.stdout = io.StringIO()\n embed_model = embedding_model(config=agent_state.embedding_config, user_id=user.id)\n service_context = ServiceContext.from_defaults(\n llm=None, embed_model=embed_model, chunk_size=agent_state.embedding_config.embedding_chunk_size\n )\n set_global_service_context(service_context)\n sys.stdout = original_stdout\n\n # start event loop\n from memgpt.main import run_agent_loop\n\n print() # extra space\n run_agent_loop(memgpt_agent, config, first, ms, no_verify) # TODO: add back no_verify" }, { "identifier": "attach", "path": "memgpt/cli/cli.py", "snippet": "def attach(\n agent: str = typer.Option(help=\"Specify agent to attach data to\"),\n data_source: str = typer.Option(help=\"Data source to attach to avent\"),\n user_id: uuid.UUID = None,\n):\n # use client ID is no user_id provided\n config = MemGPTConfig.load()\n if user_id is None:\n user_id = uuid.UUID(config.anon_clientid)\n try:\n # loads the data contained in data source into the agent's memory\n from memgpt.agent_store.storage import StorageConnector, TableType\n from tqdm import tqdm\n\n ms = MetadataStore(config)\n agent = ms.get_agent(agent_name=agent, user_id=user_id)\n source = ms.get_source(source_name=data_source, user_id=user_id)\n assert source is not None, f\"Source {data_source} does not exist for user {user_id}\"\n\n # get storage connectors\n with suppress_stdout():\n source_storage = StorageConnector.get_storage_connector(TableType.PASSAGES, config, user_id=user_id)\n dest_storage = StorageConnector.get_storage_connector(TableType.ARCHIVAL_MEMORY, config, user_id=user_id, agent_id=agent.id)\n\n size = source_storage.size({\"data_source\": data_source})\n typer.secho(f\"Ingesting {size} passages into {agent.name}\", fg=typer.colors.GREEN)\n page_size = 100\n generator = source_storage.get_all_paginated(filters={\"data_source\": data_source}, page_size=page_size) # yields List[Passage]\n passages = []\n for i in tqdm(range(0, size, page_size)):\n passages = next(generator)\n print(\"inserting\", passages)\n\n # need to associated passage with agent (for filtering)\n for passage in passages:\n passage.agent_id = agent.id\n\n # insert into agent archival memory\n dest_storage.insert_many(passages)\n\n # save destination storage\n dest_storage.save()\n\n # attach to agent\n source_id = ms.get_source(source_name=data_source, user_id=user_id).id\n ms.attach_source(agent_id=agent.id, source_id=source_id, user_id=user_id)\n\n total_agent_passages = dest_storage.size()\n\n typer.secho(\n f\"Attached data source {data_source} to agent {agent}, consisting of {len(passages)}. Agent now has {total_agent_passages} embeddings in archival memory.\",\n fg=typer.colors.GREEN,\n )\n except KeyboardInterrupt:\n typer.secho(\"Operation interrupted by KeyboardInterrupt.\", fg=typer.colors.YELLOW)" }, { "identifier": "version", "path": "memgpt/cli/cli.py", "snippet": "def version():\n import memgpt\n\n print(memgpt.__version__)\n return memgpt.__version__" }, { "identifier": "server", "path": "memgpt/cli/cli.py", "snippet": "def server(\n type: ServerChoice = typer.Option(\"rest\", help=\"Server to run\"),\n port: int = typer.Option(None, help=\"Port to run the server on\"),\n host: str = typer.Option(None, help=\"Host to run the server on (default to localhost)\"),\n debug: bool = typer.Option(True, help=\"Turn debugging output on\"),\n):\n \"\"\"Launch a MemGPT server process\"\"\"\n\n if debug:\n from memgpt.server.server import logger as server_logger\n\n # Set the logging level\n server_logger.setLevel(logging.DEBUG)\n # Create a StreamHandler\n stream_handler = logging.StreamHandler()\n # Set the formatter (optional)\n formatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n stream_handler.setFormatter(formatter)\n # Add the handler to the logger\n server_logger.addHandler(stream_handler)\n\n if type == ServerChoice.rest_api:\n import uvicorn\n from memgpt.server.rest_api.server import app\n\n try:\n # Start the subprocess in a new session\n uvicorn.run(app, host=host or \"localhost\", port=port or REST_DEFAULT_PORT)\n\n except KeyboardInterrupt:\n # Handle CTRL-C\n print(\"Terminating the server...\")\n sys.exit(0)\n\n elif type == ServerChoice.ws_api:\n if port is None:\n port = WS_DEFAULT_PORT\n\n # Change to the desired directory\n script_path = Path(__file__).resolve()\n script_dir = script_path.parent\n\n server_directory = os.path.join(script_dir.parent, \"server\", \"ws_api\")\n command = f\"python server.py {port}\"\n\n # Run the command\n print(f\"Running WS (websockets) server: {command} (inside {server_directory})\")\n\n try:\n # Start the subprocess in a new session\n process = subprocess.Popen(command, shell=True, start_new_session=True, cwd=server_directory)\n process.wait()\n except KeyboardInterrupt:\n # Handle CTRL-C\n print(\"Terminating the server...\")\n process.terminate()\n try:\n process.wait(timeout=5)\n except subprocess.TimeoutExpired:\n process.kill()\n print(\"Server terminated with kill()\")\n sys.exit(0)" }, { "identifier": "open_folder", "path": "memgpt/cli/cli.py", "snippet": "def open_folder():\n \"\"\"Open a folder viewer of the MemGPT home directory\"\"\"\n try:\n print(f\"Opening home folder: {MEMGPT_DIR}\")\n open_folder_in_explorer(MEMGPT_DIR)\n except Exception as e:\n print(f\"Failed to open folder with system viewer, error:\\n{e}\")" }, { "identifier": "quickstart", "path": "memgpt/cli/cli.py", "snippet": "def quickstart(\n backend: QuickstartChoice = typer.Option(\"memgpt\", help=\"Quickstart setup backend\"),\n latest: bool = typer.Option(False, \"--latest\", help=\"Use --latest to pull the latest config from online\"),\n debug: bool = typer.Option(False, \"--debug\", help=\"Use --debug to enable debugging output\"),\n terminal: bool = True,\n):\n \"\"\"Set the base config file with a single command\"\"\"\n\n # setup logger\n utils.DEBUG = debug\n logging.getLogger().setLevel(logging.CRITICAL)\n if debug:\n logging.getLogger().setLevel(logging.DEBUG)\n\n # make sure everything is set up properly\n MemGPTConfig.create_config_dir()\n credentials = MemGPTCredentials.load()\n\n config_was_modified = False\n if backend == QuickstartChoice.memgpt_hosted:\n # if latest, try to pull the config from the repo\n # fallback to using local\n if latest:\n # Download the latest memgpt hosted config\n url = \"https://raw.githubusercontent.com/cpacker/MemGPT/main/memgpt/configs/memgpt_hosted.json\"\n response = requests.get(url)\n\n # Check if the request was successful\n if response.status_code == 200:\n # Parse the response content as JSON\n config = response.json()\n # Output a success message and the first few items in the dictionary as a sample\n printd(\"JSON config file downloaded successfully.\")\n config_was_modified = set_config_with_dict(config)\n else:\n typer.secho(f\"Failed to download config from {url}. Status code: {response.status_code}\", fg=typer.colors.RED)\n\n # Load the file from the relative path\n script_dir = os.path.dirname(__file__) # Get the directory where the script is located\n backup_config_path = os.path.join(script_dir, \"..\", \"configs\", \"memgpt_hosted.json\")\n try:\n with open(backup_config_path, \"r\") as file:\n backup_config = json.load(file)\n printd(\"Loaded backup config file successfully.\")\n config_was_modified = set_config_with_dict(backup_config)\n except FileNotFoundError:\n typer.secho(f\"Backup config file not found at {backup_config_path}\", fg=typer.colors.RED)\n return\n else:\n # Load the file from the relative path\n script_dir = os.path.dirname(__file__) # Get the directory where the script is located\n backup_config_path = os.path.join(script_dir, \"..\", \"configs\", \"memgpt_hosted.json\")\n try:\n with open(backup_config_path, \"r\") as file:\n backup_config = json.load(file)\n printd(\"Loaded config file successfully.\")\n config_was_modified = set_config_with_dict(backup_config)\n except FileNotFoundError:\n typer.secho(f\"Config file not found at {backup_config_path}\", fg=typer.colors.RED)\n return\n\n elif backend == QuickstartChoice.openai:\n # Make sure we have an API key\n api_key = os.getenv(\"OPENAI_API_KEY\")\n while api_key is None or len(api_key) == 0:\n # Ask for API key as input\n api_key = questionary.password(\"Enter your OpenAI API key (starts with 'sk-', see https://platform.openai.com/api-keys):\").ask()\n credentials.openai_key = api_key\n credentials.save()\n\n # if latest, try to pull the config from the repo\n # fallback to using local\n if latest:\n url = \"https://raw.githubusercontent.com/cpacker/MemGPT/main/memgpt/configs/openai.json\"\n response = requests.get(url)\n\n # Check if the request was successful\n if response.status_code == 200:\n # Parse the response content as JSON\n config = response.json()\n # Output a success message and the first few items in the dictionary as a sample\n print(\"JSON config file downloaded successfully.\")\n config_was_modified = set_config_with_dict(config)\n else:\n typer.secho(f\"Failed to download config from {url}. Status code: {response.status_code}\", fg=typer.colors.RED)\n\n # Load the file from the relative path\n script_dir = os.path.dirname(__file__) # Get the directory where the script is located\n backup_config_path = os.path.join(script_dir, \"..\", \"configs\", \"openai.json\")\n try:\n with open(backup_config_path, \"r\") as file:\n backup_config = json.load(file)\n printd(\"Loaded backup config file successfully.\")\n config_was_modified = set_config_with_dict(backup_config)\n except FileNotFoundError:\n typer.secho(f\"Backup config file not found at {backup_config_path}\", fg=typer.colors.RED)\n return\n else:\n # Load the file from the relative path\n script_dir = os.path.dirname(__file__) # Get the directory where the script is located\n backup_config_path = os.path.join(script_dir, \"..\", \"configs\", \"openai.json\")\n try:\n with open(backup_config_path, \"r\") as file:\n backup_config = json.load(file)\n printd(\"Loaded config file successfully.\")\n config_was_modified = set_config_with_dict(backup_config)\n except FileNotFoundError:\n typer.secho(f\"Config file not found at {backup_config_path}\", fg=typer.colors.RED)\n return\n\n else:\n raise NotImplementedError(backend)\n\n # 'terminal' = quickstart was run alone, in which case we should guide the user on the next command\n if terminal:\n if config_was_modified:\n typer.secho('⚡ Run \"memgpt run\" to create an agent with the new config.', fg=typer.colors.YELLOW)\n else:\n typer.secho('⚡ Run \"memgpt run\" to create an agent.', fg=typer.colors.YELLOW)" }, { "identifier": "migrate", "path": "memgpt/cli/cli.py", "snippet": "def migrate():\n \"\"\"Migrate old agents (pre 0.2.12) to the new database system\"\"\"\n migrate_all_agents()\n migrate_all_sources()" }, { "identifier": "configure", "path": "memgpt/cli/cli_config.py", "snippet": "@app.command()\ndef configure():\n \"\"\"Updates default MemGPT configurations\"\"\"\n\n # check credentials\n credentials = MemGPTCredentials.load()\n openai_key = get_openai_credentials()\n azure_creds = get_azure_credentials()\n\n MemGPTConfig.create_config_dir()\n\n # Will pre-populate with defaults, or what the user previously set\n config = MemGPTConfig.load()\n try:\n model_endpoint_type, model_endpoint = configure_llm_endpoint(\n config=config,\n credentials=credentials,\n )\n model, model_wrapper, context_window = configure_model(\n config=config,\n credentials=credentials,\n model_endpoint_type=model_endpoint_type,\n model_endpoint=model_endpoint,\n )\n embedding_endpoint_type, embedding_endpoint, embedding_dim, embedding_model = configure_embedding_endpoint(\n config=config,\n credentials=credentials,\n )\n default_preset, default_persona, default_human, default_agent = configure_cli(\n config=config,\n credentials=credentials,\n )\n archival_storage_type, archival_storage_uri, archival_storage_path = configure_archival_storage(\n config=config,\n credentials=credentials,\n )\n recall_storage_type, recall_storage_uri, recall_storage_path = configure_recall_storage(\n config=config,\n credentials=credentials,\n )\n except ValueError as e:\n typer.secho(str(e), fg=typer.colors.RED)\n return\n\n # openai key might have gotten added along the way\n openai_key = credentials.openai_key if credentials.openai_key is not None else openai_key\n\n # TODO: remove most of this (deplicated with User table)\n config = MemGPTConfig(\n default_llm_config=LLMConfig(\n model=model,\n model_endpoint=model_endpoint,\n model_endpoint_type=model_endpoint_type,\n model_wrapper=model_wrapper,\n context_window=context_window,\n ),\n default_embedding_config=EmbeddingConfig(\n embedding_endpoint_type=embedding_endpoint_type,\n embedding_endpoint=embedding_endpoint,\n embedding_dim=embedding_dim,\n embedding_model=embedding_model,\n ),\n # cli configs\n preset=default_preset,\n persona=default_persona,\n human=default_human,\n agent=default_agent,\n # storage\n archival_storage_type=archival_storage_type,\n archival_storage_uri=archival_storage_uri,\n archival_storage_path=archival_storage_path,\n # recall storage\n recall_storage_type=recall_storage_type,\n recall_storage_uri=recall_storage_uri,\n recall_storage_path=recall_storage_path,\n # metadata storage (currently forced to match recall storage)\n metadata_storage_type=recall_storage_type,\n metadata_storage_uri=recall_storage_uri,\n metadata_storage_path=recall_storage_path,\n )\n\n typer.secho(f\"📖 Saving config to {config.config_path}\", fg=typer.colors.GREEN)\n config.save()\n\n # create user records\n ms = MetadataStore(config)\n user_id = uuid.UUID(config.anon_clientid)\n user = User(\n id=uuid.UUID(config.anon_clientid),\n default_preset=default_preset,\n default_persona=default_persona,\n default_human=default_human,\n default_agent=default_agent,\n )\n if ms.get_user(user_id):\n # update user\n ms.update_user(user)\n else:\n ms.create_user(user)" }, { "identifier": "list", "path": "memgpt/cli/cli_config.py", "snippet": "@app.command()\ndef list(arg: Annotated[ListChoice, typer.Argument]):\n config = MemGPTConfig.load()\n ms = MetadataStore(config)\n user_id = uuid.UUID(config.anon_clientid)\n if arg == ListChoice.agents:\n \"\"\"List all agents\"\"\"\n table = PrettyTable()\n table.field_names = [\"Name\", \"Model\", \"Persona\", \"Human\", \"Data Source\", \"Create Time\"]\n for agent in tqdm(ms.list_agents(user_id=user_id)):\n source_ids = ms.list_attached_sources(agent_id=agent.id)\n source_names = [ms.get_source(source_id=source_id).name for source_id in source_ids]\n table.add_row(\n [\n agent.name,\n agent.llm_config.model,\n agent.persona,\n agent.human,\n \",\".join(source_names),\n utils.format_datetime(agent.created_at),\n ]\n )\n print(table)\n elif arg == ListChoice.humans:\n \"\"\"List all humans\"\"\"\n table = PrettyTable()\n table.field_names = [\"Name\", \"Text\"]\n for human_file in utils.list_human_files():\n text = open(human_file, \"r\").read()\n name = os.path.basename(human_file).replace(\"txt\", \"\")\n table.add_row([name, text])\n print(table)\n elif arg == ListChoice.personas:\n \"\"\"List all personas\"\"\"\n table = PrettyTable()\n table.field_names = [\"Name\", \"Text\"]\n for persona_file in utils.list_persona_files():\n print(persona_file)\n text = open(persona_file, \"r\").read()\n name = os.path.basename(persona_file).replace(\".txt\", \"\")\n table.add_row([name, text])\n print(table)\n elif arg == ListChoice.sources:\n \"\"\"List all data sources\"\"\"\n\n # create table\n table = PrettyTable()\n table.field_names = [\"Name\", \"Created At\", \"Agents\"]\n # TODO: eventually look accross all storage connections\n # TODO: add data source stats\n # TODO: connect to agents\n\n # get all sources\n for source in ms.list_sources(user_id=user_id):\n # get attached agents\n agent_ids = ms.list_attached_agents(source_id=source.id)\n agent_names = [ms.get_agent(agent_id=agent_id).name for agent_id in agent_ids]\n\n table.add_row([source.name, utils.format_datetime(source.created_at), \",\".join(agent_names)])\n\n print(table)\n else:\n raise ValueError(f\"Unknown argument {arg}\")" }, { "identifier": "add", "path": "memgpt/cli/cli_config.py", "snippet": "@app.command()\ndef add(\n option: str, # [human, persona]\n name: str = typer.Option(help=\"Name of human/persona\"),\n text: str = typer.Option(None, help=\"Text of human/persona\"),\n filename: str = typer.Option(None, \"-f\", help=\"Specify filename\"),\n):\n \"\"\"Add a person/human\"\"\"\n\n if option == \"persona\":\n directory = os.path.join(MEMGPT_DIR, \"personas\")\n elif option == \"human\":\n directory = os.path.join(MEMGPT_DIR, \"humans\")\n else:\n raise ValueError(f\"Unknown kind {option}\")\n\n if filename:\n assert text is None, f\"Cannot provide both filename and text\"\n # copy file to directory\n shutil.copyfile(filename, os.path.join(directory, name))\n if text:\n assert filename is None, f\"Cannot provide both filename and text\"\n # write text to file\n with open(os.path.join(directory, name), \"w\") as f:\n f.write(text)" }, { "identifier": "delete", "path": "memgpt/cli/cli_config.py", "snippet": "@app.command()\ndef delete(option: str, name: str):\n \"\"\"Delete a source from the archival memory.\"\"\"\n\n config = MemGPTConfig.load()\n user_id = uuid.UUID(config.anon_clientid)\n ms = MetadataStore(config)\n assert ms.get_user(user_id=user_id), f\"User {user_id} does not exist\"\n\n try:\n # delete from metadata\n if option == \"source\":\n # delete metadata\n source = ms.get_source(source_name=name, user_id=user_id)\n ms.delete_source(source_id=source.id)\n\n # delete from passages\n conn = StorageConnector.get_storage_connector(TableType.PASSAGES, config, user_id=user_id)\n conn.delete({\"data_source\": name})\n\n assert (\n conn.get_all({\"data_source\": name}) == []\n ), f\"Expected no passages with source {name}, but got {conn.get_all({'data_source': name})}\"\n\n # TODO: should we also delete from agents?\n elif option == \"agent\":\n agent = ms.get_agent(agent_name=name, user_id=user_id)\n\n # recall memory\n recall_conn = StorageConnector.get_storage_connector(TableType.RECALL_MEMORY, config, user_id=user_id, agent_id=agent.id)\n recall_conn.delete({\"agent_id\": agent.id})\n\n # archival memory\n archival_conn = StorageConnector.get_storage_connector(TableType.ARCHIVAL_MEMORY, config, user_id=user_id, agent_id=agent.id)\n archival_conn.delete({\"agent_id\": agent.id})\n\n # metadata\n ms.delete_agent(agent_id=agent.id)\n\n else:\n raise ValueError(f\"Option {option} not implemented\")\n\n typer.secho(f\"Deleted source '{name}'\", fg=typer.colors.GREEN)\n\n except Exception as e:\n typer.secho(f\"Failed to deleted source '{name}'\\n{e}\", fg=typer.colors.RED)" }, { "identifier": "app", "path": "memgpt/cli/cli_load.py", "snippet": "def insert_passages_into_source(passages: List[Passage], source_name: str, user_id: uuid.UUID, config: MemGPTConfig):\ndef insert_passages_into_source(passages: List[Passage], source_name: str, user_id: uuid.UUID, config: MemGPTConfig):\ndef store_docs(name, docs, user_id=None, show_progress=True):\ndef load_index(\n name: str = typer.Option(help=\"Name of dataset to load.\"),\n dir: str = typer.Option(help=\"Path to directory containing index.\"),\n user_id: uuid.UUID = None,\n):\ndef load_directory(\n name: str = typer.Option(help=\"Name of dataset to load.\"),\n input_dir: str = typer.Option(None, help=\"Path to directory containing dataset.\"),\n input_files: List[str] = typer.Option(None, help=\"List of paths to files containing dataset.\"),\n recursive: bool = typer.Option(False, help=\"Recursively search for files in directory.\"),\n extensions: str = typer.Option(default_extensions, help=\"Comma separated list of file extensions to load\"),\n user_id: str = typer.Option(None, help=\"User ID to associate with dataset.\"),\n):\ndef load_webpage(\n name: str = typer.Option(help=\"Name of dataset to load.\"),\n urls: List[str] = typer.Option(None, help=\"List of urls to load.\"),\n):\ndef load_database(\n name: str = typer.Option(help=\"Name of dataset to load.\"),\n query: str = typer.Option(help=\"Database query.\"),\n dump_path: str = typer.Option(None, help=\"Path to dump file.\"),\n scheme: str = typer.Option(None, help=\"Database scheme.\"),\n host: str = typer.Option(None, help=\"Database host.\"),\n port: int = typer.Option(None, help=\"Database port.\"),\n user: str = typer.Option(None, help=\"Database user.\"),\n password: str = typer.Option(None, help=\"Database password.\"),\n dbname: str = typer.Option(None, help=\"Database name.\"),\n):\ndef load_vector_database(\n name: str = typer.Option(help=\"Name of dataset to load.\"),\n uri: str = typer.Option(help=\"Database URI.\"),\n table_name: str = typer.Option(help=\"Name of table containing data.\"),\n text_column: str = typer.Option(help=\"Name of column containing text.\"),\n embedding_column: str = typer.Option(help=\"Name of column containing embedding.\"),\n user_id: uuid.UUID = None,\n):" }, { "identifier": "StorageConnector", "path": "memgpt/agent_store/storage.py", "snippet": "class StorageConnector:\n \"\"\"Defines a DB connection that is user-specific to access data: Documents, Passages, Archival/Recall Memory\"\"\"\n\n def __init__(self, table_type: TableType, config: MemGPTConfig, user_id, agent_id=None):\n self.user_id = user_id\n self.agent_id = agent_id\n self.table_type = table_type\n\n # get object type\n if table_type == TableType.ARCHIVAL_MEMORY:\n self.type = Passage\n self.table_name = ARCHIVAL_TABLE_NAME\n elif table_type == TableType.RECALL_MEMORY:\n self.type = Message\n self.table_name = RECALL_TABLE_NAME\n elif table_type == TableType.DOCUMENTS:\n self.type = Document\n self.table_name == DOCUMENT_TABLE_NAME\n elif table_type == TableType.PASSAGES:\n self.type = Passage\n self.table_name = PASSAGE_TABLE_NAME\n else:\n raise ValueError(f\"Table type {table_type} not implemented\")\n printd(f\"Using table name {self.table_name}\")\n\n # setup base filters for agent-specific tables\n if self.table_type == TableType.ARCHIVAL_MEMORY or self.table_type == TableType.RECALL_MEMORY:\n # agent-specific table\n assert agent_id is not None, \"Agent ID must be provided for agent-specific tables\"\n self.filters = {\"user_id\": self.user_id, \"agent_id\": self.agent_id}\n elif self.table_type == TableType.PASSAGES or self.table_type == TableType.DOCUMENTS:\n # setup base filters for user-specific tables\n assert agent_id is None, \"Agent ID must not be provided for user-specific tables\"\n self.filters = {\"user_id\": self.user_id}\n else:\n raise ValueError(f\"Table type {table_type} not implemented\")\n\n def get_filters(self, filters: Optional[Dict] = {}):\n # get all filters for query\n if filters is not None:\n filter_conditions = {**self.filters, **filters}\n else:\n filter_conditions = self.filters\n return filter_conditions\n\n @staticmethod\n def get_storage_connector(table_type: TableType, config: MemGPTConfig, user_id, agent_id=None):\n if table_type == TableType.ARCHIVAL_MEMORY or table_type == TableType.PASSAGES:\n storage_type = config.archival_storage_type\n elif table_type == TableType.RECALL_MEMORY:\n storage_type = config.recall_storage_type\n else:\n raise ValueError(f\"Table type {table_type} not implemented\")\n\n if storage_type == \"postgres\":\n from memgpt.agent_store.db import PostgresStorageConnector\n\n return PostgresStorageConnector(table_type, config, user_id, agent_id)\n elif storage_type == \"chroma\":\n from memgpt.agent_store.chroma import ChromaStorageConnector\n\n return ChromaStorageConnector(table_type, config, user_id, agent_id)\n\n # TODO: add back\n # elif storage_type == \"lancedb\":\n # from memgpt.agent_store.db import LanceDBConnector\n\n # return LanceDBConnector(agent_config=agent_config, table_type=table_type)\n\n elif storage_type == \"sqlite\":\n from memgpt.agent_store.db import SQLLiteStorageConnector\n\n return SQLLiteStorageConnector(table_type, config, user_id, agent_id)\n\n else:\n raise NotImplementedError(f\"Storage type {storage_type} not implemented\")\n\n @staticmethod\n def get_archival_storage_connector(user_id, agent_id):\n config = MemGPTConfig.load()\n return StorageConnector.get_storage_connector(TableType.ARCHIVAL_MEMORY, config, user_id, agent_id)\n\n @staticmethod\n def get_recall_storage_connector(user_id, agent_id):\n config = MemGPTConfig.load()\n return StorageConnector.get_storage_connector(TableType.RECALL_MEMORY, config, user_id, agent_id)\n\n @abstractmethod\n def get_filters(self, filters: Optional[Dict] = {}):\n pass\n\n @abstractmethod\n def get_all_paginated(self, filters: Optional[Dict] = {}, page_size: Optional[int] = 1000) -> Iterator[List[Record]]:\n pass\n\n @abstractmethod\n def get_all(self, filters: Optional[Dict] = {}, limit=10) -> List[Record]:\n pass\n\n @abstractmethod\n def get(self, id: str) -> Optional[Record]:\n pass\n\n @abstractmethod\n def size(self, filters: Optional[Dict] = {}) -> int:\n pass\n\n @abstractmethod\n def insert(self, record: Record):\n pass\n\n @abstractmethod\n def insert_many(self, records: List[Record], show_progress=False):\n pass\n\n @abstractmethod\n def query(self, query: str, query_vec: List[float], top_k: int = 10, filters: Optional[Dict] = {}) -> List[Record]:\n pass\n\n @abstractmethod\n def query_date(self, start_date, end_date):\n pass\n\n @abstractmethod\n def query_text(self, query):\n pass\n\n @abstractmethod\n def delete_table(self):\n pass\n\n @abstractmethod\n def delete(self, filters: Optional[Dict] = {}):\n pass\n\n @abstractmethod\n def save(self):\n pass" }, { "identifier": "TableType", "path": "memgpt/agent_store/storage.py", "snippet": "class TableType:\n ARCHIVAL_MEMORY = \"archival_memory\" # recall memory table: memgpt_agent_{agent_id}\n RECALL_MEMORY = \"recall_memory\" # archival memory table: memgpt_agent_recall_{agent_id}\n PASSAGES = \"passages\" # TODO\n DOCUMENTS = \"documents\" # TODO" }, { "identifier": "MetadataStore", "path": "memgpt/metadata.py", "snippet": "class MetadataStore:\n def __init__(self, config: MemGPTConfig):\n # TODO: get DB URI or path\n if config.metadata_storage_type == \"postgres\":\n self.uri = config.metadata_storage_uri\n elif config.metadata_storage_type == \"sqlite\":\n path = os.path.join(config.metadata_storage_path, \"sqlite.db\")\n self.uri = f\"sqlite:///{path}\"\n else:\n raise ValueError(f\"Invalid metadata storage type: {config.metadata_storage_type}\")\n\n # TODO: check to see if table(s) need to be greated or not\n\n self.engine = create_engine(self.uri)\n Base.metadata.create_all(\n self.engine, tables=[UserModel.__table__, AgentModel.__table__, SourceModel.__table__, AgentSourceMappingModel.__table__]\n )\n session_maker = sessionmaker(bind=self.engine)\n self.session = session_maker()\n\n @enforce_types\n def create_agent(self, agent: AgentState):\n # insert into agent table\n # make sure agent.name does not already exist for user user_id\n if self.session.query(AgentModel).filter(AgentModel.name == agent.name).filter(AgentModel.user_id == agent.user_id).count() > 0:\n raise ValueError(f\"Agent with name {agent.name} already exists\")\n self.session.add(AgentModel(**vars(agent)))\n self.session.commit()\n\n @enforce_types\n def create_source(self, source: Source):\n # make sure source.name does not already exist for user\n if (\n self.session.query(SourceModel).filter(SourceModel.name == source.name).filter(SourceModel.user_id == source.user_id).count()\n > 0\n ):\n raise ValueError(f\"Source with name {source.name} already exists\")\n self.session.add(SourceModel(**vars(source)))\n self.session.commit()\n\n @enforce_types\n def create_user(self, user: User):\n if self.session.query(UserModel).filter(UserModel.id == user.id).count() > 0:\n raise ValueError(f\"User with id {user.id} already exists\")\n self.session.add(UserModel(**vars(user)))\n self.session.commit()\n\n @enforce_types\n def update_agent(self, agent: AgentState):\n self.session.query(AgentModel).filter(AgentModel.id == agent.id).update(vars(agent))\n self.session.commit()\n\n @enforce_types\n def update_user(self, user: User):\n self.session.query(UserModel).filter(UserModel.id == user.id).update(vars(user))\n self.session.commit()\n\n @enforce_types\n def update_source(self, source: Source):\n self.session.query(SourceModel).filter(SourceModel.id == source.id).update(vars(source))\n self.session.commit()\n\n @enforce_types\n def delete_agent(self, agent_id: uuid.UUID):\n self.session.query(AgentModel).filter(AgentModel.id == agent_id).delete()\n self.session.commit()\n\n @enforce_types\n def delete_source(self, source_id: uuid.UUID):\n # delete from sources table\n self.session.query(SourceModel).filter(SourceModel.id == source_id).delete()\n\n # delete any mappings\n self.session.query(AgentSourceMappingModel).filter(AgentSourceMappingModel.source_id == source_id).delete()\n\n self.session.commit()\n\n @enforce_types\n def delete_user(self, user_id: uuid.UUID):\n # delete from users table\n self.session.query(UserModel).filter(UserModel.id == user_id).delete()\n\n # delete associated agents\n self.session.query(AgentModel).filter(AgentModel.user_id == user_id).delete()\n\n # delete associated sources\n self.session.query(SourceModel).filter(SourceModel.user_id == user_id).delete()\n\n # delete associated mappings\n self.session.query(AgentSourceMappingModel).filter(AgentSourceMappingModel.user_id == user_id).delete()\n\n self.session.commit()\n\n @enforce_types\n def list_agents(self, user_id: uuid.UUID) -> List[AgentState]:\n results = self.session.query(AgentModel).filter(AgentModel.user_id == user_id).all()\n return [r.to_record() for r in results]\n\n @enforce_types\n def list_sources(self, user_id: uuid.UUID) -> List[Source]:\n results = self.session.query(SourceModel).filter(SourceModel.user_id == user_id).all()\n return [r.to_record() for r in results]\n\n @enforce_types\n def get_agent(\n self, agent_id: Optional[uuid.UUID] = None, agent_name: Optional[str] = None, user_id: Optional[uuid.UUID] = None\n ) -> Optional[AgentState]:\n if agent_id:\n results = self.session.query(AgentModel).filter(AgentModel.id == agent_id).all()\n else:\n assert agent_name is not None and user_id is not None, \"Must provide either agent_id or agent_name\"\n results = self.session.query(AgentModel).filter(AgentModel.name == agent_name).filter(AgentModel.user_id == user_id).all()\n\n if len(results) == 0:\n return None\n assert len(results) == 1, f\"Expected 1 result, got {len(results)}\" # should only be one result\n return results[0].to_record()\n\n @enforce_types\n def get_user(self, user_id: uuid.UUID) -> Optional[User]:\n results = self.session.query(UserModel).filter(UserModel.id == user_id).all()\n if len(results) == 0:\n return None\n assert len(results) == 1, f\"Expected 1 result, got {len(results)}\"\n return results[0].to_record()\n\n @enforce_types\n def get_source(\n self, source_id: Optional[uuid.UUID] = None, user_id: Optional[uuid.UUID] = None, source_name: Optional[str] = None\n ) -> Optional[Source]:\n if source_id:\n results = self.session.query(SourceModel).filter(SourceModel.id == source_id).all()\n else:\n assert user_id is not None and source_name is not None\n results = self.session.query(SourceModel).filter(SourceModel.name == source_name).filter(SourceModel.user_id == user_id).all()\n if len(results) == 0:\n return None\n assert len(results) == 1, f\"Expected 1 result, got {len(results)}\"\n return results[0].to_record()\n\n # agent source metadata\n @enforce_types\n def attach_source(self, user_id: uuid.UUID, agent_id: uuid.UUID, source_id: uuid.UUID):\n self.session.add(AgentSourceMappingModel(user_id=user_id, agent_id=agent_id, source_id=source_id))\n self.session.commit()\n\n @enforce_types\n def list_attached_sources(self, agent_id: uuid.UUID) -> List[Column]:\n results = self.session.query(AgentSourceMappingModel).filter(AgentSourceMappingModel.agent_id == agent_id).all()\n return [r.source_id for r in results]\n\n @enforce_types\n def list_attached_agents(self, source_id: uuid.UUID):\n results = self.session.query(AgentSourceMappingModel).filter(AgentSourceMappingModel.source_id == source_id).all()\n return [r.agent_id for r in results]\n\n @enforce_types\n def detach_source(self, agent_id: uuid.UUID, source_id: uuid.UUID):\n self.session.query(AgentSourceMappingModel).filter(\n AgentSourceMappingModel.agent_id == agent_id, AgentSourceMappingModel.source_id == source_id\n ).delete()\n self.session.commit()" }, { "identifier": "save_agent", "path": "memgpt/metadata.py", "snippet": "def save_agent(agent: Agent, ms: MetadataStore):\n \"\"\"Save agent to metadata store\"\"\"\n\n agent.update_state()\n agent_state = agent.agent_state\n\n if ms.get_agent(agent_id=agent_state.id):\n ms.update_agent(agent_state)\n else:\n ms.create_agent(agent_state)" } ]
import shutil import configparser import uuid import logging import glob import os import sys import pickle import traceback import json import questionary import typer import memgpt.agent as agent import memgpt.system as system import memgpt.constants as constants import memgpt.errors as errors from rich.console import Console from prettytable import PrettyTable from memgpt.log import logger from memgpt.interface import CLIInterface as interface # for printing to terminal from memgpt.config import MemGPTConfig from memgpt.cli.cli import run, attach, version, server, open_folder, quickstart, migrate from memgpt.cli.cli_config import configure, list, add, delete from memgpt.cli.cli_load import app as load_app from memgpt.agent_store.storage import StorageConnector, TableType from memgpt.metadata import MetadataStore, save_agent
17,433
console = Console() app = typer.Typer(pretty_exceptions_enable=False) app.command(name="run")(run) app.command(name="version")(version) app.command(name="attach")(attach) app.command(name="configure")(configure) app.command(name="list")(list) app.command(name="add")(add) app.command(name="delete")(delete)
console = Console() app = typer.Typer(pretty_exceptions_enable=False) app.command(name="run")(run) app.command(name="version")(version) app.command(name="attach")(attach) app.command(name="configure")(configure) app.command(name="list")(list) app.command(name="add")(add) app.command(name="delete")(delete)
app.command(name="server")(server)
6
2023-10-11 07:38:37+00:00
24k
PixArt-alpha/PixArt-alpha
train_scripts/train_pixart_lcm.py
[ { "identifier": "IDDPM", "path": "diffusion/iddpm.py", "snippet": "def IDDPM(\n timestep_respacing,\n noise_schedule=\"linear\",\n use_kl=False,\n sigma_small=False,\n predict_xstart=False,\n learn_sigma=True,\n pred_sigma=True,\n rescale_learned_sigmas=False,\n diffusion_steps=1000,\n snr=False,\n return_startx=False,\n):\n betas = gd.get_named_beta_schedule(noise_schedule, diffusion_steps)\n if use_kl:\n loss_type = gd.LossType.RESCALED_KL\n elif rescale_learned_sigmas:\n loss_type = gd.LossType.RESCALED_MSE\n else:\n loss_type = gd.LossType.MSE\n if timestep_respacing is None or timestep_respacing == \"\":\n timestep_respacing = [diffusion_steps]\n return SpacedDiffusion(\n use_timesteps=space_timesteps(diffusion_steps, timestep_respacing),\n betas=betas,\n model_mean_type=(\n gd.ModelMeanType.EPSILON if not predict_xstart else gd.ModelMeanType.START_X\n ),\n model_var_type=(\n ((\n gd.ModelVarType.FIXED_LARGE\n if not sigma_small\n else gd.ModelVarType.FIXED_SMALL\n )\n if not learn_sigma\n else gd.ModelVarType.LEARNED_RANGE\n )\n if pred_sigma\n else None\n ),\n loss_type=loss_type,\n snr=snr,\n return_startx=return_startx,\n # rescale_timesteps=rescale_timesteps,\n )" }, { "identifier": "save_checkpoint", "path": "diffusion/utils/checkpoint.py", "snippet": "def save_checkpoint(work_dir,\n epoch,\n model,\n model_ema=None,\n optimizer=None,\n lr_scheduler=None,\n keep_last=False,\n step=None,\n ):\n os.makedirs(work_dir, exist_ok=True)\n state_dict = dict(state_dict=model.state_dict())\n if model_ema is not None:\n state_dict['state_dict_ema'] = model_ema.state_dict()\n if optimizer is not None:\n state_dict['optimizer'] = optimizer.state_dict()\n if lr_scheduler is not None:\n state_dict['scheduler'] = lr_scheduler.state_dict()\n if epoch is not None:\n state_dict['epoch'] = epoch\n file_path = os.path.join(work_dir, f\"epoch_{epoch}.pth\")\n if step is not None:\n file_path = file_path.split('.pth')[0] + f\"_step_{step}.pth\"\n logger = get_root_logger()\n torch.save(state_dict, file_path)\n logger.info(f'Saved checkpoint of epoch {epoch} to {file_path.format(epoch)}.')\n if keep_last:\n for i in range(epoch):\n previous_ckgt = file_path.format(i)\n if os.path.exists(previous_ckgt):\n os.remove(previous_ckgt)" }, { "identifier": "load_checkpoint", "path": "diffusion/utils/checkpoint.py", "snippet": "def load_checkpoint(checkpoint,\n model,\n model_ema=None,\n optimizer=None,\n lr_scheduler=None,\n load_ema=False,\n resume_optimizer=True,\n resume_lr_scheduler=True\n ):\n assert isinstance(checkpoint, str)\n ckpt_file = checkpoint\n checkpoint = torch.load(ckpt_file, map_location=\"cpu\")\n\n state_dict_keys = ['pos_embed', 'base_model.pos_embed', 'model.pos_embed']\n for key in state_dict_keys:\n if key in checkpoint['state_dict']:\n del checkpoint['state_dict'][key]\n if 'state_dict_ema' in checkpoint and key in checkpoint['state_dict_ema']:\n del checkpoint['state_dict_ema'][key]\n break\n\n if load_ema:\n state_dict = checkpoint['state_dict_ema']\n else:\n state_dict = checkpoint.get('state_dict', checkpoint) # to be compatible with the official checkpoint\n # model.load_state_dict(state_dict)\n missing, unexpect = model.load_state_dict(state_dict, strict=False)\n if model_ema is not None:\n model_ema.load_state_dict(checkpoint['state_dict_ema'], strict=False)\n if optimizer is not None and resume_optimizer:\n optimizer.load_state_dict(checkpoint['optimizer'])\n if lr_scheduler is not None and resume_lr_scheduler:\n lr_scheduler.load_state_dict(checkpoint['scheduler'])\n logger = get_root_logger()\n if optimizer is not None:\n epoch = checkpoint.get('epoch', re.match(r'.*epoch_(\\d*).*.pth', ckpt_file).group()[0])\n logger.info(f'Resume checkpoint of epoch {epoch} from {ckpt_file}. Load ema: {load_ema}, '\n f'resume optimizer: {resume_optimizer}, resume lr scheduler: {resume_lr_scheduler}.')\n return epoch, missing, unexpect\n logger.info(f'Load checkpoint from {ckpt_file}. Load ema: {load_ema}.')\n return missing, unexpect" }, { "identifier": "synchronize", "path": "diffusion/utils/dist_utils.py", "snippet": "def synchronize():\n \"\"\"\n Helper function to synchronize (barrier) among all processes when\n using distributed training\n \"\"\"\n if not dist.is_available():\n return\n if not dist.is_initialized():\n return\n world_size = dist.get_world_size()\n if world_size == 1:\n return\n dist.barrier()" }, { "identifier": "get_world_size", "path": "diffusion/utils/dist_utils.py", "snippet": "def get_world_size():\n if not dist.is_available():\n return 1\n if not dist.is_initialized():\n return 1\n return dist.get_world_size()" }, { "identifier": "clip_grad_norm_", "path": "diffusion/utils/dist_utils.py", "snippet": "@torch.no_grad()\ndef clip_grad_norm_(\n self, max_norm: Union[float, int], norm_type: Union[float, int] = 2.0\n) -> None:\n self._lazy_init()\n self._wait_for_previous_optim_step()\n assert self._is_root, \"clip_grad_norm should only be called on the root (parent) instance\"\n self._assert_state(TrainingState_.IDLE)\n\n max_norm = float(max_norm)\n norm_type = float(norm_type)\n # Computes the max norm for this shard's gradients and sync's across workers\n local_norm = _calc_grad_norm(self.params_with_grad, norm_type).cuda() # type: ignore[arg-type]\n if norm_type == math.inf:\n total_norm = local_norm\n dist.all_reduce(total_norm, op=torch.distributed.ReduceOp.MAX, group=self.process_group)\n else:\n total_norm = local_norm ** norm_type\n dist.all_reduce(total_norm, group=self.process_group)\n total_norm = total_norm ** (1.0 / norm_type)\n\n clip_coef = torch.tensor(max_norm, dtype=total_norm.dtype, device=total_norm.device) / (total_norm + 1e-6)\n if clip_coef < 1:\n # multiply by clip_coef, aka, (max_norm/total_norm).\n for p in self.params_with_grad:\n assert p.grad is not None\n p.grad.detach().mul_(clip_coef.to(p.grad.device))\n return total_norm" }, { "identifier": "build_dataset", "path": "diffusion/data/builder.py", "snippet": "def build_dataset(cfg, resolution=224, **kwargs):\n logger = get_root_logger()\n\n dataset_type = cfg.get('type')\n logger.info(f\"Constructing dataset {dataset_type}...\")\n t = time.time()\n transform = cfg.pop('transform', 'default_train')\n transform = get_transform(transform, resolution)\n dataset = build_from_cfg(cfg, DATASETS, default_args=dict(transform=transform, resolution=resolution, **kwargs))\n logger.info(f\"Dataset {dataset_type} constructed. time: {(time.time() - t):.2f} s, length (use/ori): {len(dataset)}/{dataset.ori_imgs_nums}\")\n return dataset" }, { "identifier": "build_dataloader", "path": "diffusion/data/builder.py", "snippet": "def build_dataloader(dataset, batch_size=256, num_workers=4, shuffle=True, **kwargs):\n if 'batch_sampler' in kwargs:\n dataloader = DataLoader(dataset, batch_sampler=kwargs['batch_sampler'], num_workers=num_workers, pin_memory=True)\n else:\n dataloader = DataLoader(dataset,\n batch_size=batch_size,\n shuffle=shuffle,\n num_workers=num_workers,\n pin_memory=True,\n **kwargs)\n return dataloader" }, { "identifier": "set_data_root", "path": "diffusion/data/builder.py", "snippet": "def set_data_root(data_root):\n global DATA_ROOT\n DATA_ROOT = data_root" }, { "identifier": "build_model", "path": "diffusion/model/builder.py", "snippet": "def build_model(cfg, use_grad_checkpoint=False, use_fp32_attention=False, gc_step=1, **kwargs):\n if isinstance(cfg, str):\n cfg = dict(type=cfg)\n model = MODELS.build(cfg, default_args=kwargs)\n if use_grad_checkpoint:\n set_grad_checkpoint(model, use_fp32_attention=use_fp32_attention, gc_step=gc_step)\n return model" }, { "identifier": "get_root_logger", "path": "diffusion/utils/logger.py", "snippet": "def get_root_logger(log_file=None, log_level=logging.INFO, name='PixArt'):\n \"\"\"Get root logger.\n\n Args:\n log_file (str, optional): File path of log. Defaults to None.\n log_level (int, optional): The level of logger.\n Defaults to logging.INFO.\n name (str): logger name\n Returns:\n :obj:`logging.Logger`: The obtained logger\n \"\"\"\n if log_file is None:\n log_file = '/dev/null'\n logger = get_logger(name=name, log_file=log_file, log_level=log_level)\n return logger" }, { "identifier": "set_random_seed", "path": "diffusion/utils/misc.py", "snippet": "def set_random_seed(seed, deterministic=False):\n \"\"\"Set random seed.\n\n Args:\n seed (int): Seed to be used.\n deterministic (bool): Whether to set the deterministic option for\n CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`\n to True and `torch.backends.cudnn.benchmark` to False.\n Default: False.\n \"\"\"\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n if deterministic:\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False" }, { "identifier": "read_config", "path": "diffusion/utils/misc.py", "snippet": "def read_config(file):\n # solve config loading conflict when multi-processes\n import time\n while True:\n config = Config.fromfile(file)\n if len(config) == 0:\n time.sleep(0.1)\n continue\n break\n return config" }, { "identifier": "init_random_seed", "path": "diffusion/utils/misc.py", "snippet": "def init_random_seed(seed=None, device='cuda'):\n \"\"\"Initialize random seed.\n\n If the seed is not set, the seed will be automatically randomized,\n and then broadcast to all processes to prevent some potential bugs.\n\n Args:\n seed (int, Optional): The seed. Default to None.\n device (str): The device where the seed will be put on.\n Default to 'cuda'.\n\n Returns:\n int: Seed to be used.\n \"\"\"\n if seed is not None:\n return seed\n\n # Make sure all ranks share the same random seed to prevent\n # some potential bugs. Please refer to\n # https://github.com/open-mmlab/mmdetection/issues/6339\n rank, world_size = get_dist_info()\n seed = np.random.randint(2 ** 31)\n if world_size == 1:\n return seed\n\n if rank == 0:\n random_num = torch.tensor(seed, dtype=torch.int32, device=device)\n else:\n random_num = torch.tensor(0, dtype=torch.int32, device=device)\n dist.broadcast(random_num, src=0)\n return random_num.item()" }, { "identifier": "DebugUnderflowOverflow", "path": "diffusion/utils/misc.py", "snippet": "class DebugUnderflowOverflow:\n \"\"\"\n This debug class helps detect and understand where the model starts getting very large or very small, and more\n importantly `nan` or `inf` weight and activation elements.\n There are 2 working modes:\n 1. Underflow/overflow detection (default)\n 2. Specific batch absolute min/max tracing without detection\n Mode 1: Underflow/overflow detection\n To activate the underflow/overflow detection, initialize the object with the model :\n ```python\n debug_overflow = DebugUnderflowOverflow(model)\n ```\n then run the training as normal and if `nan` or `inf` gets detected in at least one of the weight, input or\n output elements this module will throw an exception and will print `max_frames_to_save` frames that lead to this\n event, each frame reporting\n 1. the fully qualified module name plus the class name whose `forward` was run\n 2. the absolute min and max value of all elements for each module weights, and the inputs and output\n For example, here is the header and the last few frames in detection report for `google/mt5-small` run in fp16 mixed precision :\n ```\n Detected inf/nan during batch_number=0\n Last 21 forward frames:\n abs min abs max metadata\n [...]\n encoder.block.2.layer.1.DenseReluDense.wi_0 Linear\n 2.17e-07 4.50e+00 weight\n 1.79e-06 4.65e+00 input[0]\n 2.68e-06 3.70e+01 output\n encoder.block.2.layer.1.DenseReluDense.wi_1 Linear\n 8.08e-07 2.66e+01 weight\n 1.79e-06 4.65e+00 input[0]\n 1.27e-04 2.37e+02 output\n encoder.block.2.layer.1.DenseReluDense.wo Linear\n 1.01e-06 6.44e+00 weight\n 0.00e+00 9.74e+03 input[0]\n 3.18e-04 6.27e+04 output\n encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense\n 1.79e-06 4.65e+00 input[0]\n 3.18e-04 6.27e+04 output\n encoder.block.2.layer.1.dropout Dropout\n 3.18e-04 6.27e+04 input[0]\n 0.00e+00 inf output\n ```\n You can see here, that `T5DenseGatedGeluDense.forward` resulted in output activations, whose absolute max value\n was around 62.7K, which is very close to fp16's top limit of 64K. In the next frame we have `Dropout` which\n renormalizes the weights, after it zeroed some of the elements, which pushes the absolute max value to more than\n 64K, and we get an overlow.\n As you can see it's the previous frames that we need to look into when the numbers start going into very large for\n fp16 numbers.\n The tracking is done in a forward hook, which gets invoked immediately after `forward` has completed.\n By default the last 21 frames are printed. You can change the default to adjust for your needs. For example :\n ```python\n debug_overflow = DebugUnderflowOverflow(model, max_frames_to_save=100)\n ```\n To validate that you have set up this debugging feature correctly, and you intend to use it in a training that may\n take hours to complete, first run it with normal tracing enabled for one of a few batches as explained in the next\n section.\n Mode 2. Specific batch absolute min/max tracing without detection\n The second work mode is per-batch tracing with the underflow/overflow detection feature turned off.\n Let's say you want to watch the absolute min and max values for all the ingredients of each `forward` call of a\n given batch, and only do that for batches 1 and 3. Then you instantiate this class as :\n ```python\n debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1,3])\n ```\n And now full batches 1 and 3 will be traced using the same format as explained above. Batches are 0-indexed.\n This is helpful if you know that the program starts misbehaving after a certain batch number, so you can\n fast-forward right to that area.\n Early stopping:\n You can also specify the batch number after which to stop the training, with :\n ```python\n debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1,3], abort_after_batch_num=3)\n ```\n This feature is mainly useful in the tracing mode, but you can use it for any mode.\n **Performance**:\n As this module measures absolute `min`/``max` of each weight of the model on every forward it'll slow the\n training down. Therefore remember to turn it off once the debugging needs have been met.\n Args:\n model (`nn.Module`):\n The model to debug.\n max_frames_to_save (`int`, *optional*, defaults to 21):\n How many frames back to record\n trace_batch_nums(`List[int]`, *optional*, defaults to `[]`):\n Which batch numbers to trace (turns detection off)\n abort_after_batch_num (`int``, *optional*):\n Whether to abort after a certain batch number has finished\n \"\"\"\n\n def __init__(self, model, max_frames_to_save=21, trace_batch_nums=[], abort_after_batch_num=None):\n self.model = model\n self.trace_batch_nums = trace_batch_nums\n self.abort_after_batch_num = abort_after_batch_num\n\n # keep a LIFO buffer of frames to dump as soon as inf/nan is encountered to give context to the problem emergence\n self.frames = collections.deque([], max_frames_to_save)\n self.frame = []\n self.batch_number = 0\n self.total_calls = 0\n self.detected_overflow = False\n self.prefix = \" \"\n\n self.analyse_model()\n\n self.register_forward_hook()\n\n def save_frame(self, frame=None):\n if frame is not None:\n self.expand_frame(frame)\n self.frames.append(\"\\n\".join(self.frame))\n self.frame = [] # start a new frame\n\n def expand_frame(self, line):\n self.frame.append(line)\n\n def trace_frames(self):\n print(\"\\n\".join(self.frames))\n self.frames = []\n\n def reset_saved_frames(self):\n self.frames = []\n\n def dump_saved_frames(self):\n print(f\"\\nDetected inf/nan during batch_number={self.batch_number} \"\n f\"Last {len(self.frames)} forward frames:\"\n f\"{'abs min':8} {'abs max':8} metadata\"\n f\"'\\n'.join(self.frames)\"\n f\"\\n\\n\")\n self.frames = []\n\n def analyse_model(self):\n # extract the fully qualified module names, to be able to report at run time. e.g.:\n # encoder.block.2.layer.0.SelfAttention.o\n #\n # for shared weights only the first shared module name will be registered\n self.module_names = {m: name for name, m in self.model.named_modules()}\n # self.longest_module_name = max(len(v) for v in self.module_names.values())\n\n def analyse_variable(self, var, ctx):\n if torch.is_tensor(var):\n self.expand_frame(self.get_abs_min_max(var, ctx))\n if self.detect_overflow(var, ctx):\n self.detected_overflow = True\n elif var is None:\n self.expand_frame(f\"{'None':>17} {ctx}\")\n else:\n self.expand_frame(f\"{'not a tensor':>17} {ctx}\")\n\n def batch_start_frame(self):\n self.expand_frame(f\"\\n\\n{self.prefix} *** Starting batch number={self.batch_number} ***\")\n self.expand_frame(f\"{'abs min':8} {'abs max':8} metadata\")\n\n def batch_end_frame(self):\n self.expand_frame(f\"{self.prefix} *** Finished batch number={self.batch_number - 1} ***\\n\\n\")\n\n def create_frame(self, module, input, output):\n self.expand_frame(f\"{self.prefix} {self.module_names[module]} {module.__class__.__name__}\")\n\n # params\n for name, p in module.named_parameters(recurse=False):\n self.analyse_variable(p, name)\n\n # inputs\n if isinstance(input, tuple):\n for i, x in enumerate(input):\n self.analyse_variable(x, f\"input[{i}]\")\n else:\n self.analyse_variable(input, \"input\")\n\n # outputs\n if isinstance(output, tuple):\n for i, x in enumerate(output):\n # possibly a tuple of tuples\n if isinstance(x, tuple):\n for j, y in enumerate(x):\n self.analyse_variable(y, f\"output[{i}][{j}]\")\n else:\n self.analyse_variable(x, f\"output[{i}]\")\n else:\n self.analyse_variable(output, \"output\")\n\n self.save_frame()\n\n def register_forward_hook(self):\n self.model.apply(self._register_forward_hook)\n\n def _register_forward_hook(self, module):\n module.register_forward_hook(self.forward_hook)\n\n def forward_hook(self, module, input, output):\n # - input is a tuple of packed inputs (could be non-Tensors)\n # - output could be a Tensor or a tuple of Tensors and non-Tensors\n\n last_frame_of_batch = False\n\n trace_mode = True if self.batch_number in self.trace_batch_nums else False\n if trace_mode:\n self.reset_saved_frames()\n\n if self.total_calls == 0:\n self.batch_start_frame()\n self.total_calls += 1\n\n # count batch numbers - the very first forward hook of the batch will be called when the\n # batch completes - i.e. it gets called very last - we know this batch has finished\n if module == self.model:\n self.batch_number += 1\n last_frame_of_batch = True\n\n self.create_frame(module, input, output)\n\n # if last_frame_of_batch:\n # self.batch_end_frame()\n\n if trace_mode:\n self.trace_frames()\n\n if last_frame_of_batch:\n self.batch_start_frame()\n\n if self.detected_overflow and not trace_mode:\n self.dump_saved_frames()\n\n # now we can abort, as it's pointless to continue running\n raise ValueError(\n \"DebugUnderflowOverflow: inf/nan detected, aborting as there is no point running further. \"\n \"Please scroll up above this traceback to see the activation values prior to this event.\"\n )\n\n # abort after certain batch if requested to do so\n if self.abort_after_batch_num is not None and self.batch_number > self.abort_after_batch_num:\n raise ValueError(\n f\"DebugUnderflowOverflow: aborting after {self.batch_number} batches due to `abort_after_batch_num={self.abort_after_batch_num}` arg\"\n )\n\n @staticmethod\n def get_abs_min_max(var, ctx):\n abs_var = var.abs()\n return f\"{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}\"\n\n @staticmethod\n def detect_overflow(var, ctx):\n \"\"\"\n Report whether the tensor contains any `nan` or `inf` entries.\n This is useful for detecting overflows/underflows and best to call right after the function that did some math that\n modified the tensor in question.\n This function contains a few other helper features that you can enable and tweak directly if you want to track\n various other things.\n Args:\n var: the tensor variable to check\n ctx: the message to print as a context\n Return:\n `True` if `inf` or `nan` was detected, `False` otherwise\n \"\"\"\n detected = False\n if torch.isnan(var).any().item():\n detected = True\n print(f\"{ctx} has nans\")\n if torch.isinf(var).any().item():\n detected = True\n print(f\"{ctx} has infs\")\n if var.dtype == torch.float32 and torch.ge(var.abs(), 65535).any().item():\n detected = True\n print(f\"{ctx} has overflow values {var.abs().max().item()}.\")\n # if needed to monitor large elements can enable the following\n if 0: # and detected:\n n100 = var[torch.ge(var.abs(), 100)]\n if n100.numel() > 0:\n print(f\"{ctx}: n100={n100.numel()}\")\n n1000 = var[torch.ge(var.abs(), 1000)]\n if n1000.numel() > 0:\n print(f\"{ctx}: n1000={n1000.numel()}\")\n n10000 = var[torch.ge(var.abs(), 10000)]\n if n10000.numel() > 0:\n print(f\"{ctx}: n10000={n10000.numel()}\")\n\n if 0:\n print(f\"min={var.min():9.2e} max={var.max():9.2e}\")\n\n if 0:\n print(f\"min={var.min():9.2e} max={var.max():9.2e} var={var.var():9.2e} mean={var.mean():9.2e} ({ctx})\")\n\n return detected" }, { "identifier": "build_optimizer", "path": "diffusion/utils/optimizer.py", "snippet": "def build_optimizer(model, optimizer_cfg):\n # default parameter-wise config\n logger = get_root_logger()\n\n if hasattr(model, 'module'):\n model = model.module\n # set optimizer constructor\n optimizer_cfg.setdefault('constructor', 'MyOptimizerConstructor')\n # parameter-wise setting: cancel weight decay for some specific modules\n custom_keys = dict()\n for name, module in model.named_modules():\n if hasattr(module, 'zero_weight_decay'):\n custom_keys.update({(name, key): dict(decay_mult=0) for key in module.zero_weight_decay})\n\n paramwise_cfg = Config(dict(cfg=dict(custom_keys=custom_keys)))\n given_cfg = optimizer_cfg.get('paramwise_cfg')\n if given_cfg:\n paramwise_cfg.merge_from_dict(dict(cfg=given_cfg))\n optimizer_cfg['paramwise_cfg'] = paramwise_cfg.cfg\n # build optimizer\n optimizer = mm_build_optimizer(model, optimizer_cfg)\n\n weight_decay_groups = dict()\n lr_groups = dict()\n for group in optimizer.param_groups:\n if not group.get('requires_grad', True): continue\n lr_groups.setdefault(group['lr'], []).append(group)\n weight_decay_groups.setdefault(group['weight_decay'], []).append(group)\n\n learnable_count, fix_count = 0, 0\n for p in model.parameters():\n if p.requires_grad:\n learnable_count += 1\n else:\n fix_count += 1\n fix_info = f\"{learnable_count} are learnable, {fix_count} are fix\"\n lr_info = \"Lr group: \" + \", \".join([f'{len(group)} params with lr {lr:.5f}' for lr, group in lr_groups.items()])\n wd_info = \"Weight decay group: \" + \", \".join(\n [f'{len(group)} params with weight decay {wd}' for wd, group in weight_decay_groups.items()])\n opt_info = f\"Optimizer: total {len(optimizer.param_groups)} param groups, {fix_info}. {lr_info}; {wd_info}.\"\n logger.info(opt_info)\n\n return optimizer" }, { "identifier": "auto_scale_lr", "path": "diffusion/utils/optimizer.py", "snippet": "def auto_scale_lr(effective_bs, optimizer_cfg, rule='linear', base_batch_size=256):\n assert rule in ['linear', 'sqrt']\n logger = get_root_logger()\n # scale by world size\n if rule == 'sqrt':\n scale_ratio = math.sqrt(effective_bs / base_batch_size)\n elif rule == 'linear':\n scale_ratio = effective_bs / base_batch_size\n optimizer_cfg['lr'] *= scale_ratio\n logger.info(f'Automatically adapt lr to {optimizer_cfg[\"lr\"]:.7f} (using {rule} scaling rule).')\n return scale_ratio" }, { "identifier": "build_lr_scheduler", "path": "diffusion/utils/lr_scheduler.py", "snippet": "def build_lr_scheduler(config, optimizer, train_dataloader, lr_scale_ratio):\n if not config.get('lr_schedule_args', None):\n config.lr_schedule_args = dict()\n if config.get('lr_warmup_steps', None):\n config['num_warmup_steps'] = config.get('lr_warmup_steps') # for compatibility with old version\n\n logger = get_root_logger()\n logger.info(\n f'Lr schedule: {config.lr_schedule}, ' + \",\".join(\n [f\"{key}:{value}\" for key, value in config.lr_schedule_args.items()]) + '.')\n if config.lr_schedule == 'cosine':\n lr_scheduler = get_cosine_schedule_with_warmup(\n optimizer=optimizer,\n **config.lr_schedule_args,\n num_training_steps=(len(train_dataloader) * config.num_epochs),\n )\n elif config.lr_schedule == 'constant':\n lr_scheduler = get_constant_schedule_with_warmup(\n optimizer=optimizer,\n **config.lr_schedule_args,\n )\n elif config.lr_schedule == 'cosine_decay_to_constant':\n assert lr_scale_ratio >= 1\n lr_scheduler = get_cosine_decay_to_constant_with_warmup(\n optimizer=optimizer,\n **config.lr_schedule_args,\n final_lr=1 / lr_scale_ratio,\n num_training_steps=(len(train_dataloader) * config.num_epochs),\n )\n else:\n raise RuntimeError(f'Unrecognized lr schedule {config.lr_schedule}.')\n return lr_scheduler" }, { "identifier": "AspectRatioBatchSampler", "path": "diffusion/utils/data_sampler.py", "snippet": "class AspectRatioBatchSampler(BatchSampler):\n \"\"\"A sampler wrapper for grouping images with similar aspect ratio into a same batch.\n\n Args:\n sampler (Sampler): Base sampler.\n dataset (Dataset): Dataset providing data information.\n batch_size (int): Size of mini-batch.\n drop_last (bool): If ``True``, the sampler will drop the last batch if\n its size would be less than ``batch_size``.\n aspect_ratios (dict): The predefined aspect ratios.\n \"\"\"\n\n def __init__(self,\n sampler: Sampler,\n dataset: Dataset,\n batch_size: int,\n aspect_ratios: dict,\n drop_last: bool = False,\n config=None,\n valid_num=0, # take as valid aspect-ratio when sample number >= valid_num\n **kwargs) -> None:\n if not isinstance(sampler, Sampler):\n raise TypeError('sampler should be an instance of ``Sampler``, '\n f'but got {sampler}')\n if not isinstance(batch_size, int) or batch_size <= 0:\n raise ValueError('batch_size should be a positive integer value, '\n f'but got batch_size={batch_size}')\n self.sampler = sampler\n self.dataset = dataset\n self.batch_size = batch_size\n self.aspect_ratios = aspect_ratios\n self.drop_last = drop_last\n self.ratio_nums_gt = kwargs.get('ratio_nums', None)\n self.config = config\n assert self.ratio_nums_gt\n # buckets for each aspect ratio\n self._aspect_ratio_buckets = {ratio: [] for ratio in aspect_ratios.keys()}\n self.current_available_bucket_keys = [str(k) for k, v in self.ratio_nums_gt.items() if v >= valid_num]\n logger = get_root_logger() if config is None else get_root_logger(os.path.join(config.work_dir, 'train_log.log'))\n logger.warning(f\"Using valid_num={valid_num} in config file. Available {len(self.current_available_bucket_keys)} aspect_ratios: {self.current_available_bucket_keys}\")\n\n def __iter__(self) -> Sequence[int]:\n for idx in self.sampler:\n data_info = self.dataset.get_data_info(idx)\n height, width = data_info['height'], data_info['width']\n ratio = height / width\n # find the closest aspect ratio\n closest_ratio = min(self.aspect_ratios.keys(), key=lambda r: abs(float(r) - ratio))\n if closest_ratio not in self.current_available_bucket_keys:\n continue\n bucket = self._aspect_ratio_buckets[closest_ratio]\n bucket.append(idx)\n # yield a batch of indices in the same aspect ratio group\n if len(bucket) == self.batch_size:\n yield bucket[:]\n del bucket[:]\n\n # yield the rest data and reset the buckets\n for bucket in self._aspect_ratio_buckets.values():\n while len(bucket) > 0:\n if len(bucket) <= self.batch_size:\n if not self.drop_last:\n yield bucket[:]\n bucket = []\n else:\n yield bucket[:self.batch_size]\n bucket = bucket[self.batch_size:]" }, { "identifier": "BalancedAspectRatioBatchSampler", "path": "diffusion/utils/data_sampler.py", "snippet": "class BalancedAspectRatioBatchSampler(AspectRatioBatchSampler):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # Assign samples to each bucket\n self.ratio_nums_gt = kwargs.get('ratio_nums', None)\n assert self.ratio_nums_gt\n self._aspect_ratio_buckets = {float(ratio): [] for ratio in self.aspect_ratios.keys()}\n self.original_buckets = {}\n self.current_available_bucket_keys = [k for k, v in self.ratio_nums_gt.items() if v >= 3000]\n self.all_available_keys = deepcopy(self.current_available_bucket_keys)\n self.exhausted_bucket_keys = []\n self.total_batches = len(self.sampler) // self.batch_size\n self._aspect_ratio_count = {}\n for k in self.all_available_keys:\n self._aspect_ratio_count[float(k)] = 0\n self.original_buckets[float(k)] = []\n logger = get_root_logger(os.path.join(self.config.work_dir, 'train_log.log'))\n logger.warning(f\"Available {len(self.current_available_bucket_keys)} aspect_ratios: {self.current_available_bucket_keys}\")\n\n def __iter__(self) -> Sequence[int]:\n i = 0\n for idx in self.sampler:\n data_info = self.dataset.get_data_info(idx)\n height, width = data_info['height'], data_info['width']\n ratio = height / width\n closest_ratio = float(min(self.aspect_ratios.keys(), key=lambda r: abs(float(r) - ratio)))\n if closest_ratio not in self.all_available_keys:\n continue\n if self._aspect_ratio_count[closest_ratio] < self.ratio_nums_gt[closest_ratio]:\n self._aspect_ratio_count[closest_ratio] += 1\n self._aspect_ratio_buckets[closest_ratio].append(idx)\n self.original_buckets[closest_ratio].append(idx) # Save the original samples for each bucket\n if not self.current_available_bucket_keys:\n self.current_available_bucket_keys, self.exhausted_bucket_keys = self.exhausted_bucket_keys, []\n\n if closest_ratio not in self.current_available_bucket_keys:\n continue\n key = closest_ratio\n bucket = self._aspect_ratio_buckets[key]\n if len(bucket) == self.batch_size:\n yield bucket[:self.batch_size]\n del bucket[:self.batch_size]\n i += 1\n self.exhausted_bucket_keys.append(key)\n self.current_available_bucket_keys.remove(key)\n\n for _ in range(self.total_batches - i):\n key = choice(self.all_available_keys)\n bucket = self._aspect_ratio_buckets[key]\n if len(bucket) >= self.batch_size:\n yield bucket[:self.batch_size]\n del bucket[:self.batch_size]\n\n # If a bucket is exhausted\n if not bucket:\n self._aspect_ratio_buckets[key] = deepcopy(self.original_buckets[key][:])\n shuffle(self._aspect_ratio_buckets[key])\n else:\n self._aspect_ratio_buckets[key] = deepcopy(self.original_buckets[key][:])\n shuffle(self._aspect_ratio_buckets[key])" }, { "identifier": "LCMScheduler", "path": "diffusion/lcm_scheduler.py", "snippet": "class LCMScheduler(SchedulerMixin, ConfigMixin):\n \"\"\"\n `LCMScheduler` extends the denoising procedure introduced in denoising diffusion probabilistic models (DDPMs) with\n non-Markovian guidance.\n This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic\n methods the library implements for all schedulers such as loading and saving.\n Args:\n num_train_timesteps (`int`, defaults to 1000):\n The number of diffusion steps to train the model.\n beta_start (`float`, defaults to 0.0001):\n The starting `beta` value of inference.\n beta_end (`float`, defaults to 0.02):\n The final `beta` value.\n beta_schedule (`str`, defaults to `\"linear\"`):\n The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from\n `linear`, `scaled_linear`, or `squaredcos_cap_v2`.\n trained_betas (`np.ndarray`, *optional*):\n Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.\n clip_sample (`bool`, defaults to `True`):\n Clip the predicted sample for numerical stability.\n clip_sample_range (`float`, defaults to 1.0):\n The maximum magnitude for sample clipping. Valid only when `clip_sample=True`.\n set_alpha_to_one (`bool`, defaults to `True`):\n Each diffusion step uses the alphas product value at that step and at the previous one. For the final step\n there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`,\n otherwise it uses the alpha value at step 0.\n steps_offset (`int`, defaults to 0):\n An offset added to the inference steps. You can use a combination of `offset=1` and\n `set_alpha_to_one=False` to make the last step use step 0 for the previous alpha product like in Stable\n Diffusion.\n prediction_type (`str`, defaults to `epsilon`, *optional*):\n Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),\n `sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen\n Video](https://imagen.research.google/video/paper.pdf) paper).\n thresholding (`bool`, defaults to `False`):\n Whether to use the \"dynamic thresholding\" method. This is unsuitable for latent-space diffusion models such\n as Stable Diffusion.\n dynamic_thresholding_ratio (`float`, defaults to 0.995):\n The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.\n sample_max_value (`float`, defaults to 1.0):\n The threshold value for dynamic thresholding. Valid only when `thresholding=True`.\n timestep_spacing (`str`, defaults to `\"leading\"`):\n The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and\n Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.\n rescale_betas_zero_snr (`bool`, defaults to `False`):\n Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and\n dark samples instead of limiting it to samples with medium brightness. Loosely related to\n [`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).\n \"\"\"\n\n # _compatibles = [e.name for e in KarrasDiffusionSchedulers]\n order = 1\n\n @register_to_config\n def __init__(\n self,\n num_train_timesteps: int = 1000,\n beta_start: float = 0.0001,\n beta_end: float = 0.02,\n beta_schedule: str = \"linear\",\n trained_betas: Optional[Union[np.ndarray, List[float]]] = None,\n clip_sample: bool = True,\n set_alpha_to_one: bool = True,\n steps_offset: int = 0,\n prediction_type: str = \"epsilon\",\n thresholding: bool = False,\n dynamic_thresholding_ratio: float = 0.995,\n clip_sample_range: float = 1.0,\n sample_max_value: float = 1.0,\n timestep_spacing: str = \"leading\",\n rescale_betas_zero_snr: bool = False,\n ):\n if trained_betas is not None:\n self.betas = torch.tensor(trained_betas, dtype=torch.float32)\n elif beta_schedule == \"linear\":\n self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)\n elif beta_schedule == \"scaled_linear\":\n # this schedule is very specific to the latent diffusion model.\n self.betas = (\n torch.linspace(beta_start ** 0.5, beta_end ** 0.5, num_train_timesteps, dtype=torch.float32) ** 2\n )\n elif beta_schedule == \"squaredcos_cap_v2\":\n # Glide cosine schedule\n self.betas = betas_for_alpha_bar(num_train_timesteps)\n else:\n raise NotImplementedError(f\"{beta_schedule} does is not implemented for {self.__class__}\")\n\n # Rescale for zero SNR\n if rescale_betas_zero_snr:\n self.betas = rescale_zero_terminal_snr(self.betas)\n\n self.alphas = 1.0 - self.betas\n self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)\n\n # At every step in ddim, we are looking into the previous alphas_cumprod\n # For the final step, there is no previous alphas_cumprod because we are already at 0\n # `set_alpha_to_one` decides whether we set this parameter simply to one or\n # whether we use the final alpha of the \"non-previous\" one.\n self.final_alpha_cumprod = torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0]\n\n # standard deviation of the initial noise distribution\n self.init_noise_sigma = 1.0\n\n # setable values\n self.num_inference_steps = None\n self.timesteps = torch.from_numpy(np.arange(0, num_train_timesteps)[::-1].copy().astype(np.int64))\n\n def scale_model_input(self, sample: torch.FloatTensor, timestep: Optional[int] = None) -> torch.FloatTensor:\n \"\"\"\n Ensures interchangeability with schedulers that need to scale the denoising model input depending on the\n current timestep.\n Args:\n sample (`torch.FloatTensor`):\n The input sample.\n timestep (`int`, *optional*):\n The current timestep in the diffusion chain.\n Returns:\n `torch.FloatTensor`:\n A scaled input sample.\n \"\"\"\n return sample\n\n def _get_variance(self, timestep, prev_timestep):\n alpha_prod_t = self.alphas_cumprod[timestep]\n alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod\n beta_prod_t = 1 - alpha_prod_t\n beta_prod_t_prev = 1 - alpha_prod_t_prev\n\n variance = (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev)\n\n return variance\n\n # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample\n def _threshold_sample(self, sample: torch.FloatTensor) -> torch.FloatTensor:\n \"\"\"\n \"Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the\n prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by\n s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing\n pixels from saturation at each step. We find that dynamic thresholding results in significantly better\n photorealism as well as better image-text alignment, especially when using very large guidance weights.\"\n https://arxiv.org/abs/2205.11487\n \"\"\"\n dtype = sample.dtype\n batch_size, channels, height, width = sample.shape\n\n if dtype not in (torch.float32, torch.float64):\n sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half\n\n # Flatten sample for doing quantile calculation along each image\n sample = sample.reshape(batch_size, channels * height * width)\n\n abs_sample = sample.abs() # \"a certain percentile absolute pixel value\"\n\n s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)\n s = torch.clamp(\n s, min=1, max=self.config.sample_max_value\n ) # When clamped to min=1, equivalent to standard clipping to [-1, 1]\n\n s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0\n sample = torch.clamp(sample, -s, s) / s # \"we threshold xt0 to the range [-s, s] and then divide by s\"\n\n sample = sample.reshape(batch_size, channels, height, width)\n sample = sample.to(dtype)\n\n return sample\n\n def set_timesteps(self, num_inference_steps: int, lcm_origin_steps: int, device: Union[str, torch.device] = None):\n \"\"\"\n Sets the discrete timesteps used for the diffusion chain (to be run before inference).\n Args:\n num_inference_steps (`int`):\n The number of diffusion steps used when generating samples with a pre-trained model.\n \"\"\"\n\n if num_inference_steps > self.config.num_train_timesteps:\n raise ValueError(\n f\"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:\"\n f\" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle\"\n f\" maximal {self.config.num_train_timesteps} timesteps.\"\n )\n\n self.num_inference_steps = num_inference_steps\n\n # LCM Timesteps Setting: # Linear Spacing\n c = self.config.num_train_timesteps // lcm_origin_steps\n lcm_origin_timesteps = np.asarray(list(range(1, lcm_origin_steps + 1))) * c - 1 # LCM Training Steps Schedule\n skipping_step = len(lcm_origin_timesteps) // num_inference_steps\n timesteps = lcm_origin_timesteps[::-skipping_step][:num_inference_steps] # LCM Inference Steps Schedule\n\n self.timesteps = torch.from_numpy(timesteps.copy()).to(device)\n\n def get_scalings_for_boundary_condition_discrete(self, t):\n self.sigma_data = 0.5 # Default: 0.5\n\n # By dividing 0.1: This is almost a delta function at t=0.\n c_skip = self.sigma_data ** 2 / ((t / 0.1) ** 2 + self.sigma_data ** 2)\n c_out = ((t / 0.1) / ((t / 0.1) ** 2 + self.sigma_data ** 2) ** 0.5)\n return c_skip, c_out\n\n def step(\n self,\n model_output: torch.FloatTensor,\n timeindex: int,\n timestep: int,\n sample: torch.FloatTensor,\n eta: float = 0.0,\n use_clipped_model_output: bool = False,\n generator=None,\n variance_noise: Optional[torch.FloatTensor] = None,\n return_dict: bool = True,\n ) -> Union[LCMSchedulerOutput, Tuple]:\n \"\"\"\n Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion\n process from the learned model outputs (most often the predicted noise).\n Args:\n model_output (`torch.FloatTensor`):\n The direct output from learned diffusion model.\n timestep (`float`):\n The current discrete timestep in the diffusion chain.\n sample (`torch.FloatTensor`):\n A current instance of a sample created by the diffusion process.\n eta (`float`):\n The weight of noise for added noise in diffusion step.\n use_clipped_model_output (`bool`, defaults to `False`):\n If `True`, computes \"corrected\" `model_output` from the clipped predicted original sample. Necessary\n because predicted original sample is clipped to [-1, 1] when `self.config.clip_sample` is `True`. If no\n clipping has happened, \"corrected\" `model_output` would coincide with the one provided as input and\n `use_clipped_model_output` has no effect.\n generator (`torch.Generator`, *optional*):\n A random number generator.\n variance_noise (`torch.FloatTensor`):\n Alternative to generating noise with `generator` by directly providing the noise for the variance\n itself. Useful for methods such as [`CycleDiffusion`].\n return_dict (`bool`, *optional*, defaults to `True`):\n Whether or not to return a [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] or `tuple`.\n Returns:\n [`~schedulers.scheduling_utils.LCMSchedulerOutput`] or `tuple`:\n If return_dict is `True`, [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] is returned, otherwise a\n tuple is returned where the first element is the sample tensor.\n \"\"\"\n if self.num_inference_steps is None:\n raise ValueError(\n \"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler\"\n )\n\n # 1. get previous step value\n prev_timeindex = timeindex + 1\n if prev_timeindex < len(self.timesteps):\n prev_timestep = self.timesteps[prev_timeindex]\n else:\n prev_timestep = timestep\n\n # 2. compute alphas, betas\n alpha_prod_t = self.alphas_cumprod[timestep]\n alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod\n\n beta_prod_t = 1 - alpha_prod_t\n beta_prod_t_prev = 1 - alpha_prod_t_prev\n\n # 3. Get scalings for boundary conditions\n c_skip, c_out = self.get_scalings_for_boundary_condition_discrete(timestep)\n\n # 4. Different Parameterization:\n parameterization = self.config.prediction_type\n\n if parameterization == \"epsilon\": # noise-prediction\n pred_x0 = (sample - beta_prod_t.sqrt() * model_output) / alpha_prod_t.sqrt()\n\n elif parameterization == \"sample\": # x-prediction\n pred_x0 = model_output\n\n elif parameterization == \"v_prediction\": # v-prediction\n pred_x0 = alpha_prod_t.sqrt() * sample - beta_prod_t.sqrt() * model_output\n\n # 4. Denoise model output using boundary conditions\n denoised = c_out * pred_x0 + c_skip * sample\n\n # 5. Sample z ~ N(0, I), For MultiStep Inference\n # Noise is not used for one-step sampling.\n if len(self.timesteps) > 1:\n noise = torch.randn(model_output.shape).to(model_output.device)\n prev_sample = alpha_prod_t_prev.sqrt() * denoised + beta_prod_t_prev.sqrt() * noise\n else:\n prev_sample = denoised\n\n if not return_dict:\n return (prev_sample, denoised)\n\n return LCMSchedulerOutput(prev_sample=prev_sample, denoised=denoised)\n\n # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.add_noise\n def add_noise(\n self,\n original_samples: torch.FloatTensor,\n noise: torch.FloatTensor,\n timesteps: torch.IntTensor,\n ) -> torch.FloatTensor:\n # Make sure alphas_cumprod and timestep have same device and dtype as original_samples\n alphas_cumprod = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)\n timesteps = timesteps.to(original_samples.device)\n\n sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5\n sqrt_alpha_prod = sqrt_alpha_prod.flatten()\n while len(sqrt_alpha_prod.shape) < len(original_samples.shape):\n sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)\n\n sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5\n sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()\n while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):\n sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)\n\n noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise\n return noisy_samples\n\n # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.get_velocity\n def get_velocity(\n self, sample: torch.FloatTensor, noise: torch.FloatTensor, timesteps: torch.IntTensor\n ) -> torch.FloatTensor:\n # Make sure alphas_cumprod and timestep have same device and dtype as sample\n alphas_cumprod = self.alphas_cumprod.to(device=sample.device, dtype=sample.dtype)\n timesteps = timesteps.to(sample.device)\n\n sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5\n sqrt_alpha_prod = sqrt_alpha_prod.flatten()\n while len(sqrt_alpha_prod.shape) < len(sample.shape):\n sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)\n\n sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5\n sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()\n while len(sqrt_one_minus_alpha_prod.shape) < len(sample.shape):\n sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)\n\n velocity = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample\n return velocity\n\n def __len__(self):\n return self.config.num_train_timesteps" } ]
import os import sys import types import argparse import datetime import time import warnings import torch import torch.nn as nn import numpy as np import torch.nn.functional as F from pathlib import Path from accelerate import Accelerator, InitProcessGroupKwargs from accelerate.utils import DistributedType from diffusers.models import AutoencoderKL from torch.utils.data import RandomSampler from mmcv.runner import LogBuffer from copy import deepcopy from tqdm import tqdm from diffusion import IDDPM from diffusion.utils.checkpoint import save_checkpoint, load_checkpoint from diffusion.utils.dist_utils import synchronize, get_world_size, clip_grad_norm_ from diffusion.data.builder import build_dataset, build_dataloader, set_data_root from diffusion.model.builder import build_model from diffusion.utils.logger import get_root_logger from diffusion.utils.misc import set_random_seed, read_config, init_random_seed, DebugUnderflowOverflow from diffusion.utils.optimizer import build_optimizer, auto_scale_lr from diffusion.utils.lr_scheduler import build_lr_scheduler from diffusion.utils.data_sampler import AspectRatioBatchSampler, BalancedAspectRatioBatchSampler from diffusion.lcm_scheduler import LCMScheduler from torchvision.utils import save_image from accelerate import FullyShardedDataParallelPlugin from torch.distributed.fsdp.fully_sharded_data_parallel import FullStateDictConfig
16,104
data_time_all += time.time() - data_time_start if load_vae_feat: z = batch[0] else: with torch.no_grad(): with torch.cuda.amp.autocast(enabled=config.mixed_precision == 'fp16'): posterior = vae.encode(batch[0]).latent_dist if config.sample_posterior: z = posterior.sample() else: z = posterior.mode() latents = z * config.scale_factor y = batch[1] y_mask = batch[2] data_info = batch[3] # Sample a random timestep for each image grad_norm = None with accelerator.accumulate(model): # Predict the noise residual optimizer.zero_grad() # Sample noise that we'll add to the latents noise = torch.randn_like(latents) bsz = latents.shape[0] # Sample a random timestep for each image t_n ~ U[0, N - k - 1] without bias. topk = config.train_sampling_steps // config.num_ddim_timesteps index = torch.randint(0, config.num_ddim_timesteps, (bsz,), device=latents.device).long() start_timesteps = solver.ddim_timesteps[index] timesteps = start_timesteps - topk timesteps = torch.where(timesteps < 0, torch.zeros_like(timesteps), timesteps) # Get boundary scalings for start_timesteps and (end) timesteps. c_skip_start, c_out_start = scalings_for_boundary_conditions(start_timesteps) c_skip_start, c_out_start = [append_dims(x, latents.ndim) for x in [c_skip_start, c_out_start]] c_skip, c_out = scalings_for_boundary_conditions(timesteps) c_skip, c_out = [append_dims(x, latents.ndim) for x in [c_skip, c_out]] # Sample a random guidance scale w from U[w_min, w_max] and embed it # w = (config.w_max - config.w_min) * torch.rand((bsz,)) + config.w_min w = config.cfg_scale * torch.ones((bsz,)) w = w.reshape(bsz, 1, 1, 1) w = w.to(device=latents.device, dtype=latents.dtype) # Get online LCM prediction on z_{t_{n + k}}, w, c, t_{n + k} _, pred_x_0, noisy_model_input = train_diffusion.training_losses(model, latents, start_timesteps, model_kwargs=dict(y=y, mask=y_mask, data_info=data_info), noise=noise) model_pred = c_skip_start * noisy_model_input + c_out_start * pred_x_0 # Use the ODE solver to predict the kth step in the augmented PF-ODE trajectory after # noisy_latents with both the conditioning embedding c and unconditional embedding 0 # Get teacher model prediction on noisy_latents and conditional embedding with torch.no_grad(): with torch.autocast("cuda"): cond_teacher_output, cond_pred_x0, _ = train_diffusion.training_losses(model_teacher, latents, start_timesteps, model_kwargs=dict(y=y, mask=y_mask, data_info=data_info), noise=noise) # Get teacher model prediction on noisy_latents and unconditional embedding uncond_teacher_output, uncond_pred_x0, _ = train_diffusion.training_losses(model_teacher, latents, start_timesteps, model_kwargs=dict(y=uncond_prompt_embeds, mask=y_mask, data_info=data_info), noise=noise) # Perform "CFG" to get x_prev estimate (using the LCM paper's CFG formulation) pred_x0 = cond_pred_x0 + w * (cond_pred_x0 - uncond_pred_x0) pred_noise = cond_teacher_output + w * (cond_teacher_output - uncond_teacher_output) x_prev = solver.ddim_step(pred_x0, pred_noise, index) # Get target LCM prediction on x_prev, w, c, t_n with torch.no_grad(): with torch.autocast("cuda", enabled=True): _, pred_x_0, _ = train_diffusion.training_losses(model_ema, x_prev.float(), timesteps, model_kwargs=dict(y=y, mask=y_mask, data_info=data_info), skip_noise=True) target = c_skip * x_prev + c_out * pred_x_0 # Calculate loss if config.loss_type == "l2": loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean") elif config.loss_type == "huber": loss = torch.mean(torch.sqrt((model_pred.float() - target.float()) ** 2 + config.huber_c**2) - config.huber_c) # Backpropagation on the online student model (`model`) accelerator.backward(loss) if accelerator.sync_gradients: grad_norm = accelerator.clip_grad_norm_(model.parameters(), config.gradient_clip) optimizer.step() lr_scheduler.step() optimizer.zero_grad(set_to_none=True) if accelerator.sync_gradients: ema_update(model_ema, model, config.ema_decay) lr = lr_scheduler.get_last_lr()[0] logs = {"loss": accelerator.gather(loss).mean().item()} if grad_norm is not None: logs.update(grad_norm=accelerator.gather(grad_norm).mean().item()) log_buffer.update(logs) if (step + 1) % config.log_interval == 0 or (step + 1) == 1: t = (time.time() - last_tic) / config.log_interval t_d = data_time_all / config.log_interval avg_time = (time.time() - time_start) / (global_step + 1) eta = str(datetime.timedelta(seconds=int(avg_time * (total_steps - start_step - global_step - 1)))) eta_epoch = str(datetime.timedelta(seconds=int(avg_time * (len(train_dataloader) - step - 1)))) # avg_loss = sum(loss_buffer) / len(loss_buffer) log_buffer.average() info = f"Step/Epoch [{(epoch-1)*len(train_dataloader)+step+1}/{epoch}][{step + 1}/{len(train_dataloader)}]:total_eta: {eta}, " \ f"epoch_eta:{eta_epoch}, time_all:{t:.3f}, time_data:{t_d:.3f}, lr:{lr:.3e}, s:({data_info['resolution'][0][0].item()}, {data_info['resolution'][0][1].item()}), " info += ', '.join([f"{k}:{v:.4f}" for k, v in log_buffer.output.items()]) logger.info(info) last_tic = time.time() log_buffer.clear() data_time_all = 0 logs.update(lr=lr) accelerator.log(logs, step=global_step + start_step) global_step += 1 data_time_start= time.time() synchronize() torch.cuda.empty_cache() if accelerator.is_main_process: # log_validation(model_ema, step, model.device) if ((epoch - 1) * len(train_dataloader) + step + 1) % config.save_model_steps == 0: os.umask(0o000)
current_file_path = Path(__file__).resolve() sys.path.insert(0, str(current_file_path.parent.parent)) warnings.filterwarnings("ignore") # ignore warning def set_fsdp_env(): os.environ["ACCELERATE_USE_FSDP"] = 'true' os.environ["FSDP_AUTO_WRAP_POLICY"] = 'TRANSFORMER_BASED_WRAP' os.environ["FSDP_BACKWARD_PREFETCH"] = 'BACKWARD_PRE' os.environ["FSDP_TRANSFORMER_CLS_TO_WRAP"] = 'PixArtBlock' def ema_update(model_dest: nn.Module, model_src: nn.Module, rate): param_dict_src = dict(model_src.named_parameters()) for p_name, p_dest in model_dest.named_parameters(): p_src = param_dict_src[p_name] assert p_src is not p_dest p_dest.data.mul_(rate).add_((1 - rate) * p_src.data) def append_dims(x, target_dims): """Appends dimensions to the end of a tensor until it has target_dims dimensions.""" dims_to_append = target_dims - x.ndim if dims_to_append < 0: raise ValueError(f"input has {x.ndim} dims but target_dims is {target_dims}, which is less") return x[(...,) + (None,) * dims_to_append] # From LCMScheduler.get_scalings_for_boundary_condition_discrete def scalings_for_boundary_conditions(timestep, sigma_data=0.5, timestep_scaling=10.0): c_skip = sigma_data**2 / ((timestep / 0.1) ** 2 + sigma_data**2) c_out = (timestep / 0.1) / ((timestep / 0.1) ** 2 + sigma_data**2) ** 0.5 return c_skip, c_out def extract_into_tensor(a, t, x_shape): b, *_ = t.shape out = a.gather(-1, t) return out.reshape(b, *((1,) * (len(x_shape) - 1))) class DDIMSolver: def __init__(self, alpha_cumprods, timesteps=1000, ddim_timesteps=50): # DDIM sampling parameters step_ratio = timesteps // ddim_timesteps self.ddim_timesteps = (np.arange(1, ddim_timesteps + 1) * step_ratio).round().astype(np.int64) - 1 self.ddim_alpha_cumprods = alpha_cumprods[self.ddim_timesteps] self.ddim_alpha_cumprods_prev = np.asarray( [alpha_cumprods[0]] + alpha_cumprods[self.ddim_timesteps[:-1]].tolist() ) # convert to torch tensors self.ddim_timesteps = torch.from_numpy(self.ddim_timesteps).long() self.ddim_alpha_cumprods = torch.from_numpy(self.ddim_alpha_cumprods) self.ddim_alpha_cumprods_prev = torch.from_numpy(self.ddim_alpha_cumprods_prev) def to(self, device): self.ddim_timesteps = self.ddim_timesteps.to(device) self.ddim_alpha_cumprods = self.ddim_alpha_cumprods.to(device) self.ddim_alpha_cumprods_prev = self.ddim_alpha_cumprods_prev.to(device) return self def ddim_step(self, pred_x0, pred_noise, timestep_index): alpha_cumprod_prev = extract_into_tensor(self.ddim_alpha_cumprods_prev, timestep_index, pred_x0.shape) dir_xt = (1.0 - alpha_cumprod_prev).sqrt() * pred_noise x_prev = alpha_cumprod_prev.sqrt() * pred_x0 + dir_xt return x_prev @torch.no_grad() def log_validation(model, step, device): if hasattr(model, 'module'): model = model.module scheduler = LCMScheduler(beta_start=0.0001, beta_end=0.02, beta_schedule="linear", prediction_type="epsilon") scheduler.set_timesteps(4, 50) infer_timesteps = scheduler.timesteps dog_embed = torch.load('data/tmp/dog.pth', map_location='cpu') caption_embs, emb_masks = dog_embed['dog_text'].to(device), dog_embed['dog_mask'].to(device) hw = torch.tensor([[1024, 1024]], dtype=torch.float, device=device).repeat(1, 1) ar = torch.tensor([[1.]], device=device).repeat(1, 1) # Create sampling noise: infer_latents = torch.randn(1, 4, 1024, 1024, device=device) model_kwargs = dict(data_info={'img_hw': hw, 'aspect_ratio': ar}, mask=emb_masks) logger.info("Running validation... ") # 7. LCM MultiStep Sampling Loop: for i, t in tqdm(list(enumerate(infer_timesteps))): ts = torch.full((1,), t, device=device, dtype=torch.long) # model prediction (v-prediction, eps, x) model_pred = model(infer_latents, ts, caption_embs, **model_kwargs)[:, :4] # compute the previous noisy sample x_t -> x_t-1 infer_latents, denoised = scheduler.step(model_pred, i, t, infer_latents, return_dict=False) samples = vae.decode(denoised / 0.18215).sample torch.cuda.empty_cache() save_image(samples[0], f'output_cv/vis/{step}.jpg', nrow=1, normalize=True, value_range=(-1, 1)) def train(): if config.get('debug_nan', False): DebugUnderflowOverflow(model) logger.info('NaN debugger registered. Start to detect overflow during training.') time_start, last_tic = time.time(), time.time() log_buffer = LogBuffer() start_step = start_epoch * len(train_dataloader) global_step = 0 total_steps = len(train_dataloader) * config.num_epochs load_vae_feat = getattr(train_dataloader.dataset, 'load_vae_feat', False) # Create uncond embeds for classifier free guidance uncond_prompt_embeds = model.module.y_embedder.y_embedding.repeat(config.train_batch_size, 1, 1, 1) # Now you train the model for epoch in range(start_epoch + 1, config.num_epochs + 1): data_time_start= time.time() data_time_all = 0 for step, batch in enumerate(train_dataloader): data_time_all += time.time() - data_time_start if load_vae_feat: z = batch[0] else: with torch.no_grad(): with torch.cuda.amp.autocast(enabled=config.mixed_precision == 'fp16'): posterior = vae.encode(batch[0]).latent_dist if config.sample_posterior: z = posterior.sample() else: z = posterior.mode() latents = z * config.scale_factor y = batch[1] y_mask = batch[2] data_info = batch[3] # Sample a random timestep for each image grad_norm = None with accelerator.accumulate(model): # Predict the noise residual optimizer.zero_grad() # Sample noise that we'll add to the latents noise = torch.randn_like(latents) bsz = latents.shape[0] # Sample a random timestep for each image t_n ~ U[0, N - k - 1] without bias. topk = config.train_sampling_steps // config.num_ddim_timesteps index = torch.randint(0, config.num_ddim_timesteps, (bsz,), device=latents.device).long() start_timesteps = solver.ddim_timesteps[index] timesteps = start_timesteps - topk timesteps = torch.where(timesteps < 0, torch.zeros_like(timesteps), timesteps) # Get boundary scalings for start_timesteps and (end) timesteps. c_skip_start, c_out_start = scalings_for_boundary_conditions(start_timesteps) c_skip_start, c_out_start = [append_dims(x, latents.ndim) for x in [c_skip_start, c_out_start]] c_skip, c_out = scalings_for_boundary_conditions(timesteps) c_skip, c_out = [append_dims(x, latents.ndim) for x in [c_skip, c_out]] # Sample a random guidance scale w from U[w_min, w_max] and embed it # w = (config.w_max - config.w_min) * torch.rand((bsz,)) + config.w_min w = config.cfg_scale * torch.ones((bsz,)) w = w.reshape(bsz, 1, 1, 1) w = w.to(device=latents.device, dtype=latents.dtype) # Get online LCM prediction on z_{t_{n + k}}, w, c, t_{n + k} _, pred_x_0, noisy_model_input = train_diffusion.training_losses(model, latents, start_timesteps, model_kwargs=dict(y=y, mask=y_mask, data_info=data_info), noise=noise) model_pred = c_skip_start * noisy_model_input + c_out_start * pred_x_0 # Use the ODE solver to predict the kth step in the augmented PF-ODE trajectory after # noisy_latents with both the conditioning embedding c and unconditional embedding 0 # Get teacher model prediction on noisy_latents and conditional embedding with torch.no_grad(): with torch.autocast("cuda"): cond_teacher_output, cond_pred_x0, _ = train_diffusion.training_losses(model_teacher, latents, start_timesteps, model_kwargs=dict(y=y, mask=y_mask, data_info=data_info), noise=noise) # Get teacher model prediction on noisy_latents and unconditional embedding uncond_teacher_output, uncond_pred_x0, _ = train_diffusion.training_losses(model_teacher, latents, start_timesteps, model_kwargs=dict(y=uncond_prompt_embeds, mask=y_mask, data_info=data_info), noise=noise) # Perform "CFG" to get x_prev estimate (using the LCM paper's CFG formulation) pred_x0 = cond_pred_x0 + w * (cond_pred_x0 - uncond_pred_x0) pred_noise = cond_teacher_output + w * (cond_teacher_output - uncond_teacher_output) x_prev = solver.ddim_step(pred_x0, pred_noise, index) # Get target LCM prediction on x_prev, w, c, t_n with torch.no_grad(): with torch.autocast("cuda", enabled=True): _, pred_x_0, _ = train_diffusion.training_losses(model_ema, x_prev.float(), timesteps, model_kwargs=dict(y=y, mask=y_mask, data_info=data_info), skip_noise=True) target = c_skip * x_prev + c_out * pred_x_0 # Calculate loss if config.loss_type == "l2": loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean") elif config.loss_type == "huber": loss = torch.mean(torch.sqrt((model_pred.float() - target.float()) ** 2 + config.huber_c**2) - config.huber_c) # Backpropagation on the online student model (`model`) accelerator.backward(loss) if accelerator.sync_gradients: grad_norm = accelerator.clip_grad_norm_(model.parameters(), config.gradient_clip) optimizer.step() lr_scheduler.step() optimizer.zero_grad(set_to_none=True) if accelerator.sync_gradients: ema_update(model_ema, model, config.ema_decay) lr = lr_scheduler.get_last_lr()[0] logs = {"loss": accelerator.gather(loss).mean().item()} if grad_norm is not None: logs.update(grad_norm=accelerator.gather(grad_norm).mean().item()) log_buffer.update(logs) if (step + 1) % config.log_interval == 0 or (step + 1) == 1: t = (time.time() - last_tic) / config.log_interval t_d = data_time_all / config.log_interval avg_time = (time.time() - time_start) / (global_step + 1) eta = str(datetime.timedelta(seconds=int(avg_time * (total_steps - start_step - global_step - 1)))) eta_epoch = str(datetime.timedelta(seconds=int(avg_time * (len(train_dataloader) - step - 1)))) # avg_loss = sum(loss_buffer) / len(loss_buffer) log_buffer.average() info = f"Step/Epoch [{(epoch-1)*len(train_dataloader)+step+1}/{epoch}][{step + 1}/{len(train_dataloader)}]:total_eta: {eta}, " \ f"epoch_eta:{eta_epoch}, time_all:{t:.3f}, time_data:{t_d:.3f}, lr:{lr:.3e}, s:({data_info['resolution'][0][0].item()}, {data_info['resolution'][0][1].item()}), " info += ', '.join([f"{k}:{v:.4f}" for k, v in log_buffer.output.items()]) logger.info(info) last_tic = time.time() log_buffer.clear() data_time_all = 0 logs.update(lr=lr) accelerator.log(logs, step=global_step + start_step) global_step += 1 data_time_start= time.time() synchronize() torch.cuda.empty_cache() if accelerator.is_main_process: # log_validation(model_ema, step, model.device) if ((epoch - 1) * len(train_dataloader) + step + 1) % config.save_model_steps == 0: os.umask(0o000)
save_checkpoint(os.path.join(config.work_dir, 'checkpoints'),
1
2023-10-12 14:16:33+00:00
24k
NVlabs/EmerNeRF
train_emernerf.py
[ { "identifier": "metrics", "path": "datasets/metrics.py", "snippet": "def compute_valid_depth_rmse(prediction: Tensor, target: Tensor) -> float:\ndef compute_psnr(prediction: Tensor, target: Tensor) -> float:\ndef compute_ssim(\n prediction: Union[Tensor, np.ndarray], target: Union[Tensor, np.ndarray]\n) -> float:\ndef compute_scene_flow_metrics(pred: Tensor, labels: Tensor):\ndef knn_predict(\n queries: Tensor,\n memory_bank: Tensor,\n memory_labels: Tensor,\n n_classes: int,\n knn_k: int = 1,\n knn_t: float = 0.1,\n) -> Tensor:\ndef knn_predict(\n queries: Tensor,\n memory_bank: Tensor,\n memory_labels: Tensor,\n n_classes: int,\n knn_k: int = 1,\n knn_t: float = 0.1,\n similarity: str = \"cosine\",\n) -> Tensor:\ndef collect_centroids(\n train_indices: List[int],\n dataset, # a WaymoDataset object\n model: RadianceField,\n device: torch.device,\n):\ndef eval_few_shot_occ(\n test_indices: List[int],\n dataset, # a WaymoDataset object\n model: RadianceField,\n device: torch.device,\n centroids_bank: Tensor,\n label_bank: Tensor,\n):\n EPE3D = torch.mean(l2_norm).item() # Mean absolute distance error" }, { "identifier": "SceneDataset", "path": "datasets/base/scene_dataset.py", "snippet": "class SceneDataset(abc.ABC):\n \"\"\"\n Base class for scene dataset.\n \"\"\"\n\n data_cfg: OmegaConf = None\n pixel_source: ScenePixelSource = None\n lidar_source: SceneLidarSource = None\n # training and testing indices are indices into the full dataset\n # train_indices are img indices, so the length is num_cams * num_timesteps\n train_indices: List[int] = None\n test_indices: List[int] = None\n # train_timesteps are timesteps, so the length is num_timesteps (len(unique_timesteps))\n train_timesteps: Tensor = None\n test_timesteps: Tensor = None\n\n # dataset wrappers\n # full: includes all data\n full_pixel_set: SplitWrapper = None\n full_lidar_set: SplitWrapper = None\n # train: includes only training data\n train_pixel_set: SplitWrapper = None\n train_lidar_set: SplitWrapper = None\n # test: includes only testing data\n test_pixel_set: SplitWrapper = None\n test_lidar_set: SplitWrapper = None\n\n def __init__(\n self,\n data_config: OmegaConf,\n ):\n super().__init__()\n self.data_cfg = data_config\n\n @abc.abstractmethod\n def build_data_source(self):\n \"\"\"\n Create the data source for the dataset.\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def build_split_wrapper(self):\n \"\"\"\n Makes each data source as a Pytorch Dataset.\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def split_train_test(self):\n raise NotImplementedError\n\n def get_aabb(self) -> Tensor:\n if self.lidar_source is not None:\n aabb = self.lidar_source.get_aabb()\n else:\n aabb = self.pixel_source.get_aabb()\n return aabb\n\n @property\n def num_cams(self) -> int:\n return self.pixel_source.num_cams\n\n @property\n def scene_idx(self) -> int:\n return self.data_cfg.scene_idx\n\n @property\n def num_img_timesteps(self) -> int:\n return self.pixel_source.num_timesteps\n\n @property\n def num_lidar_timesteps(self) -> int:\n if self.lidar_source is None:\n logger.warning(\"No lidar source, returning num_img_timesteps\")\n return self.num_img_timesteps\n return self.lidar_source.num_timesteps\n\n @property\n def num_train_timesteps(self) -> int:\n return len(self.train_timesteps)\n\n @property\n def num_test_timesteps(self) -> int:\n return len(self.test_timesteps)\n\n @property\n def unique_normalized_training_timestamps(self) -> Tensor:\n return self.pixel_source.unique_normalized_timestamps[self.train_timesteps]\n\n @property\n def device(self):\n return self.data_cfg.preload_device" }, { "identifier": "DensityField", "path": "radiance_fields/radiance_field.py", "snippet": "class DensityField(nn.Module):\n def __init__(\n self,\n xyz_encoder: HashEncoder,\n aabb: Union[Tensor, List[float]] = [[-1.0, -1.0, -1.0, 1.0, 1.0, 1.0]],\n num_dims: int = 3,\n density_activation: Callable = lambda x: trunc_exp(x - 1),\n unbounded: bool = False,\n base_mlp_layer_width: int = 64,\n ) -> None:\n super().__init__()\n if not isinstance(aabb, Tensor):\n aabb = torch.tensor(aabb, dtype=torch.float32)\n self.register_buffer(\"aabb\", aabb)\n self.num_dims = num_dims\n self.density_activation = density_activation\n self.unbounded = unbounded\n self.xyz_encoder = xyz_encoder\n\n # density head\n self.base_mlp = nn.Sequential(\n nn.Linear(self.xyz_encoder.n_output_dims, base_mlp_layer_width),\n nn.ReLU(),\n nn.Linear(base_mlp_layer_width, 1),\n )\n\n @property\n def device(self) -> torch.device:\n return self.aabb.device\n\n def set_aabb(self, aabb: Union[Tensor, List[float]]) -> None:\n if not isinstance(aabb, Tensor):\n aabb = torch.tensor(aabb, dtype=torch.float32)\n logger.info(f\"Set propnet aabb from {self.aabb} to {aabb}\")\n self.aabb.copy_(aabb)\n self.aabb = self.aabb.to(self.device)\n\n def forward(\n self, positions: Tensor, data_dict: Dict[str, Tensor] = None\n ) -> Dict[str, Tensor]:\n if self.unbounded:\n # use infinte norm to contract the positions for cuboid aabb\n positions = contract(positions, self.aabb, ord=float(\"inf\"))\n else:\n aabb_min, aabb_max = torch.split(self.aabb, 3, dim=-1)\n positions = (positions - aabb_min) / (aabb_max - aabb_min)\n selector = ((positions > 0.0) & (positions < 1.0)).all(dim=-1).to(positions)\n positions = positions * selector.unsqueeze(-1)\n xyz_encoding = self.xyz_encoder(positions.view(-1, self.num_dims))\n density_before_activation = self.base_mlp(xyz_encoding).view(\n list(positions.shape[:-1]) + [-1]\n )\n density = self.density_activation(density_before_activation)\n return {\"density\": density}" }, { "identifier": "RadianceField", "path": "radiance_fields/radiance_field.py", "snippet": "class RadianceField(nn.Module):\n def __init__(\n self,\n xyz_encoder: HashEncoder,\n dynamic_xyz_encoder: Optional[HashEncoder] = None,\n flow_xyz_encoder: Optional[HashEncoder] = None,\n aabb: Union[Tensor, List[float]] = [-1, -1, -1, 1, 1, 1],\n num_dims: int = 3,\n density_activation: Callable = lambda x: trunc_exp(x - 1),\n unbounded: bool = True,\n geometry_feature_dim: int = 15,\n base_mlp_layer_width: int = 64,\n head_mlp_layer_width: int = 64,\n enable_cam_embedding: bool = False,\n enable_img_embedding: bool = False,\n num_cams: int = 3,\n appearance_embedding_dim: int = 16,\n semantic_feature_dim: int = 64,\n feature_mlp_layer_width: int = 256,\n feature_embedding_dim: int = 768,\n enable_sky_head: bool = False,\n enable_shadow_head: bool = False,\n enable_feature_head: bool = False,\n num_train_timesteps: int = 0,\n interpolate_xyz_encoding: bool = False,\n enable_learnable_pe: bool = True,\n enable_temporal_interpolation: bool = False,\n ) -> None:\n super().__init__()\n # scene properties\n if not isinstance(aabb, Tensor):\n aabb = torch.tensor(aabb, dtype=torch.float32)\n self.register_buffer(\"aabb\", aabb)\n self.unbounded = unbounded\n self.num_cams = num_cams\n self.num_dims = num_dims\n self.density_activation = density_activation\n\n # appearance embedding\n self.enable_cam_embedding = enable_cam_embedding\n self.enable_img_embedding = enable_img_embedding\n self.appearance_embedding_dim = appearance_embedding_dim\n\n self.geometry_feature_dim = geometry_feature_dim\n # add semantic feature dim if feature head is enabled\n if not enable_feature_head:\n semantic_feature_dim = 0\n self.semantic_feature_dim = semantic_feature_dim\n\n # note: we use very conservative default values for mlps\n # usually you want to use larger ones\n\n # ======== Static Field ======== #\n self.xyz_encoder = xyz_encoder\n self.base_mlp = nn.Sequential(\n nn.Linear(self.xyz_encoder.n_output_dims, base_mlp_layer_width),\n nn.ReLU(),\n nn.Linear(\n base_mlp_layer_width, geometry_feature_dim + semantic_feature_dim\n ),\n )\n\n # ======== Dynamic Field ======== #\n self.interpolate_xyz_encoding = interpolate_xyz_encoding\n self.dynamic_xyz_encoder = dynamic_xyz_encoder\n self.enable_temporal_interpolation = enable_temporal_interpolation\n if self.dynamic_xyz_encoder is not None:\n # for temporal interpolation\n self.register_buffer(\"training_timesteps\", torch.zeros(num_train_timesteps))\n self.dynamic_base_mlp = nn.Sequential(\n nn.Linear(self.dynamic_xyz_encoder.n_output_dims, base_mlp_layer_width),\n nn.ReLU(),\n nn.Linear(\n base_mlp_layer_width,\n geometry_feature_dim + semantic_feature_dim,\n ),\n )\n\n # ======== Flow Field ======== #\n self.flow_xyz_encoder = flow_xyz_encoder\n if self.flow_xyz_encoder is not None:\n self.flow_mlp = nn.Sequential(\n nn.Linear(\n self.flow_xyz_encoder.n_output_dims,\n base_mlp_layer_width,\n ),\n nn.ReLU(),\n nn.Linear(base_mlp_layer_width, base_mlp_layer_width),\n nn.ReLU(),\n nn.Linear(base_mlp_layer_width, 6), # 3 for forward, 3 for backward\n # no activation function for flow\n )\n\n # appearance embedding\n if self.enable_cam_embedding:\n # per-camera embedding\n self.appearance_embedding = nn.Embedding(num_cams, appearance_embedding_dim)\n elif self.enable_img_embedding:\n # per-image embedding\n self.appearance_embedding = nn.Embedding(\n num_train_timesteps * num_cams, appearance_embedding_dim\n )\n else:\n self.appearance_embedding = None\n\n # direction encoding\n self.direction_encoding = SinusoidalEncoder(\n n_input_dims=3, min_deg=0, max_deg=4\n )\n\n # ======== Color Head ======== #\n self.rgb_head = MLP(\n in_dims=geometry_feature_dim\n + self.direction_encoding.n_output_dims\n + (\n appearance_embedding_dim\n if self.enable_cam_embedding or self.enable_img_embedding\n else 0 # 2 or 0?\n ),\n out_dims=3,\n num_layers=3,\n hidden_dims=head_mlp_layer_width,\n skip_connections=[1],\n )\n\n # ======== Shadow Head ======== #\n self.enable_shadow_head = enable_shadow_head\n if self.enable_shadow_head:\n self.shadow_head = nn.Sequential(\n nn.Linear(geometry_feature_dim, base_mlp_layer_width),\n nn.ReLU(),\n nn.Linear(base_mlp_layer_width, 1),\n nn.Sigmoid(),\n )\n\n # ======== Sky Head ======== #\n self.enable_sky_head = enable_sky_head\n if self.enable_sky_head:\n self.sky_head = MLP(\n in_dims=self.direction_encoding.n_output_dims\n + (\n appearance_embedding_dim\n if self.enable_cam_embedding or self.enable_img_embedding\n else 0\n ),\n out_dims=3,\n num_layers=3,\n hidden_dims=head_mlp_layer_width,\n skip_connections=[1],\n )\n if enable_feature_head:\n # feature sky head\n self.dino_sky_head = nn.Sequential(\n # TODO: remove appearance embedding from dino sky head\n nn.Linear(\n self.direction_encoding.n_output_dims\n + (\n appearance_embedding_dim\n if self.enable_cam_embedding or self.enable_img_embedding\n else 0\n ),\n feature_mlp_layer_width,\n ),\n nn.ReLU(),\n nn.Linear(feature_mlp_layer_width, feature_mlp_layer_width),\n nn.ReLU(),\n nn.Linear(feature_mlp_layer_width, feature_embedding_dim),\n )\n\n # ======== Feature Head ======== #\n self.enable_feature_head = enable_feature_head\n if self.enable_feature_head:\n self.dino_head = nn.Sequential(\n nn.Linear(semantic_feature_dim, feature_mlp_layer_width),\n nn.ReLU(),\n nn.Linear(feature_mlp_layer_width, feature_mlp_layer_width),\n nn.ReLU(),\n nn.Linear(feature_mlp_layer_width, feature_embedding_dim),\n )\n # placeholders for visualization, will be registered when available\n self.register_buffer(\n \"feats_reduction_mat\", torch.zeros(feature_embedding_dim, 3)\n )\n self.register_buffer(\"feat_color_min\", torch.zeros(3, dtype=torch.float32))\n self.register_buffer(\"feat_color_max\", torch.ones(3, dtype=torch.float32))\n\n # positional embedding (PE) decomposition\n self.enable_learnable_pe = enable_learnable_pe\n if self.enable_learnable_pe:\n # globally-shared low-resolution learnable PE map\n self.learnable_pe_map = nn.Parameter(\n 0.05 * torch.randn(1, feature_embedding_dim // 2, 80, 120),\n requires_grad=True,\n )\n # a PE head to decode PE features\n self.pe_head = nn.Sequential(\n nn.Linear(feature_embedding_dim // 2, feature_embedding_dim),\n )\n\n def register_normalized_training_timesteps(\n self, normalized_timesteps: Tensor, time_diff: float = None\n ) -> None:\n \"\"\"\n register normalized timesteps for temporal interpolation\n\n Args:\n normalized_timesteps (Tensor): normalized timesteps in [0, 1]\n time_diff (float, optional): time difference between two consecutive timesteps. Defaults to None.\n \"\"\"\n if self.dynamic_xyz_encoder is not None:\n # register timesteps for temporal interpolation\n self.training_timesteps.copy_(normalized_timesteps)\n self.training_timesteps = self.training_timesteps.to(self.device)\n if time_diff is not None:\n # use the provided time difference if available\n self.time_diff = time_diff\n else:\n if len(self.training_timesteps) > 1:\n # otherwise, compute the time difference from the provided timesteps\n # it's important to make sure the provided timesteps are consecutive\n self.time_diff = (\n self.training_timesteps[1] - self.training_timesteps[0]\n )\n else:\n self.time_diff = 0\n\n def set_aabb(self, aabb: Union[Tensor, List[float]]) -> None:\n \"\"\"\n register aabb for scene space\n \"\"\"\n if not isinstance(aabb, Tensor):\n aabb = torch.tensor(aabb, dtype=torch.float32)\n logger.info(f\"Set aabb from {self.aabb} to {aabb}\")\n self.aabb.copy_(aabb)\n self.aabb = self.aabb.to(self.device)\n\n def register_feats_reduction_mat(\n self,\n feats_reduction_mat: Tensor,\n feat_color_min: Tensor,\n feat_color_max: Tensor,\n ) -> None:\n \"\"\"\n A placeholder for registering the PCA reduction matrix and min/max values for visualization.\n You may not want to compute PCA reduction matrix every time from the dataset.\n \"\"\"\n # for visualization\n self.feats_reduction_mat.copy_(feats_reduction_mat)\n self.feat_color_min.copy_(feat_color_min)\n self.feat_color_max.copy_(feat_color_max)\n self.feats_reduction_mat = self.feats_reduction_mat.to(self.device)\n self.feat_color_min = self.feat_color_min.to(self.device)\n self.feat_color_max = self.feat_color_max.to(self.device)\n\n @property\n def device(self) -> torch.device:\n return self.aabb.device\n\n def contract_points(\n self,\n positions: Tensor,\n ) -> Tensor:\n \"\"\"\n contract [-inf, inf] points to the range [0, 1] for hash encoding\n\n Returns:\n normed_positions: [..., 3] in [0, 1]\n \"\"\"\n if self.unbounded:\n # use infinte norm to contract the positions for cuboid aabb\n normed_positions = contract(positions, self.aabb, ord=float(\"inf\"))\n else:\n aabb_min, aabb_max = torch.split(self.aabb, 3, dim=-1)\n normed_positions = (positions - aabb_min) / (aabb_max - aabb_min)\n selector = (\n ((normed_positions > 0.0) & (normed_positions < 1.0))\n .all(dim=-1)\n .to(positions)\n )\n normed_positions = normed_positions * selector.unsqueeze(-1)\n return normed_positions\n\n def forward_static_hash(\n self,\n positions: Tensor,\n ) -> Tensor:\n \"\"\"\n forward pass for static hash encoding\n\n Returns:\n encoded_features: [..., geometry_feature_dim + (semantic_feature_dim)]\n normed_positions: [..., 3] in [0, 1]\n \"\"\"\n normed_positions = self.contract_points(positions)\n xyz_encoding = self.xyz_encoder(normed_positions.view(-1, self.num_dims))\n encoded_features = self.base_mlp(xyz_encoding).view(\n list(normed_positions.shape[:-1]) + [-1]\n )\n return encoded_features, normed_positions\n\n def forward_dynamic_hash(\n self,\n normed_positions: Tensor,\n normed_timestamps: Tensor,\n return_hash_encodings: bool = False,\n ) -> Union[Tuple[Tensor, Tensor], Tensor]:\n \"\"\"\n forward pass for dynamic hash encoding\n\n Returns:\n encoded_dynamic_feats: [..., geometry_feature_dim + (semantic_feature_dim)]\n dynamic_xyz_encoding: [..., n_output_dims] (optional)\n \"\"\"\n if normed_timestamps.shape[-1] != 1:\n normed_timestamps = normed_timestamps.unsqueeze(-1)\n # To be fixed.\n # if self.training or not self.enable_temporal_interpolation:\n if True:\n temporal_positions = torch.cat(\n [normed_positions, normed_timestamps], dim=-1\n )\n dynamic_xyz_encoding = self.dynamic_xyz_encoder(\n temporal_positions.view(-1, self.num_dims + 1)\n ).view(list(temporal_positions.shape[:-1]) + [-1])\n encoded_dynamic_feats = self.dynamic_base_mlp(dynamic_xyz_encoding)\n else:\n encoded_dynamic_feats = temporal_interpolation(\n normed_timestamps,\n self.training_timesteps,\n normed_positions,\n self.dynamic_xyz_encoder,\n self.dynamic_base_mlp,\n interpolate_xyz_encoding=self.interpolate_xyz_encoding,\n )\n if return_hash_encodings:\n return encoded_dynamic_feats, dynamic_xyz_encoding\n else:\n return encoded_dynamic_feats\n\n def forward_flow_hash(\n self,\n normed_positions: Tensor,\n normed_timestamps: Tensor,\n ) -> Tuple[Tensor, Tensor]:\n \"\"\"\n forward pass for flow hash encoding\n\n Returns:\n flow: [..., 6] (forward_flow, backward_flow)\n \"\"\"\n if normed_timestamps.shape[-1] != 1:\n normed_timestamps = normed_timestamps.unsqueeze(-1)\n if self.training or not self.enable_temporal_interpolation:\n temporal_positions = torch.cat(\n [normed_positions, normed_timestamps], dim=-1\n )\n flow_xyz_encoding = self.flow_xyz_encoder(\n temporal_positions.view(-1, self.num_dims + 1)\n ).view(list(temporal_positions.shape[:-1]) + [-1])\n flow = self.flow_mlp(flow_xyz_encoding)\n else:\n flow = temporal_interpolation(\n normed_timestamps,\n self.training_timesteps,\n normed_positions,\n self.flow_xyz_encoder,\n self.flow_mlp,\n interpolate_xyz_encoding=True,\n )\n return flow\n\n def forward(\n self,\n positions: Tensor,\n directions: Tensor = None,\n data_dict: Dict[str, Tensor] = {},\n return_density_only: bool = False,\n combine_static_dynamic: bool = False,\n query_feature_head: bool = True,\n query_pe_head: bool = True,\n ) -> Dict[str, Tensor]:\n \"\"\"\n Args:\n positions: [..., 3]\n directions: [..., 3]\n data_dict: a dictionary containing additional data\n return_density_only: if True, only return density without querying other heads\n combine_static_dynamic: if True, combine static and dynamic predictions based on static and dynamic density\n in addition to returning separate results for static and dynamic fields\n query_feature_head: if True, query feature head\n query_pe_head: if True, query PE head. Disable this if we want to directly query 3D features.\n Returns:\n results_dict: a dictionary containing everything\n \"\"\"\n results_dict = {}\n # forward static branch\n encoded_features, normed_positions = self.forward_static_hash(positions)\n geo_feats, semantic_feats = torch.split(\n encoded_features,\n [self.geometry_feature_dim, self.semantic_feature_dim],\n dim=-1,\n )\n static_density = self.density_activation(geo_feats[..., 0])\n\n has_timestamps = (\n \"normed_timestamps\" in data_dict or \"lidar_normed_timestamps\" in data_dict\n )\n if self.dynamic_xyz_encoder is not None and has_timestamps:\n # forward dynamic branch\n if \"normed_timestamps\" in data_dict:\n normed_timestamps = data_dict[\"normed_timestamps\"]\n elif \"lidar_normed_timestamps\" in data_dict:\n # we use `lidar_` prefix as an identifier to skip querying other heads\n normed_timestamps = data_dict[\"lidar_normed_timestamps\"]\n dynamic_feats, dynamic_hash_encodings = self.forward_dynamic_hash(\n normed_positions, normed_timestamps, return_hash_encodings=True\n )\n if self.flow_xyz_encoder is not None:\n flow = self.forward_flow_hash(normed_positions, normed_timestamps)\n forward_flow, backward_flow = flow[..., :3], flow[..., 3:]\n results_dict[\"forward_flow\"] = forward_flow\n results_dict[\"backward_flow\"] = backward_flow\n temporal_aggregation_results = self.temporal_aggregation(\n positions,\n normed_timestamps,\n forward_flow,\n backward_flow,\n dynamic_feats,\n )\n # overwrite dynamic feats using temporal aggregation results\n dynamic_feats = temporal_aggregation_results[\"dynamic_feats\"]\n # to be studied\n temporal_aggregation_results[\n \"current_dynamic_hash_encodings\"\n ] = dynamic_hash_encodings\n results_dict.update(temporal_aggregation_results)\n (dynamic_geo_feats, dynamic_semantic_feats,) = torch.split(\n dynamic_feats,\n [self.geometry_feature_dim, self.semantic_feature_dim],\n dim=-1,\n )\n dynamic_density = self.density_activation(dynamic_geo_feats[..., 0])\n # blend static and dynamic density to get the final density\n density = static_density + dynamic_density\n results_dict.update(\n {\n \"density\": density,\n \"static_density\": static_density,\n \"dynamic_density\": dynamic_density,\n }\n )\n if return_density_only:\n # skip querying other heads\n return results_dict\n\n if directions is not None:\n rgb_results = self.query_rgb(\n directions, geo_feats, dynamic_geo_feats, data_dict=data_dict\n )\n results_dict[\"dynamic_rgb\"] = rgb_results[\"dynamic_rgb\"]\n results_dict[\"static_rgb\"] = rgb_results[\"rgb\"]\n if combine_static_dynamic:\n static_ratio = static_density / (density + 1e-6)\n dynamic_ratio = dynamic_density / (density + 1e-6)\n results_dict[\"rgb\"] = (\n static_ratio[..., None] * results_dict[\"static_rgb\"]\n + dynamic_ratio[..., None] * results_dict[\"dynamic_rgb\"]\n )\n if self.enable_shadow_head:\n shadow_ratio = self.shadow_head(dynamic_geo_feats)\n results_dict[\"shadow_ratio\"] = shadow_ratio\n if combine_static_dynamic and \"rgb\" in results_dict:\n results_dict[\"rgb\"] = (\n static_ratio[..., None]\n * results_dict[\"rgb\"]\n * (1 - shadow_ratio)\n + dynamic_ratio[..., None] * results_dict[\"dynamic_rgb\"]\n )\n else:\n # if no dynamic branch, use static density\n results_dict[\"density\"] = static_density\n if return_density_only:\n # skip querying other heads\n return results_dict\n if directions is not None:\n rgb_results = self.query_rgb(directions, geo_feats, data_dict=data_dict)\n results_dict[\"rgb\"] = rgb_results[\"rgb\"]\n\n if self.enable_feature_head and query_feature_head:\n if self.enable_learnable_pe and query_pe_head:\n learnable_pe_map = (\n F.grid_sample(\n self.learnable_pe_map,\n # assume pixel coords have been normalize to [-1, 1]\n data_dict[\"pixel_coords\"].reshape(1, 1, -1, 2) * 2 - 1,\n align_corners=False, # didn't test with True\n mode=\"bilinear\", # didn't test with other modes\n )\n .squeeze(2)\n .squeeze(0)\n .permute(1, 0)\n )\n dino_pe = self.pe_head(learnable_pe_map)\n results_dict[\"dino_pe\"] = dino_pe\n dino_feats = self.dino_head(semantic_feats)\n\n if self.dynamic_xyz_encoder is not None and has_timestamps:\n dynamic_dino_feats = self.dino_head(dynamic_semantic_feats)\n results_dict[\"static_dino_feat\"] = dino_feats\n results_dict[\"dynamic_dino_feat\"] = dynamic_dino_feats\n if combine_static_dynamic:\n static_ratio = static_density / (density + 1e-6)\n dynamic_ratio = dynamic_density / (density + 1e-6)\n results_dict[\"dino_feat\"] = (\n static_ratio[..., None] * dino_feats\n + dynamic_ratio[..., None] * dynamic_dino_feats\n )\n else:\n results_dict[\"dino_feat\"] = dino_feats\n\n # query sky if not in lidar mode\n if (\n self.enable_sky_head\n and \"lidar_origin\" not in data_dict\n and directions is not None\n ):\n directions = directions[:, 0]\n reduced_data_dict = {k: v[:, 0] for k, v in data_dict.items()}\n sky_results = self.query_sky(directions, data_dict=reduced_data_dict)\n results_dict.update(sky_results)\n\n return results_dict\n\n def temporal_aggregation(\n self,\n positions: Tensor, # current world coordinates\n normed_timestamps: Tensor, # current normalized timestamps\n forward_flow: Tensor,\n backward_flow: Tensor,\n dynamic_feats: Tensor,\n ) -> Tensor:\n \"\"\"\n temporal aggregation for dynamic features\n Eq. (8) in the emernerf paper\n \"\"\"\n if normed_timestamps.shape[-1] != 1:\n normed_timestamps = normed_timestamps.unsqueeze(-1)\n if self.training:\n noise = torch.rand_like(forward_flow)[..., 0:1]\n else:\n noise = torch.ones_like(forward_flow)[..., 0:1]\n # forward and backward warped positions\n forward_warped_positions = self.contract_points(\n positions + forward_flow * noise\n )\n backward_warped_positions = self.contract_points(\n positions + backward_flow * noise\n )\n # forward and backward warped timestamps\n forward_warped_time = torch.clamp(\n normed_timestamps + self.time_diff * noise, 0, 1.0\n )\n backward_warped_time = torch.clamp(\n normed_timestamps - self.time_diff * noise, 0, 1.0\n )\n (\n forward_dynamic_feats,\n forward_dynamic_hash_encodings,\n ) = self.forward_dynamic_hash(\n forward_warped_positions,\n forward_warped_time,\n return_hash_encodings=True,\n )\n (\n backward_dynamic_feats,\n backward_dynamic_hash_encodings,\n ) = self.forward_dynamic_hash(\n backward_warped_positions,\n backward_warped_time,\n return_hash_encodings=True,\n )\n forward_pred_flow = self.forward_flow_hash(\n forward_warped_positions,\n forward_warped_time,\n )\n backward_pred_flow = self.forward_flow_hash(\n backward_warped_positions,\n backward_warped_time,\n )\n # simple weighted sum\n aggregated_dynamic_feats = (\n dynamic_feats + 0.5 * forward_dynamic_feats + 0.5 * backward_dynamic_feats\n ) / 2.0\n return {\n \"dynamic_feats\": aggregated_dynamic_feats,\n \"forward_pred_backward_flow\": forward_pred_flow[..., 3:],\n \"backward_pred_forward_flow\": backward_pred_flow[..., :3],\n # to be studied\n \"forward_dynamic_hash_encodings\": forward_dynamic_hash_encodings,\n \"backward_dynamic_hash_encodings\": backward_dynamic_hash_encodings,\n }\n\n def query_rgb(\n self,\n directions: Tensor,\n geo_feats: Tensor,\n dynamic_geo_feats: Tensor = None,\n data_dict: Dict[str, Tensor] = None,\n ) -> Tensor:\n directions = (directions + 1.0) / 2.0 # do we need this?\n h = self.direction_encoding(directions.reshape(-1, directions.shape[-1])).view(\n *directions.shape[:-1], -1\n )\n if self.enable_cam_embedding or self.enable_img_embedding:\n if \"cam_idx\" in data_dict and self.enable_cam_embedding:\n appearance_embedding = self.appearance_embedding(data_dict[\"cam_idx\"])\n elif \"img_idx\" in data_dict and self.enable_img_embedding:\n appearance_embedding = self.appearance_embedding(data_dict[\"img_idx\"])\n else:\n # use mean appearance embedding\n # print(\"using mean appearance embedding\")\n appearance_embedding = torch.ones(\n (*directions.shape[:-1], self.appearance_embedding_dim),\n device=directions.device,\n ) * self.appearance_embedding.weight.mean(dim=0)\n h = torch.cat([h, appearance_embedding], dim=-1)\n\n rgb = self.rgb_head(torch.cat([h, geo_feats], dim=-1))\n rgb = F.sigmoid(rgb)\n results = {\"rgb\": rgb}\n\n if self.dynamic_xyz_encoder is not None:\n assert (\n dynamic_geo_feats is not None\n ), \"Dynamic geometry features are not provided.\"\n dynamic_rgb = self.rgb_head(torch.cat([h, dynamic_geo_feats], dim=-1))\n dynamic_rgb = F.sigmoid(dynamic_rgb)\n results[\"dynamic_rgb\"] = dynamic_rgb\n return results\n\n def query_sky(\n self, directions: Tensor, data_dict: Dict[str, Tensor] = None\n ) -> Dict[str, Tensor]:\n if len(directions.shape) == 2:\n dd = self.direction_encoding(directions).to(directions)\n else:\n dd = self.direction_encoding(directions[:, 0]).to(directions)\n if self.enable_cam_embedding or self.enable_img_embedding:\n # optionally add appearance embedding\n if \"cam_idx\" in data_dict and self.enable_cam_embedding:\n appearance_embedding = self.appearance_embedding(data_dict[\"cam_idx\"])\n elif \"img_idx\" in data_dict and self.enable_img_embedding:\n appearance_embedding = self.appearance_embedding(data_dict[\"img_idx\"])\n else:\n # use mean appearance embedding\n appearance_embedding = torch.ones(\n (*directions.shape[:-1], self.appearance_embedding_dim),\n device=directions.device,\n ) * self.appearance_embedding.weight.mean(dim=0)\n dd = torch.cat([dd, appearance_embedding], dim=-1)\n rgb_sky = self.sky_head(dd).to(directions)\n rgb_sky = F.sigmoid(rgb_sky)\n results = {\"rgb_sky\": rgb_sky}\n if self.enable_feature_head:\n self.dino_sky_head(dd).to(directions)\n results[\"dino_sky_feat\"] = self.dino_sky_head(dd).to(directions)\n return results\n\n def query_flow(\n self, positions: Tensor, normed_timestamps: Tensor, query_density: bool = True\n ) -> Dict[str, Tensor]:\n \"\"\"\n query flow field\n \"\"\"\n normed_positions = self.contract_points(positions)\n flow = self.forward_flow_hash(normed_positions, normed_timestamps)\n results = {\n \"forward_flow\": flow[..., :3],\n \"backward_flow\": flow[..., 3:],\n }\n if query_density:\n # it's important to filter valid flows based on a dynamic density threshold.\n # flows are valid only if they are on dynamic points.\n dynamic_feats = self.forward_dynamic_hash(\n normed_positions, normed_timestamps\n )\n (dynamic_geo_feats, _,) = torch.split(\n dynamic_feats,\n [self.geometry_feature_dim, self.semantic_feature_dim],\n dim=-1,\n )\n dynamic_density = self.density_activation(dynamic_geo_feats[..., 0])\n results[\"dynamic_density\"] = dynamic_density\n return results\n\n def query_attributes(\n self,\n positions: Tensor,\n normed_timestamps: Tensor = None,\n query_feature_head: bool = True,\n ):\n \"\"\"\n query attributes (density, dino features, etc.)\n \"\"\"\n results_dict = {}\n encoded_features, normed_positions = self.forward_static_hash(positions)\n geo_feats, semantic_feats = torch.split(\n encoded_features,\n [self.geometry_feature_dim, self.semantic_feature_dim],\n dim=-1,\n )\n static_density = self.density_activation(geo_feats[..., 0])\n if self.dynamic_xyz_encoder is not None and normed_timestamps is not None:\n dynamic_feats, dynamic_hash_encodings = self.forward_dynamic_hash(\n normed_positions, normed_timestamps, return_hash_encodings=True\n )\n if self.flow_xyz_encoder is not None:\n flow = self.forward_flow_hash(normed_positions, normed_timestamps)\n forward_flow = flow[..., :3]\n backward_flow = flow[..., 3:]\n results_dict[\"forward_flow\"] = forward_flow\n results_dict[\"backward_flow\"] = backward_flow\n temporal_aggregation_results = self.temporal_aggregation(\n positions,\n normed_timestamps,\n forward_flow,\n backward_flow,\n dynamic_feats,\n )\n dynamic_feats = temporal_aggregation_results[\"dynamic_feats\"]\n temporal_aggregation_results[\n \"current_dynamic_hash_encodings\"\n ] = dynamic_hash_encodings\n results_dict.update(temporal_aggregation_results)\n\n (dynamic_geo_feats, dynamic_semantic_feats,) = torch.split(\n dynamic_feats,\n [self.geometry_feature_dim, self.semantic_feature_dim],\n dim=-1,\n )\n dynamic_density = self.density_activation(dynamic_geo_feats[..., 0])\n density = static_density + dynamic_density\n results_dict.update(\n {\n \"density\": density,\n \"static_density\": static_density,\n \"dynamic_density\": dynamic_density,\n # \"occupancy\": occupancy,\n }\n )\n else:\n results_dict[\"density\"] = static_density\n if self.enable_feature_head and query_feature_head:\n # query on demand\n dino_feats = self.dino_head(semantic_feats)\n if self.dynamic_xyz_encoder is not None and normed_timestamps is not None:\n dynamic_dino_feats = self.dino_head(dynamic_semantic_feats)\n results_dict[\"static_dino_feat\"] = dino_feats\n results_dict[\"dynamic_dino_feat\"] = dynamic_dino_feats\n results_dict[\"dino_feat\"] = (\n static_density.unsqueeze(-1) * dino_feats\n + dynamic_density.unsqueeze(-1) * dynamic_dino_feats\n ) / (density.unsqueeze(-1) + 1e-6)\n else:\n results_dict[\"dino_feat\"] = dino_feats\n return results_dict" }, { "identifier": "render_rays", "path": "radiance_fields/render_utils.py", "snippet": "def render_rays(\n # scene\n radiance_field: RadianceField = None,\n proposal_estimator: PropNetEstimator = None,\n proposal_networks: Optional[List[DensityField]] = None,\n data_dict: Dict[str, Tensor] = None,\n cfg: OmegaConf = None,\n proposal_requires_grad: bool = False,\n return_decomposition: bool = False,\n prefix=\"\",\n) -> Dict[str, Tensor]:\n \"\"\"Render some attributes of the scene along the rays.\"\"\"\n # reshape data_dict to be (num_rays, ...)\n rays_shape = data_dict[prefix + \"origins\"].shape\n if len(rays_shape) == 3:\n height, width, _ = rays_shape\n num_rays = height * width\n reshaped_data_dict = {}\n for k, v in data_dict.items():\n reshaped_data_dict[k] = v.reshape(num_rays, -1).squeeze()\n else:\n num_rays, _ = rays_shape\n reshaped_data_dict = data_dict.copy()\n\n def prop_sigma_fn(t_starts, t_ends, proposal_network):\n # query propsal networks for density\n t_origins = chunk_data_dict[prefix + \"origins\"][..., None, :]\n t_dirs = chunk_data_dict[prefix + \"viewdirs\"][..., None, :]\n positions = t_origins + t_dirs * (t_starts + t_ends)[..., None] / 2.0\n sub_dict = {\n k: v[..., None].repeat_interleave(t_starts.shape[-1], dim=-1)\n for k, v in chunk_data_dict.items()\n if \"time\" in k\n }\n return proposal_network(positions, sub_dict)\n\n def query_fn(t_starts, t_ends):\n # query the final nerf model for density and other information along the rays\n t_origins = chunk_data_dict[prefix + \"origins\"][..., None, :]\n t_dirs = chunk_data_dict[prefix + \"viewdirs\"][..., None, :].repeat_interleave(\n t_starts.shape[-1], dim=-2\n )\n sub_dict = {\n k: v[..., None].repeat_interleave(t_starts.shape[-1], dim=-1)\n for k, v in chunk_data_dict.items()\n if k not in [prefix + \"viewdirs\", prefix + \"origins\", \"pixel_coords\"]\n }\n sub_dict[\"t_starts\"], sub_dict[\"t_ends\"] = t_starts, t_ends\n if \"pixel_coords\" in chunk_data_dict:\n # use this for positional embedding decomposition\n sub_dict[\"pixel_coords\"] = chunk_data_dict[\"pixel_coords\"]\n positions = t_origins + t_dirs * (t_starts + t_ends)[..., None] / 2.0\n # return density only when rendering lidar, i.e., no rgb or sky or features are rendered\n results_dict: Dict[str, Tensor] = radiance_field(\n positions, t_dirs, sub_dict, return_density_only=(prefix == \"lidar_\")\n )\n results_dict[\"density\"] = results_dict[\"density\"].squeeze(-1)\n return results_dict\n\n results = []\n chunk = 2**24 if radiance_field.training else cfg.render.render_chunk_size\n for i in range(0, num_rays, chunk):\n chunk_data_dict = {k: v[i : i + chunk] for k, v in reshaped_data_dict.items()}\n assert proposal_networks is not None, \"proposal_networks is required.\"\n # obtain proposed intervals\n t_starts, t_ends = proposal_estimator.sampling(\n prop_sigma_fns=[\n lambda *args: prop_sigma_fn(*args, p) for p in proposal_networks\n ],\n num_samples=cfg.nerf.sampling.num_samples,\n prop_samples=cfg.nerf.propnet.num_samples_per_prop,\n n_rays=chunk_data_dict[prefix + \"origins\"].shape[0],\n near_plane=cfg.nerf.propnet.near_plane,\n far_plane=cfg.nerf.propnet.far_plane,\n sampling_type=cfg.nerf.propnet.sampling_type,\n stratified=radiance_field.training,\n requires_grad=proposal_requires_grad,\n )\n # render the scene\n chunk_results_dict = rendering(\n t_starts,\n t_ends,\n query_fn=query_fn,\n return_decomposition=return_decomposition,\n )\n extras = chunk_results_dict.pop(\"extras\")\n results.append(chunk_results_dict)\n render_results = collate(\n results,\n collate_fn_map={\n **default_collate_fn_map,\n Tensor: lambda x, **_: torch.cat(x, 0),\n },\n )\n extras[\"density\"] = render_results.pop(\"density\")\n for k, v in render_results.items():\n # recover the original shape\n render_results[k] = v.reshape(list(rays_shape[:-1]) + list(v.shape[1:]))\n render_results[\"extras\"] = extras\n return render_results" }, { "identifier": "render_pixels", "path": "radiance_fields/video_utils.py", "snippet": "def render_pixels(\n cfg: OmegaConf,\n model: RadianceField,\n proposal_estimator: PropNetEstimator,\n dataset: SplitWrapper,\n proposal_networks: Optional[List[DensityField]] = None,\n compute_metrics: bool = False,\n vis_indices: Optional[List[int]] = None,\n return_decomposition: bool = True,\n):\n \"\"\"\n Render pixel-related outputs from a model.\n\n Args:\n ....skip obvious args\n compute_metrics (bool, optional): Whether to compute metrics. Defaults to False.\n vis_indices (Optional[List[int]], optional): Indices to visualize. Defaults to None.\n return_decomposition (bool, optional): Whether to visualize the static-dynamic decomposition. Defaults to True.\n \"\"\"\n model.eval()\n if proposal_networks is not None:\n for p in proposal_networks:\n p.eval()\n if proposal_estimator is not None:\n proposal_estimator.eval()\n # set up render function\n render_func = lambda data_dict: render_rays(\n radiance_field=model,\n proposal_estimator=proposal_estimator,\n proposal_networks=proposal_networks,\n data_dict=data_dict,\n cfg=cfg,\n return_decomposition=return_decomposition, # return static-dynamic decomposition\n )\n render_results = render(\n dataset,\n render_func,\n model=model,\n compute_metrics=compute_metrics,\n vis_indices=vis_indices,\n )\n if compute_metrics:\n num_samples = len(dataset) if vis_indices is None else len(vis_indices)\n logger.info(f\"Eval over {num_samples} images:\")\n logger.info(f\"\\tPSNR: {render_results['psnr']:.4f}\")\n logger.info(f\"\\tSSIM: {render_results['ssim']:.4f}\")\n logger.info(f\"\\tFeature PSNR: {render_results['feat_psnr']:.4f}\")\n logger.info(f\"\\tMasked PSNR: {render_results['masked_psnr']:.4f}\")\n logger.info(f\"\\tMasked SSIM: {render_results['masked_ssim']:.4f}\")\n logger.info(f\"\\tMasked Feature PSNR: {render_results['masked_feat_psnr']:.4f}\")\n\n return render_results" }, { "identifier": "save_videos", "path": "radiance_fields/video_utils.py", "snippet": "def save_videos(\n render_results: Dict[str, List[Tensor]],\n save_pth: str,\n num_timestamps: int,\n keys: List[str] = [\"gt_rgbs\", \"rgbs\", \"depths\"],\n num_cams: int = 3,\n save_seperate_video: bool = False,\n save_images: bool = False,\n fps: int = 10,\n verbose: bool = True,\n):\n if save_seperate_video:\n return_frame = save_seperate_videos(\n render_results,\n save_pth,\n num_timestamps=num_timestamps,\n keys=keys,\n num_cams=num_cams,\n save_images=save_images,\n fps=fps,\n verbose=verbose,\n )\n else:\n return_frame = save_concatenated_videos(\n render_results,\n save_pth,\n num_timestamps=num_timestamps,\n keys=keys,\n num_cams=num_cams,\n save_images=save_images,\n fps=fps,\n verbose=verbose,\n )\n return return_frame" }, { "identifier": "PropNetEstimator", "path": "third_party/nerfacc_prop_net.py", "snippet": "class PropNetEstimator(AbstractEstimator):\n \"\"\"Proposal network transmittance estimator.\n\n References: \"Mip-NeRF 360: Unbounded Anti-Aliased Neural Radiance Fields.\"\n\n Args:\n optimizer: The optimizer to use for the proposal networks.\n scheduler: The learning rate scheduler to use for the proposal networks.\n \"\"\"\n\n def __init__(\n self,\n optimizer: Optional[torch.optim.Optimizer] = None,\n scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None,\n enable_anti_aliasing_loss: Optional[bool] = True,\n anti_aliasing_pulse_width: Optional[List[float]] = [0.03, 0.003],\n ) -> None:\n super().__init__()\n self.optimizer = optimizer\n self.scheduler = scheduler\n self.prop_cache: List = []\n self.enable_anti_aliasing_loss = enable_anti_aliasing_loss\n self.pulse_width = anti_aliasing_pulse_width\n if self.enable_anti_aliasing_loss:\n logger.info(\"Enable anti-aliasing loss, pulse width: %s\", self.pulse_width)\n\n @torch.no_grad()\n def sampling(\n self,\n prop_sigma_fns: List[Callable],\n prop_samples: List[int],\n num_samples: int,\n # rendering options\n n_rays: int,\n near_plane: float,\n far_plane: float,\n sampling_type: Literal[\n \"uniform\", \"lindisp\", \"sqrt\", \"log\", \"uniform_lindisp\"\n ] = \"uniform_lindisp\",\n # training options\n stratified: bool = False,\n requires_grad: bool = False,\n ) -> Tuple[Tensor, Tensor]:\n \"\"\"Sampling with CDFs from proposal networks.\n\n Note:\n When `requires_grad` is `True`, the gradients are allowed to flow\n through the proposal networks, and the outputs of the proposal\n networks are cached to update them later when calling `update_every_n_steps()`\n\n Args:\n prop_sigma_fns: Proposal network evaluate functions. It should be a list\n of functions that take in samples {t_starts (n_rays, n_samples),\n t_ends (n_rays, n_samples)} and returns the post-activation densities\n (n_rays, n_samples).\n prop_samples: Number of samples to draw from each proposal network. Should\n be the same length as `prop_sigma_fns`.\n num_samples: Number of samples to draw in the end.\n n_rays: Number of rays.\n near_plane: Near plane.\n far_plane: Far plane.\n sampling_type: Sampling type. Either \"uniform\" or \"lindisp\". Default to\n \"lindisp\".\n stratified: Whether to use stratified sampling. Default to `False`.\n requires_grad: Whether to allow gradients to flow through the proposal\n networks. Default to `False`.\n\n Returns:\n A tuple of {Tensor, Tensor}:\n\n - **t_starts**: The starts of the samples. Shape (n_rays, num_samples).\n - **t_ends**: The ends of the samples. Shape (n_rays, num_samples).\n\n \"\"\"\n assert len(prop_sigma_fns) == len(prop_samples), (\n \"The number of proposal networks and the number of samples \"\n \"should be the same.\"\n )\n cdfs = torch.cat(\n [\n torch.zeros((n_rays, 1), device=self.device),\n torch.ones((n_rays, 1), device=self.device),\n ],\n dim=-1,\n )\n intervals = RayIntervals(vals=cdfs)\n\n for i, (level_fn, level_samples) in enumerate(\n zip(prop_sigma_fns, prop_samples)\n ):\n intervals, _ = importance_sampling(\n intervals, cdfs, level_samples, stratified\n )\n t_vals = _transform_stot(\n sampling_type, intervals.vals, near_plane, far_plane\n )\n t_starts = t_vals[..., :-1]\n t_ends = t_vals[..., 1:]\n\n with torch.set_grad_enabled(requires_grad):\n sigmas = level_fn(t_starts, t_ends)[\"density\"].squeeze(-1)\n assert sigmas.shape == t_starts.shape\n trans, _ = render_transmittance_from_density(t_starts, t_ends, sigmas)\n cdfs = 1.0 - torch.cat(\n [trans, torch.zeros_like(trans[..., :1])], dim=-1\n )\n if requires_grad:\n self.prop_cache.append((intervals, cdfs, i))\n\n intervals, _ = importance_sampling(intervals, cdfs, num_samples, stratified)\n t_vals = _transform_stot(sampling_type, intervals.vals, near_plane, far_plane)\n t_starts = t_vals[..., :-1]\n t_ends = t_vals[..., 1:]\n if requires_grad:\n self.prop_cache.append((intervals, None, None))\n\n return t_starts, t_ends\n\n @torch.enable_grad()\n def compute_loss(self, trans: Tensor, loss_scaler: float = 1.0) -> Tensor:\n \"\"\"Compute the loss for the proposal networks.\n\n Args:\n trans: The transmittance of all samples. Shape (n_rays, num_samples).\n loss_scaler: The loss scaler. Default to 1.0.\n\n Returns:\n The loss for the proposal networks.\n \"\"\"\n if len(self.prop_cache) == 0:\n return torch.zeros((), device=self.device)\n\n intervals, _, _ = self.prop_cache.pop()\n # get cdfs at all edges of intervals\n cdfs = 1.0 - torch.cat([trans, torch.zeros_like(trans[..., :1])], dim=-1)\n cdfs = cdfs.detach()\n loss = 0.0\n\n if self.enable_anti_aliasing_loss:\n w_normalize = (cdfs[..., 1:] - cdfs[..., :-1]) / (\n intervals.vals[..., 1:] - intervals.vals[..., :-1]\n )\n c1, w1 = blur_stepfun(intervals.vals, w_normalize, self.pulse_width[0])\n c2, w2 = blur_stepfun(intervals.vals, w_normalize, self.pulse_width[1])\n area1 = 0.5 * (w1[..., 1:] + w1[..., :-1]) * (c1[..., 1:] - c1[..., :-1])\n area2 = 0.5 * (w2[..., 1:] + w2[..., :-1]) * (c2[..., 1:] - c2[..., :-1])\n cdfs1 = torch.cat(\n [\n torch.zeros_like(area1[..., :1]),\n torch.cumsum(area1, dim=-1),\n ],\n dim=-1,\n )\n cdfs2 = torch.cat(\n [\n torch.zeros_like(area2[..., :1]),\n torch.cumsum(area2, dim=-1),\n ],\n dim=-1,\n )\n cs = [c1, c2]\n ws = [w1, w2]\n _cdfs = [cdfs1, cdfs2]\n while self.prop_cache:\n prop_intervals, prop_cdfs, prop_id = self.prop_cache.pop()\n wp = prop_cdfs[..., 1:] - prop_cdfs[..., :-1]\n cdf_interp = sorted_interp_quad(\n prop_intervals.vals, cs[prop_id], ws[prop_id], _cdfs[prop_id]\n )\n w_s = torch.diff(cdf_interp, dim=-1)\n loss += ((w_s - wp).clamp_min(0) ** 2 / (wp + 1e-5)).mean()\n else:\n while self.prop_cache:\n prop_intervals, prop_cdfs, _ = self.prop_cache.pop()\n loss += _pdf_loss(intervals, cdfs, prop_intervals, prop_cdfs).mean()\n return loss * loss_scaler\n\n @torch.enable_grad()\n def update_every_n_steps(\n self,\n trans: Tensor,\n requires_grad: bool = False,\n loss_scaler: float = 1.0,\n ) -> float:\n \"\"\"Update the estimator every n steps during training.\n\n Args:\n trans: The transmittance of all samples. Shape (n_rays, num_samples).\n requires_grad: Whether to allow gradients to flow through the proposal\n networks. Default to `False`.\n loss_scaler: The loss scaler to use. Default to 1.0.\n\n Returns:\n The loss of the proposal networks for logging (a float scalar).\n \"\"\"\n if requires_grad:\n return self._update(trans=trans, loss_scaler=loss_scaler)\n else:\n if self.scheduler is not None:\n self.scheduler.step()\n return 0.0\n\n @torch.enable_grad()\n def _update(self, trans: Tensor, loss_scaler: float = 1.0) -> float:\n assert len(self.prop_cache) > 0\n assert self.optimizer is not None, \"No optimizer is provided.\"\n\n loss = self.compute_loss(trans, loss_scaler)\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n if self.scheduler is not None:\n self.scheduler.step()\n return loss.item()" }, { "identifier": "get_proposal_requires_grad_fn", "path": "third_party/nerfacc_prop_net.py", "snippet": "def get_proposal_requires_grad_fn(\n target: float = 5.0, num_steps: int = 1000\n) -> Callable:\n schedule = lambda s: min(s / num_steps, 1.0) * target\n\n steps_since_last_grad = 0\n\n def proposal_requires_grad_fn(step: int) -> bool:\n nonlocal steps_since_last_grad\n target_steps_since_last_grad = schedule(step)\n requires_grad = steps_since_last_grad > target_steps_since_last_grad\n if requires_grad:\n steps_since_last_grad = 0\n steps_since_last_grad += 1\n return requires_grad\n\n return proposal_requires_grad_fn" }, { "identifier": "MetricLogger", "path": "utils/logging.py", "snippet": "class MetricLogger(object):\n def __init__(self, delimiter=\"\\t\", output_file=None):\n self.meters = defaultdict(SmoothedValue)\n self.delimiter = delimiter\n self.output_file = output_file\n\n def update(self, **kwargs):\n for k, v in kwargs.items():\n if isinstance(v, torch.Tensor):\n v = v.item()\n assert isinstance(v, (float, int))\n self.meters[k].update(v)\n\n def __getattr__(self, attr):\n if attr in self.meters:\n return self.meters[attr]\n if attr in self.__dict__:\n return self.__dict__[attr]\n raise AttributeError(\n f\"'{type(self).__name__}' object has no attribute '{attr}'\"\n )\n\n def __str__(self):\n loss_str = []\n for name, meter in self.meters.items():\n loss_str.append(f\"{name}: {str(meter)}\")\n return self.delimiter.join(loss_str)\n\n def synchronize_between_processes(self):\n for meter in self.meters.values():\n meter.synchronize_between_processes()\n\n def add_meter(self, name, meter):\n self.meters[name] = meter\n\n def dump_in_output_file(self, iteration, iter_time, data_time):\n if self.output_file is None:\n return\n dict_to_dump = dict(\n iteration=iteration,\n iter_time=iter_time,\n data_time=data_time,\n )\n dict_to_dump.update({k: v.median for k, v in self.meters.items()})\n with open(self.output_file, \"a\") as f:\n f.write(json.dumps(dict_to_dump) + \"\\n\")\n pass\n\n def log_every(\n self, iterable, print_freq, header=None, n_iterations=None, start_iteration=0\n ):\n i = start_iteration\n if not header:\n header = \"\"\n start_time = time.time()\n end = time.time()\n iter_time = SmoothedValue(fmt=\"{avg:.6f}\")\n data_time = SmoothedValue(fmt=\"{avg:.6f}\")\n\n if n_iterations is None:\n n_iterations = len(iterable)\n\n space_fmt = \":\" + str(len(str(n_iterations))) + \"d\"\n\n log_list = [\n header,\n \"[{0\" + space_fmt + \"}/{1}]\",\n \"eta: {eta}\",\n \"elapsed: {elapsed_time_str}\",\n \"{meters}\",\n \"time: {time}\",\n \"data: {data}\",\n ]\n if torch.cuda.is_available():\n log_list += [\"max mem: {memory:.0f}\"]\n\n log_msg = self.delimiter.join(log_list)\n MB = 1024.0 * 1024.0\n for obj in iterable:\n data_time.update(time.time() - end)\n yield obj\n iter_time.update(time.time() - end)\n if i % print_freq == 0 or i == n_iterations - 1:\n self.dump_in_output_file(\n iteration=i, iter_time=iter_time.avg, data_time=data_time.avg\n )\n eta_seconds = iter_time.global_avg * (n_iterations - i)\n eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))\n elapsed_time = time.time() - start_time\n elapsed_time_str = str(datetime.timedelta(seconds=int(elapsed_time)))\n\n if torch.cuda.is_available():\n logger.info(\n log_msg.format(\n i,\n n_iterations,\n eta=eta_string,\n elapsed_time_str=elapsed_time_str,\n meters=str(self),\n time=str(iter_time),\n data=str(data_time),\n memory=torch.cuda.max_memory_allocated() / MB,\n )\n )\n else:\n logger.info(\n log_msg.format(\n i,\n n_iterations,\n eta=eta_string,\n meters=str(self),\n time=str(iter_time),\n data=str(data_time),\n )\n )\n i += 1\n end = time.time()\n if i >= n_iterations:\n break\n total_time = time.time() - start_time\n total_time_str = str(datetime.timedelta(seconds=int(total_time)))\n logger.info(\n f\"{header} Total time: {total_time_str} ({total_time / n_iterations:.6f} s / it)\"\n )" }, { "identifier": "setup_logging", "path": "utils/logging.py", "snippet": "def setup_logging(\n output: Optional[str] = None,\n *,\n name: Optional[str] = None,\n level: int = logging.DEBUG,\n capture_warnings: bool = True,\n time_string: Optional[str] = None,\n) -> None:\n \"\"\"\n Setup logging.\n\n Args:\n output: A file name or a directory to save log files. If None, log\n files will not be saved. If output ends with \".txt\" or \".log\", it\n is assumed to be a file name.\n Otherwise, logs will be saved to `output/log.txt`.\n name: The name of the logger to configure, by default the root logger.\n level: The logging level to use.\n capture_warnings: Whether warnings should be captured as logs.\n \"\"\"\n logging.captureWarnings(capture_warnings)\n _configure_logger(name, level=level, output=output, time_string=time_string)" }, { "identifier": "visualize_voxels", "path": "utils/visualization_tools.py", "snippet": "def visualize_voxels(\n cfg: OmegaConf,\n model: RadianceField,\n proposal_estimator: PropNetEstimator = None,\n proposal_networks: DensityField = None,\n dataset: SceneDataset = None,\n device: str = \"cuda\",\n save_html: bool = True,\n is_dynamic: bool = False,\n):\n model.eval()\n for p in proposal_networks:\n p.eval()\n if proposal_estimator is not None:\n proposal_estimator.eval()\n if proposal_networks is not None:\n for p in proposal_networks:\n p.eval()\n\n vis_voxel_aabb = torch.tensor(model.aabb, device=device)\n # slightly expand the aabb to make sure all points are covered\n vis_voxel_aabb[1:3] -= 1\n vis_voxel_aabb[3:] += 1\n aabb_min, aabb_max = torch.split(vis_voxel_aabb, 3, dim=-1)\n aabb_length = aabb_max - aabb_min\n\n # compute the voxel resolution for visualization\n static_voxel_resolution = torch.ceil(\n (aabb_max - aabb_min) / cfg.render.vis_voxel_size\n ).long()\n empty_static_voxels = torch.zeros(*static_voxel_resolution, device=device)\n if is_dynamic:\n # use a slightly smaller voxel size for dynamic voxels\n dynamic_voxel_resolution = torch.ceil(\n (aabb_max - aabb_min) / cfg.render.vis_voxel_size * 0.8\n ).long()\n all_occupied_dynamic_points = []\n empty_dynamic_voxels = torch.zeros(*dynamic_voxel_resolution, device=device)\n\n # collect some patches for PCA\n to_compute_pca_patches = []\n\n pbar = tqdm(\n dataset.full_pixel_set,\n desc=\"querying depth\",\n dynamic_ncols=True,\n total=len(dataset.full_pixel_set),\n )\n for i, data_dict in enumerate(pbar):\n data_dict = dataset.full_pixel_set[i]\n for k, v in data_dict.items():\n data_dict[k] = v.to(device)\n if i < dataset.num_cams:\n # collect all patches from the first timestep\n with torch.no_grad():\n render_results = render_rays(\n radiance_field=model,\n proposal_estimator=proposal_estimator,\n proposal_networks=proposal_networks,\n data_dict=data_dict,\n cfg=cfg,\n proposal_requires_grad=False,\n )\n if \"dino_pe_free\" in render_results:\n dino_feats = render_results[\"dino_pe_free\"]\n else:\n dino_feats = render_results[\"dino_feat\"]\n dino_feats = dino_feats.reshape(-1, dino_feats.shape[-1])\n to_compute_pca_patches.append(dino_feats)\n # query the depth. we force a lidar mode here so that the renderer will skip\n # querying other features such as colors, features, etc.\n data_dict[\"lidar_origins\"] = data_dict[\"origins\"].to(device)\n data_dict[\"lidar_viewdirs\"] = data_dict[\"viewdirs\"].to(device)\n data_dict[\"lidar_normed_timestamps\"] = data_dict[\"normed_timestamps\"].to(device)\n with torch.no_grad():\n render_results = render_rays(\n radiance_field=model,\n proposal_estimator=proposal_estimator,\n proposal_networks=proposal_networks,\n data_dict=data_dict,\n cfg=cfg,\n proposal_requires_grad=False,\n prefix=\"lidar_\", # force lidar mode\n return_decomposition=True,\n )\n # ==== get the static voxels ======\n if is_dynamic:\n static_depth = render_results[\"static_depth\"]\n else:\n static_depth = render_results[\"depth\"]\n world_coords = (\n data_dict[\"lidar_origins\"] + data_dict[\"lidar_viewdirs\"] * static_depth\n )\n world_coords = world_coords[static_depth.squeeze() < 80]\n voxel_coords = world_coords_to_voxel_coords(\n world_coords, aabb_min, aabb_max, static_voxel_resolution\n )\n voxel_coords = voxel_coords.long()\n selector = (\n (voxel_coords[..., 0] >= 0)\n & (voxel_coords[..., 0] < static_voxel_resolution[0])\n & (voxel_coords[..., 1] >= 0)\n & (voxel_coords[..., 1] < static_voxel_resolution[1])\n & (voxel_coords[..., 2] >= 0)\n & (voxel_coords[..., 2] < static_voxel_resolution[2])\n )\n # split the voxel_coords into separate dimensions\n voxel_coords_x = voxel_coords[..., 0][selector]\n voxel_coords_y = voxel_coords[..., 1][selector]\n voxel_coords_z = voxel_coords[..., 2][selector]\n # index into empty_voxels using the separated coordinates\n empty_static_voxels[voxel_coords_x, voxel_coords_y, voxel_coords_z] = 1\n\n # ==== get the dynamic voxels ======\n if is_dynamic:\n dynamic_depth = render_results[\"dynamic_depth\"]\n world_coords = (\n data_dict[\"lidar_origins\"] + data_dict[\"lidar_viewdirs\"] * dynamic_depth\n )\n voxel_coords = world_coords_to_voxel_coords(\n world_coords, aabb_min, aabb_max, dynamic_voxel_resolution\n )\n voxel_coords = voxel_coords.long()\n selector = (\n (voxel_coords[..., 0] >= 0)\n & (voxel_coords[..., 0] < dynamic_voxel_resolution[0])\n & (voxel_coords[..., 1] >= 0)\n & (voxel_coords[..., 1] < dynamic_voxel_resolution[1])\n & (voxel_coords[..., 2] >= 0)\n & (voxel_coords[..., 2] < dynamic_voxel_resolution[2])\n )\n # split the voxel_coords into separate dimensions\n voxel_coords_x = voxel_coords[..., 0][selector]\n voxel_coords_y = voxel_coords[..., 1][selector]\n voxel_coords_z = voxel_coords[..., 2][selector]\n # index into empty_voxels using the separated coordinates\n empty_dynamic_voxels[voxel_coords_x, voxel_coords_y, voxel_coords_z] = 1\n if i % dataset.num_cams == 0 and i > 0:\n all_occupied_dynamic_points.append(\n voxel_coords_to_world_coords(\n aabb_min,\n aabb_max,\n dynamic_voxel_resolution,\n torch.nonzero(empty_dynamic_voxels),\n )\n )\n empty_dynamic_voxels = torch.zeros(\n *dynamic_voxel_resolution, device=device\n )\n # compute the pca reduction\n dummy_pca_reduction, color_min, color_max = get_robust_pca(\n torch.cat(to_compute_pca_patches, dim=0).to(device), m=2.5\n )\n # now let's query the features\n all_occupied_static_points = voxel_coords_to_world_coords(\n aabb_min, aabb_max, static_voxel_resolution, torch.nonzero(empty_static_voxels)\n )\n chunk = 2**18\n pca_colors = []\n occupied_points = []\n pbar = tqdm(\n range(0, all_occupied_static_points.shape[0], chunk),\n desc=\"querying static features\",\n dynamic_ncols=True,\n )\n for i in pbar:\n occupied_points_chunk = all_occupied_static_points[i : i + chunk]\n density_list = []\n # we need to accumulate the density from all proposal networks as well\n # to ensure reliable density estimation\n for p in proposal_networks:\n density_list.append(p(occupied_points_chunk)[\"density\"].squeeze(-1))\n with torch.no_grad():\n results = model.forward(\n occupied_points_chunk,\n query_feature_head=False,\n )\n density_list.append(results[\"density\"])\n density = torch.stack(density_list, dim=0)\n density = torch.mean(density, dim=0)\n # use a preset threshold to determine whether a voxel is occupied\n selector = density > 0.5\n occupied_points_chunk = occupied_points_chunk[selector]\n if len(occupied_points_chunk) == 0:\n # skip if no occupied points in this chunk\n continue\n with torch.no_grad():\n feats = model.forward(\n occupied_points_chunk,\n query_feature_head=True,\n query_pe_head=False,\n )[\"dino_feat\"]\n colors = feats @ dummy_pca_reduction\n del feats\n colors = (colors - color_min) / (color_max - color_min)\n pca_colors.append(torch.clamp(colors, 0, 1))\n occupied_points.append(occupied_points_chunk)\n\n pca_colors = torch.cat(pca_colors, dim=0)\n occupied_points = torch.cat(occupied_points, dim=0)\n if is_dynamic:\n dynamic_pca_colors = []\n dynamic_occupied_points = []\n unq_timestamps = dataset.pixel_source.unique_normalized_timestamps.to(device)\n # query every 10 frames\n pbar = tqdm(\n range(0, len(all_occupied_dynamic_points), 10),\n desc=\"querying dynamic fields\",\n dynamic_ncols=True,\n )\n for i in pbar:\n occupied_points_chunk = all_occupied_dynamic_points[i]\n normed_timestamps = unq_timestamps[i].repeat(\n occupied_points_chunk.shape[0], 1\n )\n with torch.no_grad():\n results = model.forward(\n occupied_points_chunk,\n data_dict={\"normed_timestamps\": normed_timestamps},\n query_feature_head=False,\n )\n selector = results[\"dynamic_density\"].squeeze() > 0.1\n occupied_points_chunk = occupied_points_chunk[selector]\n if len(occupied_points_chunk) == 0:\n continue\n # query some features\n normed_timestamps = unq_timestamps[i].repeat(\n occupied_points_chunk.shape[0], 1\n )\n with torch.no_grad():\n feats = model.forward(\n occupied_points_chunk,\n data_dict={\"normed_timestamps\": normed_timestamps},\n query_feature_head=True,\n query_pe_head=False,\n )[\"dynamic_dino_feat\"]\n colors = feats @ dummy_pca_reduction\n del feats\n colors = (colors - color_min) / (color_max - color_min)\n dynamic_pca_colors.append(torch.clamp(colors, 0, 1))\n dynamic_occupied_points.append(occupied_points_chunk)\n dynamic_coords = [x.cpu().numpy() for x in dynamic_occupied_points]\n dynamic_colors = [x.cpu().numpy() for x in dynamic_pca_colors]\n else:\n dynamic_coords = None\n dynamic_colors = None\n\n figure = vis_occ_plotly(\n vis_aabb=vis_voxel_aabb.cpu().numpy().tolist(),\n coords=occupied_points.cpu().numpy(),\n colors=pca_colors.cpu().numpy(),\n dynamic_coords=dynamic_coords,\n dynamic_colors=dynamic_colors,\n x_ratio=1,\n y_ratio=(aabb_length[1] / aabb_length[0]).item(),\n z_ratio=(aabb_length[2] / aabb_length[0]).item(),\n size=3,\n black_bg=True,\n title=f\"Lifted {cfg.data.pixel_source.feature_model_type} Features, PE_removed: {cfg.nerf.model.head.enable_learnable_pe}\",\n )\n # for plotly\n data = figure.to_dict()[\"data\"]\n layout = figure.to_dict()[\"layout\"]\n output_path = os.path.join(cfg.log_dir, f\"feature_field.json\")\n with open(output_path, \"w\") as f:\n json.dump({\"data\": data, \"layout\": layout}, f, cls=NumpyEncoder)\n logger.info(f\"Saved to {output_path}\")\n output_path = os.path.join(cfg.log_dir, f\"feature_field.html\")\n if save_html:\n figure.write_html(output_path)\n logger.info(f\"Query result saved to {output_path}\")" }, { "identifier": "visualize_scene_flow", "path": "utils/visualization_tools.py", "snippet": "def visualize_scene_flow(\n cfg: OmegaConf,\n model: RadianceField,\n dataset: SceneDataset = None,\n device: str = \"cuda\",\n save_html: bool = True,\n):\n pbar = tqdm(\n range(0, len(dataset.full_lidar_set) - 1, 10),\n desc=\"querying flow\",\n dynamic_ncols=True,\n )\n predicted_flow_colors, gt_flow_colors = [], []\n dynamic_coords = []\n for i in pbar:\n data_dict = dataset.full_lidar_set[i].copy()\n lidar_flow_class = data_dict[\"lidar_flow_class\"]\n for k, v in data_dict.items():\n # remove invalid flow (the information is from GT)\n data_dict[k] = v[lidar_flow_class != -1]\n\n if data_dict[k].shape[0] == 0:\n logger.info(f\"no valid points, skipping...\")\n continue\n # filter out ground points\n # for k, v in data_dict.items():\n # data_dict[k] = v[~data_dict[\"lidar_ground\"]]\n valid_lidar_mask = dataset.get_valid_lidar_mask(i, data_dict)\n for k, v in data_dict.items():\n data_dict[k] = v[valid_lidar_mask]\n lidar_points = (\n data_dict[\"lidar_origins\"]\n + data_dict[\"lidar_ranges\"] * data_dict[\"lidar_viewdirs\"]\n )\n normalized_timestamps = data_dict[\"lidar_normed_timestamps\"]\n with torch.no_grad():\n pred_results = model.query_flow(\n positions=lidar_points,\n normed_timestamps=normalized_timestamps,\n )\n pred_flow = pred_results[\"forward_flow\"]\n # flow is only valid when the point is not static\n pred_flow[pred_results[\"dynamic_density\"] < 0.2] *= 0\n\n predicted_flow_colors.append(\n scene_flow_to_rgb(pred_flow, flow_max_radius=2.0, background=\"bright\")\n .cpu()\n .numpy()\n )\n gt_flow_colors.append(\n scene_flow_to_rgb(\n data_dict[\"lidar_flow\"], flow_max_radius=2.0, background=\"bright\"\n )\n .cpu()\n .numpy()\n )\n dynamic_coords.append(lidar_points.cpu().numpy())\n\n vis_voxel_aabb = torch.tensor(model.aabb, device=device)\n # slightly expand the aabb to make sure all points are covered\n vis_voxel_aabb[1:3] -= 1\n vis_voxel_aabb[3:] += 1\n aabb_min, aabb_max = torch.split(vis_voxel_aabb, 3, dim=-1)\n aabb_length = aabb_max - aabb_min\n pred_figure = vis_occ_plotly(\n vis_aabb=vis_voxel_aabb.cpu().numpy().tolist(),\n dynamic_coords=dynamic_coords,\n dynamic_colors=predicted_flow_colors,\n x_ratio=1,\n y_ratio=(aabb_length[1] / aabb_length[0]).item(),\n z_ratio=(aabb_length[2] / aabb_length[0]).item(),\n size=2,\n black_bg=True,\n title=f\"Predicted Flow\",\n )\n gt_figure = vis_occ_plotly(\n vis_aabb=vis_voxel_aabb.cpu().numpy().tolist(),\n dynamic_coords=dynamic_coords,\n dynamic_colors=gt_flow_colors,\n x_ratio=1,\n y_ratio=(aabb_length[1] / aabb_length[0]).item(),\n z_ratio=(aabb_length[2] / aabb_length[0]).item(),\n size=2,\n black_bg=True,\n title=f\"GT Flow\",\n )\n if save_html:\n output_path = os.path.join(cfg.log_dir, f\"predicted_flow.html\")\n pred_figure.write_html(output_path)\n logger.info(f\"Predicted flow result saved to {output_path}\")\n output_path = os.path.join(cfg.log_dir, f\"gt_flow.html\")\n gt_figure.write_html(output_path)\n logger.info(f\"GT flow saved to {output_path}\")" } ]
import argparse import json import logging import os import time import imageio import numpy as np import torch import torch.utils.data import builders import loss import utils.misc as misc import wandb from typing import List, Optional from omegaconf import OmegaConf from tqdm import tqdm from datasets import metrics from datasets.base import SceneDataset from radiance_fields import DensityField, RadianceField from radiance_fields.render_utils import render_rays from radiance_fields.video_utils import render_pixels, save_videos from third_party.nerfacc_prop_net import PropNetEstimator, get_proposal_requires_grad_fn from utils.logging import MetricLogger, setup_logging from utils.visualization_tools import visualize_voxels, visualize_scene_flow from datasets.waymo import WaymoDataset from datasets.nuscenes import NuScenesDataset
19,783
help="Render a data video", ) parser.add_argument( "--render_data_video_only", action="store_true", help="Quit after rendering a data video", ) parser.add_argument( "--render_video_postfix", type=str, default=None, help="an optional postfix for video", ) parser.add_argument( "--output_root", default="./work_dirs/", help="path to save checkpoints and logs", type=str, ) # wandb logging part parser.add_argument( "--enable_wandb", action="store_true", help="enable wandb logging" ) parser.add_argument( "--entity", default="YOUR ENTITY NAME", type=str, help="wandb entity name", required=False, ) parser.add_argument( "--project", default="emernerf", type=str, help="wandb project name, also used to enhance log_dir", required=True, ) parser.add_argument( "--run_name", default="debug", type=str, help="wandb run name, also used to enhance log_dir", required=True, ) parser.add_argument( "opts", help="Modify config options using the command-line", default=None, nargs=argparse.REMAINDER, ) return parser def setup(args): # ------ get config from args -------- # default_config = OmegaConf.create(OmegaConf.load("configs/default_config.yaml")) cfg = OmegaConf.load(args.config_file) cfg = OmegaConf.merge(default_config, cfg, OmegaConf.from_cli(args.opts)) log_dir = os.path.join(args.output_root, args.project, args.run_name) cfg.log_dir = log_dir cfg.nerf.model.num_cams = cfg.data.pixel_source.num_cams cfg.nerf.model.unbounded = cfg.nerf.unbounded cfg.nerf.propnet.unbounded = cfg.nerf.unbounded cfg.nerf.model.resume_from = cfg.resume_from os.makedirs(log_dir, exist_ok=True) for folder in [ "images", "full_videos", "test_videos", "lowres_videos", "metrics", "configs_bk", "buffer_maps", ]: os.makedirs(os.path.join(log_dir, folder), exist_ok=True) # ------ setup logging -------- # if args.enable_wandb: # sometimes wandb fails to init in cloud machines, so we give it several (many) tries while ( wandb.init( project=args.project, entity=args.entity, sync_tensorboard=True, settings=wandb.Settings(start_method="fork"), ) is not wandb.run ): continue wandb.run.name = args.run_name wandb.run.save() wandb.config.update(OmegaConf.to_container(cfg, resolve=True)) wandb.config.update(args) misc.fix_random_seeds(cfg.optim.seed) global logger setup_logging(output=log_dir, level=logging.INFO, time_string=current_time) logger.info( "\n".join("%s: %s" % (k, str(v)) for k, v in sorted(dict(vars(args)).items())) ) # -------- write config -------- # logger.info(f"Config:\n{OmegaConf.to_yaml(cfg)}") saved_cfg_path = os.path.join(log_dir, "config.yaml") with open(saved_cfg_path, "w") as f: OmegaConf.save(config=cfg, f=f) # also save a backup copy saved_cfg_path_bk = os.path.join( log_dir, "configs_bk", f"config_{current_time}.yaml" ) with open(saved_cfg_path_bk, "w") as f: OmegaConf.save(config=cfg, f=f) logger.info(f"Full config saved to {saved_cfg_path}, and {saved_cfg_path_bk}") return cfg @torch.no_grad() def do_evaluation( step: int = 0, cfg: OmegaConf = None, model: RadianceField = None,
logger = logging.getLogger() current_time = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime()) # a global list of keys to render, # comment out the keys you don't want to render or uncomment the keys you want to render render_keys = [ "gt_rgbs", "rgbs", "depths", # "median_depths", "gt_dino_feats", "dino_feats", "dynamic_rgbs", "dynamic_depths", "static_rgbs", "static_depths", "forward_flows", "backward_flows", "dynamic_rgb_on_static_dinos", "dino_pe", "dino_feats_pe_free", # "dynamic_dino_on_static_rgbs", # "shadow_reduced_static_rgbs", # "shadow_only_static_rgbs", # "shadows", # "gt_sky_masks", # "sky_masks", ] def get_args_parser(): parser = argparse.ArgumentParser("Train EmernNerf for a single scene") parser.add_argument("--config_file", help="path to config file", type=str) parser.add_argument( "--eval_only", action="store_true", help="perform evaluation only" ) parser.add_argument( "--visualize_voxel", action="store_true", help="perform evaluation only" ) parser.add_argument( "--render_data_video", action="store_true", help="Render a data video", ) parser.add_argument( "--render_data_video_only", action="store_true", help="Quit after rendering a data video", ) parser.add_argument( "--render_video_postfix", type=str, default=None, help="an optional postfix for video", ) parser.add_argument( "--output_root", default="./work_dirs/", help="path to save checkpoints and logs", type=str, ) # wandb logging part parser.add_argument( "--enable_wandb", action="store_true", help="enable wandb logging" ) parser.add_argument( "--entity", default="YOUR ENTITY NAME", type=str, help="wandb entity name", required=False, ) parser.add_argument( "--project", default="emernerf", type=str, help="wandb project name, also used to enhance log_dir", required=True, ) parser.add_argument( "--run_name", default="debug", type=str, help="wandb run name, also used to enhance log_dir", required=True, ) parser.add_argument( "opts", help="Modify config options using the command-line", default=None, nargs=argparse.REMAINDER, ) return parser def setup(args): # ------ get config from args -------- # default_config = OmegaConf.create(OmegaConf.load("configs/default_config.yaml")) cfg = OmegaConf.load(args.config_file) cfg = OmegaConf.merge(default_config, cfg, OmegaConf.from_cli(args.opts)) log_dir = os.path.join(args.output_root, args.project, args.run_name) cfg.log_dir = log_dir cfg.nerf.model.num_cams = cfg.data.pixel_source.num_cams cfg.nerf.model.unbounded = cfg.nerf.unbounded cfg.nerf.propnet.unbounded = cfg.nerf.unbounded cfg.nerf.model.resume_from = cfg.resume_from os.makedirs(log_dir, exist_ok=True) for folder in [ "images", "full_videos", "test_videos", "lowres_videos", "metrics", "configs_bk", "buffer_maps", ]: os.makedirs(os.path.join(log_dir, folder), exist_ok=True) # ------ setup logging -------- # if args.enable_wandb: # sometimes wandb fails to init in cloud machines, so we give it several (many) tries while ( wandb.init( project=args.project, entity=args.entity, sync_tensorboard=True, settings=wandb.Settings(start_method="fork"), ) is not wandb.run ): continue wandb.run.name = args.run_name wandb.run.save() wandb.config.update(OmegaConf.to_container(cfg, resolve=True)) wandb.config.update(args) misc.fix_random_seeds(cfg.optim.seed) global logger setup_logging(output=log_dir, level=logging.INFO, time_string=current_time) logger.info( "\n".join("%s: %s" % (k, str(v)) for k, v in sorted(dict(vars(args)).items())) ) # -------- write config -------- # logger.info(f"Config:\n{OmegaConf.to_yaml(cfg)}") saved_cfg_path = os.path.join(log_dir, "config.yaml") with open(saved_cfg_path, "w") as f: OmegaConf.save(config=cfg, f=f) # also save a backup copy saved_cfg_path_bk = os.path.join( log_dir, "configs_bk", f"config_{current_time}.yaml" ) with open(saved_cfg_path_bk, "w") as f: OmegaConf.save(config=cfg, f=f) logger.info(f"Full config saved to {saved_cfg_path}, and {saved_cfg_path_bk}") return cfg @torch.no_grad() def do_evaluation( step: int = 0, cfg: OmegaConf = None, model: RadianceField = None,
proposal_networks: Optional[List[DensityField]] = None,
2
2023-10-11 20:56:27+00:00
24k
alibaba-damo-academy/FunCodec
funcodec/models/encoder/transformer_encoder.py
[ { "identifier": "AbsEncoder", "path": "funcodec/models/encoder/abs_encoder.py", "snippet": "class AbsEncoder(torch.nn.Module, ABC):\n @abstractmethod\n def output_size(self) -> int:\n raise NotImplementedError\n\n @abstractmethod\n def forward(\n self,\n xs_pad: torch.Tensor,\n ilens: torch.Tensor,\n prev_states: torch.Tensor = None,\n ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:\n raise NotImplementedError" }, { "identifier": "MultiHeadedAttention", "path": "funcodec/modules/attention.py", "snippet": "class MultiHeadedAttention(nn.Module):\n \"\"\"Multi-Head Attention layer.\n\n Args:\n n_head (int): The number of heads.\n n_feat (int): The number of features.\n dropout_rate (float): Dropout rate.\n\n \"\"\"\n\n def __init__(self, n_head, n_feat, dropout_rate):\n \"\"\"Construct an MultiHeadedAttention object.\"\"\"\n super(MultiHeadedAttention, self).__init__()\n assert n_feat % n_head == 0\n # We assume d_v always equals d_k\n self.d_k = n_feat // n_head\n self.h = n_head\n self.linear_q = nn.Linear(n_feat, n_feat)\n self.linear_k = nn.Linear(n_feat, n_feat)\n self.linear_v = nn.Linear(n_feat, n_feat)\n self.linear_out = nn.Linear(n_feat, n_feat)\n self.attn = None\n self.dropout = nn.Dropout(p=dropout_rate)\n\n def forward_qkv(self, query, key, value):\n \"\"\"Transform query, key and value.\n\n Args:\n query (torch.Tensor): Query tensor (#batch, time1, size).\n key (torch.Tensor): Key tensor (#batch, time2, size).\n value (torch.Tensor): Value tensor (#batch, time2, size).\n\n Returns:\n torch.Tensor: Transformed query tensor (#batch, n_head, time1, d_k).\n torch.Tensor: Transformed key tensor (#batch, n_head, time2, d_k).\n torch.Tensor: Transformed value tensor (#batch, n_head, time2, d_k).\n\n \"\"\"\n n_batch = query.size(0)\n q = self.linear_q(query).view(n_batch, -1, self.h, self.d_k)\n k = self.linear_k(key).view(n_batch, -1, self.h, self.d_k)\n v = self.linear_v(value).view(n_batch, -1, self.h, self.d_k)\n q = q.transpose(1, 2) # (batch, head, time1, d_k)\n k = k.transpose(1, 2) # (batch, head, time2, d_k)\n v = v.transpose(1, 2) # (batch, head, time2, d_k)\n\n return q, k, v\n\n def forward_attention(self, value, scores, mask):\n \"\"\"Compute attention context vector.\n\n Args:\n value (torch.Tensor): Transformed value (#batch, n_head, time2, d_k).\n scores (torch.Tensor): Attention score (#batch, n_head, time1, time2).\n mask (torch.Tensor): Mask (#batch, 1, time2) or (#batch, time1, time2).\n\n Returns:\n torch.Tensor: Transformed value (#batch, time1, d_model)\n weighted by the attention score (#batch, time1, time2).\n\n \"\"\"\n n_batch = value.size(0)\n if mask is not None:\n mask = mask.unsqueeze(1).eq(0) # (batch, 1, *, time2)\n min_value = float(\n numpy.finfo(torch.tensor(0, dtype=scores.dtype).numpy().dtype).min\n )\n scores = scores.masked_fill(mask, min_value)\n self.attn = torch.softmax(scores, dim=-1).masked_fill(\n mask, 0.0\n ) # (batch, head, time1, time2)\n else:\n self.attn = torch.softmax(scores, dim=-1) # (batch, head, time1, time2)\n\n p_attn = self.dropout(self.attn)\n x = torch.matmul(p_attn, value) # (batch, head, time1, d_k)\n x = (\n x.transpose(1, 2).contiguous().view(n_batch, -1, self.h * self.d_k)\n ) # (batch, time1, d_model)\n\n return self.linear_out(x) # (batch, time1, d_model)\n\n def forward(self, query, key, value, mask):\n \"\"\"Compute scaled dot product attention.\n\n Args:\n query (torch.Tensor): Query tensor (#batch, time1, size).\n key (torch.Tensor): Key tensor (#batch, time2, size).\n value (torch.Tensor): Value tensor (#batch, time2, size).\n mask (torch.Tensor): Mask tensor (#batch, 1, time2) or\n (#batch, time1, time2).\n\n Returns:\n torch.Tensor: Output tensor (#batch, time1, d_model).\n\n \"\"\"\n q, k, v = self.forward_qkv(query, key, value)\n scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_k)\n return self.forward_attention(v, scores, mask)" }, { "identifier": "RelPositionMultiHeadedAttention", "path": "funcodec/modules/attention.py", "snippet": "class RelPositionMultiHeadedAttention(MultiHeadedAttention):\n \"\"\"Multi-Head Attention layer with relative position encoding (new implementation).\n\n Details can be found in https://github.com/espnet/espnet/pull/2816.\n\n Paper: https://arxiv.org/abs/1901.02860\n\n Args:\n n_head (int): The number of heads.\n n_feat (int): The number of features.\n dropout_rate (float): Dropout rate.\n zero_triu (bool): Whether to zero the upper triangular part of attention matrix.\n\n \"\"\"\n\n def __init__(self, n_head, n_feat, dropout_rate, zero_triu=False):\n \"\"\"Construct an RelPositionMultiHeadedAttention object.\"\"\"\n super().__init__(n_head, n_feat, dropout_rate)\n self.zero_triu = zero_triu\n # linear transformation for positional encoding\n self.linear_pos = nn.Linear(n_feat, n_feat, bias=False)\n # these two learnable bias are used in matrix c and matrix d\n # as described in https://arxiv.org/abs/1901.02860 Section 3.3\n self.pos_bias_u = nn.Parameter(torch.Tensor(self.h, self.d_k))\n self.pos_bias_v = nn.Parameter(torch.Tensor(self.h, self.d_k))\n torch.nn.init.xavier_uniform_(self.pos_bias_u)\n torch.nn.init.xavier_uniform_(self.pos_bias_v)\n\n def rel_shift(self, x):\n \"\"\"Compute relative positional encoding.\n\n Args:\n x (torch.Tensor): Input tensor (batch, head, time1, 2*time1-1).\n time1 means the length of query vector.\n\n Returns:\n torch.Tensor: Output tensor.\n\n \"\"\"\n zero_pad = torch.zeros((*x.size()[:3], 1), device=x.device, dtype=x.dtype)\n x_padded = torch.cat([zero_pad, x], dim=-1)\n\n x_padded = x_padded.view(*x.size()[:2], x.size(3) + 1, x.size(2))\n x = x_padded[:, :, 1:].view_as(x)[\n :, :, :, : x.size(-1) // 2 + 1\n ] # only keep the positions from 0 to time2\n\n if self.zero_triu:\n ones = torch.ones((x.size(2), x.size(3)), device=x.device)\n x = x * torch.tril(ones, x.size(3) - x.size(2))[None, None, :, :]\n\n return x\n\n def forward(self, query, key, value, pos_emb, mask):\n \"\"\"Compute 'Scaled Dot Product Attention' with rel. positional encoding.\n\n Args:\n query (torch.Tensor): Query tensor (#batch, time1, size).\n key (torch.Tensor): Key tensor (#batch, time2, size).\n value (torch.Tensor): Value tensor (#batch, time2, size).\n pos_emb (torch.Tensor): Positional embedding tensor\n (#batch, 2*time1-1, size).\n mask (torch.Tensor): Mask tensor (#batch, 1, time2) or\n (#batch, time1, time2).\n\n Returns:\n torch.Tensor: Output tensor (#batch, time1, d_model).\n\n \"\"\"\n q, k, v = self.forward_qkv(query, key, value)\n q = q.transpose(1, 2) # (batch, time1, head, d_k)\n\n n_batch_pos = pos_emb.size(0)\n p = self.linear_pos(pos_emb).view(n_batch_pos, -1, self.h, self.d_k)\n p = p.transpose(1, 2) # (batch, head, 2*time1-1, d_k)\n\n # (batch, head, time1, d_k)\n q_with_bias_u = (q + self.pos_bias_u).transpose(1, 2)\n # (batch, head, time1, d_k)\n q_with_bias_v = (q + self.pos_bias_v).transpose(1, 2)\n\n # compute attention score\n # first compute matrix a and matrix c\n # as described in https://arxiv.org/abs/1901.02860 Section 3.3\n # (batch, head, time1, time2)\n matrix_ac = torch.matmul(q_with_bias_u, k.transpose(-2, -1))\n\n # compute matrix b and matrix d\n # (batch, head, time1, 2*time1-1)\n matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1))\n matrix_bd = self.rel_shift(matrix_bd)\n\n scores = (matrix_ac + matrix_bd) / math.sqrt(\n self.d_k\n ) # (batch, head, time1, time2)\n\n return self.forward_attention(v, scores, mask)" }, { "identifier": "LegacyRelPositionMultiHeadedAttention", "path": "funcodec/modules/attention.py", "snippet": "class LegacyRelPositionMultiHeadedAttention(MultiHeadedAttention):\n \"\"\"Multi-Head Attention layer with relative position encoding (old version).\n\n Details can be found in https://github.com/espnet/espnet/pull/2816.\n\n Paper: https://arxiv.org/abs/1901.02860\n\n Args:\n n_head (int): The number of heads.\n n_feat (int): The number of features.\n dropout_rate (float): Dropout rate.\n zero_triu (bool): Whether to zero the upper triangular part of attention matrix.\n\n \"\"\"\n\n def __init__(self, n_head, n_feat, dropout_rate, zero_triu=False):\n \"\"\"Construct an RelPositionMultiHeadedAttention object.\"\"\"\n super().__init__(n_head, n_feat, dropout_rate)\n self.zero_triu = zero_triu\n # linear transformation for positional encoding\n self.linear_pos = nn.Linear(n_feat, n_feat, bias=False)\n # these two learnable bias are used in matrix c and matrix d\n # as described in https://arxiv.org/abs/1901.02860 Section 3.3\n self.pos_bias_u = nn.Parameter(torch.Tensor(self.h, self.d_k))\n self.pos_bias_v = nn.Parameter(torch.Tensor(self.h, self.d_k))\n torch.nn.init.xavier_uniform_(self.pos_bias_u)\n torch.nn.init.xavier_uniform_(self.pos_bias_v)\n\n def rel_shift(self, x):\n \"\"\"Compute relative positional encoding.\n\n Args:\n x (torch.Tensor): Input tensor (batch, head, time1, time2).\n\n Returns:\n torch.Tensor: Output tensor.\n\n \"\"\"\n zero_pad = torch.zeros((*x.size()[:3], 1), device=x.device, dtype=x.dtype)\n x_padded = torch.cat([zero_pad, x], dim=-1)\n\n x_padded = x_padded.view(*x.size()[:2], x.size(3) + 1, x.size(2))\n x = x_padded[:, :, 1:].view_as(x)\n\n if self.zero_triu:\n ones = torch.ones((x.size(2), x.size(3)))\n x = x * torch.tril(ones, x.size(3) - x.size(2))[None, None, :, :]\n\n return x\n\n def forward(self, query, key, value, pos_emb, mask):\n \"\"\"Compute 'Scaled Dot Product Attention' with rel. positional encoding.\n\n Args:\n query (torch.Tensor): Query tensor (#batch, time1, size).\n key (torch.Tensor): Key tensor (#batch, time2, size).\n value (torch.Tensor): Value tensor (#batch, time2, size).\n pos_emb (torch.Tensor): Positional embedding tensor (#batch, time1, size).\n mask (torch.Tensor): Mask tensor (#batch, 1, time2) or\n (#batch, time1, time2).\n\n Returns:\n torch.Tensor: Output tensor (#batch, time1, d_model).\n\n \"\"\"\n q, k, v = self.forward_qkv(query, key, value)\n q = q.transpose(1, 2) # (batch, time1, head, d_k)\n\n n_batch_pos = pos_emb.size(0)\n p = self.linear_pos(pos_emb).view(n_batch_pos, -1, self.h, self.d_k)\n p = p.transpose(1, 2) # (batch, head, time1, d_k)\n\n # (batch, head, time1, d_k)\n q_with_bias_u = (q + self.pos_bias_u).transpose(1, 2)\n # (batch, head, time1, d_k)\n q_with_bias_v = (q + self.pos_bias_v).transpose(1, 2)\n\n # compute attention score\n # first compute matrix a and matrix c\n # as described in https://arxiv.org/abs/1901.02860 Section 3.3\n # (batch, head, time1, time2)\n matrix_ac = torch.matmul(q_with_bias_u, k.transpose(-2, -1))\n\n # compute matrix b and matrix d\n # (batch, head, time1, time1)\n matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1))\n matrix_bd = self.rel_shift(matrix_bd)\n\n scores = (matrix_ac + matrix_bd) / math.sqrt(\n self.d_k\n ) # (batch, head, time1, time2)\n\n return self.forward_attention(v, scores, mask)" }, { "identifier": "LayerNorm", "path": "funcodec/modules/layer_norm.py", "snippet": "class LayerNorm(torch.nn.LayerNorm):\n \"\"\"Layer normalization module.\n\n Args:\n nout (int): Output dim size.\n dim (int): Dimension to be normalized.\n\n \"\"\"\n\n def __init__(self, nout, dim=-1):\n \"\"\"Construct an LayerNorm object.\"\"\"\n super(LayerNorm, self).__init__(nout, eps=1e-12)\n self.dim = dim\n\n def forward(self, x):\n \"\"\"Apply layer normalization.\n\n Args:\n x (torch.Tensor): Input tensor.\n\n Returns:\n torch.Tensor: Normalized tensor.\n\n \"\"\"\n if self.dim == -1:\n return super(LayerNorm, self).forward(x)\n return (\n super(LayerNorm, self)\n .forward(x.transpose(self.dim, -1))\n .transpose(self.dim, -1)\n )" }, { "identifier": "Conv1dLinear", "path": "funcodec/modules/multi_layer_conv.py", "snippet": "class Conv1dLinear(torch.nn.Module):\n \"\"\"Conv1D + Linear for Transformer block.\n\n A variant of MultiLayeredConv1d, which replaces second conv-layer to linear.\n\n \"\"\"\n\n def __init__(self, in_chans, hidden_chans, kernel_size, dropout_rate):\n \"\"\"Initialize Conv1dLinear module.\n\n Args:\n in_chans (int): Number of input channels.\n hidden_chans (int): Number of hidden channels.\n kernel_size (int): Kernel size of conv1d.\n dropout_rate (float): Dropout rate.\n\n \"\"\"\n super(Conv1dLinear, self).__init__()\n self.w_1 = torch.nn.Conv1d(\n in_chans,\n hidden_chans,\n kernel_size,\n stride=1,\n padding=(kernel_size - 1) // 2,\n )\n self.w_2 = torch.nn.Linear(hidden_chans, in_chans)\n self.dropout = torch.nn.Dropout(dropout_rate)\n\n def forward(self, x):\n \"\"\"Calculate forward propagation.\n\n Args:\n x (torch.Tensor): Batch of input tensors (B, T, in_chans).\n\n Returns:\n torch.Tensor: Batch of output tensors (B, T, hidden_chans).\n\n \"\"\"\n x = torch.relu(self.w_1(x.transpose(-1, 1))).transpose(-1, 1)\n return self.w_2(self.dropout(x))" }, { "identifier": "MultiLayeredConv1d", "path": "funcodec/modules/multi_layer_conv.py", "snippet": "class MultiLayeredConv1d(torch.nn.Module):\n \"\"\"Multi-layered conv1d for Transformer block.\n\n This is a module of multi-leyered conv1d designed\n to replace positionwise feed-forward network\n in Transforner block, which is introduced in\n `FastSpeech: Fast, Robust and Controllable Text to Speech`_.\n\n .. _`FastSpeech: Fast, Robust and Controllable Text to Speech`:\n https://arxiv.org/pdf/1905.09263.pdf\n\n \"\"\"\n\n def __init__(self, in_chans, hidden_chans, kernel_size, dropout_rate):\n \"\"\"Initialize MultiLayeredConv1d module.\n\n Args:\n in_chans (int): Number of input channels.\n hidden_chans (int): Number of hidden channels.\n kernel_size (int): Kernel size of conv1d.\n dropout_rate (float): Dropout rate.\n\n \"\"\"\n super(MultiLayeredConv1d, self).__init__()\n self.w_1 = torch.nn.Conv1d(\n in_chans,\n hidden_chans,\n kernel_size,\n stride=1,\n padding=(kernel_size - 1) // 2,\n )\n self.w_2 = torch.nn.Conv1d(\n hidden_chans,\n in_chans,\n kernel_size,\n stride=1,\n padding=(kernel_size - 1) // 2,\n )\n self.dropout = torch.nn.Dropout(dropout_rate)\n\n def forward(self, x):\n \"\"\"Calculate forward propagation.\n\n Args:\n x (torch.Tensor): Batch of input tensors (B, T, in_chans).\n\n Returns:\n torch.Tensor: Batch of output tensors (B, T, hidden_chans).\n\n \"\"\"\n x = torch.relu(self.w_1(x.transpose(-1, 1))).transpose(-1, 1)\n return self.w_2(self.dropout(x).transpose(-1, 1)).transpose(-1, 1)" }, { "identifier": "make_pad_mask", "path": "funcodec/modules/nets_utils.py", "snippet": "def make_pad_mask(lengths, xs=None, length_dim=-1, maxlen=None):\n \"\"\"Make mask tensor containing indices of padded part.\n\n Args:\n lengths (LongTensor or List): Batch of lengths (B,).\n xs (Tensor, optional): The reference tensor.\n If set, masks will be the same shape as this tensor.\n length_dim (int, optional): Dimension indicator of the above tensor.\n See the example.\n\n Returns:\n Tensor: Mask tensor containing indices of padded part.\n dtype=torch.uint8 in PyTorch 1.2-\n dtype=torch.bool in PyTorch 1.2+ (including 1.2)\n\n Examples:\n With only lengths.\n\n >>> lengths = [5, 3, 2]\n >>> make_pad_mask(lengths)\n masks = [[0, 0, 0, 0 ,0],\n [0, 0, 0, 1, 1],\n [0, 0, 1, 1, 1]]\n\n With the reference tensor.\n\n >>> xs = torch.zeros((3, 2, 4))\n >>> make_pad_mask(lengths, xs)\n tensor([[[0, 0, 0, 0],\n [0, 0, 0, 0]],\n [[0, 0, 0, 1],\n [0, 0, 0, 1]],\n [[0, 0, 1, 1],\n [0, 0, 1, 1]]], dtype=torch.uint8)\n >>> xs = torch.zeros((3, 2, 6))\n >>> make_pad_mask(lengths, xs)\n tensor([[[0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 1]],\n [[0, 0, 0, 1, 1, 1],\n [0, 0, 0, 1, 1, 1]],\n [[0, 0, 1, 1, 1, 1],\n [0, 0, 1, 1, 1, 1]]], dtype=torch.uint8)\n\n With the reference tensor and dimension indicator.\n\n >>> xs = torch.zeros((3, 6, 6))\n >>> make_pad_mask(lengths, xs, 1)\n tensor([[[0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [1, 1, 1, 1, 1, 1]],\n [[0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1]],\n [[0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1]]], dtype=torch.uint8)\n >>> make_pad_mask(lengths, xs, 2)\n tensor([[[0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 1]],\n [[0, 0, 0, 1, 1, 1],\n [0, 0, 0, 1, 1, 1],\n [0, 0, 0, 1, 1, 1],\n [0, 0, 0, 1, 1, 1],\n [0, 0, 0, 1, 1, 1],\n [0, 0, 0, 1, 1, 1]],\n [[0, 0, 1, 1, 1, 1],\n [0, 0, 1, 1, 1, 1],\n [0, 0, 1, 1, 1, 1],\n [0, 0, 1, 1, 1, 1],\n [0, 0, 1, 1, 1, 1],\n [0, 0, 1, 1, 1, 1]]], dtype=torch.uint8)\n\n \"\"\"\n if length_dim == 0:\n raise ValueError(\"length_dim cannot be 0: {}\".format(length_dim))\n\n if not isinstance(lengths, list):\n lengths = lengths.tolist()\n bs = int(len(lengths))\n if maxlen is None:\n if xs is None:\n maxlen = int(max(lengths))\n else:\n maxlen = xs.size(length_dim)\n else:\n assert xs is None\n assert maxlen >= int(max(lengths))\n\n seq_range = torch.arange(0, maxlen, dtype=torch.int64)\n seq_range_expand = seq_range.unsqueeze(0).expand(bs, maxlen)\n seq_length_expand = seq_range_expand.new(lengths).unsqueeze(-1)\n mask = seq_range_expand >= seq_length_expand\n\n if xs is not None:\n assert xs.size(0) == bs, (xs.size(0), bs)\n\n if length_dim < 0:\n length_dim = xs.dim() + length_dim\n # ind = (:, None, ..., None, :, , None, ..., None)\n ind = tuple(\n slice(None) if i in (0, length_dim) else None for i in range(xs.dim())\n )\n mask = mask[ind].expand_as(xs).to(xs.device)\n return mask" }, { "identifier": "PositionalEncoding", "path": "funcodec/modules/embedding.py", "snippet": "class PositionalEncoding(torch.nn.Module):\n \"\"\"Positional encoding.\n\n Args:\n d_model (int): Embedding dimension.\n dropout_rate (float): Dropout rate.\n max_len (int): Maximum input length.\n reverse (bool): Whether to reverse the input position. Only for\n the class LegacyRelPositionalEncoding. We remove it in the current\n class RelPositionalEncoding.\n \"\"\"\n\n def __init__(self, d_model, dropout_rate, max_len=5000, reverse=False):\n \"\"\"Construct an PositionalEncoding object.\"\"\"\n super(PositionalEncoding, self).__init__()\n self.d_model = d_model\n self.reverse = reverse\n self.xscale = math.sqrt(self.d_model)\n self.dropout = torch.nn.Dropout(p=dropout_rate)\n self.pe = None\n self.extend_pe(torch.tensor(0.0).expand(1, max_len))\n self._register_load_state_dict_pre_hook(_pre_hook)\n\n def extend_pe(self, x):\n \"\"\"Reset the positional encodings.\"\"\"\n if self.pe is not None:\n if self.pe.size(1) >= x.size(1):\n if self.pe.dtype != x.dtype or self.pe.device != x.device:\n self.pe = self.pe.to(dtype=x.dtype, device=x.device)\n return\n pe = torch.zeros(x.size(1), self.d_model)\n if self.reverse:\n position = torch.arange(\n x.size(1) - 1, -1, -1.0, dtype=torch.float32\n ).unsqueeze(1)\n else:\n position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)\n div_term = torch.exp(\n torch.arange(0, self.d_model, 2, dtype=torch.float32)\n * -(math.log(10000.0) / self.d_model)\n )\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0)\n self.pe = pe.to(device=x.device, dtype=x.dtype)\n\n def forward(self, x: torch.Tensor):\n \"\"\"Add positional encoding.\n\n Args:\n x (torch.Tensor): Input tensor (batch, time, `*`).\n\n Returns:\n torch.Tensor: Encoded tensor (batch, time, `*`).\n \"\"\"\n self.extend_pe(x)\n x = x * self.xscale + self.pe[:, : x.size(1)]\n return self.dropout(x)" }, { "identifier": "ScaledPositionalEncoding", "path": "funcodec/modules/embedding.py", "snippet": "class ScaledPositionalEncoding(PositionalEncoding):\n \"\"\"Scaled positional encoding module.\n\n See Sec. 3.2 https://arxiv.org/abs/1809.08895\n\n Args:\n d_model (int): Embedding dimension.\n dropout_rate (float): Dropout rate.\n max_len (int): Maximum input length.\n\n \"\"\"\n\n def __init__(self, d_model, dropout_rate, max_len=5000):\n \"\"\"Initialize class.\"\"\"\n super().__init__(d_model=d_model, dropout_rate=dropout_rate, max_len=max_len)\n self.alpha = torch.nn.Parameter(torch.tensor(1.0))\n\n def reset_parameters(self):\n \"\"\"Reset parameters.\"\"\"\n self.alpha.data = torch.tensor(1.0)\n\n def forward(self, x):\n \"\"\"Add positional encoding.\n\n Args:\n x (torch.Tensor): Input tensor (batch, time, `*`).\n\n Returns:\n torch.Tensor: Encoded tensor (batch, time, `*`).\n\n \"\"\"\n self.extend_pe(x)\n x = x + self.alpha * self.pe[:, : x.size(1)]\n return self.dropout(x)" }, { "identifier": "RelPositionalEncoding", "path": "funcodec/modules/embedding.py", "snippet": "class RelPositionalEncoding(torch.nn.Module):\n \"\"\"Relative positional encoding module (new implementation).\n\n Details can be found in https://github.com/espnet/espnet/pull/2816.\n\n See : Appendix B in https://arxiv.org/abs/1901.02860\n\n Args:\n d_model (int): Embedding dimension.\n dropout_rate (float): Dropout rate.\n max_len (int): Maximum input length.\n\n \"\"\"\n\n def __init__(self, d_model, dropout_rate, max_len=5000):\n \"\"\"Construct an PositionalEncoding object.\"\"\"\n super(RelPositionalEncoding, self).__init__()\n self.d_model = d_model\n self.xscale = math.sqrt(self.d_model)\n self.dropout = torch.nn.Dropout(p=dropout_rate)\n self.pe = None\n self.extend_pe(torch.tensor(0.0).expand(1, max_len))\n\n def extend_pe(self, x):\n \"\"\"Reset the positional encodings.\"\"\"\n if self.pe is not None:\n # self.pe contains both positive and negative parts\n # the length of self.pe is 2 * input_len - 1\n if self.pe.size(1) >= x.size(1) * 2 - 1:\n if self.pe.dtype != x.dtype or self.pe.device != x.device:\n self.pe = self.pe.to(dtype=x.dtype, device=x.device)\n return\n # Suppose `i` means to the position of query vecotr and `j` means the\n # position of key vector. We use position relative positions when keys\n # are to the left (i>j) and negative relative positions otherwise (i<j).\n pe_positive = torch.zeros(x.size(1), self.d_model)\n pe_negative = torch.zeros(x.size(1), self.d_model)\n position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)\n div_term = torch.exp(\n torch.arange(0, self.d_model, 2, dtype=torch.float32)\n * -(math.log(10000.0) / self.d_model)\n )\n pe_positive[:, 0::2] = torch.sin(position * div_term)\n pe_positive[:, 1::2] = torch.cos(position * div_term)\n pe_negative[:, 0::2] = torch.sin(-1 * position * div_term)\n pe_negative[:, 1::2] = torch.cos(-1 * position * div_term)\n\n # Reserve the order of positive indices and concat both positive and\n # negative indices. This is used to support the shifting trick\n # as in https://arxiv.org/abs/1901.02860\n pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0)\n pe_negative = pe_negative[1:].unsqueeze(0)\n pe = torch.cat([pe_positive, pe_negative], dim=1)\n self.pe = pe.to(device=x.device, dtype=x.dtype)\n\n def forward(self, x: torch.Tensor):\n \"\"\"Add positional encoding.\n\n Args:\n x (torch.Tensor): Input tensor (batch, time, `*`).\n\n Returns:\n torch.Tensor: Encoded tensor (batch, time, `*`).\n\n \"\"\"\n self.extend_pe(x)\n x = x * self.xscale\n pos_emb = self.pe[\n :,\n self.pe.size(1) // 2 - x.size(1) + 1 : self.pe.size(1) // 2 + x.size(1),\n ]\n return self.dropout(x), self.dropout(pos_emb)" }, { "identifier": "LegacyRelPositionalEncoding", "path": "funcodec/modules/embedding.py", "snippet": "class LegacyRelPositionalEncoding(PositionalEncoding):\n \"\"\"Relative positional encoding module (old version).\n\n Details can be found in https://github.com/espnet/espnet/pull/2816.\n\n See : Appendix B in https://arxiv.org/abs/1901.02860\n\n Args:\n d_model (int): Embedding dimension.\n dropout_rate (float): Dropout rate.\n max_len (int): Maximum input length.\n\n \"\"\"\n\n def __init__(self, d_model, dropout_rate, max_len=5000):\n \"\"\"Initialize class.\"\"\"\n super().__init__(\n d_model=d_model,\n dropout_rate=dropout_rate,\n max_len=max_len,\n reverse=True,\n )\n\n def forward(self, x):\n \"\"\"Compute positional encoding.\n\n Args:\n x (torch.Tensor): Input tensor (batch, time, `*`).\n\n Returns:\n torch.Tensor: Encoded tensor (batch, time, `*`).\n torch.Tensor: Positional embedding tensor (1, time, `*`).\n\n \"\"\"\n self.extend_pe(x)\n x = x * self.xscale\n pos_emb = self.pe[:, : x.size(1)]\n return self.dropout(x), self.dropout(pos_emb)" }, { "identifier": "PositionwiseFeedForward", "path": "funcodec/modules/positionwise_feed_forward.py", "snippet": "class PositionwiseFeedForward(torch.nn.Module):\n \"\"\"Positionwise feed forward layer.\n\n Args:\n idim (int): Input dimenstion.\n hidden_units (int): The number of hidden units.\n dropout_rate (float): Dropout rate.\n\n \"\"\"\n\n def __init__(self, idim, hidden_units, dropout_rate, activation=torch.nn.ReLU()):\n \"\"\"Construct an PositionwiseFeedForward object.\"\"\"\n super(PositionwiseFeedForward, self).__init__()\n self.w_1 = torch.nn.Linear(idim, hidden_units)\n self.w_2 = torch.nn.Linear(hidden_units, idim)\n self.dropout = torch.nn.Dropout(dropout_rate)\n self.activation = activation\n\n def forward(self, x):\n \"\"\"Forward function.\"\"\"\n return self.w_2(self.dropout(self.activation(self.w_1(x))))" }, { "identifier": "repeat", "path": "funcodec/modules/repeat.py", "snippet": "def repeat(N, fn):\n \"\"\"Repeat module N times.\n\n Args:\n N (int): Number of repeat time.\n fn (Callable): Function to generate module.\n\n Returns:\n MultiSequential: Repeated model instance.\n\n \"\"\"\n return MultiSequential(*[fn(n) for n in range(N)])" }, { "identifier": "rename_state_dict", "path": "funcodec/modules/nets_utils.py", "snippet": "def rename_state_dict(\n old_prefix: str, new_prefix: str, state_dict: Dict[str, torch.Tensor]\n):\n \"\"\"Replace keys of old prefix with new prefix in state dict.\"\"\"\n # need this list not to break the dict iterator\n old_keys = [k for k in state_dict if k.startswith(old_prefix)]\n if len(old_keys) > 0:\n logging.warning(f\"Rename: {old_prefix} -> {new_prefix}\")\n for k in old_keys:\n v = state_dict.pop(k)\n new_k = k.replace(old_prefix, new_prefix)\n state_dict[new_k] = v" }, { "identifier": "DynamicConvolution", "path": "funcodec/modules/dynamic_conv.py", "snippet": "class DynamicConvolution(nn.Module):\n \"\"\"Dynamic Convolution layer.\n\n This implementation is based on\n https://github.com/pytorch/fairseq/tree/master/fairseq\n\n Args:\n wshare (int): the number of kernel of convolution\n n_feat (int): the number of features\n dropout_rate (float): dropout_rate\n kernel_size (int): kernel size (length)\n use_kernel_mask (bool): Use causal mask or not for convolution kernel\n use_bias (bool): Use bias term or not.\n\n \"\"\"\n\n def __init__(\n self,\n wshare,\n n_feat,\n dropout_rate,\n kernel_size,\n use_kernel_mask=False,\n use_bias=False,\n ):\n \"\"\"Construct Dynamic Convolution layer.\"\"\"\n super(DynamicConvolution, self).__init__()\n\n assert n_feat % wshare == 0\n self.wshare = wshare\n self.use_kernel_mask = use_kernel_mask\n self.dropout_rate = dropout_rate\n self.kernel_size = kernel_size\n self.attn = None\n\n # linear -> GLU -- -> lightconv -> linear\n # \\ /\n # Linear\n self.linear1 = nn.Linear(n_feat, n_feat * 2)\n self.linear2 = nn.Linear(n_feat, n_feat)\n self.linear_weight = nn.Linear(n_feat, self.wshare * 1 * kernel_size)\n nn.init.xavier_uniform(self.linear_weight.weight)\n self.act = nn.GLU()\n\n # dynamic conv related\n self.use_bias = use_bias\n if self.use_bias:\n self.bias = nn.Parameter(torch.Tensor(n_feat))\n\n def forward(self, query, key, value, mask):\n \"\"\"Forward of 'Dynamic Convolution'.\n\n This function takes query, key and value but uses only quert.\n This is just for compatibility with self-attention layer (attention.py)\n\n Args:\n query (torch.Tensor): (batch, time1, d_model) input tensor\n key (torch.Tensor): (batch, time2, d_model) NOT USED\n value (torch.Tensor): (batch, time2, d_model) NOT USED\n mask (torch.Tensor): (batch, time1, time2) mask\n\n Return:\n x (torch.Tensor): (batch, time1, d_model) output\n\n \"\"\"\n # linear -> GLU -- -> lightconv -> linear\n # \\ /\n # Linear\n x = query\n B, T, C = x.size()\n H = self.wshare\n k = self.kernel_size\n\n # first liner layer\n x = self.linear1(x)\n\n # GLU activation\n x = self.act(x)\n\n # get kernel of convolution\n weight = self.linear_weight(x) # B x T x kH\n weight = F.dropout(weight, self.dropout_rate, training=self.training)\n weight = weight.view(B, T, H, k).transpose(1, 2).contiguous() # B x H x T x k\n weight_new = torch.zeros(B * H * T * (T + k - 1), dtype=weight.dtype)\n weight_new = weight_new.view(B, H, T, T + k - 1).fill_(float(\"-inf\"))\n weight_new = weight_new.to(x.device) # B x H x T x T+k-1\n weight_new.as_strided(\n (B, H, T, k), ((T + k - 1) * T * H, (T + k - 1) * T, T + k, 1)\n ).copy_(weight)\n weight_new = weight_new.narrow(-1, int((k - 1) / 2), T) # B x H x T x T(k)\n if self.use_kernel_mask:\n kernel_mask = torch.tril(torch.ones(T, T, device=x.device)).unsqueeze(0)\n weight_new = weight_new.masked_fill(kernel_mask == 0.0, float(\"-inf\"))\n weight_new = F.softmax(weight_new, dim=-1)\n self.attn = weight_new\n weight_new = weight_new.view(B * H, T, T)\n\n # convolution\n x = x.transpose(1, 2).contiguous() # B x C x T\n x = x.view(B * H, int(C / H), T).transpose(1, 2)\n x = torch.bmm(weight_new, x) # BH x T x C/H\n x = x.transpose(1, 2).contiguous().view(B, C, T)\n\n if self.use_bias:\n x = x + self.bias.view(1, -1, 1)\n x = x.transpose(1, 2) # B x T x C\n\n if mask is not None and not self.use_kernel_mask:\n mask = mask.transpose(-1, -2)\n x = x.masked_fill(mask == 0, 0.0)\n\n # second linear layer\n x = self.linear2(x)\n return x" }, { "identifier": "DynamicConvolution2D", "path": "funcodec/modules/dynamic_conv2d.py", "snippet": "class DynamicConvolution2D(nn.Module):\n \"\"\"Dynamic 2-Dimensional Convolution layer.\n\n This implementation is based on\n https://github.com/pytorch/fairseq/tree/master/fairseq\n\n Args:\n wshare (int): the number of kernel of convolution\n n_feat (int): the number of features\n dropout_rate (float): dropout_rate\n kernel_size (int): kernel size (length)\n use_kernel_mask (bool): Use causal mask or not for convolution kernel\n use_bias (bool): Use bias term or not.\n\n \"\"\"\n\n def __init__(\n self,\n wshare,\n n_feat,\n dropout_rate,\n kernel_size,\n use_kernel_mask=False,\n use_bias=False,\n ):\n \"\"\"Construct Dynamic 2-Dimensional Convolution layer.\"\"\"\n super(DynamicConvolution2D, self).__init__()\n\n assert n_feat % wshare == 0\n self.wshare = wshare\n self.use_kernel_mask = use_kernel_mask\n self.dropout_rate = dropout_rate\n self.kernel_size = kernel_size\n self.padding_size = int(kernel_size / 2)\n self.attn_t = None\n self.attn_f = None\n\n # linear -> GLU -- -> lightconv -> linear\n # \\ /\n # Linear\n self.linear1 = nn.Linear(n_feat, n_feat * 2)\n self.linear2 = nn.Linear(n_feat * 2, n_feat)\n self.linear_weight = nn.Linear(n_feat, self.wshare * 1 * kernel_size)\n nn.init.xavier_uniform(self.linear_weight.weight)\n self.linear_weight_f = nn.Linear(n_feat, kernel_size)\n nn.init.xavier_uniform(self.linear_weight_f.weight)\n self.act = nn.GLU()\n\n # dynamic conv related\n self.use_bias = use_bias\n if self.use_bias:\n self.bias = nn.Parameter(torch.Tensor(n_feat))\n\n def forward(self, query, key, value, mask):\n \"\"\"Forward of 'Dynamic 2-Dimensional Convolution'.\n\n This function takes query, key and value but uses only query.\n This is just for compatibility with self-attention layer (attention.py)\n\n Args:\n query (torch.Tensor): (batch, time1, d_model) input tensor\n key (torch.Tensor): (batch, time2, d_model) NOT USED\n value (torch.Tensor): (batch, time2, d_model) NOT USED\n mask (torch.Tensor): (batch, time1, time2) mask\n\n Return:\n x (torch.Tensor): (batch, time1, d_model) output\n\n \"\"\"\n # linear -> GLU -- -> lightconv -> linear\n # \\ /\n # Linear\n x = query\n B, T, C = x.size()\n H = self.wshare\n k = self.kernel_size\n\n # first liner layer\n x = self.linear1(x)\n\n # GLU activation\n x = self.act(x)\n\n # convolution of frequency axis\n weight_f = self.linear_weight_f(x).view(B * T, 1, k) # B x T x k\n self.attn_f = weight_f.view(B, T, k).unsqueeze(1)\n xf = F.conv1d(\n x.view(1, B * T, C), weight_f, padding=self.padding_size, groups=B * T\n )\n xf = xf.view(B, T, C)\n\n # get kernel of convolution\n weight = self.linear_weight(x) # B x T x kH\n weight = F.dropout(weight, self.dropout_rate, training=self.training)\n weight = weight.view(B, T, H, k).transpose(1, 2).contiguous() # B x H x T x k\n weight_new = torch.zeros(B * H * T * (T + k - 1), dtype=weight.dtype)\n weight_new = weight_new.view(B, H, T, T + k - 1).fill_(float(\"-inf\"))\n weight_new = weight_new.to(x.device) # B x H x T x T+k-1\n weight_new.as_strided(\n (B, H, T, k), ((T + k - 1) * T * H, (T + k - 1) * T, T + k, 1)\n ).copy_(weight)\n weight_new = weight_new.narrow(-1, int((k - 1) / 2), T) # B x H x T x T(k)\n if self.use_kernel_mask:\n kernel_mask = torch.tril(torch.ones(T, T, device=x.device)).unsqueeze(0)\n weight_new = weight_new.masked_fill(kernel_mask == 0.0, float(\"-inf\"))\n weight_new = F.softmax(weight_new, dim=-1)\n self.attn_t = weight_new\n weight_new = weight_new.view(B * H, T, T)\n\n # convolution\n x = x.transpose(1, 2).contiguous() # B x C x T\n x = x.view(B * H, int(C / H), T).transpose(1, 2)\n x = torch.bmm(weight_new, x)\n x = x.transpose(1, 2).contiguous().view(B, C, T)\n\n if self.use_bias:\n x = x + self.bias.view(1, -1, 1)\n x = x.transpose(1, 2) # B x T x C\n x = torch.cat((x, xf), -1) # B x T x Cx2\n\n if mask is not None and not self.use_kernel_mask:\n mask = mask.transpose(-1, -2)\n x = x.masked_fill(mask == 0, 0.0)\n\n # second linear layer\n x = self.linear2(x)\n return x" }, { "identifier": "LightweightConvolution", "path": "funcodec/modules/lightconv.py", "snippet": "class LightweightConvolution(nn.Module):\n \"\"\"Lightweight Convolution layer.\n\n This implementation is based on\n https://github.com/pytorch/fairseq/tree/master/fairseq\n\n Args:\n wshare (int): the number of kernel of convolution\n n_feat (int): the number of features\n dropout_rate (float): dropout_rate\n kernel_size (int): kernel size (length)\n use_kernel_mask (bool): Use causal mask or not for convolution kernel\n use_bias (bool): Use bias term or not.\n\n \"\"\"\n\n def __init__(\n self,\n wshare,\n n_feat,\n dropout_rate,\n kernel_size,\n use_kernel_mask=False,\n use_bias=False,\n ):\n \"\"\"Construct Lightweight Convolution layer.\"\"\"\n super(LightweightConvolution, self).__init__()\n\n assert n_feat % wshare == 0\n self.wshare = wshare\n self.use_kernel_mask = use_kernel_mask\n self.dropout_rate = dropout_rate\n self.kernel_size = kernel_size\n self.padding_size = int(kernel_size / 2)\n\n # linear -> GLU -> lightconv -> linear\n self.linear1 = nn.Linear(n_feat, n_feat * 2)\n self.linear2 = nn.Linear(n_feat, n_feat)\n self.act = nn.GLU()\n\n # lightconv related\n self.weight = nn.Parameter(\n torch.Tensor(self.wshare, 1, kernel_size).uniform_(0, 1)\n )\n self.use_bias = use_bias\n if self.use_bias:\n self.bias = nn.Parameter(torch.Tensor(n_feat))\n\n # mask of kernel\n kernel_mask0 = torch.zeros(self.wshare, int(kernel_size / 2))\n kernel_mask1 = torch.ones(self.wshare, int(kernel_size / 2 + 1))\n self.kernel_mask = torch.cat((kernel_mask1, kernel_mask0), dim=-1).unsqueeze(1)\n\n def forward(self, query, key, value, mask):\n \"\"\"Forward of 'Lightweight Convolution'.\n\n This function takes query, key and value but uses only query.\n This is just for compatibility with self-attention layer (attention.py)\n\n Args:\n query (torch.Tensor): (batch, time1, d_model) input tensor\n key (torch.Tensor): (batch, time2, d_model) NOT USED\n value (torch.Tensor): (batch, time2, d_model) NOT USED\n mask (torch.Tensor): (batch, time1, time2) mask\n\n Return:\n x (torch.Tensor): (batch, time1, d_model) output\n\n \"\"\"\n # linear -> GLU -> lightconv -> linear\n x = query\n B, T, C = x.size()\n H = self.wshare\n\n # first liner layer\n x = self.linear1(x)\n\n # GLU activation\n x = self.act(x)\n\n # lightconv\n x = x.transpose(1, 2).contiguous().view(-1, H, T) # B x C x T\n weight = F.dropout(self.weight, self.dropout_rate, training=self.training)\n if self.use_kernel_mask:\n self.kernel_mask = self.kernel_mask.to(x.device)\n weight = weight.masked_fill(self.kernel_mask == 0.0, float(\"-inf\"))\n weight = F.softmax(weight, dim=-1)\n x = F.conv1d(x, weight, padding=self.padding_size, groups=self.wshare).view(\n B, C, T\n )\n if self.use_bias:\n x = x + self.bias.view(1, -1, 1)\n x = x.transpose(1, 2) # B x T x C\n\n if mask is not None and not self.use_kernel_mask:\n mask = mask.transpose(-1, -2)\n x = x.masked_fill(mask == 0, 0.0)\n\n # second linear layer\n x = self.linear2(x)\n return x" }, { "identifier": "LightweightConvolution2D", "path": "funcodec/modules/lightconv2d.py", "snippet": "class LightweightConvolution2D(nn.Module):\n \"\"\"Lightweight 2-Dimensional Convolution layer.\n\n This implementation is based on\n https://github.com/pytorch/fairseq/tree/master/fairseq\n\n Args:\n wshare (int): the number of kernel of convolution\n n_feat (int): the number of features\n dropout_rate (float): dropout_rate\n kernel_size (int): kernel size (length)\n use_kernel_mask (bool): Use causal mask or not for convolution kernel\n use_bias (bool): Use bias term or not.\n\n \"\"\"\n\n def __init__(\n self,\n wshare,\n n_feat,\n dropout_rate,\n kernel_size,\n use_kernel_mask=False,\n use_bias=False,\n ):\n \"\"\"Construct Lightweight 2-Dimensional Convolution layer.\"\"\"\n super(LightweightConvolution2D, self).__init__()\n\n assert n_feat % wshare == 0\n self.wshare = wshare\n self.use_kernel_mask = use_kernel_mask\n self.dropout_rate = dropout_rate\n self.kernel_size = kernel_size\n self.padding_size = int(kernel_size / 2)\n\n # linear -> GLU -> lightconv -> linear\n self.linear1 = nn.Linear(n_feat, n_feat * 2)\n self.linear2 = nn.Linear(n_feat * 2, n_feat)\n self.act = nn.GLU()\n\n # lightconv related\n self.weight = nn.Parameter(\n torch.Tensor(self.wshare, 1, kernel_size).uniform_(0, 1)\n )\n self.weight_f = nn.Parameter(torch.Tensor(1, 1, kernel_size).uniform_(0, 1))\n self.use_bias = use_bias\n if self.use_bias:\n self.bias = nn.Parameter(torch.Tensor(n_feat))\n\n # mask of kernel\n kernel_mask0 = torch.zeros(self.wshare, int(kernel_size / 2))\n kernel_mask1 = torch.ones(self.wshare, int(kernel_size / 2 + 1))\n self.kernel_mask = torch.cat((kernel_mask1, kernel_mask0), dim=-1).unsqueeze(1)\n\n def forward(self, query, key, value, mask):\n \"\"\"Forward of 'Lightweight 2-Dimensional Convolution'.\n\n This function takes query, key and value but uses only query.\n This is just for compatibility with self-attention layer (attention.py)\n\n Args:\n query (torch.Tensor): (batch, time1, d_model) input tensor\n key (torch.Tensor): (batch, time2, d_model) NOT USED\n value (torch.Tensor): (batch, time2, d_model) NOT USED\n mask (torch.Tensor): (batch, time1, time2) mask\n\n Return:\n x (torch.Tensor): (batch, time1, d_model) output\n\n \"\"\"\n # linear -> GLU -> lightconv -> linear\n x = query\n B, T, C = x.size()\n H = self.wshare\n\n # first liner layer\n x = self.linear1(x)\n\n # GLU activation\n x = self.act(x)\n\n # convolution along frequency axis\n weight_f = F.softmax(self.weight_f, dim=-1)\n weight_f = F.dropout(weight_f, self.dropout_rate, training=self.training)\n weight_new = torch.zeros(\n B * T, 1, self.kernel_size, device=x.device, dtype=x.dtype\n ).copy_(weight_f)\n xf = F.conv1d(\n x.view(1, B * T, C), weight_new, padding=self.padding_size, groups=B * T\n ).view(B, T, C)\n\n # lightconv\n x = x.transpose(1, 2).contiguous().view(-1, H, T) # B x C x T\n weight = F.dropout(self.weight, self.dropout_rate, training=self.training)\n if self.use_kernel_mask:\n self.kernel_mask = self.kernel_mask.to(x.device)\n weight = weight.masked_fill(self.kernel_mask == 0.0, float(\"-inf\"))\n weight = F.softmax(weight, dim=-1)\n x = F.conv1d(x, weight, padding=self.padding_size, groups=self.wshare).view(\n B, C, T\n )\n if self.use_bias:\n x = x + self.bias.view(1, -1, 1)\n x = x.transpose(1, 2) # B x T x C\n x = torch.cat((x, xf), -1) # B x T x Cx2\n\n if mask is not None and not self.use_kernel_mask:\n mask = mask.transpose(-1, -2)\n x = x.masked_fill(mask == 0, 0.0)\n\n # second linear layer\n x = self.linear2(x)\n return x" }, { "identifier": "Conv2dSubsampling", "path": "funcodec/modules/subsampling.py", "snippet": "class Conv2dSubsampling(torch.nn.Module):\n \"\"\"Convolutional 2D subsampling (to 1/4 length).\n\n Args:\n idim (int): Input dimension.\n odim (int): Output dimension.\n dropout_rate (float): Dropout rate.\n pos_enc (torch.nn.Module): Custom position encoding layer.\n\n \"\"\"\n\n def __init__(self, idim, odim, dropout_rate, pos_enc=None):\n \"\"\"Construct an Conv2dSubsampling object.\"\"\"\n super(Conv2dSubsampling, self).__init__()\n self.conv = torch.nn.Sequential(\n torch.nn.Conv2d(1, odim, 3, 2),\n torch.nn.ReLU(),\n torch.nn.Conv2d(odim, odim, 3, 2),\n torch.nn.ReLU(),\n )\n self.out = torch.nn.Sequential(\n torch.nn.Linear(odim * (((idim - 1) // 2 - 1) // 2), odim),\n pos_enc if pos_enc is not None else PositionalEncoding(odim, dropout_rate),\n )\n\n def forward(self, x, x_mask):\n \"\"\"Subsample x.\n\n Args:\n x (torch.Tensor): Input tensor (#batch, time, idim).\n x_mask (torch.Tensor): Input mask (#batch, 1, time).\n\n Returns:\n torch.Tensor: Subsampled tensor (#batch, time', odim),\n where time' = time // 4.\n torch.Tensor: Subsampled mask (#batch, 1, time'),\n where time' = time // 4.\n\n \"\"\"\n x = x.unsqueeze(1) # (b, c, t, f)\n x = self.conv(x)\n b, c, t, f = x.size()\n x = self.out(x.transpose(1, 2).contiguous().view(b, t, c * f))\n if x_mask is None:\n return x, None\n return x, x_mask[:, :, :-2:2][:, :, :-2:2]\n\n def __getitem__(self, key):\n \"\"\"Get item.\n\n When reset_parameters() is called, if use_scaled_pos_enc is used,\n return the positioning encoding.\n\n \"\"\"\n if key != -1:\n raise NotImplementedError(\"Support only `-1` (for `reset_parameters`).\")\n return self.out[key]" }, { "identifier": "Conv2dSubsampling2", "path": "funcodec/modules/subsampling.py", "snippet": "class Conv2dSubsampling2(torch.nn.Module):\n \"\"\"Convolutional 2D subsampling (to 1/2 length).\n\n Args:\n idim (int): Input dimension.\n odim (int): Output dimension.\n dropout_rate (float): Dropout rate.\n pos_enc (torch.nn.Module): Custom position encoding layer.\n\n \"\"\"\n\n def __init__(self, idim, odim, dropout_rate, pos_enc=None):\n \"\"\"Construct an Conv2dSubsampling2 object.\"\"\"\n super(Conv2dSubsampling2, self).__init__()\n self.conv = torch.nn.Sequential(\n torch.nn.Conv2d(1, odim, 3, 2),\n torch.nn.ReLU(),\n torch.nn.Conv2d(odim, odim, 3, 1),\n torch.nn.ReLU(),\n )\n self.out = torch.nn.Sequential(\n torch.nn.Linear(odim * (((idim - 1) // 2 - 2)), odim),\n pos_enc if pos_enc is not None else PositionalEncoding(odim, dropout_rate),\n )\n\n def forward(self, x, x_mask):\n \"\"\"Subsample x.\n\n Args:\n x (torch.Tensor): Input tensor (#batch, time, idim).\n x_mask (torch.Tensor): Input mask (#batch, 1, time).\n\n Returns:\n torch.Tensor: Subsampled tensor (#batch, time', odim),\n where time' = time // 2.\n torch.Tensor: Subsampled mask (#batch, 1, time'),\n where time' = time // 2.\n\n \"\"\"\n x = x.unsqueeze(1) # (b, c, t, f)\n x = self.conv(x)\n b, c, t, f = x.size()\n x = self.out(x.transpose(1, 2).contiguous().view(b, t, c * f))\n if x_mask is None:\n return x, None\n return x, x_mask[:, :, :-2:2][:, :, :-2:1]\n\n def __getitem__(self, key):\n \"\"\"Get item.\n\n When reset_parameters() is called, if use_scaled_pos_enc is used,\n return the positioning encoding.\n\n \"\"\"\n if key != -1:\n raise NotImplementedError(\"Support only `-1` (for `reset_parameters`).\")\n return self.out[key]" }, { "identifier": "Conv2dSubsampling6", "path": "funcodec/modules/subsampling.py", "snippet": "class Conv2dSubsampling6(torch.nn.Module):\n \"\"\"Convolutional 2D subsampling (to 1/6 length).\n\n Args:\n idim (int): Input dimension.\n odim (int): Output dimension.\n dropout_rate (float): Dropout rate.\n pos_enc (torch.nn.Module): Custom position encoding layer.\n\n \"\"\"\n\n def __init__(self, idim, odim, dropout_rate, pos_enc=None):\n \"\"\"Construct an Conv2dSubsampling6 object.\"\"\"\n super(Conv2dSubsampling6, self).__init__()\n self.conv = torch.nn.Sequential(\n torch.nn.Conv2d(1, odim, 3, 2),\n torch.nn.ReLU(),\n torch.nn.Conv2d(odim, odim, 5, 3),\n torch.nn.ReLU(),\n )\n self.out = torch.nn.Sequential(\n torch.nn.Linear(odim * (((idim - 1) // 2 - 2) // 3), odim),\n pos_enc if pos_enc is not None else PositionalEncoding(odim, dropout_rate),\n )\n\n def forward(self, x, x_mask):\n \"\"\"Subsample x.\n\n Args:\n x (torch.Tensor): Input tensor (#batch, time, idim).\n x_mask (torch.Tensor): Input mask (#batch, 1, time).\n\n Returns:\n torch.Tensor: Subsampled tensor (#batch, time', odim),\n where time' = time // 6.\n torch.Tensor: Subsampled mask (#batch, 1, time'),\n where time' = time // 6.\n\n \"\"\"\n x = x.unsqueeze(1) # (b, c, t, f)\n x = self.conv(x)\n b, c, t, f = x.size()\n x = self.out(x.transpose(1, 2).contiguous().view(b, t, c * f))\n if x_mask is None:\n return x, None\n return x, x_mask[:, :, :-2:2][:, :, :-4:3]" }, { "identifier": "Conv2dSubsampling8", "path": "funcodec/modules/subsampling.py", "snippet": "class Conv2dSubsampling8(torch.nn.Module):\n \"\"\"Convolutional 2D subsampling (to 1/8 length).\n\n Args:\n idim (int): Input dimension.\n odim (int): Output dimension.\n dropout_rate (float): Dropout rate.\n pos_enc (torch.nn.Module): Custom position encoding layer.\n\n \"\"\"\n\n def __init__(self, idim, odim, dropout_rate, pos_enc=None):\n \"\"\"Construct an Conv2dSubsampling8 object.\"\"\"\n super(Conv2dSubsampling8, self).__init__()\n self.conv = torch.nn.Sequential(\n torch.nn.Conv2d(1, odim, 3, 2),\n torch.nn.ReLU(),\n torch.nn.Conv2d(odim, odim, 3, 2),\n torch.nn.ReLU(),\n torch.nn.Conv2d(odim, odim, 3, 2),\n torch.nn.ReLU(),\n )\n self.out = torch.nn.Sequential(\n torch.nn.Linear(odim * ((((idim - 1) // 2 - 1) // 2 - 1) // 2), odim),\n pos_enc if pos_enc is not None else PositionalEncoding(odim, dropout_rate),\n )\n\n def forward(self, x, x_mask):\n \"\"\"Subsample x.\n\n Args:\n x (torch.Tensor): Input tensor (#batch, time, idim).\n x_mask (torch.Tensor): Input mask (#batch, 1, time).\n\n Returns:\n torch.Tensor: Subsampled tensor (#batch, time', odim),\n where time' = time // 8.\n torch.Tensor: Subsampled mask (#batch, 1, time'),\n where time' = time // 8.\n\n \"\"\"\n x = x.unsqueeze(1) # (b, c, t, f)\n x = self.conv(x)\n b, c, t, f = x.size()\n x = self.out(x.transpose(1, 2).contiguous().view(b, t, c * f))\n if x_mask is None:\n return x, None\n return x, x_mask[:, :, :-2:2][:, :, :-2:2][:, :, :-2:2]" }, { "identifier": "TooShortUttError", "path": "funcodec/modules/subsampling.py", "snippet": "class TooShortUttError(Exception):\n \"\"\"Raised when the utt is too short for subsampling.\n\n Args:\n message (str): Message for error catch\n actual_size (int): the short size that cannot pass the subsampling\n limit (int): the limit size for subsampling\n\n \"\"\"\n\n def __init__(self, message, actual_size, limit):\n \"\"\"Construct a TooShortUttError for error handler.\"\"\"\n super().__init__(message)\n self.actual_size = actual_size\n self.limit = limit" }, { "identifier": "check_short_utt", "path": "funcodec/modules/subsampling.py", "snippet": "def check_short_utt(ins, size):\n \"\"\"Check if the utterance is too short for subsampling.\"\"\"\n if isinstance(ins, Conv2dSubsampling2) and size < 3:\n return True, 3\n if isinstance(ins, Conv2dSubsampling) and size < 7:\n return True, 7\n if isinstance(ins, Conv2dSubsampling6) and size < 11:\n return True, 11\n if isinstance(ins, Conv2dSubsampling8) and size < 15:\n return True, 15\n return False, -1" } ]
from typing import List from typing import Optional from typing import Tuple from torch import nn from funcodec.models.encoder.abs_encoder import AbsEncoder from funcodec.modules.attention import ( MultiHeadedAttention, RelPositionMultiHeadedAttention, # noqa: H301 LegacyRelPositionMultiHeadedAttention, # noqa: H301 ) from funcodec.modules.layer_norm import LayerNorm from funcodec.modules.multi_layer_conv import Conv1dLinear from funcodec.modules.multi_layer_conv import MultiLayeredConv1d from funcodec.modules.nets_utils import make_pad_mask from funcodec.modules.embedding import ( PositionalEncoding, # noqa: H301 ScaledPositionalEncoding, # noqa: H301 RelPositionalEncoding, # noqa: H301 LegacyRelPositionalEncoding, # noqa: H301 ) from funcodec.modules.positionwise_feed_forward import ( PositionwiseFeedForward, # noqa: H301 ) from funcodec.modules.repeat import repeat from funcodec.modules.nets_utils import rename_state_dict from funcodec.modules.dynamic_conv import DynamicConvolution from funcodec.modules.dynamic_conv2d import DynamicConvolution2D from funcodec.modules.lightconv import LightweightConvolution from funcodec.modules.lightconv2d import LightweightConvolution2D from funcodec.modules.subsampling import Conv2dSubsampling from funcodec.modules.subsampling import Conv2dSubsampling2 from funcodec.modules.subsampling import Conv2dSubsampling6 from funcodec.modules.subsampling import Conv2dSubsampling8 from funcodec.modules.subsampling import TooShortUttError from funcodec.modules.subsampling import check_short_utt import torch import logging
19,166
selfattention_layer_type == "lightconv*" or "dynamiconv*". linear_units (int): The number of units of position-wise feed forward. num_blocks (int): The number of decoder blocks. dropout_rate (float): Dropout rate. positional_dropout_rate (float): Dropout rate after adding positional encoding. attention_dropout_rate (float): Dropout rate in attention. input_layer (Union[str, torch.nn.Module]): Input layer type. pos_enc_class (torch.nn.Module): Positional encoding module class. `PositionalEncoding `or `ScaledPositionalEncoding` normalize_before (bool): Whether to use layer_norm before the first block. concat_after (bool): Whether to concat attention layer's input and output. if True, additional linear will be applied. i.e. x -> x + linear(concat(x, att(x))) if False, no additional linear will be applied. i.e. x -> x + att(x) positionwise_layer_type (str): "linear", "conv1d", or "conv1d-linear". positionwise_conv_kernel_size (int): Kernel size of positionwise conv1d layer. selfattention_layer_type (str): Encoder attention layer type. padding_idx (int): Padding idx for input_layer=embed. stochastic_depth_rate (float): Maximum probability to skip the encoder layer. intermediate_layers (Union[List[int], None]): indices of intermediate CTC layer. indices start from 1. if not None, intermediate outputs are returned (which changes return type signature.) """ def __init__( self, idim, attention_dim=256, attention_heads=4, conv_wshare=4, conv_kernel_length="11", conv_usebias=False, linear_units=2048, num_blocks=6, dropout_rate=0.1, positional_dropout_rate=0.1, attention_dropout_rate=0.0, input_layer="conv2d", pos_enc_class=PositionalEncoding, normalize_before=True, concat_after=False, positionwise_layer_type="linear", positionwise_conv_kernel_size=1, selfattention_layer_type="selfattn", padding_idx=-1, stochastic_depth_rate=0.0, intermediate_layers=None, ctc_softmax=None, conditioning_layer_dim=None, zero_triu: bool = False, ): """Construct an Encoder object.""" super(TransformerEncoder_s0, self).__init__() self._register_load_state_dict_pre_hook(_pre_hook) self.conv_subsampling_factor = 1 if input_layer == "linear": self.embed = torch.nn.Sequential( torch.nn.Linear(idim, attention_dim), torch.nn.LayerNorm(attention_dim), torch.nn.Dropout(dropout_rate), torch.nn.ReLU(), pos_enc_class(attention_dim, positional_dropout_rate), ) elif input_layer == "conv2d": self.embed = Conv2dSubsampling(idim, attention_dim, dropout_rate) self.conv_subsampling_factor = 4 elif input_layer == "conv2d-scaled-pos-enc": self.embed = Conv2dSubsampling( idim, attention_dim, dropout_rate, pos_enc_class(attention_dim, positional_dropout_rate), ) self.conv_subsampling_factor = 4 elif input_layer == "conv2d6": self.embed = Conv2dSubsampling6(idim, attention_dim, dropout_rate) self.conv_subsampling_factor = 6 elif input_layer == "conv2d8": self.embed = Conv2dSubsampling8(idim, attention_dim, dropout_rate) self.conv_subsampling_factor = 8 elif input_layer == "embed": self.embed = torch.nn.Sequential( torch.nn.Embedding(idim, attention_dim, padding_idx=padding_idx), pos_enc_class(attention_dim, positional_dropout_rate), ) elif isinstance(input_layer, torch.nn.Module): self.embed = torch.nn.Sequential( input_layer, pos_enc_class(attention_dim, positional_dropout_rate), ) elif input_layer is None: self.embed = torch.nn.Sequential( pos_enc_class(attention_dim, positional_dropout_rate) ) elif input_layer == "none": self.embed = torch.nn.Identity() else: raise ValueError("unknown input_layer: " + input_layer) self.normalize_before = normalize_before positionwise_layer, positionwise_layer_args = self.get_positionwise_layer( positionwise_layer_type, attention_dim, linear_units, dropout_rate, positionwise_conv_kernel_size, ) if selfattention_layer_type == "selfattn": logging.info("encoder self-attention layer type = self-attention") encoder_selfattn_layer = MultiHeadedAttention encoder_selfattn_layer_args = [( attention_heads, attention_dim, attention_dropout_rate, )] * num_blocks elif selfattention_layer_type == "legacy_rel_selfattn": logging.info("encoder self-attention layer type = legacy relative self-attention") assert pos_enc_class == LegacyRelPositionalEncoding
# Copyright 2019 Shigeki Karita # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Transformer encoder definition.""" class EncoderLayer(nn.Module): """Encoder layer module. Args: size (int): Input dimension. self_attn (torch.nn.Module): Self-attention module instance. `MultiHeadedAttention` or `RelPositionMultiHeadedAttention` instance can be used as the argument. feed_forward (torch.nn.Module): Feed-forward module instance. `PositionwiseFeedForward`, `MultiLayeredConv1d`, or `Conv1dLinear` instance can be used as the argument. dropout_rate (float): Dropout rate. normalize_before (bool): Whether to use layer_norm before the first block. concat_after (bool): Whether to concat attention layer's input and output. if True, additional linear will be applied. i.e. x -> x + linear(concat(x, att(x))) if False, no additional linear will be applied. i.e. x -> x + att(x) stochastic_depth_rate (float): Proability to skip this layer. During training, the layer may skip residual computation and return input as-is with given probability. """ def __init__( self, size, self_attn, feed_forward, dropout_rate, normalize_before=True, concat_after=False, stochastic_depth_rate=0.0, ): """Construct an EncoderLayer object.""" super(EncoderLayer, self).__init__() self.self_attn = self_attn self.feed_forward = feed_forward self.norm1 = LayerNorm(size) self.norm2 = LayerNorm(size) self.dropout = nn.Dropout(dropout_rate) self.size = size self.normalize_before = normalize_before self.concat_after = concat_after if self.concat_after: self.concat_linear = nn.Linear(size + size, size) self.stochastic_depth_rate = stochastic_depth_rate def forward(self, x, mask, cache=None): """Compute encoded features. Args: x_input (torch.Tensor): Input tensor (#batch, time, size). mask (torch.Tensor): Mask tensor for the input (#batch, time). cache (torch.Tensor): Cache tensor of the input (#batch, time - 1, size). Returns: torch.Tensor: Output tensor (#batch, time, size). torch.Tensor: Mask tensor (#batch, time). """ if isinstance(x, tuple): x, pos_emb = x[0], x[1] else: x, pos_emb = x, None skip_layer = False # with stochastic depth, residual connection `x + f(x)` becomes # `x <- x + 1 / (1 - p) * f(x)` at training time. stoch_layer_coeff = 1.0 if self.training and self.stochastic_depth_rate > 0: skip_layer = torch.rand(1).item() < self.stochastic_depth_rate stoch_layer_coeff = 1.0 / (1 - self.stochastic_depth_rate) if skip_layer: if cache is not None: x = torch.cat([cache, x], dim=1) if pos_emb is not None: return (x, pos_emb), mask return x, mask residual = x if self.normalize_before: x = self.norm1(x) if cache is None: x_q = x else: assert cache.shape == (x.shape[0], x.shape[1] - 1, self.size) x_q = x[:, -1:, :] residual = residual[:, -1:, :] mask = None if mask is None else mask[:, -1:, :] if pos_emb is not None: x_att = self.self_attn(x_q, x, x, pos_emb, mask) else: x_att = self.self_attn(x_q, x, x, mask) if self.concat_after: x_concat = torch.cat((x, x_att), dim=-1) x = residual + stoch_layer_coeff * self.concat_linear(x_concat) else: x = residual + stoch_layer_coeff * self.dropout(x_att) if not self.normalize_before: x = self.norm1(x) residual = x if self.normalize_before: x = self.norm2(x) x = residual + stoch_layer_coeff * self.dropout(self.feed_forward(x)) if not self.normalize_before: x = self.norm2(x) if cache is not None: x = torch.cat([cache, x], dim=1) if pos_emb is not None: return (x, pos_emb), mask return x, mask class TransformerEncoder(AbsEncoder): """Transformer encoder module. Args: input_size: input dim output_size: dimension of attention attention_heads: the number of heads of multi head attention linear_units: the number of units of position-wise feed forward num_blocks: the number of decoder blocks dropout_rate: dropout rate attention_dropout_rate: dropout rate in attention positional_dropout_rate: dropout rate after adding positional encoding input_layer: input layer type pos_enc_class: PositionalEncoding or ScaledPositionalEncoding normalize_before: whether to use layer_norm before the first block concat_after: whether to concat attention layer's input and output if True, additional linear will be applied. i.e. x -> x + linear(concat(x, att(x))) if False, no additional linear will be applied. i.e. x -> x + att(x) positionwise_layer_type: linear of conv1d positionwise_conv_kernel_size: kernel size of positionwise conv1d layer padding_idx: padding_idx for input_layer=embed """ def __init__( self, input_size: int, output_size: int = 256, attention_heads: int = 4, linear_units: int = 2048, num_blocks: int = 6, dropout_rate: float = 0.1, positional_dropout_rate: float = 0.1, attention_dropout_rate: float = 0.0, input_layer: Optional[str] = "conv2d", pos_enc_class=PositionalEncoding, normalize_before: bool = True, concat_after: bool = False, positionwise_layer_type: str = "linear", positionwise_conv_kernel_size: int = 1, padding_idx: int = -1, interctc_layer_idx: List[int] = [], interctc_use_conditioning: bool = False, causal_mode: str = "None", ): super().__init__() self._output_size = output_size self.causal_mode = causal_mode if input_layer == "linear": self.embed = torch.nn.Sequential( torch.nn.Linear(input_size, output_size), torch.nn.LayerNorm(output_size), torch.nn.Dropout(dropout_rate), torch.nn.ReLU(), pos_enc_class(output_size, positional_dropout_rate), ) elif input_layer == "conv2d": self.embed = Conv2dSubsampling(input_size, output_size, dropout_rate) elif input_layer == "conv2d2": self.embed = Conv2dSubsampling2(input_size, output_size, dropout_rate) elif input_layer == "conv2d6": self.embed = Conv2dSubsampling6(input_size, output_size, dropout_rate) elif input_layer == "conv2d8": self.embed = Conv2dSubsampling8(input_size, output_size, dropout_rate) elif input_layer == "embed": self.embed = torch.nn.Sequential( torch.nn.Embedding(input_size, output_size, padding_idx=padding_idx), pos_enc_class(output_size, positional_dropout_rate), ) elif input_layer is None: if input_size == output_size: self.embed = None else: self.embed = torch.nn.Linear(input_size, output_size) else: raise ValueError("unknown input_layer: " + input_layer) self.normalize_before = normalize_before if positionwise_layer_type == "linear": positionwise_layer = PositionwiseFeedForward positionwise_layer_args = ( output_size, linear_units, dropout_rate, ) elif positionwise_layer_type == "conv1d": positionwise_layer = MultiLayeredConv1d positionwise_layer_args = ( output_size, linear_units, positionwise_conv_kernel_size, dropout_rate, ) elif positionwise_layer_type == "conv1d-linear": positionwise_layer = Conv1dLinear positionwise_layer_args = ( output_size, linear_units, positionwise_conv_kernel_size, dropout_rate, ) else: raise NotImplementedError("Support only linear or conv1d.") self.encoders = repeat( num_blocks, lambda lnum: EncoderLayer( output_size, MultiHeadedAttention( attention_heads, output_size, attention_dropout_rate ), positionwise_layer(*positionwise_layer_args), dropout_rate, normalize_before, concat_after, ), ) if self.normalize_before: self.after_norm = LayerNorm(output_size) self.interctc_layer_idx = interctc_layer_idx if len(interctc_layer_idx) > 0: assert 0 < min(interctc_layer_idx) and max(interctc_layer_idx) < num_blocks self.interctc_use_conditioning = interctc_use_conditioning self.conditioning_layer = None def output_size(self) -> int: return self._output_size def forward( self, xs_pad: torch.Tensor, ilens: torch.Tensor, prev_states: torch.Tensor = None, ctc = None, ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: """Embed positions in tensor. Args: xs_pad: input tensor (B, L, D) ilens: input length (B) prev_states: Not to be used now. Returns: position embedded tensor and mask """ masks = (~make_pad_mask(ilens)[:, None, :]).to(xs_pad.device) if self.causal_mode == "None": pass elif self.causal_mode == "causal": tt = xs_pad.shape[1] pos_idx = torch.arange(tt) causal_mask = torch.less_equal(pos_idx.unsqueeze(0), pos_idx.unsqueeze(1)) causal_mask = causal_mask.unsqueeze(0).to(xs_pad.device) masks = masks * causal_mask if self.embed is None: xs_pad = xs_pad elif ( isinstance(self.embed, Conv2dSubsampling) or isinstance(self.embed, Conv2dSubsampling2) or isinstance(self.embed, Conv2dSubsampling6) or isinstance(self.embed, Conv2dSubsampling8) ): short_status, limit_size = check_short_utt(self.embed, xs_pad.size(1)) if short_status: raise TooShortUttError( f"has {xs_pad.size(1)} frames and is too short for subsampling " + f"(it needs more than {limit_size} frames), return empty results", xs_pad.size(1), limit_size, ) xs_pad, masks = self.embed(xs_pad, masks) else: xs_pad = self.embed(xs_pad) intermediate_outs = [] if len(self.interctc_layer_idx) == 0: xs_pad, masks = self.encoders(xs_pad, masks) else: for layer_idx, encoder_layer in enumerate(self.encoders): xs_pad, masks = encoder_layer(xs_pad, masks) if layer_idx + 1 in self.interctc_layer_idx: encoder_out = xs_pad # intermediate outputs are also normalized if self.normalize_before: encoder_out = self.after_norm(encoder_out) intermediate_outs.append((layer_idx + 1, encoder_out)) if self.interctc_use_conditioning: ctc_out = ctc.softmax(encoder_out) xs_pad = xs_pad + self.conditioning_layer(ctc_out) if self.normalize_before: xs_pad = self.after_norm(xs_pad) olens = masks.squeeze(1).sum(1) if len(intermediate_outs) > 0: return (xs_pad, intermediate_outs), olens, None return xs_pad, olens, None def _pre_hook( state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, ): # https://github.com/espnet/espnet/commit/21d70286c354c66c0350e65dc098d2ee236faccc#diff-bffb1396f038b317b2b64dd96e6d3563 rename_state_dict(prefix + "input_layer.", prefix + "embed.", state_dict) # https://github.com/espnet/espnet/commit/3d422f6de8d4f03673b89e1caef698745ec749ea#diff-bffb1396f038b317b2b64dd96e6d3563 rename_state_dict(prefix + "norm.", prefix + "after_norm.", state_dict) class TransformerEncoder_s0(torch.nn.Module): """Transformer encoder module. Args: idim (int): Input dimension. attention_dim (int): Dimension of attention. attention_heads (int): The number of heads of multi head attention. conv_wshare (int): The number of kernel of convolution. Only used in selfattention_layer_type == "lightconv*" or "dynamiconv*". conv_kernel_length (Union[int, str]): Kernel size str of convolution (e.g. 71_71_71_71_71_71). Only used in selfattention_layer_type == "lightconv*" or "dynamiconv*". conv_usebias (bool): Whether to use bias in convolution. Only used in selfattention_layer_type == "lightconv*" or "dynamiconv*". linear_units (int): The number of units of position-wise feed forward. num_blocks (int): The number of decoder blocks. dropout_rate (float): Dropout rate. positional_dropout_rate (float): Dropout rate after adding positional encoding. attention_dropout_rate (float): Dropout rate in attention. input_layer (Union[str, torch.nn.Module]): Input layer type. pos_enc_class (torch.nn.Module): Positional encoding module class. `PositionalEncoding `or `ScaledPositionalEncoding` normalize_before (bool): Whether to use layer_norm before the first block. concat_after (bool): Whether to concat attention layer's input and output. if True, additional linear will be applied. i.e. x -> x + linear(concat(x, att(x))) if False, no additional linear will be applied. i.e. x -> x + att(x) positionwise_layer_type (str): "linear", "conv1d", or "conv1d-linear". positionwise_conv_kernel_size (int): Kernel size of positionwise conv1d layer. selfattention_layer_type (str): Encoder attention layer type. padding_idx (int): Padding idx for input_layer=embed. stochastic_depth_rate (float): Maximum probability to skip the encoder layer. intermediate_layers (Union[List[int], None]): indices of intermediate CTC layer. indices start from 1. if not None, intermediate outputs are returned (which changes return type signature.) """ def __init__( self, idim, attention_dim=256, attention_heads=4, conv_wshare=4, conv_kernel_length="11", conv_usebias=False, linear_units=2048, num_blocks=6, dropout_rate=0.1, positional_dropout_rate=0.1, attention_dropout_rate=0.0, input_layer="conv2d", pos_enc_class=PositionalEncoding, normalize_before=True, concat_after=False, positionwise_layer_type="linear", positionwise_conv_kernel_size=1, selfattention_layer_type="selfattn", padding_idx=-1, stochastic_depth_rate=0.0, intermediate_layers=None, ctc_softmax=None, conditioning_layer_dim=None, zero_triu: bool = False, ): """Construct an Encoder object.""" super(TransformerEncoder_s0, self).__init__() self._register_load_state_dict_pre_hook(_pre_hook) self.conv_subsampling_factor = 1 if input_layer == "linear": self.embed = torch.nn.Sequential( torch.nn.Linear(idim, attention_dim), torch.nn.LayerNorm(attention_dim), torch.nn.Dropout(dropout_rate), torch.nn.ReLU(), pos_enc_class(attention_dim, positional_dropout_rate), ) elif input_layer == "conv2d": self.embed = Conv2dSubsampling(idim, attention_dim, dropout_rate) self.conv_subsampling_factor = 4 elif input_layer == "conv2d-scaled-pos-enc": self.embed = Conv2dSubsampling( idim, attention_dim, dropout_rate, pos_enc_class(attention_dim, positional_dropout_rate), ) self.conv_subsampling_factor = 4 elif input_layer == "conv2d6": self.embed = Conv2dSubsampling6(idim, attention_dim, dropout_rate) self.conv_subsampling_factor = 6 elif input_layer == "conv2d8": self.embed = Conv2dSubsampling8(idim, attention_dim, dropout_rate) self.conv_subsampling_factor = 8 elif input_layer == "embed": self.embed = torch.nn.Sequential( torch.nn.Embedding(idim, attention_dim, padding_idx=padding_idx), pos_enc_class(attention_dim, positional_dropout_rate), ) elif isinstance(input_layer, torch.nn.Module): self.embed = torch.nn.Sequential( input_layer, pos_enc_class(attention_dim, positional_dropout_rate), ) elif input_layer is None: self.embed = torch.nn.Sequential( pos_enc_class(attention_dim, positional_dropout_rate) ) elif input_layer == "none": self.embed = torch.nn.Identity() else: raise ValueError("unknown input_layer: " + input_layer) self.normalize_before = normalize_before positionwise_layer, positionwise_layer_args = self.get_positionwise_layer( positionwise_layer_type, attention_dim, linear_units, dropout_rate, positionwise_conv_kernel_size, ) if selfattention_layer_type == "selfattn": logging.info("encoder self-attention layer type = self-attention") encoder_selfattn_layer = MultiHeadedAttention encoder_selfattn_layer_args = [( attention_heads, attention_dim, attention_dropout_rate, )] * num_blocks elif selfattention_layer_type == "legacy_rel_selfattn": logging.info("encoder self-attention layer type = legacy relative self-attention") assert pos_enc_class == LegacyRelPositionalEncoding
encoder_selfattn_layer = LegacyRelPositionMultiHeadedAttention
3
2023-10-07 02:00:40+00:00
24k
Beckschen/3D-TransUNet
nn_transunet/trainer/nnUNetTrainerV2_DDP.py
[ { "identifier": "nnUNetTrainerV2", "path": "nn_transunet/trainer/nnUNetTrainerV2.py", "snippet": "class nnUNetTrainerV2(nnUNetTrainer):\n \"\"\"\n Info for Fabian: same as internal nnUNetTrainerV2_2\n \"\"\"\n\n def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None,\n unpack_data=True, deterministic=True, fp16=False, input_size=(64, 160, 160),args=None):\n super().__init__(plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data,\n deterministic, fp16)\n if args is not None: \n self.input_size=input_size\n self.model = args.model\n self.resume = args.resume\n self.disable_ds=args.disable_ds\n self.max_num_epochs = args.max_num_epochs # set 1 gpu training\n self.initial_lr = args.initial_lr # 0.01\n self.args = args\n \n if self.disable_ds:\n print(\"disable_ds\")\n # print(\"not runnable for this feature! current nnunetV2 (w/o DDP) only support deep supervision version\")\n # raise NotImplementedError\n else:\n print(\"runnning DDP, inheriting nnUNetTrainerV2\")\n \n self.save_every = 1 # prev 50\n # self.max_num_epochs = 1000\n # self.initial_lr = 1e-2\n self.deep_supervision_scales = None\n self.ds_loss_weights = None\n\n self.pin_memory = True\n\n def initialize(self, training=True, force_load_plans=False):\n \"\"\"\n - replaced get_default_augmentation with get_moreDA_augmentation\n - enforce to only run this code once\n - loss function wrapper for deep supervision\n\n :param training:\n :param force_load_plans:\n :return:\n \"\"\"\n if not self.was_initialized:\n maybe_mkdir_p(self.output_folder)\n\n if force_load_plans or (self.plans is None):\n self.load_plans_file()\n\n self.process_plans(self.plans)\n\n self.setup_DA_params()\n\n ################# Here we wrap the loss for deep supervision ############\n # we need to know the number of outputs of the network\n net_numpool = len(self.net_num_pool_op_kernel_sizes)\n\n # we give each output a weight which decreases exponentially (division by 2) as the resolution decreases\n # this gives higher resolution outputs more weight in the loss\n weights = np.array([1 / (2 ** i) for i in range(net_numpool)])\n\n # we don't use the lowest 2 outputs. Normalize weights so that they sum to 1\n mask = np.array([True] + [True if i < net_numpool - 1 else False for i in range(1, net_numpool)])\n weights[~mask] = 0\n weights = weights / weights.sum()\n self.ds_loss_weights = weights\n if self.disable_ds:\n \n self.ds_loss_weights[0]=1\n self.ds_loss_weights[1:]=0\n from loss_functions import DC_and_CE_loss\n self.loss = DC_and_CE_loss({'batch_dice': self.batch_dice, 'smooth': 1e-5, 'do_bg': False}, {})\n\n else:\n # now wrap the loss\n self.loss = MultipleOutputLoss2(self.loss, self.ds_loss_weights)\n ################# END ###################\n\n self.folder_with_preprocessed_data = join(self.dataset_directory, self.plans['data_identifier'] +\n \"_stage%d\" % self.stage)\n if training:\n self.dl_tr, self.dl_val = self.get_basic_generators()\n if self.unpack_data:\n print(\"unpacking dataset\")\n unpack_dataset(self.folder_with_preprocessed_data)\n print(\"done\")\n else:\n print(\n \"INFO: Not unpacking data! Training may be slow due to that. Pray you are not using 2d or you \"\n \"will wait all winter for your model to finish!\")\n\n self.tr_gen, self.val_gen = get_moreDA_augmentation(\n self.dl_tr, self.dl_val,\n self.data_aug_params[\n 'patch_size_for_spatialtransform'],\n self.data_aug_params,\n deep_supervision_scales=self.deep_supervision_scales,\n pin_memory=self.pin_memory,\n use_nondetMultiThreadedAugmenter=False\n )\n self.print_to_log_file(\"TRAINING KEYS:\\n %s\" % (str(self.dataset_tr.keys())),\n also_print_to_console=False)\n self.print_to_log_file(\"VALIDATION KEYS:\\n %s\" % (str(self.dataset_val.keys())),\n also_print_to_console=False)\n else:\n pass\n\n self.initialize_network()\n self.initialize_optimizer_and_scheduler()\n\n # assert isinstance(self.network, (SegmentationNetwork, nn.DataParallel))\n else:\n self.print_to_log_file('self.was_initialized is True, not running self.initialize again')\n self.was_initialized = True\n\n\n def initialize_network(self):\n \"\"\"\n - momentum 0.99\n - SGD instead of Adam\n - self.lr_scheduler = None because we do poly_lr\n - deep supervision = True\n - i am sure I forgot something here\n\n Known issue: forgot to set neg_slope=0 in InitWeights_He; should not make a difference though\n :return:\n \"\"\"\n\n # model_list = {'Generic_UNet': Generic_UNet}\n\n if self.model.startswith(\"Generic\"):\n if self.threeD:\n conv_op = nn.Conv3d\n dropout_op = nn.Dropout3d\n norm_op = nn.InstanceNorm3d\n\n else:\n conv_op = nn.Conv2d\n dropout_op = nn.Dropout2d\n norm_op = nn.InstanceNorm2d\n\n norm_op_kwargs = {'eps': 1e-5, 'affine': True}\n dropout_op_kwargs = {'p': 0, 'inplace': True}\n net_nonlin = nn.LeakyReLU\n net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True}\n do_ds = not self.disable_ds\n if not do_ds: print(\"disable ds\")\n if self.model == 'Generic_TransUNet_max_ppbp':\n from ..networks.transunet3d_model import Generic_TransUNet_max_ppbp\n self.network = Generic_TransUNet_max_ppbp(self.num_input_channels, self.base_num_features, self.num_classes,\n len(self.net_num_pool_op_kernel_sizes),\n self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op,\n dropout_op_kwargs,\n net_nonlin, net_nonlin_kwargs, do_ds, False, lambda x: x, InitWeights_He(1e-2),\n self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, \n convolutional_upsampling= False if ('is_fam' in self.model_params.keys() and self.model_params['is_fam']) else True, # default True,\n patch_size=self.args.crop_size, \n **self.model_params)\n else:\n raise NotImplementedError\n \n if torch.cuda.is_available():\n self.network.cuda()\n self.network.inference_apply_nonlin = softmax_helper\n\n else:\n raise NotImplementedError\n\n\n def initialize_optimizer_and_scheduler(self):\n assert self.network is not None, \"self.initialize_network must be called first\"\n self.optimizer = torch.optim.SGD(self.network.parameters(), self.initial_lr, weight_decay=self.weight_decay,\n momentum=0.99, nesterov=True)\n self.lr_scheduler = None\n\n def run_online_evaluation(self, output, target):\n \"\"\"\n due to deep supervision the return value and the reference are now lists of tensors. We only need the full\n resolution output because this is what we are interested in in the end. The others are ignored\n :param output:\n :param target:\n :return:\n \"\"\"\n target = target[0]\n output = output[0]\n return super().run_online_evaluation(output, target)\n\n def validate(self, do_mirroring: bool = True, use_sliding_window: bool = True,\n step_size: float = 0.5, save_softmax: bool = True, use_gaussian: bool = True, overwrite: bool = True,\n validation_folder_name: str = 'validation_raw', debug: bool = False, all_in_gpu: bool = False,\n segmentation_export_kwargs: dict = None, run_postprocessing_on_folds: bool = True):\n \"\"\"\n We need to wrap this because we need to enforce self.network.do_ds = False for prediction\n \"\"\"\n ds = self.network.do_ds\n self.network.do_ds = False\n ret = super().validate(do_mirroring=do_mirroring, use_sliding_window=use_sliding_window, step_size=step_size,\n save_softmax=save_softmax, use_gaussian=use_gaussian,\n overwrite=overwrite, validation_folder_name=validation_folder_name, debug=debug,\n all_in_gpu=all_in_gpu, segmentation_export_kwargs=segmentation_export_kwargs,\n run_postprocessing_on_folds=run_postprocessing_on_folds)\n\n self.network.do_ds = ds\n return ret\n\n def predict_preprocessed_data_return_seg_and_softmax(self, data: np.ndarray, do_mirroring: bool = True,\n mirror_axes: Tuple[int] = None,\n use_sliding_window: bool = True, step_size: float = 0.5,\n use_gaussian: bool = True, pad_border_mode: str = 'constant',\n pad_kwargs: dict = None, all_in_gpu: bool = False,\n verbose: bool = True, mixed_precision=True) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n We need to wrap this because we need to enforce self.network.do_ds = False for prediction\n \"\"\"\n ds = self.network.do_ds\n self.network.do_ds = False\n ret = super().predict_preprocessed_data_return_seg_and_softmax(data,\n do_mirroring=do_mirroring,\n mirror_axes=mirror_axes,\n use_sliding_window=use_sliding_window,\n step_size=step_size, use_gaussian=use_gaussian,\n pad_border_mode=pad_border_mode,\n pad_kwargs=pad_kwargs, all_in_gpu=all_in_gpu,\n verbose=verbose,\n mixed_precision=mixed_precision)\n self.network.do_ds = ds\n return ret\n\n def run_iteration(self, data_generator, do_backprop=True, run_online_evaluation=False):\n \"\"\"\n gradient clipping improves training stability\n\n :param data_generator:\n :param do_backprop:\n :param run_online_evaluation:\n :return:\n \"\"\"\n data_dict = next(data_generator)\n data = data_dict['data']\n target = data_dict['target']\n\n data = maybe_to_torch(data)\n target = maybe_to_torch(target)\n\n if torch.cuda.is_available():\n data = to_cuda(data)\n target = to_cuda(target)\n\n self.optimizer.zero_grad()\n\n if self.fp16:\n with autocast():\n output = self.network(data)\n del data\n if self.disable_ds:\n if isinstance(output, tuple) or isinstance(output, list):\n output = output[0]\n if isinstance(target, tuple) or isinstance(target, list):\n target = target[0]\n l = self.loss(output, target)\n\n if do_backprop:\n self.amp_grad_scaler.scale(l).backward()\n self.amp_grad_scaler.unscale_(self.optimizer)\n torch.nn.utils.clip_grad_norm_(self.network.parameters(), 12)\n self.amp_grad_scaler.step(self.optimizer)\n self.amp_grad_scaler.update()\n else:\n output = self.network(data)\n del data\n l = self.loss(output, target)\n\n if do_backprop:\n l.backward()\n torch.nn.utils.clip_grad_norm_(self.network.parameters(), 12)\n self.optimizer.step()\n\n if run_online_evaluation:\n if self.disable_ds:\n output = output.unsqueeze(0)\n target = target.unsqueeze(0)\n self.run_online_evaluation(output, target)\n\n del target\n\n return l.detach().cpu().numpy()\n\n def do_split(self):\n \"\"\"\n The default split is a 5 fold CV on all available training cases. nnU-Net will create a split (it is seeded,\n so always the same) and save it as splits_final.pkl file in the preprocessed data directory.\n Sometimes you may want to create your own split for various reasons. For this you will need to create your own\n splits_final.pkl file. If this file is present, nnU-Net is going to use it and whatever splits are defined in\n it. You can create as many splits in this file as you want. Note that if you define only 4 splits (fold 0-3)\n and then set fold=4 when training (that would be the fifth split), nnU-Net will print a warning and proceed to\n use a random 80:20 data split.\n :return:\n \"\"\"\n if isinstance(self.fold, str) and self.fold.startswith(\"all\"):\n # achtung!\n if self.fold == \"all\":\n tr_keys = val_keys = list(self.dataset.keys())\n elif self.fold.find(\"tr\") != -1:\n # np.sort(list(self.dataset.keys()))\n np.random.seed(12345)\n all_keys = list(self.dataset.keys())\n np.random.shuffle(all_keys)\n proportion = float(self.fold.split(\"tr\")[-1])\n assert proportion < 1.0\n cur_num = int(len(all_keys) * proportion)\n tr_keys = val_keys = all_keys[:cur_num]\n\n else:\n splits_file = join(self.dataset_directory, \"splits_final.pkl\")\n # if the split file does not exist we need to create it\n if not isfile(splits_file):\n self.print_to_log_file(\"Creating new 5-fold cross-validation split...\")\n splits = []\n all_keys_sorted = np.sort(list(self.dataset.keys()))\n kfold = KFold(n_splits=5, shuffle=True, random_state=12345)\n for i, (train_idx, test_idx) in enumerate(kfold.split(all_keys_sorted)):\n train_keys = np.array(all_keys_sorted)[train_idx]\n test_keys = np.array(all_keys_sorted)[test_idx]\n splits.append(OrderedDict())\n splits[-1]['train'] = train_keys\n splits[-1]['val'] = test_keys\n save_pickle(splits, splits_file)\n\n else:\n self.print_to_log_file(\"Using splits from existing split file:\", splits_file)\n splits = load_pickle(splits_file)\n self.print_to_log_file(\"The split file contains %d splits.\" % len(splits))\n\n self.print_to_log_file(\"Desired fold for training: %d\" % self.fold)\n if self.fold < len(splits):\n tr_keys = splits[self.fold]['train']\n val_keys = splits[self.fold]['val']\n self.print_to_log_file(\"This split has %d training and %d validation cases.\"\n % (len(tr_keys), len(val_keys)))\n else:\n self.print_to_log_file(\"INFO: You requested fold %d for training but splits \"\n \"contain only %d folds. I am now creating a \"\n \"random (but seeded) 80:20 split!\" % (self.fold, len(splits)))\n # if we request a fold that is not in the split file, create a random 80:20 split\n rnd = np.random.RandomState(seed=12345 + self.fold)\n keys = np.sort(list(self.dataset.keys()))\n idx_tr = rnd.choice(len(keys), int(len(keys) * 0.8), replace=False)\n idx_val = [i for i in range(len(keys)) if i not in idx_tr]\n tr_keys = [keys[i] for i in idx_tr]\n val_keys = [keys[i] for i in idx_val]\n self.print_to_log_file(\"This random 80:20 split has %d training and %d validation cases.\"\n % (len(tr_keys), len(val_keys)))\n\n tr_keys.sort()\n val_keys.sort()\n self.dataset_tr = OrderedDict()\n for i in tr_keys:\n self.dataset_tr[i] = self.dataset[i]\n self.dataset_val = OrderedDict()\n for i in val_keys:\n self.dataset_val[i] = self.dataset[i]\n\n def setup_DA_params(self):\n \"\"\"\n - we increase roation angle from [-15, 15] to [-30, 30]\n - scale range is now (0.7, 1.4), was (0.85, 1.25)\n - we don't do elastic deformation anymore\n\n :return:\n \"\"\"\n\n self.deep_supervision_scales = [[1, 1, 1]] + list(list(i) for i in 1 / np.cumprod(\n np.vstack(self.net_num_pool_op_kernel_sizes), axis=0))[:-1]\n\n if self.threeD:\n self.data_aug_params = default_3D_augmentation_params\n self.data_aug_params['rotation_x'] = (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi)\n self.data_aug_params['rotation_y'] = (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi)\n self.data_aug_params['rotation_z'] = (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi)\n if self.do_dummy_2D_aug:\n self.data_aug_params[\"dummy_2D\"] = True\n self.print_to_log_file(\"Using dummy2d data augmentation\")\n self.data_aug_params[\"elastic_deform_alpha\"] = \\\n default_2D_augmentation_params[\"elastic_deform_alpha\"]\n self.data_aug_params[\"elastic_deform_sigma\"] = \\\n default_2D_augmentation_params[\"elastic_deform_sigma\"]\n self.data_aug_params[\"rotation_x\"] = default_2D_augmentation_params[\"rotation_x\"]\n else:\n self.do_dummy_2D_aug = False\n if max(self.patch_size) / min(self.patch_size) > 1.5:\n default_2D_augmentation_params['rotation_x'] = (-15. / 360 * 2. * np.pi, 15. / 360 * 2. * np.pi)\n self.data_aug_params = default_2D_augmentation_params\n self.data_aug_params[\"mask_was_used_for_normalization\"] = self.use_mask_for_norm\n\n if self.do_dummy_2D_aug:\n self.basic_generator_patch_size = get_patch_size(self.patch_size[1:],\n self.data_aug_params['rotation_x'],\n self.data_aug_params['rotation_y'],\n self.data_aug_params['rotation_z'],\n self.data_aug_params['scale_range'])\n self.basic_generator_patch_size = np.array([self.patch_size[0]] + list(self.basic_generator_patch_size))\n else:\n self.basic_generator_patch_size = get_patch_size(self.patch_size, self.data_aug_params['rotation_x'],\n self.data_aug_params['rotation_y'],\n self.data_aug_params['rotation_z'],\n self.data_aug_params['scale_range'])\n\n self.data_aug_params[\"scale_range\"] = (0.7, 1.4)\n self.data_aug_params[\"do_elastic\"] = False\n self.data_aug_params['selected_seg_channels'] = [0]\n self.data_aug_params['patch_size_for_spatialtransform'] = self.patch_size\n\n self.data_aug_params[\"num_cached_per_thread\"] = 2\n\n def maybe_update_lr(self, epoch=None):\n \"\"\"\n if epoch is not None we overwrite epoch. Else we use epoch = self.epoch + 1\n\n (maybe_update_lr is called in on_epoch_end which is called before epoch is incremented.\n herefore we need to do +1 here)\n\n :param epoch:\n :return:\n \"\"\"\n if epoch is None:\n ep = self.epoch + 1\n else:\n ep = epoch\n self.optimizer.param_groups[0]['lr'] = poly_lr(ep, self.max_num_epochs, self.initial_lr, 0.9)\n self.print_to_log_file(\"lr:\", np.round(self.optimizer.param_groups[0]['lr'], decimals=6))\n\n def on_epoch_end(self):\n \"\"\"\n overwrite patient-based early stopping. Always run to 1000 epochs\n :return:\n \"\"\"\n super().on_epoch_end()\n continue_training = self.epoch < self.max_num_epochs\n\n # it can rarely happen that the momentum of nnUNetTrainerV2 is too high for some dataset. If at epoch 100 the\n # estimated validation Dice is still 0 then we reduce the momentum from 0.99 to 0.95\n if self.epoch == 100:\n if self.all_val_eval_metrics[-1] == 0:\n self.optimizer.param_groups[0][\"momentum\"] = 0.95\n self.network.apply(InitWeights_He(1e-2))\n self.print_to_log_file(\"At epoch 100, the mean foreground Dice was 0. This can be caused by a too \"\n \"high momentum. High momentum (0.99) is good for datasets where it works, but \"\n \"sometimes causes issues such as this one. Momentum has now been reduced to \"\n \"0.95 and network weights have been reinitialized\")\n return continue_training\n\n def run_training(self):\n \"\"\"\n if we run with -c then we need to set the correct lr for the first epoch, otherwise it will run the first\n continued epoch with self.initial_lr\n\n we also need to make sure deep supervision in the network is enabled for training, thus the wrapper\n :return:\n \"\"\"\n self.maybe_update_lr(self.epoch) # if we dont overwrite epoch then self.epoch+1 is used which is not what we\n # want at the start of the training\n ds = self.network.do_ds\n if not self.disable_ds:\n self.network.do_ds = True\n ret = super().run_training()\n self.network.do_ds = ds\n\n\n\n return ret" }, { "identifier": "InitWeights_He", "path": "nn_transunet/trainer/nnUNetTrainerV2.py", "snippet": "class InitWeights_He(object):\n def __init__(self, neg_slope=1e-2):\n self.neg_slope = neg_slope\n\n def __call__(self, module):\n if isinstance(module, nn.Conv3d) or isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d) or isinstance(module, nn.ConvTranspose3d):\n module.weight = nn.init.kaiming_normal_(module.weight, a=self.neg_slope)\n if module.bias is not None:\n module.bias = nn.init.constant_(module.bias, 0)" }, { "identifier": "get_moreDA_augmentation", "path": "nn_transunet/data/data_augmentation_moreDA.py", "snippet": "def get_moreDA_augmentation(dataloader_train, dataloader_val, patch_size, params=default_3D_augmentation_params,\n border_val_seg=-1,\n seeds_train=None, seeds_val=None, order_seg=1, order_data=3, deep_supervision_scales=None,\n soft_ds=False,\n classes=None, pin_memory=True, regions=None,\n use_nondetMultiThreadedAugmenter: bool = False,\n is_spatial_aug_only=False, reclip=None):\n\n # default_3D_augmentation_params: {'selected_data_channels': None, 'selected_seg_channels': [0], 'do_elastic': False, 'elastic_deform_alpha': (0.0, 900.0), 'elastic_deform_sigma': (9.0, 13.0), 'p_eldef': 0.2, 'do_scaling': True, 'scale_range': (0.7, 1.4), 'independent_scale_factor_for_each_axis': False, 'p_independent_scale_per_axis': 1, 'p_scale': 0.2, 'do_rotation': True, 'rotation_x': (-0.5235987755982988, 0.5235987755982988), 'rotation_y': (-0.5235987755982988, 0.5235987755982988), 'rotation_z': (-0.5235987755982988, 0.5235987755982988), 'rotation_p_per_axis': 1, 'p_rot': 0.2, 'random_crop': False, 'random_crop_dist_to_border': None, 'do_gamma': True, 'gamma_retain_stats': True, 'gamma_range': (0.7, 1.5), 'p_gamma': 0.3, 'do_mirror': True, 'mirror_axes': (0, 1, 2), 'dummy_2D': False, 'mask_was_used_for_normalization': OrderedDict([(0, False)]), 'border_mode_data': 'constant', 'all_segmentation_labels': None, 'move_last_seg_chanel_to_data': False, 'cascade_do_cascade_augmentations': False, 'cascade_random_binary_transform_p': 0.4, 'cascade_random_binary_transform_p_per_label': 1, 'cascade_random_binary_transform_size': (1, 8), 'cascade_remove_conn_comp_p': 0.2, 'cascade_remove_conn_comp_max_size_percent_threshold': 0.15, 'cascade_remove_conn_comp_fill_with_other_class_p': 0.0, 'do_additive_brightness': False, 'additive_brightness_p_per_sample': 0.15, 'additive_brightness_p_per_channel': 0.5, 'additive_brightness_mu': 0.0, 'additive_brightness_sigma': 0.1, 'num_threads': 12, 'num_cached_per_thread': 2, 'patch_size_for_spatialtransform': [64, 128, 128]} \n\n assert params.get('mirror') is None, \"old version of params, use new keyword do_mirror\"\n\n tr_transforms = []\n\n\n if params.get(\"selected_data_channels\") is not None:\n tr_transforms.append(DataChannelSelectionTransform(params.get(\"selected_data_channels\")))\n\n if params.get(\"selected_seg_channels\") is not None:\n tr_transforms.append(SegChannelSelectionTransform(params.get(\"selected_seg_channels\")))\n\n # don't do color augmentations while in 2d mode with 3d data because the color channel is overloaded!!\n if params.get(\"dummy_2D\") is not None and params.get(\"dummy_2D\"):\n ignore_axes = (0,)\n tr_transforms.append(Convert3DTo2DTransform())\n patch_size_spatial = patch_size[1:]\n else:\n patch_size_spatial = patch_size\n ignore_axes = None\n\n tr_transforms.append(SpatialTransform(\n patch_size_spatial, patch_center_dist_from_border=None,\n do_elastic_deform=params.get(\"do_elastic\"), alpha=params.get(\"elastic_deform_alpha\"),\n sigma=params.get(\"elastic_deform_sigma\"),\n do_rotation=params.get(\"do_rotation\"), angle_x=params.get(\"rotation_x\"), angle_y=params.get(\"rotation_y\"),\n angle_z=params.get(\"rotation_z\"), p_rot_per_axis=params.get(\"rotation_p_per_axis\"),\n do_scale=params.get(\"do_scaling\"), scale=params.get(\"scale_range\"),\n border_mode_data=params.get(\"border_mode_data\"), border_cval_data=0, order_data=order_data,\n border_mode_seg=\"constant\", border_cval_seg=border_val_seg,\n order_seg=order_seg, random_crop=params.get(\"random_crop\"), p_el_per_sample=params.get(\"p_eldef\"),\n p_scale_per_sample=params.get(\"p_scale\"), p_rot_per_sample=params.get(\"p_rot\"),\n independent_scale_for_each_axis=params.get(\"independent_scale_factor_for_each_axis\")\n ))\n\n if params.get(\"dummy_2D\"):\n tr_transforms.append(Convert2DTo3DTransform())\n\n # we need to put the color augmentations after the dummy 2d part (if applicable). Otherwise the overloaded color\n # channel gets in the way\n tr_transforms.append(GaussianNoiseTransform(p_per_sample=0.1)) # a kind of noise transform\n tr_transforms.append(GaussianBlurTransform((0.5, 1.), different_sigma_per_channel=True, p_per_sample=0.2, p_per_channel=0.5))\n tr_transforms.append(BrightnessMultiplicativeTransform(multiplier_range=(0.75, 1.25), p_per_sample=0.15))\n\n if params.get(\"do_additive_brightness\"):\n tr_transforms.append(BrightnessTransform(params.get(\"additive_brightness_mu\"),\n params.get(\"additive_brightness_sigma\"),\n True, p_per_sample=params.get(\"additive_brightness_p_per_sample\"),\n p_per_channel=params.get(\"additive_brightness_p_per_channel\")))\n\n tr_transforms.append(ContrastAugmentationTransform(p_per_sample=0.15))\n tr_transforms.append(SimulateLowResolutionTransform(zoom_range=(0.5, 1), per_channel=True,\n p_per_channel=0.5,\n order_downsample=0, order_upsample=3, p_per_sample=0.25,\n ignore_axes=ignore_axes))\n tr_transforms.append(\n GammaTransform(params.get(\"gamma_range\"), True, True, retain_stats=params.get(\"gamma_retain_stats\"),\n p_per_sample=0.1)) # inverted gamma, a kind of color transform\n\n if params.get(\"do_gamma\"):\n tr_transforms.append(\n GammaTransform(params.get(\"gamma_range\"), False, True, retain_stats=params.get(\"gamma_retain_stats\"),\n p_per_sample=params[\"p_gamma\"]))\n if params.get(\"do_mirror\") or params.get(\"mirror\"):\n tr_transforms.append(MirrorTransform(params.get(\"mirror_axes\")))\n\n if params.get(\"mask_was_used_for_normalization\") is not None:\n mask_was_used_for_normalization = params.get(\"mask_was_used_for_normalization\")\n tr_transforms.append(MaskTransform(mask_was_used_for_normalization, mask_idx_in_seg=0, set_outside_to=0))\n # Replaces all pixels in data_dict[input_key] that have value remove_label with replace_with and saves the result to data_dict[output_key]\n tr_transforms.append(RemoveLabelTransform(-1, 0))\n\n if params.get(\"move_last_seg_chanel_to_data\") is not None and params.get(\"move_last_seg_chanel_to_data\"): # only used for cascade\n print(\"only used for cascaded!\")\n raise NotImplementedError\n\n tr_transforms.append(RenameTransform('seg', 'target', True))\n\n if regions is not None:\n tr_transforms.append(ConvertSegmentationToRegionsTransform(regions, 'target', 'target'))\n\n if deep_supervision_scales is not None:\n if soft_ds:\n assert classes is not None\n tr_transforms.append(DownsampleSegForDSTransform3(deep_supervision_scales, 'target', 'target', classes))\n else:\n tr_transforms.append(DownsampleSegForDSTransform2(deep_supervision_scales, 0, input_key='target',\n output_key='target'))\n\n tr_transforms.append(NumpyToTensor(['data', 'target'], 'float'))\n tr_transforms = Compose(tr_transforms)\n\n if use_nondetMultiThreadedAugmenter:\n if NonDetMultiThreadedAugmenter is None:\n raise RuntimeError('NonDetMultiThreadedAugmenter is not yet available')\n batchgenerator_train = NonDetMultiThreadedAugmenter(dataloader_train, tr_transforms, params.get('num_threads'),\n params.get(\"num_cached_per_thread\"), seeds=seeds_train,\n pin_memory=pin_memory)\n else:\n batchgenerator_train = MultiThreadedAugmenter(dataloader_train, tr_transforms, params.get('num_threads'),\n params.get(\"num_cached_per_thread\"),\n seeds=seeds_train, pin_memory=pin_memory)\n # batchgenerator_train = SingleThreadedAugmenter(dataloader_train, tr_transforms)\n # import IPython;IPython.embed()\n\n val_transforms = []\n val_transforms.append(RemoveLabelTransform(-1, 0))\n if params.get(\"selected_data_channels\") is not None:\n val_transforms.append(DataChannelSelectionTransform(params.get(\"selected_data_channels\")))\n if params.get(\"selected_seg_channels\") is not None:\n val_transforms.append(SegChannelSelectionTransform(params.get(\"selected_seg_channels\")))\n\n if params.get(\"move_last_seg_chanel_to_data\") is not None and params.get(\"move_last_seg_chanel_to_data\"):\n print(\"only used for cascaded!\")\n raise NotImplementedError\n # val_transforms.append(MoveSegAsOneHotToData(1, params.get(\"all_segmentation_labels\"), 'seg', 'data'))\n\n\n val_transforms.append(RenameTransform('seg', 'target', True))\n\n if regions is not None:\n val_transforms.append(ConvertSegmentationToRegionsTransform(regions, 'target', 'target'))\n\n if deep_supervision_scales is not None:\n if soft_ds:\n assert classes is not None\n val_transforms.append(DownsampleSegForDSTransform3(deep_supervision_scales, 'target', 'target', classes))\n else:\n val_transforms.append(DownsampleSegForDSTransform2(deep_supervision_scales, 0, input_key='target',\n output_key='target'))\n\n val_transforms.append(NumpyToTensor(['data', 'target'], 'float'))\n val_transforms = Compose(val_transforms)\n\n if use_nondetMultiThreadedAugmenter:\n if NonDetMultiThreadedAugmenter is None:\n raise RuntimeError('NonDetMultiThreadedAugmenter is not yet available')\n batchgenerator_val = NonDetMultiThreadedAugmenter(dataloader_val, val_transforms,\n max(params.get('num_threads') // 2, 1),\n params.get(\"num_cached_per_thread\"),\n seeds=seeds_val, pin_memory=pin_memory)\n else:\n batchgenerator_val = MultiThreadedAugmenter(dataloader_val, val_transforms,\n max(params.get('num_threads') // 2, 1),\n params.get(\"num_cached_per_thread\"),\n seeds=seeds_val, pin_memory=pin_memory)\n # batchgenerator_val = SingleThreadedAugmenter(dataloader_val, val_transforms)\n return batchgenerator_train, batchgenerator_val" }, { "identifier": "unpack_dataset", "path": "nn_transunet/data/dataset_loading.py", "snippet": "def unpack_dataset(folder, threads=default_num_threads, key=\"data\"):\n \"\"\"\n unpacks all npz files in a folder to npy (whatever you want to have unpacked must be saved unter key)\n :param folder:\n :param threads:\n :param key:\n :return:\n \"\"\"\n p = Pool(threads)\n npz_files = subfiles(folder, True, None, \".npz\", True)\n p.map(convert_to_npy, zip(npz_files, [key] * len(npz_files)))\n p.close()\n p.join()" }, { "identifier": "default_2D_augmentation_params", "path": "nn_transunet/data/default_data_augmentation.py", "snippet": "def get_patch_size(final_patch_size, rot_x, rot_y, rot_z, scale_range):\ndef get_default_augmentation(dataloader_train, dataloader_val, patch_size, params=default_3D_augmentation_params,\n border_val_seg=-1, pin_memory=True,\n seeds_train=None, seeds_val=None, regions=None):" }, { "identifier": "Generic_TransUNet_max_ppbp", "path": "nn_transunet/networks/transunet3d_model.py", "snippet": "class Generic_TransUNet_max_ppbp(SegmentationNetwork):\n DEFAULT_BATCH_SIZE_3D = 2\n DEFAULT_PATCH_SIZE_3D = (64, 192, 160)\n SPACING_FACTOR_BETWEEN_STAGES = 2\n BASE_NUM_FEATURES_3D = 30\n MAX_NUMPOOL_3D = 999\n MAX_NUM_FILTERS_3D = 320\n\n DEFAULT_PATCH_SIZE_2D = (256, 256)\n BASE_NUM_FEATURES_2D = 30\n DEFAULT_BATCH_SIZE_2D = 50\n MAX_NUMPOOL_2D = 999\n MAX_FILTERS_2D = 480\n\n use_this_for_batch_size_computation_2D = 19739648\n use_this_for_batch_size_computation_3D = 520000000 # 505789440\n\n def __init__(self, input_channels, base_num_features, num_classes, num_pool, num_conv_per_stage=2,\n feat_map_mul_on_downscale=2, conv_op=nn.Conv2d,\n norm_op=nn.BatchNorm2d, norm_op_kwargs=None,\n dropout_op=nn.Dropout2d, dropout_op_kwargs=None,\n nonlin=nn.LeakyReLU, nonlin_kwargs=None, deep_supervision=True, dropout_in_localization=False,\n final_nonlin=softmax_helper, weightInitializer=InitWeights_He(1e-2), pool_op_kernel_sizes=None,\n conv_kernel_sizes=None,\n upscale_logits=False, convolutional_pooling=False, convolutional_upsampling=False, # TODO default False\n max_num_features=None, basic_block=ConvDropoutNormNonlin,\n seg_output_use_bias=False,\n patch_size=None, is_vit_pretrain=False, \n vit_depth=12, vit_hidden_size=768, vit_mlp_dim=3072, vit_num_heads=12,\n max_msda='', is_max_ms=True, is_max_ms_fpn=False, max_n_fpn=4, max_ms_idxs=[-4,-3,-2], max_ss_idx=0,\n is_max_bottleneck_transformer=False, max_seg_weight=1.0, max_hidden_dim=256, max_dec_layers=10,\n mw = 0.5,\n is_max=True, is_masked_attn=False, is_max_ds=False, is_masking=False, is_masking_argmax=False,\n is_fam=False, fam_k=5, fam_reduct_ratio=8,\n is_max_hungarian=False, num_queries=None, is_max_cls=False,\n point_rend=False, num_point_rend=None, no_object_weight=None, is_mhsa_float32=False, no_max_hw_pe=False,\n max_infer=None, cost_weight=[2.0, 5.0, 5.0], vit_layer_scale=False, decoder_layer_scale=False):\n\n super(Generic_TransUNet_max_ppbp, self).__init__()\n\n # newly added\n self.is_fam = is_fam\n self.is_max, self.max_msda, self.is_max_ms, self.is_max_ms_fpn, self.max_n_fpn, self.max_ss_idx, self.mw = is_max, max_msda, is_max_ms, is_max_ms_fpn, max_n_fpn, max_ss_idx, mw\n self.max_ms_idxs = max_ms_idxs\n\n self.is_max_cls = is_max_cls\n self.is_masked_attn, self.is_max_ds = is_masked_attn, is_max_ds\n self.is_max_bottleneck_transformer = is_max_bottleneck_transformer\n\n self.convolutional_upsampling = convolutional_upsampling\n self.convolutional_pooling = convolutional_pooling\n self.upscale_logits = upscale_logits\n if nonlin_kwargs is None:\n nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True}\n if dropout_op_kwargs is None:\n dropout_op_kwargs = {'p': 0.5, 'inplace': True}\n if norm_op_kwargs is None:\n norm_op_kwargs = {'eps': 1e-5, 'affine': True, 'momentum': 0.1}\n\n self.conv_kwargs = {'stride': 1, 'dilation': 1, 'bias': True}\n\n self.nonlin = nonlin\n self.nonlin_kwargs = nonlin_kwargs\n self.dropout_op_kwargs = dropout_op_kwargs\n self.norm_op_kwargs = norm_op_kwargs\n self.weightInitializer = weightInitializer\n self.conv_op = conv_op\n self.norm_op = norm_op\n self.dropout_op = dropout_op\n self.num_classes = num_classes\n self.final_nonlin = final_nonlin\n self._deep_supervision = deep_supervision\n self.do_ds = deep_supervision\n\n if conv_op == nn.Conv2d:\n upsample_mode = 'bilinear'\n pool_op = nn.MaxPool2d\n transpconv = nn.ConvTranspose2d\n if pool_op_kernel_sizes is None:\n pool_op_kernel_sizes = [(2, 2)] * num_pool\n if conv_kernel_sizes is None:\n conv_kernel_sizes = [(3, 3)] * (num_pool + 1)\n elif conv_op == nn.Conv3d:\n upsample_mode = 'trilinear'\n pool_op = nn.MaxPool3d\n transpconv = nn.ConvTranspose3d\n if pool_op_kernel_sizes is None:\n pool_op_kernel_sizes = [(2, 2, 2)] * num_pool\n if conv_kernel_sizes is None:\n conv_kernel_sizes = [(3, 3, 3)] * (num_pool + 1)\n else:\n raise ValueError(\"unknown convolution dimensionality, conv op: %s\" % str(conv_op))\n\n self.input_shape_must_be_divisible_by = np.prod(pool_op_kernel_sizes, 0, dtype=np.int64)\n self.pool_op_kernel_sizes = pool_op_kernel_sizes\n self.conv_kernel_sizes = conv_kernel_sizes\n\n self.conv_pad_sizes = []\n for krnl in self.conv_kernel_sizes:\n self.conv_pad_sizes.append([1 if i == 3 else 0 for i in krnl])\n\n if max_num_features is None:\n if self.conv_op == nn.Conv3d:\n self.max_num_features = self.MAX_NUM_FILTERS_3D\n else:\n self.max_num_features = self.MAX_FILTERS_2D\n else:\n self.max_num_features = max_num_features\n\n self.conv_blocks_context = []\n self.conv_blocks_localization = []\n self.td = []\n self.tu = []\n\n\n self.fams = []\n\n output_features = base_num_features\n input_features = input_channels\n\n for d in range(num_pool):\n # determine the first stride\n if d != 0 and self.convolutional_pooling:\n first_stride = pool_op_kernel_sizes[d - 1]\n else:\n first_stride = None\n\n self.conv_kwargs['kernel_size'] = self.conv_kernel_sizes[d]\n self.conv_kwargs['padding'] = self.conv_pad_sizes[d]\n # add convolutions\n self.conv_blocks_context.append(StackedConvLayers(input_features, output_features, num_conv_per_stage,\n self.conv_op, self.conv_kwargs, self.norm_op,\n self.norm_op_kwargs, self.dropout_op,\n self.dropout_op_kwargs, self.nonlin, self.nonlin_kwargs,\n first_stride, basic_block=basic_block))\n if not self.convolutional_pooling:\n self.td.append(pool_op(pool_op_kernel_sizes[d]))\n input_features = output_features\n output_features = int(np.round(output_features * feat_map_mul_on_downscale))\n\n output_features = min(output_features, self.max_num_features)\n\n # now the bottleneck.\n # determine the first stride\n if self.convolutional_pooling:\n first_stride = pool_op_kernel_sizes[-1]\n else:\n first_stride = None\n\n # the output of the last conv must match the number of features from the skip connection if we are not using\n # convolutional upsampling. If we use convolutional upsampling then the reduction in feature maps will be\n # done by the transposed conv\n if self.convolutional_upsampling:\n final_num_features = output_features\n else:\n final_num_features = self.conv_blocks_context[-1].output_channels\n\n self.conv_kwargs['kernel_size'] = self.conv_kernel_sizes[num_pool]\n self.conv_kwargs['padding'] = self.conv_pad_sizes[num_pool]\n self.conv_blocks_context.append(nn.Sequential(\n StackedConvLayers(input_features, output_features, num_conv_per_stage - 1, self.conv_op, self.conv_kwargs,\n self.norm_op, self.norm_op_kwargs, self.dropout_op, self.dropout_op_kwargs, self.nonlin,\n self.nonlin_kwargs, first_stride, basic_block=basic_block),\n StackedConvLayers(output_features, final_num_features, 1, self.conv_op, self.conv_kwargs,\n self.norm_op, self.norm_op_kwargs, self.dropout_op, self.dropout_op_kwargs, self.nonlin,\n self.nonlin_kwargs, basic_block=basic_block)))\n\n # if we don't want to do dropout in the localization pathway then we set the dropout prob to zero here\n if not dropout_in_localization:\n old_dropout_p = self.dropout_op_kwargs['p']\n self.dropout_op_kwargs['p'] = 0.0\n\n # now lets build the localization pathway\n for u in range(num_pool):\n nfeatures_from_down = final_num_features\n nfeatures_from_skip = self.conv_blocks_context[\n -(2 + u)].output_channels # self.conv_blocks_context[-1] is bottleneck, so start with -2\n n_features_after_tu_and_concat = nfeatures_from_skip * 2\n\n # the first conv reduces the number of features to match those of skip\n # the following convs work on that number of features\n # if not convolutional upsampling then the final conv reduces the num of features again\n if u != num_pool - 1 and not self.convolutional_upsampling:\n final_num_features = self.conv_blocks_context[-(3 + u)].output_channels\n else:\n final_num_features = nfeatures_from_skip\n\n if not self.convolutional_upsampling:\n self.tu.append(Upsample(scale_factor=pool_op_kernel_sizes[-(u + 1)], mode=upsample_mode))\n else:\n self.tu.append(transpconv(nfeatures_from_down, nfeatures_from_skip, pool_op_kernel_sizes[-(u + 1)],\n pool_op_kernel_sizes[-(u + 1)], bias=False))\n\n self.conv_kwargs['kernel_size'] = self.conv_kernel_sizes[- (u + 1)]\n self.conv_kwargs['padding'] = self.conv_pad_sizes[- (u + 1)]\n self.conv_blocks_localization.append(nn.Sequential(\n StackedConvLayers(n_features_after_tu_and_concat, nfeatures_from_skip, num_conv_per_stage - 1,\n self.conv_op, self.conv_kwargs, self.norm_op, self.norm_op_kwargs, self.dropout_op,\n self.dropout_op_kwargs, self.nonlin, self.nonlin_kwargs, basic_block=basic_block),\n StackedConvLayers(nfeatures_from_skip, final_num_features, 1, self.conv_op, self.conv_kwargs,\n self.norm_op, self.norm_op_kwargs, self.dropout_op, self.dropout_op_kwargs,\n self.nonlin, self.nonlin_kwargs, basic_block=basic_block)\n ))\n\n\n\n if self.is_fam:\n self.fams = nn.ModuleList(self.fams)\n\n if self.do_ds:\n self.seg_outputs = []\n for ds in range(len(self.conv_blocks_localization)):\n self.seg_outputs.append(conv_op(self.conv_blocks_localization[ds][-1].output_channels, num_classes,\n 1, 1, 0, 1, 1, seg_output_use_bias))\n self.seg_outputs = nn.ModuleList(self.seg_outputs)\n\n self.upscale_logits_ops = []\n cum_upsample = np.cumprod(np.vstack(pool_op_kernel_sizes), axis=0)[::-1]\n for usl in range(num_pool - 1):\n if self.upscale_logits:\n self.upscale_logits_ops.append(Upsample(scale_factor=tuple([int(i) for i in cum_upsample[usl + 1]]),\n mode=upsample_mode))\n else:\n self.upscale_logits_ops.append(lambda x: x)\n\n if not dropout_in_localization:\n self.dropout_op_kwargs['p'] = old_dropout_p\n\n # register all modules properly\n self.conv_blocks_localization = nn.ModuleList(self.conv_blocks_localization)\n self.conv_blocks_context = nn.ModuleList(self.conv_blocks_context)\n self.td = nn.ModuleList(self.td)\n self.tu = nn.ModuleList(self.tu)\n\n if self.upscale_logits:\n self.upscale_logits_ops = nn.ModuleList(\n self.upscale_logits_ops) # lambda x:x is not a Module so we need to distinguish here\n\n if self.weightInitializer is not None:\n self.apply(self.weightInitializer)\n # self.apply(print_module_training_status)\n\n # Transformer configuration\n if self.is_max_bottleneck_transformer:\n self.patch_size = patch_size # e.g. [48, 192, 192]\n config_vit = CONFIGS_ViT['R50-ViT-B_16']\n config_vit.transformer.num_layers = vit_depth\n config_vit.hidden_size = vit_hidden_size # 768\n config_vit.transformer.mlp_dim = vit_mlp_dim # 3072\n config_vit.transformer.num_heads = vit_num_heads # 12\n self.conv_more = nn.Conv3d(config_vit.hidden_size, output_features, 1)\n num_pool_per_axis = np.prod(np.array(pool_op_kernel_sizes), axis=0)\n num_pool_per_axis = np.log2(num_pool_per_axis).astype(np.uint8)\n feat_size = [int(self.patch_size[0]/2**num_pool_per_axis[0]), int(self.patch_size[1]/2**num_pool_per_axis[1]), int(self.patch_size[2]/2**num_pool_per_axis[2])]\n self.transformer = Transformer(config_vit, feat_size=feat_size, vis=False, feat_channels=output_features, use_layer_scale=vit_layer_scale)\n if is_vit_pretrain:\n self.transformer.load_from(weights=np.load(config_vit.pretrained_path))\n\n\n if self.is_max:\n # Max PPB+ configuration (i.e. MultiScaleStandardTransformerDecoder)\n cfg = {\n \"num_classes\": num_classes,\n \"hidden_dim\": max_hidden_dim,\n \"num_queries\": num_classes if num_queries is None else num_queries, # N=K if 'fixed matching', else default=100,\n \"nheads\": 8,\n \"dim_feedforward\": max_hidden_dim * 8, # 2048,\n \"dec_layers\": max_dec_layers, # 9 decoder layers, add one for the loss on learnable query?\n \"pre_norm\": False,\n \"enforce_input_project\": False,\n \"mask_dim\": max_hidden_dim, # input feat of segm head?\n \"non_object\": False,\n \"use_layer_scale\": decoder_layer_scale,\n }\n cfg['non_object'] = is_max_cls\n input_proj_list = [] # from low resolution to high resolution (res4 -> res1), [1, 1024, 14, 14], [1, 512, 28, 28], 1, 256, 56, 56], [1, 64, 112, 112]\n decoder_channels = [320, 320, 256, 128, 64, 32]\n if self.is_max_ms: # use multi-scale feature as Transformer decoder input\n if self.is_max_ms_fpn:\n for idx, in_channels in enumerate(decoder_channels[:max_n_fpn]): # max_n_fpn=4: 1/32, 1/16, 1/8, 1/4\n input_proj_list.append(nn.Sequential(\n nn.Conv3d(in_channels, max_hidden_dim, kernel_size=1),\n nn.GroupNorm(32, max_hidden_dim),\n nn.Upsample(size=(int(patch_size[0]/2), int(patch_size[1]/4), int(patch_size[2]/4)), mode='trilinear')\n )) # proj to scale (1, 1/2, 1/2), TODO: init\n self.input_proj = nn.ModuleList(input_proj_list)\n self.linear_encoder_feature = nn.Conv3d(max_hidden_dim * max_n_fpn, max_hidden_dim, 1, 1) # concat four-level feature\n else:\n for idx, in_channels in enumerate([decoder_channels[i] for i in self.max_ms_idxs]):\n input_proj_list.append(nn.Sequential(\n nn.Conv3d(in_channels, max_hidden_dim, kernel_size=1),\n nn.GroupNorm(32, max_hidden_dim),\n ))\n self.input_proj = nn.ModuleList(input_proj_list)\n\n # self.linear_mask_features =nn.Conv3d(decoder_channels[max_n_fpn-1], cfg[\"mask_dim\"], kernel_size=1, stride=1, padding=0,) # low-level feat, dot product Trans-feat\n self.linear_mask_features =nn.Conv3d(decoder_channels[-1], cfg[\"mask_dim\"], kernel_size=1, stride=1, padding=0,) # following SingleScale, high-level feat, obtain seg_map\n else:\n self.linear_encoder_feature = nn.Conv3d(decoder_channels[max_ss_idx], cfg[\"mask_dim\"], kernel_size=1)\n self.linear_mask_features = nn.Conv3d(decoder_channels[-1], cfg[\"mask_dim\"], kernel_size=1, stride=1, padding=0,) # low-level feat, dot product Trans-feat\n\n if self.is_masked_attn:\n from .mask2former_modeling.transformer_decoder.mask2former_transformer_decoder3d import MultiScaleMaskedTransformerDecoder3d\n cfg['num_feature_levels'] = 1 if not self.is_max_ms or self.is_max_ms_fpn else 3\n cfg[\"is_masking\"] = True if is_masking else False\n cfg[\"is_masking_argmax\"] = True if is_masking_argmax else False\n cfg[\"is_mhsa_float32\"] = True if is_mhsa_float32 else False\n cfg[\"no_max_hw_pe\"] = True if no_max_hw_pe else False\n self.predictor = MultiScaleMaskedTransformerDecoder3d(in_channels=max_hidden_dim, mask_classification=is_max_cls, **cfg)\n else:\n from .mask2former_modeling.transformer_decoder.maskformer_transformer_decoder3d import StandardTransformerDecoder\n cfg[\"dropout\"], cfg[\"enc_layers\"], cfg[\"deep_supervision\"] = 0.1, 0, False\n self.predictor = StandardTransformerDecoder(in_channels=max_hidden_dim, mask_classification=is_max_cls, **cfg)\n\n def forward(self, x):\n skips = []\n seg_outputs = []\n for d in range(len(self.conv_blocks_context) - 1):\n x = self.conv_blocks_context[d](x)\n skips.append(x)\n if not self.convolutional_pooling:\n x = self.td[d](x)\n \n x = self.conv_blocks_context[-1](x)\n ######### TransUNet #########\n if self.is_max_bottleneck_transformer:\n x, attn = self.transformer(x) # [b, hidden, d/8, h/16, w/16]\n x = self.conv_more(x)\n #############################\n\n ds_feats = [] # obtain multi-scale feature\n ds_feats.append(x)\n for u in range(len(self.tu)):\n if u<len(self.tu)-1 and isinstance(self.is_fam, str) and self.is_fam.startswith('fam_down'):\n skip_down = nn.Upsample(size=x.shape[2:])(skips[-(u + 1)]) if x.shape[2:]!=skips[-(u + 1)].shape[2:] else skips[-(u + 1)]\n x_align = self.fams[u](x, x_l=skip_down)\n x = x + x_align\n\n x = self.tu[u](x) # merely an upsampling or transposeconv operation\n\n if isinstance(self.is_fam, bool) and self.is_fam:\n x_align = self.fams[u](x, x_l=skips[-(u + 1)])\n x = x + x_align\n x = torch.cat((x, skips[-(u + 1)]), dim=1)\n x = self.conv_blocks_localization[u](x)\n if self.do_ds:\n seg_outputs.append(self.final_nonlin(self.seg_outputs[u](x)))\n ds_feats.append(x)\n\n ######### Max PPB+ #########\n if self.is_max:\n if self.is_max_ms: # is_max_ms_fpn\n multi_scale_features = []\n ms_pixel_feats = ds_feats[:self.max_n_fpn] if self.is_max_ms_fpn else [ds_feats[i] for i in self.max_ms_idxs]\n \n for idx, f in enumerate(ms_pixel_feats): \n\n f = self.input_proj[idx](f) # proj into same spatial/channel dim , but transformer_decoder also project to same mask_dim \n multi_scale_features.append(f)\n transformer_decoder_in_feature = self.linear_encoder_feature(torch.cat(multi_scale_features, dim=1)) if self.is_max_ms_fpn else multi_scale_features # feature pyramid\n mask_features = self.linear_mask_features(ds_feats[-1]) # following SingleScale\n else:\n transformer_decoder_in_feature = self.linear_encoder_feature(ds_feats[self.max_ss_idx])\n mask_features = self.linear_mask_features(ds_feats[-1])\n \n predictions = self.predictor(transformer_decoder_in_feature, mask_features, mask=None)\n\n if self.is_max_cls and self.is_max_ds:\n if self._deep_supervision and self.do_ds:\n return [predictions] + [i(j) for i, j in zip(list(self.upscale_logits_ops)[::-1], seg_outputs[:-1][::-1])]\n return predictions\n\n elif self.is_max_ds and not self.is_max_ms and self.mw==1.0: # aux output of max decoder\n aux_out = [p['pred_masks'] for p in predictions['aux_outputs']] # ascending order\n all_out = [predictions[\"pred_masks\"]] + aux_out[::-1] # reverse order, w/o sigmoid activation\n return tuple(all_out)\n elif not self.is_max_ds and self.mw==1.0:\n raise NotImplementedError\n else:\n raise NotImplementedError\n\n #############################\n\n if self._deep_supervision and self.do_ds: # assuming turn off ds\n return tuple([seg_outputs[-1]] + [i(j) for i, j in zip(list(self.upscale_logits_ops)[::-1], seg_outputs[:-1][::-1])])\n else:\n return seg_outputs[-1]\n\n @staticmethod\n def compute_approx_vram_consumption(patch_size, num_pool_per_axis, base_num_features, max_num_features,\n num_modalities, num_classes, pool_op_kernel_sizes, deep_supervision=False,\n conv_per_stage=2):\n \"\"\"\n This only applies for num_conv_per_stage and convolutional_upsampling=True\n not real vram consumption. just a constant term to which the vram consumption will be approx proportional\n (+ offset for parameter storage)\n :param deep_supervision:\n :param patch_size:\n :param num_pool_per_axis:\n :param base_num_features:\n :param max_num_features:\n :param num_modalities:\n :param num_classes:\n :param pool_op_kernel_sizes:\n :return:\n \"\"\"\n if not isinstance(num_pool_per_axis, np.ndarray):\n num_pool_per_axis = np.array(num_pool_per_axis)\n\n npool = len(pool_op_kernel_sizes)\n\n map_size = np.array(patch_size)\n tmp = np.int64((conv_per_stage * 2 + 1) * np.prod(map_size, dtype=np.int64) * base_num_features +\n num_modalities * np.prod(map_size, dtype=np.int64) +\n num_classes * np.prod(map_size, dtype=np.int64))\n\n num_feat = base_num_features\n\n for p in range(npool):\n for pi in range(len(num_pool_per_axis)):\n map_size[pi] /= pool_op_kernel_sizes[p][pi]\n num_feat = min(num_feat * 2, max_num_features)\n num_blocks = (conv_per_stage * 2 + 1) if p < (npool - 1) else conv_per_stage # conv_per_stage + conv_per_stage for the convs of encode/decode and 1 for transposed conv\n tmp += num_blocks * np.prod(map_size, dtype=np.int64) * num_feat\n if deep_supervision and p < (npool - 2):\n tmp += np.prod(map_size, dtype=np.int64) * num_classes\n # print(p, map_size, num_feat, tmp)\n return tmp" } ]
from genericpath import exists from _warnings import warn from collections import OrderedDict from multiprocessing import Pool from time import sleep, time from typing import Tuple from nnunet.configuration import default_num_threads from nnunet.evaluation.evaluator import aggregate_scores from nnunet.inference.segmentation_export import save_segmentation_nifti_from_softmax from nnunet.network_architecture.neural_network import SegmentationNetwork from nnunet.postprocessing.connected_components import determine_postprocessing from nnunet.utilities.distributed import awesome_allgather_function from nnunet.utilities.nd_softmax import softmax_helper from nnunet.utilities.tensor_utilities import sum_tensor from nnunet.utilities.to_torch import to_cuda, maybe_to_torch from nnunet.training.loss_functions.crossentropy import RobustCrossEntropyLoss from nnunet.training.loss_functions.dice_loss import get_tp_fp_fn_tn from torch import nn, distributed from torch.backends import cudnn from torch.cuda.amp import autocast from torch.nn.parallel import DistributedDataParallel as DDP from torch.optim.lr_scheduler import _LRScheduler from tqdm import trange from ..trainer.nnUNetTrainerV2 import nnUNetTrainerV2, InitWeights_He from batchgenerators.utilities.file_and_folder_operations import maybe_mkdir_p, join, subfiles, isfile, load_pickle, \ save_json from ..data.data_augmentation_moreDA import get_moreDA_augmentation from ..data.dataset_loading import unpack_dataset from ..data.default_data_augmentation import default_2D_augmentation_params, get_patch_size, default_3D_augmentation_params from ..networks.transunet3d_model import Generic_TransUNet_max_ppbp from nnunet.training.data_augmentation.data_augmentation_insaneDA2 import get_insaneDA_augmentation2 from ..optimizers.lr_scheduler import LinearWarmupCosineAnnealingLR from torch.optim import lr_scheduler from network_trainer import warmup_poly_lr from network_trainer import poly_lr from ..networks.transunet3d_model import HungarianMatcher3D, compute_loss_hungarian from ..utils.dist_utils import check_call_hdfs_command, mkdir_hdfs import os import shutil import numpy as np import torch import torch.distributed as dist import torch.nn.functional as F
17,954
self.folder_with_preprocessed_data = join(self.dataset_directory, self.plans['data_identifier'] + "_stage%d" % self.stage) if training: self.dl_tr, self.dl_val = self.get_basic_generators() if self.unpack_data: if self.local_rank == 0: print("unpacking dataset") unpack_dataset(self.folder_with_preprocessed_data) print("done") distributed.barrier() else: # distributed.barrier() print( "INFO: Not unpacking data! Training may be slow due to that. Pray you are not using 2d or you " "will wait all winter for your model to finish!") # setting weights for deep supervision losses if not self.model.startswith("Generic") and self.args.fix_ds_net_numpool: # here is a bug, which need to be fixed! net_numpool = len(self.deep_supervision_scales) else: net_numpool = len(self.net_num_pool_op_kernel_sizes) # we give each output a weight which decreases exponentially (division by 2) as the resolution decreases # this gives higher resolution outputs more weight in the loss weights = np.array([1 / (2 ** i) for i in range(net_numpool)]) # we don't use the lowest 2 outputs. Normalize weights so that they sum to 1 mask = np.array([True if i < net_numpool - 1 else False for i in range(net_numpool)]) weights[~mask] = 0 weights = weights / weights.sum() self.ds_loss_weights = weights if self.disable_ds: self.ds_loss_weights[0]=1 self.ds_loss_weights[1:]=0 seeds_train = np.random.random_integers(0, 99999, self.data_aug_params.get('num_threads')) seeds_val = np.random.random_integers(0, 99999, max(self.data_aug_params.get('num_threads') // 2, 1)) print("seeds train", seeds_train) print("seeds_val", seeds_val) # add more transform into dataloader if self.reclip: lb, ub, means, stds = self.reclip[0], self.reclip[1], self.intensity_properties[0]['mean'], self.intensity_properties[0]['sd'] self.reclip = [lb, ub, means, stds] if self.args.config.find('500Region') != -1: # BraTSRegions_moreDA self.tr_gen, self.val_gen = get_insaneDA_augmentation2( self.dl_tr, self.dl_val, self.data_aug_params[ 'patch_size_for_spatialtransform'], self.data_aug_params, deep_supervision_scales=self.deep_supervision_scales, pin_memory=self.pin_memory, regions=self.regions ) # such that we can get val else: self.tr_gen, self.val_gen = get_moreDA_augmentation( self.dl_tr, self.dl_val, self.data_aug_params[ 'patch_size_for_spatialtransform'], self.data_aug_params, deep_supervision_scales=self.deep_supervision_scales, seeds_train=seeds_train, seeds_val=seeds_val, pin_memory=self.pin_memory, is_spatial_aug_only=self.is_spatial_aug_only, reclip=self.reclip ) self.print_to_log_file("TRAINING KEYS:\n %s" % (str(self.dataset_tr.keys())), also_print_to_console=False) # in network_trainer.py tr_keys = val_keys = list(self.dataset.keys()) if fold=='all' self.print_to_log_file("VALIDATION KEYS:\n %s" % (str(self.dataset_val.keys())), also_print_to_console=False) else: pass self.initialize_network() self.initialize_optimizer_and_scheduler() self.network = DDP(self.network, device_ids=[self.local_rank], find_unused_parameters=True) if self.local_rank==0: print(self.network) else: self.print_to_log_file('self.was_initialized is True, not running self.initialize again') self.was_initialized = True def initialize_network(self): """ - momentum 0.99 - SGD instead of Adam - self.lr_scheduler = None because we do poly_lr - deep supervision = True - i am sure I forgot something here Known issue: forgot to set neg_slope=0 in InitWeights_He; should not make a difference though :return: """ if self.model.startswith("Generic"): if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU # nnunet v1, not softmax..., interesting..., but compute_loss has consider the softmax.. net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} do_ds = not self.disable_ds if not do_ds: print("disable ds") if self.model == 'Generic_TransUNet_max_ppbp':
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #installed package class nnUNetTrainerV2_DDP(nnUNetTrainerV2): def __init__(self, plans_file, fold, local_rank, output_folder=None, dataset_directory=None, batch_dice=True, stage=None, unpack_data=True, deterministic=True, distribute_batch_size=False, fp16=False, model="Generic_UNet", input_size=(64, 160, 160), args=None): super().__init__(plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data, deterministic, fp16) self.init_args = ( plans_file, fold, local_rank, output_folder, dataset_directory, batch_dice, stage, unpack_data, deterministic, distribute_batch_size, fp16) assert args is not None self.args = args if self.args.config.find('500Region') != -1: self.regions = {"whole tumor": (1, 2, 3), "tumor core": (2, 3), "enhancing tumor": (3,) # correct } if self.args.config.find('500RegionFix') != -1: self.regions = {"whole tumor": (1, 2, 3), "tumor core": (2, 3), "enhancing tumor": (2,) # fig 1: the innermost tumor, but this is a bug!! } self.regions_class_order = (1, 2, 3) self.layer_decay = args.layer_decay self.lr_scheduler_name = args.lrschedule # [ TO DO ] self.reclip = args.reclip self.warmup_epochs = args.warmup_epochs self.min_lr = args.min_lr self.is_spatial_aug_only = args.is_spatial_aug_only if "model_params" in args: self.model_params = args.model_params else: self.model_params = {} self.optim_name = args.optim_name self.find_zero_weight_decay = args.find_zero_weight_decay self.model = args.model self.resume = args.resume self.input_size=input_size self.disable_ds=args.disable_ds self.max_num_epochs = args.max_num_epochs # set 8 gpu training self.initial_lr = args.initial_lr # 8 * 0.01 self.weight_decay = args.weight_decay # 3e-5 in nnUNetTrainer.py self.save_every = 1 # prev 50 self.distribute_batch_size = distribute_batch_size np.random.seed(local_rank) torch.manual_seed(local_rank) if torch.cuda.is_available(): torch.cuda.manual_seed_all(local_rank) self.local_rank = local_rank if torch.cuda.is_available(): torch.cuda.set_device(local_rank) # dist.init_process_group(backend='nccl', init_method='env://') # init outside self.loss = None self.ce_loss = RobustCrossEntropyLoss() self.global_batch_size = None # we need to know this to properly steer oversample def setup_DA_params_BraTSRegions(self): # nnUNetTrainerV2.setup_DA_params(self) self.deep_supervision_scales = [[1, 1, 1]] + list(list(i) for i in 1 / np.cumprod( np.vstack(self.net_num_pool_op_kernel_sizes), axis=0))[:-1] if self.threeD: self.data_aug_params = default_3D_augmentation_params self.data_aug_params['rotation_x'] = (-90. / 360 * 2. * np.pi, 90. / 360 * 2. * np.pi) self.data_aug_params['rotation_y'] = (-90. / 360 * 2. * np.pi, 90. / 360 * 2. * np.pi) self.data_aug_params['rotation_z'] = (-90. / 360 * 2. * np.pi, 90. / 360 * 2. * np.pi) if self.do_dummy_2D_aug: self.data_aug_params["dummy_2D"] = True self.print_to_log_file("Using dummy2d data augmentation") self.data_aug_params["elastic_deform_alpha"] = \ default_2D_augmentation_params["elastic_deform_alpha"] self.data_aug_params["elastic_deform_sigma"] = \ default_2D_augmentation_params["elastic_deform_sigma"] self.data_aug_params["rotation_x"] = default_2D_augmentation_params["rotation_x"] else: self.do_dummy_2D_aug = False if max(self.patch_size) / min(self.patch_size) > 1.5: default_2D_augmentation_params['rotation_x'] = (-180. / 360 * 2. * np.pi, 180. / 360 * 2. * np.pi) self.data_aug_params = default_2D_augmentation_params self.data_aug_params["mask_was_used_for_normalization"] = self.use_mask_for_norm if self.do_dummy_2D_aug: self.basic_generator_patch_size = get_patch_size(self.patch_size[1:], self.data_aug_params['rotation_x'], self.data_aug_params['rotation_y'], self.data_aug_params['rotation_z'], self.data_aug_params['scale_range']) self.basic_generator_patch_size = np.array([self.patch_size[0]] + list(self.basic_generator_patch_size)) else: self.basic_generator_patch_size = get_patch_size(self.patch_size, self.data_aug_params['rotation_x'], self.data_aug_params['rotation_y'], self.data_aug_params['rotation_z'], self.data_aug_params['scale_range']) self.data_aug_params['selected_seg_channels'] = [0] self.data_aug_params['patch_size_for_spatialtransform'] = self.patch_size self.data_aug_params["p_rot"] = 0.3 self.data_aug_params["scale_range"] = (0.65, 1.6) self.data_aug_params["p_scale"] = 0.3 self.data_aug_params["independent_scale_factor_for_each_axis"] = True self.data_aug_params["p_independent_scale_per_axis"] = 0.3 self.data_aug_params["do_elastic"] = True self.data_aug_params["p_eldef"] = 0.3 # LMH 0.2 -> 0.3 according to paper self.data_aug_params["eldef_deformation_scale"] = (0, 0.25) self.data_aug_params["do_additive_brightness"] = True self.data_aug_params["additive_brightness_mu"] = 0 self.data_aug_params["additive_brightness_sigma"] = 0.2 self.data_aug_params["additive_brightness_p_per_sample"] = 0.3 self.data_aug_params["additive_brightness_p_per_channel"] = 0.5 self.data_aug_params['gamma_range'] = (0.5, 1.6) self.data_aug_params['num_cached_per_thread'] = 4 def set_batch_size_and_oversample(self): batch_sizes = [] oversample_percents = [] world_size = self.args.world_size# dist.get_world_size() my_rank = self.args.rank # dist.get_rank() # not local_rank if self.args.total_batch_size: # actually it is global_batch_size # reset the batch_size per gpu accordingly self.batch_size = self.args.total_batch_size // world_size # if self.args.local_rank == 0: # print("total_batch_size: %d, updated batch_size per gpu %d, world_size %d" % (self.args.total_batch_size, self.batch_size, world_size)) if self.distribute_batch_size: # set total batch_size to 16 will be fine... self.global_batch_size = self.batch_size else: self.global_batch_size = self.batch_size * world_size batch_size_per_GPU = np.ceil(self.batch_size / world_size).astype(int) # probably 1 for rank in range(world_size): if self.distribute_batch_size: if (rank + 1) * batch_size_per_GPU > self.batch_size: batch_size = batch_size_per_GPU - ((rank + 1) * batch_size_per_GPU - self.batch_size) else: batch_size = batch_size_per_GPU else: batch_size = self.batch_size batch_sizes.append(batch_size) sample_id_low = 0 if len(batch_sizes) == 0 else np.sum(batch_sizes[:-1]) sample_id_high = np.sum(batch_sizes) if sample_id_high / self.global_batch_size < (1 - self.oversample_foreground_percent): oversample_percents.append(0.0) elif sample_id_low / self.global_batch_size > (1 - self.oversample_foreground_percent): oversample_percents.append(1.0) else: percent_covered_by_this_rank = sample_id_high / self.global_batch_size - sample_id_low / self.global_batch_size oversample_percent_here = 1 - (((1 - self.oversample_foreground_percent) - sample_id_low / self.global_batch_size) / percent_covered_by_this_rank) oversample_percents.append(oversample_percent_here) print("worker", my_rank, "oversample", oversample_percents[my_rank]) print("worker", my_rank, "batch_size", batch_sizes[my_rank]) # batch_sizes [self.batch_size]*world_size self.batch_size = batch_sizes[my_rank] self.oversample_foreground_percent = oversample_percents[my_rank] def save_checkpoint(self, fname, save_optimizer=True): if self.local_rank == 0: super().save_checkpoint(fname, save_optimizer) def plot_progress(self): if self.local_rank == 0: super().plot_progress() def print_to_log_file(self, *args, also_print_to_console=True): if self.local_rank == 0: super().print_to_log_file(*args, also_print_to_console=also_print_to_console) def process_plans(self, plans): super().process_plans(plans) if (self.patch_size != self.args.crop_size).any(): self.patch_size = self.args.crop_size self.set_batch_size_and_oversample() if self.args.config.find('500Region') != -1: self.num_classes = len(self.regions) # only care about foreground (compatible with sigmoid) def initialize(self, training=True, force_load_plans=False): """ :param training: :return: """ if not self.was_initialized: maybe_mkdir_p(self.output_folder) if force_load_plans or (self.plans is None): self.load_plans_file() self.process_plans(self.plans) self.setup_DA_params() if self.args.config.find('500Region') != -1: # BraTSRegions_moreDA self.setup_DA_params_BraTSRegions() if hasattr(self.args, 'deep_supervision_scales') and len(self.args.deep_supervision_scales)>0: self.deep_supervision_scales = self.args.deep_supervision_scales # overwrite setup_DA_params() from nnUNetTrainerV2 self.folder_with_preprocessed_data = join(self.dataset_directory, self.plans['data_identifier'] + "_stage%d" % self.stage) if training: self.dl_tr, self.dl_val = self.get_basic_generators() if self.unpack_data: if self.local_rank == 0: print("unpacking dataset") unpack_dataset(self.folder_with_preprocessed_data) print("done") distributed.barrier() else: # distributed.barrier() print( "INFO: Not unpacking data! Training may be slow due to that. Pray you are not using 2d or you " "will wait all winter for your model to finish!") # setting weights for deep supervision losses if not self.model.startswith("Generic") and self.args.fix_ds_net_numpool: # here is a bug, which need to be fixed! net_numpool = len(self.deep_supervision_scales) else: net_numpool = len(self.net_num_pool_op_kernel_sizes) # we give each output a weight which decreases exponentially (division by 2) as the resolution decreases # this gives higher resolution outputs more weight in the loss weights = np.array([1 / (2 ** i) for i in range(net_numpool)]) # we don't use the lowest 2 outputs. Normalize weights so that they sum to 1 mask = np.array([True if i < net_numpool - 1 else False for i in range(net_numpool)]) weights[~mask] = 0 weights = weights / weights.sum() self.ds_loss_weights = weights if self.disable_ds: self.ds_loss_weights[0]=1 self.ds_loss_weights[1:]=0 seeds_train = np.random.random_integers(0, 99999, self.data_aug_params.get('num_threads')) seeds_val = np.random.random_integers(0, 99999, max(self.data_aug_params.get('num_threads') // 2, 1)) print("seeds train", seeds_train) print("seeds_val", seeds_val) # add more transform into dataloader if self.reclip: lb, ub, means, stds = self.reclip[0], self.reclip[1], self.intensity_properties[0]['mean'], self.intensity_properties[0]['sd'] self.reclip = [lb, ub, means, stds] if self.args.config.find('500Region') != -1: # BraTSRegions_moreDA self.tr_gen, self.val_gen = get_insaneDA_augmentation2( self.dl_tr, self.dl_val, self.data_aug_params[ 'patch_size_for_spatialtransform'], self.data_aug_params, deep_supervision_scales=self.deep_supervision_scales, pin_memory=self.pin_memory, regions=self.regions ) # such that we can get val else: self.tr_gen, self.val_gen = get_moreDA_augmentation( self.dl_tr, self.dl_val, self.data_aug_params[ 'patch_size_for_spatialtransform'], self.data_aug_params, deep_supervision_scales=self.deep_supervision_scales, seeds_train=seeds_train, seeds_val=seeds_val, pin_memory=self.pin_memory, is_spatial_aug_only=self.is_spatial_aug_only, reclip=self.reclip ) self.print_to_log_file("TRAINING KEYS:\n %s" % (str(self.dataset_tr.keys())), also_print_to_console=False) # in network_trainer.py tr_keys = val_keys = list(self.dataset.keys()) if fold=='all' self.print_to_log_file("VALIDATION KEYS:\n %s" % (str(self.dataset_val.keys())), also_print_to_console=False) else: pass self.initialize_network() self.initialize_optimizer_and_scheduler() self.network = DDP(self.network, device_ids=[self.local_rank], find_unused_parameters=True) if self.local_rank==0: print(self.network) else: self.print_to_log_file('self.was_initialized is True, not running self.initialize again') self.was_initialized = True def initialize_network(self): """ - momentum 0.99 - SGD instead of Adam - self.lr_scheduler = None because we do poly_lr - deep supervision = True - i am sure I forgot something here Known issue: forgot to set neg_slope=0 in InitWeights_He; should not make a difference though :return: """ if self.model.startswith("Generic"): if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU # nnunet v1, not softmax..., interesting..., but compute_loss has consider the softmax.. net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} do_ds = not self.disable_ds if not do_ds: print("disable ds") if self.model == 'Generic_TransUNet_max_ppbp':
self.network = Generic_TransUNet_max_ppbp(self.num_input_channels, self.base_num_features, self.num_classes,
5
2023-10-11 05:19:25+00:00
24k
eai-lab/On-NAS
cifar_search.py
[ { "identifier": "genotypes", "path": "utils/genotypes.py", "snippet": "PRIMITIVES = [\n \"max_pool_3x3\",\n \"avg_pool_3x3\",\n \"skip_connect\", # identity\n \"sep_conv_3x3\",\n \"sep_conv_5x5\",\n \"dil_conv_3x3\",\n \"dil_conv_5x5\",\n \"none\",\n]\nPRIMITIVES_FEWSHOT = [\n \"max_pool_3x3\",\n \"avg_pool_3x3\",\n \"skip_connect\", # identity\n \"conv_1x5_5x1\",\n \"conv_3x3\",\n \"sep_conv_3x3\",\n # \"sep_conv_5x5\",\n \"dil_conv_3x3\",\n # \"dil_conv_5x5\",\n # \"none\",\n]\ndef to_dag(C_in, gene, reduction):\ndef from_str(s):\ndef parse(alpha, k, primitives=PRIMITIVES_FEWSHOT):\ndef parse_pairwise(alpha, alpha_pairwise, primitives=PRIMITIVES_FEWSHOT): # deprecated" }, { "identifier": "SearchCNNController", "path": "models/search_cnn.py", "snippet": "class SearchCNNController(nn.Module):\n \"\"\" SearchCNN controller supporting multi-gpu \"\"\"\n def __init__(\n self,\n \n C_in,\n C,\n n_classes,\n n_layers,\n config,\n n_nodes=4,\n reduction_layers=[],\n stem_multiplier=3,\n device_ids=None,\n normalizer=dict(),\n PRIMITIVES=None,\n feature_scale_rate=2,\n use_hierarchical_alphas=False, # deprecated\n use_pairwise_input_alphas=False,\n alpha_prune_threshold=0.0,\n ):\n super().__init__()\n self.n_nodes = n_nodes\n self.criterion = nn.CrossEntropyLoss()\n self.use_pairwise_input_alphas = use_pairwise_input_alphas\n self.use_hierarchical_alphas = use_hierarchical_alphas\n self.alpha_prune_threshold = alpha_prune_threshold\n \n if \"name\" not in normalizer.keys():\n normalizer[\"func\"] = SoftMax\n normalizer[\"params\"] = dict()\n normalizer[\"params\"][\"temp_anneal_mode\"] = None\n elif normalizer[\"name\"] == \"softmax\":\n normalizer[\"func\"] = SoftMax\n elif normalizer[\"name\"] == \"relusoftmax\":\n normalizer[\"func\"] = ReLUSoftMax\n elif normalizer[\"name\"] == \"gumbel_softmax\":\n normalizer[\"func\"] = GumbelSoftMax\n else:\n raise RuntimeError(f\"Unknown normalizer {normalizer['name']}\")\n self.normalizer = normalizer\n\n if device_ids is None:\n device_ids = list(range(torch.cuda.device_count()))\n self.device_ids = device_ids\n\n \n \n # initialize architect parameters: alphas\n if PRIMITIVES is None:\n PRIMITIVES = gt.PRIMITIVES\n\n self.primitives = PRIMITIVES\n n_ops = len(PRIMITIVES)\n\n self.alpha_normal = nn.ParameterList()\n self.alpha_reduce = nn.ParameterList()\n\n \n for i in range(n_nodes):\n # create alpha parameters over parallel operations\n self.alpha_normal.append(nn.Parameter(1e-3 * torch.randn(i + 2, n_ops)))\n self.alpha_reduce.append(nn.Parameter(1e-3 * torch.randn(i + 2, n_ops)))\n \n \n\n \n assert not (\n use_hierarchical_alphas and use_pairwise_input_alphas\n ), \"Hierarchical and pairwise alphas exclude each other.\"\n\n self.alpha_pw_normal = None\n self.alpha_pw_reduce = None\n self.alpha_in_normal = None\n self.alpha_in_reduce = None\n if use_hierarchical_alphas: # deprecated\n # create alpha parameters the different input nodes for a cell, i.e. for each node in a\n # cell an additional distribution over the input nodes is introduced\n print(\"Using hierarchical alphas.\")\n\n self.alpha_in_normal = nn.ParameterList()\n self.alpha_in_reduce = nn.ParameterList()\n\n for i in range(n_nodes):\n self.alpha_in_normal.append(nn.Parameter(1e-3 * torch.randn(i + 2)))\n self.alpha_in_reduce.append(nn.Parameter(1e-3 * torch.randn(i + 2)))\n\n elif use_pairwise_input_alphas:\n print(\"Using pairwise input alphas.\")\n\n self.alpha_pw_normal = nn.ParameterList()\n self.alpha_pw_reduce = nn.ParameterList()\n\n \n for i in range(n_nodes):\n num_comb = int(scipy.special.binom(i + 2, 2))\n self.alpha_pw_normal.append(nn.Parameter(1e-3 * torch.randn(num_comb)))\n self.alpha_pw_reduce.append(nn.Parameter(1e-3 * torch.randn(num_comb)))\n \n \n\n # setup alphas list\n self._alphas = []\n \n for n, p in self.named_parameters():\n if \"alpha\" in n:\n self._alphas.append((n, p))\n\n \n \n self.net = SearchCNN(\n \n C_in,\n C,\n n_classes,\n n_layers,\n config,\n n_nodes,\n reduction_layers,\n stem_multiplier,\n PRIMITIVES=self.primitives,\n feature_scale_rate=feature_scale_rate,\n )\n\n \n\n def apply_normalizer(self, alpha):\n return self.normalizer[\"func\"](alpha, self.normalizer[\"params\"])\n\n def _get_normalized_alphas(self):\n weights_normal = [self.apply_normalizer(alpha) for alpha in self.alpha_normal]\n weights_reduce = [self.apply_normalizer(alpha) for alpha in self.alpha_reduce]\n\n weights_pw_normal = None\n weights_pw_reduce = None\n weights_in_normal = None\n weights_in_reduce = None\n if self.alpha_in_normal is not None:\n weights_in_normal = [\n self.apply_normalizer(alpha) for alpha in self.alpha_in_normal\n ]\n weights_in_reduce = [\n self.apply_normalizer(alpha) for alpha in self.alpha_in_reduce\n ]\n elif self.alpha_pw_normal is not None:\n weights_pw_normal = [\n self.apply_normalizer(alpha) for alpha in self.alpha_pw_normal\n ]\n weights_pw_reduce = [\n self.apply_normalizer(alpha) for alpha in self.alpha_pw_reduce\n ]\n\n return (\n weights_normal,\n weights_reduce,\n weights_in_normal,\n weights_in_reduce,\n weights_pw_normal,\n weights_pw_reduce,\n )\n\n def prune_alphas(self, prune_threshold=0.0, val=-10e8):\n \"\"\"Set the alphas with probability below prune_threshold to a large negative value\n\n Note:\n The prune_threshold applies to the alpha probabilities (after the softmax is\n applied) while `val` corresponds to the logit values (thus a large negative value\n corresponds to a low probability).\n \"\"\"\n\n # reset temperature for prunning\n model_has_normalizer = hasattr(self, \"normalizer\")\n if model_has_normalizer:\n curr_step_backup = self.normalizer[\"params\"][\"curr_step\"]\n self.normalizer[\"params\"][\"curr_step\"] = (\n self.normalizer[\"params\"][\"max_steps\"] - 1\n )\n\n weights_normal = [self.apply_normalizer(alpha) for alpha in self.alpha_normal]\n weights_reduce = [self.apply_normalizer(alpha) for alpha in self.alpha_reduce]\n for idx in range(len(weights_normal)):\n # need to modify data because alphas are leaf variables\n self.alpha_normal[idx].data[weights_normal[idx] < prune_threshold] = val\n self.alpha_reduce[idx].data[weights_reduce[idx] < prune_threshold] = val\n\n # set curr_step back to original value\n self.normalizer[\"params\"][\"curr_step\"] = curr_step_backup\n\n def get_sparse_alphas_pw(self, alpha_prune_threshold=0.0):\n\n \"\"\"\n Convert alphas to zero-one-vectors under consideration of pairwise alphas\n\n\n :param alpha_prune_threshold: threshold for pruning\n\n :return: binary tensors with shape like alpha_normal and alpha_reduce, indicating whether an op is included in the\n sparsified one shot model\n \"\"\"\n\n assert (\n self.alpha_pw_normal is not None\n ), \"Error: function only availaible for pw models\"\n\n weights_normal = [\n self.apply_normalizer(alpha) for alpha in self.alpha_normal\n ] # get normalized weights\n weights_reduce = [self.apply_normalizer(alpha) for alpha in self.alpha_reduce]\n\n weights_pw_normal = [\n self.apply_normalizer(alpha) for alpha in self.alpha_pw_normal\n ]\n\n weights_pw_reduce = [\n self.apply_normalizer(alpha) for alpha in self.alpha_pw_reduce\n ]\n\n weights_normal_sparse = list()\n\n # get all the pairs of inputs\n for node_idx, node_weights in enumerate(weights_normal):\n input_pairs = list()\n\n # get pairs of inputs correspeonding to indices in alpha_pw\n for input_1 in range(len(node_weights)):\n for input_2 in range(input_1 + 1, len(node_weights)):\n input_pairs.append([input_1, input_2])\n\n assert len(input_pairs) == len(\n weights_pw_normal[node_idx]\n ), \"error: pairwise alpha length does not match pairwise terms length\"\n\n keep_inputs = list() # list of input nodes that are kept\n\n for input_pair_idx in range(len(input_pairs)):\n if (\n weights_pw_normal[node_idx][input_pair_idx] >= alpha_prune_threshold\n ): # if pw weight larger than threshold keep input\n keep_inputs.extend(input_pairs[input_pair_idx])\n\n weights_normal_sparse.append(\n torch.stack(\n [\n (weight >= alpha_prune_threshold).type(torch.float)\n if weight_idx in keep_inputs\n else torch.zeros_like(weight)\n for weight_idx, weight in enumerate(node_weights)\n ]\n )\n )\n\n ### same for reduction\n\n weights_reduce_sparse = list()\n\n for node_idx, node_weights in enumerate(weights_reduce):\n input_pairs = list()\n\n # get pairs of inputs correspeonding to indices in alpha_pw\n for input_1 in range(len(node_weights)):\n for input_2 in range(input_1 + 1, len(node_weights)):\n input_pairs.append([input_1, input_2])\n\n assert len(input_pairs) == len(\n weights_pw_reduce[node_idx]\n ), \"error: pairwise alpha length does not match pairwise terms length\"\n\n keep_inputs = list() # list of input nodes that are kept\n\n for input_pair_idx in range(len(input_pairs)):\n if (\n weights_pw_reduce[node_idx][input_pair_idx] >= alpha_prune_threshold\n ): # if pw weight larger than threshold keep input\n keep_inputs.extend(input_pairs[input_pair_idx])\n\n weights_reduce_sparse.append(\n torch.stack(\n [\n (weight >= alpha_prune_threshold).type(torch.float)\n if weight_idx in keep_inputs\n else torch.zeros_like(weight)\n for weight_idx, weight in enumerate(node_weights)\n ]\n )\n )\n\n return weights_normal_sparse, weights_reduce_sparse\n\n def get_sparse_num_params(self, alpha_prune_threshold=0.0):\n \"\"\"Get number of parameters for sparse one-shot-model\n\n Returns:\n A torch tensor\n \"\"\"\n\n weights_normal, weights_reduce = self.get_sparse_alphas_pw(\n alpha_prune_threshold\n )\n # this returns tensors with only 0's and 1's depending on whether an op is used in the sparsified model\n\n # get none active ops/layer names\n\n # for normal cell\n none_active_ops_normal = list()\n for node_idx, node in enumerate(weights_normal):\n for mixed_op_idx, mixed_op in enumerate(node):\n none_active_ops_idx = (mixed_op == 0.0).nonzero()\n for op in none_active_ops_idx:\n none_active_ops_normal.append(\n str(node_idx)\n + \".\"\n + str(mixed_op_idx)\n + \"._ops.\"\n + str(int(op))\n )\n\n # and for reduction cell\n none_active_ops_reduce = list()\n for node_idx, node in enumerate(weights_reduce):\n for mixed_op_idx, mixed_op in enumerate(node):\n none_active_ops_idx = (mixed_op == 0.0).nonzero()\n for op in none_active_ops_idx:\n none_active_ops_reduce.append(\n str(node_idx)\n + \".\"\n + str(mixed_op_idx)\n + \"._ops.\"\n + str(int(op))\n )\n\n all_params = sum(\n p.numel() for p in self.net.parameters()\n ) # params of one-shot model\n\n # get normal and reduction layers\n normal_cells = list()\n red_cells = list()\n for lyr, cell in enumerate(self.net.cells):\n if cell.reduction:\n red_cells.append(lyr)\n else:\n normal_cells.append(lyr)\n\n # count params of non-active ops\n\n none_active_params = 0\n for layer_name, layer_weights in self.named_parameters():\n # check if layer is part of normal or reduction cell\n if \"net.cells.\" in layer_name: # layer part of cells at all?\n for cell in normal_cells: # normal cell?\n if \"net.cells.\" + str(cell) in layer_name: # normal cell\n none_active_ops = none_active_ops_normal\n\n # else reduction cell\n for cell in red_cells:\n if \"net.cells.\" + str(cell) in layer_name: # normal cell\n none_active_ops = none_active_ops_reduce\n\n if any(\n [none_active_op in layer_name for none_active_op in none_active_ops]\n ): # check if layer is part of none-active ops\n none_active_params += layer_weights.numel()\n\n active_params = all_params - none_active_params\n\n return active_params\n\n def drop_path_prob(self, p):\n \"\"\" Set drop path probability \"\"\"\n for module in self.net.modules():\n if isinstance(module, ops.DropPath_):\n module.p = p\n def forward(self, x, sparsify_input_alphas=None):\n \"\"\"Forward pass through the network\n\n Args:\n x: The input tensor\n sparsify_input_alphas: Whether to sparsify the alphas over the input nodes. Use `None`\n to not sparsify input alphas.\n For hierarchical alphas, `sparsify_input_alphas` should be a (float) threshold on\n the probability (i.e. between 0 and 1). Alphas above the threshold (and thus the\n corresponding input nodes) are kept.\n For pairwise alphas, if `sparsify_input_alphas` is larger than 0, then only the\n largest alpha is kept.\n Note that the sparsification is not be differentiable and thus cannot be used during\n training.\n\n Returns:\n The network output\n \"\"\"\n (\n weights_normal,\n weights_reduce,\n weights_in_normal,\n weights_in_reduce,\n weights_pw_normal,\n weights_pw_reduce,\n ) = self._get_normalized_alphas()\n\n \n if len(self.device_ids) == 1 :\n output= self.net(\n x,\n weights_normal,\n weights_reduce,\n weights_in_normal,\n weights_in_reduce,\n weights_pw_normal,\n weights_pw_reduce,\n sparsify_input_alphas=sparsify_input_alphas,\n alpha_prune_threshold=self.alpha_prune_threshold,\n )\n return output\n\n \n # scatter x\n xs = nn.parallel.scatter(x, self.device_ids)\n # broadcast weights\n wnormal_copies = broadcast_list(weights_normal, self.device_ids)\n wreduce_copies = broadcast_list(weights_reduce, self.device_ids)\n if weights_in_normal is not None:\n wnormal_in_copies = broadcast_list(weights_in_normal, self.device_ids)\n wreduce_in_copies = broadcast_list(weights_in_reduce, self.device_ids)\n else:\n \n wnormal_in_copies = None\n wreduce_in_copies = None\n\n if weights_pw_normal is not None:\n wnormal_pw_copies = broadcast_list(weights_pw_normal, self.device_ids)\n wreduce_pw_copies = broadcast_list(weights_pw_reduce, self.device_ids)\n else:\n wnormal_pw_copies = None\n wreduce_pw_copies = None\n\n # replicate modules\n replicas = nn.parallel.replicate(self.net, self.device_ids)\n outputs = nn.parallel.parallel_apply(\n replicas,\n list(\n zip(\n xs,\n wnormal_copies,\n wreduce_copies,\n # wnormal_in_copies,\n # wreduce_in_copies,\n # wnormal_pw_copies,\n # wreduce_pw_copies,\n )\n ),\n devices=self.device_ids,\n )\n return nn.parallel.gather(outputs, self.device_ids[0])\n\n def loss(self, X, y):\n logits = self.forward(X)\n return self.criterion(logits, y)\n\n def print_alphas(self, logger):\n # remove formats\n org_formatters = []\n for handler in logger.handlers:\n org_formatters.append(handler.formatter)\n handler.setFormatter(logging.Formatter(\"%(message)s\"))\n\n normalizer = self.get_normalizer(deterministic=True)\n logger.info(\"####### ALPHA #######\")\n logger.info(\"# Alpha - normal\")\n for alpha in self.alpha_normal:\n logger.info(normalizer(alpha))\n\n logger.info(\"\\n# Alpha - reduce\")\n for alpha in self.alpha_reduce:\n logger.info(normalizer(alpha))\n logger.info(\"#####################\")\n\n # restore formats\n for handler, formatter in zip(logger.handlers, org_formatters):\n handler.setFormatter(formatter)\n\n def genotype(self):\n if self.use_pairwise_input_alphas:\n\n weights_pw_normal = [\n F.softmax(alpha, dim=-1) for alpha in self.alpha_pw_normal\n ]\n weights_pw_reduce = [\n F.softmax(alpha, dim=-1) for alpha in self.alpha_pw_reduce\n ]\n\n gene_normal = gt.parse_pairwise(\n self.alpha_normal, weights_pw_normal, primitives=self.primitives\n )\n gene_reduce = gt.parse_pairwise(\n self.alpha_reduce, weights_pw_reduce, primitives=self.primitives\n )\n\n elif self.use_hierarchical_alphas:\n raise NotImplementedError\n else:\n\n gene_normal = gt.parse(self.alpha_normal, k=2, primitives=self.primitives)\n gene_reduce = gt.parse(self.alpha_reduce, k=2, primitives=self.primitives)\n\n concat = range(2, 2 + self.n_nodes) # concat all intermediate nodes\n\n return gt.Genotype(\n normal=gene_normal,\n normal_concat=concat,\n reduce=gene_reduce,\n reduce_concat=concat,\n )\n\n def weights(self):\n return self.net.parameters()\n\n def named_weights(self):\n return self.net.named_parameters()\n\n def named_weights_with_net(self):\n return self.named_parameters()\n\n def alphas(self):\n for n, p in self._alphas:\n yield p\n\n def named_alphas(self):\n for n, p in self._alphas:\n yield n, p" }, { "identifier": "SearchCNNControllerPC", "path": "models/search_cnn_PC.py", "snippet": "class SearchCNNControllerPC(nn.Module):\n \"\"\" SearchCNN controller supporting multi-gpu \"\"\"\n\n def __init__(\n self,\n C_in,\n C,\n n_classes,\n n_layers,\n n_nodes=4,\n reduction_layers=[],\n stem_multiplier=3,\n device_ids=None,\n normalizer=dict(),\n PRIMITIVES=None,\n feature_scale_rate=2,\n use_hierarchical_alphas=False, # deprecated\n use_pairwise_input_alphas=False,\n use_pc_adaptation=False,\n alpha_prune_threshold=0.0,\n ):\n super().__init__()\n self.n_nodes = n_nodes\n self.criterion = nn.CrossEntropyLoss()\n self.use_pairwise_input_alphas = use_pairwise_input_alphas\n self.use_hierarchical_alphas = use_hierarchical_alphas\n self.alpha_prune_threshold = alpha_prune_threshold\n self.use_pc_adaptation = use_pc_adaptation\n if \"name\" not in normalizer.keys():\n normalizer[\"func\"] = SoftMax\n normalizer[\"params\"] = dict()\n normalizer[\"params\"][\"temp_anneal_mode\"] = None\n elif normalizer[\"name\"] == \"softmax\":\n normalizer[\"func\"] = SoftMax\n elif normalizer[\"name\"] == \"relusoftmax\":\n normalizer[\"func\"] = ReLUSoftMax\n elif normalizer[\"name\"] == \"gumbel_softmax\":\n normalizer[\"func\"] = GumbelSoftMax\n else:\n raise RuntimeError(f\"Unknown normalizer {normalizer['name']}\")\n self.normalizer = normalizer\n\n if device_ids is None:\n device_ids = list(range(torch.cuda.device_count()))\n self.device_ids = device_ids\n\n # initialize architect parameters: alphas\n if PRIMITIVES is None:\n PRIMITIVES = gt.PRIMITIVES\n\n self.primitives = PRIMITIVES\n n_ops = len(PRIMITIVES)\n\n self.alpha_normal = nn.ParameterList()\n self.alpha_reduce = nn.ParameterList()\n\n\n self.pc_beta_normal = nn.ParameterList()\n self.pc_beta_reduce = nn.ParameterList()\n\n for i in range(n_nodes):\n # create alpha parameters over parallel operations\n self.alpha_normal.append(nn.Parameter(1e-3 * torch.randn(i + 2, n_ops)))\n self.alpha_reduce.append(nn.Parameter(1e-3 * torch.randn(i + 2, n_ops)))\n\n assert not (\n use_hierarchical_alphas and use_pairwise_input_alphas\n ), \"Hierarchical and pairwise alphas exclude each other.\"\n\n self.alpha_pw_normal = None\n self.alpha_pw_reduce = None\n self.alpha_in_normal = None\n self.alpha_in_reduce = None\n self.pc_alpha_normal = None\n self.pc_alpha_reduce = None \n\n if use_hierarchical_alphas: # deprecated\n # create alpha parameters the different input nodes for a cell, i.e. for each node in a\n # cell an additional distribution over the input nodes is introduced\n print(\"Using hierarchical alphas.\")\n\n self.alpha_in_normal = nn.ParameterList()\n self.alpha_in_reduce = nn.ParameterList()\n\n for i in range(n_nodes):\n self.alpha_in_normal.append(nn.Parameter(1e-3 * torch.randn(i + 2)))\n self.alpha_in_reduce.append(nn.Parameter(1e-3 * torch.randn(i + 2)))\n\n elif use_pairwise_input_alphas:\n print(\"Using pairwise input alphas.\")\n\n self.alpha_pw_normal = nn.ParameterList()\n self.alpha_pw_reduce = nn.ParameterList()\n\n for i in range(n_nodes):\n num_comb = int(scipy.special.binom(i + 2, 2))\n self.alpha_pw_normal.append(nn.Parameter(1e-3 * torch.randn(num_comb)))\n self.alpha_pw_reduce.append(nn.Parameter(1e-3 * torch.randn(num_comb)))\n \n if use_pc_adaptation:\n # initialize pc_beta here\n # beta have to be [[2],[3],[4]]\n self.pc_alpha_normal = nn.ParameterList()\n self.pc_alpha_reduce = nn.ParameterList()\n for i in range(n_nodes):\n num_edges = i + 2\n self.pc_alpha_normal.append(nn.Parameter(1e-3 * torch.randn(num_edges)))\n self.pc_alpha_reduce.append(nn.Parameter(1e-3 * torch.randn(num_edges)))\n\n\n # setup alphas list\n self._alphas = []\n for n, p in self.named_parameters():\n if \"alpha\" in n:\n self._alphas.append((n, p))\n\n self.net = SearchCNNPC(\n C_in,\n C,\n n_classes,\n n_layers,\n n_nodes,\n reduction_layers,\n stem_multiplier,\n PRIMITIVES=self.primitives,\n feature_scale_rate=feature_scale_rate,\n )\n\n def apply_normalizer(self, alpha):\n return self.normalizer[\"func\"](alpha, self.normalizer[\"params\"])\n\n def _get_normalized_alphas(self):\n weights_normal = [self.apply_normalizer(alpha) for alpha in self.alpha_normal]\n weights_reduce = [self.apply_normalizer(alpha) for alpha in self.alpha_reduce]\n\n weights_pw_normal = None\n weights_pw_reduce = None\n weights_in_normal = None\n weights_in_reduce = None\n weights_pc_normal = None\n weights_pc_reduce = None\n\n if self.alpha_in_normal is not None:\n weights_in_normal = [\n self.apply_normalizer(alpha) for alpha in self.alpha_in_normal\n ]\n weights_in_reduce = [\n self.apply_normalizer(alpha) for alpha in self.alpha_in_reduce\n ]\n elif self.alpha_pw_normal is not None:\n weights_pw_normal = [\n self.apply_normalizer(alpha) for alpha in self.alpha_pw_normal\n ]\n weights_pw_reduce = [\n self.apply_normalizer(alpha) for alpha in self.alpha_pw_reduce\n ]\n if self.pc_alpha_normal is not None:\n weights_pc_normal = [\n self.apply_normalizer(alpha) for alpha in self.pc_alpha_normal\n ]\n weights_pc_reduce = [\n self.apply_normalizer(alpha) for alpha in self.pc_alpha_reduce\n ]\n return (\n weights_normal,\n weights_reduce,\n weights_in_normal,\n weights_in_reduce,\n weights_pw_normal,\n weights_pw_reduce,\n weights_pc_normal,\n weights_pc_reduce,\n )\n\n def prune_alphas(self, prune_threshold=0.0, val=-10e8):\n \"\"\"Set the alphas with probability below prune_threshold to a large negative value\n\n Note:\n The prune_threshold applies to the alpha probabilities (after the softmax is\n applied) while `val` corresponds to the logit values (thus a large negative value\n corresponds to a low probability).\n \"\"\"\n\n # reset temperature for prunning\n model_has_normalizer = hasattr(self, \"normalizer\")\n if model_has_normalizer:\n curr_step_backup = self.normalizer[\"params\"][\"curr_step\"]\n self.normalizer[\"params\"][\"curr_step\"] = (\n self.normalizer[\"params\"][\"max_steps\"] - 1\n )\n\n weights_normal = [self.apply_normalizer(alpha) for alpha in self.alpha_normal]\n weights_reduce = [self.apply_normalizer(alpha) for alpha in self.alpha_reduce]\n for idx in range(len(weights_normal)):\n # need to modify data because alphas are leaf variables\n self.alpha_normal[idx].data[weights_normal[idx] < prune_threshold] = val\n self.alpha_reduce[idx].data[weights_reduce[idx] < prune_threshold] = val\n\n # set curr_step back to original value\n self.normalizer[\"params\"][\"curr_step\"] = curr_step_backup\n\n def get_sparse_alphas_pw(self, alpha_prune_threshold=0.0):\n\n \"\"\"\n Convert alphas to zero-one-vectors under consideration of pairwise alphas\n\n\n :param alpha_prune_threshold: threshold for pruning\n\n :return: binary tensors with shape like alpha_normal and alpha_reduce, indicating whether an op is included in the\n sparsified one shot model\n \"\"\"\n\n assert (\n self.alpha_pw_normal is not None\n ), \"Error: function only availaible for pw models\"\n\n weights_normal = [\n self.apply_normalizer(alpha) for alpha in self.alpha_normal\n ] # get normalized weights\n weights_reduce = [self.apply_normalizer(alpha) for alpha in self.alpha_reduce]\n\n weights_pw_normal = [\n self.apply_normalizer(alpha) for alpha in self.alpha_pw_normal\n ]\n\n weights_pw_reduce = [\n self.apply_normalizer(alpha) for alpha in self.alpha_pw_reduce\n ]\n\n weights_normal_sparse = list()\n\n # get all the pairs of inputs\n for node_idx, node_weights in enumerate(weights_normal):\n input_pairs = list()\n\n # get pairs of inputs correspeonding to indices in alpha_pw\n for input_1 in range(len(node_weights)):\n for input_2 in range(input_1 + 1, len(node_weights)):\n input_pairs.append([input_1, input_2])\n\n assert len(input_pairs) == len(\n weights_pw_normal[node_idx]\n ), \"error: pairwise alpha length does not match pairwise terms length\"\n\n keep_inputs = list() # list of input nodes that are kept\n\n for input_pair_idx in range(len(input_pairs)):\n if (\n weights_pw_normal[node_idx][input_pair_idx] >= alpha_prune_threshold\n ): # if pw weight larger than threshold keep input\n keep_inputs.extend(input_pairs[input_pair_idx])\n\n weights_normal_sparse.append(\n torch.stack(\n [\n (weight >= alpha_prune_threshold).type(torch.float)\n if weight_idx in keep_inputs\n else torch.zeros_like(weight)\n for weight_idx, weight in enumerate(node_weights)\n ]\n )\n )\n\n ### same for reduction\n\n weights_reduce_sparse = list()\n\n for node_idx, node_weights in enumerate(weights_reduce):\n input_pairs = list()\n\n # get pairs of inputs correspeonding to indices in alpha_pw\n for input_1 in range(len(node_weights)):\n for input_2 in range(input_1 + 1, len(node_weights)):\n input_pairs.append([input_1, input_2])\n\n assert len(input_pairs) == len(\n weights_pw_reduce[node_idx]\n ), \"error: pairwise alpha length does not match pairwise terms length\"\n\n keep_inputs = list() # list of input nodes that are kept\n\n for input_pair_idx in range(len(input_pairs)):\n if (\n weights_pw_reduce[node_idx][input_pair_idx] >= alpha_prune_threshold\n ): # if pw weight larger than threshold keep input\n keep_inputs.extend(input_pairs[input_pair_idx])\n\n weights_reduce_sparse.append(\n torch.stack(\n [\n (weight >= alpha_prune_threshold).type(torch.float)\n if weight_idx in keep_inputs\n else torch.zeros_like(weight)\n for weight_idx, weight in enumerate(node_weights)\n ]\n )\n )\n\n return weights_normal_sparse, weights_reduce_sparse\n\n def get_sparse_num_params(self, alpha_prune_threshold=0.0):\n \"\"\"Get number of parameters for sparse one-shot-model\n\n Returns:\n A torch tensor\n \"\"\"\n\n weights_normal, weights_reduce = self.get_sparse_alphas_pw(\n alpha_prune_threshold\n )\n # this returns tensors with only 0's and 1's depending on whether an op is used in the sparsified model\n\n # get none active ops/layer names\n\n # for normal cell\n none_active_ops_normal = list()\n for node_idx, node in enumerate(weights_normal):\n for mixed_op_idx, mixed_op in enumerate(node):\n none_active_ops_idx = (mixed_op == 0.0).nonzero()\n for op in none_active_ops_idx:\n none_active_ops_normal.append(\n str(node_idx)\n + \".\"\n + str(mixed_op_idx)\n + \"._ops.\"\n + str(int(op))\n )\n\n # and for reduction cell\n none_active_ops_reduce = list()\n for node_idx, node in enumerate(weights_reduce):\n for mixed_op_idx, mixed_op in enumerate(node):\n none_active_ops_idx = (mixed_op == 0.0).nonzero()\n for op in none_active_ops_idx:\n none_active_ops_reduce.append(\n str(node_idx)\n + \".\"\n + str(mixed_op_idx)\n + \"._ops.\"\n + str(int(op))\n )\n\n all_params = sum(\n p.numel() for p in self.net.parameters()\n ) # params of one-shot model\n\n # get normal and reduction layers\n normal_cells = list()\n red_cells = list()\n for lyr, cell in enumerate(self.net.cells):\n if cell.reduction:\n red_cells.append(lyr)\n else:\n normal_cells.append(lyr)\n\n # count params of non-active ops\n\n none_active_params = 0\n for layer_name, layer_weights in self.named_parameters():\n # check if layer is part of normal or reduction cell\n if \"net.cells.\" in layer_name: # layer part of cells at all?\n for cell in normal_cells: # normal cell?\n if \"net.cells.\" + str(cell) in layer_name: # normal cell\n none_active_ops = none_active_ops_normal\n\n # else reduction cell\n for cell in red_cells:\n if \"net.cells.\" + str(cell) in layer_name: # normal cell\n none_active_ops = none_active_ops_reduce\n\n if any(\n [none_active_op in layer_name for none_active_op in none_active_ops]\n ): # check if layer is part of none-active ops\n none_active_params += layer_weights.numel()\n\n active_params = all_params - none_active_params\n\n return active_params\n\n def drop_path_prob(self, p):\n \"\"\" Set drop path probability \"\"\"\n for module in self.net.modules():\n if isinstance(module, ops_7c.DropPath_):\n module.p = p\n\n def forward(self, x, sparsify_input_alphas=None):\n \"\"\"Forward pass through the network\n\n Args:\n x: The input tensor\n sparsify_input_alphas: Whether to sparsify the alphas over the input nodes. Use `None`\n to not sparsify input alphas.\n For hierarchical alphas, `sparsify_input_alphas` should be a (float) threshold on\n the probability (i.e. between 0 and 1). Alphas above the threshold (and thus the\n corresponding input nodes) are kept.\n For pairwise alphas, if `sparsify_input_alphas` is larger than 0, then only the\n largest alpha is kept.\n Note that the sparsification is not be differentiable and thus cannot be used during\n training.\n\n Returns:\n The network output\n \"\"\"\n\n (\n weights_normal,\n weights_reduce,\n weights_in_normal,\n weights_in_reduce,\n weights_pw_normal,\n weights_pw_reduce,\n weights_pc_normal,\n weights_pc_reduce,\n ) = self._get_normalized_alphas()\n\n if len(self.device_ids) == 1:\n return self.net(\n x,\n weights_normal,\n weights_reduce,\n weights_in_normal,\n weights_in_reduce,\n weights_pw_normal,\n weights_pw_reduce,\n weights_pc_normal,\n weights_pc_reduce,\n sparsify_input_alphas=sparsify_input_alphas,\n alpha_prune_threshold=self.alpha_prune_threshold,\n )\n\n # scatter x\n xs = nn.parallel.scatter(x, self.device_ids)\n # broadcast weights\n wnormal_copies = broadcast_list(weights_normal, self.device_ids)\n wreduce_copies = broadcast_list(weights_reduce, self.device_ids)\n\n if weights_in_normal is not None:\n wnormal_in_copies = broadcast_list(weights_in_normal, self.device_ids)\n wreduce_in_copies = broadcast_list(weights_in_reduce, self.device_ids)\n else:\n wnormal_in_copies = None\n wreduce_in_copies = None\n\n if weights_pw_normal is not None:\n wnormal_pw_copies = broadcast_list(weights_pw_normal, self.device_ids)\n wreduce_pw_copies = broadcast_list(weights_pw_reduce, self.device_ids)\n else:\n wnormal_pw_copies = None\n wreduce_pw_copies = None\n\n # replicate modules\n replicas = nn.parallel.replicate(self.net, self.device_ids)\n outputs = nn.parallel.parallel_apply(\n replicas,\n list(\n zip(\n xs,\n wnormal_copies,\n wreduce_copies,\n wnormal_in_copies,\n wreduce_in_copies,\n wnormal_pw_copies,\n wreduce_pw_copies,\n )\n ),\n devices=self.device_ids,\n )\n return nn.parallel.gather(outputs, self.device_ids[0])\n\n def loss(self, X, y):\n logits = self.forward(X)\n return self.criterion(logits, y)\n\n def print_alphas(self, logger):\n # remove formats\n org_formatters = []\n for handler in logger.handlers:\n org_formatters.append(handler.formatter)\n handler.setFormatter(logging.Formatter(\"%(message)s\"))\n\n normalizer = self.get_normalizer(deterministic=True)\n logger.info(\"####### ALPHA #######\")\n logger.info(\"# Alpha - normal\")\n for alpha in self.alpha_normal:\n logger.info(normalizer(alpha))\n\n logger.info(\"\\n# Alpha - reduce\")\n for alpha in self.alpha_reduce:\n logger.info(normalizer(alpha))\n logger.info(\"#####################\")\n\n # restore formats\n for handler, formatter in zip(logger.handlers, org_formatters):\n handler.setFormatter(formatter)\n\n def genotype(self):\n if self.use_pairwise_input_alphas:\n\n weights_pw_normal = [\n F.softmax(alpha, dim=-1) for alpha in self.alpha_pw_normal\n ]\n weights_pw_reduce = [\n F.softmax(alpha, dim=-1) for alpha in self.alpha_pw_reduce\n ]\n\n gene_normal = gt.parse_pairwise(\n self.alpha_normal, weights_pw_normal, primitives=self.primitives\n )\n gene_reduce = gt.parse_pairwise(\n self.alpha_reduce, weights_pw_reduce, primitives=self.primitives\n )\n\n elif self.use_hierarchical_alphas:\n raise NotImplementedError\n else:\n\n gene_normal = gt.parse(self.alpha_normal, k=2, primitives=self.primitives)\n gene_reduce = gt.parse(self.alpha_reduce, k=2, primitives=self.primitives)\n\n concat = range(2, 2 + self.n_nodes) # concat all intermediate nodes\n\n return gt.Genotype(\n normal=gene_normal,\n normal_concat=concat,\n reduce=gene_reduce,\n reduce_concat=concat,\n )\n\n def weights(self):\n return self.net.parameters()\n\n def named_weights(self):\n return self.net.named_parameters()\n\n def named_weights_with_net(self):\n return self.named_parameters()\n\n def alphas(self):\n for n, p in self._alphas:\n yield p\n\n def named_alphas(self):\n for n, p in self._alphas:\n yield n, p" }, { "identifier": "Darts", "path": "task_optimizer/darts.py", "snippet": "class Darts:\n def __init__(self, model, config, do_schedule_lr=False):\n\n self.config = config\n self.config.logger = None\n self.model = model\n self.do_schedule_lr = do_schedule_lr\n self.task_train_steps = config.task_train_steps\n self.test_task_train_steps = config.test_task_train_steps\n self.warm_up_epochs = config.warm_up_epochs\n self.eval_switch = 0\n self.pprevious_grads = 0\n # weights optimizer\n\n self.w_optim = torch.optim.Adam(\n self.model.weights(),\n lr=self.config.w_lr,\n betas=(0.0, 0.999), # config.w_momentum,\n weight_decay=self.config.w_weight_decay,\n ) #\n\n # architecture optimizer\n self.a_optim = torch.optim.Adam(\n model.alphas(),\n self.config.alpha_lr,\n betas=(0.0, 0.999),\n weight_decay=self.config.alpha_weight_decay,\n )\n self.architect = Architect(\n self.model,\n self.config.w_momentum,\n self.config.w_weight_decay,\n self.config.use_first_order_darts,\n )\n def step(\n self,\n task,\n epoch,\n global_progress=\"\",\n test_phase=False,\n alpha_logger=None,\n sparsify_input_alphas=None,\n ):\n \n\n\n log_alphas = False\n\n if test_phase:\n top1_logger = self.config.top1_logger_test\n losses_logger = self.config.losses_logger_test\n train_steps = self.config.test_task_train_steps\n arch_adap_steps = int(train_steps * self.config.test_adapt_steps)\n \n if alpha_logger is not None:\n log_alphas = True\n\n else:\n top1_logger = self.config.top1_logger\n losses_logger = self.config.losses_logger\n train_steps = self.config.task_train_steps\n arch_adap_steps = train_steps\n \n\n \n\n lr = self.config.w_lr\n\n if self.config.w_task_anneal:\n for group in self.w_optim.param_groups:\n group[\"lr\"] = self.config.w_lr\n\n w_task_lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(\n self.w_optim, train_steps, eta_min=0.0\n )\n else:\n w_task_lr_scheduler = None\n\n if self.config.a_task_anneal:\n for group in self.a_optim.param_groups:\n group[\"lr\"] = self.config.alpha_lr\n\n a_task_lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(\n self.a_optim, arch_adap_steps, eta_min=0.0\n )\n\n else:\n a_task_lr_scheduler = None\n\n model_has_normalizer = hasattr(self.model, \"normalizer\")\n if model_has_normalizer:\n self.model.normalizer[\"params\"][\"curr_step\"] = 0.0\n self.architect.v_net.normalizer[\"params\"][\"curr_step\"] = 0.0\n self.model.normalizer[\"params\"][\"max_steps\"] = float(arch_adap_steps)\n self.architect.v_net.normalizer[\"params\"][\"max_steps\"] = float(\n arch_adap_steps\n )\n from tqdm import tqdm\n if self.config.drop_path_prob > 0.0:\n if not test_phase or self.config.use_drop_path_in_meta_testing:\n self.model.drop_path_prob(self.config.drop_path_prob)\n\n p_bar = tqdm(range(train_steps))\n self.config.total_steps = train_steps * len(task.train_loader)\n \n\n\n for train_step in p_bar: # task train_steps = epochs per task\n warm_up = (\n epoch < self.warm_up_epochs\n ) # if epoch < warm_up_epochs, do warm up\n if (\n train_step >= arch_adap_steps\n ): # no architecture adap after arch_adap_steps steps\n warm_up = 1\n\n if w_task_lr_scheduler is not None:\n w_task_lr_scheduler.step()\n\n if a_task_lr_scheduler is not None:\n a_task_lr_scheduler.step()\n torch.cuda.reset_peak_memory_stats(device=0)\n \n task_specific_model = train( \n task,\n self.model,\n self.architect,\n self.w_optim,\n self.a_optim,\n lr,\n global_progress,\n self.config,\n warm_up,\n test_phase\n )\n mem = torch.cuda.memory_stats(0)['allocated_bytes.all.peak']/(1024**2)\n p_bar.set_postfix({\"Memory\" : f\"{mem : .2f}\",\"Task average\":f\"{self.config.top1_logger_test.avg:.1%}\"})\n if train_step == 9:\n self.config.memory_snap = mem\n if (\n model_has_normalizer\n and train_step < (arch_adap_steps - 1)\n and not warm_up\n ): \n self.model.normalizer[\"params\"][\"curr_step\"] += 1\n self.architect.v_net.normalizer[\"params\"][\"curr_step\"] += 1\n\n w_task = OrderedDict(\n {\n layer_name: copy.deepcopy(layer_weight)\n for layer_name, layer_weight in self.model.named_weights()\n # if layer_weight.grad is not None\n }\n )\n a_task = OrderedDict(\n {\n layer_name: copy.deepcopy(layer_alpha)\n for layer_name, layer_alpha in self.model.named_alphas()\n # if layer_alpha.grad is not None\n }\n )\n\n \n w_task_bot = OrderedDict(\n {\n layer_name: copy.deepcopy(layer_weight)\n for layer_name, layer_weight in task_specific_model.named_weights()\n \n }\n )\n a_task_bot = OrderedDict(\n {\n layer_name: copy.deepcopy(layer_alpha)\n for layer_name, layer_alpha in task_specific_model.named_alphas()\n \n }\n )\n # Log genotype\n genotype = self.model.genotype()\n\n if log_alphas:\n alpha_logger[\"normal_relaxed\"].append(\n copy.deepcopy(self.model.alpha_normal)\n )\n alpha_logger[\"reduced_relaxed\"].append(\n copy.deepcopy(self.model.alpha_reduce)\n )\n alpha_logger[\"all_alphas\"].append(a_task)\n alpha_logger[\"normal_hierarchical\"].append(\n copy.deepcopy(self.model.alpha_in_normal)\n )\n alpha_logger[\"reduced_hierarchical\"].append(\n copy.deepcopy(self.model.alpha_in_reduce)\n )\n alpha_logger[\"normal_pairwise\"].append(\n copy.deepcopy(self.model.alpha_pw_normal)\n )\n alpha_logger[\"reduced_pairwise\"].append(\n copy.deepcopy(self.model.alpha_pw_reduce)\n )\n\n # for test data evaluation, turn off drop path\n if self.config.drop_path_prob > 0.0:\n self.model.drop_path_prob(0.0)\n little_switch = 0\n\n if self.config.naivenaive:\n little_switch = 1\n with torch.no_grad():\n self.config.naivenaive = 1\n self.config.eval_switch = 1\n self.config.cell_phase = 3\n\n for batch_idx, batch in enumerate(task.test_loader):\n \n x_test, y_test = batch\n x_test = x_test.to(self.config.device, non_blocking=True)\n y_test = y_test.to(self.config.device, non_blocking=True)\n if isinstance(self.model, SearchCNNController):\n logits = self.model(\n x_test, sparsify_input_alphas=sparsify_input_alphas\n )\n else:\n logits = self.model(x_test)\n loss = self.model.criterion(logits, y_test)\n\n y_test_pred = logits.softmax(dim=1)\n now = time.strftime('%c', time.localtime(time.time()))\n prec1, prec5 = utils.accuracy(logits, y_test, self.config, topk=(1, 5))\n losses_logger.update(loss.item(), 1)\n top1_logger.update(prec1.item(), 1)\n \n self.config.naivenaive = 0 \n self.config.eval_switch = 0\n self.config.cell_phase = 3 \n\n if little_switch == 1:\n self.config.naivenaive = 1\n \n task_info = namedtuple(\n \"task_info\",\n [\n \"genotype\",\n \"top1\",\n \"w_task\",\n \"a_task\",\n \"loss\",\n \"y_test_pred\",\n \"sparse_num_params\",\n \"w_task_bot\",\n \"a_task_bot\"\n ],\n )\n task_info.w_task = w_task\n task_info.a_task = a_task\n task_info.loss = loss\n y_test_pred = y_test_pred\n task_info.y_test_pred = y_test_pred\n task_info.genotype = genotype\n # task_info.top1 = top1\n\n # task_info.sparse_num_params = self.model.get_sparse_num_params(\n # self.model.alpha_prune_threshold\n # )\n task_info.w_task_bot = w_task_bot\n task_info.a_task_bot = a_task_bot\n\n return task_info" }, { "identifier": "Architect", "path": "task_optimizer/darts.py", "snippet": "class Architect:\n \"\"\" Compute gradients of alphas \"\"\"\n\n def __init__(self, net, w_momentum, w_weight_decay, use_first_order_darts):\n \"\"\"\n Args:\n net\n w_momentum: weights momentum\n \"\"\"\n self.net = net\n self.v_net = copy.deepcopy(net)\n self.w_momentum = w_momentum\n self.w_weight_decay = w_weight_decay\n self.use_first_order_darts = use_first_order_darts\n self.pprevious_grads = list()\n \n\n def virtual_step(self, train_X, train_y, xi, w_optim):\n \"\"\"\n Compute unrolled weight w' (virtual step)\n\n Step process:\n 1) forward\n 2) calc loss\n 3) compute gradient (by backprop)\n 4) update gradient\n\n Args:\n xi: learning rate for virtual gradient step (same as weights lr)\n w_optim: weights optimizer\n \"\"\"\n # forward & calc loss\n loss = self.net.loss(train_X, train_y) # L_train(w)\n\n # compute gradient\n gradients = torch.autograd.grad(loss, self.net.weights())\n\n \n \n\n\n\n \n # do virtual step (update gradient)\n # below operations do not need gradient tracking\n with torch.no_grad():\n # dict key is not the value, but the pointer. So original network weight have to\n # be iterated also.\n for w, vw, g in zip(self.net.weights(), self.v_net.weights(), gradients):\n m = w_optim.state[w].get(\"momentum_buffer\", 0.0) * self.w_momentum\n vw.copy_(w - xi * (m + g + self.w_weight_decay * w))\n\n # synchronize alphas\n for a, va in zip(self.net.alphas(), self.v_net.alphas()):\n va.copy_(a)\n\n def backward(self, train_X, train_y, val_X, val_y, xi, w_optim):\n \"\"\"Compute loss and backward its gradients\n Args:\n xi: learning rate for virtual gradient step (same as net lr)\n w_optim: weights optimizer - for virtual step\n \"\"\"\n # calc unrolled loss\n loss = self.v_net.loss(val_X, val_y) # L_val(w`)\n # compute gradient\n v_alphas = tuple(self.v_net.alphas())\n v_weights = tuple(self.v_net.weights())\n v_grads = torch.autograd.grad(loss, v_alphas + v_weights, allow_unused=True)\n dalpha = v_grads[: len(v_alphas)]\n dw = v_grads[len(v_alphas) :]\n\n \n\n if self.use_first_order_darts: # use first oder approximation for darts\n \n with torch.no_grad():\n for alpha, da in zip(self.net.alphas(), dalpha):\n alpha.grad = da\n \n\n else: # 2nd order DARTS\n\n hessian = self.compute_hessian(dw, train_X, train_y)\n\n # update final gradient = dalpha - xi*hessian\n with torch.no_grad():\n for alpha, da, h in zip(self.net.alphas(), dalpha, hessian):\n alpha.grad = da - xi * h\n\n\n\n\n def partial_alpha_backward(self,config, train_X, train_y, val_X, val_y, xi, w_optim):\n \"\"\"Compute loss and backward its gradients\n Args:\n \n xi: learning rate for virtual gradient step (same as net lr)\n w_optim: weights optimizer - for virtual step\n \"\"\"\n # compute gradient\n grad_output_sum = copy.deepcopy(self.v_net.net.config.alpha_previous_grad)\n \n if config.residual_flag == 1:\n pprevious_grad = copy.deepcopy(self.v_net.net.config.alpha_pprevious_grad)\n self.pprevious_grads.append(pprevious_grad) \n \n latent = self.v_net(val_X)\n\n\n v_alphas = tuple(self.v_net.alphas())\n v_weights = tuple(self.v_net.weights())\n\n if config.residual_flag == 1:\n try:\n if self.v_net.net.config.cell_phase == 1:\n grad_output_sum = torch.add(self.pprevious_grads[0],grad_output_sum)\n\n elif self.v_net.net.config.cell_phase == 0:\n grad_output_sum = torch.add(self.pprevious_grads[1],grad_output_sum)\n except:\n print(f\"Shape error,{grad_output_sum.shape} was the desired shape but you got {self.pprevious_grads[0].shape} or {self.pprevious_grads[1].shape}.\")\n print(\"Bypassing residual flag.\")\n\n v_grads = torch.autograd.grad(latent, v_alphas + v_weights, grad_outputs=grad_output_sum, allow_unused=True) \n dalpha = v_grads[: len(v_alphas)]\n dw = v_grads[len(v_alphas) :]\n \n \n\n if self.use_first_order_darts: # use first oder approximation for darts\n \n with torch.no_grad():\n for alpha, da in zip(self.net.alphas(), dalpha):\n if alpha.grad is not None and da is not None:\n alpha.grad.data.add_(da)\n else:\n alpha.grad= da\n\n else: # 2nd order DARTS\n\n hessian = self.compute_hessian(dw, train_X, train_y)\n\n # update final gradient = dalpha - xi*hessian\n with torch.no_grad():\n for alpha, da, h in zip(self.net.alphas(), dalpha, hessian):\n alpha.grad = da - xi * h\n\n def compute_hessian(self, dw, train_X, train_y):\n \"\"\"\n dw = dw` { L_val(w`, alpha) }\n w+ = w + eps * dw\n w- = w - eps * dw\n hessian = (dalpha { L_train(w+, alpha) } - dalpha { L_train(w-, alpha) }) / (2*eps)\n eps = 0.01 / ||dw||\n \"\"\"\n norm = torch.cat([w.view(-1) for w in dw]).norm()\n eps = 0.01 / norm\n \n # w+ = w + eps*dw`\n with torch.no_grad():\n for p, d in zip(self.net.weights(), dw):\n p += eps * d\n\n # dalpha { L_train(w+) }\n loss = self.net.loss(train_X, train_y)\n dalpha_pos = torch.autograd.grad(loss, self.net.alphas())\n\n # w- = w - eps*dw`\n with torch.no_grad():\n for p, d in zip(self.net.weights(), dw):\n p -= 2.0 * eps * d\n\n # dalpha { L_train(w-) }\n loss = self.net.loss(train_X, train_y)\n dalpha_neg = torch.autograd.grad(loss, self.net.alphas())\n\n # recover w\n with torch.no_grad():\n for p, d in zip(self.net.weights(), dw):\n p += eps * d\n\n hessian = [(p - n) / 2.0 * eps for p, n in zip(dalpha_pos, dalpha_neg)]\n return hessian" }, { "identifier": "train", "path": "task_optimizer/darts.py", "snippet": "def train(\n task,\n model,\n architect,\n w_optim,\n alpha_optim,\n lr,\n global_progress,\n config,\n warm_up=False,\n test_phase = False\n):\n model.train()\n pprevious_grads = list()\n initial_model = copy.deepcopy(model)\n \n p_bar_monitor = (enumerate(zip(task.train_loader, task.valid_loader)))#\n for step, ((train_X, train_y), (val_X, val_y)) in p_bar_monitor:\n\n start = torch.cuda.Event(enable_timing=True)\n end = torch.cuda.Event(enable_timing=True)\n start.record()\n \n train_X, train_y = train_X.to(config.device), train_y.to(config.device)\n val_X, val_y = val_X.to(config.device), val_y.to(config.device)\n N = train_X.size(0)\n initial_alpha = [copy.deepcopy(x).detach().cpu() for x in model.alphas()]\n \n if config.light_exp == 1:\n\n if config.meta_model != \"pc_adaptation\" and config.meta_model != \"pure_darts\" and config.dataset != \"cifar10\" and config.dataset != \"cifar100\":\n config.cell_phase = config.layers -1\n architect.v_net.net.config.cell_phase = config.layers -1\n # phase 2. architect step (alpha)\n prohibited_list = config.prohibited_list\n if config.naivenaive != 1 and config.eval_switch != 1 and config.meta_model != \"pc_adaptation\" and config.meta_model != \"pure_darts\" and config.dataset not in prohibited_list:\n\n w_optim.zero_grad()\n alpha_optim.zero_grad()\n train_X, train_y = train_X.chunk(config.split_num), train_y.chunk(config.split_num)\n val_X,val_y = val_X.chunk(config.split_num), val_y.chunk(config.split_num)\n \n for (train_X_chunk, train_y_chunk) ,(val_X_chunk,val_y_chunk) in zip(zip(train_X,train_y),zip(val_X,val_y)):\n config.cell_phase = config.layers -1\n architect.v_net.net.config.cell_phase = config.layers -1\n for phase in range(config.layers):\n \n if not warm_up: # only update alphas outside warm up phase\n if config.do_unrolled_architecture_steps:\n architect.virtual_step(train_X_chunk, train_y_chunk, lr, w_optim) # (calc w`)\n \n if config.cell_phase == config.layers -1:\n architect.v_net.net.cells[config.cell_phase].alpha_switch = 1 \n architect.backward(train_X_chunk, train_y_chunk, val_X_chunk, val_y_chunk, lr, w_optim)\n \n \n else:\n architect.v_net.net.cells[config.cell_phase].alpha_switch = 1\n architect.partial_alpha_backward(config, train_X_chunk, train_y_chunk, val_X_chunk, val_y_chunk, lr, w_optim) \n \n \n model.net.alpha_switch = 0\n architect.v_net.net.alpha_switch = 0\n\n # phase 1. child network step (w)\n if config.cell_phase == config.layers -1:\n w_optim.zero_grad()\n logits = model(train_X_chunk)\n loss = model.criterion(logits, train_y_chunk)\n loss_monitor = loss.item()\n loss.backward()\n nn.utils.clip_grad_norm_(model.weights(), config.w_grad_clip) \n w_optim.step()\n\n\n else:\n w_optim.zero_grad()\n output_grad_sum = copy.deepcopy(config.previous_grad)\n pprevious_grad = copy.deepcopy(config.pprevious_grad)\n pprevious_grads.append(pprevious_grad)\n\n if config.residual_flag == 1:\n if config.cell_phase == 1:\n if pprevious_grads[0].shape != output_grad_sum.shape:\n output_grad_sum = output_grad_sum\n else:\n output_grad_sum = torch.add(pprevious_grads[0],output_grad_sum)\n elif config.cell_phase == 0:\n if pprevious_grads[1].shape != output_grad_sum.shape:\n output_grad_sum = output_grad_sum\n else:\n output_grad_sum = torch.add(pprevious_grads[1],output_grad_sum)\n latent = model(train_X_chunk)\n\n\n \n try:\n latent.backward(output_grad_sum)\n \n except:\n if output_grad_sum is not None:\n print(\"batch passed,\",output_grad_sum.shape, \" was the shape of grad saved\")\n print(\"what we had to save was this shape, \", latent.shape )\n print(f\"And this was the phase.{config.cell_phase} what can be the problem here ? \")\n else:\n print(\"output was none. Why?\")\n pass\n nn.utils.clip_grad_norm_(model.weights(), config.w_grad_clip)\n \n\n \n config.cell_phase -= 1\n architect.v_net.net.config.cell_phase -= 1\n alpha_optim.step() \n w_optim.step()\n \n\n \n \n \n\n else:\n if not warm_up: # only update alphas outside warm up phase\n alpha_optim.zero_grad()\n \n if config.do_unrolled_architecture_steps:\n architect.virtual_step(train_X, train_y, lr, w_optim) # (calc w`)\n \n architect.backward(train_X, train_y, val_X, val_y, lr, w_optim)\n alpha_optim.step()\n \n\n \n w_optim.zero_grad()\n \n logits = model(train_X)\n \n loss = model.criterion(logits, train_y)\n loss.backward()\n nn.utils.clip_grad_norm_(model.weights(), config.w_grad_clip)\n w_optim.step()\n\n \n \n\n\n end.record()\n torch.cuda.synchronize()\n config.computing_time += start.elapsed_time(end)\n \n config.total_steps -= 1\n pprevious_grads = list()\n architect.pprevious_grads = list()\n \n if config.alpha_expect and config.meta_model != 'pc_adaptation':\n if len(config.alpha_grad_footprints) <= 5:\n\n learnt_alpha = [copy.deepcopy(x).detach().cpu() for x in model.alphas()]\n alpha_grad = _alpha_subtract(initial_alpha,learnt_alpha)\n config.alpha_grad_footprints.append(alpha_grad) \n\n\n else:\n \n learnt_alpha = [copy.deepcopy(x).detach().cpu() for x in model.alphas()]\n alpha_grad = _alpha_subtract(initial_alpha,learnt_alpha)\n \n config.alpha_grad_footprints.pop(0) \n config.alpha_grad_footprints.append(alpha_grad) \n\n config.alpha_sample_metrics = _exp_alpha_metric(initial_alpha,config)\n architect.v_net.net.config.alpha_sample_metrics = config.alpha_sample_metrics\n\n ###################################################################################\n\n\n task_specific_model = copy.deepcopy(model)\n task_specific_model = get_diff_for_const_bottom(initial_model,task_specific_model)\n \n return task_specific_model" } ]
import os import torch import torch.nn as nn import numpy as np import utils.utils as utils import random import time import pandas as pd import copy import argparse from utils import genotypes as gt from models.search_cnn import SearchCNNController from models.search_cnn_PC import SearchCNNControllerPC from task_optimizer.darts import Darts,Architect from task_optimizer.darts import train as d_train from tqdm import tqdm from tqdm import tqdm
16,321
torch.backends.cudnn.benchmark = True # get data with meta info input_size, input_channels, n_classes, train_data = utils.get_data( config.dataset, config.data_path, cutout_length=0, validation=False) _,_,_,_,test_data = utils.get_data(config.dataset, config.data_path, cutout_length=0, validation=True) # input my model architecture here normalizer = _init_alpha_normalizer( config.normalizer, config.task_train_steps, config.normalizer_t_max, config.normalizer_t_min, config.normalizer_temp_anneal_mode, ) net_crit = nn.CrossEntropyLoss().to(device) model = SearchCNNController( 3, config.init_channels, config.k, config.layers, config, n_nodes=config.nodes, reduction_layers=config.reduction_layers, device_ids=config.gpus, normalizer=normalizer, PRIMITIVES=gt.PRIMITIVES, feature_scale_rate=1, use_hierarchical_alphas=config.use_hierarchical_alphas, use_pairwise_input_alphas=config.use_pairwise_input_alphas, alpha_prune_threshold=config.alpha_prune_threshold, ) if config.meta_model == 'pc_adaptation': print("model created as PC adaptation") model = SearchCNNControllerPC( 3, config.init_channels, config.k, config.layers, n_nodes=config.nodes, reduction_layers=config.reduction_layers, device_ids=config.gpus, normalizer=normalizer, PRIMITIVES=gt.PRIMITIVES, feature_scale_rate=1, use_hierarchical_alphas=config.use_hierarchical_alphas, use_pairwise_input_alphas=config.use_pairwise_input_alphas, use_pc_adaptation=True, alpha_prune_threshold=config.alpha_prune_threshold ) ############################################################ model = model.to(device) # weights optimizer w_optim = torch.optim.Adam(model.weights(), config.w_lr, betas=(0.0, 0.999), weight_decay=config.w_weight_decay) # alphas optimizer alpha_optim = torch.optim.Adam(model.alphas(), config.alpha_lr, betas=(0.0, 0.999), weight_decay=config.alpha_weight_decay) # split data to train/validation n_train = len(train_data) split = n_train // 2 # changed here indices = list(range(n_train)) train_sampler = torch.utils.data.sampler.SubsetRandomSampler(indices[split:]) #and order of these valid_sampler = torch.utils.data.sampler.SubsetRandomSampler(indices[:split]) train_loader = torch.utils.data.DataLoader(train_data, batch_size=config.batch_size, sampler=train_sampler, num_workers=config.workers, pin_memory=True) valid_loader = torch.utils.data.DataLoader(train_data, batch_size=config.batch_size, sampler=valid_sampler, num_workers=config.workers, pin_memory=True) test_loader = torch.utils.data.DataLoader(test_data,batch_size=config.batch_size, shuffle=True, num_workers=config.workers, pin_memory=True) lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(w_optim, config.epochs, eta_min=0.0) architect = Architect(model, config.w_momentum, config.w_weight_decay, use_first_order_darts=True) # training loop best_top1 = 0. global_progress = 0 start_time = time.process_time() warm_up_flag = False epoch_avg = pd.DataFrame() for epoch in tqdm(range(config.epochs),total=config.epochs): mem = torch.cuda.memory_stats(0)['allocated_bytes.all.peak']/(1024**2) config.epoch_score = [] lr = lr_scheduler.get_last_lr()[0] # training loader_chunk = Loader_Chunk(train_loader,valid_loader) if epoch < config.warm_up_epochs: warm_up_flag = True #a = list(self.parameters())[0].clone() # loss.backward() # self.optimizer.step() # b = list(self.parameters())[0].clone() # torch.equal(a.data, b.data)
""" Search cell """ ''' Based on https://github.com/boschresearch/metanas which is licensed under GNU Affero General Public License, ''' device = torch.device("cuda") # tensorboard def _init_alpha_normalizer(name, task_train_steps, t_max, t_min, temp_anneal_mode): normalizer = dict() normalizer["name"] = name normalizer["params"] = dict() normalizer["params"]["curr_step"] = 0.0 # current step for scheduling normalizer normalizer["params"]["max_steps"] = float( task_train_steps ) # for scheduling normalizer normalizer["params"]["t_max"] = t_max normalizer["params"]["t_min"] = t_min normalizer["params"]["temp_anneal_mode"] = temp_anneal_mode # temperature annealing return normalizer def main(config): # set default gpu device id torch.cuda.set_device(config.gpus[0]) # set seed np.random.seed(config.seed) torch.manual_seed(config.seed) torch.cuda.manual_seed_all(config.seed) random.seed(config.seed) torch.backends.cudnn.benchmark = True # get data with meta info input_size, input_channels, n_classes, train_data = utils.get_data( config.dataset, config.data_path, cutout_length=0, validation=False) _,_,_,_,test_data = utils.get_data(config.dataset, config.data_path, cutout_length=0, validation=True) # input my model architecture here normalizer = _init_alpha_normalizer( config.normalizer, config.task_train_steps, config.normalizer_t_max, config.normalizer_t_min, config.normalizer_temp_anneal_mode, ) net_crit = nn.CrossEntropyLoss().to(device) model = SearchCNNController( 3, config.init_channels, config.k, config.layers, config, n_nodes=config.nodes, reduction_layers=config.reduction_layers, device_ids=config.gpus, normalizer=normalizer, PRIMITIVES=gt.PRIMITIVES, feature_scale_rate=1, use_hierarchical_alphas=config.use_hierarchical_alphas, use_pairwise_input_alphas=config.use_pairwise_input_alphas, alpha_prune_threshold=config.alpha_prune_threshold, ) if config.meta_model == 'pc_adaptation': print("model created as PC adaptation") model = SearchCNNControllerPC( 3, config.init_channels, config.k, config.layers, n_nodes=config.nodes, reduction_layers=config.reduction_layers, device_ids=config.gpus, normalizer=normalizer, PRIMITIVES=gt.PRIMITIVES, feature_scale_rate=1, use_hierarchical_alphas=config.use_hierarchical_alphas, use_pairwise_input_alphas=config.use_pairwise_input_alphas, use_pc_adaptation=True, alpha_prune_threshold=config.alpha_prune_threshold ) ############################################################ model = model.to(device) # weights optimizer w_optim = torch.optim.Adam(model.weights(), config.w_lr, betas=(0.0, 0.999), weight_decay=config.w_weight_decay) # alphas optimizer alpha_optim = torch.optim.Adam(model.alphas(), config.alpha_lr, betas=(0.0, 0.999), weight_decay=config.alpha_weight_decay) # split data to train/validation n_train = len(train_data) split = n_train // 2 # changed here indices = list(range(n_train)) train_sampler = torch.utils.data.sampler.SubsetRandomSampler(indices[split:]) #and order of these valid_sampler = torch.utils.data.sampler.SubsetRandomSampler(indices[:split]) train_loader = torch.utils.data.DataLoader(train_data, batch_size=config.batch_size, sampler=train_sampler, num_workers=config.workers, pin_memory=True) valid_loader = torch.utils.data.DataLoader(train_data, batch_size=config.batch_size, sampler=valid_sampler, num_workers=config.workers, pin_memory=True) test_loader = torch.utils.data.DataLoader(test_data,batch_size=config.batch_size, shuffle=True, num_workers=config.workers, pin_memory=True) lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(w_optim, config.epochs, eta_min=0.0) architect = Architect(model, config.w_momentum, config.w_weight_decay, use_first_order_darts=True) # training loop best_top1 = 0. global_progress = 0 start_time = time.process_time() warm_up_flag = False epoch_avg = pd.DataFrame() for epoch in tqdm(range(config.epochs),total=config.epochs): mem = torch.cuda.memory_stats(0)['allocated_bytes.all.peak']/(1024**2) config.epoch_score = [] lr = lr_scheduler.get_last_lr()[0] # training loader_chunk = Loader_Chunk(train_loader,valid_loader) if epoch < config.warm_up_epochs: warm_up_flag = True #a = list(self.parameters())[0].clone() # loss.backward() # self.optimizer.step() # b = list(self.parameters())[0].clone() # torch.equal(a.data, b.data)
d_train(loader_chunk,model,architect,w_optim,alpha_optim,config.w_lr,global_progress,config,warm_up=warm_up_flag)
4
2023-10-08 02:42:27+00:00
24k
LukeForeverYoung/UReader
serve/model_worker.py
[ { "identifier": "IO", "path": "serve/io_utils.py", "snippet": "class IO:\n @staticmethod\n def register(options):\n pass\n\n def open(self, path: str, mode: str):\n raise NotImplementedError\n\n def exists(self, path: str) -> bool:\n raise NotImplementedError\n\n def move(self, src: str, dst: str):\n raise NotImplementedError\n\n def copy(self, src: str, dst: str):\n raise NotImplementedError\n\n def makedirs(self, path: str, exist_ok=True):\n raise NotImplementedError\n\n def remove(self, path: str):\n raise NotImplementedError\n\n def listdir(self, path: str, recursive=False, full_path=False, contains=None):\n raise NotImplementedError\n\n def isdir(self, path: str) -> bool:\n raise NotImplementedError\n\n def isfile(self, path: str) -> bool:\n raise NotImplementedError\n\n def abspath(self, path: str) -> str:\n raise NotImplementedError\n\n def last_modified(self, path: str) -> datetime:\n raise NotImplementedError\n\n def md5(self, path: str) -> str:\n hash_md5 = hashlib.md5()\n with self.open(path, 'rb') as f:\n for chunk in iter(lambda: f.read(4096), b''):\n hash_md5.update(chunk)\n return hash_md5.hexdigest()\n\n re_remote = re.compile(r'(oss|https?)://')\n\n def islocal(self, path: str) -> bool:\n return not self.re_remote.match(path.lstrip())" }, { "identifier": "DefaultIO", "path": "serve/io_utils.py", "snippet": "class DefaultIO(IO):\n __name__ = 'DefaultIO'\n\n def _check_path(self, path):\n if not self.islocal(path):\n raise RuntimeError(\n 'Credentials must be provided to use oss path. '\n 'Make sure you have created \"user/modules/oss_credentials.py\" according to ReadMe.')\n\n def open(self, path, mode='r'):\n self._check_path(path)\n path = self.abspath(path)\n return open(path, mode=mode)\n\n def exists(self, path):\n self._check_path(path)\n path = self.abspath(path)\n return os.path.exists(path)\n\n def move(self, src, dst):\n self._check_path(src)\n self._check_path(dst)\n src = self.abspath(src)\n dst = self.abspath(dst)\n shutil.move(src, dst)\n\n def copy(self, src, dst):\n self._check_path(src)\n self._check_path(dst)\n src = self.abspath(src)\n dst = self.abspath(dst)\n try:\n shutil.copyfile(src, dst)\n except shutil.SameFileError:\n pass\n\n def makedirs(self, path, exist_ok=True):\n self._check_path(path)\n path = self.abspath(path)\n os.makedirs(path, exist_ok=exist_ok)\n\n def remove(self, path):\n self._check_path(path)\n path = self.abspath(path)\n if os.path.isdir(path):\n shutil.rmtree(path)\n else:\n os.remove(path)\n\n def listdir(self, path, recursive=False, full_path=False, contains=None):\n self._check_path(path)\n path = self.abspath(path)\n contains = contains or ''\n if recursive:\n files = (os.path.join(dp, f) if full_path else f for dp, dn, fn in os.walk(path) for f in fn)\n files = [file for file in files if contains in file]\n else:\n files = os.listdir(path)\n if full_path:\n files = [os.path.join(path, file) for file in files if contains in file]\n return files\n\n def isdir(self, path):\n return os.path.isdir(path)\n\n def isfile(self, path):\n return os.path.isfile(path)\n\n def abspath(self, path):\n return os.path.abspath(path)\n\n def last_modified(self, path):\n return datetime.fromtimestamp(os.path.getmtime(path))" }, { "identifier": "OSS", "path": "serve/io_utils.py", "snippet": "class OSS(DefaultIO):\n \"Mixed IO module to support both system-level and OSS IO methods\"\n __name__ = 'OSS'\n\n def __init__(self, access_key_id: str, access_key_secret: str, region_bucket: List[List[str]]):\n \"\"\"\n the value of \"region_bucket\" should be something like [[\"cn-hangzhou\", \"<yourBucketName>\"], [\"cn-zhangjiakou\", \"<yourBucketName>\"]],\n specifying your buckets and corresponding regions\n \"\"\"\n from oss2 import Auth, Bucket, ObjectIterator\n super().__init__()\n self.ObjectIterator = ObjectIterator\n self.auth = Auth(access_key_id, access_key_secret)\n self.buckets = {\n bucket_name: Bucket(self.auth, f'http://oss-{region}.aliyuncs.com', bucket_name)\n for region, bucket_name in region_bucket\n }\n self.oss_pattern = re.compile(r'oss://([^/]+)/(.+)')\n\n def _split_name(self, path):\n m = self.oss_pattern.match(path)\n if not m:\n raise IOError(f'invalid oss path: \"{path}\", should be \"oss://<bucket_name>/path\"')\n bucket_name, path = m.groups()\n return bucket_name, path\n\n def _split(self, path):\n bucket_name, path = self._split_name(path)\n try:\n bucket = self.buckets[bucket_name]\n except KeyError:\n raise IOError(f'Bucket {bucket_name} not registered in oss_credentials.py')\n return bucket, path\n\n def open(self, full_path, mode='r'):\n if not full_path.startswith('oss://'):\n return super().open(full_path, mode)\n\n bucket, path = self._split(full_path)\n with mute_stderr():\n path_exists = bucket.object_exists(path)\n if 'w' in mode:\n if path_exists:\n bucket.delete_object(path)\n if 'b' in mode:\n return BinaryOSSFile(bucket, path)\n return OSSFile(bucket, path)\n elif mode == 'a':\n position = bucket.head_object(path).content_length if path_exists else 0\n return OSSFile(bucket, path, position=position)\n else:\n if not path_exists:\n raise FileNotFoundError(full_path)\n obj = bucket.get_object(path)\n # auto cache large files to avoid memory issues\n # if obj.content_length > 30 * 1024 ** 2: # 30M\n # from da.utils import cache_file\n # path = cache_file(full_path)\n # return super().open(path, mode)\n if mode == 'rb':\n # TODO for a large file, this will load the whole file into memory\n return NullContextWrapper(BytesIO(obj.read()))\n else:\n assert mode == 'r'\n return NullContextWrapper(StringIO(obj.read().decode()))\n\n def exists(self, path):\n if not path.startswith('oss://'):\n return super().exists(path)\n\n bucket, _path = self._split(path)\n # if file exists\n exists = self._file_exists(bucket, _path)\n # if directory exists\n if not exists:\n try:\n self.listdir(path)\n exists = True\n except FileNotFoundError:\n pass\n return exists\n\n def _file_exists(self, bucket, path):\n with mute_stderr():\n return bucket.object_exists(path)\n\n def move(self, src, dst):\n if not src.startswith('oss://') and not dst.startswith('oss://'):\n return super().move(src, dst)\n self.copy(src, dst)\n self.remove(src)\n\n def copy(self, src, dst):\n cloud_src = src.startswith('oss://')\n cloud_dst = dst.startswith('oss://')\n if not cloud_src and not cloud_dst:\n return super().copy(src, dst)\n\n # download\n if cloud_src and not cloud_dst:\n bucket, src = self._split(src)\n obj = bucket.get_object(src)\n if obj.content_length > 100 * 1024 ** 2: # 100M\n from tqdm import tqdm\n progress = None\n\n def callback(i, n):\n nonlocal progress\n if progress is None:\n progress = tqdm(total=n, unit='B', unit_scale=True, unit_divisor=1024, leave=False,\n desc=f'downloading')\n progress.update(i - progress.n)\n\n bucket.get_object_to_file(src, dst, progress_callback=callback)\n if progress is not None:\n progress.close()\n else:\n bucket.get_object_to_file(src, dst)\n return\n bucket, dst = self._split(dst)\n # upload\n if cloud_dst and not cloud_src:\n bucket.put_object_from_file(dst, src)\n return\n # copy between oss paths\n if src != dst:\n src_bucket_name, src = self._split_name(src)\n bucket.copy_object(src_bucket_name, src, dst)\n # TODO: support large file copy\n # https://help.aliyun.com/document_detail/88465.html?spm=a2c4g.11174283.6.882.4d157da2mgp3xc\n\n def listdir(self, path, recursive=False, full_path=False, contains=None):\n if not path.startswith('oss://'):\n return super().listdir(path, recursive, full_path, contains)\n\n bucket, path = self._split(path)\n path = path.rstrip('/') + '/'\n files = [obj.key for obj in self.ObjectIterator(bucket, prefix=path, delimiter='' if recursive else '/')]\n try:\n files.remove(path)\n except ValueError:\n pass\n if full_path:\n files = [f'oss://{bucket.bucket_name}/{file}' for file in files]\n else:\n files = [file[len(path):] for file in files]\n if not files:\n raise FileNotFoundError(f'No such directory: oss://{bucket.bucket_name}/{path}')\n files = [file for file in files if (contains or '') in file]\n return files\n\n def remove(self, path):\n if not path.startswith('oss://'):\n return super().remove(path)\n\n if self.isfile(path):\n paths = [path]\n else:\n paths = self.listdir(path, recursive=True, full_path=True)\n for path in paths:\n bucket, path = self._split(path)\n bucket.delete_object(path)\n\n def makedirs(self, path, exist_ok=True):\n # there is no need to create directory in oss\n if not path.startswith('oss://'):\n return super().makedirs(path)\n\n def isdir(self, path):\n if not path.startswith('oss://'):\n return super().isdir(path)\n return self.exists(path.rstrip('/') + '/')\n\n def isfile(self, path):\n if not path.startswith('oss://'):\n return super().isdir(path)\n return self.exists(path) and not self.isdir(path)\n\n def abspath(self, path):\n if not path.startswith('oss://'):\n return super().abspath(path)\n return path\n\n def authorize(self, path):\n if not path.startswith('oss://'):\n raise ValueError('Only oss path can use \"authorize\"')\n import oss2\n bucket, path = self._split(path)\n bucket.put_object_acl(path, oss2.OBJECT_ACL_PUBLIC_READ)\n\n def last_modified(self, path):\n if not path.startswith('oss://'):\n return super().last_modified(path)\n bucket, path = self._split(path)\n return datetime.strptime(\n bucket.get_object_meta(path).headers['Last-Modified'],\n r'%a, %d %b %Y %H:%M:%S %Z'\n ) + timedelta(hours=8)" }, { "identifier": "MplugOwlProcessor", "path": "mplug_owl/processing_mplug_owl.py", "snippet": "class MplugOwlProcessor(ProcessorMixin):\n attributes = []\n tokenizer_class = (\"MplugOwlTokenizer\")\n\n def __init__(self, image_processor=None, tokenizer=None, **kwargs):\n super().__init__(**kwargs)\n self.tokens_to_generate = 0\n self.image_processor = image_processor\n self.tokenizer = tokenizer\n self.add_BOS = True\n\n def __call__(self, text=None, images=None, return_tensors=None, **kwargs):\n args = get_args()\n if text is None and images is None:\n raise ValueError(\"You have to specify either text or images. Both cannot be none.\")\n\n if images is not None:\n if not isinstance(images, list):\n images = [images]\n # image_features, = self.image_processor(images, return_tensors=return_tensors, **kwargs)\n process_results = [self.image_processor(image=image, text=None) for image in images]\n if len(process_results)>0 and len(process_results[0][0].shape) == 4:\n # 图片被切分成了多块 默认是doc场景\n text_list = text.split('<image>')\n images = []\n patch_positions = []\n text = text_list[0]\n for ri, (image_input, text_input, patch_position) in enumerate(process_results):\n images.append(image_input)\n patch_positions.append(patch_position)\n if args.patch_pos_embed_type == 'pre':\n # 对于pre处理 v2t最终输出的是一张图的token\n text += '<image>'\n else:\n # 对于post处理 v2t最终输出的是多图\n text += '<image>'*image_input.shape[0]\n text += text_list[ri+1]\n images = torch.cat(images, dim=0)\n patch_positions = torch.cat(patch_positions, dim=0)\n else:\n # 如果没有切片 则正常stack 并创建patch position = num_image (0,0)的patch id以保持一致\n images = [_[0] for _ in process_results]\n images = torch.stack(images, dim=0)\n patch_positions = torch.zeros(images.shape[0],2).long()\n text = text\n if text is not None:\n encoding = tokenize_prompts(\n prompts=[text],\n tokens_to_generate=self.tokens_to_generate,\n add_BOS=self.add_BOS,\n tokenizer=self.tokenizer,\n ignore_dist=True,\n **kwargs,\n )\n # encoding = self.tokenizer(text, return_tensors=return_tensors, **kwargs)\n\n \n if text is not None and images is not None:\n encoding[\"pixel_values\"] = images\n encoding[\"patch_positions\"] = patch_position\n return BatchEncoding(data=encoding)\n elif text is not None:\n return BatchEncoding(data=encoding)\n else:\n return BatchEncoding(data=dict(pixel_values=images, patch_position=patch_position), tensor_type=return_tensors)\n\n def batch_decode(self, skip_special_tokens=True, *args, **kwargs):\n \"\"\"\n This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please\n refer to the docstring of this method for more information.\n \"\"\"\n return self.tokenizer.batch_decode(*args, skip_special_tokens=skip_special_tokens, **kwargs)\n\n def decode(self, skip_special_tokens=True, *args, **kwargs):\n \"\"\"\n This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to\n the docstring of this method for more information.\n \"\"\"\n return self.tokenizer.decode(*args, skip_special_tokens=skip_special_tokens, **kwargs)" }, { "identifier": "MplugOwlImageProcessor", "path": "mplug_owl/processing_mplug_owl.py", "snippet": "class MplugOwlImageProcessor(CLIPImageProcessor):\n pass" }, { "identifier": "MplugOwlForConditionalGeneration", "path": "mplug_owl/modeling_mplug_owl.py", "snippet": "class MplugOwlForConditionalGeneration(MplugOwlPreTrainedModel):\n config_class = MplugOwlConfig\n main_input_name = \"pixel_values\"\n\n def __init__(self, config: MplugOwlConfig):\n super().__init__(config)\n\n self.vision_model = MplugOwlVisionModel(config.vision_config)\n\n self.query_tokens = nn.Parameter(\n torch.zeros(1, config.num_query_tokens, config.visual_abstractor_config.hidden_size)\n )\n self.num_queries = config.num_query_tokens\n self.abstractor = MplugOwlVisualAbstractorModel(\n config.visual_abstractor_config, config.text_config.hidden_size\n )\n language_model = AutoModelForCausalLM.from_config(config.text_config)\n self.language_model = language_model\n\n # Initialize weights and apply final processing\n self.post_init()\n self.main_input_name = \"input_ids\"\n from transformers import GenerationConfig\n\n self.generation_config = GenerationConfig(\n max_length=512, do_sample=True, top_k=3, pad_token_id=0, unk_token_id=0, bos_token_id=1, eos_token_id=2\n )\n\n def get_input_embeddings(self):\n return self.language_model.get_input_embeddings()\n\n def set_input_embeddings(self, value):\n self.language_model.set_input_embeddings(value)\n\n def set_output_embeddings(self, new_embeddings):\n self.language_model.set_output_embeddings(new_embeddings)\n\n def get_output_embeddings(self) -> nn.Module:\n return self.language_model.get_output_embeddings()\n\n def get_encoder(self):\n return self.language_model.get_encoder()\n\n def get_decoder(self):\n return self.language_model.get_decoder()\n\n def _tie_weights(self):\n if not self.config.use_decoder_only_language_model:\n self.language_model.encoder.embed_tokens = self.language_model.shared\n self.language_model.decoder.embed_tokens = self.language_model.shared\n\n def _preprocess_accelerate(self):\n r\"\"\"\n Some pre-processing hacks to make the model `accelerate` compatible. Check\n https://github.com/huggingface/transformers/pull/21707 for more details.\n \"\"\"\n hf_device_map = self.hf_device_map\n\n if len(hf_device_map) > 1 and \"language_model\" not in hf_device_map and torch.cuda.device_count() > 1:\n # warn users about unexpected behavior when using multi-GPU + mPLUG-Owl + `accelerate`.\n logger.warning(\n \"The `language_model` is not in the `hf_device_map` dictionary and you are running your script\"\n \" in a multi-GPU environment. this may lead to unexpected behavior when using `accelerate`.\"\n \" Please pass a `device_map` that contains `language_model` to remove this warning.\"\n \" Please refer to https://github.com/huggingface/blog/blob/main/accelerate-large-models.md for\"\n \" more details on creating a `device_map` for large models.\",\n )\n\n if hasattr(self.language_model, \"_hf_hook\"):\n self.language_model._hf_hook.io_same_device = True # For `generate` compatibility\n\n @add_start_docstrings_to_model_forward(MPLUG_OWL_INPUTS_DOCSTRING)\n @replace_return_docstrings(\n output_type=MplugOwlForConditionalGenerationModelOutput, config_class=MplugOwlVisionConfig\n )\n def forward(\n self,\n pixel_values: torch.FloatTensor,\n input_ids: torch.FloatTensor,\n num_images,\n non_padding_mask: Optional[torch.LongTensor] = None,\n non_media_mask: Optional[torch.LongTensor] = None,\n prompt_mask: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n labels: Optional[torch.LongTensor] = None,\n patch_positions=None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, MplugOwlForConditionalGenerationModelOutput]:\n r\"\"\"\n Returns:\n\n SFT example:\n\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> from transformers import MplugOwlProcessor, MplugOwlForConditionalGeneration\n >>> import torch\n\n >>> device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n >>> processor = MplugOwlProcessor.from_pretrained(\"MAGAer13/mplug-owl-llama-7b\")\n >>> model = MplugOwlForConditionalGeneration.from_pretrained(\n ... \"MAGAer13/mplug-owl-llama-7b\", torch_dtype=torch.float16\n ... )\n >>> model.to(device) # doctest: +IGNORE_RESULT\n\n >>> url = \"http://images.cocodataset.org/val2017/000000039769.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> prompt = [\n ... \"The following is a conversation between a curious human and AI assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.\\nHuman: <image>\\nHuman: how many cats are there?\\nAI: \"\n ... ]\n >>> inputs = processor(images=[image], text=prompt, return_tensors=\"pt\").to(device, torch.float16)\n\n >>> generated_ids = model.generate(**inputs)\n >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()\n >>> print(generated_text)\n There are two cats in the image.\n ```\"\"\"\n if pixel_values is not None:\n pixel_values = pixel_values.to(self.vision_model.embeddings.cls_token.data.dtype)\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # get text embedding\n text_tokens_ = input_ids.clone()\n batch_size = input_ids.shape[0]\n # labels = text_tokens_[:, 1:].clone().contiguous()\n\n media_token_indices = [\n # [:-1] since we would not use the last token for embedding\n get_media_indices(text_tokens_[i][:-1], self.num_queries)\n for i in range(batch_size)\n ]\n text_tokens_[text_tokens_ < 0] = 1 # Not used\n # text_tokens = text_tokens_[:, :-1].contiguous()\n text_embeds = self.get_input_embeddings()(text_tokens_) # Temporally Embedding\n\n if pixel_values is not None:\n image_embeds = self.vision_model(pixel_values, patch_positions=patch_positions, return_dict=True).last_hidden_state\n\n image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)\n query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)\n\n query_features = self.abstractor(\n query_embeds=query_tokens,\n encoder_hidden_states=image_embeds,\n encoder_attention_mask=image_attention_mask,\n patch_positions=patch_positions,\n )[\"last_hidden_state\"]\n torch.ones(query_features.size()[:-1], dtype=torch.long).to(query_features.device)\n img_seq_length = query_features.shape[1]\n\n num_images_per_sample = num_images.long().cpu().tolist()\n\n text_chunk_embeds = []\n img_idx = 0\n for b in range(batch_size):\n start = 0\n result = []\n if len(media_token_indices[b]) > 0:\n for i, pos in enumerate(media_token_indices[b][0]):\n if pos > start:\n result.append(text_embeds[b, start:pos])\n result.append(query_features[img_idx + i])\n start = pos + img_seq_length\n if start < text_embeds.shape[1]:\n result.append(text_embeds[b, start:])\n\n img_idx += media_token_indices[b][1]\n text_chunk_embeds.append(torch.cat(result, dim=0))\n\n # Actual Input Embeddings\n input_embeds = torch.stack(text_chunk_embeds, dim=0)\n\n # Create causal mask and position ids\n _, loss_mask, position_ids = get_ltor_masks_and_position_ids_from_embeddings(input_embeds)\n\n # Calculate the loss_mask\n non_padding_mask = non_padding_mask.long()\n non_media_mask = non_media_mask.long()\n prompt_mask = prompt_mask.long() # TODO How to deal with prompt mask\n # from icecream import ic\n # non_padding_mask = non_padding_mask[:,:-1]\n # non_media_mask = non_media_mask[:,:-1]\n # prompt_mask = prompt_mask[:,:-1]\n # attention_mask = attention_mask[:,:-1]\n loss_mask = loss_mask[:, :-1]\n\n loss_mask = loss_mask * non_padding_mask * non_media_mask * prompt_mask\n labels[:, 1:][loss_mask != 1] = -100\n # Forward into GPT\n outputs = self.language_model(\n inputs_embeds=input_embeds,\n attention_mask=attention_mask,\n labels=labels,\n return_dict=return_dict,\n output_attentions=self.config.output_attentions,\n )\n outputs.loss = (outputs.loss * loss_mask.view(-1)\n ).sum()/loss_mask.sum()\n return outputs\n\n @torch.no_grad()\n def generate(\n self,\n pixel_values: torch.FloatTensor = None,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n patch_positions=None,\n isdecoder=True,\n **generate_kwargs,\n ) -> torch.LongTensor:\n \"\"\"\n Overrides `generate` function to be able to use the model as a conditional generator.\n\n Args:\n pixel_values (`torch.FloatTensor` of shape (batch_size, num_channels, height, width)):\n Input images to be processed.\n input_ids (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):\n The sequence used as a prompt for the generation.\n attention_mask (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):\n Mask to avoid performing attention on padding token indices\n\n Returns:\n captions (list): A list of strings of length batch_size * num_captions.\n \"\"\"\n if pixel_values is not None:\n pixel_values = pixel_values.to(self.vision_model.embeddings.cls_token.data.dtype)\n if input_ids is None:\n return self.language_model.generate(attention_mask=attention_mask, **generate_kwargs)\n\n if attention_mask is None:\n attention_mask = input_ids.new_ones(*input_ids.shape)\n\n batch_size = input_ids.size(0)\n media_token_indices = [get_media_indices(input_ids[i], self.num_queries) for i in range(batch_size)]\n input_ids = input_ids.clone() # prevent inplace modify\n input_ids[input_ids < 0] = 0 # Not used\n\n if hasattr(self, \"hf_device_map\"):\n # preprocess for `accelerate`\n self._preprocess_accelerate()\n batch_size = input_ids.shape[0]\n # get text embedding\n inputs_embeds = self.get_input_embeddings()(input_ids)\n # get visual embedding\n if pixel_values is not None:\n pixel_values = pixel_values.to(input_ids.device)\n with torch.no_grad():\n image_embeds = self.vision_model(pixel_values, patch_positions=patch_positions, return_dict=True).last_hidden_state\n image_attention_mask = torch.ones(\n image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device\n )\n query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)\n query_outputs = self.abstractor(\n query_embeds=query_tokens,\n encoder_hidden_states=image_embeds,\n encoder_attention_mask=image_attention_mask,\n patch_positions=patch_positions,\n return_dict=True,\n )\n query_output = query_outputs[\"last_hidden_state\"]\n image_embeds = query_output\n img_seq_length = image_embeds.shape[1]\n\n # ===================\n # Get actual input embeddings\n # ===================\n text_chunk_embeds = []\n text_chunk_attns = []\n img_idx = 0\n\n for b in range(batch_size):\n start = 0\n result = []\n result_attn = []\n for i, pos in enumerate(media_token_indices[b][0]):\n if pos > start:\n result.append(inputs_embeds[b, start:pos])\n result_attn.append(attention_mask[b, start:pos])\n result.append(image_embeds[img_idx + i])\n result_attn.append(torch.ones(image_embeds[img_idx + i].shape[0], device=inputs_embeds.device))\n start = pos + img_seq_length\n if start < inputs_embeds.shape[1]:\n result.append(inputs_embeds[b, start:])\n result_attn.append(attention_mask[b, start:])\n\n img_idx += media_token_indices[b][1]\n text_chunk_embeds.append(torch.cat(result, dim=0))\n text_chunk_attns.append(torch.cat(result_attn, dim=0))\n inputs_embeds = torch.stack(text_chunk_embeds, dim=0)\n attention_mask = torch.stack(text_chunk_attns, dim=0)\n\n outputs = self.language_model.generate(\n inputs_embeds=inputs_embeds,\n # input_ids=input_ids,\n attention_mask=attention_mask,\n **generate_kwargs,\n )\n\n return outputs\n\n def prepare_inputs_for_generation(\n self, input_ids, pixel_values=None, past_key_values=None, attention_mask=None, **model_kwargs\n ):\n input_shape = input_ids.shape\n # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly\n if attention_mask is None:\n attention_mask = input_ids.new_ones(input_shape)\n\n # # cut decoder_input_ids if past_key_values is used\n # if past_key_values is not None:\n # input_ids = input_ids[:, -1:]\n\n return {\n \"input_ids\": input_ids,\n \"pixel_values\": pixel_values,\n \"attention_mask\": attention_mask,\n \"is_decoder\": True,\n }" }, { "identifier": "MplugOwlConfig", "path": "mplug_owl/configuration_mplug_owl.py", "snippet": "class MplugOwlConfig(PretrainedConfig):\n r\"\"\"\n [`MplugOwlConfig`] is the configuration class to store the configuration of a [`MplugOwlForConditionalGeneration`].\n It is used to instantiate a mPLUG-Owl model according to the specified arguments, defining the vision model,\n Q-Former model and language model configs. Instantiating a configuration with the defaults will yield a similar\n configuration to that of the mPLUG-Owl [x-plug/x_plug-llama-7b](https://huggingface.co/x-plug/x_plug-llama-7b)\n architecture.\n\n Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the\n documentation from [`PretrainedConfig`] for more information.\n\n Args:\n vision_config (`dict`, *optional*):\n Dictionary of configuration options used to initialize [`MplugOwlVisionConfig`].\n visual_abstractor_config (`dict`, *optional*):\n Dictionary of configuration options used to initialize [`MplugOwlVisualAbstractorConfig`].\n text_config (`dict`, *optional*):\n Dictionary of configuration options used to initialize any [`PretrainedConfig`].\n num_query_tokens (`int`, *optional*, defaults to 32):\n The number of query tokens passed through the Transformer.\n\n kwargs (*optional*):\n Dictionary of keyword arguments.\n\n Example:\n\n ```python\n >>> from transformers import (\n ... MplugOwlVisionConfig,\n ... MplugOwlVisualAbstractorConfig,\n ... OPTConfig,\n ... MplugOwlConfig,\n ... MplugOwlForConditionalGeneration,\n ... )\n\n >>> # Initializing a MplugOwlConfig with x-plug/x_plug-llama-7b style configuration\n >>> configuration = MplugOwlConfig()\n\n >>> # Initializing a MplugOwlForConditionalGeneration (with random weights) from the x-plug/x_plug-llama-7b style configuration\n >>> model = MplugOwlForConditionalGeneration(configuration)\n\n >>> # Accessing the model configuration\n >>> configuration = model.config\n\n >>> # We can also initialize a MplugOwlConfig from a MplugOwlVisionConfig, MplugOwlVisualAbstractorConfig and any PretrainedConfig\n\n >>> # Initializing mPLUG-Owl vision, mPLUG-Owl Q-Former and language model configurations\n >>> vision_config = MplugOwlVisionConfig()\n >>> visual_abstractor_config = MplugOwlVisualAbstractorConfig()\n >>> text_config = OPTConfig()\n\n >>> config = MplugOwlConfig.from_text_vision_configs(vision_config, visual_abstractor_config, text_config)\n ```\"\"\"\n model_type = \"mplug-owl\"\n is_composition = True\n\n def __init__(\n self, vision_config=None, visual_abstractor_config=None, text_config=None, num_query_tokens=64, **kwargs\n ):\n super().__init__(**kwargs)\n if vision_config is None:\n vision_config = MplugOwlVisionConfig().to_dict()\n logger.info(\"vision_config is None.\")\n\n if visual_abstractor_config is None:\n visual_abstractor_config = {}\n logger.info(\"abstractor_config is None. \")\n\n if text_config is None:\n # we use LLAMA 7b by default\n from transformers.llama.configuration_llama import LlamaConfig\n\n text_config = LlamaConfig(pad_token_id=2).to_dict()\n logger.info(\"text_config is None.\")\n\n self.vision_config = MplugOwlVisionConfig(**vision_config)\n self.visual_abstractor_config = MplugOwlVisualAbstractorConfig(**visual_abstractor_config)\n # self.visual_abstractor_config.layer_norm_eps = 1e-6\n text_model_type = text_config[\"model_type\"] if \"model_type\" in text_config else \"llama\"\n self.text_config = CONFIG_MAPPING[text_model_type](**text_config)\n\n self.tie_word_embeddings = self.text_config.tie_word_embeddings\n self.is_encoder_decoder = self.text_config.is_encoder_decoder\n\n self.num_query_tokens = num_query_tokens\n # self.visual_abstractor_config.encoder_hidden_size = self.vision_config.hidden_size\n self.use_decoder_only_language_model = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES\n self.initializer_factor = 1.0\n self.initializer_range = 0.02\n\n for attr in dir(self.text_config):\n if not hasattr(self, attr):\n setattr(self, attr, getattr(self.text_config, attr))\n\n @classmethod\n def from_vision_visual_abstractor_text_configs(\n cls,\n vision_config: MplugOwlVisionConfig,\n visual_abstractor_config: MplugOwlVisualAbstractorConfig,\n text_config: PretrainedConfig,\n **kwargs,\n ):\n r\"\"\"\n Instantiate a [`MplugOwlConfig`] (or a derived class) from a mPLUG-Owl vision model, Q-Former and language\n model configurations.\n\n Returns:\n [`MplugOwlConfig`]: An instance of a configuration object\n \"\"\"\n\n return cls(\n vision_config=vision_config.to_dict(),\n visual_abstractor_config=visual_abstractor_config.to_dict(),\n text_config=text_config.to_dict(),\n **kwargs,\n )\n\n def to_dict(self):\n \"\"\"\n Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].\n\n Returns:\n `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,\n \"\"\"\n output = copy.deepcopy(self.__dict__)\n output[\"vision_config\"] = self.vision_config.to_dict()\n output[\"visual_abstractor_config\"] = self.visual_abstractor_config.to_dict()\n output[\"text_config\"] = self.text_config.to_dict()\n output[\"model_type\"] = self.__class__.model_type\n return output" }, { "identifier": "MplugOwlTokenizer", "path": "mplug_owl/tokenization_mplug_owl.py", "snippet": "class MplugOwlTokenizer(LlamaTokenizer):\n def __init__(\n self,\n vocab_file,\n unk_token=\"<unk>\",\n bos_token=\"<s>\",\n eos_token=\"</s>\",\n pad_token=\"<unk>\",\n sp_model_kwargs=None,\n add_bos_token=False,\n add_eos_token=False,\n clean_up_tokenization_spaces=False,\n **kwargs,\n ):\n super().__init__(\n vocab_file,\n unk_token,\n bos_token,\n eos_token,\n pad_token,\n sp_model_kwargs,\n add_bos_token,\n add_eos_token,\n clean_up_tokenization_spaces,\n **kwargs,\n )\n self.eod_id = self.eos_token_id" }, { "identifier": "post_process_output", "path": "serve/model_utils.py", "snippet": "def post_process_output(text):\n text = text.strip()\n pattern = re.compile(\n r\"<unk>|<pad>|<s>|</s>|\\[PAD\\]|<\\|endoftext\\|>|\\[UNK\\]|\\[CLS\\]|\\[MASK\\]|<\\|startofpiece\\|>|<\\|endofpiece\\|>|\\[gMASK\\]|\\[sMASK\\]\"\n )\n text = pattern.sub(\"\", text.strip()).strip()\n return text" }, { "identifier": "Stream", "path": "serve/model_utils.py", "snippet": "class Stream(transformers.StoppingCriteria):\n def __init__(self, callback_func=None):\n self.callback_func = callback_func\n\n def __call__(self, input_ids, scores) -> bool:\n if self.callback_func is not None:\n self.callback_func(input_ids[0])\n return False" }, { "identifier": "Iteratorize", "path": "serve/model_utils.py", "snippet": "class Iteratorize:\n\n \"\"\"\n Transforms a function that takes a callback\n into a lazy iterator (generator).\n \"\"\"\n\n def __init__(self, func, kwargs={}, callback=None):\n self.mfunc = func\n self.c_callback = callback\n self.q = Queue()\n self.sentinel = object()\n self.kwargs = kwargs\n self.stop_now = False\n\n def _callback(val):\n if self.stop_now:\n raise ValueError\n self.q.put(val)\n\n def gentask():\n try:\n ret = self.mfunc(callback=_callback, **self.kwargs)\n except ValueError:\n pass\n except:\n traceback.print_exc()\n pass\n\n self.q.put(self.sentinel)\n if self.c_callback:\n self.c_callback(ret)\n\n self.thread = Thread(target=gentask)\n self.thread.start()\n\n def __iter__(self):\n return self\n\n def __next__(self):\n obj = self.q.get(True, None)\n if obj is self.sentinel:\n raise StopIteration\n else:\n return obj\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.stop_now = True" }, { "identifier": "MplugOwlProcessor", "path": "mplug_owl/processing_mplug_owl.py", "snippet": "class MplugOwlProcessor(ProcessorMixin):\n attributes = []\n tokenizer_class = (\"MplugOwlTokenizer\")\n\n def __init__(self, image_processor=None, tokenizer=None, **kwargs):\n super().__init__(**kwargs)\n self.tokens_to_generate = 0\n self.image_processor = image_processor\n self.tokenizer = tokenizer\n self.add_BOS = True\n\n def __call__(self, text=None, images=None, return_tensors=None, **kwargs):\n args = get_args()\n if text is None and images is None:\n raise ValueError(\"You have to specify either text or images. Both cannot be none.\")\n\n if images is not None:\n if not isinstance(images, list):\n images = [images]\n # image_features, = self.image_processor(images, return_tensors=return_tensors, **kwargs)\n process_results = [self.image_processor(image=image, text=None) for image in images]\n if len(process_results)>0 and len(process_results[0][0].shape) == 4:\n # 图片被切分成了多块 默认是doc场景\n text_list = text.split('<image>')\n images = []\n patch_positions = []\n text = text_list[0]\n for ri, (image_input, text_input, patch_position) in enumerate(process_results):\n images.append(image_input)\n patch_positions.append(patch_position)\n if args.patch_pos_embed_type == 'pre':\n # 对于pre处理 v2t最终输出的是一张图的token\n text += '<image>'\n else:\n # 对于post处理 v2t最终输出的是多图\n text += '<image>'*image_input.shape[0]\n text += text_list[ri+1]\n images = torch.cat(images, dim=0)\n patch_positions = torch.cat(patch_positions, dim=0)\n else:\n # 如果没有切片 则正常stack 并创建patch position = num_image (0,0)的patch id以保持一致\n images = [_[0] for _ in process_results]\n images = torch.stack(images, dim=0)\n patch_positions = torch.zeros(images.shape[0],2).long()\n text = text\n if text is not None:\n encoding = tokenize_prompts(\n prompts=[text],\n tokens_to_generate=self.tokens_to_generate,\n add_BOS=self.add_BOS,\n tokenizer=self.tokenizer,\n ignore_dist=True,\n **kwargs,\n )\n # encoding = self.tokenizer(text, return_tensors=return_tensors, **kwargs)\n\n \n if text is not None and images is not None:\n encoding[\"pixel_values\"] = images\n encoding[\"patch_positions\"] = patch_position\n return BatchEncoding(data=encoding)\n elif text is not None:\n return BatchEncoding(data=encoding)\n else:\n return BatchEncoding(data=dict(pixel_values=images, patch_position=patch_position), tensor_type=return_tensors)\n\n def batch_decode(self, skip_special_tokens=True, *args, **kwargs):\n \"\"\"\n This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please\n refer to the docstring of this method for more information.\n \"\"\"\n return self.tokenizer.batch_decode(*args, skip_special_tokens=skip_special_tokens, **kwargs)\n\n def decode(self, skip_special_tokens=True, *args, **kwargs):\n \"\"\"\n This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to\n the docstring of this method for more information.\n \"\"\"\n return self.tokenizer.decode(*args, skip_special_tokens=skip_special_tokens, **kwargs)" }, { "identifier": "MplugOwlForConditionalGeneration", "path": "mplug_owl/modeling_mplug_owl.py", "snippet": "class MplugOwlForConditionalGeneration(MplugOwlPreTrainedModel):\n config_class = MplugOwlConfig\n main_input_name = \"pixel_values\"\n\n def __init__(self, config: MplugOwlConfig):\n super().__init__(config)\n\n self.vision_model = MplugOwlVisionModel(config.vision_config)\n\n self.query_tokens = nn.Parameter(\n torch.zeros(1, config.num_query_tokens, config.visual_abstractor_config.hidden_size)\n )\n self.num_queries = config.num_query_tokens\n self.abstractor = MplugOwlVisualAbstractorModel(\n config.visual_abstractor_config, config.text_config.hidden_size\n )\n language_model = AutoModelForCausalLM.from_config(config.text_config)\n self.language_model = language_model\n\n # Initialize weights and apply final processing\n self.post_init()\n self.main_input_name = \"input_ids\"\n from transformers import GenerationConfig\n\n self.generation_config = GenerationConfig(\n max_length=512, do_sample=True, top_k=3, pad_token_id=0, unk_token_id=0, bos_token_id=1, eos_token_id=2\n )\n\n def get_input_embeddings(self):\n return self.language_model.get_input_embeddings()\n\n def set_input_embeddings(self, value):\n self.language_model.set_input_embeddings(value)\n\n def set_output_embeddings(self, new_embeddings):\n self.language_model.set_output_embeddings(new_embeddings)\n\n def get_output_embeddings(self) -> nn.Module:\n return self.language_model.get_output_embeddings()\n\n def get_encoder(self):\n return self.language_model.get_encoder()\n\n def get_decoder(self):\n return self.language_model.get_decoder()\n\n def _tie_weights(self):\n if not self.config.use_decoder_only_language_model:\n self.language_model.encoder.embed_tokens = self.language_model.shared\n self.language_model.decoder.embed_tokens = self.language_model.shared\n\n def _preprocess_accelerate(self):\n r\"\"\"\n Some pre-processing hacks to make the model `accelerate` compatible. Check\n https://github.com/huggingface/transformers/pull/21707 for more details.\n \"\"\"\n hf_device_map = self.hf_device_map\n\n if len(hf_device_map) > 1 and \"language_model\" not in hf_device_map and torch.cuda.device_count() > 1:\n # warn users about unexpected behavior when using multi-GPU + mPLUG-Owl + `accelerate`.\n logger.warning(\n \"The `language_model` is not in the `hf_device_map` dictionary and you are running your script\"\n \" in a multi-GPU environment. this may lead to unexpected behavior when using `accelerate`.\"\n \" Please pass a `device_map` that contains `language_model` to remove this warning.\"\n \" Please refer to https://github.com/huggingface/blog/blob/main/accelerate-large-models.md for\"\n \" more details on creating a `device_map` for large models.\",\n )\n\n if hasattr(self.language_model, \"_hf_hook\"):\n self.language_model._hf_hook.io_same_device = True # For `generate` compatibility\n\n @add_start_docstrings_to_model_forward(MPLUG_OWL_INPUTS_DOCSTRING)\n @replace_return_docstrings(\n output_type=MplugOwlForConditionalGenerationModelOutput, config_class=MplugOwlVisionConfig\n )\n def forward(\n self,\n pixel_values: torch.FloatTensor,\n input_ids: torch.FloatTensor,\n num_images,\n non_padding_mask: Optional[torch.LongTensor] = None,\n non_media_mask: Optional[torch.LongTensor] = None,\n prompt_mask: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n labels: Optional[torch.LongTensor] = None,\n patch_positions=None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, MplugOwlForConditionalGenerationModelOutput]:\n r\"\"\"\n Returns:\n\n SFT example:\n\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> from transformers import MplugOwlProcessor, MplugOwlForConditionalGeneration\n >>> import torch\n\n >>> device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n >>> processor = MplugOwlProcessor.from_pretrained(\"MAGAer13/mplug-owl-llama-7b\")\n >>> model = MplugOwlForConditionalGeneration.from_pretrained(\n ... \"MAGAer13/mplug-owl-llama-7b\", torch_dtype=torch.float16\n ... )\n >>> model.to(device) # doctest: +IGNORE_RESULT\n\n >>> url = \"http://images.cocodataset.org/val2017/000000039769.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> prompt = [\n ... \"The following is a conversation between a curious human and AI assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.\\nHuman: <image>\\nHuman: how many cats are there?\\nAI: \"\n ... ]\n >>> inputs = processor(images=[image], text=prompt, return_tensors=\"pt\").to(device, torch.float16)\n\n >>> generated_ids = model.generate(**inputs)\n >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()\n >>> print(generated_text)\n There are two cats in the image.\n ```\"\"\"\n if pixel_values is not None:\n pixel_values = pixel_values.to(self.vision_model.embeddings.cls_token.data.dtype)\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # get text embedding\n text_tokens_ = input_ids.clone()\n batch_size = input_ids.shape[0]\n # labels = text_tokens_[:, 1:].clone().contiguous()\n\n media_token_indices = [\n # [:-1] since we would not use the last token for embedding\n get_media_indices(text_tokens_[i][:-1], self.num_queries)\n for i in range(batch_size)\n ]\n text_tokens_[text_tokens_ < 0] = 1 # Not used\n # text_tokens = text_tokens_[:, :-1].contiguous()\n text_embeds = self.get_input_embeddings()(text_tokens_) # Temporally Embedding\n\n if pixel_values is not None:\n image_embeds = self.vision_model(pixel_values, patch_positions=patch_positions, return_dict=True).last_hidden_state\n\n image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)\n query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)\n\n query_features = self.abstractor(\n query_embeds=query_tokens,\n encoder_hidden_states=image_embeds,\n encoder_attention_mask=image_attention_mask,\n patch_positions=patch_positions,\n )[\"last_hidden_state\"]\n torch.ones(query_features.size()[:-1], dtype=torch.long).to(query_features.device)\n img_seq_length = query_features.shape[1]\n\n num_images_per_sample = num_images.long().cpu().tolist()\n\n text_chunk_embeds = []\n img_idx = 0\n for b in range(batch_size):\n start = 0\n result = []\n if len(media_token_indices[b]) > 0:\n for i, pos in enumerate(media_token_indices[b][0]):\n if pos > start:\n result.append(text_embeds[b, start:pos])\n result.append(query_features[img_idx + i])\n start = pos + img_seq_length\n if start < text_embeds.shape[1]:\n result.append(text_embeds[b, start:])\n\n img_idx += media_token_indices[b][1]\n text_chunk_embeds.append(torch.cat(result, dim=0))\n\n # Actual Input Embeddings\n input_embeds = torch.stack(text_chunk_embeds, dim=0)\n\n # Create causal mask and position ids\n _, loss_mask, position_ids = get_ltor_masks_and_position_ids_from_embeddings(input_embeds)\n\n # Calculate the loss_mask\n non_padding_mask = non_padding_mask.long()\n non_media_mask = non_media_mask.long()\n prompt_mask = prompt_mask.long() # TODO How to deal with prompt mask\n # from icecream import ic\n # non_padding_mask = non_padding_mask[:,:-1]\n # non_media_mask = non_media_mask[:,:-1]\n # prompt_mask = prompt_mask[:,:-1]\n # attention_mask = attention_mask[:,:-1]\n loss_mask = loss_mask[:, :-1]\n\n loss_mask = loss_mask * non_padding_mask * non_media_mask * prompt_mask\n labels[:, 1:][loss_mask != 1] = -100\n # Forward into GPT\n outputs = self.language_model(\n inputs_embeds=input_embeds,\n attention_mask=attention_mask,\n labels=labels,\n return_dict=return_dict,\n output_attentions=self.config.output_attentions,\n )\n outputs.loss = (outputs.loss * loss_mask.view(-1)\n ).sum()/loss_mask.sum()\n return outputs\n\n @torch.no_grad()\n def generate(\n self,\n pixel_values: torch.FloatTensor = None,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n patch_positions=None,\n isdecoder=True,\n **generate_kwargs,\n ) -> torch.LongTensor:\n \"\"\"\n Overrides `generate` function to be able to use the model as a conditional generator.\n\n Args:\n pixel_values (`torch.FloatTensor` of shape (batch_size, num_channels, height, width)):\n Input images to be processed.\n input_ids (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):\n The sequence used as a prompt for the generation.\n attention_mask (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):\n Mask to avoid performing attention on padding token indices\n\n Returns:\n captions (list): A list of strings of length batch_size * num_captions.\n \"\"\"\n if pixel_values is not None:\n pixel_values = pixel_values.to(self.vision_model.embeddings.cls_token.data.dtype)\n if input_ids is None:\n return self.language_model.generate(attention_mask=attention_mask, **generate_kwargs)\n\n if attention_mask is None:\n attention_mask = input_ids.new_ones(*input_ids.shape)\n\n batch_size = input_ids.size(0)\n media_token_indices = [get_media_indices(input_ids[i], self.num_queries) for i in range(batch_size)]\n input_ids = input_ids.clone() # prevent inplace modify\n input_ids[input_ids < 0] = 0 # Not used\n\n if hasattr(self, \"hf_device_map\"):\n # preprocess for `accelerate`\n self._preprocess_accelerate()\n batch_size = input_ids.shape[0]\n # get text embedding\n inputs_embeds = self.get_input_embeddings()(input_ids)\n # get visual embedding\n if pixel_values is not None:\n pixel_values = pixel_values.to(input_ids.device)\n with torch.no_grad():\n image_embeds = self.vision_model(pixel_values, patch_positions=patch_positions, return_dict=True).last_hidden_state\n image_attention_mask = torch.ones(\n image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device\n )\n query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)\n query_outputs = self.abstractor(\n query_embeds=query_tokens,\n encoder_hidden_states=image_embeds,\n encoder_attention_mask=image_attention_mask,\n patch_positions=patch_positions,\n return_dict=True,\n )\n query_output = query_outputs[\"last_hidden_state\"]\n image_embeds = query_output\n img_seq_length = image_embeds.shape[1]\n\n # ===================\n # Get actual input embeddings\n # ===================\n text_chunk_embeds = []\n text_chunk_attns = []\n img_idx = 0\n\n for b in range(batch_size):\n start = 0\n result = []\n result_attn = []\n for i, pos in enumerate(media_token_indices[b][0]):\n if pos > start:\n result.append(inputs_embeds[b, start:pos])\n result_attn.append(attention_mask[b, start:pos])\n result.append(image_embeds[img_idx + i])\n result_attn.append(torch.ones(image_embeds[img_idx + i].shape[0], device=inputs_embeds.device))\n start = pos + img_seq_length\n if start < inputs_embeds.shape[1]:\n result.append(inputs_embeds[b, start:])\n result_attn.append(attention_mask[b, start:])\n\n img_idx += media_token_indices[b][1]\n text_chunk_embeds.append(torch.cat(result, dim=0))\n text_chunk_attns.append(torch.cat(result_attn, dim=0))\n inputs_embeds = torch.stack(text_chunk_embeds, dim=0)\n attention_mask = torch.stack(text_chunk_attns, dim=0)\n\n outputs = self.language_model.generate(\n inputs_embeds=inputs_embeds,\n # input_ids=input_ids,\n attention_mask=attention_mask,\n **generate_kwargs,\n )\n\n return outputs\n\n def prepare_inputs_for_generation(\n self, input_ids, pixel_values=None, past_key_values=None, attention_mask=None, **model_kwargs\n ):\n input_shape = input_ids.shape\n # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly\n if attention_mask is None:\n attention_mask = input_ids.new_ones(input_shape)\n\n # # cut decoder_input_ids if past_key_values is used\n # if past_key_values is not None:\n # input_ids = input_ids[:, -1:]\n\n return {\n \"input_ids\": input_ids,\n \"pixel_values\": pixel_values,\n \"attention_mask\": attention_mask,\n \"is_decoder\": True,\n }" }, { "identifier": "build_processors", "path": "pipeline/data_utils/processors/builder.py", "snippet": "def build_processors(processors_cfg):\n processors = dict()\n for task, processor in processors_cfg.items():\n processors[task] = build_from_cfg(processor, PROCESSORS)\n ic(type(processors[task]))\n return processors" } ]
from PIL import Image from io import BytesIO from .io_utils import IO, DefaultIO, OSS from mplug_owl.processing_mplug_owl import MplugOwlProcessor, MplugOwlImageProcessor from mplug_owl.modeling_mplug_owl import MplugOwlForConditionalGeneration from mplug_owl.configuration_mplug_owl import MplugOwlConfig from mplug_owl.tokenization_mplug_owl import MplugOwlTokenizer from transformers import GenerationConfig from .model_utils import post_process_output, Stream, Iteratorize from pathlib import Path from mplug_owl.processing_mplug_owl import MplugOwlProcessor from mplug_owl.modeling_mplug_owl import MplugOwlForConditionalGeneration from pipeline.data_utils.processors.builder import build_processors from pipeline.data_utils.processors import * from transformers.models.llama.tokenization_llama import LlamaTokenizer from icecream import ic import torch import gradio as gr import logging import sys import os import json import requests import datetime import uuid import base64 import time import sys import transformers
15,224
# text_list = prompts[0].split('<image>') # text = text_list[0] # for ri, image in enumerate(images): # if args.patch_pos_embed_type == 'pre': # # 对于pre处理 v2t最终输出的是一张图的token # text += '<image>' # else: # # 对于post处理 v2t最终输出的是多图 # text += '<image>'*image.shape[0] # text += text_list[ri+1] # images = torch.cat(images, dim=0) # patch_position = torch.cat(patch_position, dim=0) # print(text) # ic(images.shape) # ic(patch_position.shape) # from mplug_owl.processing_mplug_owl import tokenize_prompts # input_ids = tokenize_prompts(text, tokenizer=self.tokenizer, return_tensors='pt') # return { # "pixel_values": images, # 'patch_position': patch_position, # "input_ids": input_ids # } class mPLUG_Owl_Server: def __init__( self, base_model='MAGAer13/mplug-owl-llama-7b', log_dir='./', load_in_8bit=False, bf16=True, device="cuda", io=None, config=None, ): self.log_dir = log_dir self.config = config self.image_processor = build_processors(config['valid_processors'])['sft'] self.tokenizer = LlamaTokenizer.from_pretrained(base_model) self.processor = MplugOwlProcessor(self.image_processor, self.tokenizer) self.model = MplugOwlForConditionalGeneration.from_pretrained( base_model, torch_dtype=torch.float, ) ckpt = {} for cf in Path(base_model).iterdir(): if 'pytorch_model' in cf.name and cf.name.endswith('.bin'): ckpt.update(torch.load(cf, map_location='cpu')) msg = self.model.load_state_dict(ckpt, strict=False) print(msg) del ckpt self.bf16 = bf16 self.load_in_8bit = load_in_8bit if not load_in_8bit: if bf16: self.model.bfloat16() else: self.model.half() self.model.cuda() self.model.eval() self.io = io def evaluate( self, pixel_values=None, patch_positions=None, input_ids=None, temperature=1.0, top_p=0.9, top_k=5, num_beams=3, max_new_tokens=256, stream_output=True, length_penalty=1.0, no_repeat_ngram_size=2, do_sample=False, early_stopping=True, **kwargs ): generation_config = dict( temperature=temperature, top_p=top_p, top_k=top_k, num_beams=num_beams, no_repeat_ngram_size=no_repeat_ngram_size, do_sample=do_sample, early_stopping=early_stopping, length_penalty=length_penalty, ) generate_params = { "pixel_values": pixel_values, "patch_positions": patch_positions, "input_ids": input_ids, "return_dict_in_generate": True, "output_scores": True, "max_new_tokens": max_new_tokens, } generate_params.update(generation_config) if stream_output: # Stream the reply 1 token at a time. # This is based on the trick of using 'stopping_criteria' to create an iterator, # from https://github.com/oobabooga/text-generation-webui/blob/ad37f396fc8bcbab90e11ecf17c56c97bfbd4a9c/modules/text_generation.py#L216-L243. def generate_with_callback(callback=None, **kwargs): kwargs.setdefault( "stopping_criteria", transformers.StoppingCriteriaList() ) kwargs["stopping_criteria"].append(Stream(callback_func=callback)) with torch.no_grad(): self.model.generate(**kwargs) def generate_with_streaming(**kwargs):
sys.path.append("..") server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**" # from pipeline.data_utils.xgpt3_dataset import ImageIO # class ImageProcessor(object): # def __init__(self, resolution=224, tokenizer=None): # normalize = transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)) # # self.transform = transforms.Compose([ # # transforms.Resize((resolution, resolution),interpolation=Image.BICUBIC), # # transforms.ToTensor(), # # normalize, # # ]) # from megatron.data.processors import doc_processor # processor_class = os.environ.get('DocProcessor','DocSFTProcessor') # self.transform = getattr(doc_processor,processor_class)() # self.image_io = ImageIO() # self.tokenizer=tokenizer # def __call__(self, image_paths, prompts): # if isinstance(image_paths, str): # image_paths = [image_paths] # images = [] # images = self.image_io._load_img(image_paths) # images = [self.transform(image, None) for image in images] # image_input, text_input, patch_position # patch_position = [_[2] for _ in images] # images = [_[0] for _ in images] # text_list = prompts[0].split('<image>') # text = text_list[0] # for ri, image in enumerate(images): # if args.patch_pos_embed_type == 'pre': # # 对于pre处理 v2t最终输出的是一张图的token # text += '<image>' # else: # # 对于post处理 v2t最终输出的是多图 # text += '<image>'*image.shape[0] # text += text_list[ri+1] # images = torch.cat(images, dim=0) # patch_position = torch.cat(patch_position, dim=0) # print(text) # ic(images.shape) # ic(patch_position.shape) # from mplug_owl.processing_mplug_owl import tokenize_prompts # input_ids = tokenize_prompts(text, tokenizer=self.tokenizer, return_tensors='pt') # return { # "pixel_values": images, # 'patch_position': patch_position, # "input_ids": input_ids # } class mPLUG_Owl_Server: def __init__( self, base_model='MAGAer13/mplug-owl-llama-7b', log_dir='./', load_in_8bit=False, bf16=True, device="cuda", io=None, config=None, ): self.log_dir = log_dir self.config = config self.image_processor = build_processors(config['valid_processors'])['sft'] self.tokenizer = LlamaTokenizer.from_pretrained(base_model) self.processor = MplugOwlProcessor(self.image_processor, self.tokenizer) self.model = MplugOwlForConditionalGeneration.from_pretrained( base_model, torch_dtype=torch.float, ) ckpt = {} for cf in Path(base_model).iterdir(): if 'pytorch_model' in cf.name and cf.name.endswith('.bin'): ckpt.update(torch.load(cf, map_location='cpu')) msg = self.model.load_state_dict(ckpt, strict=False) print(msg) del ckpt self.bf16 = bf16 self.load_in_8bit = load_in_8bit if not load_in_8bit: if bf16: self.model.bfloat16() else: self.model.half() self.model.cuda() self.model.eval() self.io = io def evaluate( self, pixel_values=None, patch_positions=None, input_ids=None, temperature=1.0, top_p=0.9, top_k=5, num_beams=3, max_new_tokens=256, stream_output=True, length_penalty=1.0, no_repeat_ngram_size=2, do_sample=False, early_stopping=True, **kwargs ): generation_config = dict( temperature=temperature, top_p=top_p, top_k=top_k, num_beams=num_beams, no_repeat_ngram_size=no_repeat_ngram_size, do_sample=do_sample, early_stopping=early_stopping, length_penalty=length_penalty, ) generate_params = { "pixel_values": pixel_values, "patch_positions": patch_positions, "input_ids": input_ids, "return_dict_in_generate": True, "output_scores": True, "max_new_tokens": max_new_tokens, } generate_params.update(generation_config) if stream_output: # Stream the reply 1 token at a time. # This is based on the trick of using 'stopping_criteria' to create an iterator, # from https://github.com/oobabooga/text-generation-webui/blob/ad37f396fc8bcbab90e11ecf17c56c97bfbd4a9c/modules/text_generation.py#L216-L243. def generate_with_callback(callback=None, **kwargs): kwargs.setdefault( "stopping_criteria", transformers.StoppingCriteriaList() ) kwargs["stopping_criteria"].append(Stream(callback_func=callback)) with torch.no_grad(): self.model.generate(**kwargs) def generate_with_streaming(**kwargs):
return Iteratorize(generate_with_callback, kwargs, callback=None)
10
2023-10-08 06:29:02+00:00
24k
sakemin/cog-musicgen-remixer
predict.py
[ { "identifier": "MultiBandDiffusion", "path": "audiocraft/models/multibanddiffusion.py", "snippet": "class MultiBandDiffusion:\n \"\"\"Sample from multiple diffusion models.\n\n Args:\n DPs (list of DiffusionProcess): Diffusion processes.\n codec_model (CompressionModel): Underlying compression model used to obtain discrete tokens.\n \"\"\"\n def __init__(self, DPs: tp.List[DiffusionProcess], codec_model: CompressionModel) -> None:\n self.DPs = DPs\n self.codec_model = codec_model\n self.device = next(self.codec_model.parameters()).device\n\n @property\n def sample_rate(self) -> int:\n return self.codec_model.sample_rate\n\n @staticmethod\n def get_mbd_musicgen(device=None):\n \"\"\"Load our diffusion models trained for MusicGen.\"\"\"\n if device is None:\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n path = 'facebook/multiband-diffusion'\n filename = 'mbd_musicgen_32khz.th'\n name = 'facebook/musicgen-small'\n codec_model = load_compression_model(name, device=device)\n models, processors, cfgs = load_diffusion_models(path, filename=filename, device=device)\n DPs = []\n for i in range(len(models)):\n schedule = NoiseSchedule(**cfgs[i].schedule, sample_processor=processors[i], device=device)\n DPs.append(DiffusionProcess(model=models[i], noise_schedule=schedule))\n return MultiBandDiffusion(DPs=DPs, codec_model=codec_model)\n\n @staticmethod\n def get_mbd_24khz(bw: float = 3.0, pretrained: bool = True,\n device: tp.Optional[tp.Union[torch.device, str]] = None,\n n_q: tp.Optional[int] = None):\n \"\"\"Get the pretrained Models for MultibandDiffusion.\n\n Args:\n bw (float): Bandwidth of the compression model.\n pretrained (bool): Whether to use / download if necessary the models.\n device (torch.device or str, optional): Device on which the models are loaded.\n n_q (int, optional): Number of quantizers to use within the compression model.\n \"\"\"\n if device is None:\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n assert bw in [1.5, 3.0, 6.0], f\"bandwidth {bw} not available\"\n if n_q is not None:\n assert n_q in [2, 4, 8]\n assert {1.5: 2, 3.0: 4, 6.0: 8}[bw] == n_q, \\\n f\"bandwidth and number of codebooks missmatch to use n_q = {n_q} bw should be {n_q * (1.5 / 2)}\"\n n_q = {1.5: 2, 3.0: 4, 6.0: 8}[bw]\n codec_model = CompressionSolver.model_from_checkpoint(\n '//pretrained/facebook/encodec_24khz', device=device)\n codec_model.set_num_codebooks(n_q)\n codec_model = codec_model.to(device)\n path = 'facebook/multiband-diffusion'\n filename = f'mbd_comp_{n_q}.pt'\n models, processors, cfgs = load_diffusion_models(path, filename=filename, device=device)\n DPs = []\n for i in range(len(models)):\n schedule = NoiseSchedule(**cfgs[i].schedule, sample_processor=processors[i], device=device)\n DPs.append(DiffusionProcess(model=models[i], noise_schedule=schedule))\n return MultiBandDiffusion(DPs=DPs, codec_model=codec_model)\n\n return MultiBandDiffusion(DPs, codec_model)\n\n @torch.no_grad()\n def get_condition(self, wav: torch.Tensor, sample_rate: int) -> torch.Tensor:\n \"\"\"Get the conditioning (i.e. latent reprentatios of the compression model) from a waveform.\n Args:\n wav (torch.Tensor): The audio that we want to extract the conditioning from\n sample_rate (int): sample rate of the audio\"\"\"\n if sample_rate != self.sample_rate:\n wav = julius.resample_frac(wav, sample_rate, self.sample_rate)\n codes, scale = self.codec_model.encode(wav)\n assert scale is None, \"Scaled compression models not supported.\"\n emb = self.get_emb(codes)\n return emb\n\n @torch.no_grad()\n def get_emb(self, codes: torch.Tensor):\n \"\"\"Get latent representation from the discrete codes\n Argrs:\n codes (torch.Tensor): discrete tokens\"\"\"\n emb = self.codec_model.decode_latent(codes)\n return emb\n\n def generate(self, emb: torch.Tensor, size: tp.Optional[torch.Size] = None,\n step_list: tp.Optional[tp.List[int]] = None):\n \"\"\"Generate Wavform audio from the latent embeddings of the compression model\n Args:\n emb (torch.Tensor): Conditioning embeddinds\n size (none torch.Size): size of the output\n if None this is computed from the typical upsampling of the model\n step_list (optional list[int]): list of Markov chain steps, defaults to 50 linearly spaced step.\n \"\"\"\n if size is None:\n upsampling = int(self.codec_model.sample_rate / self.codec_model.frame_rate)\n size = torch.Size([emb.size(0), self.codec_model.channels, emb.size(-1) * upsampling])\n assert size[0] == emb.size(0)\n out = torch.zeros(size).to(self.device)\n for DP in self.DPs:\n out += DP.generate(condition=emb, step_list=step_list, initial_noise=torch.randn_like(out))\n return out\n\n def re_eq(self, wav: torch.Tensor, ref: torch.Tensor, n_bands: int = 32, strictness: float = 1):\n \"\"\"match the eq to the encodec output by matching the standard deviation of some frequency bands\n Args:\n wav (torch.Tensor): audio to equalize\n ref (torch.Tensor):refenrence audio from which we match the spectrogram.\n n_bands (int): number of bands of the eq\n strictness (float): how strict the the matching. 0 is no matching, 1 is exact matching.\n \"\"\"\n split = julius.SplitBands(n_bands=n_bands, sample_rate=self.codec_model.sample_rate).to(wav.device)\n bands = split(wav)\n bands_ref = split(ref)\n out = torch.zeros_like(ref)\n for i in range(n_bands):\n out += bands[i] * (bands_ref[i].std() / bands[i].std()) ** strictness\n return out\n\n def regenerate(self, wav: torch.Tensor, sample_rate: int):\n \"\"\"Regenerate a wavform through compression and diffusion regeneration.\n Args:\n wav (torch.Tensor): Original 'ground truth' audio\n sample_rate (int): sample rate of the input (and output) wav\n \"\"\"\n if sample_rate != self.codec_model.sample_rate:\n wav = julius.resample_frac(wav, sample_rate, self.codec_model.sample_rate)\n emb = self.get_condition(wav, sample_rate=self.codec_model.sample_rate)\n size = wav.size()\n out = self.generate(emb, size=size)\n if sample_rate != self.codec_model.sample_rate:\n out = julius.resample_frac(out, self.codec_model.sample_rate, sample_rate)\n return out\n\n def tokens_to_wav(self, tokens: torch.Tensor, n_bands: int = 32):\n \"\"\"Generate Waveform audio with diffusion from the discrete codes.\n Args:\n tokens (torch.Tensor): discrete codes\n n_bands (int): bands for the eq matching.\n \"\"\"\n wav_encodec = self.codec_model.decode(tokens)\n condition = self.get_emb(tokens)\n wav_diffusion = self.generate(emb=condition, size=wav_encodec.size())\n return self.re_eq(wav=wav_diffusion, ref=wav_encodec, n_bands=n_bands)" }, { "identifier": "MusicGen", "path": "audiocraft/models/musicgen.py", "snippet": "class MusicGen:\n \"\"\"MusicGen main model with convenient generation API.\n\n Args:\n name (str): name of the model.\n compression_model (CompressionModel): Compression model\n used to map audio to invertible discrete representations.\n lm (LMModel): Language model over discrete representations.\n max_duration (float, optional): maximum duration the model can produce,\n otherwise, inferred from the training params.\n \"\"\"\n def __init__(self, name: str, compression_model: CompressionModel, lm: LMModel,\n max_duration: tp.Optional[float] = None):\n self.name = name\n self.compression_model = compression_model\n self.lm = lm\n self.cfg: tp.Optional[omegaconf.DictConfig] = None\n # Just to be safe, let's put everything in eval mode.\n self.compression_model.eval()\n self.lm.eval()\n\n if hasattr(lm, 'cfg'):\n cfg = lm.cfg\n assert isinstance(cfg, omegaconf.DictConfig)\n self.cfg = cfg\n\n if self.cfg is not None:\n self.compression_model = get_wrapped_compression_model(self.compression_model, self.cfg)\n\n if max_duration is None:\n if self.cfg is not None:\n max_duration = lm.cfg.dataset.segment_duration # type: ignore\n else:\n raise ValueError(\"You must provide max_duration when building directly MusicGen\")\n assert max_duration is not None\n self.max_duration: float = max_duration\n self.device = next(iter(lm.parameters())).device\n\n self.generation_params: dict = {}\n self.set_generation_params(duration=15) # 15 seconds by default\n self._progress_callback: tp.Optional[tp.Callable[[int, int], None]] = None\n if self.device.type == 'cpu':\n self.autocast = TorchAutocast(enabled=False)\n else:\n self.autocast = TorchAutocast(\n enabled=True, device_type=self.device.type, dtype=torch.float16)\n\n @property\n def frame_rate(self) -> float:\n \"\"\"Roughly the number of AR steps per seconds.\"\"\"\n return self.compression_model.frame_rate\n\n @property\n def sample_rate(self) -> int:\n \"\"\"Sample rate of the generated audio.\"\"\"\n return self.compression_model.sample_rate\n\n @property\n def audio_channels(self) -> int:\n \"\"\"Audio channels of the generated audio.\"\"\"\n return self.compression_model.channels\n\n @staticmethod\n def get_pretrained(name: str = 'facebook/musicgen-melody', device=None):\n \"\"\"Return pretrained model, we provide four models:\n - facebook/musicgen-small (300M), text to music,\n # see: https://huggingface.co/facebook/musicgen-small\n - facebook/musicgen-medium (1.5B), text to music,\n # see: https://huggingface.co/facebook/musicgen-medium\n - facebook/musicgen-melody (1.5B) text to music and text+melody to music,\n # see: https://huggingface.co/facebook/musicgen-melody\n - facebook/musicgen-large (3.3B), text to music,\n # see: https://huggingface.co/facebook/musicgen-large\n \"\"\"\n if device is None:\n if torch.cuda.device_count():\n device = 'cuda'\n else:\n device = 'cpu'\n\n if name == 'debug':\n # used only for unit tests\n compression_model = get_debug_compression_model(device)\n lm = get_debug_lm_model(device)\n return MusicGen(name, compression_model, lm, max_duration=30)\n\n if name in _HF_MODEL_CHECKPOINTS_MAP:\n warnings.warn(\n \"MusicGen pretrained model relying on deprecated checkpoint mapping. \" +\n f\"Please use full pre-trained id instead: facebook/musicgen-{name}\")\n name = _HF_MODEL_CHECKPOINTS_MAP[name]\n\n lm = load_lm_model(name, device=device)\n compression_model = load_compression_model(name, device=device)\n if 'self_wav' in lm.condition_provider.conditioners:\n lm.condition_provider.conditioners['self_wav'].match_len_on_eval = True\n lm.condition_provider.conditioners['self_wav']._use_masking = False\n\n return MusicGen(name, compression_model, lm)\n\n def set_generation_params(self, use_sampling: bool = True, top_k: int = 250,\n top_p: float = 0.0, temperature: float = 1.0,\n duration: float = 30.0, cfg_coef: float = 3.0,\n two_step_cfg: bool = False, extend_stride: float = 18):\n \"\"\"Set the generation parameters for MusicGen.\n\n Args:\n use_sampling (bool, optional): Use sampling if True, else do argmax decoding. Defaults to True.\n top_k (int, optional): top_k used for sampling. Defaults to 250.\n top_p (float, optional): top_p used for sampling, when set to 0 top_k is used. Defaults to 0.0.\n temperature (float, optional): Softmax temperature parameter. Defaults to 1.0.\n duration (float, optional): Duration of the generated waveform. Defaults to 30.0.\n cfg_coef (float, optional): Coefficient used for classifier free guidance. Defaults to 3.0.\n two_step_cfg (bool, optional): If True, performs 2 forward for Classifier Free Guidance,\n instead of batching together the two. This has some impact on how things\n are padded but seems to have little impact in practice.\n extend_stride: when doing extended generation (i.e. more than 30 seconds), by how much\n should we extend the audio each time. Larger values will mean less context is\n preserved, and shorter value will require extra computations.\n \"\"\"\n assert extend_stride < self.max_duration, \"Cannot stride by more than max generation duration.\"\n self.extend_stride = extend_stride\n self.duration = duration\n self.generation_params = {\n 'use_sampling': use_sampling,\n 'temp': temperature,\n 'top_k': top_k,\n 'top_p': top_p,\n 'cfg_coef': cfg_coef,\n 'two_step_cfg': two_step_cfg,\n }\n\n def set_custom_progress_callback(self, progress_callback: tp.Optional[tp.Callable[[int, int], None]] = None):\n \"\"\"Override the default progress callback.\"\"\"\n self._progress_callback = progress_callback\n\n def generate_unconditional(self, num_samples: int, progress: bool = False,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples in an unconditional manner.\n\n Args:\n num_samples (int): Number of samples to be generated.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n descriptions: tp.List[tp.Optional[str]] = [None] * num_samples\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions, None)\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate(self, descriptions: tp.List[str], progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions, None)\n assert prompt_tokens is None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_with_chroma(self, descriptions: tp.List[str], melody_wavs: MelodyType,\n melody_sample_rate: int, progress: bool = False,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text and melody.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n melody_wavs: (torch.Tensor or list of Tensor): A batch of waveforms used as\n melody conditioning. Should have shape [B, C, T] with B matching the description length,\n C=1 or 2. It can be [C, T] if there is a single description. It can also be\n a list of [C, T] tensors.\n melody_sample_rate: (int): Sample rate of the melody waveforms.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if isinstance(melody_wavs, torch.Tensor):\n if melody_wavs.dim() == 2:\n melody_wavs = melody_wavs[None]\n if melody_wavs.dim() != 3:\n raise ValueError(\"Melody wavs should have a shape [B, C, T].\")\n melody_wavs = list(melody_wavs)\n else:\n for melody in melody_wavs:\n if melody is not None:\n assert melody.dim() == 2, \"One melody in the list has the wrong number of dims.\"\n\n melody_wavs = [\n convert_audio(wav, melody_sample_rate, self.sample_rate, self.audio_channels)\n if wav is not None else None\n for wav in melody_wavs]\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=None,\n melody_wavs=melody_wavs)\n assert prompt_tokens is None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation(self, prompt: torch.Tensor, prompt_sample_rate: int,\n descriptions: tp.Optional[tp.List[tp.Optional[str]]] = None,\n progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on audio prompts.\n\n Args:\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n Prompt should be [B, C, T], or [C, T] if only one sample is generated.\n prompt_sample_rate (int): Sampling rate of the given audio waveforms.\n descriptions (list of str, optional): A list of strings used as text conditioning. Defaults to None.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if prompt.dim() == 2:\n prompt = prompt[None]\n if prompt.dim() != 3:\n raise ValueError(\"prompt should have 3 dimensions: [B, C, T] (C = 1).\")\n prompt = convert_audio(prompt, prompt_sample_rate, self.sample_rate, self.audio_channels)\n if descriptions is None:\n descriptions = [None] * len(prompt)\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions, prompt)\n assert prompt_tokens is not None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n \n def generate_continuation_with_audio_token(self, prompt, \n descriptions: tp.Optional[tp.List[tp.Optional[str]]] = None,\n progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on audio prompts.\n\n Args:\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n Prompt should be [B, C, T], or [C, T] if only one sample is generated.\n prompt_sample_rate (int): Sampling rate of the given audio waveforms.\n descriptions (list of str, optional): A list of strings used as text conditioning. Defaults to None.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n \n if descriptions is None:\n descriptions = [None] * len(prompt)\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions, None)\n assert prompt_tokens is None\n prompt_tokens = prompt\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation_with_audio_chroma(self, prompt: torch.Tensor, prompt_sample_rate: int, melody_wavs: MelodyType,\n melody_sample_rate: int, descriptions: tp.Optional[tp.List[tp.Optional[str]]] = None,\n progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on audio prompts.\n\n Args:\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n Prompt should be [B, C, T], or [C, T] if only one sample is generated.\n prompt_sample_rate (int): Sampling rate of the given audio waveforms.\n descriptions (list of str, optional): A list of strings used as text conditioning. Defaults to None.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if prompt.dim() == 2:\n prompt = prompt[None]\n if prompt.dim() != 3:\n raise ValueError(\"prompt should have 3 dimensions: [B, C, T] (C = 1).\")\n prompt = convert_audio(prompt, prompt_sample_rate, self.sample_rate, self.audio_channels)\n\n if isinstance(melody_wavs, torch.Tensor):\n if melody_wavs.dim() == 2:\n melody_wavs = melody_wavs[None]\n if melody_wavs.dim() != 3:\n raise ValueError(\"Melody wavs should have a shape [B, C, T].\")\n melody_wavs = list(melody_wavs)\n else:\n for melody in melody_wavs:\n if melody is not None:\n assert melody.dim() == 2, \"One melody in the list has the wrong number of dims.\"\n\n melody_wavs = [\n convert_audio(wav, melody_sample_rate, self.sample_rate, self.audio_channels)\n if wav is not None else None\n for wav in melody_wavs]\n \n if descriptions is None:\n descriptions = [None] * len(prompt)\n \n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=prompt, melody_wavs=melody_wavs)\n assert prompt_tokens is not None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation_with_audio_tokens_and_audio_chroma(self, prompt, melody_wavs: MelodyType,\n melody_sample_rate: int, descriptions: tp.Optional[tp.List[tp.Optional[str]]] = None,\n progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on audio prompts.\n\n Args:\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n Prompt should be [B, C, T], or [C, T] if only one sample is generated.\n prompt_sample_rate (int): Sampling rate of the given audio waveforms.\n descriptions (list of str, optional): A list of strings used as text conditioning. Defaults to None.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if isinstance(melody_wavs, torch.Tensor):\n if melody_wavs.dim() == 2:\n melody_wavs = melody_wavs[None]\n if melody_wavs.dim() != 3:\n raise ValueError(\"Melody wavs should have a shape [B, C, T].\")\n melody_wavs = list(melody_wavs)\n else:\n for melody in melody_wavs:\n if melody is not None:\n assert melody.dim() == 2, \"One melody in the list has the wrong number of dims.\"\n\n melody_wavs = [\n convert_audio(wav, melody_sample_rate, self.sample_rate, self.audio_channels)\n if wav is not None else None\n for wav in melody_wavs]\n \n if descriptions is None:\n descriptions = [None] * len(prompt)\n \n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=None, melody_wavs=melody_wavs)\n assert prompt_tokens is None\n prompt_tokens = prompt\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation_with_text_chroma(self, prompt: torch.Tensor, prompt_sample_rate: int, descriptions: tp.List[str], chord_texts: tp.Union[tp.List[str],str],\n progress: bool = False, bpm: tp.Union[float,int,tp.List[float],tp.List[int]] = 120, meter: tp.Optional[tp.Union[int,tp.List[int]]] = 4,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text and melody.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n melody_wavs: (torch.Tensor or list of Tensor): A batch of waveforms used as\n melody conditioning. Should have shape [B, C, T] with B matching the description length,\n C=1 or 2. It can be [C, T] if there is a single description. It can also be\n a list of [C, T] tensors.\n melody_sample_rate: (int): Sample rate of the melody waveforms.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if prompt.dim() == 2:\n prompt = prompt[None]\n if prompt.dim() != 3:\n raise ValueError(\"prompt should have 3 dimensions: [B, C, T] (C = 1).\")\n prompt = convert_audio(prompt, prompt_sample_rate, self.sample_rate, self.audio_channels)\n\n if isinstance(chord_texts, str):\n chord_texts = [chord_texts]\n\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=prompt,\n melody_wavs=chord_texts, bpm=bpm, meter=meter)\n\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation_with_audio_tokens_and_text_chroma(self, prompt, descriptions: tp.List[str], chord_texts: tp.Union[tp.List[str],str],\n progress: bool = False, bpm: tp.Union[float,int,tp.List[float],tp.List[int]] = 120, meter: tp.Optional[tp.Union[int,tp.List[int]]] = 4,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text and melody.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n melody_wavs: (torch.Tensor or list of Tensor): A batch of waveforms used as\n melody conditioning. Should have shape [B, C, T] with B matching the description length,\n C=1 or 2. It can be [C, T] if there is a single description. It can also be\n a list of [C, T] tensors.\n melody_sample_rate: (int): Sample rate of the melody waveforms.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n \n if isinstance(chord_texts, str):\n chord_texts = [chord_texts]\n\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=None,\n melody_wavs=chord_texts, bpm=bpm, meter=meter)\n prompt_tokens = prompt\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n \n def generate_with_text_chroma(self, descriptions: tp.List[str], chord_texts: tp.Union[tp.List[str],str],\n progress: bool = False, bpm: tp.Union[float,int,tp.List[float],tp.List[int]] = 120, meter: tp.Optional[tp.Union[int,tp.List[int]]] = 4,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text and melody.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n melody_wavs: (torch.Tensor or list of Tensor): A batch of waveforms used as\n melody conditioning. Should have shape [B, C, T] with B matching the description length,\n C=1 or 2. It can be [C, T] if there is a single description. It can also be\n a list of [C, T] tensors.\n melody_sample_rate: (int): Sample rate of the melody waveforms.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if isinstance(chord_texts, str):\n chord_texts = [chord_texts]\n\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=None,\n melody_wavs=chord_texts, bpm=bpm, meter=meter)\n assert prompt_tokens is None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n \n @torch.no_grad()\n def _prepare_tokens_and_attributes(\n self,\n descriptions: tp.Sequence[tp.Optional[str]],\n prompt: tp.Optional[torch.Tensor],\n melody_wavs: tp.Optional[tp.Union[MelodyList,tp.List[str]]] = None, bpm: tp.Optional[tp.Union[float,int,tp.List[float],tp.List[int]]] = None, meter:tp.Optional[tp.Union[int,tp.List[int]]] = None\n ) -> tp.Tuple[tp.List[ConditioningAttributes], tp.Optional[torch.Tensor]]:\n \"\"\"Prepare model inputs.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n melody_wavs (torch.Tensor, optional): A batch of waveforms\n used as melody conditioning. Defaults to None.\n \"\"\"\n attributes = [\n ConditioningAttributes(text={'description': description})\n for description in descriptions]\n\n if melody_wavs is None:\n for attr in attributes:\n attr.wav['self_wav'] = WavCondition(\n torch.zeros((1, 1, 1), device=self.device),\n torch.tensor([0], device=self.device),\n sample_rate=[self.sample_rate],\n path=[None])\n else:\n if 'self_wav' not in self.lm.condition_provider.conditioners:\n raise RuntimeError(\"This model doesn't support melody conditioning. \"\n \"Use the `melody` model.\")\n assert len(melody_wavs) == len(descriptions), \\\n f\"number of melody wavs must match number of descriptions! \" \\\n f\"got melody len={len(melody_wavs)}, and descriptions len={len(descriptions)}\"\n\n if bpm is not None and (isinstance(bpm, int) or isinstance(bpm, float)):\n bpm = [bpm for i in range(len(melody_wavs))]\n elif bpm is not None and isinstance(bpm, tp.List):\n assert len(melody_wavs) == len(bpm)\n\n if meter is not None and (isinstance(meter, int) or isinstance(meter, float)):\n meter = [meter for i in range(len(melody_wavs))]\n elif meter is not None and isinstance(meter, tp.List):\n assert len(melody_wavs) == len(meter)\n\n for attr, melody, i in zip(attributes, melody_wavs, range(len(melody_wavs))):\n if melody is None:\n attr.wav['self_wav'] = WavCondition(\n torch.zeros((1, 1, 1), device=self.device),\n torch.tensor([0], device=self.device),\n sample_rate=[self.sample_rate],\n path=[None])\n elif isinstance(melody, torch.Tensor):\n attr.wav['self_wav'] = WavCondition(\n melody[None].to(device=self.device),\n torch.tensor([melody.shape[-1]], device=self.device),\n sample_rate=[self.sample_rate],\n path=[None],\n )\n else :\n attr.wav['self_wav'] = WavChordTextCondition(\n [melody],\n torch.tensor([self.duration*self.sample_rate], device=self.device),\n sample_rate=[self.sample_rate],\n path=[None],\n bpm = [bpm[i]],\n meter = [meter[i]]\n )\n\n if prompt is not None:\n if descriptions is not None:\n assert len(descriptions) == len(prompt), \"Prompt and nb. descriptions doesn't match\"\n prompt = prompt.to(self.device)\n prompt_tokens, scale = self.compression_model.encode(prompt)\n assert scale is None\n else:\n prompt_tokens = None\n return attributes, prompt_tokens\n\n def _generate_tokens(self, attributes: tp.List[ConditioningAttributes],\n prompt_tokens: tp.Optional[torch.Tensor], progress: bool = False) -> torch.Tensor:\n \"\"\"Generate discrete audio tokens given audio prompt and/or conditions.\n\n Args:\n attributes (list of ConditioningAttributes): Conditions used for generation (text/melody).\n prompt_tokens (torch.Tensor, optional): Audio prompt used for continuation.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n Returns:\n torch.Tensor: Generated audio, of shape [B, C, T], T is defined by the generation params.\n \"\"\"\n total_gen_len = int(self.duration * self.frame_rate)\n max_prompt_len = int(min(self.duration, self.max_duration) * self.frame_rate)\n current_gen_offset: int = 0\n\n def _progress_callback(generated_tokens: int, tokens_to_generate: int):\n generated_tokens += current_gen_offset\n if self._progress_callback is not None:\n # Note that total_gen_len might be quite wrong depending on the\n # codebook pattern used, but with delay it is almost accurate.\n self._progress_callback(generated_tokens, total_gen_len)\n else:\n print(f'{generated_tokens: 6d} / {total_gen_len: 6d}', end='\\r')\n\n if prompt_tokens is not None:\n assert max_prompt_len >= prompt_tokens.shape[-1], \\\n \"Prompt is longer than audio to generate\"\n\n callback = None\n if progress:\n callback = _progress_callback\n\n if self.duration <= self.max_duration:\n # generate by sampling from LM, simple case.\n with self.autocast:\n gen_tokens = self.lm.generate(\n prompt_tokens, attributes,\n callback=callback, max_gen_len=total_gen_len, **self.generation_params)\n\n else:\n # now this gets a bit messier, we need to handle prompts,\n # melody conditioning etc.\n ref_wavs = [attr.wav['self_wav'] for attr in attributes]\n all_tokens = []\n if prompt_tokens is None:\n prompt_length = 0\n else:\n all_tokens.append(prompt_tokens)\n prompt_length = prompt_tokens.shape[-1]\n\n stride_tokens = int(self.frame_rate * self.extend_stride)\n step = 0\n\n while current_gen_offset + prompt_length < total_gen_len:\n self.lm.condition_provider.conditioners['self_wav'].set_continuation_count(self.extend_stride/self.max_duration, step) #For text based chord conditioning\n time_offset = current_gen_offset / self.frame_rate\n chunk_duration = min(self.duration - time_offset, self.max_duration)\n max_gen_len = int(chunk_duration * self.frame_rate)\n for attr, ref_wav in zip(attributes, ref_wavs):\n if isinstance(ref_wav, WavCondition):\n wav_length = ref_wav.length.item()\n if wav_length == 0:\n continue\n # We will extend the wav periodically if it not long enough.\n # we have to do it here rather than in conditioners.py as otherwise\n # we wouldn't have the full wav.\n initial_position = int(time_offset * self.sample_rate)\n wav_target_length = int(self.max_duration * self.sample_rate)\n positions = torch.arange(initial_position,\n initial_position + wav_target_length, device=self.device)\n attr.wav['self_wav'] = WavCondition(\n ref_wav[0][..., positions % wav_length],\n torch.full_like(ref_wav[1], wav_target_length),\n [self.sample_rate] * ref_wav[0].size(0),\n [None], [0.])\n with self.autocast:\n gen_tokens = self.lm.generate(\n prompt_tokens, attributes,\n callback=callback, max_gen_len=max_gen_len, **self.generation_params)\n if prompt_tokens is None:\n all_tokens.append(gen_tokens)\n else:\n all_tokens.append(gen_tokens[:, :, prompt_tokens.shape[-1]:])\n prompt_tokens = gen_tokens[:, :, stride_tokens:]\n prompt_length = prompt_tokens.shape[-1]\n current_gen_offset += stride_tokens\n step = step + 1\n\n gen_tokens = torch.cat(all_tokens, dim=-1)\n return gen_tokens\n\n def generate_audio(self, gen_tokens: torch.Tensor):\n \"\"\"Generate Audio from tokens\"\"\"\n assert gen_tokens.dim() == 3\n with torch.no_grad():\n gen_audio = self.compression_model.decode(gen_tokens, None)\n return gen_audio" }, { "identifier": "CompressionSolver", "path": "audiocraft/solvers/compression.py", "snippet": "class CompressionSolver(base.StandardSolver):\n \"\"\"Solver for compression task.\n\n The compression task combines a set of perceptual and objective losses\n to train an EncodecModel (composed of an encoder-decoder and a quantizer)\n to perform high fidelity audio reconstruction.\n \"\"\"\n def __init__(self, cfg: omegaconf.DictConfig):\n super().__init__(cfg)\n self.rng: torch.Generator # set at each epoch\n self.adv_losses = builders.get_adversarial_losses(self.cfg)\n self.aux_losses = nn.ModuleDict()\n self.info_losses = nn.ModuleDict()\n assert not cfg.fsdp.use, \"FSDP not supported by CompressionSolver.\"\n loss_weights = dict()\n for loss_name, weight in self.cfg.losses.items():\n if loss_name in ['adv', 'feat']:\n for adv_name, _ in self.adv_losses.items():\n loss_weights[f'{loss_name}_{adv_name}'] = weight\n elif weight > 0:\n self.aux_losses[loss_name] = builders.get_loss(loss_name, self.cfg)\n loss_weights[loss_name] = weight\n else:\n self.info_losses[loss_name] = builders.get_loss(loss_name, self.cfg)\n self.balancer = builders.get_balancer(loss_weights, self.cfg.balancer)\n self.register_stateful('adv_losses')\n\n @property\n def best_metric_name(self) -> tp.Optional[str]:\n # best model is the last for the compression model\n return None\n\n def build_model(self):\n \"\"\"Instantiate model and optimizer.\"\"\"\n # Model and optimizer\n self.model = models.builders.get_compression_model(self.cfg).to(self.device)\n self.optimizer = builders.get_optimizer(self.model.parameters(), self.cfg.optim)\n self.register_stateful('model', 'optimizer')\n self.register_best_state('model')\n self.register_ema('model')\n\n def build_dataloaders(self):\n \"\"\"Instantiate audio dataloaders for each stage.\"\"\"\n self.dataloaders = builders.get_audio_datasets(self.cfg)\n\n def show(self):\n \"\"\"Show the compression model and employed adversarial loss.\"\"\"\n self.logger.info(f\"Compression model with {self.model.quantizer.total_codebooks} codebooks:\")\n self.log_model_summary(self.model)\n self.logger.info(\"Adversarial loss:\")\n self.log_model_summary(self.adv_losses)\n self.logger.info(\"Auxiliary losses:\")\n self.logger.info(self.aux_losses)\n self.logger.info(\"Info losses:\")\n self.logger.info(self.info_losses)\n\n def run_step(self, idx: int, batch: torch.Tensor, metrics: dict):\n \"\"\"Perform one training or valid step on a given batch.\"\"\"\n x = batch.to(self.device)\n y = x.clone()\n\n qres = self.model(x)\n assert isinstance(qres, quantization.QuantizedResult)\n y_pred = qres.x\n # Log bandwidth in kb/s\n metrics['bandwidth'] = qres.bandwidth.mean()\n\n if self.is_training:\n d_losses: dict = {}\n if len(self.adv_losses) > 0 and torch.rand(1, generator=self.rng).item() <= 1 / self.cfg.adversarial.every:\n for adv_name, adversary in self.adv_losses.items():\n disc_loss = adversary.train_adv(y_pred, y)\n d_losses[f'd_{adv_name}'] = disc_loss\n metrics['d_loss'] = torch.sum(torch.stack(list(d_losses.values())))\n metrics.update(d_losses)\n\n balanced_losses: dict = {}\n other_losses: dict = {}\n\n # penalty from quantization\n if qres.penalty is not None and qres.penalty.requires_grad:\n other_losses['penalty'] = qres.penalty # penalty term from the quantizer\n\n # adversarial losses\n for adv_name, adversary in self.adv_losses.items():\n adv_loss, feat_loss = adversary(y_pred, y)\n balanced_losses[f'adv_{adv_name}'] = adv_loss\n balanced_losses[f'feat_{adv_name}'] = feat_loss\n\n # auxiliary losses\n for loss_name, criterion in self.aux_losses.items():\n loss = criterion(y_pred, y)\n balanced_losses[loss_name] = loss\n\n # weighted losses\n metrics.update(balanced_losses)\n metrics.update(other_losses)\n metrics.update(qres.metrics)\n\n if self.is_training:\n # backprop losses that are not handled by balancer\n other_loss = torch.tensor(0., device=self.device)\n if 'penalty' in other_losses:\n other_loss += other_losses['penalty']\n if other_loss.requires_grad:\n other_loss.backward(retain_graph=True)\n ratio1 = sum(p.grad.data.norm(p=2).pow(2)\n for p in self.model.parameters() if p.grad is not None)\n assert isinstance(ratio1, torch.Tensor)\n metrics['ratio1'] = ratio1.sqrt()\n\n # balancer losses backward, returns effective training loss\n # with effective weights at the current batch.\n metrics['g_loss'] = self.balancer.backward(balanced_losses, y_pred)\n # add metrics corresponding to weight ratios\n metrics.update(self.balancer.metrics)\n ratio2 = sum(p.grad.data.norm(p=2).pow(2)\n for p in self.model.parameters() if p.grad is not None)\n assert isinstance(ratio2, torch.Tensor)\n metrics['ratio2'] = ratio2.sqrt()\n\n # optim\n flashy.distrib.sync_model(self.model)\n if self.cfg.optim.max_norm:\n torch.nn.utils.clip_grad_norm_(\n self.model.parameters(), self.cfg.optim.max_norm\n )\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n # informative losses only\n info_losses: dict = {}\n with torch.no_grad():\n for loss_name, criterion in self.info_losses.items():\n loss = criterion(y_pred, y)\n info_losses[loss_name] = loss\n\n metrics.update(info_losses)\n\n # aggregated GAN losses: this is useful to report adv and feat across different adversarial loss setups\n adv_losses = [loss for loss_name, loss in metrics.items() if loss_name.startswith('adv')]\n if len(adv_losses) > 0:\n metrics['adv'] = torch.sum(torch.stack(adv_losses))\n feat_losses = [loss for loss_name, loss in metrics.items() if loss_name.startswith('feat')]\n if len(feat_losses) > 0:\n metrics['feat'] = torch.sum(torch.stack(feat_losses))\n\n return metrics\n\n def run_epoch(self):\n # reset random seed at the beginning of the epoch\n self.rng = torch.Generator()\n self.rng.manual_seed(1234 + self.epoch)\n # run epoch\n super().run_epoch()\n\n def evaluate(self):\n \"\"\"Evaluate stage. Runs audio reconstruction evaluation.\"\"\"\n self.model.eval()\n evaluate_stage_name = str(self.current_stage)\n\n loader = self.dataloaders['evaluate']\n updates = len(loader)\n lp = self.log_progress(f'{evaluate_stage_name} inference', loader, total=updates, updates=self.log_updates)\n average = flashy.averager()\n\n pendings = []\n ctx = multiprocessing.get_context('spawn')\n with get_pool_executor(self.cfg.evaluate.num_workers, mp_context=ctx) as pool:\n for idx, batch in enumerate(lp):\n x = batch.to(self.device)\n with torch.no_grad():\n qres = self.model(x)\n\n y_pred = qres.x.cpu()\n y = batch.cpu() # should already be on CPU but just in case\n pendings.append(pool.submit(evaluate_audio_reconstruction, y_pred, y, self.cfg))\n\n metrics_lp = self.log_progress(f'{evaluate_stage_name} metrics', pendings, updates=self.log_updates)\n for pending in metrics_lp:\n metrics = pending.result()\n metrics = average(metrics)\n\n metrics = flashy.distrib.average_metrics(metrics, len(loader))\n return metrics\n\n def generate(self):\n \"\"\"Generate stage.\"\"\"\n self.model.eval()\n sample_manager = SampleManager(self.xp, map_reference_to_sample_id=True)\n generate_stage_name = str(self.current_stage)\n\n loader = self.dataloaders['generate']\n updates = len(loader)\n lp = self.log_progress(generate_stage_name, loader, total=updates, updates=self.log_updates)\n\n for batch in lp:\n reference, _ = batch\n reference = reference.to(self.device)\n with torch.no_grad():\n qres = self.model(reference)\n assert isinstance(qres, quantization.QuantizedResult)\n\n reference = reference.cpu()\n estimate = qres.x.cpu()\n sample_manager.add_samples(estimate, self.epoch, ground_truth_wavs=reference)\n\n flashy.distrib.barrier()\n\n def load_from_pretrained(self, name: str) -> dict:\n model = models.CompressionModel.get_pretrained(name)\n if isinstance(model, models.DAC):\n raise RuntimeError(\"Cannot fine tune a DAC model.\")\n elif isinstance(model, models.HFEncodecCompressionModel):\n self.logger.warning('Trying to automatically convert a HuggingFace model '\n 'to AudioCraft, this might fail!')\n state = model.model.state_dict()\n new_state = {}\n for k, v in state.items():\n if k.startswith('decoder.layers') and '.conv.' in k and '.block.' not in k:\n # We need to determine if this a convtr or a regular conv.\n layer = int(k.split('.')[2])\n if isinstance(model.model.decoder.layers[layer].conv, torch.nn.ConvTranspose1d):\n\n k = k.replace('.conv.', '.convtr.')\n k = k.replace('encoder.layers.', 'encoder.model.')\n k = k.replace('decoder.layers.', 'decoder.model.')\n k = k.replace('conv.', 'conv.conv.')\n k = k.replace('convtr.', 'convtr.convtr.')\n k = k.replace('quantizer.layers.', 'quantizer.vq.layers.')\n k = k.replace('.codebook.', '._codebook.')\n new_state[k] = v\n state = new_state\n elif isinstance(model, models.EncodecModel):\n state = model.state_dict()\n else:\n raise RuntimeError(f\"Cannot fine tune model type {type(model)}.\")\n return {\n 'best_state': {'model': state}\n }\n\n @staticmethod\n def model_from_checkpoint(checkpoint_path: tp.Union[Path, str],\n device: tp.Union[torch.device, str] = 'cpu') -> models.CompressionModel:\n \"\"\"Instantiate a CompressionModel from a given checkpoint path or dora sig.\n This method is a convenient endpoint to load a CompressionModel to use in other solvers.\n\n Args:\n checkpoint_path (Path or str): Path to checkpoint or dora sig from where the checkpoint is resolved.\n This also supports pre-trained models by using a path of the form //pretrained/NAME.\n See `model_from_pretrained` for a list of supported pretrained models.\n use_ema (bool): Use EMA variant of the model instead of the actual model.\n device (torch.device or str): Device on which the model is loaded.\n \"\"\"\n checkpoint_path = str(checkpoint_path)\n if checkpoint_path.startswith('//pretrained/'):\n name = checkpoint_path.split('/', 3)[-1]\n return models.CompressionModel.get_pretrained(name, device)\n logger = logging.getLogger(__name__)\n logger.info(f\"Loading compression model from checkpoint: {checkpoint_path}\")\n _checkpoint_path = checkpoint.resolve_checkpoint_path(checkpoint_path, use_fsdp=False)\n assert _checkpoint_path is not None, f\"Could not resolve compression model checkpoint path: {checkpoint_path}\"\n state = checkpoint.load_checkpoint(_checkpoint_path)\n assert state is not None and 'xp.cfg' in state, f\"Could not load compression model from ckpt: {checkpoint_path}\"\n cfg = state['xp.cfg']\n cfg.device = device\n compression_model = models.builders.get_compression_model(cfg).to(device)\n assert compression_model.sample_rate == cfg.sample_rate, \"Compression model sample rate should match\"\n\n assert 'best_state' in state and state['best_state'] != {}\n assert 'exported' not in state, \"When loading an exported checkpoint, use the //pretrained/ prefix.\"\n compression_model.load_state_dict(state['best_state']['model'])\n compression_model.eval()\n logger.info(\"Compression model loaded!\")\n return compression_model\n\n @staticmethod\n def wrapped_model_from_checkpoint(cfg: omegaconf.DictConfig,\n checkpoint_path: tp.Union[Path, str],\n device: tp.Union[torch.device, str] = 'cpu') -> models.CompressionModel:\n \"\"\"Instantiate a wrapped CompressionModel from a given checkpoint path or dora sig.\n\n Args:\n cfg (omegaconf.DictConfig): Configuration to read from for wrapped mode.\n checkpoint_path (Path or str): Path to checkpoint or dora sig from where the checkpoint is resolved.\n use_ema (bool): Use EMA variant of the model instead of the actual model.\n device (torch.device or str): Device on which the model is loaded.\n \"\"\"\n compression_model = CompressionSolver.model_from_checkpoint(checkpoint_path, device)\n compression_model = models.builders.get_wrapped_compression_model(compression_model, cfg)\n return compression_model" }, { "identifier": "load_compression_model", "path": "audiocraft/models/loaders.py", "snippet": "def load_compression_model(file_or_url_or_id: tp.Union[Path, str], device='cpu', cache_dir: tp.Optional[str] = None):\n pkg = load_compression_model_ckpt(file_or_url_or_id, cache_dir=cache_dir)\n if 'pretrained' in pkg:\n return CompressionModel.get_pretrained(pkg['pretrained'], device=device)\n cfg = OmegaConf.create(pkg['xp.cfg'])\n cfg.device = str(device)\n model = builders.get_compression_model(cfg)\n model.load_state_dict(pkg['best_state'])\n model.eval()\n return model" }, { "identifier": "load_lm_model", "path": "audiocraft/models/loaders.py", "snippet": "def load_lm_model(file_or_url_or_id: tp.Union[Path, str], device='cpu', cache_dir: tp.Optional[str] = None):\n pkg = load_lm_model_ckpt(file_or_url_or_id, cache_dir=cache_dir)\n cfg = OmegaConf.create(pkg['xp.cfg'])\n cfg.device = str(device)\n if cfg.device == 'cpu':\n cfg.dtype = 'float32'\n else:\n cfg.dtype = 'float16'\n _delete_param(cfg, 'conditioners.self_wav.chroma_chord.cache_path')\n _delete_param(cfg, 'conditioners.self_wav.chroma_stem.cache_path')\n _delete_param(cfg, 'conditioners.args.merge_text_conditions_p')\n _delete_param(cfg, 'conditioners.args.drop_desc_p')\n model = builders.get_lm_model(cfg)\n model.load_state_dict(pkg['best_state'])\n model.eval()\n model.cfg = cfg\n return model" }, { "identifier": "audio_write", "path": "audiocraft/data/audio.py", "snippet": "def audio_write(stem_name: tp.Union[str, Path],\n wav: torch.Tensor, sample_rate: int,\n format: str = 'wav', mp3_rate: int = 320, ogg_rate: tp.Optional[int] = None,\n normalize: bool = True, strategy: str = 'peak', peak_clip_headroom_db: float = 1,\n rms_headroom_db: float = 18, loudness_headroom_db: float = 14,\n loudness_compressor: bool = False,\n log_clipping: bool = True, make_parent_dir: bool = True,\n add_suffix: bool = True) -> Path:\n \"\"\"Convenience function for saving audio to disk. Returns the filename the audio was written to.\n\n Args:\n stem_name (str or Path): Filename without extension which will be added automatically.\n wav (torch.Tensor): Audio data to save.\n sample_rate (int): Sample rate of audio data.\n format (str): Either \"wav\", \"mp3\", \"ogg\", or \"flac\".\n mp3_rate (int): kbps when using mp3s.\n ogg_rate (int): kbps when using ogg/vorbis. If not provided, let ffmpeg decide for itself.\n normalize (bool): if `True` (default), normalizes according to the prescribed\n strategy (see after). If `False`, the strategy is only used in case clipping\n would happen.\n strategy (str): Can be either 'clip', 'peak', or 'rms'. Default is 'peak',\n i.e. audio is normalized by its largest value. RMS normalizes by root-mean-square\n with extra headroom to avoid clipping. 'clip' just clips.\n peak_clip_headroom_db (float): Headroom in dB when doing 'peak' or 'clip' strategy.\n rms_headroom_db (float): Headroom in dB when doing 'rms' strategy. This must be much larger\n than the `peak_clip` one to avoid further clipping.\n loudness_headroom_db (float): Target loudness for loudness normalization.\n loudness_compressor (bool): Uses tanh for soft clipping when strategy is 'loudness'.\n when strategy is 'loudness' log_clipping (bool): If True, basic logging on stderr when clipping still\n occurs despite strategy (only for 'rms').\n make_parent_dir (bool): Make parent directory if it doesn't exist.\n Returns:\n Path: Path of the saved audio.\n \"\"\"\n assert wav.dtype.is_floating_point, \"wav is not floating point\"\n if wav.dim() == 1:\n wav = wav[None]\n elif wav.dim() > 2:\n raise ValueError(\"Input wav should be at most 2 dimension.\")\n assert wav.isfinite().all()\n wav = normalize_audio(wav, normalize, strategy, peak_clip_headroom_db,\n rms_headroom_db, loudness_headroom_db, loudness_compressor,\n log_clipping=log_clipping, sample_rate=sample_rate,\n stem_name=str(stem_name))\n if format == 'mp3':\n suffix = '.mp3'\n flags = ['-f', 'mp3', '-c:a', 'libmp3lame', '-b:a', f'{mp3_rate}k']\n elif format == 'wav':\n suffix = '.wav'\n flags = ['-f', 'wav', '-c:a', 'pcm_s16le']\n elif format == 'ogg':\n suffix = '.ogg'\n flags = ['-f', 'ogg', '-c:a', 'libvorbis']\n if ogg_rate is not None:\n flags += ['-b:a', f'{ogg_rate}k']\n elif format == 'flac':\n suffix = '.flac'\n flags = ['-f', 'flac']\n else:\n raise RuntimeError(f\"Invalid format {format}. Only wav or mp3 are supported.\")\n if not add_suffix:\n suffix = ''\n path = Path(str(stem_name) + suffix)\n if make_parent_dir:\n path.parent.mkdir(exist_ok=True, parents=True)\n try:\n _piping_to_ffmpeg(path, wav, sample_rate, flags)\n except Exception:\n if path.exists():\n # we do not want to leave half written files around.\n path.unlink()\n raise\n return path" }, { "identifier": "get_lm_model", "path": "audiocraft/models/builders.py", "snippet": "def get_lm_model(cfg: omegaconf.DictConfig) -> LMModel:\n \"\"\"Instantiate a transformer LM.\"\"\"\n if cfg.lm_model == 'transformer_lm':\n kwargs = dict_from_config(getattr(cfg, 'transformer_lm'))\n n_q = kwargs['n_q']\n q_modeling = kwargs.pop('q_modeling', None)\n codebooks_pattern_cfg = getattr(cfg, 'codebooks_pattern')\n attribute_dropout = dict_from_config(getattr(cfg, 'attribute_dropout'))\n cls_free_guidance = dict_from_config(getattr(cfg, 'classifier_free_guidance'))\n cfg_prob, cfg_coef = cls_free_guidance['training_dropout'], cls_free_guidance['inference_coef']\n fuser = get_condition_fuser(cfg)\n condition_provider = get_conditioner_provider(kwargs[\"dim\"], cfg).to(cfg.device)\n if len(fuser.fuse2cond['cross']) > 0: # enforce cross-att programmatically\n kwargs['cross_attention'] = True\n if codebooks_pattern_cfg.modeling is None:\n assert q_modeling is not None, \\\n \"LM model should either have a codebook pattern defined or transformer_lm.q_modeling\"\n codebooks_pattern_cfg = omegaconf.OmegaConf.create(\n {'modeling': q_modeling, 'delay': {'delays': list(range(n_q))}}\n )\n pattern_provider = get_codebooks_pattern_provider(n_q, codebooks_pattern_cfg)\n return LMModel(\n pattern_provider=pattern_provider,\n condition_provider=condition_provider,\n fuser=fuser,\n cfg_dropout=cfg_prob,\n cfg_coef=cfg_coef,\n attribute_dropout=attribute_dropout,\n dtype=getattr(torch, cfg.dtype),\n device=cfg.device,\n **kwargs\n ).to(cfg.device)\n else:\n raise KeyError(f\"Unexpected LM model {cfg.lm_model}\")" } ]
import os import random import torchaudio import typing as tp import numpy as np import torch import librosa import subprocess import math import allin1 import pytsmod as tsm import shutil import shutil from typing import Optional from cog import BasePredictor, Input, Path from audiocraft.models import MusicGen, MultiBandDiffusion from audiocraft.solvers.compression import CompressionSolver from audiocraft.models.loaders import ( load_compression_model, load_lm_model, ) from audiocraft.data.audio import audio_write from audiocraft.models.builders import get_lm_model from omegaconf import OmegaConf from audiocraft.modules.btc.btc_model import BTC_model from audiocraft.modules.btc.utils.mir_eval_modules import idx2chord from demucs.audio import convert_audio from demucs.apply import apply_model
14,614
# Prediction interface for Cog ⚙️ # https://github.com/replicate/cog/blob/main/docs/python.md # We need to set `TRANSFORMERS_CACHE` before any imports, which is why this is up here. MODEL_PATH = "/src/models/" os.environ["TRANSFORMERS_CACHE"] = MODEL_PATH os.environ["TORCH_HOME"] = MODEL_PATH # Model specific imports def _delete_param(cfg, full_name: str): parts = full_name.split('.') for part in parts[:-1]: if part in cfg: cfg = cfg[part] else: return OmegaConf.set_struct(cfg, False) if parts[-1] in cfg: del cfg[parts[-1]] OmegaConf.set_struct(cfg, True) def load_ckpt(path, device, url=False): if url: loaded = torch.hub.load_state_dict_from_url(str(path)) else: loaded = torch.load(str(path)) cfg = OmegaConf.create(loaded['xp.cfg']) cfg.device = str(device) if cfg.device == 'cpu': cfg.dtype = 'float32' else: cfg.dtype = 'float16' _delete_param(cfg, 'conditioners.self_wav.chroma_chord.cache_path') _delete_param(cfg, 'conditioners.self_wav.chroma_stem.cache_path') _delete_param(cfg, 'conditioners.args.merge_text_conditions_p') _delete_param(cfg, 'conditioners.args.drop_desc_p') lm = get_lm_model(loaded['xp.cfg']) lm.load_state_dict(loaded['model']) lm.eval() lm.cfg = cfg
# Prediction interface for Cog ⚙️ # https://github.com/replicate/cog/blob/main/docs/python.md # We need to set `TRANSFORMERS_CACHE` before any imports, which is why this is up here. MODEL_PATH = "/src/models/" os.environ["TRANSFORMERS_CACHE"] = MODEL_PATH os.environ["TORCH_HOME"] = MODEL_PATH # Model specific imports def _delete_param(cfg, full_name: str): parts = full_name.split('.') for part in parts[:-1]: if part in cfg: cfg = cfg[part] else: return OmegaConf.set_struct(cfg, False) if parts[-1] in cfg: del cfg[parts[-1]] OmegaConf.set_struct(cfg, True) def load_ckpt(path, device, url=False): if url: loaded = torch.hub.load_state_dict_from_url(str(path)) else: loaded = torch.load(str(path)) cfg = OmegaConf.create(loaded['xp.cfg']) cfg.device = str(device) if cfg.device == 'cpu': cfg.dtype = 'float32' else: cfg.dtype = 'float16' _delete_param(cfg, 'conditioners.self_wav.chroma_chord.cache_path') _delete_param(cfg, 'conditioners.self_wav.chroma_stem.cache_path') _delete_param(cfg, 'conditioners.args.merge_text_conditions_p') _delete_param(cfg, 'conditioners.args.drop_desc_p') lm = get_lm_model(loaded['xp.cfg']) lm.load_state_dict(loaded['model']) lm.eval() lm.cfg = cfg
compression_model = CompressionSolver.model_from_checkpoint(cfg.compression_model_checkpoint, device=device)
2
2023-10-09 09:55:24+00:00
24k
oracle/guardian-ai
tests/unitary/test_fairness_metrics.py
[ { "identifier": "ConsistencyScorer", "path": "guardian_ai/fairness/metrics/dataset.py", "snippet": "class ConsistencyScorer(_SimpleDatasetFairnessScorer):\n \"\"\"\n Measures the consistency of a dataset.\n\n Consistency is measured as the number of ratio of instances that have a\n different label from the k=5 nearest neighbors.\n\n Perfect score\n A perfect score for this metric is 0, meaning that the dataset does\n not have different labels for instances that are similar to one another.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import ConsistencyScorer\n scorer = ConsistencyScorer(['race', 'sex'])\n scorer(X=X, y_true=y_true)\n scorer(None, X, y_true)\n \"\"\"\n\n def __init__(self, protected_attributes: Union[pd.Series, np.ndarray, List, str]):\n super().__init__(protected_attributes=protected_attributes, metric=consistency)" }, { "identifier": "DatasetStatisticalParityScorer", "path": "guardian_ai/fairness/metrics/dataset.py", "snippet": "class DatasetStatisticalParityScorer(_DatasetFairnessScorer):\n \"\"\"\n Measures the statistical parity [1] of a dataset. Statistical parity (also\n known as Base Rate or Disparate Impact) for a dataset states that a dataset\n is unbiased if the label is independent of the protected attribute.\n\n For each subgroup, statistical parity is computed as the ratio of positive\n labels in a subgroup.\n\n Statistical Parity (also known as Base Rate or Disparate Impact) is\n calculated as PL / N, where PL and N are the number of Positive Labels and\n total number of instances, respectively.\n\n Perfect score\n A perfect score for this metric means that the dataset does not have\n a different ratio of positive labels for a subgroup than it does for\n the rest of the subgroups. For example, if the protected attributes\n are race and sex, then a perfect statistical parity would mean that\n all combinations of values for race and sex have identical ratios of\n positive labels. Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n\n References\n ----------\n [1] `Cynthia Dwork et al. \"Fairness Through Awareness\". Innovations in\n Theoretical Computer Science. 2012. <https://arxiv.org/abs/1104.3913>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import DatasetStatisticalParityScorer\n scorer = DatasetStatisticalParityScorer(['race', 'sex'])\n scorer(X=X, y_true=y_true)\n scorer(None, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=dataset_statistical_parity,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "SmoothedEDFScorer", "path": "guardian_ai/fairness/metrics/dataset.py", "snippet": "class SmoothedEDFScorer(_SimpleDatasetFairnessScorer):\n \"\"\"\n Measures the smoothed Empirical Differential Fairness (EDF) of a dataset, as\n proposed by Foulds et al. [1].\n\n Smoothed EDF returns the minimal exponential deviation of positive target\n ratios comparing a subgroup to the rest of the subgroups.\n\n This metric is related to :class:`.DatasetStatisticalParity` with\n `reduction='max'` and `distance_measure='ratio'`, with the only difference\n being that :class:`.SmoothedEDFScorer` returns a logarithmic value instead.\n\n Perfect score\n A perfect score for this metric is 0, meaning that the dataset does\n not have a different ratio of positive labels for a subgroup than\n it does for the rest of the subgroups. For example, if the\n protected attributes are race and sex, then a perfect smoothed EDF\n would mean that all combinations of values for race and sex have\n identical ratios of positive labels.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n\n References\n ----------\n [1] `Foulds, James R., et al. \"An intersectional definition of fairness.\"\n 2020 IEEE 36th International Conference on Data Engineering (ICDE).\n IEEE, 2020. <https://arxiv.org/abs/1807.08362>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import SmoothedEDFScorer\n scorer = SmoothedEDFScorer(['race', 'sex'])\n scorer(X=X, y_true=y_true)\n scorer(None, X, y_true)\n \"\"\"\n\n def __init__(self, protected_attributes: Union[pd.Series, np.ndarray, List, str]):\n super().__init__(protected_attributes=protected_attributes, metric=smoothed_edf)" }, { "identifier": "consistency", "path": "guardian_ai/fairness/metrics/dataset.py", "snippet": "def consistency(y_true: Union[pd.Series, np.ndarray, List], subgroups: pd.DataFrame):\n \"\"\"\n Measures the consistency of a dataset.\n\n For more details, refer to :class:`.ConsistencyScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import consistency\n subgroups = X[['race', 'sex']]\n consistency(y_true, subgroups)\n \"\"\"\n # Need to read with [0] because consistency returns an array of size 1.\n return _simple_dataset_metric(y_true, subgroups, metric=\"consistency\")[0]" }, { "identifier": "dataset_statistical_parity", "path": "guardian_ai/fairness/metrics/dataset.py", "snippet": "def dataset_statistical_parity(\n y_true: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: str = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the statistical parity of a dataset.\n\n For more details, refer to :class:`.DatasetStatisticalParityScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import dataset_statistical_parity\n subgroups = X[['race', 'sex']]\n dataset_statistical_parity(y_true, subgroups)\n \"\"\"\n return _dataset_metric(\n y_true,\n subgroups,\n metric=\"base_rate\",\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "smoothed_edf", "path": "guardian_ai/fairness/metrics/dataset.py", "snippet": "def smoothed_edf(y_true: Union[pd.Series, np.ndarray, List], subgroups: pd.DataFrame):\n \"\"\"\n Measures the smoothed Empirical Differential Fairness (EDF) of a dataset, as\n proposed by Foulds et al. [1].\n\n For more details, refer to :class:`.SmoothedEDFScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n\n References\n ----------\n [1] `Foulds, James R., et al. \"An intersectional definition of fairness.\"\n 2020 IEEE 36th International Conference on Data Engineering (ICDE).\n IEEE, 2020. <https://arxiv.org/abs/1807.08362>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import smoothed_edf\n subgroups = X[['race', 'sex']]\n smoothed_edf(y_true, subgroups)\n \"\"\"\n return _simple_dataset_metric(\n y_true, subgroups, metric=\"smoothed_empirical_differential_fairness\"\n )" }, { "identifier": "EqualizedOddsScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class EqualizedOddsScorer(_ModelFairnessScorer):\n \"\"\"\n Measures the disparity of a model's true positive and false positive rates\n between subgroups and the rest of the subgroups.\n\n The disparity is measured by comparing the true positive and false positive\n rates on instances of a subgroup against the rest of the subgroups.\n\n True Positive Rate (also known as TPR, recall, or sensitivity) is\n calculated as TP / (TP + FN), where TP and FN are the number of true\n positives and false negatives, respectively.\n\n False Positive Rate (also known as FPR or fall-out) is calculated as\n FP / (FP + TN), where FP and TN are the number of false positives and\n true negatives, respectively.\n\n Equalized Odds [1] is computed by taking the maximum distance between\n TPR and FPR for a subgroup against the rest of the subgroups.\n\n Perfect score\n A perfect score for this metric means that the model has the same TPR and\n FPR when comparing a subgroup to the rest of the subgroups. For example,\n if the protected attributes are race and sex, then a perfect\n Equalized Odds disparity would mean that all combinations of values for\n race and sex have identical TPR and FPR. Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n References\n ----------\n [1] `Moritz Hardt et al. \"Equality of Opportunity in Supervised Learning\".\n Advances in Neural Information Processing Systems. 2016.\n <https://arxiv.org/pdf/1610.02413.pdf>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import EqualizedOddsScorer\n scorer = EqualizedOddsScorer(['race', 'sex'])\n scorer(model, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=equalized_odds,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "ErrorRateScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class ErrorRateScorer(_ModelFairnessScorer):\n \"\"\"\n Measures the disparity of a model's error rate between all subgroup pairs.\n\n For each subgroup, the disparity is measured by comparing the error rate on\n instances of a subgroup against the rest of the subgroups.\n\n Error Rate (also known as inaccuracy) is calculated as\n (FP + FN) / N, where FP and FN are the number of false positives and\n false negatives, respectively, while N is the total Number of\n instances.\n\n Perfect score\n A perfect score for this metric means that the model does not make more\n mistakes for any of the subgroups more often than it\n does for the rest of the subgroups. For example, if the protected\n attributes are race and sex, then a perfect error rate disparity would\n mean that all combinations of values for race and sex have identical\n error rates. Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import ErrorRateScorer\n scorer = ErrorRateScorer(['race', 'sex'])\n scorer(model, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=error_rate,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "FalseDiscoveryRateScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class FalseDiscoveryRateScorer(_ModelFairnessScorer):\n \"\"\"\n Measures the disparity of a model's false discovery rate between all subgroup pairs.\n\n For each subgroup, the disparity is measured by comparing the false\n discovery rate on instances of a subgroup against the rest of the\n subgroups.\n\n False Discovery Rate (also known as FDR) is calculated as\n FP / (FP + TP), where FP and TP are the number of false positives and\n true positives, respectively.\n\n Perfect score\n A perfect score for this metric means that the model does not make more\n mistakes on the positive class for any of the subgroups more often than it\n does for the rest of the subgroups. For example, if the protected\n attributes are race and sex, then a perfect false discovery rate disparity\n would mean that all combinations of values for race and sex have identical\n false discovery rates. Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import FalseDiscoveryRateScorer\n scorer = FalseDiscoveryRateScorer(['race', 'sex'])\n scorer(model, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=false_discovery_rate,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "FalseNegativeRateScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class FalseNegativeRateScorer(_ModelFairnessScorer):\n \"\"\"\n Measures the disparity of a model's false negative rate between all subgroup pairs.\n\n For each subgroup, the disparity is measured by comparing the false\n negative rate on instances of a subgroup against the rest of the subgroups.\n\n False Negative Rate [1] (also known as FNR or miss rate) is calculated as\n FN / (FN + TP), where FN and TP are the number of false negatives and\n true positives, respectively.\n\n Perfect score\n A perfect score for this metric means that the model does not incorrectly\n predict the negative class for any of the subgroups more often than it\n does for the rest of the subgroups. For example, if the protected\n attributes are race and sex, then a perfect false negative rate disparity\n would mean that all combinations of values for race and sex have identical\n false negative rates. Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n References\n ----------\n [1] `Alexandra Chouldechova. \"Fair Prediction with Disparate Impact: A Study\n of Bias in Recidivism Prediction Instruments\". Big Data (2016).\n <https://www.liebertpub.com/doi/10.1089/big.2016.0047>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import FalseNegativeRateScorer\n scorer = FalseNegativeRateScorer(['race', 'sex'])\n scorer(model, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=false_negative_rate,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "FalseOmissionRateScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class FalseOmissionRateScorer(_ModelFairnessScorer):\n \"\"\"\n Measures the disparity of a model's false omission rate between all subgroup pairs.\n\n For each subgroup, the disparity is measured by comparing the false\n omission rate on instances of a subgroup against the rest of the subgroups.\n\n False Omission Rate (also known as FOR) is calculated as\n FN / (FN + TN), where FN and TN are the number of false negatives and\n true negatives, respectively.\n\n Perfect score\n A perfect score for this metric means that the model does not make more\n mistakes on the negative class for any of the subgroups more often than it\n does for the rest of the subgroups. For example, if the protected\n attributes are race and sex, then a perfect false omission rate disparity\n would mean that all combinations of values for race and sex have identical\n false omission rates. Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import FalseOmissionRateScorer\n scorer = FalseOmissionRateScorer(['race', 'sex'])\n scorer(model, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=false_omission_rate,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "FalsePositiveRateScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class FalsePositiveRateScorer(_ModelFairnessScorer):\n \"\"\"\n Measures the disparity of a model's false positive rate between all subgroup pairs.\n\n For each subgroup, the disparity is measured by comparing the false\n positive rate on instances of a subgroup against the rest of the subgroups.\n\n False Positive Rate [1] (also known as FPR or fall-out) is calculated as\n FP / (FP + TN), where FP and TN are the number of false positives and\n true negatives, respectively.\n\n Perfect score\n A perfect score for this metric means that the model does not incorrectly\n predict the positive class for any of the subgroups more often than it\n does for the rest of the subgroups. For example, if the protected\n attributes are race and sex, then a perfect false positive rate disparity\n would mean that all combinations of values for race and sex have identical\n false positive rates. Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n References\n ----------\n [1] `Alexandra Chouldechova. \"Fair Prediction with Disparate Impact: A Study\n of Bias in Recidivism Prediction Instruments\". Big Data (2016).\n <https://www.liebertpub.com/doi/10.1089/big.2016.0047>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import FalsePositiveRateScorer\n scorer = FalsePositiveRateScorer(['race', 'sex'])\n scorer(model, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=false_positive_rate,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "ModelStatisticalParityScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class ModelStatisticalParityScorer(_ModelFairnessScorer): # noqa: D412\n \"\"\"\n Measure the statistical parity [1] of a model's output between all subgroup pairs.\n\n Statistical parity (also known as Base Rate or Disparate Impact) states that\n a predictor is unbiased if the prediction is independent of the protected\n attribute.\n\n Statistical Parity is calculated as PP / N, where PP and N are the number of\n Positive Predictions and total Number of predictions made, respectively.\n\n Perfect score\n A perfect score for this metric means that the model does not predict\n positively any of the subgroups at a different rate than it does for the\n rest of the subgroups. For example, if the protected attributes are race\n and sex, then a perfect statistical parity would mean that all combinations\n of values for race and sex have identical ratios of positive predictions.\n Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n\n References\n ----------\n [1] `Cynthia Dwork et al. \"Fairness Through Awareness\". Innovations in\n Theoretical Computer Science. 2012. <https://arxiv.org/abs/1104.3913>`_\n\n Examples\n --------\n\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import ModelStatisticalParityScorer\n\n scorer = ModelStatisticalParityScorer(['race', 'sex'])\n scorer(model, X, y_true)\n\n This metric does not require `y_true`. It can also be called using\n\n .. code-block:: python\n\n scorer(model, X)\n \"\"\" # noqa: D412\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=model_statistical_parity,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )\n\n def __call__(\n self,\n model: Any,\n X: pd.DataFrame,\n y_true: Optional[Union[pd.Series, np.ndarray, List]] = None,\n supplementary_features: Optional[pd.DataFrame] = None,\n ):\n \"\"\"\n Compute the metric using a model's predictions on a given array\n of instances ``X``.\n\n Parameters\n ----------\n model: Any\n Object that implements a `predict(X)` function to collect\n categorical predictions.\n X : pandas.DataFrame\n Array of instances to compute the metric on.\n y_true : pandas.Series, numpy.ndarray, list, or None, default=None\n Array of groundtruth labels.\n supplementary_features : pandas.DataFrame, or None, default=None\n Array of supplementary features for each instance. Used in case\n one attribute in ``self.protected_attributes`` is not contained by\n ``X`` (e.g. if the protected attribute is not used by the model).\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to ``self.reduction``.\n\n\n Raises\n ------\n GuardianAIValueError\n - if a feature is present in both ``X``\n and ``supplementary_features``.\n\n \"\"\"\n y_pred = model.predict(X)\n\n subgroups = self._get_check_subgroups(X, supplementary_features)\n\n return self.metric(\n y_true, y_pred, subgroups, self.distance_measure, self.reduction\n )" }, { "identifier": "TheilIndexScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class TheilIndexScorer(_ModelFairnessScorer):\n \"\"\"\n Measures the disparity of a model's predictions according to groundtruth\n labels, as proposed by Speicher et al. [1].\n\n Intuitively, the Theil Index can be thought of as a measure of the\n divergence between a subgroup's different error distributions (i.e. false\n positives and false negatives) against the rest of the subgroups.\n\n Perfect score\n The perfect score for this metric is 0, meaning that the model does not\n have a different error distribution for any subgroup when compared to the\n rest of the subgroups. For example, if the protected attributes are\n race and sex, then a perfect Theil Index disparity would mean that all\n combinations of values for race and sex have identical error\n distributions.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str or None, default=None\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n References\n ----------\n [1] `Speicher, Till, et al. \"A unified approach to quantifying algorithmic\n unfairness: Measuring individual & group unfairness via inequality indices.\"\n Proceedings of the 24th ACM SIGKDD international conference on knowledge\n discovery & data mining. 2018. <https://arxiv.org/abs/1807.00787>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import TheilIndexScorer\n scorer = TheilIndexScorer(['race', 'sex'])\n scorer(model, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: Optional[str] = None,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=theil_index,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=True,\n )" }, { "identifier": "TruePositiveRateScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class TruePositiveRateScorer(_ModelFairnessScorer):\n \"\"\"\n Measures the disparity of a model's true positive rate between\n all subgroup pairs (also known as equal opportunity).\n\n For each subgroup, the disparity is measured by comparing the true positive\n rate on instances of a subgroup against the rest of the subgroups.\n\n True Positive Rate [1] (also known as TPR, recall, or sensitivity) is\n calculated as TP / (TP + FN), where TP and FN are the number of true\n positives and false negatives, respectively.\n\n\n Perfect score\n A perfect score for this metric means that the model does not correctly\n predict the positive class for any of the subgroups more often than it\n does for the rest of the subgroups. For example, if the protected\n attributes are race and sex, then a perfect true positive rate disparity\n would mean that all combinations of values for race and sex have\n identical true positive rates. Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n References\n ----------\n [1] `Moritz Hardt et al. \"Equality of Opportunity in Supervised Learning\".\n Advances in Neural Information Processing Systems. 2016.\n <https://arxiv.org/pdf/1610.02413.pdf>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import TruePositiveRateScorer\n scorer = TruePositiveRateScorer(['race', 'sex'])\n scorer(model, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=true_positive_rate,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "equalized_odds", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def equalized_odds(\n y_true: Union[pd.Series, np.ndarray, List],\n y_pred: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the disparity of a model's true positive and false positive rates\n between subgroups and the rest of the subgroups.\n\n For more details, refer to :class:`.EqualizedOddsScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list\n Array of model predictions.\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import equalized_odds\n subgroups = X[['race', 'sex']]\n equalized_odds(y_true, y_pred, subgroups)\n \"\"\"\n tpr = true_positive_rate(\n y_true,\n y_pred,\n subgroups,\n distance_measure=distance_measure,\n reduction=reduction,\n )\n\n fpr = false_positive_rate(\n y_true,\n y_pred,\n subgroups,\n distance_measure=distance_measure,\n reduction=reduction,\n )\n if isinstance(tpr, dict):\n eq_odds = {}\n for key in tpr:\n eq_odds[key] = np.nanmax([tpr[key], fpr[key]])\n else:\n eq_odds = np.nanmax([tpr, fpr])\n\n return eq_odds" }, { "identifier": "error_rate", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def error_rate(\n y_true: Union[pd.Series, np.ndarray, List],\n y_pred: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the disparity of a model's error rate between all subgroup pairs.\n\n For more details, refer to :class:`.ErrorRateScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list\n Array of model predictions.\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import error_rate\n subgroups = X[['race', 'sex']]\n error_rate(y_true, y_pred, subgroups)\n \"\"\"\n return _model_metric(\n y_true,\n y_pred,\n subgroups,\n metric=\"error_rate\",\n distance_measure=distance_measure,\n reduction=reduction,\n allow_y_true_none=False,\n allow_distance_measure_none=False,\n )" }, { "identifier": "false_discovery_rate", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def false_discovery_rate(\n y_true: Union[pd.Series, np.ndarray, List],\n y_pred: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the disparity of a model's false discovery rate between all subgroup pairs.\n\n For more details, refer to :class:`.FalseDiscoveryRateScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list\n Array of model predictions.\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import false_discovery_rate\n subgroups = X[['race', 'sex']]\n false_discovery_rate(y_true, y_pred, subgroups)\n \"\"\"\n return _model_metric(\n y_true,\n y_pred,\n subgroups,\n metric=\"false_discovery_rate\",\n distance_measure=distance_measure,\n reduction=reduction,\n allow_y_true_none=False,\n allow_distance_measure_none=False,\n )" }, { "identifier": "false_negative_rate", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def false_negative_rate(\n y_true: Union[pd.Series, np.ndarray, List],\n y_pred: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the disparity of a model's false negative rate between all subgroup pairs.\n\n For more details, refer to :class:`.FalseNegativeRateScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list\n Array of model predictions.\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import false_negative_rate\n subgroups = X[['race', 'sex']]\n false_negative_rate(y_true, y_pred, subgroups)\n \"\"\"\n return _model_metric(\n y_true,\n y_pred,\n subgroups,\n metric=\"false_negative_rate\",\n distance_measure=distance_measure,\n reduction=reduction,\n allow_y_true_none=False,\n allow_distance_measure_none=False,\n )" }, { "identifier": "false_omission_rate", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def false_omission_rate(\n y_true: Union[pd.Series, np.ndarray, List],\n y_pred: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the disparity of a model's false omission rate between all subgroup pairs.\n\n For more details, refer to :class:`.FalseOmissionRateScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list\n Array of model predictions.\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import false_omission_rate\n subgroups = X[['race', 'sex']]\n false_omission_rate(y_true, y_pred, subgroups)\n \"\"\"\n return _model_metric(\n y_true,\n y_pred,\n subgroups,\n metric=\"false_omission_rate\",\n distance_measure=distance_measure,\n reduction=reduction,\n allow_y_true_none=False,\n allow_distance_measure_none=False,\n )" }, { "identifier": "false_positive_rate", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def false_positive_rate(\n y_true: Union[pd.Series, np.ndarray, List],\n y_pred: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the disparity of a model's false positive rate between all subgroup pairs.\n\n For more details, refer to :class:`.FalsePositiveRateScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list\n Array of model predictions.\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import false_positive_rate\n subgroups = X[['race', 'sex']]\n false_positive_rate(y_true, y_pred, subgroups)\n \"\"\"\n return _model_metric(\n y_true,\n y_pred,\n subgroups,\n metric=\"false_positive_rate\",\n distance_measure=distance_measure,\n reduction=reduction,\n allow_y_true_none=False,\n allow_distance_measure_none=False,\n )" }, { "identifier": "model_statistical_parity", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def model_statistical_parity(\n y_true: Optional[Union[pd.Series, np.ndarray, List]] = None,\n y_pred: Optional[Union[pd.Series, np.ndarray, List]] = None,\n subgroups: Optional[pd.DataFrame] = None,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measure the statistical parity of a model's output between all subgroup pairs.\n\n For more details, refer to :class:`.ModelStatisticalParityScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list or None, default=None\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list or None, default=None\n Array of model predictions.\n subgroups : pandas.DataFrame or None, default=None\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n Raises\n ------\n GuardianAIValueError\n If Value of None is received for either `y_pred` or `subgroups`.\n\n Examples\n --------\n\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import model_statistical_parity\n subgroups = X[['race', 'sex']]\n model_statistical_parity(y_true, y_pred, subgroups)\n\n This metric does not require `y_true`. It can also be called using\n\n .. code-block:: python\n\n model_statistical_parity(None, y_pred, subgroups)\n model_statistical_parity(y_pred=y_pred, subgroups=subgroups)\n \"\"\" # noqa: D412\n\n if y_pred is None or subgroups is None:\n raise GuardianAIValueError(\n \"Value of None was received for either `y_pred` or `subgroups`. \"\n \"This may be due to calling the metric using only 2 positional \"\n \"arguments. If this is the case, either call the function by \"\n \"passing ``None`` as the first argument or use named arguments for \"\n \"`y_pred` and `subgroups`.\"\n )\n\n return _model_metric(\n None,\n y_pred,\n subgroups,\n metric=\"selection_rate\",\n distance_measure=distance_measure,\n reduction=reduction,\n allow_y_true_none=True,\n allow_distance_measure_none=False,\n )" }, { "identifier": "theil_index", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def theil_index(\n y_true: Union[pd.Series, np.ndarray, List],\n y_pred: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: Optional[str] = None,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the disparity of a model's predictions according to groundtruth\n labels, as proposed by Speicher et al. [1].\n\n For more details, refer to :class:`.TheilIndexScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list\n Array of model predictions.\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str or None, default=None\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n Raises\n ------\n GuardianAIValueError\n If distance_measure values are given to Theil Index.\n\n References\n ----------\n [1]: `Speicher, Till, et al. \"A unified approach to quantifying algorithmic\n unfairness: Measuring individual & group unfairness via inequality indices.\"\n Proceedings of the 24th ACM SIGKDD international conference on knowledge\n discovery & data mining. 2018. <https://arxiv.org/abs/1807.00787>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import theil_index\n subgroups = X[['race', 'sex']]\n theil_index(y_true, y_pred, subgroups)\n \"\"\"\n\n if distance_measure is not None and not isinstance(\n distance_measure, _DistanceMetric\n ):\n raise GuardianAIValueError(\n \"Theil Index does not accept distance_measure values. It should\"\n \"always be set to ``None``.\"\n )\n\n return _model_metric(\n y_true,\n y_pred,\n subgroups,\n metric=\"between_group_theil_index\",\n distance_measure=None,\n reduction=reduction,\n allow_y_true_none=False,\n allow_distance_measure_none=True,\n )" }, { "identifier": "true_positive_rate", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def true_positive_rate(\n y_true: Union[pd.Series, np.ndarray, List],\n y_pred: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the disparity of a model's true positive rate between all subgroup pairs.\n\n For more details, refer to :class:`.TruePositiveRateScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list\n Array of model predictions.\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import true_positive_rate\n subgroups = X[['race', 'sex']]\n true_positive_rate(y_true, y_pred, subgroups)\n \"\"\"\n return _model_metric(\n y_true,\n y_pred,\n subgroups,\n metric=\"true_positive_rate\",\n distance_measure=distance_measure,\n reduction=reduction,\n allow_y_true_none=False,\n allow_distance_measure_none=False,\n )" }, { "identifier": "GuardianAITypeError", "path": "guardian_ai/utils/exception.py", "snippet": "class GuardianAITypeError(TypeError, GuardianAIError):\n \"\"\"Exception raised for generic type issues.\"\"\"\n\n pass" }, { "identifier": "GuardianAIValueError", "path": "guardian_ai/utils/exception.py", "snippet": "class GuardianAIValueError(ValueError, GuardianAIError):\n \"\"\"Exception raised for unexpected values.\"\"\"\n\n pass" }, { "identifier": "get_dummy_dataset", "path": "tests/utils.py", "snippet": "def get_dummy_dataset(\n n_samples=5000,\n n_features=10,\n n_classes=2,\n types=[str, float, bool, int],\n content=[],\n contain_null=False,\n null_ratio=0.3,\n dtime_types=[],\n tz_aware=False,\n reg_range=10.0,\n cat_range=30,\n random_seed=9999,\n imb_factor=1.0,\n task=\"classification\",\n **kwargs,\n):\n \"\"\"\n Generates a dummy dataset and returns its corresponding ope/oml\n dataframe:\n dataset shape n_samples x n_features.\n\n types: column types you wish to generate (random number of columns=\n n_features types are generated, with at least one of each type).\n\n content: list of tuples (dtype, feature) specifying bad column\n features. Features can be 'const' - to make all values in column\n constant, or value between 0 and 1 which indicates percentage of\n missing values in a column\n\n dtime_types: datetime column types to generate. Acceptable types\n are: ['datetime', 'date', 'time', 'timedelta', 'datetimetz']\n\n n_classes: number of target classes (only used for classification)\n\n reg_range: range of target for regression datasets, not used for\n classification\n\n cat_range: maximum number of unique values for the categorical\n features\n\n imb_factor: ~ class_ratio = minority_class_size/majority_class_size\n approximately controls dataset target imbalance\n (only used for classification).\n\n \"\"\"\n np.random.seed(random_seed)\n allowed_dtime_types = [\n \"datetime\",\n \"date\",\n \"time\",\n \"timedelta\",\n \"datetimez\",\n \"Timestamp\",\n ]\n\n # sanity checks\n assert (\n n_samples >= n_classes\n ), \"Number of samples has to be greater than num of classes\"\n assert (imb_factor > 0) and (\n imb_factor <= 1.0\n ), \"imb_factor has to be in range of (0, 1.0]\"\n assert len(types) == len(set(types)), \"types inside the list must be unique\"\n assert len(dtime_types) == len(\n set(dtime_types)\n ), \"dtime_types inside the list must be unique\"\n assert (\n len(dtime_types) + len(types) <= n_features\n ), \"provided number of feature types is more than n_features\"\n assert task in [\n \"classification\",\n \"regression\",\n \"anomaly_detection\",\n ], \"Task must be one of classification or regression\"\n assert all(\n x for x in dtime_types if x in allowed_dtime_types\n ), \"dtime_types: {} outside of allowed: {}\".format(dtime_types, allowed_dtime_types)\n\n extra_types, extra_feats, extra_cols = [], [], 0\n if content != []:\n extra_cols = len(content)\n extra_types = [x for x, _ in content]\n extra_feats = [x for _, x in content]\n\n # target labels for the dataset\n if task == \"classification\" or task == \"anomaly_detection\":\n # assign class counts based on geometric distribution of classes based on imb_factor\n class_weights = np.geomspace(imb_factor, 1.0, num=n_classes)\n class_counts = [\n max(1, int(n_samples * x / np.sum(class_weights))) for x in class_weights\n ]\n class_excess = np.sum(class_counts) - n_samples\n class_counts[-1] -= class_excess\n\n # create labels based on class counts and shuffle them\n y = np.hstack(\n [np.full((1, count), cl) for cl, count in enumerate(class_counts)]\n ).ravel()\n np.random.shuffle(y.astype(int))\n y = y.tolist()\n elif task == \"regression\":\n # noise between (-reg_range/2, reg_range/2) for regression\n y = reg_range * np.random.random(size=(1, n_samples, 1)) + reg_range / 2.0\n y = y.reshape(1, n_samples).ravel().tolist()\n\n # tally total number of features\n all_feat_types = types + dtime_types + extra_types\n total_feat_types = len(types) + len(dtime_types)\n if total_feat_types > 0:\n feat_col_types = np.random.choice(\n range(0, total_feat_types), size=n_features - total_feat_types\n ).tolist()\n feat_col_types += list(\n range(0, total_feat_types)\n ) # to ensure at least one of each type\n\n else:\n feat_col_types = []\n feat_col_types += list(range(total_feat_types, total_feat_types + len(extra_types)))\n features = []\n col_types = []\n tz = {}\n # extra_features provided in content, and certain datetime columns are handled differently\n # they get added as pandas Series or DataFrames to rest of features in the end\n special_cols_num, special_pd_df = [], []\n extra_features = pd.DataFrame()\n for i, t in enumerate(feat_col_types):\n assert t < total_feat_types + len(extra_types)\n typ = all_feat_types[t]\n if typ is str:\n high_val = np.random.randint(3, cat_range)\n feat = np.random.randint(0, high_val, size=n_samples).tolist()\n feat = [\"STR{}\".format(val) for val in feat]\n elif typ is int:\n low_val = np.random.randint(-50000, -10)\n high_val = np.random.randint(10, 50000)\n feat = np.random.randint(low_val, high_val, size=n_samples).tolist()\n elif typ is float:\n feat = np.random.rand(n_samples).tolist()\n elif typ is bool:\n feat = np.random.randint(0, 2, size=n_samples).tolist()\n feat = [bool(val) for val in feat]\n elif typ in allowed_dtime_types:\n if typ == \"datetime\":\n # generating random datetime\n deltas = random.sample(range(1, 172800000), n_samples)\n d1 = datetime.datetime.now() - datetime.timedelta(days=2000)\n d2 = datetime.datetime.now()\n generated_datetime = []\n for d in deltas:\n generated_datetime.append(d1 + datetime.timedelta(seconds=d))\n feat = generated_datetime\n elif typ == \"timedelta\":\n feat = n_samples * [datetime.timedelta()]\n elif typ == \"time\":\n feat = n_samples * [datetime.time()]\n elif typ == \"date\":\n feat = n_samples * [datetime.date(2019, 9, 11)]\n elif typ == \"datetimez\":\n special_cols_num.append(i)\n special_pd_df.append(\n pd.date_range(start=0, periods=n_samples, tz=\"UTC\")\n )\n feat = n_samples * [\n datetime.date(2019, 9, 11)\n ] # needs to be handled in special way b/c it's already pandas obj\n else:\n raise Exception(\"Unrecognized datetime type of column\")\n else:\n raise Exception(\"Unrecognized type of column\")\n\n # If index reached the last extra_col number of feature types, start modifying features\n # and adding them to extra_features DataFrame instead of list of features\n if extra_cols > 0 and i >= (len(feat_col_types) - extra_cols):\n feat_idx = i - (len(feat_col_types) - extra_cols)\n if isinstance(extra_feats[feat_idx], numbers.Number):\n # missing values given by extra_feats[feat_idx] percentage of instances\n assert (\n extra_feats[feat_idx] <= 1.0 and extra_feats[feat_idx] >= 0\n ), \"feature in content has to be ratio between 0 and 1\"\n ids = np.random.choice(\n range(0, n_samples), size=int(extra_feats[feat_idx] * n_samples)\n ).astype(int)\n dtype = map_col_types([extra_types[feat_idx].__name__])[0]\n feat = pd.Series(data=np.array(feat), dtype=dtype)\n feat[ids] = np.nan\n elif extra_feats[feat_idx] == \"const\":\n # constant column, set all rows to be same as the first instance\n dtype = map_col_types([extra_types[feat_idx].__name__])[0]\n feat = pd.Series(data=np.array(feat), dtype=dtype)\n feat = feat[0]\n extra_features[i] = feat\n else: # add features to the list\n features.append(feat)\n col_types.append(type(feat[0]).__name__)\n\n # if task == 'regression':\n # # Add scaled target column for regression so that score is positive\n # features.append([-0.5*x for x in y])\n # col_types.append('float') # target column type is int\n\n # Add target column and convert all types to pandas dtypes\n features.append(y)\n col_types.append(\n \"int\" if task == \"classification\" else \"float\"\n ) # target column type is int\n pd_col_types = map_col_types(col_types)\n pd_df = pd.DataFrame(features).T # transpose to get samples x features\n num_feats = len(features) - 1\n columns = list(range(0, num_feats)) if num_feats > 0 else []\n columns = columns + [\"target\"]\n pd_df.columns = columns # rename columns\n\n # handle special column from datettime: replace placeholder with pandas.date_range columns\n for i, col in enumerate(special_cols_num):\n pd_df[col] = special_pd_df[i]\n pd_col_types[col] = pd_df.dtypes[col]\n\n # assign datatypes to pd dataframe for non-datetime types\n columns_types_all = list(zip(columns, pd_col_types))\n columns_types_nodtime = [\n (name, typ)\n for (name, typ) in columns_types_all\n if typ not in allowed_dtime_types\n ]\n columns_types_dtime = [\n (name, typ) for (name, typ) in columns_types_all if typ in allowed_dtime_types\n ]\n pd_df = pd_df.astype(dict(columns_types_nodtime)) # cast types on non-dtime columns\n\n # assign datatypes to pd dataframe only for datetime types\n for col, col_type in columns_types_dtime:\n if col_type == \"timedelta\":\n pd_df[col] = pd.to_timedelta(pd_df[col], errors=\"coerce\")\n elif col_type == \"datetimez\":\n pd_df[col] = pd_df[col]\n elif col_type == \"datetime\":\n pd_df[col] = pd.to_datetime(pd_df[col], errors=\"coerce\")\n if contain_null:\n pd_df[col] = generate_null(pd_df[col], null_ratio)\n if tz_aware:\n tz[str(col)] = pytz.all_timezones[\n np.random.randint(len(pytz.all_timezones))\n ]\n else:\n pd_df[col] = pd.to_timedelta(pd_df[col], errors=\"coerce\")\n\n # add extra features columns that were provided by content\n pd_df[pd_df.shape[1] + extra_features.columns] = extra_features\n\n # Convert all the column names to string type (mainly for FS min_features [] tests)\n pd_df.columns = [str(col) for col in pd_df.columns]\n\n if tz_aware:\n return pd_df.drop([\"target\"], axis=1), pd_df[\"target\"], tz\n else:\n return pd_df.drop([\"target\"], axis=1), pd_df[\"target\"]" } ]
import math import numpy as np import pandas as pd import pytest import sklearn from sklearn.pipeline import Pipeline from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import OneHotEncoder from guardian_ai.fairness.metrics.dataset import ( ConsistencyScorer, DatasetStatisticalParityScorer, SmoothedEDFScorer, consistency, dataset_statistical_parity, smoothed_edf, ) from guardian_ai.fairness.metrics.model import ( EqualizedOddsScorer, ErrorRateScorer, FalseDiscoveryRateScorer, FalseNegativeRateScorer, FalseOmissionRateScorer, FalsePositiveRateScorer, ModelStatisticalParityScorer, TheilIndexScorer, TruePositiveRateScorer, equalized_odds, error_rate, false_discovery_rate, false_negative_rate, false_omission_rate, false_positive_rate, model_statistical_parity, theil_index, true_positive_rate, ) from guardian_ai.utils.exception import GuardianAITypeError, GuardianAIValueError from tests.utils import get_dummy_dataset
18,505
#!/usr/bin/env python # -*- coding: utf-8 -*-- # Copyright (c) 2023 Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ @pytest.fixture(scope="module", autouse=True) def init(): np.random.seed(12345) def is_close(a, b): return math.isclose(a, b, rel_tol=1e-5) def approx_dict(d): return pytest.approx(d, rel=1e-5) MODEL_X_Y_SCORERS = { "model_statistical_parity_scorer": ModelStatisticalParityScorer, "true_positive_rate_scorer": TruePositiveRateScorer, "false_positive_rate_scorer": FalsePositiveRateScorer, "false_negative_rate_scorer": FalseNegativeRateScorer, "false_omission_rate_scorer": FalseOmissionRateScorer, "false_discovery_rate_scorer": FalseDiscoveryRateScorer, "error_rate_scorer": ErrorRateScorer, "equalized_odds_scorer": EqualizedOddsScorer, "theil_index_scorer": TheilIndexScorer, } MODEL_SUBGROUPS_SCORERS = { "model_statistical_parity_scorer": model_statistical_parity, "true_positive_rate_scorer": true_positive_rate,
#!/usr/bin/env python # -*- coding: utf-8 -*-- # Copyright (c) 2023 Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ @pytest.fixture(scope="module", autouse=True) def init(): np.random.seed(12345) def is_close(a, b): return math.isclose(a, b, rel_tol=1e-5) def approx_dict(d): return pytest.approx(d, rel=1e-5) MODEL_X_Y_SCORERS = { "model_statistical_parity_scorer": ModelStatisticalParityScorer, "true_positive_rate_scorer": TruePositiveRateScorer, "false_positive_rate_scorer": FalsePositiveRateScorer, "false_negative_rate_scorer": FalseNegativeRateScorer, "false_omission_rate_scorer": FalseOmissionRateScorer, "false_discovery_rate_scorer": FalseDiscoveryRateScorer, "error_rate_scorer": ErrorRateScorer, "equalized_odds_scorer": EqualizedOddsScorer, "theil_index_scorer": TheilIndexScorer, } MODEL_SUBGROUPS_SCORERS = { "model_statistical_parity_scorer": model_statistical_parity, "true_positive_rate_scorer": true_positive_rate,
"false_positive_rate_scorer": false_positive_rate,
20
2023-10-09 09:48:50+00:00
24k
jiangjiechen/auction-arena
app.py
[ { "identifier": "create_items", "path": "src/item_base.py", "snippet": "def create_items(item_info_jsl):\n '''\n item_info: a list of dict (name, price, desc, id)\n '''\n item_info_jsl = LoadJsonL(item_info_jsl)\n item_list = []\n for info in item_info_jsl:\n item_list.append(Item(**info))\n return item_list" }, { "identifier": "Bidder", "path": "src/bidder_base.py", "snippet": "class Bidder(BaseModel):\n name: str\n model_name: str \n budget: int \n desire: str\n plan_strategy: str\n temperature: float = 0.7\n overestimate_percent: int = 10\n correct_belief: bool\n enable_learning: bool = False\n \n llm: BaseLanguageModel = None\n openai_cost = 0\n llm_token_count = 0\n \n verbose: bool = False\n auction_hash: str = ''\n\n system_message: str = ''\n original_budget: int = 0\n\n # working memory\n profit: int = 0\n cur_item_id = 0\n items: list = []\n dialogue_history: list = [] # for gradio UI display\n llm_prompt_history: list = [] # for tracking llm calling\n items_won = []\n bid_history: list = [] # history of the bidding of a single item\n plan_instruct: str = '' # instruction for planning\n cur_plan: str = '' # current plan\n status_quo: dict = {} # belief of budget and profit, self and others\n withdraw: bool = False # state of withdraw\n learnings: str = '' # learnings from previous biddings. If given, then use it to guide the rest of the auction.\n max_bid_cnt: int = 4 # Rule Bidder: maximum number of bids on one item (K = 1 starting bid + K-1 increase bid)\n rule_bid_cnt: int = 0 # Rule Bidder: count of bids on one item\n\n # belief tracking\n failed_bid_cnt: int = 0 # count of failed bids (overspending)\n total_bid_cnt: int = 0 # count of total bids\n self_belief_error_cnt: int = 0\n total_self_belief_cnt: int = 0\n other_belief_error_cnt: int = 0\n total_other_belief_cnt: int = 0\n \n engagement_count: int = 0\n budget_history = []\n profit_history = []\n budget_error_history = []\n profit_error_history = []\n win_bid_error_history = []\n engagement_history = defaultdict(int)\n all_bidders_status = {} # track others' profit\n changes_of_plan = []\n \n # not used\n input_box: str = None\n need_input = False\n semaphore = 0\n\n class Config:\n arbitrary_types_allowed = True\n\n def __repr__(self):\n return self.name\n\n def __str__(self):\n return self.name\n \n @classmethod\n def create(cls, **data):\n instance = cls(**data)\n instance._post_init()\n return instance\n\n def _post_init(self):\n self.original_budget = self.budget\n self.system_message = SYSTEM_MESSAGE.format(\n name=self.name,\n desire_desc=DESIRE_DESC[self.desire],\n )\n self._parse_llm()\n self.dialogue_history += [\n SystemMessage(content=self.system_message), \n AIMessage(content='')\n ]\n self.budget_history.append(self.budget)\n self.profit_history.append(self.profit)\n\n def _parse_llm(self):\n if 'gpt-' in self.model_name:\n self.llm = ChatOpenAI(model=self.model_name, temperature=self.temperature, max_retries=30, request_timeout=1200)\n elif 'claude' in self.model_name:\n self.llm = ChatAnthropic(model=self.model_name, temperature=self.temperature, default_request_timeout=1200)\n elif 'bison' in self.model_name:\n self.llm = ChatGooglePalm(model_name=f'models/{self.model_name}', temperature=self.temperature)\n elif 'rule' in self.model_name or 'human' in self.model_name:\n self.llm = None\n else:\n raise NotImplementedError(self.model_name)\n \n # def _rotate_openai_org(self):\n # # use two organizations to avoid rate limit\n # if os.environ.get('OPENAI_ORGANIZATION_1') and os.environ.get('OPENAI_ORGANIZATION_2'):\n # return random.choice([os.environ.get('OPENAI_ORGANIZATION_1'), os.environ.get('OPENAI_ORGANIZATION_2')])\n # else:\n # return None\n \n def _run_llm_standalone(self, messages: list):\n \n with get_openai_callback() as cb:\n for i in range(6):\n try:\n input_token_num = self.llm.get_num_tokens_from_messages(messages)\n if 'claude' in self.model_name: # anthropic's claude\n result = self.llm(messages, max_tokens_to_sample=2048)\n elif 'bison' in self.model_name: # google's palm-2\n max_tokens = min(max(3900 - input_token_num, 192), 2048)\n if isinstance(self.llm, ChatVertexAI):\n result = self.llm(messages, max_output_tokens=max_tokens)\n else:\n result = self.llm(messages)\n elif 'gpt' in self.model_name: # openai\n if 'gpt-3.5-turbo' in self.model_name and '16k' not in self.model_name:\n max_tokens = max(3900 - input_token_num, 192)\n else:\n # gpt-4\n # self.llm.openai_organization = self._rotate_openai_org()\n max_tokens = max(8000 - input_token_num, 192)\n result = self.llm(messages, max_tokens=max_tokens)\n elif 'llama' in self.model_name.lower():\n raise NotImplementedError\n else:\n raise NotImplementedError\n break\n except:\n print(f'Retrying for {self.model_name} ({i+1}/6), wait for {2**(i+1)} sec...')\n time.sleep(2**(i+1))\n self.openai_cost += cb.total_cost\n self.llm_token_count = self.llm.get_num_tokens_from_messages(messages)\n return result.content\n\n def _get_estimated_value(self, item):\n value = item.true_value * (1 + self.overestimate_percent / 100)\n return int(value)\n \n def _get_cur_item(self, key=None):\n if self.cur_item_id < len(self.items):\n if key is not None:\n return self.items[self.cur_item_id].__dict__[key]\n else:\n return self.items[self.cur_item_id]\n else:\n return 'no item left'\n \n def _get_next_item(self, key=None):\n if self.cur_item_id + 1 < len(self.items):\n if key is not None:\n return self.items[self.cur_item_id + 1].__dict__[key]\n else:\n return self.items[self.cur_item_id + 1]\n else:\n return 'no item left'\n \n def _get_remaining_items(self, as_str=False):\n remain_items = self.items[self.cur_item_id + 1:]\n if as_str:\n return ', '.join([item.name for item in remain_items])\n else:\n return remain_items\n \n def _get_items_value_str(self, items: List[Item]):\n if not isinstance(items, list):\n items = [items]\n items_info = ''\n for i, item in enumerate(items):\n estimated_value = self._get_estimated_value(item)\n _info = f\"{i+1}. {item}, starting price is ${item.price}. Your estimated value for this item is ${estimated_value}.\\n\"\n items_info += _info\n return items_info.strip()\n \n # ********** Main Instructions and Functions ********** #\n \n def learn_from_prev_auction(self, past_learnings, past_auction_log):\n if not self.enable_learning or 'rule' in self.model_name or 'human' in self.model_name:\n return ''\n \n instruct_learn = INSTRUCT_LEARNING_TEMPLATE.format(\n past_auction_log=past_auction_log,\n past_learnings=past_learnings)\n\n result = self._run_llm_standalone([HumanMessage(content=instruct_learn)])\n self.dialogue_history += [\n HumanMessage(content=instruct_learn),\n AIMessage(content=result),\n ]\n self.llm_prompt_history.append({\n 'messages': [{x.type: x.content} for x in [HumanMessage(content=instruct_learn)]],\n 'result': result,\n 'tag': 'learn_0'\n })\n \n self.learnings = '\\n'.join(extract_numbered_list(result))\n if self.learnings != '':\n self.system_message += f\"\\n\\nHere are your key learning points and practical tips from a previous auction. You can use them to guide this auction:\\n```\\n{self.learnings}\\n```\"\n \n if self.verbose:\n print(f\"Learn from previous auction: {self.name} ({self.model_name}).\")\n return result\n\n def _choose_items(self, budget, items: List[Item]):\n '''\n Choose items within budget for rule bidders.\n Cheap ones first if maximize_items, expensive ones first if maximize_profit.\n '''\n sorted_items = sorted(items, key=lambda x: self._get_estimated_value(x), \n reverse=self.desire == 'maximize_profit')\n \n chosen_items = []\n i = 0\n while budget >= 0 and i < len(sorted_items):\n item = sorted_items[i]\n if item.price <= budget:\n chosen_items.append(item)\n budget -= item.price\n i += 1\n \n return chosen_items\n \n def get_plan_instruct(self, items: List[Item]):\n self.items = items\n plan_instruct = INSTRUCT_PLAN_TEMPLATE.format(\n bidder_name=self.name, \n budget=self.budget, \n item_num=len(items), \n items_info=self._get_items_value_str(items), \n desire_desc=DESIRE_DESC[self.desire],\n learning_statement='' if not self.enable_learning else _LEARNING_STATEMENT\n )\n return plan_instruct\n \n def init_plan(self, plan_instruct: str):\n '''\n Plan for bidding with auctioneer's instruction and items information for customize estimated value.\n plan = plan(system_message, instruct_plan)\n '''\n if 'rule' in self.model_name: \n # self.cur_plan = ', '.join([x.name for x in self._choose_items(self.budget, self.items)])\n # self.dialogue_history += [\n # HumanMessage(content=plan_instruct),\n # AIMessage(content=self.cur_plan),\n # ]\n # return self.cur_plan\n return ''\n\n self.status_quo = {\n 'remaining_budget': self.budget,\n 'total_profits': {bidder: 0 for bidder in self.all_bidders_status.keys()},\n 'winning_bids': {bidder: {} for bidder in self.all_bidders_status.keys()},\n }\n\n if self.plan_strategy == 'none':\n self.plan_instruct = ''\n self.cur_plan = ''\n return None\n\n system_msg = SystemMessage(content=self.system_message)\n plan_msg = HumanMessage(content=plan_instruct)\n messages = [system_msg, plan_msg]\n result = self._run_llm_standalone(messages)\n \n if self.verbose:\n print(get_colored_text(plan_msg.content, 'red'))\n print(get_colored_text(result, 'green'))\n \n self.dialogue_history += [\n plan_msg,\n AIMessage(content=result),\n ]\n self.llm_prompt_history.append({\n 'messages': [{x.type: x.content} for x in messages],\n 'result': result,\n 'tag': 'plan_0'\n })\n self.cur_plan = result\n self.plan_instruct = plan_instruct\n \n self.changes_of_plan.append([\n f\"{self.cur_item_id} (Initial)\", \n False, \n json.dumps(extract_jsons_from_text(result)[-1]),\n ])\n \n if self.verbose:\n print(f\"Plan: {self.name} ({self.model_name}) for {self._get_cur_item()}.\")\n return result\n \n def get_rebid_instruct(self, auctioneer_msg: str):\n self.dialogue_history += [\n HumanMessage(content=auctioneer_msg),\n AIMessage(content='')\n ]\n return auctioneer_msg\n\n def get_bid_instruct(self, auctioneer_msg: str, bid_round: int):\n auctioneer_msg = auctioneer_msg.replace(self.name, f'You ({self.name})')\n \n bid_instruct = INSTRUCT_BID_TEMPLATE.format(\n auctioneer_msg=auctioneer_msg, \n bidder_name=self.name,\n cur_item=self._get_cur_item(),\n estimated_value=self._get_estimated_value(self._get_cur_item()),\n desire_desc=DESIRE_DESC[self.desire],\n learning_statement='' if not self.enable_learning else _LEARNING_STATEMENT\n )\n if bid_round == 0:\n if self.plan_strategy in ['static', 'none']:\n # if static planner, then no replanning is needed. status quo is updated in replanning. thus need to add status quo in bid instruct.\n bid_instruct = f\"\"\"The status quo of this auction so far is:\\n\"{json.dumps(self.status_quo, indent=4)}\"\\n\\n{bid_instruct}\\n---\\n\"\"\"\n else:\n bid_instruct = f'Now, the auctioneer says: \"{auctioneer_msg}\"'\n \n self.dialogue_history += [\n HumanMessage(content=bid_instruct),\n AIMessage(content='')\n ]\n return bid_instruct\n \n def bid_rule(self, cur_bid: int, min_markup_pct: float = 0.1):\n '''\n :param cur_bid: current highest bid\n :param min_markup_pct: minimum percentage for bid increase\n :param max_bid_cnt: maximum number of bids on one item (K = 1 starting bid + K-1 increase bid)\n '''\n # dialogue history already got bid_instruction.\n cur_item = self._get_cur_item()\n \n if cur_bid <= 0:\n next_bid = cur_item.price\n else:\n next_bid = cur_bid + min_markup_pct * cur_item.price\n \n if self.budget - next_bid >= 0 and self.rule_bid_cnt < self.max_bid_cnt:\n msg = int(next_bid)\n self.rule_bid_cnt += 1\n else:\n msg = -1\n \n content = f'The current highest bid for {cur_item.name} is ${cur_bid}. '\n content += \"I'm out!\" if msg < 0 else f\"I bid ${msg}! (Rule generated)\"\n self.dialogue_history += [\n HumanMessage(content=''),\n AIMessage(content=content)\n ]\n \n return msg\n \n def bid(self, bid_instruct):\n '''\n Bid for an item with auctioneer's instruction and bidding history.\n bid_history = bid(system_message, instruct_plan, plan, bid_history)\n '''\n if self.model_name == 'rule':\n return ''\n \n bid_msg = HumanMessage(content=bid_instruct)\n \n if self.plan_strategy == 'none':\n messages = [SystemMessage(content=self.system_message)]\n else:\n messages = [SystemMessage(content=self.system_message),\n HumanMessage(content=self.plan_instruct),\n AIMessage(content=self.cur_plan)]\n \n self.bid_history += [bid_msg]\n messages += self.bid_history\n \n result = self._run_llm_standalone(messages)\n \n self.bid_history += [AIMessage(content=result)]\n\n self.dialogue_history += [\n HumanMessage(content=''),\n AIMessage(content=result)\n ]\n \n self.llm_prompt_history.append({\n 'messages': [{x.type: x.content} for x in messages],\n 'result': result,\n 'tag': f'bid_{self.cur_item_id}'\n })\n \n if self.verbose:\n print(get_colored_text(bid_instruct, 'yellow'))\n print(get_colored_text(result, 'green'))\n \n print(f\"Bid: {self.name} ({self.model_name}) for {self._get_cur_item()}.\")\n self.total_bid_cnt += 1\n \n return result\n\n def get_summarize_instruct(self, bidding_history: str, hammer_msg: str, win_lose_msg: str):\n instruct = INSTRUCT_SUMMARIZE_TEMPLATE.format(\n cur_item=self._get_cur_item(), \n bidding_history=bidding_history, \n hammer_msg=hammer_msg.strip(), \n win_lose_msg=win_lose_msg.strip(), \n bidder_name=self.name,\n prev_status=self._status_json_to_text(self.status_quo),\n )\n return instruct\n\n def summarize(self, instruct_summarize: str):\n '''\n Update belief/status quo\n status_quo = summarize(system_message, bid_history, prev_status + instruct_summarize)\n '''\n self.budget_history.append(self.budget)\n self.profit_history.append(self.profit)\n \n if self.model_name == 'rule': \n self.rule_bid_cnt = 0 # reset bid count for rule bidder\n return ''\n \n messages = [SystemMessage(content=self.system_message)]\n # messages += self.bid_history\n summ_msg = HumanMessage(content=instruct_summarize)\n messages.append(summ_msg)\n\n status_quo_text = self._run_llm_standalone(messages)\n \n self.dialogue_history += [summ_msg, AIMessage(content=status_quo_text)]\n self.bid_history += [summ_msg, AIMessage(content=status_quo_text)]\n \n self.llm_prompt_history.append({\n 'messages': [{x.type: x.content} for x in messages],\n 'result': status_quo_text,\n 'tag': f'summarize_{self.cur_item_id}'\n })\n\n cnt = 0\n while cnt <= 3:\n sanity_msg = self._sanity_check_status_json(extract_jsons_from_text(status_quo_text)[-1])\n if sanity_msg == '':\n # pass sanity check then track beliefs\n consistency_msg = self._belief_tracking(status_quo_text)\n else:\n sanity_msg = f'- {sanity_msg}'\n consistency_msg = ''\n \n if sanity_msg != '' or (consistency_msg != '' and self.correct_belief):\n err_msg = f\"As {self.name}, here are some error(s) of your summary of the status JSON:\\n{sanity_msg.strip()}\\n{consistency_msg.strip()}\\n\\nPlease revise the status JSON based on the errors. Don't apologize. Just give me the revised status JSON.\".strip()\n \n # print(f\"{self.name}: revising status quo for the {cnt} time:\")\n # print(get_colored_text(err_msg, 'green'))\n # print(get_colored_text(status_quo_text, 'red'))\n \n messages += [AIMessage(content=status_quo_text), \n HumanMessage(content=err_msg)]\n status_quo_text = self._run_llm_standalone(messages)\n self.dialogue_history += [\n HumanMessage(content=err_msg),\n AIMessage(content=status_quo_text),\n ]\n cnt += 1\n else:\n break\n \n self.status_quo = extract_jsons_from_text(status_quo_text)[-1]\n\n if self.verbose:\n print(get_colored_text(instruct_summarize, 'blue'))\n print(get_colored_text(status_quo_text, 'green'))\n \n print(f\"Summarize: {self.name} ({self.model_name}) for {self._get_cur_item()}.\")\n \n return status_quo_text\n \n def get_replan_instruct(self):\n instruct = INSTRUCT_REPLAN_TEMPLATE.format(\n status_quo=self._status_json_to_text(self.status_quo),\n remaining_items_info=self._get_items_value_str(self._get_remaining_items()),\n bidder_name=self.name,\n desire_desc=DESIRE_DESC[self.desire],\n learning_statement='' if not self.enable_learning else _LEARNING_STATEMENT\n )\n return instruct\n\n def replan(self, instruct_replan: str):\n '''\n plan = replan(system_message, instruct_plan, prev_plan, status_quo + (learning) + instruct_replan)\n '''\n if self.model_name == 'rule': \n self.withdraw = False\n self.cur_item_id += 1\n return ''\n \n if self.plan_strategy in ['none', 'static']:\n self.bid_history = [] # clear bid history\n self.cur_item_id += 1\n self.withdraw = False\n return 'Skip replanning for bidders with static or no plan.'\n \n replan_msg = HumanMessage(content=instruct_replan)\n \n messages = [SystemMessage(content=self.system_message),\n HumanMessage(content=self.plan_instruct),\n AIMessage(content=self.cur_plan)]\n messages.append(replan_msg)\n\n result = self._run_llm_standalone(messages)\n \n new_plan_dict = extract_jsons_from_text(result)[-1]\n cnt = 0\n while len(new_plan_dict) == 0 and cnt < 2:\n err_msg = 'Your response does not contain a JSON-format priority list for items. Please revise your plan.'\n messages += [\n AIMessage(content=result),\n HumanMessage(content=err_msg),\n ]\n result = self._run_llm_standalone(messages)\n new_plan_dict = extract_jsons_from_text(result)[-1]\n \n self.dialogue_history += [\n HumanMessage(content=err_msg),\n AIMessage(content=result),\n ]\n cnt += 1\n \n old_plan_dict = extract_jsons_from_text(self.cur_plan)[-1]\n self.changes_of_plan.append([\n f\"{self.cur_item_id + 1} ({self._get_cur_item('name')})\", \n self._change_of_plan(old_plan_dict, new_plan_dict),\n json.dumps(new_plan_dict)\n ])\n \n self.plan_instruct = instruct_replan\n self.cur_plan = result\n self.withdraw = False\n self.bid_history = [] # clear bid history\n self.cur_item_id += 1\n\n self.dialogue_history += [\n replan_msg,\n AIMessage(content=result),\n ]\n self.llm_prompt_history.append({\n 'messages': [{x.type: x.content} for x in messages],\n 'result': result,\n 'tag': f'plan_{self.cur_item_id}'\n })\n \n if self.verbose:\n print(get_colored_text(instruct_replan, 'blue'))\n print(get_colored_text(result, 'green'))\n\n print(f\"Replan: {self.name} ({self.model_name}).\")\n return result\n \n def _change_of_plan(self, old_plan: dict, new_plan: dict):\n for k in new_plan:\n if new_plan[k] != old_plan.get(k, None):\n return True\n return False\n \n # *********** Belief Tracking and Sanity Check *********** #\n \n def bid_sanity_check(self, bid_price, prev_round_max_bid, min_markup_pct):\n # can't bid more than budget or less than previous highest bid\n if bid_price < 0:\n msg = None\n else:\n min_bid_increase = int(min_markup_pct * self._get_cur_item('price'))\n if bid_price > self.budget:\n msg = f\"you don't have insufficient budget (${self.budget} left)\"\n elif bid_price < self._get_cur_item('price'):\n msg = f\"your bid is lower than the starting bid (${self._get_cur_item('price')})\"\n elif bid_price < prev_round_max_bid + min_bid_increase:\n msg = f\"you must advance previous highest bid (${prev_round_max_bid}) by at least ${min_bid_increase} ({int(100 * min_markup_pct)}%).\"\n else:\n msg = None\n return msg\n\n def rebid_for_failure(self, fail_instruct: str):\n result = self.bid(fail_instruct)\n self.failed_bid_cnt += 1\n return result\n \n def _sanity_check_status_json(self, data: dict):\n if data == {}:\n return \"Error: No parsible JSON in your response. Possibly due to missing a closing curly bracket '}', or unpasible values (e.g., 'profit': 1000 + 400, instead of 'profit': 1400).\"\n\n # Check if all expected top-level keys are present\n expected_keys = [\"remaining_budget\", \"total_profits\", \"winning_bids\"]\n for key in expected_keys:\n if key not in data:\n return f\"Error: Missing '{key}' field in the status JSON.\"\n\n # Check if \"remaining_budget\" is a number\n if not isinstance(data[\"remaining_budget\"], (int, float)):\n return \"Error: 'remaining_budget' should be a number, and only about your remaining budget.\"\n\n # Check if \"total_profits\" is a dictionary with numbers as values\n if not isinstance(data[\"total_profits\"], dict):\n return \"Error: 'total_profits' should be a dictionary of every bidder.\"\n for bidder, profit in data[\"total_profits\"].items():\n if not isinstance(profit, (int, float)):\n return f\"Error: Profit for {bidder} should be a number.\"\n\n # Check if \"winning_bids\" is a dictionary and that each bidder's entry is a dictionary with numbers\n if not isinstance(data[\"winning_bids\"], dict):\n return \"Error: 'winning_bids' should be a dictionary.\"\n for bidder, bids in data[\"winning_bids\"].items():\n if not isinstance(bids, dict):\n return f\"Error: Bids for {bidder} should be a dictionary.\"\n for item, amount in bids.items():\n if not isinstance(amount, (int, float)):\n return f\"Error: Amount for {item} under {bidder} should be a number.\"\n\n # If everything is fine\n return \"\"\n \n def _status_json_to_text(self, data: dict):\n if 'rule' in self.model_name: return ''\n \n # Extract and format remaining budget\n structured_text = f\"* Remaining Budget: ${data.get('remaining_budget', 'unknown')}\\n\\n\"\n \n # Extract and format total profits for each bidder\n structured_text += \"* Total Profits:\\n\"\n if data.get('total_profits'):\n for bidder, profit in data['total_profits'].items():\n structured_text += f\" * {bidder}: ${profit}\\n\"\n \n # Extract and list the winning bids for each item by each bidder\n structured_text += \"\\n* Winning Bids:\\n\"\n if data.get('winning_bids'):\n for bidder, bids in data['winning_bids'].items():\n structured_text += f\" * {bidder}:\\n\"\n if bids:\n for item, amount in bids.items():\n structured_text += f\" * {item}: ${amount}\\n\"\n else:\n structured_text += f\" * No winning bids\\n\"\n \n return structured_text.strip()\n\n def _belief_tracking(self, status_text: str):\n '''\n Parse status quo and check if the belief is correct.\n '''\n belief_json = extract_jsons_from_text(status_text)[-1]\n # {\"remaining_budget\": 8000, \"total_profits\": {\"Bidder 1\": 1300, \"Bidder 2\": 1800, \"Bidder 3\": 0}, \"winning_bids\": {\"Bidder 1\": {\"Item 2\": 1200, \"Item 3\": 1000}, \"Bidder 2\": {\"Item 1\": 2000}, \"Bidder 3\": {}}}\n budget_belief = belief_json['remaining_budget']\n profits_belief = belief_json['total_profits']\n winning_bids = belief_json['winning_bids']\n\n msg = ''\n # track belief of budget\n self.total_self_belief_cnt += 1\n if budget_belief != self.budget:\n msg += f'- Your belief of budget is wrong: you have ${self.budget} left, but you think you have ${budget_belief} left.\\n'\n self.self_belief_error_cnt += 1\n self.budget_error_history.append([\n self._get_cur_item('name'),\n budget_belief,\n self.budget,\n ])\n \n # track belief of profits\n for bidder_name, profit in profits_belief.items():\n if self.all_bidders_status.get(bidder_name) is None:\n # due to a potentially unreasonable parsing\n continue\n \n if self.name in bidder_name: \n bidder_name = self.name\n self.total_self_belief_cnt += 1\n else:\n self.total_other_belief_cnt += 1\n \n real_profit = self.all_bidders_status[bidder_name]['profit']\n \n if profit != real_profit:\n if self.name == bidder_name:\n self.self_belief_error_cnt += 1\n else:\n self.other_belief_error_cnt += 1\n\n msg += f'- Your belief of total profit of {bidder_name} is wrong: {bidder_name} has earned ${real_profit} so far, but you think {bidder_name} has earned ${profit}.\\n'\n\n # add to history\n self.profit_error_history.append([\n f\"{bidder_name} ({self._get_cur_item('name')})\",\n profit,\n real_profit\n ])\n\n # track belief of winning bids\n for bidder_name, items_won_dict in winning_bids.items():\n if self.all_bidders_status.get(bidder_name) is None:\n # due to a potentially unreasonable parsing\n continue\n\n real_items_won = self.all_bidders_status[bidder_name]['items_won']\n # items_won = [(item, bid_price), ...)]\n \n items_won_list = list(items_won_dict.keys())\n real_items_won_list = [str(x) for x, _ in real_items_won]\n \n if self.name in bidder_name:\n self.total_self_belief_cnt += 1\n else:\n self.total_other_belief_cnt += 1\n \n if not item_list_equal(items_won_list, real_items_won_list):\n if bidder_name == self.name:\n self.self_belief_error_cnt += 1\n _bidder_name = f'you'\n else:\n self.other_belief_error_cnt += 1\n _bidder_name = bidder_name\n \n msg += f\"- Your belief of winning items of {bidder_name} is wrong: {bidder_name} won {real_items_won}, but you think {bidder_name} won {items_won_dict}.\\n\"\n\n self.win_bid_error_history.append([\n f\"{_bidder_name} ({self._get_cur_item('name')})\",\n ', '.join(items_won_list),\n ', '.join(real_items_won_list)\n ])\n \n return msg\n \n def win_bid(self, item: Item, bid: int):\n self.budget -= bid\n self.profit += item.true_value - bid\n self.items_won += [[item, bid]]\n msg = f\"Congratuations! You won {item} at ${bid}.\"# Now you have ${self.budget} left. Your total profit so far is ${self.profit}.\"\n return msg\n \n def lose_bid(self, item: Item):\n return f\"You lost {item}.\"# Now, you have ${self.budget} left. Your total profit so far is ${self.profit}.\"\n \n # set the profit information of other bidders\n def set_all_bidders_status(self, all_bidders_status: dict):\n self.all_bidders_status = all_bidders_status.copy()\n\n def set_withdraw(self, bid: int):\n if bid < 0: # withdraw\n self.withdraw = True\n elif bid == 0: # enable discount and bid again\n self.withdraw = False\n else: # normal bid\n self.withdraw = False\n self.engagement_count += 1\n self.engagement_history[self._get_cur_item('name')] += 1\n \n # ****************** Logging ****************** #\n \n # def _parse_hedging(self, plan: str): # deprecated\n # prompt = PARSE_HEDGE_INSTRUCTION.format(\n # item_name=self._get_cur_item(), \n # plan=plan)\n \n # with get_openai_callback() as cb:\n # llm = ChatOpenAI(model='gpt-3.5-turbo-0613', temperature=0)\n # result = llm([HumanMessage(content=prompt)]).content\n # self.openai_cost += cb.total_cost\n # # parse a number, which could be a digit\n # hedge_percent = re.findall(r'\\d+\\.?\\d*%', result)\n # if len(hedge_percent) > 0:\n # hedge_percent = hedge_percent[0].replace('%', '')\n # else:\n # hedge_percent = 0\n # return float(hedge_percent)\n \n def profit_report(self):\n '''\n Personal profit report at the end of an auction.\n '''\n msg = f\"* {self.name}, starting with ${self.original_budget}, has won {len(self.items_won)} items in this auction, with a total profit of ${self.profit}.:\\n\"\n profit = 0\n for item, bid in self.items_won:\n profit += item.true_value - bid\n msg += f\" * Won {item} at ${bid} over ${item.price}, with a true value of ${item.true_value}.\\n\"\n return msg.strip()\n \n def to_monitors(self, as_json=False):\n # budget, profit, items_won, tokens\n if len(self.items_won) == 0 and not as_json: \n items_won = [['', 0, 0]]\n else:\n items_won = []\n for item, bid in self.items_won:\n items_won.append([str(item), bid, item.true_value])\n \n profit_error_history = self.profit_error_history if self.profit_error_history != [] or as_json else [['', '', '']]\n win_bid_error_history = self.win_bid_error_history if self.win_bid_error_history != [] or as_json else [['', '', '']]\n budget_error_history = self.budget_error_history if self.budget_error_history != [] or as_json else [['', '']]\n changes_of_plan = self.changes_of_plan if self.changes_of_plan != [] or as_json else [['', '', '']]\n \n if as_json:\n return {\n 'auction_hash': self.auction_hash,\n 'bidder_name': self.name,\n 'model_name': self.model_name,\n 'desire': self.desire,\n 'plan_strategy': self.plan_strategy,\n 'overestimate_percent': self.overestimate_percent,\n 'temperature': self.temperature,\n 'correct_belief': self.correct_belief,\n 'enable_learning': self.enable_learning,\n 'budget': self.original_budget,\n 'money_left': self.budget,\n 'profit': self.profit,\n 'items_won': items_won,\n 'tokens_used': self.llm_token_count,\n 'openai_cost': round(self.openai_cost, 2),\n 'failed_bid_cnt': self.failed_bid_cnt,\n 'self_belief_error_cnt': self.self_belief_error_cnt,\n 'other_belief_error_cnt': self.other_belief_error_cnt,\n 'failed_bid_rate': round(self.failed_bid_cnt / (self.total_bid_cnt+1e-8), 2),\n 'self_error_rate': round(self.self_belief_error_cnt / (self.total_self_belief_cnt+1e-8), 2),\n 'other_error_rate': round(self.other_belief_error_cnt / (self.total_other_belief_cnt+1e-8), 2),\n 'engagement_count': self.engagement_count,\n 'engagement_history': self.engagement_history,\n 'changes_of_plan': changes_of_plan,\n 'budget_error_history': budget_error_history,\n 'profit_error_history': profit_error_history,\n 'win_bid_error_history': win_bid_error_history,\n 'history': self.llm_prompt_history\n }\n else:\n return [\n self.budget, \n self.profit, \n items_won, \n self.llm_token_count, \n round(self.openai_cost, 2), \n round(self.failed_bid_cnt / (self.total_bid_cnt+1e-8), 2), \n round(self.self_belief_error_cnt / (self.total_self_belief_cnt+1e-8), 2), \n round(self.other_belief_error_cnt / (self.total_other_belief_cnt+1e-8), 2), \n self.engagement_count,\n draw_plot(f\"{self.name} ({self.model_name})\", self.budget_history, self.profit_history), \n changes_of_plan,\n budget_error_history,\n profit_error_history, \n win_bid_error_history\n ]\n\n def dialogue_to_chatbot(self):\n # chatbot: [[Human, AI], [], ...]\n # only dialogue will be sent to LLMs. chatbot is just for display.\n assert len(self.dialogue_history) % 2 == 0\n chatbot = []\n for i in range(0, len(self.dialogue_history), 2):\n # if exceeds the length of dialogue, append the last message\n human_msg = self.dialogue_history[i].content\n ai_msg = self.dialogue_history[i+1].content\n if ai_msg == '': ai_msg = None\n if human_msg == '': human_msg = None\n chatbot.append([human_msg, ai_msg])\n return chatbot" }, { "identifier": "HumanBidder", "path": "src/human_bidder.py", "snippet": "class HumanBidder(Bidder):\n name: str\n human_name: str = \"Adam\"\n budget: int\n auction_hash: str\n \n cur_item_id = 0\n items: list = []\n withdraw: bool = False\n \n engagement_count: int = 0\n original_budget: int = 0\n profit: int = 0\n items_won = []\n \n all_bidders_status = {} # track others' profit\n \n # essential for demo\n need_input: bool = False\n semaphore: int = 0 # if needs input, then semaphore is set as 1, else waits.\n input_box: str = None # global variable for accepting user input\n \n # not used\n model_name: str = 'human'\n openai_cost = 0\n desire = ''\n plan_strategy = ''\n correct_belief = True\n \n class Config:\n arbitrary_types_allowed = True\n \n def get_plan_instruct(self, items: List[Item]):\n self.items = items\n plan_instruct = \"As {bidder_name}, you have a total budget of ${budget}. This auction has a total of {item_num} items to be sequentially presented, they are:\\n{items_info}\".format(\n bidder_name=self.name, \n budget=self.budget, \n item_num=len(items), \n items_info=self._get_items_value_str(items)\n )\n return plan_instruct\n \n def init_plan(self, plan_instruct: str):\n # Human = auctioneer, AI = bidder\n self.dialogue_history += [\n HumanMessage(content=plan_instruct),\n AIMessage(content='(Getting ready...)')\n ]\n return ''\n \n def get_bid_instruct(self, auctioneer_msg, bid_round):\n self.dialogue_history += [\n HumanMessage(content=auctioneer_msg), \n AIMessage(content='')\n ]\n return auctioneer_msg\n \n def bid(self, bid_instruct):\n # wait for the cue to handle user input\n while self.semaphore <= 0:\n time.sleep(1)\n \n self.dialogue_history += [\n HumanMessage(content=''),\n AIMessage(content=self.input_box)\n ]\n self.semaphore -= 1\n self.need_input = False\n return self.input_box\n \n def get_summarize_instruct(self, bidding_history: str, hammer_msg: str, win_lose_msg: str):\n instruct_summarize = f\"{bidding_history}\\n\\n{hammer_msg}\\n{win_lose_msg}\"\n return instruct_summarize\n \n def summarize(self, instruct_summarize: str):\n self.dialogue_history += [\n HumanMessage(content=instruct_summarize),\n AIMessage(content='(Taking notes...)')\n ]\n self.budget_history.append(self.budget)\n self.profit_history.append(self.profit)\n return ''\n \n def get_replan_instruct(self):\n return ''\n\n def replan(self, instruct_replan):\n self.withdraw = False\n self.cur_item_id += 1\n return ''\n \n def to_monitors(self, as_json=False):\n items_won = []\n for item, bid in self.items_won:\n items_won.append([str(item), bid, item.true_value])\n if as_json:\n return {\n 'auction_hash': self.auction_hash,\n 'bidder_name': self.name,\n 'human_name': self.human_name,\n 'model_name': self.model_name,\n 'budget': self.original_budget,\n 'money_left': self.budget,\n 'profit': self.profit,\n 'items_won': items_won,\n 'engagement_count': self.engagement_count,\n }\n else:\n return [\n self.budget, \n self.profit, \n items_won, \n 0, \n 0, \n round(self.failed_bid_cnt / (self.total_bid_cnt+1e-8), 2), \n 0, \n 0, \n self.engagement_count,\n draw_plot(f\"{self.name} ({self.model_name})\", self.budget_history, self.profit_history), \n [],\n [],\n [], \n []\n ]" }, { "identifier": "Auctioneer", "path": "src/auctioneer_base.py", "snippet": "class Auctioneer(BaseModel):\n enable_discount: bool = False\n items: List[Item] = []\n cur_item: Item = None\n highest_bidder: Bidder = None\n highest_bid: int = -1\n bidding_history = defaultdict(list) # history about the bidding war of one item\n items_queue: List[Item] = [] # updates when a item is taken.\n auction_logs = defaultdict(list) # history about the bidding war of all items\n openai_cost = 0\n prev_round_max_bid: int = -1\n min_bid: int = 0\n fail_to_sell = False\n min_markup_pct = 0.1\n\n class Config:\n arbitrary_types_allowed = True\n \n def init_items(self, items: List[Item]):\n for item in items:\n # reset discounted price\n item.reset_price()\n self.items = items\n self.items_queue = items.copy()\n\n def summarize_items_info(self):\n desc = ''\n for item in self.items:\n desc += f\"- {item.get_desc()}\\n\"\n return desc.strip()\n \n def present_item(self):\n cur_item = self.items_queue.pop(0)\n self.cur_item = cur_item\n return cur_item\n \n def shuffle_items(self):\n random.shuffle(self.items)\n self.items_queue = self.items.copy()\n \n def record_bid(self, bid_info: dict, bid_round: int):\n '''\n Save the bidding history for each round, log the highest bidder and highest bidding\n '''\n # bid_info: {'bidder': xxx, 'bid': xxx, 'raw_msg': xxx}\n self.bidding_history[bid_round].append(bid_info)\n for hist in self.bidding_history[bid_round]:\n if hist['bid'] > 0:\n if self.highest_bid < hist['bid']:\n self.highest_bid = hist['bid']\n self.highest_bidder = hist['bidder']\n elif self.highest_bid == hist['bid']:\n # random if there's a tie\n self.highest_bidder = random.choice([self.highest_bidder, hist['bidder']])\n self.auction_logs[f\"{self.cur_item.get_desc()}\"].append(\n {'bidder': bid_info['bidder'], \n 'bid': bid_info['bid'], \n 'bid_round': bid_round})\n\n def _biddings_to_string(self, bid_round: int):\n '''\n Return a string that summarizes the bidding history in a round\n '''\n # bid_hist_text = '' if bid_round == 0 else f'- {self.highest_bidder}: ${self.highest_bid}\\n'\n bid_hist_text = ''\n for js in self.bidding_history[bid_round]:\n if js['bid'] < 0:\n bid_hist_text += f\"- {js['bidder']} withdrew\\n\"\n else:\n bid_hist_text += f\"- {js['bidder']}: ${js['bid']}\\n\"\n return bid_hist_text.strip()\n \n def all_bidding_history_to_string(self):\n bid_hist_text = ''\n for bid_round in self.bidding_history:\n bid_hist_text += f\"Round {bid_round}:\\n{self._biddings_to_string(bid_round)}\\n\\n\"\n return bid_hist_text.strip()\n\n def ask_for_bid(self, bid_round: int):\n '''\n Ask for bid, return the message to be sent to bidders\n '''\n if self.highest_bidder is None:\n if bid_round > 0:\n msg = f\"Seeing as we've had no takers at the initial price, we're going to lower the starting bid to ${self.cur_item.price} for {self.cur_item.name} to spark some interest! Do I have any takers?\"\n else:\n remaining_items = [self.cur_item.name] + [item.name for item in self.items_queue]\n msg = f\"Attention, bidders! {len(remaining_items)} item(s) left, they are: {', '.join(remaining_items)}.\\n\\nNow, please bid on {self.cur_item}. The starting price for bidding for {self.cur_item} is ${self.cur_item.price}. Anyone interested in this item?\"\n else:\n bidding_history = self._biddings_to_string(bid_round - 1)\n msg = f\"Thank you! This is the {p.ordinal(bid_round)} round of bidding for this item:\\n{bidding_history}\\n\\nNow we have ${self.highest_bid} from {self.highest_bidder.name} for {self.cur_item.name}. The minimum increase over this highest bid is ${int(self.cur_item.price * self.min_markup_pct)}. Do I have any advance on ${self.highest_bid}?\"\n return msg\n \n def ask_for_rebid(self, fail_msg: str, bid_price: int):\n return f\"Your bid of ${bid_price} failed, because {fail_msg}: You must reconsider your bid.\"\n\n def get_hammer_msg(self):\n if self.highest_bidder is None:\n return f\"Since no one bid on {self.cur_item.name}, we'll move on to the next item.\"\n else:\n return f\"Sold! {self.cur_item} to {self.highest_bidder} at ${self.highest_bid}! The true value for {self.cur_item} is ${self.cur_item.true_value}.\"# Thus {self.highest_bidder}'s profit by winning this item is ${self.cur_item.true_value - self.highest_bid}.\"\n\n def check_hammer(self, bid_round: int):\n # check if the item is sold\n self.fail_to_sell = False\n num_bid = self._num_bids_in_round(bid_round)\n\n # highest_bidder has already been updated in record_bid().\n # so when num_bid == 0 & highest_bidder is None, it means no one bid on this item\n if self.highest_bidder is None:\n if num_bid == 0:\n # failed to sell, as there is no highest bidder\n self.fail_to_sell = True\n if self.enable_discount and bid_round < 3:\n # lower the starting price by 50%. discoutn only applies to the first 3 rounds\n self.cur_item.lower_price(0.5)\n is_sold = False\n else:\n is_sold = True\n else:\n # won't happen\n raise ValueError(f\"highest_bidder is None but num_bid is {num_bid}\")\n else:\n if self.prev_round_max_bid < 0 and num_bid == 1:\n # only one bidder in the first round \n is_sold = True\n else:\n self.prev_round_max_bid = self.highest_bid\n is_sold = self._num_bids_in_round(bid_round) == 0\n return is_sold\n \n def _num_bids_in_round(self, bid_round: int):\n # check if there is no bid in the current round\n cnt = 0\n for hist in self.bidding_history[bid_round]:\n if hist['bid'] > 0:\n cnt += 1\n return cnt\n\n def hammer_fall(self):\n print(f'* Sold! {self.cur_item} (${self.cur_item.true_value}) goes to {self.highest_bidder} at ${self.highest_bid}.')\n self.auction_logs[f\"{self.cur_item.get_desc()}\"].append({\n 'bidder': self.highest_bidder, \n 'bid': f\"{self.highest_bid} (${self.cur_item.true_value})\", # no need for the first $, as it will be added in the self.log()\n 'bid_round': 'Hammer price (true value)'})\n self.cur_item = None\n self.highest_bidder = None\n self.highest_bid = -1\n self.bidding_history = defaultdict(list)\n self.prev_round_max_bid = -1\n self.fail_to_sell = False\n\n def end_auction(self):\n return len(self.items_queue) == 0\n \n def gather_all_status(self, bidders: List[Bidder]):\n status = {}\n for bidder in bidders:\n status[bidder.name] = {\n 'profit': bidder.profit, \n 'items_won': bidder.items_won\n }\n return status\n\n def parse_bid(self, text: str):\n prompt = PARSE_BID_INSTRUCTION.format(response=text)\n with get_openai_callback() as cb:\n llm = ChatOpenAI(model='gpt-3.5-turbo-0613', temperature=0)\n result = llm([HumanMessage(content=prompt)]).content\n self.openai_cost += cb.total_cost\n \n bid_number = re.findall(r'\\$?\\d+', result.replace(',', ''))\n # find number in the result\n if '-1' in result:\n return -1\n elif len(bid_number) > 0:\n return int(bid_number[-1].replace('$', ''))\n else:\n print('* Rebid:', text)\n return None\n\n def log(self, bidder_personal_reports: list = [], show_model_name=True):\n ''' example\n Apparatus H, starting at $1000.\n\n 1st bid:\n Bidder 1 (gpt-3.5-turbo-16k-0613): $1200\n Bidder 2 (gpt-3.5-turbo-16k-0613): $1100\n Bidder 3 (gpt-3.5-turbo-16k-0613): Withdrawn\n Bidder 4 (gpt-3.5-turbo-16k-0613): $1200\n \n 2nd bid:\n Bidder 1 (gpt-3.5-turbo-16k-0613): Withdrawn\n Bidder 2 (gpt-3.5-turbo-16k-0613): Withdrawn\n \n Hammer price:\n Bidder 4 (gpt-3.5-turbo-16k-0613): $1200\n '''\n markdown_output = \"## Auction Log\\n\\n\"\n for i, (item, bids) in enumerate(self.auction_logs.items()):\n markdown_output += f\"### {i+1}. {item}\\n\\n\"\n cur_bid_round = -1\n for i, bid in enumerate(bids):\n if bid['bid_round'] != cur_bid_round:\n cur_bid_round = bid['bid_round']\n if isinstance(bid['bid_round'], int):\n markdown_output += f\"\\n#### {p.ordinal(bid['bid_round']+1)} bid:\\n\\n\"\n else:\n markdown_output += f\"\\n#### {bid['bid_round']}:\\n\\n\"\n bid_price = f\"${bid['bid']}\" if bid['bid'] != -1 else 'Withdrew'\n if isinstance(bid['bidder'], Bidder) or isinstance(bid['bidder'], HumanBidder):\n if show_model_name:\n markdown_output += f\"* {bid['bidder']} ({bid['bidder'].model_name}): {bid_price}\\n\"\n else:\n markdown_output += f\"* {bid['bidder']}: {bid_price}\\n\"\n else:\n markdown_output += f\"* None bid\\n\"\n markdown_output += \"\\n\"\n \n if len(bidder_personal_reports) != 0:\n markdown_output += f\"\\n## Personal Report\"\n for report in bidder_personal_reports:\n markdown_output += f\"\\n\\n{report}\"\n return markdown_output.strip()\n \n def finish_auction(self):\n self.auction_logs = defaultdict(list)\n self.cur_item = None\n self.highest_bidder = None\n self.highest_bid = -1\n self.bidding_history = defaultdict(list)\n self.items_queue = []\n self.items = []\n self.prev_round_max_bid = -1\n self.fail_to_sell = False\n self.min_bid = 0" }, { "identifier": "run_auction", "path": "auction_workflow.py", "snippet": "def run_auction(\n auction_hash: str, \n auctioneer: Auctioneer, \n bidder_list: List[Bidder], \n thread_num: int, \n yield_for_demo=True,\n log_dir=LOG_DIR,\n repeat_num=0,\n memo_file=None):\n \n # bidder_list[0].verbose=True\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log()] + [disable_gr, disable_gr] + disable_all_box(bidder_list)\n \n # ***************** Learn Round ****************\n for bidder in bidder_list:\n if bidder.enable_learning and memo_file:\n # if no prev memo file, then no need to learn.\n if os.path.exists(memo_file):\n with open(memo_file) as f:\n data = json.load(f)\n past_learnings = data['learnings'][bidder.name]\n past_auction_log = data['auction_log']\n bidder.learn_from_prev_auction(past_learnings, past_auction_log)\n \n # ***************** Plan Round *****************\n # init bidder profit\n bidder_profit_info = auctioneer.gather_all_status(bidder_list)\n for bidder in bidder_list:\n bidder.set_all_bidders_status(bidder_profit_info)\n\n plan_instructs = [bidder.get_plan_instruct(auctioneer.items) for bidder in bidder_list]\n\n bidding_multithread(bidder_list, plan_instructs, func_type='plan', thread_num=thread_num)\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log()] + [disable_gr, disable_gr] + disable_all_box(bidder_list)\n \n bar = tqdm(total=len(auctioneer.items_queue), desc='Auction Progress')\n while not auctioneer.end_auction():\n cur_item = auctioneer.present_item()\n \n bid_round = 0\n while True:\n # ***************** Bid Round ***************** \n auctioneer_msg = auctioneer.ask_for_bid(bid_round)\n _bidder_list = []\n _bid_instruct_list = []\n # remove highest bidder and withdrawn bidders\n for bidder in bidder_list:\n if bidder is auctioneer.highest_bidder or bidder.withdraw:\n bidder.need_input = False\n continue\n else:\n bidder.need_input = True # enable input from demo\n instruct = bidder.get_bid_instruct(auctioneer_msg, bid_round)\n _bidder_list.append(bidder)\n _bid_instruct_list.append(instruct)\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log()] + [disable_gr, disable_gr] + enable_human_box(bidder_list)\n \n _msgs = bidding_multithread(_bidder_list, _bid_instruct_list, func_type='bid', thread_num=thread_num)\n\n for i, (msg, bidder) in enumerate(zip(_msgs, _bidder_list)):\n if bidder.model_name == 'rule':\n bid_price = bidder.bid_rule(auctioneer.prev_round_max_bid, auctioneer.min_markup_pct)\n else:\n bid_price = parse_bid_price(auctioneer, bidder, msg)\n\n # can't bid more than budget or less than previous highest bid\n while True:\n fail_msg = bidder.bid_sanity_check(bid_price, auctioneer.prev_round_max_bid, auctioneer.min_markup_pct)\n if fail_msg is None: \n break\n else:\n bidder.need_input = True # enable input from demo\n auctioneer_msg = auctioneer.ask_for_rebid(fail_msg=fail_msg, bid_price=bid_price)\n rebid_instruct = bidder.get_rebid_instruct(auctioneer_msg)\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log()] + [disable_gr, disable_gr] + disable_all_box(bidder_list)\n \n msg = bidder.rebid_for_failure(rebid_instruct)\n bid_price = parse_bid_price(auctioneer, bidder, msg)\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log()] + [disable_gr, disable_gr] + disable_all_box(bidder_list)\n \n bidder.set_withdraw(bid_price)\n auctioneer.record_bid({'bidder': bidder, 'bid': bid_price, 'raw_msg': msg}, bid_round)\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log()] + [disable_gr, disable_gr] + disable_all_box(bidder_list)\n \n is_sold = auctioneer.check_hammer(bid_round)\n bid_round += 1\n if is_sold: \n break\n else:\n if auctioneer.fail_to_sell and auctioneer.enable_discount:\n for bidder in bidder_list:\n bidder.set_withdraw(0) # back in the game\n\n # ***************** Summarize ***************** \n summarize_instruct_list = []\n for bidder in bidder_list:\n if bidder is auctioneer.highest_bidder:\n win_lose_msg = bidder.win_bid(cur_item, auctioneer.highest_bid)\n else:\n win_lose_msg = bidder.lose_bid(cur_item)\n msg = bidder.get_summarize_instruct(\n bidding_history=auctioneer.all_bidding_history_to_string(),\n hammer_msg=auctioneer.get_hammer_msg(),\n win_lose_msg=win_lose_msg\n )\n summarize_instruct_list.append(msg)\n\n # record profit information of all bidders for each bidder\n # (not used in the auction, just for belief tracking evaluation)\n bidder_profit_info = auctioneer.gather_all_status(bidder_list)\n for bidder in bidder_list:\n bidder.set_all_bidders_status(bidder_profit_info)\n \n bidding_multithread(bidder_list, summarize_instruct_list, func_type='summarize', thread_num=thread_num)\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log()] + [disable_gr, disable_gr] + disable_all_box(bidder_list)\n\n # ***************** Replan *****************\n if len(auctioneer.items_queue) > 0: # no need to replan if all items are sold\n replan_instruct_list = [bidder.get_replan_instruct(\n # bidding_history=auctioneer.all_bidding_history_to_string(), \n # hammer_msg=auctioneer.get_hammer_msg()\n ) for bidder in bidder_list]\n bidding_multithread(bidder_list, replan_instruct_list, func_type='replan', thread_num=thread_num)\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log()] + [disable_gr, disable_gr] + disable_all_box(bidder_list)\n\n auctioneer.hammer_fall()\n bar.update(1)\n\n total_cost = sum([b.openai_cost for b in bidder_list]) + auctioneer.openai_cost\n bidder_reports = [bidder.profit_report() for bidder in bidder_list]\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list, profit_report=True)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log(bidder_reports) + f'\\n## Total Cost: ${total_cost}'] + [disable_gr, enable_gr] + disable_all_box(bidder_list)\n \n memo = {'auction_log': auctioneer.log(show_model_name=False),\n 'memo_text': bidder_reports,\n 'profit': {bidder.name: bidder.profit for bidder in bidder_list},\n 'total_cost': total_cost,\n 'learnings': {bidder.name: bidder.learnings for bidder in bidder_list},\n 'model_info': {bidder.name: bidder.model_name for bidder in bidder_list}}\n log_bidders(log_dir, auction_hash, bidder_list, repeat_num, memo)\n \n auctioneer.finish_auction()\n \n if not yield_for_demo:\n yield total_cost" }, { "identifier": "make_auction_hash", "path": "auction_workflow.py", "snippet": "def make_auction_hash():\n return str(int(time.time()))" }, { "identifier": "chunks", "path": "utils.py", "snippet": "def chunks(lst, n):\n \"\"\"Yield successive n-sized chunks from lst.\"\"\"\n for i in range(0, len(lst), n):\n yield lst[i : i + n]" }, { "identifier": "reset_state_list", "path": "utils.py", "snippet": "def reset_state_list(*states):\n empty = [None for _ in states[1:]]\n return [[]] + empty" } ]
import os import gradio as gr from app_modules.presets import * from app_modules.overwrites import * from app_modules.utils import * from src.item_base import create_items from src.bidder_base import Bidder from src.human_bidder import HumanBidder from src.auctioneer_base import Auctioneer from auction_workflow import run_auction, make_auction_hash from utils import chunks, reset_state_list
15,496
BIDDER_NUM = 4 items = create_items('data/items_demo.jsonl') def auction_loop_app(*args): global items bidder_list = args[0] # gr.State() -> session state items_id = args[1] os.environ['OPENAI_API_KEY'] = args[2] if args[2] != '' else os.environ.get('OPENAI_API_KEY', '') os.environ['ANTHROPIC_API_KEY'] = args[3] if args[3] != '' else os.environ.get('ANTHROPIC_API_KEY', '') thread_num = args[4] item_shuffle = args[5] enable_discount = args[6] min_markup_pct = args[7] args = args[8:]
BIDDER_NUM = 4 items = create_items('data/items_demo.jsonl') def auction_loop_app(*args): global items bidder_list = args[0] # gr.State() -> session state items_id = args[1] os.environ['OPENAI_API_KEY'] = args[2] if args[2] != '' else os.environ.get('OPENAI_API_KEY', '') os.environ['ANTHROPIC_API_KEY'] = args[3] if args[3] != '' else os.environ.get('ANTHROPIC_API_KEY', '') thread_num = args[4] item_shuffle = args[5] enable_discount = args[6] min_markup_pct = args[7] args = args[8:]
auction_hash = make_auction_hash()
5
2023-10-08 09:30:57+00:00
24k
sakemin/cog-musicgen-chord
predict.py
[ { "identifier": "CompressionSolver", "path": "audiocraft/solvers/compression.py", "snippet": "class CompressionSolver(base.StandardSolver):\n \"\"\"Solver for compression task.\n\n The compression task combines a set of perceptual and objective losses\n to train an EncodecModel (composed of an encoder-decoder and a quantizer)\n to perform high fidelity audio reconstruction.\n \"\"\"\n def __init__(self, cfg: omegaconf.DictConfig):\n super().__init__(cfg)\n self.rng: torch.Generator # set at each epoch\n self.adv_losses = builders.get_adversarial_losses(self.cfg)\n self.aux_losses = nn.ModuleDict()\n self.info_losses = nn.ModuleDict()\n assert not cfg.fsdp.use, \"FSDP not supported by CompressionSolver.\"\n loss_weights = dict()\n for loss_name, weight in self.cfg.losses.items():\n if loss_name in ['adv', 'feat']:\n for adv_name, _ in self.adv_losses.items():\n loss_weights[f'{loss_name}_{adv_name}'] = weight\n elif weight > 0:\n self.aux_losses[loss_name] = builders.get_loss(loss_name, self.cfg)\n loss_weights[loss_name] = weight\n else:\n self.info_losses[loss_name] = builders.get_loss(loss_name, self.cfg)\n self.balancer = builders.get_balancer(loss_weights, self.cfg.balancer)\n self.register_stateful('adv_losses')\n\n @property\n def best_metric_name(self) -> tp.Optional[str]:\n # best model is the last for the compression model\n return None\n\n def build_model(self):\n \"\"\"Instantiate model and optimizer.\"\"\"\n # Model and optimizer\n self.model = models.builders.get_compression_model(self.cfg).to(self.device)\n self.optimizer = builders.get_optimizer(self.model.parameters(), self.cfg.optim)\n self.register_stateful('model', 'optimizer')\n self.register_best_state('model')\n self.register_ema('model')\n\n def build_dataloaders(self):\n \"\"\"Instantiate audio dataloaders for each stage.\"\"\"\n self.dataloaders = builders.get_audio_datasets(self.cfg)\n\n def show(self):\n \"\"\"Show the compression model and employed adversarial loss.\"\"\"\n self.logger.info(f\"Compression model with {self.model.quantizer.total_codebooks} codebooks:\")\n self.log_model_summary(self.model)\n self.logger.info(\"Adversarial loss:\")\n self.log_model_summary(self.adv_losses)\n self.logger.info(\"Auxiliary losses:\")\n self.logger.info(self.aux_losses)\n self.logger.info(\"Info losses:\")\n self.logger.info(self.info_losses)\n\n def run_step(self, idx: int, batch: torch.Tensor, metrics: dict):\n \"\"\"Perform one training or valid step on a given batch.\"\"\"\n x = batch.to(self.device)\n y = x.clone()\n\n qres = self.model(x)\n assert isinstance(qres, quantization.QuantizedResult)\n y_pred = qres.x\n # Log bandwidth in kb/s\n metrics['bandwidth'] = qres.bandwidth.mean()\n\n if self.is_training:\n d_losses: dict = {}\n if len(self.adv_losses) > 0 and torch.rand(1, generator=self.rng).item() <= 1 / self.cfg.adversarial.every:\n for adv_name, adversary in self.adv_losses.items():\n disc_loss = adversary.train_adv(y_pred, y)\n d_losses[f'd_{adv_name}'] = disc_loss\n metrics['d_loss'] = torch.sum(torch.stack(list(d_losses.values())))\n metrics.update(d_losses)\n\n balanced_losses: dict = {}\n other_losses: dict = {}\n\n # penalty from quantization\n if qres.penalty is not None and qres.penalty.requires_grad:\n other_losses['penalty'] = qres.penalty # penalty term from the quantizer\n\n # adversarial losses\n for adv_name, adversary in self.adv_losses.items():\n adv_loss, feat_loss = adversary(y_pred, y)\n balanced_losses[f'adv_{adv_name}'] = adv_loss\n balanced_losses[f'feat_{adv_name}'] = feat_loss\n\n # auxiliary losses\n for loss_name, criterion in self.aux_losses.items():\n loss = criterion(y_pred, y)\n balanced_losses[loss_name] = loss\n\n # weighted losses\n metrics.update(balanced_losses)\n metrics.update(other_losses)\n metrics.update(qres.metrics)\n\n if self.is_training:\n # backprop losses that are not handled by balancer\n other_loss = torch.tensor(0., device=self.device)\n if 'penalty' in other_losses:\n other_loss += other_losses['penalty']\n if other_loss.requires_grad:\n other_loss.backward(retain_graph=True)\n ratio1 = sum(p.grad.data.norm(p=2).pow(2)\n for p in self.model.parameters() if p.grad is not None)\n assert isinstance(ratio1, torch.Tensor)\n metrics['ratio1'] = ratio1.sqrt()\n\n # balancer losses backward, returns effective training loss\n # with effective weights at the current batch.\n metrics['g_loss'] = self.balancer.backward(balanced_losses, y_pred)\n # add metrics corresponding to weight ratios\n metrics.update(self.balancer.metrics)\n ratio2 = sum(p.grad.data.norm(p=2).pow(2)\n for p in self.model.parameters() if p.grad is not None)\n assert isinstance(ratio2, torch.Tensor)\n metrics['ratio2'] = ratio2.sqrt()\n\n # optim\n flashy.distrib.sync_model(self.model)\n if self.cfg.optim.max_norm:\n torch.nn.utils.clip_grad_norm_(\n self.model.parameters(), self.cfg.optim.max_norm\n )\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n # informative losses only\n info_losses: dict = {}\n with torch.no_grad():\n for loss_name, criterion in self.info_losses.items():\n loss = criterion(y_pred, y)\n info_losses[loss_name] = loss\n\n metrics.update(info_losses)\n\n # aggregated GAN losses: this is useful to report adv and feat across different adversarial loss setups\n adv_losses = [loss for loss_name, loss in metrics.items() if loss_name.startswith('adv')]\n if len(adv_losses) > 0:\n metrics['adv'] = torch.sum(torch.stack(adv_losses))\n feat_losses = [loss for loss_name, loss in metrics.items() if loss_name.startswith('feat')]\n if len(feat_losses) > 0:\n metrics['feat'] = torch.sum(torch.stack(feat_losses))\n\n return metrics\n\n def run_epoch(self):\n # reset random seed at the beginning of the epoch\n self.rng = torch.Generator()\n self.rng.manual_seed(1234 + self.epoch)\n # run epoch\n super().run_epoch()\n\n def evaluate(self):\n \"\"\"Evaluate stage. Runs audio reconstruction evaluation.\"\"\"\n self.model.eval()\n evaluate_stage_name = str(self.current_stage)\n\n loader = self.dataloaders['evaluate']\n updates = len(loader)\n lp = self.log_progress(f'{evaluate_stage_name} inference', loader, total=updates, updates=self.log_updates)\n average = flashy.averager()\n\n pendings = []\n ctx = multiprocessing.get_context('spawn')\n with get_pool_executor(self.cfg.evaluate.num_workers, mp_context=ctx) as pool:\n for idx, batch in enumerate(lp):\n x = batch.to(self.device)\n with torch.no_grad():\n qres = self.model(x)\n\n y_pred = qres.x.cpu()\n y = batch.cpu() # should already be on CPU but just in case\n pendings.append(pool.submit(evaluate_audio_reconstruction, y_pred, y, self.cfg))\n\n metrics_lp = self.log_progress(f'{evaluate_stage_name} metrics', pendings, updates=self.log_updates)\n for pending in metrics_lp:\n metrics = pending.result()\n metrics = average(metrics)\n\n metrics = flashy.distrib.average_metrics(metrics, len(loader))\n return metrics\n\n def generate(self):\n \"\"\"Generate stage.\"\"\"\n self.model.eval()\n sample_manager = SampleManager(self.xp, map_reference_to_sample_id=True)\n generate_stage_name = str(self.current_stage)\n\n loader = self.dataloaders['generate']\n updates = len(loader)\n lp = self.log_progress(generate_stage_name, loader, total=updates, updates=self.log_updates)\n\n for batch in lp:\n reference, _ = batch\n reference = reference.to(self.device)\n with torch.no_grad():\n qres = self.model(reference)\n assert isinstance(qres, quantization.QuantizedResult)\n\n reference = reference.cpu()\n estimate = qres.x.cpu()\n sample_manager.add_samples(estimate, self.epoch, ground_truth_wavs=reference)\n\n flashy.distrib.barrier()\n\n def load_from_pretrained(self, name: str) -> dict:\n model = models.CompressionModel.get_pretrained(name)\n if isinstance(model, models.DAC):\n raise RuntimeError(\"Cannot fine tune a DAC model.\")\n elif isinstance(model, models.HFEncodecCompressionModel):\n self.logger.warning('Trying to automatically convert a HuggingFace model '\n 'to AudioCraft, this might fail!')\n state = model.model.state_dict()\n new_state = {}\n for k, v in state.items():\n if k.startswith('decoder.layers') and '.conv.' in k and '.block.' not in k:\n # We need to determine if this a convtr or a regular conv.\n layer = int(k.split('.')[2])\n if isinstance(model.model.decoder.layers[layer].conv, torch.nn.ConvTranspose1d):\n\n k = k.replace('.conv.', '.convtr.')\n k = k.replace('encoder.layers.', 'encoder.model.')\n k = k.replace('decoder.layers.', 'decoder.model.')\n k = k.replace('conv.', 'conv.conv.')\n k = k.replace('convtr.', 'convtr.convtr.')\n k = k.replace('quantizer.layers.', 'quantizer.vq.layers.')\n k = k.replace('.codebook.', '._codebook.')\n new_state[k] = v\n state = new_state\n elif isinstance(model, models.EncodecModel):\n state = model.state_dict()\n else:\n raise RuntimeError(f\"Cannot fine tune model type {type(model)}.\")\n return {\n 'best_state': {'model': state}\n }\n\n @staticmethod\n def model_from_checkpoint(checkpoint_path: tp.Union[Path, str],\n device: tp.Union[torch.device, str] = 'cpu') -> models.CompressionModel:\n \"\"\"Instantiate a CompressionModel from a given checkpoint path or dora sig.\n This method is a convenient endpoint to load a CompressionModel to use in other solvers.\n\n Args:\n checkpoint_path (Path or str): Path to checkpoint or dora sig from where the checkpoint is resolved.\n This also supports pre-trained models by using a path of the form //pretrained/NAME.\n See `model_from_pretrained` for a list of supported pretrained models.\n use_ema (bool): Use EMA variant of the model instead of the actual model.\n device (torch.device or str): Device on which the model is loaded.\n \"\"\"\n checkpoint_path = str(checkpoint_path)\n if checkpoint_path.startswith('//pretrained/'):\n name = checkpoint_path.split('/', 3)[-1]\n return models.CompressionModel.get_pretrained(name, device)\n logger = logging.getLogger(__name__)\n logger.info(f\"Loading compression model from checkpoint: {checkpoint_path}\")\n _checkpoint_path = checkpoint.resolve_checkpoint_path(checkpoint_path, use_fsdp=False)\n assert _checkpoint_path is not None, f\"Could not resolve compression model checkpoint path: {checkpoint_path}\"\n state = checkpoint.load_checkpoint(_checkpoint_path)\n assert state is not None and 'xp.cfg' in state, f\"Could not load compression model from ckpt: {checkpoint_path}\"\n cfg = state['xp.cfg']\n cfg.device = device\n compression_model = models.builders.get_compression_model(cfg).to(device)\n assert compression_model.sample_rate == cfg.sample_rate, \"Compression model sample rate should match\"\n\n assert 'best_state' in state and state['best_state'] != {}\n assert 'exported' not in state, \"When loading an exported checkpoint, use the //pretrained/ prefix.\"\n compression_model.load_state_dict(state['best_state']['model'])\n compression_model.eval()\n logger.info(\"Compression model loaded!\")\n return compression_model\n\n @staticmethod\n def wrapped_model_from_checkpoint(cfg: omegaconf.DictConfig,\n checkpoint_path: tp.Union[Path, str],\n device: tp.Union[torch.device, str] = 'cpu') -> models.CompressionModel:\n \"\"\"Instantiate a wrapped CompressionModel from a given checkpoint path or dora sig.\n\n Args:\n cfg (omegaconf.DictConfig): Configuration to read from for wrapped mode.\n checkpoint_path (Path or str): Path to checkpoint or dora sig from where the checkpoint is resolved.\n use_ema (bool): Use EMA variant of the model instead of the actual model.\n device (torch.device or str): Device on which the model is loaded.\n \"\"\"\n compression_model = CompressionSolver.model_from_checkpoint(checkpoint_path, device)\n compression_model = models.builders.get_wrapped_compression_model(compression_model, cfg)\n return compression_model" }, { "identifier": "MultiBandDiffusion", "path": "audiocraft/models/multibanddiffusion.py", "snippet": "class MultiBandDiffusion:\n \"\"\"Sample from multiple diffusion models.\n\n Args:\n DPs (list of DiffusionProcess): Diffusion processes.\n codec_model (CompressionModel): Underlying compression model used to obtain discrete tokens.\n \"\"\"\n def __init__(self, DPs: tp.List[DiffusionProcess], codec_model: CompressionModel) -> None:\n self.DPs = DPs\n self.codec_model = codec_model\n self.device = next(self.codec_model.parameters()).device\n\n @property\n def sample_rate(self) -> int:\n return self.codec_model.sample_rate\n\n @staticmethod\n def get_mbd_musicgen(device=None):\n \"\"\"Load our diffusion models trained for MusicGen.\"\"\"\n if device is None:\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n path = 'facebook/multiband-diffusion'\n filename = 'mbd_musicgen_32khz.th'\n name = 'facebook/musicgen-small'\n codec_model = load_compression_model(name, device=device)\n models, processors, cfgs = load_diffusion_models(path, filename=filename, device=device)\n DPs = []\n for i in range(len(models)):\n schedule = NoiseSchedule(**cfgs[i].schedule, sample_processor=processors[i], device=device)\n DPs.append(DiffusionProcess(model=models[i], noise_schedule=schedule))\n return MultiBandDiffusion(DPs=DPs, codec_model=codec_model)\n\n @staticmethod\n def get_mbd_24khz(bw: float = 3.0, pretrained: bool = True,\n device: tp.Optional[tp.Union[torch.device, str]] = None,\n n_q: tp.Optional[int] = None):\n \"\"\"Get the pretrained Models for MultibandDiffusion.\n\n Args:\n bw (float): Bandwidth of the compression model.\n pretrained (bool): Whether to use / download if necessary the models.\n device (torch.device or str, optional): Device on which the models are loaded.\n n_q (int, optional): Number of quantizers to use within the compression model.\n \"\"\"\n if device is None:\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n assert bw in [1.5, 3.0, 6.0], f\"bandwidth {bw} not available\"\n if n_q is not None:\n assert n_q in [2, 4, 8]\n assert {1.5: 2, 3.0: 4, 6.0: 8}[bw] == n_q, \\\n f\"bandwidth and number of codebooks missmatch to use n_q = {n_q} bw should be {n_q * (1.5 / 2)}\"\n n_q = {1.5: 2, 3.0: 4, 6.0: 8}[bw]\n codec_model = CompressionSolver.model_from_checkpoint(\n '//pretrained/facebook/encodec_24khz', device=device)\n codec_model.set_num_codebooks(n_q)\n codec_model = codec_model.to(device)\n path = 'facebook/multiband-diffusion'\n filename = f'mbd_comp_{n_q}.pt'\n models, processors, cfgs = load_diffusion_models(path, filename=filename, device=device)\n DPs = []\n for i in range(len(models)):\n schedule = NoiseSchedule(**cfgs[i].schedule, sample_processor=processors[i], device=device)\n DPs.append(DiffusionProcess(model=models[i], noise_schedule=schedule))\n return MultiBandDiffusion(DPs=DPs, codec_model=codec_model)\n\n return MultiBandDiffusion(DPs, codec_model)\n\n @torch.no_grad()\n def get_condition(self, wav: torch.Tensor, sample_rate: int) -> torch.Tensor:\n \"\"\"Get the conditioning (i.e. latent reprentatios of the compression model) from a waveform.\n Args:\n wav (torch.Tensor): The audio that we want to extract the conditioning from\n sample_rate (int): sample rate of the audio\"\"\"\n if sample_rate != self.sample_rate:\n wav = julius.resample_frac(wav, sample_rate, self.sample_rate)\n codes, scale = self.codec_model.encode(wav)\n assert scale is None, \"Scaled compression models not supported.\"\n emb = self.get_emb(codes)\n return emb\n\n @torch.no_grad()\n def get_emb(self, codes: torch.Tensor):\n \"\"\"Get latent representation from the discrete codes\n Argrs:\n codes (torch.Tensor): discrete tokens\"\"\"\n emb = self.codec_model.decode_latent(codes)\n return emb\n\n def generate(self, emb: torch.Tensor, size: tp.Optional[torch.Size] = None,\n step_list: tp.Optional[tp.List[int]] = None):\n \"\"\"Generate Wavform audio from the latent embeddings of the compression model\n Args:\n emb (torch.Tensor): Conditioning embeddinds\n size (none torch.Size): size of the output\n if None this is computed from the typical upsampling of the model\n step_list (optional list[int]): list of Markov chain steps, defaults to 50 linearly spaced step.\n \"\"\"\n if size is None:\n upsampling = int(self.codec_model.sample_rate / self.codec_model.frame_rate)\n size = torch.Size([emb.size(0), self.codec_model.channels, emb.size(-1) * upsampling])\n assert size[0] == emb.size(0)\n out = torch.zeros(size).to(self.device)\n for DP in self.DPs:\n out += DP.generate(condition=emb, step_list=step_list, initial_noise=torch.randn_like(out))\n return out\n\n def re_eq(self, wav: torch.Tensor, ref: torch.Tensor, n_bands: int = 32, strictness: float = 1):\n \"\"\"match the eq to the encodec output by matching the standard deviation of some frequency bands\n Args:\n wav (torch.Tensor): audio to equalize\n ref (torch.Tensor):refenrence audio from which we match the spectrogram.\n n_bands (int): number of bands of the eq\n strictness (float): how strict the the matching. 0 is no matching, 1 is exact matching.\n \"\"\"\n split = julius.SplitBands(n_bands=n_bands, sample_rate=self.codec_model.sample_rate).to(wav.device)\n bands = split(wav)\n bands_ref = split(ref)\n out = torch.zeros_like(ref)\n for i in range(n_bands):\n out += bands[i] * (bands_ref[i].std() / bands[i].std()) ** strictness\n return out\n\n def regenerate(self, wav: torch.Tensor, sample_rate: int):\n \"\"\"Regenerate a wavform through compression and diffusion regeneration.\n Args:\n wav (torch.Tensor): Original 'ground truth' audio\n sample_rate (int): sample rate of the input (and output) wav\n \"\"\"\n if sample_rate != self.codec_model.sample_rate:\n wav = julius.resample_frac(wav, sample_rate, self.codec_model.sample_rate)\n emb = self.get_condition(wav, sample_rate=self.codec_model.sample_rate)\n size = wav.size()\n out = self.generate(emb, size=size)\n if sample_rate != self.codec_model.sample_rate:\n out = julius.resample_frac(out, self.codec_model.sample_rate, sample_rate)\n return out\n\n def tokens_to_wav(self, tokens: torch.Tensor, n_bands: int = 32):\n \"\"\"Generate Waveform audio with diffusion from the discrete codes.\n Args:\n tokens (torch.Tensor): discrete codes\n n_bands (int): bands for the eq matching.\n \"\"\"\n wav_encodec = self.codec_model.decode(tokens)\n condition = self.get_emb(tokens)\n wav_diffusion = self.generate(emb=condition, size=wav_encodec.size())\n return self.re_eq(wav=wav_diffusion, ref=wav_encodec, n_bands=n_bands)" }, { "identifier": "MusicGen", "path": "audiocraft/models/musicgen.py", "snippet": "class MusicGen:\n \"\"\"MusicGen main model with convenient generation API.\n\n Args:\n name (str): name of the model.\n compression_model (CompressionModel): Compression model\n used to map audio to invertible discrete representations.\n lm (LMModel): Language model over discrete representations.\n max_duration (float, optional): maximum duration the model can produce,\n otherwise, inferred from the training params.\n \"\"\"\n def __init__(self, name: str, compression_model: CompressionModel, lm: LMModel,\n max_duration: tp.Optional[float] = None):\n self.name = name\n self.compression_model = compression_model\n self.lm = lm\n self.cfg: tp.Optional[omegaconf.DictConfig] = None\n # Just to be safe, let's put everything in eval mode.\n self.compression_model.eval()\n self.lm.eval()\n\n if hasattr(lm, 'cfg'):\n cfg = lm.cfg\n assert isinstance(cfg, omegaconf.DictConfig)\n self.cfg = cfg\n\n if self.cfg is not None:\n self.compression_model = get_wrapped_compression_model(self.compression_model, self.cfg)\n\n if max_duration is None:\n if self.cfg is not None:\n max_duration = lm.cfg.dataset.segment_duration # type: ignore\n else:\n raise ValueError(\"You must provide max_duration when building directly MusicGen\")\n assert max_duration is not None\n self.max_duration: float = max_duration\n self.device = next(iter(lm.parameters())).device\n\n self.generation_params: dict = {}\n self.set_generation_params(duration=15) # 15 seconds by default\n self._progress_callback: tp.Optional[tp.Callable[[int, int], None]] = None\n if self.device.type == 'cpu':\n self.autocast = TorchAutocast(enabled=False)\n else:\n self.autocast = TorchAutocast(\n enabled=True, device_type=self.device.type, dtype=torch.float16)\n\n @property\n def frame_rate(self) -> float:\n \"\"\"Roughly the number of AR steps per seconds.\"\"\"\n return self.compression_model.frame_rate\n\n @property\n def sample_rate(self) -> int:\n \"\"\"Sample rate of the generated audio.\"\"\"\n return self.compression_model.sample_rate\n\n @property\n def audio_channels(self) -> int:\n \"\"\"Audio channels of the generated audio.\"\"\"\n return self.compression_model.channels\n\n @staticmethod\n def get_pretrained(name: str = 'facebook/musicgen-melody', device=None):\n \"\"\"Return pretrained model, we provide four models:\n - facebook/musicgen-small (300M), text to music,\n # see: https://huggingface.co/facebook/musicgen-small\n - facebook/musicgen-medium (1.5B), text to music,\n # see: https://huggingface.co/facebook/musicgen-medium\n - facebook/musicgen-melody (1.5B) text to music and text+melody to music,\n # see: https://huggingface.co/facebook/musicgen-melody\n - facebook/musicgen-large (3.3B), text to music,\n # see: https://huggingface.co/facebook/musicgen-large\n \"\"\"\n if device is None:\n if torch.cuda.device_count():\n device = 'cuda'\n else:\n device = 'cpu'\n\n if name == 'debug':\n # used only for unit tests\n compression_model = get_debug_compression_model(device)\n lm = get_debug_lm_model(device)\n return MusicGen(name, compression_model, lm, max_duration=30)\n\n if name in _HF_MODEL_CHECKPOINTS_MAP:\n warnings.warn(\n \"MusicGen pretrained model relying on deprecated checkpoint mapping. \" +\n f\"Please use full pre-trained id instead: facebook/musicgen-{name}\")\n name = _HF_MODEL_CHECKPOINTS_MAP[name]\n\n lm = load_lm_model(name, device=device)\n compression_model = load_compression_model(name, device=device)\n if 'self_wav' in lm.condition_provider.conditioners:\n lm.condition_provider.conditioners['self_wav'].match_len_on_eval = True\n lm.condition_provider.conditioners['self_wav']._use_masking = False\n\n return MusicGen(name, compression_model, lm)\n\n def set_generation_params(self, use_sampling: bool = True, top_k: int = 250,\n top_p: float = 0.0, temperature: float = 1.0,\n duration: float = 30.0, cfg_coef: float = 3.0,\n two_step_cfg: bool = False, extend_stride: float = 18):\n \"\"\"Set the generation parameters for MusicGen.\n\n Args:\n use_sampling (bool, optional): Use sampling if True, else do argmax decoding. Defaults to True.\n top_k (int, optional): top_k used for sampling. Defaults to 250.\n top_p (float, optional): top_p used for sampling, when set to 0 top_k is used. Defaults to 0.0.\n temperature (float, optional): Softmax temperature parameter. Defaults to 1.0.\n duration (float, optional): Duration of the generated waveform. Defaults to 30.0.\n cfg_coef (float, optional): Coefficient used for classifier free guidance. Defaults to 3.0.\n two_step_cfg (bool, optional): If True, performs 2 forward for Classifier Free Guidance,\n instead of batching together the two. This has some impact on how things\n are padded but seems to have little impact in practice.\n extend_stride: when doing extended generation (i.e. more than 30 seconds), by how much\n should we extend the audio each time. Larger values will mean less context is\n preserved, and shorter value will require extra computations.\n \"\"\"\n assert extend_stride < self.max_duration, \"Cannot stride by more than max generation duration.\"\n self.extend_stride = extend_stride\n self.duration = duration\n self.generation_params = {\n 'use_sampling': use_sampling,\n 'temp': temperature,\n 'top_k': top_k,\n 'top_p': top_p,\n 'cfg_coef': cfg_coef,\n 'two_step_cfg': two_step_cfg,\n }\n\n def set_custom_progress_callback(self, progress_callback: tp.Optional[tp.Callable[[int, int], None]] = None):\n \"\"\"Override the default progress callback.\"\"\"\n self._progress_callback = progress_callback\n\n def generate_unconditional(self, num_samples: int, progress: bool = False,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples in an unconditional manner.\n\n Args:\n num_samples (int): Number of samples to be generated.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n descriptions: tp.List[tp.Optional[str]] = [None] * num_samples\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions, None)\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate(self, descriptions: tp.List[str], progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions, None)\n assert prompt_tokens is None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_with_chroma(self, descriptions: tp.List[str], melody_wavs: MelodyType,\n melody_sample_rate: int, progress: bool = False,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text and melody.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n melody_wavs: (torch.Tensor or list of Tensor): A batch of waveforms used as\n melody conditioning. Should have shape [B, C, T] with B matching the description length,\n C=1 or 2. It can be [C, T] if there is a single description. It can also be\n a list of [C, T] tensors.\n melody_sample_rate: (int): Sample rate of the melody waveforms.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if isinstance(melody_wavs, torch.Tensor):\n if melody_wavs.dim() == 2:\n melody_wavs = melody_wavs[None]\n if melody_wavs.dim() != 3:\n raise ValueError(\"Melody wavs should have a shape [B, C, T].\")\n melody_wavs = list(melody_wavs)\n else:\n for melody in melody_wavs:\n if melody is not None:\n assert melody.dim() == 2, \"One melody in the list has the wrong number of dims.\"\n\n melody_wavs = [\n convert_audio(wav, melody_sample_rate, self.sample_rate, self.audio_channels)\n if wav is not None else None\n for wav in melody_wavs]\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=None,\n melody_wavs=melody_wavs)\n assert prompt_tokens is None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation(self, prompt: torch.Tensor, prompt_sample_rate: int,\n descriptions: tp.Optional[tp.List[tp.Optional[str]]] = None,\n progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on audio prompts.\n\n Args:\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n Prompt should be [B, C, T], or [C, T] if only one sample is generated.\n prompt_sample_rate (int): Sampling rate of the given audio waveforms.\n descriptions (list of str, optional): A list of strings used as text conditioning. Defaults to None.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if prompt.dim() == 2:\n prompt = prompt[None]\n if prompt.dim() != 3:\n raise ValueError(\"prompt should have 3 dimensions: [B, C, T] (C = 1).\")\n prompt = convert_audio(prompt, prompt_sample_rate, self.sample_rate, self.audio_channels)\n if descriptions is None:\n descriptions = [None] * len(prompt)\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions, prompt)\n assert prompt_tokens is not None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n \n def generate_continuation_with_audio_token(self, prompt, \n descriptions: tp.Optional[tp.List[tp.Optional[str]]] = None,\n progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on audio prompts.\n\n Args:\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n Prompt should be [B, C, T], or [C, T] if only one sample is generated.\n prompt_sample_rate (int): Sampling rate of the given audio waveforms.\n descriptions (list of str, optional): A list of strings used as text conditioning. Defaults to None.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n \n if descriptions is None:\n descriptions = [None] * len(prompt)\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions, None)\n assert prompt_tokens is None\n prompt_tokens = prompt\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation_with_audio_chroma(self, prompt: torch.Tensor, prompt_sample_rate: int, melody_wavs: MelodyType,\n melody_sample_rate: int, descriptions: tp.Optional[tp.List[tp.Optional[str]]] = None,\n progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on audio prompts.\n\n Args:\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n Prompt should be [B, C, T], or [C, T] if only one sample is generated.\n prompt_sample_rate (int): Sampling rate of the given audio waveforms.\n descriptions (list of str, optional): A list of strings used as text conditioning. Defaults to None.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if prompt.dim() == 2:\n prompt = prompt[None]\n if prompt.dim() != 3:\n raise ValueError(\"prompt should have 3 dimensions: [B, C, T] (C = 1).\")\n prompt = convert_audio(prompt, prompt_sample_rate, self.sample_rate, self.audio_channels)\n\n if isinstance(melody_wavs, torch.Tensor):\n if melody_wavs.dim() == 2:\n melody_wavs = melody_wavs[None]\n if melody_wavs.dim() != 3:\n raise ValueError(\"Melody wavs should have a shape [B, C, T].\")\n melody_wavs = list(melody_wavs)\n else:\n for melody in melody_wavs:\n if melody is not None:\n assert melody.dim() == 2, \"One melody in the list has the wrong number of dims.\"\n\n melody_wavs = [\n convert_audio(wav, melody_sample_rate, self.sample_rate, self.audio_channels)\n if wav is not None else None\n for wav in melody_wavs]\n \n if descriptions is None:\n descriptions = [None] * len(prompt)\n \n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=prompt, melody_wavs=melody_wavs)\n assert prompt_tokens is not None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation_with_audio_tokens_and_audio_chroma(self, prompt, melody_wavs: MelodyType,\n melody_sample_rate: int, descriptions: tp.Optional[tp.List[tp.Optional[str]]] = None,\n progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on audio prompts.\n\n Args:\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n Prompt should be [B, C, T], or [C, T] if only one sample is generated.\n prompt_sample_rate (int): Sampling rate of the given audio waveforms.\n descriptions (list of str, optional): A list of strings used as text conditioning. Defaults to None.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if isinstance(melody_wavs, torch.Tensor):\n if melody_wavs.dim() == 2:\n melody_wavs = melody_wavs[None]\n if melody_wavs.dim() != 3:\n raise ValueError(\"Melody wavs should have a shape [B, C, T].\")\n melody_wavs = list(melody_wavs)\n else:\n for melody in melody_wavs:\n if melody is not None:\n assert melody.dim() == 2, \"One melody in the list has the wrong number of dims.\"\n\n melody_wavs = [\n convert_audio(wav, melody_sample_rate, self.sample_rate, self.audio_channels)\n if wav is not None else None\n for wav in melody_wavs]\n \n if descriptions is None:\n descriptions = [None] * len(prompt)\n \n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=None, melody_wavs=melody_wavs)\n assert prompt_tokens is None\n prompt_tokens = prompt\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation_with_text_chroma(self, prompt: torch.Tensor, prompt_sample_rate: int, descriptions: tp.List[str], chord_texts: tp.Union[tp.List[str],str],\n progress: bool = False, bpm: tp.Union[float,int,tp.List[float],tp.List[int]] = 120, meter: tp.Optional[tp.Union[int,tp.List[int]]] = 4,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text and melody.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n melody_wavs: (torch.Tensor or list of Tensor): A batch of waveforms used as\n melody conditioning. Should have shape [B, C, T] with B matching the description length,\n C=1 or 2. It can be [C, T] if there is a single description. It can also be\n a list of [C, T] tensors.\n melody_sample_rate: (int): Sample rate of the melody waveforms.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if prompt.dim() == 2:\n prompt = prompt[None]\n if prompt.dim() != 3:\n raise ValueError(\"prompt should have 3 dimensions: [B, C, T] (C = 1).\")\n prompt = convert_audio(prompt, prompt_sample_rate, self.sample_rate, self.audio_channels)\n\n if isinstance(chord_texts, str):\n chord_texts = [chord_texts]\n\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=prompt,\n melody_wavs=chord_texts, bpm=bpm, meter=meter)\n\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation_with_audio_tokens_and_text_chroma(self, prompt, descriptions: tp.List[str], chord_texts: tp.Union[tp.List[str],str],\n progress: bool = False, bpm: tp.Union[float,int,tp.List[float],tp.List[int]] = 120, meter: tp.Optional[tp.Union[int,tp.List[int]]] = 4,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text and melody.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n melody_wavs: (torch.Tensor or list of Tensor): A batch of waveforms used as\n melody conditioning. Should have shape [B, C, T] with B matching the description length,\n C=1 or 2. It can be [C, T] if there is a single description. It can also be\n a list of [C, T] tensors.\n melody_sample_rate: (int): Sample rate of the melody waveforms.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n \n if isinstance(chord_texts, str):\n chord_texts = [chord_texts]\n\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=None,\n melody_wavs=chord_texts, bpm=bpm, meter=meter)\n prompt_tokens = prompt\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n \n def generate_with_text_chroma(self, descriptions: tp.List[str], chord_texts: tp.Union[tp.List[str],str],\n progress: bool = False, bpm: tp.Union[float,int,tp.List[float],tp.List[int]] = 120, meter: tp.Optional[tp.Union[int,tp.List[int]]] = 4,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text and melody.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n melody_wavs: (torch.Tensor or list of Tensor): A batch of waveforms used as\n melody conditioning. Should have shape [B, C, T] with B matching the description length,\n C=1 or 2. It can be [C, T] if there is a single description. It can also be\n a list of [C, T] tensors.\n melody_sample_rate: (int): Sample rate of the melody waveforms.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if isinstance(chord_texts, str):\n chord_texts = [chord_texts]\n\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=None,\n melody_wavs=chord_texts, bpm=bpm, meter=meter)\n assert prompt_tokens is None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n \n @torch.no_grad()\n def _prepare_tokens_and_attributes(\n self,\n descriptions: tp.Sequence[tp.Optional[str]],\n prompt: tp.Optional[torch.Tensor],\n melody_wavs: tp.Optional[tp.Union[MelodyList,tp.List[str]]] = None, bpm: tp.Optional[tp.Union[float,int,tp.List[float],tp.List[int]]] = None, meter:tp.Optional[tp.Union[int,tp.List[int]]] = None\n ) -> tp.Tuple[tp.List[ConditioningAttributes], tp.Optional[torch.Tensor]]:\n \"\"\"Prepare model inputs.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n melody_wavs (torch.Tensor, optional): A batch of waveforms\n used as melody conditioning. Defaults to None.\n \"\"\"\n attributes = [\n ConditioningAttributes(text={'description': description})\n for description in descriptions]\n\n if melody_wavs is None:\n for attr in attributes:\n attr.wav['self_wav'] = WavCondition(\n torch.zeros((1, 1, 1), device=self.device),\n torch.tensor([0], device=self.device),\n sample_rate=[self.sample_rate],\n path=[None])\n else:\n if 'self_wav' not in self.lm.condition_provider.conditioners:\n raise RuntimeError(\"This model doesn't support melody conditioning. \"\n \"Use the `melody` model.\")\n assert len(melody_wavs) == len(descriptions), \\\n f\"number of melody wavs must match number of descriptions! \" \\\n f\"got melody len={len(melody_wavs)}, and descriptions len={len(descriptions)}\"\n\n if bpm is not None and (isinstance(bpm, int) or isinstance(bpm, float)):\n bpm = [bpm for i in range(len(melody_wavs))]\n elif bpm is not None and isinstance(bpm, tp.List):\n assert len(melody_wavs) == len(bpm)\n\n if meter is not None and (isinstance(meter, int) or isinstance(meter, float)):\n meter = [meter for i in range(len(melody_wavs))]\n elif meter is not None and isinstance(meter, tp.List):\n assert len(melody_wavs) == len(meter)\n\n for attr, melody, i in zip(attributes, melody_wavs, range(len(melody_wavs))):\n if melody is None:\n attr.wav['self_wav'] = WavCondition(\n torch.zeros((1, 1, 1), device=self.device),\n torch.tensor([0], device=self.device),\n sample_rate=[self.sample_rate],\n path=[None])\n elif isinstance(melody, torch.Tensor):\n attr.wav['self_wav'] = WavCondition(\n melody[None].to(device=self.device),\n torch.tensor([melody.shape[-1]], device=self.device),\n sample_rate=[self.sample_rate],\n path=[None],\n )\n else :\n attr.wav['self_wav'] = WavChordTextCondition(\n [melody],\n torch.tensor([self.duration*self.sample_rate], device=self.device),\n sample_rate=[self.sample_rate],\n path=[None],\n bpm = [bpm[i]],\n meter = [meter[i]]\n )\n\n if prompt is not None:\n if descriptions is not None:\n assert len(descriptions) == len(prompt), \"Prompt and nb. descriptions doesn't match\"\n prompt = prompt.to(self.device)\n prompt_tokens, scale = self.compression_model.encode(prompt)\n assert scale is None\n else:\n prompt_tokens = None\n return attributes, prompt_tokens\n\n def _generate_tokens(self, attributes: tp.List[ConditioningAttributes],\n prompt_tokens: tp.Optional[torch.Tensor], progress: bool = False) -> torch.Tensor:\n \"\"\"Generate discrete audio tokens given audio prompt and/or conditions.\n\n Args:\n attributes (list of ConditioningAttributes): Conditions used for generation (text/melody).\n prompt_tokens (torch.Tensor, optional): Audio prompt used for continuation.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n Returns:\n torch.Tensor: Generated audio, of shape [B, C, T], T is defined by the generation params.\n \"\"\"\n total_gen_len = int(self.duration * self.frame_rate)\n max_prompt_len = int(min(self.duration, self.max_duration) * self.frame_rate)\n current_gen_offset: int = 0\n\n def _progress_callback(generated_tokens: int, tokens_to_generate: int):\n generated_tokens += current_gen_offset\n if self._progress_callback is not None:\n # Note that total_gen_len might be quite wrong depending on the\n # codebook pattern used, but with delay it is almost accurate.\n self._progress_callback(generated_tokens, total_gen_len)\n else:\n print(f'{generated_tokens: 6d} / {total_gen_len: 6d}', end='\\r')\n\n if prompt_tokens is not None:\n assert max_prompt_len >= prompt_tokens.shape[-1], \\\n \"Prompt is longer than audio to generate\"\n\n callback = None\n if progress:\n callback = _progress_callback\n\n if self.duration <= self.max_duration:\n # generate by sampling from LM, simple case.\n with self.autocast:\n gen_tokens = self.lm.generate(\n prompt_tokens, attributes,\n callback=callback, max_gen_len=total_gen_len, **self.generation_params)\n\n else:\n # now this gets a bit messier, we need to handle prompts,\n # melody conditioning etc.\n ref_wavs = [attr.wav['self_wav'] for attr in attributes]\n all_tokens = []\n if prompt_tokens is None:\n prompt_length = 0\n else:\n all_tokens.append(prompt_tokens)\n prompt_length = prompt_tokens.shape[-1]\n\n stride_tokens = int(self.frame_rate * self.extend_stride)\n step = 0\n\n while current_gen_offset + prompt_length < total_gen_len:\n self.lm.condition_provider.conditioners['self_wav'].set_continuation_count(self.extend_stride/self.max_duration, step) #For text based chord conditioning\n time_offset = current_gen_offset / self.frame_rate\n chunk_duration = min(self.duration - time_offset, self.max_duration)\n max_gen_len = int(chunk_duration * self.frame_rate)\n for attr, ref_wav in zip(attributes, ref_wavs):\n if isinstance(ref_wav, WavCondition):\n wav_length = ref_wav.length.item()\n if wav_length == 0:\n continue\n # We will extend the wav periodically if it not long enough.\n # we have to do it here rather than in conditioners.py as otherwise\n # we wouldn't have the full wav.\n initial_position = int(time_offset * self.sample_rate)\n wav_target_length = int(self.max_duration * self.sample_rate)\n positions = torch.arange(initial_position,\n initial_position + wav_target_length, device=self.device)\n attr.wav['self_wav'] = WavCondition(\n ref_wav[0][..., positions % wav_length],\n torch.full_like(ref_wav[1], wav_target_length),\n [self.sample_rate] * ref_wav[0].size(0),\n [None], [0.])\n with self.autocast:\n gen_tokens = self.lm.generate(\n prompt_tokens, attributes,\n callback=callback, max_gen_len=max_gen_len, **self.generation_params)\n if prompt_tokens is None:\n all_tokens.append(gen_tokens)\n else:\n all_tokens.append(gen_tokens[:, :, prompt_tokens.shape[-1]:])\n prompt_tokens = gen_tokens[:, :, stride_tokens:]\n prompt_length = prompt_tokens.shape[-1]\n current_gen_offset += stride_tokens\n step = step + 1\n\n gen_tokens = torch.cat(all_tokens, dim=-1)\n return gen_tokens\n\n def generate_audio(self, gen_tokens: torch.Tensor):\n \"\"\"Generate Audio from tokens\"\"\"\n assert gen_tokens.dim() == 3\n with torch.no_grad():\n gen_audio = self.compression_model.decode(gen_tokens, None)\n return gen_audio" }, { "identifier": "CompressionSolver", "path": "audiocraft/solvers/compression.py", "snippet": "class CompressionSolver(base.StandardSolver):\n \"\"\"Solver for compression task.\n\n The compression task combines a set of perceptual and objective losses\n to train an EncodecModel (composed of an encoder-decoder and a quantizer)\n to perform high fidelity audio reconstruction.\n \"\"\"\n def __init__(self, cfg: omegaconf.DictConfig):\n super().__init__(cfg)\n self.rng: torch.Generator # set at each epoch\n self.adv_losses = builders.get_adversarial_losses(self.cfg)\n self.aux_losses = nn.ModuleDict()\n self.info_losses = nn.ModuleDict()\n assert not cfg.fsdp.use, \"FSDP not supported by CompressionSolver.\"\n loss_weights = dict()\n for loss_name, weight in self.cfg.losses.items():\n if loss_name in ['adv', 'feat']:\n for adv_name, _ in self.adv_losses.items():\n loss_weights[f'{loss_name}_{adv_name}'] = weight\n elif weight > 0:\n self.aux_losses[loss_name] = builders.get_loss(loss_name, self.cfg)\n loss_weights[loss_name] = weight\n else:\n self.info_losses[loss_name] = builders.get_loss(loss_name, self.cfg)\n self.balancer = builders.get_balancer(loss_weights, self.cfg.balancer)\n self.register_stateful('adv_losses')\n\n @property\n def best_metric_name(self) -> tp.Optional[str]:\n # best model is the last for the compression model\n return None\n\n def build_model(self):\n \"\"\"Instantiate model and optimizer.\"\"\"\n # Model and optimizer\n self.model = models.builders.get_compression_model(self.cfg).to(self.device)\n self.optimizer = builders.get_optimizer(self.model.parameters(), self.cfg.optim)\n self.register_stateful('model', 'optimizer')\n self.register_best_state('model')\n self.register_ema('model')\n\n def build_dataloaders(self):\n \"\"\"Instantiate audio dataloaders for each stage.\"\"\"\n self.dataloaders = builders.get_audio_datasets(self.cfg)\n\n def show(self):\n \"\"\"Show the compression model and employed adversarial loss.\"\"\"\n self.logger.info(f\"Compression model with {self.model.quantizer.total_codebooks} codebooks:\")\n self.log_model_summary(self.model)\n self.logger.info(\"Adversarial loss:\")\n self.log_model_summary(self.adv_losses)\n self.logger.info(\"Auxiliary losses:\")\n self.logger.info(self.aux_losses)\n self.logger.info(\"Info losses:\")\n self.logger.info(self.info_losses)\n\n def run_step(self, idx: int, batch: torch.Tensor, metrics: dict):\n \"\"\"Perform one training or valid step on a given batch.\"\"\"\n x = batch.to(self.device)\n y = x.clone()\n\n qres = self.model(x)\n assert isinstance(qres, quantization.QuantizedResult)\n y_pred = qres.x\n # Log bandwidth in kb/s\n metrics['bandwidth'] = qres.bandwidth.mean()\n\n if self.is_training:\n d_losses: dict = {}\n if len(self.adv_losses) > 0 and torch.rand(1, generator=self.rng).item() <= 1 / self.cfg.adversarial.every:\n for adv_name, adversary in self.adv_losses.items():\n disc_loss = adversary.train_adv(y_pred, y)\n d_losses[f'd_{adv_name}'] = disc_loss\n metrics['d_loss'] = torch.sum(torch.stack(list(d_losses.values())))\n metrics.update(d_losses)\n\n balanced_losses: dict = {}\n other_losses: dict = {}\n\n # penalty from quantization\n if qres.penalty is not None and qres.penalty.requires_grad:\n other_losses['penalty'] = qres.penalty # penalty term from the quantizer\n\n # adversarial losses\n for adv_name, adversary in self.adv_losses.items():\n adv_loss, feat_loss = adversary(y_pred, y)\n balanced_losses[f'adv_{adv_name}'] = adv_loss\n balanced_losses[f'feat_{adv_name}'] = feat_loss\n\n # auxiliary losses\n for loss_name, criterion in self.aux_losses.items():\n loss = criterion(y_pred, y)\n balanced_losses[loss_name] = loss\n\n # weighted losses\n metrics.update(balanced_losses)\n metrics.update(other_losses)\n metrics.update(qres.metrics)\n\n if self.is_training:\n # backprop losses that are not handled by balancer\n other_loss = torch.tensor(0., device=self.device)\n if 'penalty' in other_losses:\n other_loss += other_losses['penalty']\n if other_loss.requires_grad:\n other_loss.backward(retain_graph=True)\n ratio1 = sum(p.grad.data.norm(p=2).pow(2)\n for p in self.model.parameters() if p.grad is not None)\n assert isinstance(ratio1, torch.Tensor)\n metrics['ratio1'] = ratio1.sqrt()\n\n # balancer losses backward, returns effective training loss\n # with effective weights at the current batch.\n metrics['g_loss'] = self.balancer.backward(balanced_losses, y_pred)\n # add metrics corresponding to weight ratios\n metrics.update(self.balancer.metrics)\n ratio2 = sum(p.grad.data.norm(p=2).pow(2)\n for p in self.model.parameters() if p.grad is not None)\n assert isinstance(ratio2, torch.Tensor)\n metrics['ratio2'] = ratio2.sqrt()\n\n # optim\n flashy.distrib.sync_model(self.model)\n if self.cfg.optim.max_norm:\n torch.nn.utils.clip_grad_norm_(\n self.model.parameters(), self.cfg.optim.max_norm\n )\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n # informative losses only\n info_losses: dict = {}\n with torch.no_grad():\n for loss_name, criterion in self.info_losses.items():\n loss = criterion(y_pred, y)\n info_losses[loss_name] = loss\n\n metrics.update(info_losses)\n\n # aggregated GAN losses: this is useful to report adv and feat across different adversarial loss setups\n adv_losses = [loss for loss_name, loss in metrics.items() if loss_name.startswith('adv')]\n if len(adv_losses) > 0:\n metrics['adv'] = torch.sum(torch.stack(adv_losses))\n feat_losses = [loss for loss_name, loss in metrics.items() if loss_name.startswith('feat')]\n if len(feat_losses) > 0:\n metrics['feat'] = torch.sum(torch.stack(feat_losses))\n\n return metrics\n\n def run_epoch(self):\n # reset random seed at the beginning of the epoch\n self.rng = torch.Generator()\n self.rng.manual_seed(1234 + self.epoch)\n # run epoch\n super().run_epoch()\n\n def evaluate(self):\n \"\"\"Evaluate stage. Runs audio reconstruction evaluation.\"\"\"\n self.model.eval()\n evaluate_stage_name = str(self.current_stage)\n\n loader = self.dataloaders['evaluate']\n updates = len(loader)\n lp = self.log_progress(f'{evaluate_stage_name} inference', loader, total=updates, updates=self.log_updates)\n average = flashy.averager()\n\n pendings = []\n ctx = multiprocessing.get_context('spawn')\n with get_pool_executor(self.cfg.evaluate.num_workers, mp_context=ctx) as pool:\n for idx, batch in enumerate(lp):\n x = batch.to(self.device)\n with torch.no_grad():\n qres = self.model(x)\n\n y_pred = qres.x.cpu()\n y = batch.cpu() # should already be on CPU but just in case\n pendings.append(pool.submit(evaluate_audio_reconstruction, y_pred, y, self.cfg))\n\n metrics_lp = self.log_progress(f'{evaluate_stage_name} metrics', pendings, updates=self.log_updates)\n for pending in metrics_lp:\n metrics = pending.result()\n metrics = average(metrics)\n\n metrics = flashy.distrib.average_metrics(metrics, len(loader))\n return metrics\n\n def generate(self):\n \"\"\"Generate stage.\"\"\"\n self.model.eval()\n sample_manager = SampleManager(self.xp, map_reference_to_sample_id=True)\n generate_stage_name = str(self.current_stage)\n\n loader = self.dataloaders['generate']\n updates = len(loader)\n lp = self.log_progress(generate_stage_name, loader, total=updates, updates=self.log_updates)\n\n for batch in lp:\n reference, _ = batch\n reference = reference.to(self.device)\n with torch.no_grad():\n qres = self.model(reference)\n assert isinstance(qres, quantization.QuantizedResult)\n\n reference = reference.cpu()\n estimate = qres.x.cpu()\n sample_manager.add_samples(estimate, self.epoch, ground_truth_wavs=reference)\n\n flashy.distrib.barrier()\n\n def load_from_pretrained(self, name: str) -> dict:\n model = models.CompressionModel.get_pretrained(name)\n if isinstance(model, models.DAC):\n raise RuntimeError(\"Cannot fine tune a DAC model.\")\n elif isinstance(model, models.HFEncodecCompressionModel):\n self.logger.warning('Trying to automatically convert a HuggingFace model '\n 'to AudioCraft, this might fail!')\n state = model.model.state_dict()\n new_state = {}\n for k, v in state.items():\n if k.startswith('decoder.layers') and '.conv.' in k and '.block.' not in k:\n # We need to determine if this a convtr or a regular conv.\n layer = int(k.split('.')[2])\n if isinstance(model.model.decoder.layers[layer].conv, torch.nn.ConvTranspose1d):\n\n k = k.replace('.conv.', '.convtr.')\n k = k.replace('encoder.layers.', 'encoder.model.')\n k = k.replace('decoder.layers.', 'decoder.model.')\n k = k.replace('conv.', 'conv.conv.')\n k = k.replace('convtr.', 'convtr.convtr.')\n k = k.replace('quantizer.layers.', 'quantizer.vq.layers.')\n k = k.replace('.codebook.', '._codebook.')\n new_state[k] = v\n state = new_state\n elif isinstance(model, models.EncodecModel):\n state = model.state_dict()\n else:\n raise RuntimeError(f\"Cannot fine tune model type {type(model)}.\")\n return {\n 'best_state': {'model': state}\n }\n\n @staticmethod\n def model_from_checkpoint(checkpoint_path: tp.Union[Path, str],\n device: tp.Union[torch.device, str] = 'cpu') -> models.CompressionModel:\n \"\"\"Instantiate a CompressionModel from a given checkpoint path or dora sig.\n This method is a convenient endpoint to load a CompressionModel to use in other solvers.\n\n Args:\n checkpoint_path (Path or str): Path to checkpoint or dora sig from where the checkpoint is resolved.\n This also supports pre-trained models by using a path of the form //pretrained/NAME.\n See `model_from_pretrained` for a list of supported pretrained models.\n use_ema (bool): Use EMA variant of the model instead of the actual model.\n device (torch.device or str): Device on which the model is loaded.\n \"\"\"\n checkpoint_path = str(checkpoint_path)\n if checkpoint_path.startswith('//pretrained/'):\n name = checkpoint_path.split('/', 3)[-1]\n return models.CompressionModel.get_pretrained(name, device)\n logger = logging.getLogger(__name__)\n logger.info(f\"Loading compression model from checkpoint: {checkpoint_path}\")\n _checkpoint_path = checkpoint.resolve_checkpoint_path(checkpoint_path, use_fsdp=False)\n assert _checkpoint_path is not None, f\"Could not resolve compression model checkpoint path: {checkpoint_path}\"\n state = checkpoint.load_checkpoint(_checkpoint_path)\n assert state is not None and 'xp.cfg' in state, f\"Could not load compression model from ckpt: {checkpoint_path}\"\n cfg = state['xp.cfg']\n cfg.device = device\n compression_model = models.builders.get_compression_model(cfg).to(device)\n assert compression_model.sample_rate == cfg.sample_rate, \"Compression model sample rate should match\"\n\n assert 'best_state' in state and state['best_state'] != {}\n assert 'exported' not in state, \"When loading an exported checkpoint, use the //pretrained/ prefix.\"\n compression_model.load_state_dict(state['best_state']['model'])\n compression_model.eval()\n logger.info(\"Compression model loaded!\")\n return compression_model\n\n @staticmethod\n def wrapped_model_from_checkpoint(cfg: omegaconf.DictConfig,\n checkpoint_path: tp.Union[Path, str],\n device: tp.Union[torch.device, str] = 'cpu') -> models.CompressionModel:\n \"\"\"Instantiate a wrapped CompressionModel from a given checkpoint path or dora sig.\n\n Args:\n cfg (omegaconf.DictConfig): Configuration to read from for wrapped mode.\n checkpoint_path (Path or str): Path to checkpoint or dora sig from where the checkpoint is resolved.\n use_ema (bool): Use EMA variant of the model instead of the actual model.\n device (torch.device or str): Device on which the model is loaded.\n \"\"\"\n compression_model = CompressionSolver.model_from_checkpoint(checkpoint_path, device)\n compression_model = models.builders.get_wrapped_compression_model(compression_model, cfg)\n return compression_model" }, { "identifier": "load_compression_model", "path": "audiocraft/models/loaders.py", "snippet": "def load_compression_model(file_or_url_or_id: tp.Union[Path, str], device='cpu', cache_dir: tp.Optional[str] = None):\n pkg = load_compression_model_ckpt(file_or_url_or_id, cache_dir=cache_dir)\n if 'pretrained' in pkg:\n return CompressionModel.get_pretrained(pkg['pretrained'], device=device)\n cfg = OmegaConf.create(pkg['xp.cfg'])\n cfg.device = str(device)\n model = builders.get_compression_model(cfg)\n model.load_state_dict(pkg['best_state'])\n model.eval()\n return model" }, { "identifier": "load_lm_model", "path": "audiocraft/models/loaders.py", "snippet": "def load_lm_model(file_or_url_or_id: tp.Union[Path, str], device='cpu', cache_dir: tp.Optional[str] = None):\n pkg = load_lm_model_ckpt(file_or_url_or_id, cache_dir=cache_dir)\n cfg = OmegaConf.create(pkg['xp.cfg'])\n cfg.device = str(device)\n if cfg.device == 'cpu':\n cfg.dtype = 'float32'\n else:\n cfg.dtype = 'float16'\n _delete_param(cfg, 'conditioners.self_wav.chroma_chord.cache_path')\n _delete_param(cfg, 'conditioners.self_wav.chroma_stem.cache_path')\n _delete_param(cfg, 'conditioners.args.merge_text_conditions_p')\n _delete_param(cfg, 'conditioners.args.drop_desc_p')\n model = builders.get_lm_model(cfg)\n model.load_state_dict(pkg['best_state'])\n model.eval()\n model.cfg = cfg\n return model" }, { "identifier": "audio_write", "path": "audiocraft/data/audio.py", "snippet": "def audio_write(stem_name: tp.Union[str, Path],\n wav: torch.Tensor, sample_rate: int,\n format: str = 'wav', mp3_rate: int = 320, ogg_rate: tp.Optional[int] = None,\n normalize: bool = True, strategy: str = 'peak', peak_clip_headroom_db: float = 1,\n rms_headroom_db: float = 18, loudness_headroom_db: float = 14,\n loudness_compressor: bool = False,\n log_clipping: bool = True, make_parent_dir: bool = True,\n add_suffix: bool = True) -> Path:\n \"\"\"Convenience function for saving audio to disk. Returns the filename the audio was written to.\n\n Args:\n stem_name (str or Path): Filename without extension which will be added automatically.\n wav (torch.Tensor): Audio data to save.\n sample_rate (int): Sample rate of audio data.\n format (str): Either \"wav\", \"mp3\", \"ogg\", or \"flac\".\n mp3_rate (int): kbps when using mp3s.\n ogg_rate (int): kbps when using ogg/vorbis. If not provided, let ffmpeg decide for itself.\n normalize (bool): if `True` (default), normalizes according to the prescribed\n strategy (see after). If `False`, the strategy is only used in case clipping\n would happen.\n strategy (str): Can be either 'clip', 'peak', or 'rms'. Default is 'peak',\n i.e. audio is normalized by its largest value. RMS normalizes by root-mean-square\n with extra headroom to avoid clipping. 'clip' just clips.\n peak_clip_headroom_db (float): Headroom in dB when doing 'peak' or 'clip' strategy.\n rms_headroom_db (float): Headroom in dB when doing 'rms' strategy. This must be much larger\n than the `peak_clip` one to avoid further clipping.\n loudness_headroom_db (float): Target loudness for loudness normalization.\n loudness_compressor (bool): Uses tanh for soft clipping when strategy is 'loudness'.\n when strategy is 'loudness' log_clipping (bool): If True, basic logging on stderr when clipping still\n occurs despite strategy (only for 'rms').\n make_parent_dir (bool): Make parent directory if it doesn't exist.\n Returns:\n Path: Path of the saved audio.\n \"\"\"\n assert wav.dtype.is_floating_point, \"wav is not floating point\"\n if wav.dim() == 1:\n wav = wav[None]\n elif wav.dim() > 2:\n raise ValueError(\"Input wav should be at most 2 dimension.\")\n assert wav.isfinite().all()\n wav = normalize_audio(wav, normalize, strategy, peak_clip_headroom_db,\n rms_headroom_db, loudness_headroom_db, loudness_compressor,\n log_clipping=log_clipping, sample_rate=sample_rate,\n stem_name=str(stem_name))\n if format == 'mp3':\n suffix = '.mp3'\n flags = ['-f', 'mp3', '-c:a', 'libmp3lame', '-b:a', f'{mp3_rate}k']\n elif format == 'wav':\n suffix = '.wav'\n flags = ['-f', 'wav', '-c:a', 'pcm_s16le']\n elif format == 'ogg':\n suffix = '.ogg'\n flags = ['-f', 'ogg', '-c:a', 'libvorbis']\n if ogg_rate is not None:\n flags += ['-b:a', f'{ogg_rate}k']\n elif format == 'flac':\n suffix = '.flac'\n flags = ['-f', 'flac']\n else:\n raise RuntimeError(f\"Invalid format {format}. Only wav or mp3 are supported.\")\n if not add_suffix:\n suffix = ''\n path = Path(str(stem_name) + suffix)\n if make_parent_dir:\n path.parent.mkdir(exist_ok=True, parents=True)\n try:\n _piping_to_ffmpeg(path, wav, sample_rate, flags)\n except Exception:\n if path.exists():\n # we do not want to leave half written files around.\n path.unlink()\n raise\n return path" }, { "identifier": "get_lm_model", "path": "audiocraft/models/builders.py", "snippet": "def get_lm_model(cfg: omegaconf.DictConfig) -> LMModel:\n \"\"\"Instantiate a transformer LM.\"\"\"\n if cfg.lm_model == 'transformer_lm':\n kwargs = dict_from_config(getattr(cfg, 'transformer_lm'))\n n_q = kwargs['n_q']\n q_modeling = kwargs.pop('q_modeling', None)\n codebooks_pattern_cfg = getattr(cfg, 'codebooks_pattern')\n attribute_dropout = dict_from_config(getattr(cfg, 'attribute_dropout'))\n cls_free_guidance = dict_from_config(getattr(cfg, 'classifier_free_guidance'))\n cfg_prob, cfg_coef = cls_free_guidance['training_dropout'], cls_free_guidance['inference_coef']\n fuser = get_condition_fuser(cfg)\n condition_provider = get_conditioner_provider(kwargs[\"dim\"], cfg).to(cfg.device)\n if len(fuser.fuse2cond['cross']) > 0: # enforce cross-att programmatically\n kwargs['cross_attention'] = True\n if codebooks_pattern_cfg.modeling is None:\n assert q_modeling is not None, \\\n \"LM model should either have a codebook pattern defined or transformer_lm.q_modeling\"\n codebooks_pattern_cfg = omegaconf.OmegaConf.create(\n {'modeling': q_modeling, 'delay': {'delays': list(range(n_q))}}\n )\n pattern_provider = get_codebooks_pattern_provider(n_q, codebooks_pattern_cfg)\n return LMModel(\n pattern_provider=pattern_provider,\n condition_provider=condition_provider,\n fuser=fuser,\n cfg_dropout=cfg_prob,\n cfg_coef=cfg_coef,\n attribute_dropout=attribute_dropout,\n dtype=getattr(torch, cfg.dtype),\n device=cfg.device,\n **kwargs\n ).to(cfg.device)\n else:\n raise KeyError(f\"Unexpected LM model {cfg.lm_model}\")" } ]
import os import random import torchaudio import typing as tp import numpy as np import torch import subprocess from typing import Optional from cog import BasePredictor, Input, Path from audiocraft.solvers.compression import CompressionSolver from audiocraft.models import MusicGen, MultiBandDiffusion from audiocraft.solvers.compression import CompressionSolver from audiocraft.models.loaders import ( load_compression_model, load_lm_model, ) from audiocraft.data.audio import audio_write from audiocraft.models.builders import get_lm_model from omegaconf import OmegaConf
17,665
# Prediction interface for Cog ⚙️ # https://github.com/replicate/cog/blob/main/docs/python.md # We need to set `TRANSFORMERS_CACHE` before any imports, which is why this is up here. MODEL_PATH = "/src/models/" os.environ["TRANSFORMERS_CACHE"] = MODEL_PATH os.environ["TORCH_HOME"] = MODEL_PATH # Model specific imports def _delete_param(cfg, full_name: str): parts = full_name.split('.') for part in parts[:-1]: if part in cfg: cfg = cfg[part] else: return OmegaConf.set_struct(cfg, False) if parts[-1] in cfg: del cfg[parts[-1]] OmegaConf.set_struct(cfg, True) def load_ckpt(path, device, url=False): if url: loaded = torch.hub.load_state_dict_from_url(str(path)) else: loaded = torch.load(str(path)) cfg = OmegaConf.create(loaded['xp.cfg']) cfg.device = str(device) if cfg.device == 'cpu': cfg.dtype = 'float32' else: cfg.dtype = 'float16' _delete_param(cfg, 'conditioners.self_wav.chroma_chord.cache_path') _delete_param(cfg, 'conditioners.self_wav.chroma_stem.cache_path') _delete_param(cfg, 'conditioners.args.merge_text_conditions_p') _delete_param(cfg, 'conditioners.args.drop_desc_p')
# Prediction interface for Cog ⚙️ # https://github.com/replicate/cog/blob/main/docs/python.md # We need to set `TRANSFORMERS_CACHE` before any imports, which is why this is up here. MODEL_PATH = "/src/models/" os.environ["TRANSFORMERS_CACHE"] = MODEL_PATH os.environ["TORCH_HOME"] = MODEL_PATH # Model specific imports def _delete_param(cfg, full_name: str): parts = full_name.split('.') for part in parts[:-1]: if part in cfg: cfg = cfg[part] else: return OmegaConf.set_struct(cfg, False) if parts[-1] in cfg: del cfg[parts[-1]] OmegaConf.set_struct(cfg, True) def load_ckpt(path, device, url=False): if url: loaded = torch.hub.load_state_dict_from_url(str(path)) else: loaded = torch.load(str(path)) cfg = OmegaConf.create(loaded['xp.cfg']) cfg.device = str(device) if cfg.device == 'cpu': cfg.dtype = 'float32' else: cfg.dtype = 'float16' _delete_param(cfg, 'conditioners.self_wav.chroma_chord.cache_path') _delete_param(cfg, 'conditioners.self_wav.chroma_stem.cache_path') _delete_param(cfg, 'conditioners.args.merge_text_conditions_p') _delete_param(cfg, 'conditioners.args.drop_desc_p')
lm = get_lm_model(loaded['xp.cfg'])
7
2023-10-09 09:52:24+00:00
24k
zhijie-group/LOVECon
test_lovecon.py
[ { "identifier": "UNetPseudo3DConditionModel", "path": "video_diffusion/models/unet_3d_condition.py", "snippet": "class UNetPseudo3DConditionModel(ModelMixin, ConfigMixin):\n _supports_gradient_checkpointing = True\n\n @register_to_config\n def __init__(\n self,\n sample_size: Optional[int] = None,\n in_channels: int = 4,\n out_channels: int = 4,\n center_input_sample: bool = False,\n flip_sin_to_cos: bool = True,\n freq_shift: int = 0,\n down_block_types: Tuple[str] = (\n \"CrossAttnDownBlockPseudo3D\",\n \"CrossAttnDownBlockPseudo3D\",\n \"CrossAttnDownBlockPseudo3D\",\n \"DownBlockPseudo3D\",\n ),\n mid_block_type: str = \"UNetMidBlockPseudo3DCrossAttn\",\n up_block_types: Tuple[str] = (\n \"UpBlockPseudo3D\",\n \"CrossAttnUpBlockPseudo3D\",\n \"CrossAttnUpBlockPseudo3D\",\n \"CrossAttnUpBlockPseudo3D\",\n ),\n only_cross_attention: Union[bool, Tuple[bool]] = False,\n block_out_channels: Tuple[int] = (320, 640, 1280, 1280),\n layers_per_block: int = 2,\n downsample_padding: int = 1,\n mid_block_scale_factor: float = 1,\n act_fn: str = \"silu\",\n norm_num_groups: int = 32,\n norm_eps: float = 1e-5,\n cross_attention_dim: int = 1280,\n attention_head_dim: Union[int, Tuple[int]] = 8,\n dual_cross_attention: bool = False,\n use_linear_projection: bool = False,\n class_embed_type: Optional[str] = None,\n num_class_embeds: Optional[int] = None,\n upcast_attention: bool = False,\n resnet_time_scale_shift: str = \"default\",\n **kwargs\n ):\n super().__init__()\n\n self.sample_size = sample_size\n time_embed_dim = block_out_channels[0] * 4\n if 'temporal_downsample' in kwargs and kwargs['temporal_downsample'] is True:\n kwargs['temporal_downsample_time'] = 3\n self.temporal_downsample_time = kwargs.get('temporal_downsample_time', 0)\n \n # input\n self.conv_in = PseudoConv3d(in_channels, block_out_channels[0], \n kernel_size=3, padding=(1, 1), model_config=kwargs)\n\n # time\n self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)\n timestep_input_dim = block_out_channels[0]\n\n self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n\n # class embedding\n if class_embed_type is None and num_class_embeds is not None:\n self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)\n elif class_embed_type == \"timestep\":\n self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n elif class_embed_type == \"identity\":\n self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)\n else:\n self.class_embedding = None\n\n self.down_blocks = nn.ModuleList([])\n self.mid_block = None\n self.up_blocks = nn.ModuleList([])\n\n if isinstance(only_cross_attention, bool):\n only_cross_attention = [only_cross_attention] * len(down_block_types)\n\n if isinstance(attention_head_dim, int):\n attention_head_dim = (attention_head_dim,) * len(down_block_types)\n\n # down\n output_channel = block_out_channels[0]\n for i, down_block_type in enumerate(down_block_types):\n input_channel = output_channel\n output_channel = block_out_channels[i]\n is_final_block = i == len(block_out_channels) - 1\n kwargs_copy=copy.deepcopy(kwargs)\n temporal_downsample_i = ((i >= (len(down_block_types)-self.temporal_downsample_time))\n and (not is_final_block))\n kwargs_copy.update({'temporal_downsample': temporal_downsample_i} )\n # kwargs_copy.update({'SparseCausalAttention_index': temporal_downsample_i} )\n if temporal_downsample_i:\n print(f'Initialize model temporal downsample at layer {i}')\n down_block = get_down_block(\n down_block_type,\n num_layers=layers_per_block,\n in_channels=input_channel,\n out_channels=output_channel,\n temb_channels=time_embed_dim,\n add_downsample=not is_final_block,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[i],\n downsample_padding=downsample_padding,\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n model_config=kwargs_copy\n )\n self.down_blocks.append(down_block)\n # mid\n if mid_block_type == \"UNetMidBlockPseudo3DCrossAttn\":\n self.mid_block = UNetMidBlockPseudo3DCrossAttn(\n in_channels=block_out_channels[-1],\n temb_channels=time_embed_dim,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n output_scale_factor=mid_block_scale_factor,\n resnet_time_scale_shift=resnet_time_scale_shift,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[-1],\n resnet_groups=norm_num_groups,\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n upcast_attention=upcast_attention,\n model_config=kwargs\n )\n else:\n raise ValueError(f\"unknown mid_block_type : {mid_block_type}\")\n\n # count how many layers upsample the images\n self.num_upsamplers = 0\n\n # up\n reversed_block_out_channels = list(reversed(block_out_channels))\n reversed_attention_head_dim = list(reversed(attention_head_dim))\n only_cross_attention = list(reversed(only_cross_attention))\n output_channel = reversed_block_out_channels[0]\n for i, up_block_type in enumerate(up_block_types):\n is_final_block = i == len(block_out_channels) - 1\n\n prev_output_channel = output_channel\n output_channel = reversed_block_out_channels[i]\n input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]\n\n # add upsample block for all BUT final layer\n if not is_final_block:\n add_upsample = True\n self.num_upsamplers += 1\n else:\n add_upsample = False\n \n kwargs_copy=copy.deepcopy(kwargs)\n kwargs_copy.update({'temporal_downsample': \n i < (self.temporal_downsample_time-1)})\n if i < (self.temporal_downsample_time-1):\n print(f'Initialize model temporal updample at layer {i}')\n\n up_block = get_up_block(\n up_block_type,\n num_layers=layers_per_block + 1,\n in_channels=input_channel,\n out_channels=output_channel,\n prev_output_channel=prev_output_channel,\n temb_channels=time_embed_dim,\n add_upsample=add_upsample,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=reversed_attention_head_dim[i],\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n model_config=kwargs_copy\n )\n self.up_blocks.append(up_block)\n prev_output_channel = output_channel\n\n # out\n self.conv_norm_out = nn.GroupNorm(\n num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps\n )\n self.conv_act = nn.SiLU()\n self.conv_out = PseudoConv3d(block_out_channels[0], out_channels, \n kernel_size=3, padding=1, model_config=kwargs)\n\n def set_attention_slice(self, slice_size):\n r\"\"\"\n Enable sliced attention computation.\n\n When this option is enabled, the attention module will split the input tensor in slices, to compute attention\n in several steps. This is useful to save some memory in exchange for a small speed decrease.\n\n Args:\n slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `\"auto\"`):\n When `\"auto\"`, halves the input to the attention heads, so attention will be computed in two steps. If\n `\"max\"`, maxium amount of memory will be saved by running only one slice at a time. If a number is\n provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`\n must be a multiple of `slice_size`.\n \"\"\"\n sliceable_head_dims = []\n\n def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):\n if hasattr(module, \"set_attention_slice\"):\n sliceable_head_dims.append(module.sliceable_head_dim)\n\n for child in module.children():\n fn_recursive_retrieve_slicable_dims(child)\n\n # retrieve number of attention layers\n for module in self.children():\n fn_recursive_retrieve_slicable_dims(module)\n\n num_slicable_layers = len(sliceable_head_dims)\n\n if slice_size == \"auto\":\n # half the attention head size is usually a good trade-off between\n # speed and memory\n slice_size = [dim // 2 for dim in sliceable_head_dims]\n elif slice_size == \"max\":\n # make smallest slice possible\n slice_size = num_slicable_layers * [1]\n\n slice_size = (\n num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size\n )\n\n if len(slice_size) != len(sliceable_head_dims):\n raise ValueError(\n f\"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different\"\n f\" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}.\"\n )\n\n for i in range(len(slice_size)):\n size = slice_size[i]\n dim = sliceable_head_dims[i]\n if size is not None and size > dim:\n raise ValueError(f\"size {size} has to be smaller or equal to {dim}.\")\n\n # Recursively walk through all the children.\n # Any children which exposes the set_attention_slice method\n # gets the message\n def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):\n if hasattr(module, \"set_attention_slice\"):\n module.set_attention_slice(slice_size.pop())\n\n for child in module.children():\n fn_recursive_set_attention_slice(child, slice_size)\n\n reversed_slice_size = list(reversed(slice_size))\n for module in self.children():\n fn_recursive_set_attention_slice(module, reversed_slice_size)\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(\n module,\n (CrossAttnDownBlockPseudo3D, DownBlockPseudo3D, CrossAttnUpBlockPseudo3D, UpBlockPseudo3D),\n ):\n module.gradient_checkpointing = value\n\n def forward(\n self,\n sample: torch.FloatTensor,\n timestep: Union[torch.Tensor, float, int],\n encoder_hidden_states: torch.Tensor,\n class_labels: Optional[torch.Tensor] = None, # None\n attention_mask: Optional[torch.Tensor] = None, # None\n down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,\n mid_block_additional_residual: Optional[torch.Tensor] = None,\n return_dict: bool = True,\n ) -> Union[UNetPseudo3DConditionOutput, Tuple]:\n # By default samples have to be AT least a multiple of the overall upsampling factor.\n # The overall upsampling factor is equal to 2 ** (# num of upsampling layears).\n # However, the upsampling interpolation output size can be forced to fit any upsampling size\n # on the fly if necessary.\n default_overall_up_factor = 2**self.num_upsamplers\n\n # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`\n forward_upsample_size = False\n upsample_size = None\n\n if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):\n logger.info(\"Forward upsample size to force interpolation output size.\")\n forward_upsample_size = True\n\n # prepare attention_mask\n if attention_mask is not None: # None\n attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0\n attention_mask = attention_mask.unsqueeze(1)\n\n # 0. center input if necessary\n if self.config.center_input_sample: # False\n sample = 2 * sample - 1.0\n\n # 1. time\n timesteps = timestep\n if not torch.is_tensor(timesteps):\n # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can\n # This would be a good case for the `match` statement (Python 3.10+)\n is_mps = sample.device.type == \"mps\"\n if isinstance(timestep, float):\n dtype = torch.float32 if is_mps else torch.float64\n else:\n dtype = torch.int32 if is_mps else torch.int64\n timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)\n elif len(timesteps.shape) == 0:\n timesteps = timesteps[None].to(sample.device)\n\n # broadcast to batch dimension in a way that's compatible with ONNX/Core ML\n timesteps = timesteps.expand(sample.shape[0])\n\n t_emb = self.time_proj(timesteps)\n\n # timesteps does not contain any weights and will always return f32 tensors\n # but time_embedding might actually be running in fp16. so we need to cast here.\n # there might be better ways to encapsulate this.\n t_emb = t_emb.to(dtype=self.dtype)\n emb = self.time_embedding(t_emb)\n\n if self.class_embedding is not None:\n if class_labels is None:\n raise ValueError(\"class_labels should be provided when num_class_embeds > 0\")\n\n if self.config.class_embed_type == \"timestep\":\n class_labels = self.time_proj(class_labels)\n\n class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)\n emb = emb + class_emb\n\n # 2. pre-process\n sample = self.conv_in(sample)\n\n # 3. down\n down_block_res_samples = (sample,)\n for downsample_block in self.down_blocks:\n if hasattr(downsample_block, \"has_cross_attention\") and downsample_block.has_cross_attention:\n sample, res_samples = downsample_block(\n hidden_states=sample,\n temb=emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n )\n else:\n sample, res_samples = downsample_block(hidden_states=sample, temb=emb)\n\n down_block_res_samples += res_samples\n\n if down_block_additional_residuals is not None:\n new_down_block_res_samples = ()\n\n for down_block_res_sample, down_block_additional_residual in zip(\n down_block_res_samples, down_block_additional_residuals\n ):\n new_down_block_res_samples += (down_block_res_sample + down_block_additional_residual,)\n\n down_block_res_samples = new_down_block_res_samples\n\n # 4. mid\n sample = self.mid_block(\n sample, emb, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask\n )\n # for i in down_block_res_samples: print(i.shape) \n # torch.Size([1, 320, 16, 64, 64])\n # torch.Size([1, 320, 16, 64, 64])\n # torch.Size([1, 320, 16, 64, 64])\n # torch.Size([1, 320, 8, 32, 32])\n # torch.Size([1, 640, 8, 32, 32])\n # torch.Size([1, 640, 8, 32, 32])\n # torch.Size([1, 640, 4, 16, 16])\n # torch.Size([1, 1280, 4, 16, 16])\n # torch.Size([1, 1280, 4, 16, 16])\n # torch.Size([1, 1280, 2, 8, 8])\n # torch.Size([1, 1280, 2, 8, 8])\n # torch.Size([1, 1280, 2, 8, 8])\n if mid_block_additional_residual is not None:\n sample = sample + mid_block_additional_residual\n \n # 5. up\n for i, upsample_block in enumerate(self.up_blocks):\n is_final_block = i == len(self.up_blocks) - 1\n\n res_samples = down_block_res_samples[-len(upsample_block.resnets) :]\n down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]\n\n # if we have not reached the final block and need to forward the\n # upsample size, we do it here\n if not is_final_block and forward_upsample_size:\n upsample_size = down_block_res_samples[-1].shape[2:]\n\n if hasattr(upsample_block, \"has_cross_attention\") and upsample_block.has_cross_attention:\n sample = upsample_block(\n hidden_states=sample,\n temb=emb,\n res_hidden_states_tuple=res_samples,\n encoder_hidden_states=encoder_hidden_states,\n upsample_size=upsample_size,\n attention_mask=attention_mask,\n )\n else:\n sample = upsample_block(\n hidden_states=sample,\n temb=emb,\n res_hidden_states_tuple=res_samples,\n upsample_size=upsample_size,\n )\n # 6. post-process\n sample = self.conv_norm_out(sample)\n sample = self.conv_act(sample)\n sample = self.conv_out(sample)\n\n if not return_dict:\n return (sample,)\n\n return UNetPseudo3DConditionOutput(sample=sample)\n\n @classmethod\n def from_2d_model(cls, model_path, model_config):\n config_path = os.path.join(model_path, \"config.json\")\n if not os.path.isfile(config_path):\n raise RuntimeError(f\"{config_path} does not exist\")\n with open(config_path, \"r\") as f:\n config = json.load(f)\n\n config.pop(\"_class_name\")\n config.pop(\"_diffusers_version\")\n\n block_replacer = {\n \"CrossAttnDownBlock2D\": \"CrossAttnDownBlockPseudo3D\",\n \"DownBlock2D\": \"DownBlockPseudo3D\",\n \"UpBlock2D\": \"UpBlockPseudo3D\",\n \"CrossAttnUpBlock2D\": \"CrossAttnUpBlockPseudo3D\",\n }\n\n def convert_2d_to_3d_block(block):\n return block_replacer[block] if block in block_replacer else block\n\n config[\"down_block_types\"] = [\n convert_2d_to_3d_block(block) for block in config[\"down_block_types\"]\n ]\n config[\"up_block_types\"] = [convert_2d_to_3d_block(block) for block in config[\"up_block_types\"]]\n if model_config is not None:\n config.update(model_config)\n\n model = cls(**config)\n\n state_dict_path_condidates = glob.glob(os.path.join(model_path, \"*.bin\"))\n if state_dict_path_condidates:\n state_dict = torch.load(state_dict_path_condidates[0], map_location=\"cpu\")\n model.load_2d_state_dict(state_dict=state_dict)\n\n return model\n\n def load_2d_state_dict(self, state_dict, **kwargs):\n state_dict_3d = self.state_dict()\n\n for k, v in state_dict.items():\n if k not in state_dict_3d:\n raise KeyError(f\"2d state_dict key {k} does not exist in 3d model\")\n elif v.shape != state_dict_3d[k].shape:\n raise ValueError(f\"state_dict shape mismatch, 2d {v.shape}, 3d {state_dict_3d[k].shape}\")\n\n for k, v in state_dict_3d.items():\n if \"_temporal\" in k:\n continue\n if k not in state_dict:\n raise KeyError(f\"3d state_dict key {k} does not exist in 2d model\")\n\n state_dict_3d.update(state_dict)\n self.load_state_dict(state_dict_3d, **kwargs)" }, { "identifier": "ControlNetPseudo3DModel", "path": "video_diffusion/models/controlnet_3d_condition.py", "snippet": "class ControlNetPseudo3DModel(ModelMixin, ConfigMixin):\n _supports_gradient_checkpointing = True\n\n @register_to_config\n def __init__(\n self,\n in_channels: int = 4,\n flip_sin_to_cos: bool = True,\n freq_shift: int = 0,\n down_block_types: Tuple[str] = (\n \"CrossAttnDownBlockPseudo3D\",\n \"CrossAttnDownBlockPseudo3D\",\n \"CrossAttnDownBlockPseudo3D\",\n \"DownBlockPseudo3D\",\n ),\n only_cross_attention: Union[bool, Tuple[bool]] = False,\n block_out_channels: Tuple[int] = (320, 640, 1280, 1280),\n layers_per_block: int = 2,\n downsample_padding: int = 1,\n mid_block_scale_factor: float = 1,\n act_fn: str = \"silu\",\n norm_num_groups: Optional[int] = 32,\n norm_eps: float = 1e-5,\n cross_attention_dim: int = 1280,\n attention_head_dim: Union[int, Tuple[int]] = 8,\n use_linear_projection: bool = False,\n class_embed_type: Optional[str] = None,\n num_class_embeds: Optional[int] = None,\n upcast_attention: bool = False,\n resnet_time_scale_shift: str = \"default\",\n projection_class_embeddings_input_dim: Optional[int] = None,\n controlnet_conditioning_channel_order: str = \"rgb\",\n conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),\n **kwargs\n ):\n super().__init__()\n\n if 'temporal_downsample' in kwargs and kwargs['temporal_downsample'] is True:\n kwargs['temporal_downsample_time'] = 3\n self.temporal_downsample_time = kwargs.get('temporal_downsample_time', 0)\n\n # Check inputs\n if len(block_out_channels) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}.\"\n )\n\n if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}.\"\n )\n\n if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}.\"\n )\n\n # input\n conv_in_kernel = 3\n conv_in_padding = (conv_in_kernel - 1) // 2\n # self.conv_in = PseudoConv3d(\n # in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding\n # )\n self.conv_in = InflatedConv3d(\n in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding\n )\n # time\n time_embed_dim = block_out_channels[0] * 4\n\n self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)\n timestep_input_dim = block_out_channels[0]\n\n self.time_embedding = TimestepEmbedding(\n timestep_input_dim,\n time_embed_dim,\n act_fn=act_fn,\n )\n\n # class embedding\n if class_embed_type is None and num_class_embeds is not None:\n self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)\n elif class_embed_type == \"timestep\":\n self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n elif class_embed_type == \"identity\":\n self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)\n elif class_embed_type == \"projection\":\n if projection_class_embeddings_input_dim is None:\n raise ValueError(\n \"`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set\"\n )\n # The projection `class_embed_type` is the same as the timestep `class_embed_type` except\n # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings\n # 2. it projects from an arbitrary input dimension.\n #\n # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.\n # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.\n # As a result, `TimestepEmbedding` can be passed arbitrary vectors.\n self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)\n else:\n self.class_embedding = None\n\n # control net conditioning embedding\n self.controlnet_cond_embedding = ControlNetPseudo3DConditioningEmbedding(\n conditioning_embedding_channels=block_out_channels[0],\n block_out_channels=conditioning_embedding_out_channels,\n )\n\n self.down_blocks = nn.ModuleList([])\n self.controlnet_down_blocks = nn.ModuleList([])\n\n if isinstance(only_cross_attention, bool):\n only_cross_attention = [only_cross_attention] * len(down_block_types)\n\n if isinstance(attention_head_dim, int):\n attention_head_dim = (attention_head_dim,) * len(down_block_types)\n\n # down\n output_channel = block_out_channels[0]\n\n # controlnet_block = PseudoConv3d(output_channel, output_channel, kernel_size=1)\n controlnet_block = InflatedConv3d(output_channel, output_channel, kernel_size=1)\n\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n for i, down_block_type in enumerate(down_block_types):\n input_channel = output_channel\n output_channel = block_out_channels[i]\n is_final_block = i == len(block_out_channels) - 1\n #non temperal \n # kwargs_copy=copy.deepcopy(kwargs)\n # temporal_downsample_i = ((i >= (len(down_block_types)-self.temporal_downsample_time))\n # and (not is_final_block))\n # kwargs_copy.update({'temporal_downsample': temporal_downsample_i} )\n\n down_block = get_down_block(\n down_block_type,\n num_layers=layers_per_block,\n in_channels=input_channel,\n out_channels=output_channel,\n temb_channels=time_embed_dim,\n add_downsample=not is_final_block,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[i],\n downsample_padding=downsample_padding,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n # model_config=kwargs_copy\n )\n self.down_blocks.append(down_block)\n\n for _ in range(layers_per_block):\n # controlnet_block = PseudoConv3d(output_channel, output_channel, kernel_size=1)\n controlnet_block = InflatedConv3d(output_channel, output_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n if not is_final_block:\n # controlnet_block = PseudoConv3d(output_channel, output_channel, kernel_size=1)\n controlnet_block = InflatedConv3d(output_channel, output_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n # mid\n mid_block_channel = block_out_channels[-1]\n\n # controlnet_block = PseudoConv3d(mid_block_channel, mid_block_channel, kernel_size=1)\n controlnet_block = InflatedConv3d(mid_block_channel, mid_block_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_mid_block = controlnet_block\n\n self.mid_block = UNetMidBlockPseudo3DCrossAttn(\n in_channels=mid_block_channel,\n temb_channels=time_embed_dim,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n output_scale_factor=mid_block_scale_factor,\n resnet_time_scale_shift=resnet_time_scale_shift,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[-1],\n resnet_groups=norm_num_groups,\n use_linear_projection=use_linear_projection,\n upcast_attention=upcast_attention,\n # model_config=kwargs\n )\n\n def set_attention_slice(self, slice_size):\n r\"\"\"\n Enable sliced attention computation.\n\n When this option is enabled, the attention module will split the input tensor in slices, to compute attention\n in several steps. This is useful to save some memory in exchange for a small speed decrease.\n\n Args:\n slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `\"auto\"`):\n When `\"auto\"`, halves the input to the attention heads, so attention will be computed in two steps. If\n `\"max\"`, maxium amount of memory will be saved by running only one slice at a time. If a number is\n provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`\n must be a multiple of `slice_size`.\n \"\"\"\n sliceable_head_dims = []\n\n def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):\n if hasattr(module, \"set_attention_slice\"):\n sliceable_head_dims.append(module.sliceable_head_dim)\n\n for child in module.children():\n fn_recursive_retrieve_slicable_dims(child)\n\n # retrieve number of attention layers\n for module in self.children():\n fn_recursive_retrieve_slicable_dims(module)\n\n num_slicable_layers = len(sliceable_head_dims)\n\n if slice_size == \"auto\":\n # half the attention head size is usually a good trade-off between\n # speed and memory\n slice_size = [dim // 2 for dim in sliceable_head_dims]\n elif slice_size == \"max\":\n # make smallest slice possible\n slice_size = num_slicable_layers * [1]\n\n slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size\n\n if len(slice_size) != len(sliceable_head_dims):\n raise ValueError(\n f\"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different\"\n f\" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}.\"\n )\n\n for i in range(len(slice_size)):\n size = slice_size[i]\n dim = sliceable_head_dims[i]\n if size is not None and size > dim:\n raise ValueError(f\"size {size} has to be smaller or equal to {dim}.\")\n\n # Recursively walk through all the children.\n # Any children which exposes the set_attention_slice method\n # gets the message\n def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):\n if hasattr(module, \"set_attention_slice\"):\n module.set_attention_slice(slice_size.pop())\n\n for child in module.children():\n fn_recursive_set_attention_slice(child, slice_size)\n\n reversed_slice_size = list(reversed(slice_size))\n for module in self.children():\n fn_recursive_set_attention_slice(module, reversed_slice_size)\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, (CrossAttnDownBlockPseudo3D, DownBlockPseudo3D)):\n module.gradient_checkpointing = value\n\n def forward(\n self,\n sample: torch.FloatTensor,\n timestep: Union[torch.Tensor, float, int],\n encoder_hidden_states: torch.Tensor,\n controlnet_cond: torch.FloatTensor,\n class_labels: Optional[torch.Tensor] = None,\n timestep_cond: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n return_dict: bool = True,\n ) -> Union[ControlNetPseudo3DOutput, Tuple]:\n # check channel order\n channel_order = self.config.controlnet_conditioning_channel_order\n if channel_order == \"rgb\":\n # in rgb order by default\n ...\n elif channel_order == \"bgr\":\n controlnet_cond = torch.flip(controlnet_cond, dims=[1])\n else:\n raise ValueError(f\"unknown `controlnet_conditioning_channel_order`: {channel_order}\")\n\n # prepare attention_mask\n if attention_mask is not None:\n attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0\n attention_mask = attention_mask.unsqueeze(1)\n\n # 1. time\n timesteps = timestep\n if not torch.is_tensor(timesteps):\n # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can\n # This would be a good case for the `match` statement (Python 3.10+)\n is_mps = sample.device.type == \"mps\"\n if isinstance(timestep, float):\n dtype = torch.float32 if is_mps else torch.float64\n else:\n dtype = torch.int32 if is_mps else torch.int64\n timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)\n elif len(timesteps.shape) == 0:\n timesteps = timesteps[None].to(sample.device)\n\n # broadcast to batch dimension in a way that's compatible with ONNX/Core ML\n timesteps = timesteps.expand(sample.shape[0])\n\n t_emb = self.time_proj(timesteps)\n \n\n # timesteps does not contain any weights and will always return f32 tensors\n # but time_embedding might actually be running in fp16. so we need to cast here.\n # there might be better ways to encapsulate this.\n t_emb = t_emb.to(dtype=self.dtype)\n\n emb = self.time_embedding(t_emb)\n\n\n if self.class_embedding is not None:\n if class_labels is None:\n raise ValueError(\"class_labels should be provided when num_class_embeds > 0\")\n\n if self.config.class_embed_type == \"timestep\":\n class_labels = self.time_proj(class_labels)\n\n class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)\n emb = emb + class_emb\n\n # 2. pre-process\n sample = self.conv_in(sample)\n\n controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)\n # print(sample.shape,controlnet_cond.shape)\n sample += controlnet_cond\n \n # 3. down\n down_block_res_samples = (sample,)\n for downsample_block in self.down_blocks:\n if hasattr(downsample_block, \"has_cross_attention\") and downsample_block.has_cross_attention:\n sample, res_samples = downsample_block(\n hidden_states=sample,\n temb=emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n )\n else:\n sample, res_samples = downsample_block(hidden_states=sample, temb=emb)\n\n down_block_res_samples += res_samples\n\n # 4. mid\n if self.mid_block is not None:\n sample = self.mid_block(\n sample,\n emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n )\n\n # 5. Control net blocks\n\n controlnet_down_block_res_samples = ()\n\n for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):\n down_block_res_sample = controlnet_block(down_block_res_sample)\n controlnet_down_block_res_samples += (down_block_res_sample,)\n\n down_block_res_samples = controlnet_down_block_res_samples\n\n mid_block_res_sample = self.controlnet_mid_block(sample)\n\n if not return_dict:\n return (down_block_res_samples, mid_block_res_sample)\n\n return ControlNetPseudo3DOutput(\n down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample\n )\n\n @classmethod\n def from_pretrained_2d(cls, pretrained_model_path, subfolder=None, control_temporal_idx=None, control_mid_temporal=None):\n if subfolder is not None:\n pretrained_model_path = os.path.join(pretrained_model_path, subfolder)\n\n config_file = os.path.join(pretrained_model_path, 'config.json')\n if not os.path.isfile(config_file):\n raise RuntimeError(f\"{config_file} does not exist\")\n with open(config_file, \"r\") as f:\n config = json.load(f)\n config[\"_class_name\"] = cls.__name__\n config[\"down_block_types\"] = [\n \"CrossAttnDownBlockPseudo3D\",\n \"CrossAttnDownBlockPseudo3D\",\n \"CrossAttnDownBlockPseudo3D\",\n \"DownBlockPseudo3D\"\n ]\n # config[\"control_temporal_idx\"] = control_temporal_idx\n # config[\"control_mid_temporal\"] = control_mid_temporal\n\n from diffusers.utils import WEIGHTS_NAME\n model = cls.from_config(config)\n model_file = os.path.join(pretrained_model_path, WEIGHTS_NAME)\n if not os.path.isfile(model_file):\n raise RuntimeError(f\"{model_file} does not exist\")\n\n state_dict = torch.load(model_file, map_location=\"cpu\")\n for k, v in model.state_dict().items():\n if '_temp.' in k:\n if 'conv' in k:\n state_dict.update({k: v})\n else:\n copyk = k\n copyk = copyk.replace('_temp.', '1.')\n state_dict.update({k: state_dict[copyk]})\n model.load_state_dict(state_dict)\n\n return model\n\n\n @classmethod\n def from_2d_model(cls, model_path, model_config):\n config_path = os.path.join(model_path, \"config.json\")\n if not os.path.isfile(config_path):\n raise RuntimeError(f\"{config_path} does not exist\")\n with open(config_path, \"r\") as f:\n config = json.load(f)\n\n config.pop(\"_class_name\")\n config.pop(\"_diffusers_version\")\n\n block_replacer = {\n \"CrossAttnDownBlock2D\": \"CrossAttnDownBlockPseudo3D\",\n \"DownBlock2D\": \"DownBlockPseudo3D\",\n \"UpBlock2D\": \"UpBlockPseudo3D\",\n \"CrossAttnUpBlock2D\": \"CrossAttnUpBlockPseudo3D\",\n }\n\n def convert_2d_to_3d_block(block):\n return block_replacer[block] if block in block_replacer else block\n\n config[\"down_block_types\"] = [\n convert_2d_to_3d_block(block) for block in config[\"down_block_types\"]\n ]\n \n if model_config is not None:\n config.update(model_config)\n\n model = cls(**config)\n\n state_dict_path_condidates = glob.glob(os.path.join(model_path, \"*.bin\"))\n if state_dict_path_condidates:\n state_dict = torch.load(state_dict_path_condidates[0], map_location=\"cpu\")\n model.load_2d_state_dict(state_dict=state_dict)\n\n return model\n\n def load_2d_state_dict(self, state_dict, **kwargs):\n state_dict_3d = self.state_dict()\n\n for k, v in state_dict.items():\n if k not in state_dict_3d:\n raise KeyError(f\"2d state_dict key {k} does not exist in 3d model\")\n elif v.shape != state_dict_3d[k].shape:\n raise ValueError(f\"state_dict shape mismatch, 2d {v.shape}, 3d {state_dict_3d[k].shape}\")\n\n for k, v in state_dict_3d.items():\n if \"_temporal\" in k:\n continue\n if k not in state_dict:\n raise KeyError(f\"3d state_dict key {k} does not exist in 2d model\")\n\n state_dict_3d.update(state_dict)\n self.load_state_dict(state_dict_3d, **kwargs)" }, { "identifier": "ImageSequenceDataset", "path": "video_diffusion/data/dataset.py", "snippet": "class ImageSequenceDataset(Dataset):\n def __init__(\n self,\n path: str,\n prompt_ids: torch.Tensor,\n prompt: str,\n start_sample_frame: int=0,\n n_sample_frame: int = 8,\n sampling_rate: int = 1,\n stride: int = -1, # only used during tuning to sample a long video\n image_mode: str = \"RGB\",\n image_size: int = 512,\n crop: str = \"center\",\n \n class_data_root: str = None,\n class_prompt_ids: torch.Tensor = None,\n \n offset: dict = {\n \"left\": 0,\n \"right\": 0,\n \"top\": 0,\n \"bottom\": 0\n },\n **args\n \n ):\n self.path = path\n self.images = self.get_image_list(path)\n self.n_images = len(self.images)\n self.offset = offset\n self.start_sample_frame = start_sample_frame\n if n_sample_frame < 0:\n n_sample_frame = len(self.images) \n self.n_sample_frame = n_sample_frame\n # local sampling rate from the video\n self.sampling_rate = sampling_rate\n\n self.sequence_length = (n_sample_frame - 1) * sampling_rate + 1\n if self.n_images < self.sequence_length:\n raise ValueError(f\"self.n_images {self.n_images } < self.sequence_length {self.sequence_length}: Required number of frames {self.sequence_length} larger than total frames in the dataset {self.n_images }\")\n \n # During tuning if video is too long, we sample the long video every self.stride globally\n self.stride = stride if stride > 0 else (self.n_images+1)\n self.video_len = (self.n_images - self.sequence_length) // self.stride + 1\n\n self.image_mode = image_mode\n self.image_size = image_size\n crop_methods = {\n \"center\": center_crop,\n \"random\": random_crop,\n }\n if crop not in crop_methods:\n raise ValueError\n self.crop = crop_methods[crop]\n\n self.prompt = prompt\n self.prompt_ids = prompt_ids\n # Negative prompt for regularization to avoid overfitting during one-shot tuning\n if class_data_root is not None:\n self.class_data_root = Path(class_data_root)\n self.class_images_path = sorted(list(self.class_data_root.iterdir()))\n self.num_class_images = len(self.class_images_path)\n self.class_prompt_ids = class_prompt_ids\n \n \n def __len__(self):\n max_len = (self.n_images - self.sequence_length) // self.stride + 1\n \n if hasattr(self, 'num_class_images'):\n max_len = max(max_len, self.num_class_images)\n \n return max_len\n\n def __getitem__(self, index):\n return_batch = {}\n frame_indices = self.get_frame_indices(index%self.video_len)\n frames = [self.load_frame(i) for i in frame_indices]\n frames = self.transform(frames)\n\n return_batch.update(\n {\n \"images\": frames,\n \"prompt_ids\": self.prompt_ids,\n }\n )\n\n if hasattr(self, 'class_data_root'):\n class_index = index % (self.num_class_images - self.n_sample_frame)\n class_indices = self.get_class_indices(class_index) \n frames = [self.load_class_frame(i) for i in class_indices]\n return_batch[\"class_images\"] = self.tensorize_frames(frames)\n return_batch[\"class_prompt_ids\"] = self.class_prompt_ids\n return return_batch\n \n def transform(self, frames):\n frames = self.tensorize_frames(frames)\n frames = offset_crop(frames, **self.offset)\n frames = short_size_scale(frames, size=self.image_size)\n frames = self.crop(frames, height=self.image_size, width=self.image_size)\n return frames\n\n @staticmethod\n def tensorize_frames(frames):\n frames = rearrange(np.stack(frames), \"f h w c -> c f h w\")\n return torch.from_numpy(frames).div(255) * 2 - 1\n\n def load_frame(self, index):\n image_path = os.path.join(self.path, self.images[index])\n return Image.open(image_path).convert(self.image_mode)\n\n def load_class_frame(self, index):\n image_path = self.class_images_path[index]\n return Image.open(image_path).convert(self.image_mode)\n\n def get_frame_indices(self, index):\n if self.start_sample_frame is not None:\n frame_start = self.start_sample_frame + self.stride * index\n else:\n frame_start = self.stride * index\n return (frame_start + i * self.sampling_rate for i in range(self.n_sample_frame))\n\n def get_class_indices(self, index):\n frame_start = index\n return (frame_start + i for i in range(self.n_sample_frame))\n\n @staticmethod\n def get_image_list(path):\n images = []\n for file in sorted(os.listdir(path)):\n if file.endswith(IMAGE_EXTENSION):\n images.append(file)\n return images" }, { "identifier": "get_time_string", "path": "video_diffusion/common/util.py", "snippet": "def get_time_string() -> str:\n x = datetime.datetime.now()\n return f\"{(x.year - 2000):02d}{x.month:02d}{x.day:02d}-{x.hour:02d}{x.minute:02d}{x.second:02d}\"" }, { "identifier": "get_function_args", "path": "video_diffusion/common/util.py", "snippet": "def get_function_args() -> Dict:\n frame = sys._getframe(1)\n args, _, _, values = inspect.getargvalues(frame)\n args_dict = copy.deepcopy({arg: values[arg] for arg in args})\n\n return args_dict" }, { "identifier": "get_logger_config_path", "path": "video_diffusion/common/logger.py", "snippet": "def get_logger_config_path(logdir):\n # accelerate handles the logger in multiprocessing\n logger = get_logger(__name__)\n logging.basicConfig(\n level=logging.INFO, \n format='%(asctime)s:%(levelname)s : %(message)s', \n datefmt='%a, %d %b %Y %H:%M:%S', \n filename=os.path.join(logdir, 'log.log'),\n filemode='w')\n chlr = logging.StreamHandler()\n chlr.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s : %(message)s'))\n logger.logger.addHandler(chlr)\n return logger" }, { "identifier": "log_train_samples", "path": "video_diffusion/common/image_util.py", "snippet": "def log_train_samples(\n train_dataloader,\n save_path,\n num_batch: int = 4,\n):\n train_samples = []\n for idx, batch in enumerate(train_dataloader):\n if idx >= num_batch:\n break\n train_samples.append(batch[\"images\"])\n\n train_samples = torch.cat(train_samples).numpy()\n train_samples = rearrange(train_samples, \"b c f h w -> b f h w c\")\n train_samples = (train_samples * 0.5 + 0.5).clip(0, 1)\n train_samples = numpy_batch_seq_to_pil(train_samples)\n train_samples = [make_grid(images, cols=int(np.ceil(np.sqrt(len(train_samples))))) for images in zip(*train_samples)]\n # save_images_as_gif(train_samples, save_path)\n save_gif_mp4_folder_type(train_samples, save_path)" }, { "identifier": "instantiate_from_config", "path": "video_diffusion/common/instantiate_from_config.py", "snippet": "def instantiate_from_config(config:dict, **args_from_code):\n \"\"\"Util funciton to decompose differenct modules using config\n\n Args:\n config (dict): with key of \"target\" and \"params\", better from yaml\n static \n args_from_code: additional con\n\n\n Returns:\n a validation/training pipeline, a module\n \"\"\"\n if not \"target\" in config:\n if config == '__is_first_stage__':\n return None\n elif config == \"__is_unconditional__\":\n return None\n raise KeyError(\"Expected key `target` to instantiate.\")\n return get_obj_from_str(config[\"target\"])(**config.get(\"params\", dict()), **args_from_code)" }, { "identifier": "P2pSampleLogger", "path": "video_diffusion/pipelines/p2p_validation_loop_controlnet.py", "snippet": "class P2pSampleLogger:\n def __init__(\n self,\n editing_prompts: List[str],\n clip_length: int,\n logdir: str,\n subdir: str = \"sample\",\n num_samples_per_prompt: int = 1,\n sample_seeds: List[int] = None,\n num_inference_steps: int = 20,\n guidance_scale: float = 7,\n strength: float = None,\n annotate: bool = False,\n annotate_size: int = 15,\n use_make_grid: bool = True,\n grid_column_size: int = 2,\n prompt2prompt_edit: bool=False,\n p2p_config: dict = None,\n use_inversion_attention: bool = True,\n source_prompt: str = None,\n traverse_p2p_config: bool = False,\n **args\n ) -> None:\n self.editing_prompts = editing_prompts\n self.clip_length = clip_length\n self.guidance_scale = guidance_scale\n self.num_inference_steps = num_inference_steps\n self.strength = strength\n\n if sample_seeds is None:\n max_num_samples_per_prompt = int(1e5)\n if num_samples_per_prompt > max_num_samples_per_prompt:\n raise ValueError\n sample_seeds = torch.randint(0, max_num_samples_per_prompt, (num_samples_per_prompt,))\n sample_seeds = sorted(sample_seeds.numpy().tolist())\n self.sample_seeds = sample_seeds\n\n self.logdir = os.path.join(logdir, subdir)\n os.makedirs(self.logdir)\n\n self.annotate = annotate\n self.annotate_size = annotate_size\n self.make_grid = use_make_grid\n self.grid_column_size = grid_column_size\n self.prompt2prompt_edit = prompt2prompt_edit\n self.p2p_config = p2p_config\n self.use_inversion_attention = use_inversion_attention\n self.source_prompt = source_prompt\n self.traverse_p2p_config =traverse_p2p_config\n\n def log_sample_images(\n self, pipeline: DiffusionPipeline,\n device: torch.device, step: int,\n image: Union[torch.FloatTensor, PIL.Image.Image] = None,\n control_image: torch.FloatTensor = None,\n latents: torch.FloatTensor = None,\n mask:torch.FloatTensor = None,\n editing_type:str = \"attribute\",\n uncond_embeddings_list: List[torch.FloatTensor] = None,\n save_dir = None,\n duration = 100,\n fps = 10,\n use_interpolater = True\n ):\n torch.cuda.empty_cache()\n samples_all = []\n attention_all = []\n # handle input image\n if image is not None:\n input_pil_images = pipeline.numpy_to_pil(tensor_to_numpy(image))[0]\n if self.annotate :\n samples_all.append([\n annotate_image(image, \"input sequence\", font_size=self.annotate_size) for image in input_pil_images\n ])\n else:\n samples_all.append(input_pil_images)\n if isinstance(self.editing_prompts,str):\n self.editing_prompts = [self.editing_prompts]\n for idx, prompt in enumerate(tqdm(self.editing_prompts, desc=\"Generating sample images\")):\n # if self.prompt2prompt_edit:\n # if self.traverse_p2p_config:\n # p2p_config_now = copy.deepcopy(self.p2p_config[idx])\n # else:\n # p2p_config_now = copy.deepcopy(self.p2p_config[idx])\n\n # if idx == 0 and not self.use_inversion_attention:\n # edit_type = 'save'\n # p2p_config_now.update({'save_self_attention': True})\n # print('Reflash the attention map in pipeline')\n\n # else:\n # edit_type = 'swap'\n # p2p_config_now.update({'save_self_attention': False})\n\n # p2p_config_now.update({'use_inversion_attention': self.use_inversion_attention})\n # else:\n # edit_type = None\n\n input_prompt = prompt\n\n # generator = torch.Generator(device=device)\n # generator.manual_seed(seed)\n generator = None\n sequence = []\n window = 8\n window = min(window,self.clip_length)\n start_frame = 0\n end_frame = window\n patch_index = 0\n while start_frame < self.clip_length:\n torch.cuda.empty_cache()\n if patch_index == 0:\n sequence_return = pipeline(\n prompt=input_prompt,\n source_prompt = self.editing_prompts[0] if self.source_prompt is None else self.source_prompt,\n # edit_type = edit_type,\n image=image[[0] + [0] + list(range(start_frame,min(self.clip_length,end_frame))),], # torch.Size([8, 3, 512, 512])\n strength=self.strength,\n generator=generator,\n # window = 1,\n num_inference_steps=self.num_inference_steps,\n guidance_scale=self.guidance_scale,\n num_images_per_prompt=1,\n # used in null inversion\n editing_type = editing_type,\n latents = [timestep_latent[:, :,[0] + [0] + list(range(start_frame,min(self.clip_length,end_frame))), :, :] for timestep_latent in latents],\n mask = mask[:,:, [0] + [0] + list(range(start_frame, min(self.clip_length,end_frame))),] if mask is not None else None,\n # latents = [timestep_latent[:, :,list(range(start_frame,min(self.clip_length,end_frame))), :, :] for timestep_latent in latents],\n # mask = mask[:,:, list(range(start_frame, min(self.clip_length,end_frame))),] if mask is not None else None,\n uncond_embeddings_list = uncond_embeddings_list,\n save_path = save_dir,\n # **p2p_config_now,\n )\n else:\n sequence_return = pipeline(\n prompt=input_prompt,\n reference_global_latents = reference_global_latents,\n reference_latents = reference_latents,\n source_prompt = self.editing_prompts[0] if self.source_prompt is None else self.source_prompt,\n # edit_type = edit_type,\n image=image[[0] + list(range(start_frame - 1,min(self.clip_length,end_frame))),], # torch.Size([8, 3, 512, 512])\n strength=self.strength,\n generator=generator,\n # window = window,\n num_inference_steps=self.num_inference_steps,\n guidance_scale=self.guidance_scale,\n num_images_per_prompt=1,\n # used in null inversion\n editing_type = editing_type,\n latents = [timestep_latent[:, :,[0] + list(range(start_frame-1,min(self.clip_length,end_frame))), :, :] for timestep_latent in latents],\n mask = mask[:,:, [0] + list(range(start_frame-1, min(self.clip_length,end_frame))),] if mask is not None else None,\n # latents = [timestep_latent[:, :,list(range(start_frame,min(self.clip_length,end_frame))), :, :] for timestep_latent in latents],\n # mask = mask[:,:, list(range(start_frame, min(self.clip_length,end_frame))),] if mask is not None else None,\n uncond_embeddings_list = uncond_embeddings_list,\n save_path = save_dir,\n # **p2p_config_now,\n )\n start_frame = end_frame\n end_frame = end_frame + window\n if patch_index == 0:\n reference_global_latents = sequence_return['reference_global_latents']\n reference_latents = sequence_return['reference_latents']\n patch_index = patch_index + 1\n # if self.prompt2prompt_edit:\n # sequence_temp = sequence_return['sdimage_output'].images[0]\n # # attention_output = sequence_return['attention_output']\n # else:\n # sequence_temp = sequence_return.images[0]\n sequence_temp = sequence_return['sdimage_output'].images[0]\n sequence = sequence + sequence_temp\n torch.cuda.empty_cache()\n # sequence = torch.cat(sequence,dim = 2)\n\n if self.annotate:\n images = [\n annotate_image(image, prompt, font_size=self.annotate_size) for image in sequence\n ]\n else:\n images = sequence\n control_images = []\n for i in range(control_image.shape[2]):\n control_images.append(Image.fromarray((control_image[0,:,i]*255).cpu().numpy().transpose(1,2,0).astype(np.uint8)))\n #smoother start\n if use_interpolater:\n for i in range(len(images)):\n images[i] = np.array(images[i]).transpose(2,0,1)[None:]/255\n frames = torch.from_numpy(np.stack(images, axis= 0)).cuda()\n f, C, H, W = frames.shape\n ph = ((H - 1) // 32 + 1) * 32\n pw = ((W - 1) // 32 + 1) * 32\n padding = (0, pw - W, 0, ph - H)\n frames = F.pad(frames,padding)\n smoother = Model()\n smoother.load_model('RIFEModel', -1)\n print('using smoother')\n with torch.no_grad():\n for i in range(f - 2):\n img0 = frames[i:i+1].float()\n img1 = frames[i+2:i+3].float()\n mid = smoother.inference(img0,img1)\n mid_padded = F.pad(mid,padding)\n frames[i+1:i+2,] = (frames[i+1:i+2,] + mid_padded[None:])/2\n torch.cuda.empty_cache()\n images = []\n for i in range(len(frames)):\n images.append(Image.fromarray((frames[i] * 255).cpu().numpy().astype(np.uint8).transpose(1,2,0)))\n # smoother end\n if self.make_grid:\n samples_all.append(control_images)\n samples_all.append(images)\n # if self.prompt2prompt_edit:\n # if attention_output is not None:\n # attention_all.append(attention_output)\n\n save_path = os.path.join(self.logdir, f\"step_{step}_{idx}.gif\")\n save_gif_mp4_folder_type(images, save_path,duration = duration,fps = fps)\n\n # if self.prompt2prompt_edit:\n\n # if attention_output is not None:\n # save_gif_mp4_folder_type(attention_output, save_path.replace('.gif', 'atten.gif'),duration = duration,fps = fps)\n\n if self.make_grid:\n samples_all = [make_grid(images, cols=int(len(samples_all))) for images in zip(*samples_all)]\n save_path = os.path.join(self.logdir, f\"step_{step}.gif\")\n save_gif_mp4_folder_type(samples_all, save_path,duration = duration,fps = fps)\n if self.prompt2prompt_edit:\n if len(attention_all) > 0 :\n attention_all = [make_grid(images, cols=1) for images in zip(*attention_all)]\n if len(attention_all) > 0:\n save_gif_mp4_folder_type(attention_all, save_path.replace('.gif', 'atten.gif'),duration = duration,fps = fps)\n return samples_all" }, { "identifier": "get_control", "path": "annotator/util.py", "snippet": "def get_control(type):\n if type == 'canny':\n from .canny import CannyDetector\n apply_control = CannyDetector()\n elif type == 'openpose':\n from .openpose import OpenposeDetector\n apply_control = OpenposeDetector()\n elif type == 'depth' or type == 'normal':\n from .midas import MidasDetector\n apply_control = MidasDetector()\n elif type == 'hed':\n from .hed import HEDdetector\n apply_control = HEDdetector()\n elif type == 'scribble':\n apply_control = None\n elif type == 'seg':\n from .uniformer import UniformerDetector\n apply_control = UniformerDetector()\n elif type == 'mlsd':\n from .mlsd import MLSDdetector\n apply_control = MLSDdetector()\n else:\n raise TypeError(type)\n return apply_control" }, { "identifier": "DDIMInterpolationScheduler", "path": "video_diffusion/pipelines/DDIMInterpolationScheduler.py", "snippet": "class DDIMInterpolationScheduler(DDIMScheduler):\n \"\"\"\n Denoising diffusion implicit models is a scheduler that extends the denoising procedure introduced in denoising\n diffusion probabilistic models (DDPMs) with non-Markovian guidance.\n\n [`~ConfigMixin`] takes care of storing all config attributes that are passed in the scheduler's `__init__`\n function, such as `num_train_timesteps`. They can be accessed via `scheduler.config.num_train_timesteps`.\n [`SchedulerMixin`] provides general loading and saving functionality via the [`SchedulerMixin.save_pretrained`] and\n [`~SchedulerMixin.from_pretrained`] functions.\n\n For more details, see the original paper: https://arxiv.org/abs/2010.02502\n\n Args:\n num_train_timesteps (`int`): number of diffusion steps used to train the model.\n beta_start (`float`): the starting `beta` value of inference.\n beta_end (`float`): the final `beta` value.\n beta_schedule (`str`):\n the beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from\n `linear`, `scaled_linear`, or `squaredcos_cap_v2`.\n trained_betas (`np.ndarray`, optional):\n option to pass an array of betas directly to the constructor to bypass `beta_start`, `beta_end` etc.\n clip_sample (`bool`, default `True`):\n option to clip predicted sample between -1 and 1 for numerical stability.\n set_alpha_to_one (`bool`, default `True`):\n each diffusion step uses the value of alphas product at that step and at the previous one. For the final\n step there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`,\n otherwise it uses the value of alpha at step 0.\n steps_offset (`int`, default `0`):\n an offset added to the inference steps. You can use a combination of `offset=1` and\n `set_alpha_to_one=False`, to make the last step use step 0 for the previous alpha product, as done in\n stable diffusion.\n prediction_type (`str`, default `epsilon`, optional):\n prediction type of the scheduler function, one of `epsilon` (predicting the noise of the diffusion\n process), `sample` (directly predicting the noisy sample`) or `v_prediction` (see section 2.4\n https://imagen.research.google/video/paper.pdf)\n \"\"\"\n\n _compatibles = _COMPATIBLE_STABLE_DIFFUSION_SCHEDULERS.copy()\n _deprecated_kwargs = [\"predict_epsilon\"]\n order = 1\n\n def set_model(self,vae,interpolater):\n self.interpolater = interpolater\n self.vae = vae\n \n \n def decode_latents(self, latents):\n is_video = (latents.dim() == 5)\n b = latents.shape[0]\n latents = 1 / 0.18215 * latents\n \n if is_video:\n latents = rearrange(latents, \"b c f h w -> (b f) c h w\") # torch.Size([70, 4, 64, 64])\n\n latents_split = torch.split(latents, 16, dim=0)\n image = torch.cat([self.vae.decode(l).sample for l in latents_split], dim=0)\n \n # image_full = self.vae.decode(latents).sample\n # RuntimeError: upsample_nearest_nhwc only supports output tensors with less than INT_MAX elements\n # Pytorch upsample alogrithm not work for batch size 32 -> 64 \n image = (image / 2 + 0.5).clamp(0, 1)\n # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16\n\n # image = image.cpu().float().numpy()\n # if is_video:\n # image = rearrange(image, \"(b f) c h w -> b f h w c\", b=b)\n # else:\n # image = rearrange(image, \"b c h w -> b h w c\", b=b)\n return image\n def encode_latents(self,images,generator = None):\n if len(images.shape) == 4:\n images = images[None:]\n images = ((images - 0.5) * 2 ) \n latents = self.vae.encode(images).latent_dist.sample(generator)\n latents = latents * 0.18215\n return latents\n\n def step(\n self,\n model_output: torch.FloatTensor,\n timestep: int,\n sample: torch.FloatTensor,\n eta: float = 0.0,\n use_clipped_model_output: bool = False,\n generator=None,\n variance_noise: Optional[torch.FloatTensor] = None,\n return_dict: bool = True,\n ) -> Union[DDIMSchedulerOutput, Tuple]:\n \"\"\"\n Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion\n process from the learned model outputs (most often the predicted noise).\n\n Args:\n model_output (`torch.FloatTensor`): direct output from learned diffusion model.\n timestep (`int`): current discrete timestep in the diffusion chain.\n sample (`torch.FloatTensor`):\n current instance of sample being created by diffusion process.\n eta (`float`): weight of noise for added noise in diffusion step.\n use_clipped_model_output (`bool`): if `True`, compute \"corrected\" `model_output` from the clipped\n predicted original sample. Necessary because predicted original sample is clipped to [-1, 1] when\n `self.config.clip_sample` is `True`. If no clipping has happened, \"corrected\" `model_output` would\n coincide with the one provided as input and `use_clipped_model_output` will have not effect.\n generator: random number generator.\n variance_noise (`torch.FloatTensor`): instead of generating noise for the variance using `generator`, we\n can directly provide the noise for the variance itself. This is useful for methods such as\n CycleDiffusion. (https://arxiv.org/abs/2210.05559)\n return_dict (`bool`): option for returning tuple rather than DDIMSchedulerOutput class\n\n Returns:\n [`~schedulers.scheduling_utils.DDIMSchedulerOutput`] or `tuple`:\n [`~schedulers.scheduling_utils.DDIMSchedulerOutput`] if `return_dict` is True, otherwise a `tuple`. When\n returning a tuple, the first element is the sample tensor.\n\n \"\"\"\n if self.num_inference_steps is None:\n raise ValueError(\n \"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler\"\n )\n\n # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf\n # Ideally, read DDIM paper in-detail understanding\n\n # Notation (<variable name> -> <name in paper>\n # - pred_noise_t -> e_theta(x_t, t)\n # - pred_original_sample -> f_theta(x_t, t) or x_0\n # - std_dev_t -> sigma_t\n # - eta -> η\n # - pred_sample_direction -> \"direction pointing to x_t\"\n # - pred_prev_sample -> \"x_t-1\"\n\n # 1. get previous step value (=t-1)\n prev_timestep = timestep - self.config.num_train_timesteps // self.num_inference_steps\n\n # 2. compute alphas, betas\n alpha_prod_t = self.alphas_cumprod[timestep]\n alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod\n\n beta_prod_t = 1 - alpha_prod_t\n\n # 3. compute predicted original sample from predicted noise also called\n # \"predicted x_0\" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf\n if self.config.prediction_type == \"epsilon\":\n pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)\n elif self.config.prediction_type == \"sample\":\n pred_original_sample = model_output\n elif self.config.prediction_type == \"v_prediction\":\n pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output\n # predict V\n model_output = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample\n else:\n raise ValueError(\n f\"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or\"\n \" `v_prediction`\"\n )\n\n # # add a interpolater\n images = self.decode_latents(pred_original_sample)\n\n f , C, H, W = images.shape\n # images = torch.from_numpy(images).cuda()\n ph = ((H - 1) // 32 + 1) * 32\n pw = ((W - 1) // 32 + 1) * 32\n padding = (0, pw - W, 0, ph - H)\n images= F.pad(images,padding).float()\n for i in range(1,f-2):\n img0 = images[i:i+1]\n img1 = images[i+2:i+3] \n inference_img = self.interpolater.inference(img0,img1)\n images[i+1:i+2] = inference_img\n pred_original_sample = self.encode_latents(images.to(self.vae.dtype),generator)\n pred_original_sample = rearrange(pred_original_sample[None], 'b f c h w -> b c f h w') \n\n \n # 4. Clip \"predicted x_0\"\n if self.config.clip_sample:\n pred_original_sample = torch.clamp(pred_original_sample, -1, 1)\n\n # 5. compute variance: \"sigma_t(η)\" -> see formula (16)\n # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)\n variance = self._get_variance(timestep, prev_timestep)\n std_dev_t = eta * variance ** (0.5)\n\n if use_clipped_model_output:\n # the model_output is always re-derived from the clipped x_0 in Glide\n model_output = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5)\n\n # 6. compute \"direction pointing to x_t\" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf\n pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * model_output\n\n # 7. compute x_t without \"random noise\" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf\n prev_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction\n\n if eta > 0:\n # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072\n device = model_output.device\n if variance_noise is not None and generator is not None:\n raise ValueError(\n \"Cannot pass both generator and variance_noise. Please make sure that either `generator` or\"\n \" `variance_noise` stays `None`.\"\n )\n\n if variance_noise is None:\n if device.type == \"mps\":\n # randn does not work reproducibly on mps\n variance_noise = torch.randn(model_output.shape, dtype=model_output.dtype, generator=generator)\n variance_noise = variance_noise.to(device)\n else:\n variance_noise = torch.randn(\n model_output.shape, generator=generator, device=device, dtype=model_output.dtype\n )\n variance = self._get_variance(timestep, prev_timestep) ** (0.5) * eta * variance_noise\n\n prev_sample = prev_sample + variance\n\n if not return_dict:\n return (prev_sample,)\n\n return DDIMSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_original_sample)" }, { "identifier": "Model", "path": "RIFEModel/RIFE_HDv3.py", "snippet": "class Model:\n def __init__(self, local_rank=-1):\n self.flownet = IFNet()\n self.device()\n self.optimG = AdamW(self.flownet.parameters(), lr=1e-6, weight_decay=1e-4)\n self.epe = EPE()\n # self.vgg = VGGPerceptualLoss().to(device)\n self.sobel = SOBEL()\n if local_rank != -1:\n self.flownet = DDP(self.flownet, device_ids=[local_rank], output_device=local_rank)\n\n def train(self):\n self.flownet.train()\n\n def eval(self):\n self.flownet.eval()\n\n def device(self):\n self.flownet.to(device)\n\n def load_model(self, path, rank=0):\n def convert(param):\n if rank == -1:\n return {\n k.replace(\"module.\", \"\"): v\n for k, v in param.items()\n if \"module.\" in k\n }\n else:\n return param\n if rank <= 0:\n if torch.cuda.is_available():\n self.flownet.load_state_dict(convert(torch.load('{}/flownet.pkl'.format(path))))\n else:\n self.flownet.load_state_dict(convert(torch.load('{}/flownet.pkl'.format(path), map_location ='cpu')))\n \n def save_model(self, path, rank=0):\n if rank == 0:\n torch.save(self.flownet.state_dict(),'{}/flownet.pkl'.format(path))\n\n def inference(self, img0, img1, scale=1.0):\n imgs = torch.cat((img0, img1), 1)\n scale_list = [4/scale, 2/scale, 1/scale]\n flow, mask, merged = self.flownet(imgs, scale_list)\n return merged[2]\n \n def update(self, imgs, gt, learning_rate=0, mul=1, training=True, flow_gt=None):\n for param_group in self.optimG.param_groups:\n param_group['lr'] = learning_rate\n img0 = imgs[:, :3]\n img1 = imgs[:, 3:]\n if training:\n self.train()\n else:\n self.eval()\n scale = [4, 2, 1]\n flow, mask, merged = self.flownet(torch.cat((imgs, gt), 1), scale=scale, training=training)\n loss_l1 = (merged[2] - gt).abs().mean()\n loss_smooth = self.sobel(flow[2], flow[2]*0).mean()\n # loss_vgg = self.vgg(merged[2], gt)\n if training:\n self.optimG.zero_grad()\n loss_G = loss_cons + loss_smooth * 0.1\n loss_G.backward()\n self.optimG.step()\n else:\n flow_teacher = flow[2]\n return merged[2], {\n 'mask': mask,\n 'flow': flow[2][:, :2],\n 'loss_l1': loss_l1,\n 'loss_cons': loss_cons,\n 'loss_smooth': loss_smooth,\n }" } ]
import os import copy import click import re import numpy as np import torch import torch.utils.data import torch.utils.checkpoint import decord import shutil from glob import glob from typing import Optional,Dict from tqdm.auto import tqdm from omegaconf import OmegaConf from PIL import Image from accelerate import Accelerator from accelerate.logging import get_logger from accelerate.utils import set_seed from diffusers import ( AutoencoderKL, DDIMScheduler, ) from diffusers.utils.import_utils import is_xformers_available from transformers import AutoTokenizer, CLIPTextModel from einops import rearrange from video_diffusion.models.unet_3d_condition import UNetPseudo3DConditionModel from video_diffusion.models.controlnet_3d_condition import ControlNetPseudo3DModel from video_diffusion.data.dataset import ImageSequenceDataset from video_diffusion.common.util import get_time_string, get_function_args from video_diffusion.common.logger import get_logger_config_path from video_diffusion.common.image_util import log_train_samples from video_diffusion.common.instantiate_from_config import instantiate_from_config from video_diffusion.pipelines.p2p_validation_loop_controlnet import P2pSampleLogger from annotator.util import get_control from video_diffusion.pipelines.DDIMInterpolationScheduler import DDIMInterpolationScheduler from RIFEModel.RIFE_HDv3 import Model
20,742
pipeline = instantiate_from_config( test_pipeline_config, vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet, controlnet=controlnet, scheduler=scheduler, control_type = control_type, editing_type = editing_config.editing_type, dilation_kernel = editing_config.dilation_kernel, disk_store=kwargs.get('disk_store', False) ) pipeline.scheduler.set_timesteps(editing_config['num_inference_steps']) if editing_config.use_interpolater: new_scheduler = DDIMInterpolationScheduler.from_pretrained( pretrained_model_path, subfolder="scheduler", ) interpolater = Model() interpolater.load_model('RIFEModel', -1) new_scheduler.set_model(vae,interpolater) print('using interpolater') pipeline.add_new_scheduler(new_scheduler) pipeline.new_scheduler.set_timesteps(editing_config['num_inference_steps']) pipeline.set_progress_bar_config(disable=True) # pipeline.print_pipeline(logger) if is_xformers_available(): try: pipeline.enable_xformers_memory_efficient_attention() except Exception as e: logger.warning( "Could not enable memory efficient attention. Make sure xformers is installed" f" correctly and a GPU is available: {e}" ) vae.requires_grad_(False) unet.requires_grad_(False) text_encoder.requires_grad_(False) prompt_ids = tokenizer( dataset_config["prompt"], truncation=True, padding="max_length", max_length=tokenizer.model_max_length, return_tensors="pt", ).input_ids video_dataset = ImageSequenceDataset(**dataset_config, prompt_ids=prompt_ids) train_dataloader = torch.utils.data.DataLoader( video_dataset, batch_size=batch_size, shuffle=True, num_workers=4, collate_fn=collate_fn, ) train_sample_save_path = os.path.join(logdir, "train_samples.gif") log_train_samples(save_path=train_sample_save_path, train_dataloader=train_dataloader) unet, train_dataloader,controlnet = accelerator.prepare( unet, train_dataloader,controlnet ) weight_dtype = torch.float32 if accelerator.mixed_precision == "fp16": weight_dtype = torch.float16 print('use fp16') elif accelerator.mixed_precision == "bf16": weight_dtype = torch.bfloat16 # Move text_encode and vae to gpu. # For mixed precision training we cast the text_encoder and vae weights to half-precision # These models are only used for inference, keeping weights in full precision is not required. vae.to(accelerator.device, dtype=weight_dtype) text_encoder.to(accelerator.device, dtype=weight_dtype) # We need to initialize the trackers we use, and also store our configuration. # The trackers initializes automatically on the main process. if accelerator.is_main_process: accelerator.init_trackers("video") # , config=vars(args)) logger.info("***** wait to fix the logger path *****") if editing_config is not None and accelerator.is_main_process: validation_sample_logger = P2pSampleLogger(**editing_config, logdir=logdir, source_prompt=dataset_config['prompt']) # validation_sample_logger.log_sample_images( # pipeline=pipeline, # device=accelerator.device, # step=0, # ) def make_data_yielder(dataloader): while True: for batch in dataloader: yield batch accelerator.wait_for_everyone() train_data_yielder = make_data_yielder(train_dataloader) batch = next(train_data_yielder) if editing_config.get('use_invertion_latents', False): # Precompute the latents for this video to align the initial latents in training and test assert batch["images"].shape[0] == 1, "Only support, overfiting on a single video" # we only inference for latents, no training vae.eval() text_encoder.eval() unet.eval() text_embeddings = pipeline._encode_prompt( dataset_config.prompt, device = accelerator.device, num_images_per_prompt = 1, do_classifier_free_guidance = True, negative_prompt=None ) use_inversion_attention = editing_config.get('use_inversion_attention', False)
decord.bridge.set_bridge('torch') # from video_diffusion.pipelines.p2p_validation_loop_controlnet_ablation import P2pSampleLogger # logger = get_logger(__name__) def collate_fn(examples): """Concat a batch of sampled image in dataloader """ batch = { "prompt_ids": torch.cat([example["prompt_ids"] for example in examples], dim=0), "images": torch.stack([example["images"] for example in examples]), } return batch def test( config: str, pretrained_model_path: str, control_type:str, pretrained_controlnet_model_path :str, dataset_config: Dict, logdir: str = None, editing_config: Optional[Dict] = None, test_pipeline_config: Optional[Dict] = None, gradient_accumulation_steps: int = 1, seed: Optional[int] = None, mixed_precision: Optional[str] = "fp16", batch_size: int = 1, model_config: dict={}, verbose: bool=True, **kwargs ): args = get_function_args() vr = decord.VideoReader(dataset_config.video_path) fps = vr.get_avg_fps() duration = len(vr) / fps print("There are {} frames in the video but we take {} frames".format(len(vr), dataset_config.n_sample_frame)) if dataset_config.n_sample_frame <= 50: duration = 100 fps = 10 sample_index = list(range(0,len(vr), 1))[:dataset_config.n_sample_frame] video = vr.get_batch(sample_index) video_name_match = re.search(r"(.*)/(.*).mp4", dataset_config.video_path) video_name = video_name_match.group(2) video_frame_folder = os.path.join('data',video_name) if os.path.exists(video_frame_folder): shutil.rmtree(video_frame_folder) os.makedirs(video_frame_folder,exist_ok=True) for i in range(video.shape[0]): frame = video[i] frame_path = os.path.join(video_frame_folder,f'frame-{i:04}.jpg') frame = Image.fromarray(frame.numpy().astype(np.uint8)) frame.save(frame_path) dataset_config.update({'path': video_frame_folder} ) time_string = get_time_string() if logdir is None: logdir = config.replace('config', 'result').replace('.yml', '').replace('.yaml', '') logdir += f"_{time_string}" accelerator = Accelerator( gradient_accumulation_steps=gradient_accumulation_steps, mixed_precision=mixed_precision, ) if accelerator.is_main_process: os.makedirs(logdir, exist_ok=True) OmegaConf.save(args, os.path.join(logdir, "config.yml")) logger = get_logger_config_path(logdir) if seed is not None: set_seed(seed) # Load the tokenizer tokenizer = AutoTokenizer.from_pretrained( pretrained_model_path, subfolder="tokenizer", use_fast=False, ) # Load models and create wrapper for stable diffusion text_encoder = CLIPTextModel.from_pretrained( pretrained_model_path, subfolder="text_encoder", ) vae = AutoencoderKL.from_pretrained( pretrained_model_path, subfolder="vae", ) #加载unet报错 unet = UNetPseudo3DConditionModel.from_2d_model( os.path.join(pretrained_model_path, "unet"), model_config=model_config ) controlnet = ControlNetPseudo3DModel.from_2d_model( pretrained_controlnet_model_path, model_config=model_config ) if 'target' not in test_pipeline_config: test_pipeline_config['target'] = 'video_diffusion.pipelines.stable_diffusion.SpatioTemporalStableDiffusionControlPipeline' scheduler = DDIMScheduler.from_pretrained( pretrained_model_path, subfolder="scheduler", ) pipeline = instantiate_from_config( test_pipeline_config, vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet, controlnet=controlnet, scheduler=scheduler, control_type = control_type, editing_type = editing_config.editing_type, dilation_kernel = editing_config.dilation_kernel, disk_store=kwargs.get('disk_store', False) ) pipeline.scheduler.set_timesteps(editing_config['num_inference_steps']) if editing_config.use_interpolater: new_scheduler = DDIMInterpolationScheduler.from_pretrained( pretrained_model_path, subfolder="scheduler", ) interpolater = Model() interpolater.load_model('RIFEModel', -1) new_scheduler.set_model(vae,interpolater) print('using interpolater') pipeline.add_new_scheduler(new_scheduler) pipeline.new_scheduler.set_timesteps(editing_config['num_inference_steps']) pipeline.set_progress_bar_config(disable=True) # pipeline.print_pipeline(logger) if is_xformers_available(): try: pipeline.enable_xformers_memory_efficient_attention() except Exception as e: logger.warning( "Could not enable memory efficient attention. Make sure xformers is installed" f" correctly and a GPU is available: {e}" ) vae.requires_grad_(False) unet.requires_grad_(False) text_encoder.requires_grad_(False) prompt_ids = tokenizer( dataset_config["prompt"], truncation=True, padding="max_length", max_length=tokenizer.model_max_length, return_tensors="pt", ).input_ids video_dataset = ImageSequenceDataset(**dataset_config, prompt_ids=prompt_ids) train_dataloader = torch.utils.data.DataLoader( video_dataset, batch_size=batch_size, shuffle=True, num_workers=4, collate_fn=collate_fn, ) train_sample_save_path = os.path.join(logdir, "train_samples.gif") log_train_samples(save_path=train_sample_save_path, train_dataloader=train_dataloader) unet, train_dataloader,controlnet = accelerator.prepare( unet, train_dataloader,controlnet ) weight_dtype = torch.float32 if accelerator.mixed_precision == "fp16": weight_dtype = torch.float16 print('use fp16') elif accelerator.mixed_precision == "bf16": weight_dtype = torch.bfloat16 # Move text_encode and vae to gpu. # For mixed precision training we cast the text_encoder and vae weights to half-precision # These models are only used for inference, keeping weights in full precision is not required. vae.to(accelerator.device, dtype=weight_dtype) text_encoder.to(accelerator.device, dtype=weight_dtype) # We need to initialize the trackers we use, and also store our configuration. # The trackers initializes automatically on the main process. if accelerator.is_main_process: accelerator.init_trackers("video") # , config=vars(args)) logger.info("***** wait to fix the logger path *****") if editing_config is not None and accelerator.is_main_process: validation_sample_logger = P2pSampleLogger(**editing_config, logdir=logdir, source_prompt=dataset_config['prompt']) # validation_sample_logger.log_sample_images( # pipeline=pipeline, # device=accelerator.device, # step=0, # ) def make_data_yielder(dataloader): while True: for batch in dataloader: yield batch accelerator.wait_for_everyone() train_data_yielder = make_data_yielder(train_dataloader) batch = next(train_data_yielder) if editing_config.get('use_invertion_latents', False): # Precompute the latents for this video to align the initial latents in training and test assert batch["images"].shape[0] == 1, "Only support, overfiting on a single video" # we only inference for latents, no training vae.eval() text_encoder.eval() unet.eval() text_embeddings = pipeline._encode_prompt( dataset_config.prompt, device = accelerator.device, num_images_per_prompt = 1, do_classifier_free_guidance = True, negative_prompt=None ) use_inversion_attention = editing_config.get('use_inversion_attention', False)
apply_control = get_control(control_type)
9
2023-10-09 14:38:28+00:00
24k
LiYunfengLYF/LightFC
lib/train/data/base_functions.py
[ { "identifier": "sampler", "path": "lib/train/data/sampler.py", "snippet": "def no_processing(data):\r\n def __init__(self, datasets, p_datasets, samples_per_epoch, max_gap,\r\n num_search_frames, num_template_frames=1, processing=no_processing, frame_sample_mode='causal',\r\n train_cls=False, pos_prob=0.5):\r\n def __len__(self):\r\n def _sample_visible_ids(self, visible, num_ids=1, min_id=None, max_id=None,\r\n allow_invisible=False, force_invisible=False):\r\n def __getitem__(self, index):\r\n def getitem(self):\r\n def getitem_cls(self):\r\n def get_center_box(self, H, W, ratio=1 / 8):\r\n def sample_seq_from_dataset(self, dataset, is_video_dataset):\r\n def get_one_search(self):\r\n def get_frame_ids_trident(self, visible):\r\n def get_frame_ids_stark(self, visible, valid):\r\nclass TrackingSampler(torch.utils.data.Dataset):\r\n H, W, _ = template_frames[0].shape\r\n H, W, _ = template_frames[0].shape\r\n H, W, _ = search_frames[0].shape\r" }, { "identifier": "processing", "path": "lib/train/data/processing.py", "snippet": "def stack_tensors(x):\r\n def __init__(self, transform=transforms.ToTensor(), template_transform=None, search_transform=None,\r\n joint_transform=None):\r\n def __call__(self, data: TensorDict):\r\n def __init__(self, search_area_factor, output_sz, center_jitter_factor, scale_jitter_factor,\r\n mode='pair', settings=None, *args, **kwargs):\r\n def _get_jittered_box(self, box, mode):\r\n def __call__(self, data: TensorDict):\r\nclass BaseProcessing:\r\nclass STARKProcessing(BaseProcessing):\r" }, { "identifier": "LTRLoader", "path": "lib/train/data/loader.py", "snippet": "class LTRLoader(torch.utils.data.dataloader.DataLoader):\r\n \"\"\"\r\n Data loader. Combines a dataset and a sampler, and provides\r\n single- or multi-process iterators over the dataset.\r\n\r\n Note: The only difference with default pytorch DataLoader is that an additional option stack_dim is available to\r\n select along which dimension the data should be stacked to form a batch.\r\n\r\n Arguments:\r\n dataset (Dataset): dataset from which to load the data.\r\n batch_size (int, optional): how many samples per batch to load\r\n (default: 1).\r\n shuffle (bool, optional): set to ``True`` to have the data reshuffled\r\n at every epoch (default: False).\r\n sampler (Sampler, optional): defines the strategy to draw samples from\r\n the dataset. If specified, ``shuffle`` must be False.\r\n batch_sampler (Sampler, optional): like sampler, but returns a batch of\r\n indices at a time. Mutually exclusive with batch_size, shuffle,\r\n sampler, and drop_last.\r\n num_workers (int, optional): how many subprocesses to use for data\r\n loading. 0 means that the data will be loaded in the main process.\r\n (default: 0)\r\n collate_fn (callable, optional): merges a list of samples to form a mini-batch.\r\n stack_dim (int): Dimension along which to stack to form the batch. (default: 0)\r\n pin_memory (bool, optional): If ``True``, the data loader will copy tensors\r\n into CUDA pinned memory before returning them.\r\n drop_last (bool, optional): set to ``True`` to drop the last incomplete batch,\r\n if the dataset size is not divisible by the batch size. If ``False`` and\r\n the size of dataset is not divisible by the batch size, then the last batch\r\n will be smaller. (default: False)\r\n timeout (numeric, optional): if positive, the timeout value for collecting a batch\r\n from workers. Should always be non-negative. (default: 0)\r\n worker_init_fn (callable, optional): If not None, this will be called on each\r\n worker subprocess with the worker id (an int in ``[0, num_workers - 1]``) as\r\n input, after seeding and before data loading. (default: None)\r\n\r\n .. note:: By default, each worker will have its PyTorch seed set to\r\n ``base_seed + worker_id``, where ``base_seed`` is a long generated\r\n by main process using its RNG. However, seeds for other libraries\r\n may be duplicated upon initializing workers (w.g., NumPy), causing\r\n each worker to return identical random numbers. (See\r\n :ref:`dataloader-workers-random-seed` section in FAQ.) You may\r\n use ``torch.initial_seed()`` to access the PyTorch seed for each\r\n worker in :attr:`worker_init_fn`, and use it to set other seeds\r\n before data loading.\r\n\r\n .. warning:: If ``spawn`` start method is used, :attr:`worker_init_fn` cannot be an\r\n unpicklable object, e.g., a lambda function.\r\n \"\"\"\r\n\r\n __initialized = False\r\n\r\n def __init__(self, name, dataset, training=True, batch_size=1, shuffle=False, sampler=None, batch_sampler=None,\r\n num_workers=0, epoch_interval=1, collate_fn=None, stack_dim=0, pin_memory=False, drop_last=False,\r\n timeout=0, worker_init_fn=None):\r\n if collate_fn is None:\r\n if stack_dim == 0:\r\n collate_fn = ltr_collate\r\n elif stack_dim == 1:\r\n collate_fn = ltr_collate_stack1\r\n else:\r\n raise ValueError('Stack dim no supported. Must be 0 or 1.')\r\n\r\n super(LTRLoader, self).__init__(dataset, batch_size, shuffle, sampler, batch_sampler,\r\n num_workers, collate_fn, pin_memory, drop_last,\r\n timeout, worker_init_fn)\r\n\r\n self.name = name\r\n self.training = training\r\n self.epoch_interval = epoch_interval\r\n self.stack_dim = stack_dim\r" }, { "identifier": "opencv_loader", "path": "lib/train/data/image_loader.py", "snippet": "def opencv_loader(path):\r\n \"\"\" Read image using opencv's imread function and returns it in rgb format\"\"\"\r\n try:\r\n im = cv.imread(path, cv.IMREAD_COLOR)\r\n\r\n # convert to rgb and return\r\n return cv.cvtColor(im, cv.COLOR_BGR2RGB)\r\n except Exception as e:\r\n print('ERROR: Could not read image \"{}\"'.format(path))\r\n print(e)\r\n return None\r" }, { "identifier": "Lasot", "path": "lib/train/dataset/lasot.py", "snippet": "class Lasot(BaseVideoDataset):\r\n \"\"\" LaSOT dataset.\r\n\r\n Publication:\r\n LaSOT: A High-quality Benchmark for Large-scale Single Object Tracking\r\n Heng Fan, Liting Lin, Fan Yang, Peng Chu, Ge Deng, Sijia Yu, Hexin Bai, Yong Xu, Chunyuan Liao and Haibin Ling\r\n CVPR, 2019\r\n https://arxiv.org/pdf/1809.07845.pdf\r\n\r\n Download the dataset from https://cis.temple.edu/lasot/download.html\r\n \"\"\"\r\n\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, vid_ids=None, split=None, data_fraction=None,\r\n env_num=None):\r\n \"\"\"\r\n args:\r\n root - path to the lasot dataset.\r\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\r\n is used by default.\r\n vid_ids - List containing the ids of the videos (1 - 20) used for training. If vid_ids = [1, 3, 5], then the\r\n videos with subscripts -1, -3, and -5 from each class will be used for training.\r\n split - If split='train', the official train split (protocol-II) is used for training. Note: Only one of\r\n vid_ids or split option can be used at a time.\r\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\r\n \"\"\"\r\n root = env_settings(env_num).lasot_dir if root is None else root\r\n super().__init__('LaSOT', root, image_loader)\r\n\r\n # Keep a list of all classes\r\n self.class_list = [f for f in os.listdir(self.root)]\r\n self.class_to_id = {cls_name: cls_id for cls_id, cls_name in enumerate(self.class_list)}\r\n\r\n self.sequence_list = self._build_sequence_list(vid_ids, split)\r\n\r\n if data_fraction is not None:\r\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\r\n\r\n self.seq_per_class = self._build_class_list()\r\n\r\n def _build_sequence_list(self, vid_ids=None, split=None):\r\n if split is not None:\r\n if vid_ids is not None:\r\n raise ValueError('Cannot set both split_name and vid_ids.')\r\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\r\n if split == 'train':\r\n file_path = os.path.join(ltr_path, 'data_specs', 'lasot_train_split.txt')\r\n else:\r\n raise ValueError('Unknown split name.')\r\n # sequence_list = pandas.read_csv(file_path, header=None, squeeze=True).values.tolist()\r\n sequence_list = pandas.read_csv(file_path, header=None).squeeze(\"columns\").values.tolist()\r\n elif vid_ids is not None:\r\n sequence_list = [c + '-' + str(v) for c in self.class_list for v in vid_ids]\r\n else:\r\n raise ValueError('Set either split_name or vid_ids.')\r\n\r\n return sequence_list\r\n\r\n def _build_class_list(self):\r\n seq_per_class = {}\r\n for seq_id, seq_name in enumerate(self.sequence_list):\r\n class_name = seq_name.split('-')[0]\r\n if class_name in seq_per_class:\r\n seq_per_class[class_name].append(seq_id)\r\n else:\r\n seq_per_class[class_name] = [seq_id]\r\n\r\n return seq_per_class\r\n\r\n def get_name(self):\r\n return 'lasot'\r\n\r\n def has_class_info(self):\r\n return True\r\n\r\n def has_occlusion_info(self):\r\n return True\r\n\r\n def get_num_sequences(self):\r\n return len(self.sequence_list)\r\n\r\n def get_num_classes(self):\r\n return len(self.class_list)\r\n\r\n def get_sequences_in_class(self, class_name):\r\n return self.seq_per_class[class_name]\r\n\r\n def _read_bb_anno(self, seq_path):\r\n bb_anno_file = os.path.join(seq_path, \"groundtruth.txt\")\r\n gt = pandas.read_csv(bb_anno_file, delimiter=',', header=None, dtype=np.float32, na_filter=False,\r\n low_memory=False).values\r\n return torch.tensor(gt)\r\n\r\n def _read_target_visible(self, seq_path):\r\n # Read full occlusion and out_of_view\r\n occlusion_file = os.path.join(seq_path, \"full_occlusion.txt\")\r\n out_of_view_file = os.path.join(seq_path, \"out_of_view.txt\")\r\n\r\n with open(occlusion_file, 'r', newline='') as f:\r\n occlusion = torch.ByteTensor([int(v) for v in list(csv.reader(f))[0]])\r\n with open(out_of_view_file, 'r') as f:\r\n out_of_view = torch.ByteTensor([int(v) for v in list(csv.reader(f))[0]])\r\n\r\n target_visible = ~occlusion & ~out_of_view\r\n\r\n return target_visible\r\n\r\n def _get_sequence_path(self, seq_id):\r\n seq_name = self.sequence_list[seq_id]\r\n class_name = seq_name.split('-')[0]\r\n vid_id = seq_name.split('-')[1]\r\n\r\n return os.path.join(self.root, class_name, class_name + '-' + vid_id)\r\n\r\n def get_sequence_info(self, seq_id):\r\n seq_path = self._get_sequence_path(seq_id)\r\n bbox = self._read_bb_anno(seq_path)\r\n\r\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\r\n visible = self._read_target_visible(seq_path) & valid.byte()\r\n\r\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\r\n\r\n def _get_frame_path(self, seq_path, frame_id):\r\n return os.path.join(seq_path, 'img', '{:08}.jpg'.format(frame_id + 1)) # frames start from 1\r\n\r\n def _get_frame(self, seq_path, frame_id):\r\n return self.image_loader(self._get_frame_path(seq_path, frame_id))\r\n\r\n def _get_class(self, seq_path):\r\n raw_class = seq_path.split('/')[-2]\r\n return raw_class\r\n\r\n def get_class_name(self, seq_id):\r\n seq_path = self._get_sequence_path(seq_id)\r\n obj_class = self._get_class(seq_path)\r\n\r\n return obj_class\r\n\r\n def get_frames(self, seq_id, frame_ids, anno=None):\r\n seq_path = self._get_sequence_path(seq_id)\r\n\r\n obj_class = self._get_class(seq_path)\r\n frame_list = [self._get_frame(seq_path, f_id) for f_id in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\r\n\r\n object_meta = OrderedDict({'object_class_name': obj_class,\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n\r\n return frame_list, anno_frames, object_meta\r" }, { "identifier": "Got10k", "path": "lib/train/dataset/got10k.py", "snippet": "class Got10k(BaseVideoDataset):\r\n \"\"\" GOT-10k dataset.\r\n\r\n Publication:\r\n GOT-10k: A Large High-Diversity Benchmark for Generic Object Tracking in the Wild\r\n Lianghua Huang, Xin Zhao, and Kaiqi Huang\r\n arXiv:1810.11981, 2018\r\n https://arxiv.org/pdf/1810.11981.pdf\r\n\r\n Download dataset from http://got-10k.aitestunion.com/downloads\r\n \"\"\"\r\n\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, split=None, seq_ids=None, data_fraction=None,\r\n env_num=None):\r\n \"\"\"\r\n args:\r\n root - path to the got-10k training data. Note: This should point to the 'train' folder inside GOT-10k\r\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\r\n is used by default.\r\n split - 'train' or 'val'. Note: The validation split here is a subset of the official got-10k train split,\r\n not NOT the official got-10k validation split. To use the official validation split, provide that as\r\n the root folder instead.\r\n seq_ids - List containing the ids of the videos to be used for training. Note: Only one of 'split' or 'seq_ids'\r\n options can be used at the same time.\r\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\r\n \"\"\"\r\n root = env_settings(env_num).got10k_dir if root is None else root\r\n super().__init__('GOT10k', root, image_loader)\r\n\r\n # all folders inside the root\r\n self.sequence_list = self._get_sequence_list()\r\n\r\n # seq_id is the index of the folder inside the got10k root path\r\n if split is not None:\r\n if seq_ids is not None:\r\n raise ValueError('Cannot set both split_name and seq_ids.')\r\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\r\n if split == 'train':\r\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_train_split.txt')\r\n elif split == 'val':\r\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_val_split.txt')\r\n elif split == 'train_full':\r\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_train_full_split.txt')\r\n elif split == 'vottrain':\r\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_vot_train_split.txt')\r\n elif split == 'votval':\r\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_vot_val_split.txt')\r\n else:\r\n raise ValueError('Unknown split name.')\r\n # seq_ids = pandas.read_csv(file_path, header=None, squeeze=True, dtype=np.int64).values.tolist()\r\n seq_ids = pandas.read_csv(file_path, header=None, dtype=np.int64).squeeze(\"columns\").values.tolist()\r\n elif seq_ids is None:\r\n seq_ids = list(range(0, len(self.sequence_list)))\r\n\r\n self.sequence_list = [self.sequence_list[i] for i in seq_ids]\r\n\r\n if data_fraction is not None:\r\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\r\n\r\n self.sequence_meta_info = self._load_meta_info()\r\n self.seq_per_class = self._build_seq_per_class()\r\n\r\n self.class_list = list(self.seq_per_class.keys())\r\n self.class_list.sort()\r\n\r\n def get_name(self):\r\n return 'got10k'\r\n\r\n def has_class_info(self):\r\n return True\r\n\r\n def has_occlusion_info(self):\r\n return True\r\n\r\n def _load_meta_info(self):\r\n sequence_meta_info = {s: self._read_meta(os.path.join(self.root, s)) for s in self.sequence_list}\r\n return sequence_meta_info\r\n\r\n def _read_meta(self, seq_path):\r\n try:\r\n with open(os.path.join(seq_path, 'meta_info.ini')) as f:\r\n meta_info = f.readlines()\r\n object_meta = OrderedDict({'object_class_name': meta_info[5].split(': ')[-1][:-1],\r\n 'motion_class': meta_info[6].split(': ')[-1][:-1],\r\n 'major_class': meta_info[7].split(': ')[-1][:-1],\r\n 'root_class': meta_info[8].split(': ')[-1][:-1],\r\n 'motion_adverb': meta_info[9].split(': ')[-1][:-1]})\r\n except:\r\n object_meta = OrderedDict({'object_class_name': None,\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n return object_meta\r\n\r\n def _build_seq_per_class(self):\r\n seq_per_class = {}\r\n\r\n for i, s in enumerate(self.sequence_list):\r\n object_class = self.sequence_meta_info[s]['object_class_name']\r\n if object_class in seq_per_class:\r\n seq_per_class[object_class].append(i)\r\n else:\r\n seq_per_class[object_class] = [i]\r\n\r\n return seq_per_class\r\n\r\n def get_sequences_in_class(self, class_name):\r\n return self.seq_per_class[class_name]\r\n\r\n def _get_sequence_list(self):\r\n with open(os.path.join(self.root, 'list.txt')) as f:\r\n dir_list = list(csv.reader(f))\r\n dir_list = [dir_name[0] for dir_name in dir_list]\r\n return dir_list\r\n\r\n def _read_bb_anno(self, seq_path):\r\n bb_anno_file = os.path.join(seq_path, \"groundtruth.txt\")\r\n gt = pandas.read_csv(bb_anno_file, delimiter=',', header=None, dtype=np.float32, na_filter=False,\r\n low_memory=False).values\r\n return torch.tensor(gt)\r\n\r\n def _read_target_visible(self, seq_path):\r\n # Read full occlusion and out_of_view\r\n occlusion_file = os.path.join(seq_path, \"absence.label\")\r\n cover_file = os.path.join(seq_path, \"cover.label\")\r\n\r\n with open(occlusion_file, 'r', newline='') as f:\r\n occlusion = torch.ByteTensor([int(v[0]) for v in csv.reader(f)])\r\n with open(cover_file, 'r', newline='') as f:\r\n cover = torch.ByteTensor([int(v[0]) for v in csv.reader(f)])\r\n\r\n target_visible = ~occlusion & (cover > 0).byte()\r\n\r\n visible_ratio = cover.float() / 8\r\n return target_visible, visible_ratio\r\n\r\n def _get_sequence_path(self, seq_id):\r\n return os.path.join(self.root, self.sequence_list[seq_id])\r\n\r\n def get_sequence_info(self, seq_id):\r\n seq_path = self._get_sequence_path(seq_id)\r\n bbox = self._read_bb_anno(seq_path)\r\n\r\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\r\n visible, visible_ratio = self._read_target_visible(seq_path)\r\n visible = visible & valid.byte()\r\n\r\n return {'bbox': bbox, 'valid': valid, 'visible': visible, 'visible_ratio': visible_ratio}\r\n\r\n def _get_frame_path(self, seq_path, frame_id):\r\n return os.path.join(seq_path, '{:08}.jpg'.format(frame_id + 1)) # frames start from 1\r\n\r\n def _get_frame(self, seq_path, frame_id):\r\n return self.image_loader(self._get_frame_path(seq_path, frame_id))\r\n\r\n def get_class_name(self, seq_id):\r\n obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]\r\n\r\n return obj_meta['object_class_name']\r\n\r\n def get_frames(self, seq_id, frame_ids, anno=None):\r\n seq_path = self._get_sequence_path(seq_id)\r\n obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]\r\n\r\n frame_list = [self._get_frame(seq_path, f_id) for f_id in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\r\n\r\n return frame_list, anno_frames, obj_meta\r" }, { "identifier": "TrackingNet", "path": "lib/train/dataset/tracking_net.py", "snippet": "class TrackingNet(BaseVideoDataset):\r\n \"\"\" TrackingNet dataset.\r\n\r\n Publication:\r\n TrackingNet: A Large-Scale Dataset and Benchmark for Object Tracking in the Wild.\r\n Matthias Mueller,Adel Bibi, Silvio Giancola, Salman Al-Subaihi and Bernard Ghanem\r\n ECCV, 2018\r\n https://ivul.kaust.edu.sa/Documents/Publications/2018/TrackingNet%20A%20Large%20Scale%20Dataset%20and%20Benchmark%20for%20Object%20Tracking%20in%20the%20Wild.pdf\r\n\r\n Download the dataset using the toolkit https://github.com/SilvioGiancola/TrackingNet-devkit.\r\n \"\"\"\r\n\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, set_ids=None, data_fraction=None, env_num=None):\r\n \"\"\"\r\n args:\r\n root - The path to the TrackingNet folder, containing the training sets.\r\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\r\n is used by default.\r\n set_ids (None) - List containing the ids of the TrackingNet sets to be used for training. If None, all the\r\n sets (0 - 11) will be used.\r\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\r\n \"\"\"\r\n root = env_settings(env_num).trackingnet_dir if root is None else root\r\n super().__init__('TrackingNet', root, image_loader)\r\n\r\n if set_ids is None:\r\n set_ids = [i for i in range(12)]\r\n\r\n self.set_ids = set_ids\r\n\r\n # Keep a list of all videos. Sequence list is a list of tuples (set_id, video_name) containing the set_id and\r\n # video_name for each sequence\r\n self.sequence_list = list_sequences(self.root, self.set_ids)\r\n\r\n if data_fraction is not None:\r\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\r\n\r\n self.seq_to_class_map, self.seq_per_class = self._load_class_info()\r\n\r\n # we do not have the class_lists for the tracking net\r\n self.class_list = list(self.seq_per_class.keys())\r\n self.class_list.sort()\r\n\r\n def _load_class_info(self):\r\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\r\n class_map_path = os.path.join(ltr_path, 'data_specs', 'trackingnet_classmap.txt')\r\n\r\n with open(class_map_path, 'r') as f:\r\n seq_to_class_map = {seq_class.split('\\t')[0]: seq_class.rstrip().split('\\t')[1] for seq_class in f}\r\n\r\n seq_per_class = {}\r\n for i, seq in enumerate(self.sequence_list):\r\n class_name = seq_to_class_map.get(seq[1], 'Unknown')\r\n if class_name not in seq_per_class:\r\n seq_per_class[class_name] = [i]\r\n else:\r\n seq_per_class[class_name].append(i)\r\n\r\n return seq_to_class_map, seq_per_class\r\n\r\n def get_name(self):\r\n return 'trackingnet'\r\n\r\n def has_class_info(self):\r\n return True\r\n\r\n def get_sequences_in_class(self, class_name):\r\n return self.seq_per_class[class_name]\r\n\r\n def _read_bb_anno(self, seq_id):\r\n set_id = self.sequence_list[seq_id][0]\r\n vid_name = self.sequence_list[seq_id][1]\r\n bb_anno_file = os.path.join(self.root, \"TRAIN_\" + str(set_id), \"anno\", vid_name + \".txt\")\r\n gt = pandas.read_csv(bb_anno_file, delimiter=',', header=None, dtype=np.float32, na_filter=False,\r\n low_memory=False).values\r\n return torch.tensor(gt)\r\n\r\n def get_sequence_info(self, seq_id):\r\n bbox = self._read_bb_anno(seq_id)\r\n\r\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\r\n visible = valid.clone().byte()\r\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\r\n\r\n def _get_frame(self, seq_id, frame_id):\r\n set_id = self.sequence_list[seq_id][0]\r\n vid_name = self.sequence_list[seq_id][1]\r\n frame_path = os.path.join(self.root, \"TRAIN_\" + str(set_id), \"frames\", vid_name, str(frame_id) + \".jpg\")\r\n return self.image_loader(frame_path)\r\n\r\n def _get_class(self, seq_id):\r\n seq_name = self.sequence_list[seq_id][1]\r\n return self.seq_to_class_map[seq_name]\r\n\r\n def get_class_name(self, seq_id):\r\n obj_class = self._get_class(seq_id)\r\n\r\n return obj_class\r\n\r\n def get_frames(self, seq_id, frame_ids, anno=None):\r\n frame_list = [self._get_frame(seq_id, f) for f in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\r\n\r\n obj_class = self._get_class(seq_id)\r\n\r\n object_meta = OrderedDict({'object_class_name': obj_class,\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n\r\n return frame_list, anno_frames, object_meta\r" }, { "identifier": "ImagenetVID", "path": "lib/train/dataset/imagenetvid.py", "snippet": "class ImagenetVID(BaseVideoDataset):\r\n \"\"\" Imagenet VID dataset.\r\n\r\n Publication:\r\n ImageNet Large Scale Visual Recognition Challenge\r\n Olga Russakovsky, Jia Deng, Hao Su, Jonathan Krause, Sanjeev Satheesh, Sean Ma, Zhiheng Huang, Andrej Karpathy,\r\n Aditya Khosla, Michael Bernstein, Alexander C. Berg and Li Fei-Fei\r\n IJCV, 2015\r\n https://arxiv.org/pdf/1409.0575.pdf\r\n\r\n Download the dataset from http://image-net.org/\r\n \"\"\"\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, min_length=0, max_target_area=1,env_num=None):\r\n \"\"\"\r\n args:\r\n root - path to the imagenet vid dataset.\r\n image_loader (default_image_loader) - The function to read the images. If installed,\r\n jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,\r\n opencv's imread is used.\r\n min_length - Minimum allowed sequence length.\r\n max_target_area - max allowed ratio between target area and image area. Can be used to filter out targets\r\n which cover complete image.\r\n \"\"\"\r\n root = env_settings(env_num).imagenet_dir if root is None else root\r\n super().__init__(\"imagenetvid\", root, image_loader)\r\n\r\n cache_file = os.path.join(root, 'cache.json')\r\n if os.path.isfile(cache_file):\r\n # If available, load the pre-processed cache file containing meta-info for each sequence\r\n with open(cache_file, 'r') as f:\r\n sequence_list_dict = json.load(f)\r\n\r\n self.sequence_list = sequence_list_dict\r\n else:\r\n # Else process the imagenet annotations and generate the cache file\r\n self.sequence_list = self._process_anno(root)\r\n\r\n with open(cache_file, 'w') as f:\r\n json.dump(self.sequence_list, f)\r\n\r\n # Filter the sequences based on min_length and max_target_area in the first frame\r\n self.sequence_list = [x for x in self.sequence_list if len(x['anno']) >= min_length and\r\n get_target_to_image_ratio(x) < max_target_area]\r\n\r\n def get_name(self):\r\n return 'imagenetvid'\r\n\r\n def get_num_sequences(self):\r\n return len(self.sequence_list)\r\n\r\n def get_sequence_info(self, seq_id):\r\n bb_anno = torch.Tensor(self.sequence_list[seq_id]['anno'])\r\n valid = (bb_anno[:, 2] > 0) & (bb_anno[:, 3] > 0)\r\n visible = torch.ByteTensor(self.sequence_list[seq_id]['target_visible']) & valid.byte()\r\n return {'bbox': bb_anno, 'valid': valid, 'visible': visible}\r\n\r\n def _get_frame(self, sequence, frame_id):\r\n set_name = 'ILSVRC2015_VID_train_{:04d}'.format(sequence['set_id'])\r\n vid_name = 'ILSVRC2015_train_{:08d}'.format(sequence['vid_id'])\r\n frame_number = frame_id + sequence['start_frame']\r\n frame_path = os.path.join(self.root, 'Data', 'VID', 'train', set_name, vid_name,\r\n '{:06d}.JPEG'.format(frame_number))\r\n return self.image_loader(frame_path)\r\n\r\n def get_frames(self, seq_id, frame_ids, anno=None):\r\n sequence = self.sequence_list[seq_id]\r\n\r\n frame_list = [self._get_frame(sequence, f) for f in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n # Create anno dict\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\r\n\r\n # added the class info to the meta info\r\n object_meta = OrderedDict({'object_class': sequence['class_name'],\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n\r\n return frame_list, anno_frames, object_meta\r\n\r\n def _process_anno(self, root):\r\n # Builds individual tracklets\r\n base_vid_anno_path = os.path.join(root, 'Annotations', 'VID', 'train')\r\n\r\n all_sequences = []\r\n for set in sorted(os.listdir(base_vid_anno_path)):\r\n set_id = int(set.split('_')[-1])\r\n for vid in sorted(os.listdir(os.path.join(base_vid_anno_path, set))):\r\n\r\n vid_id = int(vid.split('_')[-1])\r\n anno_files = sorted(os.listdir(os.path.join(base_vid_anno_path, set, vid)))\r\n\r\n frame1_anno = ET.parse(os.path.join(base_vid_anno_path, set, vid, anno_files[0]))\r\n image_size = [int(frame1_anno.find('size/width').text), int(frame1_anno.find('size/height').text)]\r\n\r\n objects = [ET.ElementTree(file=os.path.join(base_vid_anno_path, set, vid, f)).findall('object')\r\n for f in anno_files]\r\n\r\n tracklets = {}\r\n\r\n # Find all tracklets along with start frame\r\n for f_id, all_targets in enumerate(objects):\r\n for target in all_targets:\r\n tracklet_id = target.find('trackid').text\r\n if tracklet_id not in tracklets:\r\n tracklets[tracklet_id] = f_id\r\n\r\n for tracklet_id, tracklet_start in tracklets.items():\r\n tracklet_anno = []\r\n target_visible = []\r\n class_name_id = None\r\n\r\n for f_id in range(tracklet_start, len(objects)):\r\n found = False\r\n for target in objects[f_id]:\r\n if target.find('trackid').text == tracklet_id:\r\n if not class_name_id:\r\n class_name_id = target.find('name').text\r\n x1 = int(target.find('bndbox/xmin').text)\r\n y1 = int(target.find('bndbox/ymin').text)\r\n x2 = int(target.find('bndbox/xmax').text)\r\n y2 = int(target.find('bndbox/ymax').text)\r\n\r\n tracklet_anno.append([x1, y1, x2 - x1, y2 - y1])\r\n target_visible.append(target.find('occluded').text == '0')\r\n\r\n found = True\r\n break\r\n if not found:\r\n break\r\n\r\n new_sequence = {'set_id': set_id, 'vid_id': vid_id, 'class_name': class_name_id,\r\n 'start_frame': tracklet_start, 'anno': tracklet_anno,\r\n 'target_visible': target_visible, 'image_size': image_size}\r\n all_sequences.append(new_sequence)\r\n\r\n return all_sequences\r" }, { "identifier": "MSCOCOSeq", "path": "lib/train/dataset/coco_seq.py", "snippet": "class MSCOCOSeq(BaseVideoDataset):\r\n \"\"\" The COCO dataset. COCO is an image dataset. Thus, we treat each image as a sequence of length 1.\r\n\r\n Publication:\r\n Microsoft COCO: Common Objects in Context.\r\n Tsung-Yi Lin, Michael Maire, Serge J. Belongie, Lubomir D. Bourdev, Ross B. Girshick, James Hays, Pietro Perona,\r\n Deva Ramanan, Piotr Dollar and C. Lawrence Zitnick\r\n ECCV, 2014\r\n https://arxiv.org/pdf/1405.0312.pdf\r\n\r\n Download the images along with annotations from http://cocodataset.org/#download. The root folder should be\r\n organized as follows.\r\n - coco_root\r\n - annotations\r\n - instances_train2014.json\r\n - instances_train2017.json\r\n - images\r\n - train2014\r\n - train2017\r\n\r\n Note: You also have to install the coco pythonAPI from https://github.com/cocodataset/cocoapi.\r\n \"\"\"\r\n\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None, split=\"train\", version=\"2014\",env_num=None):\r\n \"\"\"\r\n args:\r\n root - path to the coco dataset.\r\n image_loader (default_image_loader) - The function to read the images. If installed,\r\n jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,\r\n opencv's imread is used.\r\n data_fraction (None) - Fraction of images to be used. The images are selected randomly. If None, all the\r\n images will be used\r\n split - 'train' or 'val'.\r\n version - version of coco dataset (2014 or 2017)\r\n \"\"\"\r\n root = env_settings(env_num).coco_dir if root is None else root\r\n super().__init__('COCO', root, image_loader)\r\n\r\n self.img_pth = os.path.join(root, 'images/{}{}/'.format(split, version))\r\n self.anno_path = os.path.join(root, 'annotations/instances_{}{}.json'.format(split, version))\r\n\r\n # Load the COCO set.\r\n self.coco_set = COCO(self.anno_path)\r\n\r\n self.cats = self.coco_set.cats\r\n\r\n self.class_list = self.get_class_list()\r\n\r\n self.sequence_list = self._get_sequence_list()\r\n\r\n if data_fraction is not None:\r\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))\r\n self.seq_per_class = self._build_seq_per_class()\r\n\r\n def _get_sequence_list(self):\r\n ann_list = list(self.coco_set.anns.keys())\r\n seq_list = [a for a in ann_list if self.coco_set.anns[a]['iscrowd'] == 0]\r\n\r\n return seq_list\r\n\r\n def is_video_sequence(self):\r\n return False\r\n\r\n def get_num_classes(self):\r\n return len(self.class_list)\r\n\r\n def get_name(self):\r\n return 'coco'\r\n\r\n def has_class_info(self):\r\n return True\r\n\r\n def get_class_list(self):\r\n class_list = []\r\n for cat_id in self.cats.keys():\r\n class_list.append(self.cats[cat_id]['name'])\r\n return class_list\r\n\r\n def has_segmentation_info(self):\r\n return True\r\n\r\n def get_num_sequences(self):\r\n return len(self.sequence_list)\r\n\r\n def _build_seq_per_class(self):\r\n seq_per_class = {}\r\n for i, seq in enumerate(self.sequence_list):\r\n class_name = self.cats[self.coco_set.anns[seq]['category_id']]['name']\r\n if class_name not in seq_per_class:\r\n seq_per_class[class_name] = [i]\r\n else:\r\n seq_per_class[class_name].append(i)\r\n\r\n return seq_per_class\r\n\r\n def get_sequences_in_class(self, class_name):\r\n return self.seq_per_class[class_name]\r\n\r\n def get_sequence_info(self, seq_id):\r\n anno = self._get_anno(seq_id)\r\n\r\n bbox = torch.Tensor(anno['bbox']).view(1, 4)\r\n\r\n mask = torch.Tensor(self.coco_set.annToMask(anno)).unsqueeze(dim=0)\r\n\r\n '''2021.1.3 To avoid too small bounding boxes. Here we change the threshold to 50 pixels'''\r\n valid = (bbox[:, 2] > 50) & (bbox[:, 3] > 50)\r\n\r\n visible = valid.clone().byte()\r\n\r\n return {'bbox': bbox, 'mask': mask, 'valid': valid, 'visible': visible}\r\n\r\n def _get_anno(self, seq_id):\r\n anno = self.coco_set.anns[self.sequence_list[seq_id]]\r\n\r\n return anno\r\n\r\n def _get_frames(self, seq_id):\r\n path = self.coco_set.loadImgs([self.coco_set.anns[self.sequence_list[seq_id]]['image_id']])[0]['file_name']\r\n img = self.image_loader(os.path.join(self.img_pth, path))\r\n return img\r\n\r\n def get_meta_info(self, seq_id):\r\n try:\r\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\r\n object_meta = OrderedDict({'object_class_name': cat_dict_current['name'],\r\n 'motion_class': None,\r\n 'major_class': cat_dict_current['supercategory'],\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n except:\r\n object_meta = OrderedDict({'object_class_name': None,\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n return object_meta\r\n\r\n\r\n def get_class_name(self, seq_id):\r\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\r\n return cat_dict_current['name']\r\n\r\n def get_frames(self, seq_id=None, frame_ids=None, anno=None):\r\n # COCO is an image dataset. Thus we replicate the image denoted by seq_id len(frame_ids) times, and return a\r\n # list containing these replicated images.\r\n frame = self._get_frames(seq_id)\r\n\r\n frame_list = [frame.copy() for _ in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[0, ...] for _ in frame_ids]\r\n\r\n object_meta = self.get_meta_info(seq_id)\r\n\r\n return frame_list, anno_frames, object_meta\r" }, { "identifier": "Got10k_lmdb", "path": "lib/train/dataset/got10k_lmdb.py", "snippet": "class Got10k_lmdb(BaseVideoDataset):\r\n\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, split=None, seq_ids=None, data_fraction=None,\r\n env_num=None):\r\n \"\"\"\r\n args:\r\n root - path to the got-10k training data. Note: This should point to the 'train' folder inside GOT-10k\r\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\r\n is used by default.\r\n split - 'train' or 'val'. Note: The validation split here is a subset of the official got-10k train split,\r\n not NOT the official got-10k validation split. To use the official validation split, provide that as\r\n the root folder instead.\r\n seq_ids - List containing the ids of the videos to be used for training. Note: Only one of 'split' or 'seq_ids'\r\n options can be used at the same time.\r\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\r\n use_lmdb - whether the dataset is stored in lmdb format\r\n \"\"\"\r\n root = env_settings(env_num).got10k_lmdb_dir if root is None else root\r\n super().__init__('GOT10k_lmdb', root, image_loader)\r\n\r\n # all folders inside the root\r\n self.sequence_list = self._get_sequence_list()\r\n\r\n # seq_id is the index of the folder inside the got10k root path\r\n if split is not None:\r\n if seq_ids is not None:\r\n raise ValueError('Cannot set both split_name and seq_ids.')\r\n train_lib_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\r\n if split == 'train':\r\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_train_split.txt')\r\n elif split == 'val':\r\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_val_split.txt')\r\n elif split == 'train_full':\r\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_train_full_split.txt')\r\n elif split == 'vottrain':\r\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_vot_train_split.txt')\r\n elif split == 'votval':\r\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_vot_val_split.txt')\r\n else:\r\n raise ValueError('Unknown split name.')\r\n seq_ids = pandas.read_csv(file_path, header=None, squeeze=True, dtype=np.int64).values.tolist()\r\n elif seq_ids is None:\r\n seq_ids = list(range(0, len(self.sequence_list)))\r\n\r\n self.sequence_list = [self.sequence_list[i] for i in seq_ids]\r\n\r\n if data_fraction is not None:\r\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\r\n\r\n self.sequence_meta_info = self._load_meta_info()\r\n self.seq_per_class = self._build_seq_per_class()\r\n\r\n self.class_list = list(self.seq_per_class.keys())\r\n self.class_list.sort()\r\n\r\n def get_name(self):\r\n return 'got10k_lmdb'\r\n\r\n def has_class_info(self):\r\n return True\r\n\r\n def has_occlusion_info(self):\r\n return True\r\n\r\n def _load_meta_info(self):\r\n def _read_meta(meta_info):\r\n\r\n object_meta = OrderedDict({'object_class_name': meta_info[5].split(': ')[-1],\r\n 'motion_class': meta_info[6].split(': ')[-1],\r\n 'major_class': meta_info[7].split(': ')[-1],\r\n 'root_class': meta_info[8].split(': ')[-1],\r\n 'motion_adverb': meta_info[9].split(': ')[-1]})\r\n\r\n return object_meta\r\n\r\n sequence_meta_info = {}\r\n for s in self.sequence_list:\r\n try:\r\n meta_str = decode_str(self.root, \"train/%s/meta_info.ini\" % s)\r\n sequence_meta_info[s] = _read_meta(meta_str.split('\\n'))\r\n except:\r\n sequence_meta_info[s] = OrderedDict({'object_class_name': None,\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n return sequence_meta_info\r\n\r\n def _build_seq_per_class(self):\r\n seq_per_class = {}\r\n\r\n for i, s in enumerate(self.sequence_list):\r\n object_class = self.sequence_meta_info[s]['object_class_name']\r\n if object_class in seq_per_class:\r\n seq_per_class[object_class].append(i)\r\n else:\r\n seq_per_class[object_class] = [i]\r\n\r\n return seq_per_class\r\n\r\n def get_sequences_in_class(self, class_name):\r\n return self.seq_per_class[class_name]\r\n\r\n def _get_sequence_list(self):\r\n dir_str = decode_str(self.root, 'train/list.txt')\r\n dir_list = dir_str.split('\\n')\r\n return dir_list\r\n\r\n def _read_bb_anno(self, seq_path):\r\n bb_anno_file = os.path.join(seq_path, \"groundtruth.txt\")\r\n gt_str_list = decode_str(self.root, bb_anno_file).split('\\n')[:-1] # the last line in got10k is empty\r\n gt_list = [list(map(float, line.split(','))) for line in gt_str_list]\r\n gt_arr = np.array(gt_list).astype(np.float32)\r\n\r\n return torch.tensor(gt_arr)\r\n\r\n def _read_target_visible(self, seq_path):\r\n # full occlusion and out_of_view files\r\n occlusion_file = os.path.join(seq_path, \"absence.label\")\r\n cover_file = os.path.join(seq_path, \"cover.label\")\r\n # Read these files\r\n occ_list = list(\r\n map(int, decode_str(self.root, occlusion_file).split('\\n')[:-1])) # the last line in got10k is empty\r\n occlusion = torch.ByteTensor(occ_list)\r\n cover_list = list(\r\n map(int, decode_str(self.root, cover_file).split('\\n')[:-1])) # the last line in got10k is empty\r\n cover = torch.ByteTensor(cover_list)\r\n\r\n target_visible = ~occlusion & (cover > 0).byte()\r\n\r\n visible_ratio = cover.float() / 8\r\n return target_visible, visible_ratio\r\n\r\n def _get_sequence_path(self, seq_id):\r\n return os.path.join(\"train\", self.sequence_list[seq_id])\r\n\r\n def get_sequence_info(self, seq_id):\r\n seq_path = self._get_sequence_path(seq_id)\r\n bbox = self._read_bb_anno(seq_path)\r\n\r\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\r\n visible, visible_ratio = self._read_target_visible(seq_path)\r\n visible = visible & valid.byte()\r\n\r\n return {'bbox': bbox, 'valid': valid, 'visible': visible, 'visible_ratio': visible_ratio}\r\n\r\n def _get_frame_path(self, seq_path, frame_id):\r\n return os.path.join(seq_path, '{:08}.jpg'.format(frame_id + 1)) # frames start from 1\r\n\r\n def _get_frame(self, seq_path, frame_id):\r\n return decode_img(self.root, self._get_frame_path(seq_path, frame_id))\r\n\r\n def get_class_name(self, seq_id):\r\n obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]\r\n\r\n return obj_meta['object_class_name']\r\n\r\n def get_frames(self, seq_id, frame_ids, anno=None):\r\n seq_path = self._get_sequence_path(seq_id)\r\n obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]\r\n\r\n frame_list = [self._get_frame(seq_path, f_id) for f_id in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\r\n\r\n return frame_list, anno_frames, obj_meta\r" }, { "identifier": "Lasot_lmdb", "path": "lib/train/dataset/lasot_lmdb.py", "snippet": "class Lasot_lmdb(BaseVideoDataset):\r\n\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, vid_ids=None, split=None, data_fraction=None,\r\n env_num=None):\r\n \"\"\"\r\n args:\r\n root - path to the lasot dataset.\r\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\r\n is used by default.\r\n vid_ids - List containing the ids of the videos (1 - 20) used for training. If vid_ids = [1, 3, 5], then the\r\n videos with subscripts -1, -3, and -5 from each class will be used for training.\r\n split - If split='train', the official train split (protocol-II) is used for training. Note: Only one of\r\n vid_ids or split option can be used at a time.\r\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\r\n \"\"\"\r\n root = env_settings(env_num).lasot_lmdb_dir if root is None else root\r\n super().__init__('LaSOT_lmdb', root, image_loader)\r\n\r\n self.sequence_list = self._build_sequence_list(vid_ids, split)\r\n class_list = [seq_name.split('-')[0] for seq_name in self.sequence_list]\r\n self.class_list = []\r\n for ele in class_list:\r\n if ele not in self.class_list:\r\n self.class_list.append(ele)\r\n # Keep a list of all classes\r\n self.class_to_id = {cls_name: cls_id for cls_id, cls_name in enumerate(self.class_list)}\r\n\r\n if data_fraction is not None:\r\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\r\n\r\n self.seq_per_class = self._build_class_list()\r\n\r\n def _build_sequence_list(self, vid_ids=None, split=None):\r\n if split is not None:\r\n if vid_ids is not None:\r\n raise ValueError('Cannot set both split_name and vid_ids.')\r\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\r\n if split == 'train':\r\n file_path = os.path.join(ltr_path, 'data_specs', 'lasot_train_split.txt')\r\n else:\r\n raise ValueError('Unknown split name.')\r\n sequence_list = pandas.read_csv(file_path, header=None, squeeze=True).values.tolist()\r\n elif vid_ids is not None:\r\n sequence_list = [c + '-' + str(v) for c in self.class_list for v in vid_ids]\r\n else:\r\n raise ValueError('Set either split_name or vid_ids.')\r\n\r\n return sequence_list\r\n\r\n def _build_class_list(self):\r\n seq_per_class = {}\r\n for seq_id, seq_name in enumerate(self.sequence_list):\r\n class_name = seq_name.split('-')[0]\r\n if class_name in seq_per_class:\r\n seq_per_class[class_name].append(seq_id)\r\n else:\r\n seq_per_class[class_name] = [seq_id]\r\n\r\n return seq_per_class\r\n\r\n def get_name(self):\r\n return 'lasot_lmdb'\r\n\r\n def has_class_info(self):\r\n return True\r\n\r\n def has_occlusion_info(self):\r\n return True\r\n\r\n def get_num_sequences(self):\r\n return len(self.sequence_list)\r\n\r\n def get_num_classes(self):\r\n return len(self.class_list)\r\n\r\n def get_sequences_in_class(self, class_name):\r\n return self.seq_per_class[class_name]\r\n\r\n def _read_bb_anno(self, seq_path):\r\n bb_anno_file = os.path.join(seq_path, \"groundtruth.txt\")\r\n gt_str_list = decode_str(self.root, bb_anno_file).split('\\n')[:-1] # the last line is empty\r\n gt_list = [list(map(float, line.split(','))) for line in gt_str_list]\r\n gt_arr = np.array(gt_list).astype(np.float32)\r\n return torch.tensor(gt_arr)\r\n\r\n def _read_target_visible(self, seq_path):\r\n # Read full occlusion and out_of_view\r\n occlusion_file = os.path.join(seq_path, \"full_occlusion.txt\")\r\n out_of_view_file = os.path.join(seq_path, \"out_of_view.txt\")\r\n\r\n occ_list = list(map(int, decode_str(self.root, occlusion_file).split(',')))\r\n occlusion = torch.ByteTensor(occ_list)\r\n out_view_list = list(map(int, decode_str(self.root, out_of_view_file).split(',')))\r\n out_of_view = torch.ByteTensor(out_view_list)\r\n\r\n target_visible = ~occlusion & ~out_of_view\r\n\r\n return target_visible\r\n\r\n def _get_sequence_path(self, seq_id):\r\n seq_name = self.sequence_list[seq_id]\r\n class_name = seq_name.split('-')[0]\r\n vid_id = seq_name.split('-')[1]\r\n\r\n return os.path.join(class_name, class_name + '-' + vid_id)\r\n\r\n def get_sequence_info(self, seq_id):\r\n seq_path = self._get_sequence_path(seq_id)\r\n bbox = self._read_bb_anno(seq_path)\r\n\r\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\r\n visible = self._read_target_visible(seq_path) & valid.byte()\r\n\r\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\r\n\r\n def _get_frame_path(self, seq_path, frame_id):\r\n return os.path.join(seq_path, 'img', '{:08}.jpg'.format(frame_id + 1)) # frames start from 1\r\n\r\n def _get_frame(self, seq_path, frame_id):\r\n return decode_img(self.root, self._get_frame_path(seq_path, frame_id))\r\n\r\n def _get_class(self, seq_path):\r\n raw_class = seq_path.split('/')[-2]\r\n return raw_class\r\n\r\n def get_class_name(self, seq_id):\r\n seq_path = self._get_sequence_path(seq_id)\r\n obj_class = self._get_class(seq_path)\r\n\r\n return obj_class\r\n\r\n def get_frames(self, seq_id, frame_ids, anno=None):\r\n seq_path = self._get_sequence_path(seq_id)\r\n\r\n obj_class = self._get_class(seq_path)\r\n frame_list = [self._get_frame(seq_path, f_id) for f_id in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\r\n\r\n object_meta = OrderedDict({'object_class_name': obj_class,\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n\r\n return frame_list, anno_frames, object_meta\r" }, { "identifier": "ImagenetVID_lmdb", "path": "lib/train/dataset/imagenetvid_lmdb.py", "snippet": "class ImagenetVID_lmdb(BaseVideoDataset):\r\n \"\"\" Imagenet VID dataset.\r\n\r\n Publication:\r\n ImageNet Large Scale Visual Recognition Challenge\r\n Olga Russakovsky, Jia Deng, Hao Su, Jonathan Krause, Sanjeev Satheesh, Sean Ma, Zhiheng Huang, Andrej Karpathy,\r\n Aditya Khosla, Michael Bernstein, Alexander C. Berg and Li Fei-Fei\r\n IJCV, 2015\r\n https://arxiv.org/pdf/1409.0575.pdf\r\n\r\n Download the dataset from http://image-net.org/\r\n \"\"\"\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, min_length=0, max_target_area=1,env_num=None):\r\n \"\"\"\r\n args:\r\n root - path to the imagenet vid dataset.\r\n image_loader (default_image_loader) - The function to read the images. If installed,\r\n jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,\r\n opencv's imread is used.\r\n min_length - Minimum allowed sequence length.\r\n max_target_area - max allowed ratio between target area and image area. Can be used to filter out targets\r\n which cover complete image.\r\n \"\"\"\r\n root = env_settings(env_num).imagenet_dir if root is None else root\r\n super().__init__(\"imagenetvid_lmdb\", root, image_loader)\r\n\r\n sequence_list_dict = decode_json(root, \"cache.json\")\r\n self.sequence_list = sequence_list_dict\r\n\r\n # Filter the sequences based on min_length and max_target_area in the first frame\r\n self.sequence_list = [x for x in self.sequence_list if len(x['anno']) >= min_length and\r\n get_target_to_image_ratio(x) < max_target_area]\r\n\r\n def get_name(self):\r\n return 'imagenetvid_lmdb'\r\n\r\n def get_num_sequences(self):\r\n return len(self.sequence_list)\r\n\r\n def get_sequence_info(self, seq_id):\r\n bb_anno = torch.Tensor(self.sequence_list[seq_id]['anno'])\r\n valid = (bb_anno[:, 2] > 0) & (bb_anno[:, 3] > 0)\r\n visible = torch.ByteTensor(self.sequence_list[seq_id]['target_visible']) & valid.byte()\r\n return {'bbox': bb_anno, 'valid': valid, 'visible': visible}\r\n\r\n def _get_frame(self, sequence, frame_id):\r\n set_name = 'ILSVRC2015_VID_train_{:04d}'.format(sequence['set_id'])\r\n vid_name = 'ILSVRC2015_train_{:08d}'.format(sequence['vid_id'])\r\n frame_number = frame_id + sequence['start_frame']\r\n frame_path = os.path.join('Data', 'VID', 'train', set_name, vid_name,\r\n '{:06d}.JPEG'.format(frame_number))\r\n return decode_img(self.root, frame_path)\r\n\r\n def get_frames(self, seq_id, frame_ids, anno=None):\r\n sequence = self.sequence_list[seq_id]\r\n\r\n frame_list = [self._get_frame(sequence, f) for f in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n # Create anno dict\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\r\n\r\n # added the class info to the meta info\r\n object_meta = OrderedDict({'object_class': sequence['class_name'],\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n\r\n return frame_list, anno_frames, object_meta\r" }, { "identifier": "MSCOCOSeq_lmdb", "path": "lib/train/dataset/coco_seq_lmdb.py", "snippet": "class MSCOCOSeq_lmdb(BaseVideoDataset):\r\n \"\"\" The COCO dataset. COCO is an image dataset. Thus, we treat each image as a sequence of length 1.\r\n\r\n Publication:\r\n Microsoft COCO: Common Objects in Context.\r\n Tsung-Yi Lin, Michael Maire, Serge J. Belongie, Lubomir D. Bourdev, Ross B. Girshick, James Hays, Pietro Perona,\r\n Deva Ramanan, Piotr Dollar and C. Lawrence Zitnick\r\n ECCV, 2014\r\n https://arxiv.org/pdf/1405.0312.pdf\r\n\r\n Download the images along with annotations from http://cocodataset.org/#download. The root folder should be\r\n organized as follows.\r\n - coco_root\r\n - annotations\r\n - instances_train2014.json\r\n - instances_train2017.json\r\n - images\r\n - train2014\r\n - train2017\r\n\r\n Note: You also have to install the coco pythonAPI from https://github.com/cocodataset/cocoapi.\r\n \"\"\"\r\n\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None, split=\"train\", version=\"2014\",\r\n env_num=None):\r\n \"\"\"\r\n args:\r\n root - path to the coco dataset.\r\n image_loader (default_image_loader) - The function to read the images. If installed,\r\n jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,\r\n opencv's imread is used.\r\n data_fraction (None) - Fraction of images to be used. The images are selected randomly. If None, all the\r\n images will be used\r\n split - 'train' or 'val'.\r\n version - version of coco dataset (2014 or 2017)\r\n \"\"\"\r\n root = env_settings(env_num).coco_dir if root is None else root\r\n super().__init__('COCO_lmdb', root, image_loader)\r\n self.root = root\r\n self.img_pth = 'images/{}{}/'.format(split, version)\r\n self.anno_path = 'annotations/instances_{}{}.json'.format(split, version)\r\n\r\n # Load the COCO set.\r\n print('loading annotations into memory...')\r\n tic = time.time()\r\n coco_json = decode_json(root, self.anno_path)\r\n print('Done (t={:0.2f}s)'.format(time.time() - tic))\r\n\r\n self.coco_set = COCO(coco_json)\r\n\r\n self.cats = self.coco_set.cats\r\n\r\n self.class_list = self.get_class_list()\r\n\r\n self.sequence_list = self._get_sequence_list()\r\n\r\n if data_fraction is not None:\r\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\r\n self.seq_per_class = self._build_seq_per_class()\r\n\r\n def _get_sequence_list(self):\r\n ann_list = list(self.coco_set.anns.keys())\r\n seq_list = [a for a in ann_list if self.coco_set.anns[a]['iscrowd'] == 0]\r\n\r\n return seq_list\r\n\r\n def is_video_sequence(self):\r\n return False\r\n\r\n def get_num_classes(self):\r\n return len(self.class_list)\r\n\r\n def get_name(self):\r\n return 'coco_lmdb'\r\n\r\n def has_class_info(self):\r\n return True\r\n\r\n def get_class_list(self):\r\n class_list = []\r\n for cat_id in self.cats.keys():\r\n class_list.append(self.cats[cat_id]['name'])\r\n return class_list\r\n\r\n def has_segmentation_info(self):\r\n return True\r\n\r\n def get_num_sequences(self):\r\n return len(self.sequence_list)\r\n\r\n def _build_seq_per_class(self):\r\n seq_per_class = {}\r\n for i, seq in enumerate(self.sequence_list):\r\n class_name = self.cats[self.coco_set.anns[seq]['category_id']]['name']\r\n if class_name not in seq_per_class:\r\n seq_per_class[class_name] = [i]\r\n else:\r\n seq_per_class[class_name].append(i)\r\n\r\n return seq_per_class\r\n\r\n def get_sequences_in_class(self, class_name):\r\n return self.seq_per_class[class_name]\r\n\r\n def get_sequence_info(self, seq_id):\r\n anno = self._get_anno(seq_id)\r\n\r\n bbox = torch.Tensor(anno['bbox']).view(1, 4)\r\n\r\n mask = torch.Tensor(self.coco_set.annToMask(anno)).unsqueeze(dim=0)\r\n\r\n '''2021.1.3 To avoid too small bounding boxes. Here we change the threshold to 50 pixels'''\r\n valid = (bbox[:, 2] > 50) & (bbox[:, 3] > 50)\r\n\r\n visible = valid.clone().byte()\r\n\r\n return {'bbox': bbox, 'mask': mask, 'valid': valid, 'visible': visible}\r\n\r\n def _get_anno(self, seq_id):\r\n anno = self.coco_set.anns[self.sequence_list[seq_id]]\r\n\r\n return anno\r\n\r\n def _get_frames(self, seq_id):\r\n path = self.coco_set.loadImgs([self.coco_set.anns[self.sequence_list[seq_id]]['image_id']])[0]['file_name']\r\n # img = self.image_loader(os.path.join(self.img_pth, path))\r\n img = decode_img(self.root, os.path.join(self.img_pth, path))\r\n return img\r\n\r\n def get_meta_info(self, seq_id):\r\n try:\r\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\r\n object_meta = OrderedDict({'object_class_name': cat_dict_current['name'],\r\n 'motion_class': None,\r\n 'major_class': cat_dict_current['supercategory'],\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n except:\r\n object_meta = OrderedDict({'object_class_name': None,\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n return object_meta\r\n\r\n def get_class_name(self, seq_id):\r\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\r\n return cat_dict_current['name']\r\n\r\n def get_frames(self, seq_id=None, frame_ids=None, anno=None):\r\n # COCO is an image dataset. Thus we replicate the image denoted by seq_id len(frame_ids) times, and return a\r\n # list containing these replicated images.\r\n frame = self._get_frames(seq_id)\r\n\r\n frame_list = [frame.copy() for _ in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[0, ...] for _ in frame_ids]\r\n\r\n object_meta = self.get_meta_info(seq_id)\r\n\r\n return frame_list, anno_frames, object_meta\r" }, { "identifier": "TrackingNet_lmdb", "path": "lib/train/dataset/tracking_net_lmdb.py", "snippet": "class TrackingNet_lmdb(BaseVideoDataset):\r\n \"\"\" TrackingNet dataset.\r\n\r\n Publication:\r\n TrackingNet: A Large-Scale Dataset and Benchmark for Object Tracking in the Wild.\r\n Matthias Mueller,Adel Bibi, Silvio Giancola, Salman Al-Subaihi and Bernard Ghanem\r\n ECCV, 2018\r\n https://ivul.kaust.edu.sa/Documents/Publications/2018/TrackingNet%20A%20Large%20Scale%20Dataset%20and%20Benchmark%20for%20Object%20Tracking%20in%20the%20Wild.pdf\r\n\r\n Download the dataset using the toolkit https://github.com/SilvioGiancola/TrackingNet-devkit.\r\n \"\"\"\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, set_ids=None, data_fraction=None,env_num=None):\r\n \"\"\"\r\n args:\r\n root - The path to the TrackingNet folder, containing the training sets.\r\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\r\n is used by default.\r\n set_ids (None) - List containing the ids of the TrackingNet sets to be used for training. If None, all the\r\n sets (0 - 11) will be used.\r\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\r\n \"\"\"\r\n root = env_settings(env_num).trackingnet_lmdb_dir if root is None else root\r\n super().__init__('TrackingNet_lmdb', root, image_loader)\r\n\r\n if set_ids is None:\r\n set_ids = [i for i in range(12)]\r\n\r\n self.set_ids = set_ids\r\n\r\n # Keep a list of all videos. Sequence list is a list of tuples (set_id, video_name) containing the set_id and\r\n # video_name for each sequence\r\n self.sequence_list = list_sequences(self.root)\r\n\r\n if data_fraction is not None:\r\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\r\n\r\n self.seq_to_class_map, self.seq_per_class = self._load_class_info()\r\n\r\n # we do not have the class_lists for the tracking net\r\n self.class_list = list(self.seq_per_class.keys())\r\n self.class_list.sort()\r\n\r\n def _load_class_info(self):\r\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\r\n class_map_path = os.path.join(ltr_path, 'data_specs', 'trackingnet_classmap.txt')\r\n\r\n with open(class_map_path, 'r') as f:\r\n seq_to_class_map = {seq_class.split('\\t')[0]: seq_class.rstrip().split('\\t')[1] for seq_class in f}\r\n\r\n seq_per_class = {}\r\n for i, seq in enumerate(self.sequence_list):\r\n class_name = seq_to_class_map.get(seq[1], 'Unknown')\r\n if class_name not in seq_per_class:\r\n seq_per_class[class_name] = [i]\r\n else:\r\n seq_per_class[class_name].append(i)\r\n\r\n return seq_to_class_map, seq_per_class\r\n\r\n def get_name(self):\r\n return 'trackingnet_lmdb'\r\n\r\n def has_class_info(self):\r\n return True\r\n\r\n def get_sequences_in_class(self, class_name):\r\n return self.seq_per_class[class_name]\r\n\r\n def _read_bb_anno(self, seq_id):\r\n set_id = self.sequence_list[seq_id][0]\r\n vid_name = self.sequence_list[seq_id][1]\r\n gt_str_list = decode_str(os.path.join(self.root, \"TRAIN_%d_lmdb\" % set_id),\r\n os.path.join(\"anno\", vid_name + \".txt\")).split('\\n')[:-1]\r\n gt_list = [list(map(float, line.split(','))) for line in gt_str_list]\r\n gt_arr = np.array(gt_list).astype(np.float32)\r\n return torch.tensor(gt_arr)\r\n\r\n def get_sequence_info(self, seq_id):\r\n bbox = self._read_bb_anno(seq_id)\r\n\r\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\r\n visible = valid.clone().byte()\r\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\r\n\r\n def _get_frame(self, seq_id, frame_id):\r\n set_id = self.sequence_list[seq_id][0]\r\n vid_name = self.sequence_list[seq_id][1]\r\n return decode_img(os.path.join(self.root, \"TRAIN_%d_lmdb\" % set_id),\r\n os.path.join(\"frames\", vid_name, str(frame_id) + \".jpg\"))\r\n\r\n def _get_class(self, seq_id):\r\n seq_name = self.sequence_list[seq_id][1]\r\n return self.seq_to_class_map[seq_name]\r\n\r\n def get_class_name(self, seq_id):\r\n obj_class = self._get_class(seq_id)\r\n\r\n return obj_class\r\n\r\n def get_frames(self, seq_id, frame_ids, anno=None):\r\n frame_list = [self._get_frame(seq_id, f) for f in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\r\n\r\n obj_class = self._get_class(seq_id)\r\n\r\n object_meta = OrderedDict({'object_class_name': obj_class,\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n\r\n return frame_list, anno_frames, object_meta\r" }, { "identifier": "Adan", "path": "lib/train/optimizer/anan.py", "snippet": "class Adan(Optimizer):\r\n \"\"\"\r\n Implements a pytorch variant of Adan\r\n Adan was proposed in\r\n Adan: Adaptive Nesterov Momentum Algorithm for\r\n Faster Optimizing Deep Models[J].arXiv preprint arXiv:2208.06677, 2022.\r\n https://arxiv.org/abs/2208.06677\r\n Arguments:\r\n params (iterable): iterable of parameters to optimize or\r\n dicts defining parameter groups.\r\n lr (float, optional): learning rate. (default: 1e-3)\r\n betas (Tuple[float, float, flot], optional): coefficients used for\r\n first- and second-order moments. (default: (0.98, 0.92, 0.99))\r\n eps (float, optional): term added to the denominator to improve\r\n numerical stability. (default: 1e-8)\r\n weight_decay (float, optional): decoupled weight decay\r\n (L2 penalty) (default: 0)\r\n max_grad_norm (float, optional): value used to clip\r\n global grad norm (default: 0.0 no clip)\r\n no_prox (bool): how to perform the decoupled weight decay\r\n (default: False)\r\n foreach (bool): if True would use torch._foreach implementation.\r\n It's faster but uses slightly more memory. (default: True)\r\n fused (bool, optional): whether fused implementation is used.\r\n (default: False)\r\n\r\n VIT:\r\n 150\r\n lr 0.015\r\n betas (0.98, 0.92, 0.99)\r\n eps 1.0e-08\r\n weight_decay 0.02\r\n max_grad_norm 5.0\r\n no_prox\r\n foreach\r\n fused\r\n 300\r\n lr 0.015\r\n betas (0.98, 0.92, 0.99)\r\n eps 1.0e-08\r\n weight_decay 0.02\r\n max_grad_norm 5.0\r\n no_prox\r\n foreach\r\n fused\r\n \"\"\"\r\n def __init__(self,\r\n params,\r\n lr=1e-3,\r\n betas=(0.98, 0.92, 0.99),\r\n eps=1e-8,\r\n weight_decay=0.0,\r\n max_grad_norm=0.0,\r\n no_prox=False,\r\n foreach: bool = True,\r\n fused: bool = False):\r\n if not 0.0 <= max_grad_norm:\r\n raise ValueError('Invalid Max grad norm: {}'.format(max_grad_norm))\r\n if not 0.0 <= lr:\r\n raise ValueError('Invalid learning rate: {}'.format(lr))\r\n if not 0.0 <= eps:\r\n raise ValueError('Invalid epsilon value: {}'.format(eps))\r\n if not 0.0 <= betas[0] < 1.0:\r\n raise ValueError('Invalid beta parameter at index 0: {}'.format(\r\n betas[0]))\r\n if not 0.0 <= betas[1] < 1.0:\r\n raise ValueError('Invalid beta parameter at index 1: {}'.format(\r\n betas[1]))\r\n if not 0.0 <= betas[2] < 1.0:\r\n raise ValueError('Invalid beta parameter at index 2: {}'.format(\r\n betas[2]))\r\n defaults = dict(lr=lr,\r\n betas=betas,\r\n eps=eps,\r\n weight_decay=weight_decay,\r\n max_grad_norm=max_grad_norm,\r\n no_prox=no_prox,\r\n foreach=foreach,\r\n fused=fused)\r\n super().__init__(params, defaults)\r\n\r\n def __setstate__(self, state):\r\n super(Adan, self).__setstate__(state)\r\n for group in self.param_groups:\r\n group.setdefault('no_prox', False)\r\n\r\n @torch.no_grad()\r\n def restart_opt(self):\r\n for group in self.param_groups:\r\n group['step'] = 0\r\n for p in group['params']:\r\n if p.requires_grad:\r\n state = self.state[p]\r\n # State initialization\r\n\r\n # Exponential moving average of gradient values\r\n state['exp_avg'] = torch.zeros_like(p)\r\n # Exponential moving average of squared gradient values\r\n state['exp_avg_sq'] = torch.zeros_like(p)\r\n # Exponential moving average of gradient difference\r\n state['exp_avg_diff'] = torch.zeros_like(p)\r\n\r\n @torch.no_grad()\r\n def step(self, closure=None):\r\n \"\"\"Performs a single optimization step.\"\"\"\r\n\r\n loss = None\r\n if closure is not None:\r\n with torch.enable_grad():\r\n loss = closure()\r\n\r\n if self.defaults['max_grad_norm'] > 0:\r\n device = self.param_groups[0]['params'][0].device\r\n global_grad_norm = torch.zeros(1, device=device)\r\n\r\n max_grad_norm = torch.tensor(self.defaults['max_grad_norm'],\r\n device=device)\r\n for group in self.param_groups:\r\n\r\n for p in group['params']:\r\n if p.grad is not None:\r\n grad = p.grad\r\n global_grad_norm.add_(grad.pow(2).sum())\r\n\r\n global_grad_norm = torch.sqrt(global_grad_norm)\r\n\r\n clip_global_grad_norm = torch.clamp(\r\n max_grad_norm / (global_grad_norm + group['eps']),\r\n max=1.0).item()\r\n else:\r\n clip_global_grad_norm = 1.0\r\n\r\n for group in self.param_groups:\r\n params_with_grad = []\r\n grads = []\r\n exp_avgs = []\r\n exp_avg_sqs = []\r\n exp_avg_diffs = []\r\n neg_pre_grads = []\r\n\r\n beta1, beta2, beta3 = group['betas']\r\n # assume same step across group now to simplify things\r\n # per parameter step can be easily support\r\n # by making it tensor, or pass list into kernel\r\n if 'step' in group:\r\n group['step'] += 1\r\n else:\r\n group['step'] = 1\r\n\r\n bias_correction1 = 1.0 - beta1**group['step']\r\n bias_correction2 = 1.0 - beta2**group['step']\r\n bias_correction3 = 1.0 - beta3**group['step']\r\n\r\n for p in group['params']:\r\n if p.grad is None:\r\n continue\r\n params_with_grad.append(p)\r\n grads.append(p.grad)\r\n\r\n state = self.state[p]\r\n if len(state) == 0:\r\n state['exp_avg'] = torch.zeros_like(p)\r\n state['exp_avg_sq'] = torch.zeros_like(p)\r\n state['exp_avg_diff'] = torch.zeros_like(p)\r\n\r\n if 'neg_pre_grad' not in state or group['step'] == 1:\r\n state['neg_pre_grad'] = p.grad.clone().mul_(\r\n -clip_global_grad_norm)\r\n\r\n exp_avgs.append(state['exp_avg'])\r\n exp_avg_sqs.append(state['exp_avg_sq'])\r\n exp_avg_diffs.append(state['exp_avg_diff'])\r\n neg_pre_grads.append(state['neg_pre_grad'])\r\n\r\n kwargs = dict(\r\n params=params_with_grad,\r\n grads=grads,\r\n exp_avgs=exp_avgs,\r\n exp_avg_sqs=exp_avg_sqs,\r\n exp_avg_diffs=exp_avg_diffs,\r\n neg_pre_grads=neg_pre_grads,\r\n beta1=beta1,\r\n beta2=beta2,\r\n beta3=beta3,\r\n bias_correction1=bias_correction1,\r\n bias_correction2=bias_correction2,\r\n bias_correction3_sqrt=math.sqrt(bias_correction3),\r\n lr=group['lr'],\r\n weight_decay=group['weight_decay'],\r\n eps=group['eps'],\r\n no_prox=group['no_prox'],\r\n clip_global_grad_norm=clip_global_grad_norm,\r\n )\r\n\r\n if group['foreach']:\r\n if group['fused']:\r\n if torch.cuda.is_available():\r\n _fused_adan_multi_tensor(**kwargs)\r\n else:\r\n raise ValueError('Fused Adan does not support CPU')\r\n else:\r\n _multi_tensor_adan(**kwargs)\r\n elif group['fused']:\r\n if torch.cuda.is_available():\r\n _fused_adan_single_tensor(**kwargs)\r\n else:\r\n raise ValueError('Fused Adan does not support CPU')\r\n else:\r\n _single_tensor_adan(**kwargs)\r\n\r\n return loss\r" }, { "identifier": "Lion", "path": "lib/train/optimizer/lion.py", "snippet": "class Lion(Optimizer):\r\n r\"\"\"Implements Lion algorithm.\"\"\"\r\n\r\n def __init__(self, params, lr=1e-4, betas=(0.9, 0.99), weight_decay=0.0):\r\n \"\"\"Initialize the hyperparameters.\r\n\r\n Args:\r\n params (iterable): iterable of parameters to optimize or dicts defining\r\n parameter groups\r\n lr (float, optional): learning rate (default: 1e-4)\r\n betas (Tuple[float, float], optional): coefficients used for computing\r\n running averages of gradient and its square (default: (0.9, 0.99))\r\n weight_decay (float, optional): weight decay coefficient (default: 0)\r\n \"\"\"\r\n\r\n if not 0.0 <= lr:\r\n raise ValueError('Invalid learning rate: {}'.format(lr))\r\n if not 0.0 <= betas[0] < 1.0:\r\n raise ValueError('Invalid beta parameter at index 0: {}'.format(betas[0]))\r\n if not 0.0 <= betas[1] < 1.0:\r\n raise ValueError('Invalid beta parameter at index 1: {}'.format(betas[1]))\r\n defaults = dict(lr=lr, betas=betas, weight_decay=weight_decay)\r\n super().__init__(params, defaults)\r\n\r\n @torch.no_grad()\r\n def step(self, closure=None):\r\n \"\"\"Performs a single optimization step.\r\n\r\n Args:\r\n closure (callable, optional): A closure that reevaluates the model\r\n and returns the loss.\r\n\r\n Returns:\r\n the loss.\r\n \"\"\"\r\n loss = None\r\n if closure is not None:\r\n with torch.enable_grad():\r\n loss = closure()\r\n\r\n for group in self.param_groups:\r\n for p in group['params']:\r\n if p.grad is None:\r\n continue\r\n\r\n # Perform stepweight decay\r\n p.data.mul_(1 - group['lr'] * group['weight_decay'])\r\n\r\n grad = p.grad\r\n state = self.state[p]\r\n # State initialization\r\n if len(state) == 0:\r\n # Exponential moving average of gradient values\r\n state['exp_avg'] = torch.zeros_like(p)\r\n\r\n exp_avg = state['exp_avg']\r\n beta1, beta2 = group['betas']\r\n\r\n # Weight update\r\n update = exp_avg * beta1 + grad * (1 - beta1)\r\n p.add_(torch.sign(update), alpha=-group['lr'])\r\n # Decay the momentum running average coefficient\r\n exp_avg.mul_(beta2).add_(grad, alpha=1 - beta2)\r\n\r\n return loss" }, { "identifier": "is_main_process", "path": "lib/utils/misc.py", "snippet": "def is_main_process():\r\n return get_rank() == 0\r" } ]
import torch import lib.train.data.transforms as tfm from torch.utils.data.distributed import DistributedSampler from lib.train.data import sampler, opencv_loader, processing, LTRLoader from lib.train.dataset import Lasot, Got10k, MSCOCOSeq, ImagenetVID, TrackingNet from lib.train.dataset import Lasot_lmdb, Got10k_lmdb, MSCOCOSeq_lmdb, ImagenetVID_lmdb, TrackingNet_lmdb from lib.train.optimizer.anan import Adan from lib.train.optimizer.lion import Lion from lib.utils.misc import is_main_process
20,935
# datasets related def update_settings(settings, cfg): settings.print_interval = cfg.TRAIN.PRINT_INTERVAL settings.search_area_factor = {'template': cfg.DATA.TEMPLATE.FACTOR, 'search': cfg.DATA.SEARCH.FACTOR} settings.output_sz = {'template': cfg.DATA.TEMPLATE.SIZE, 'search': cfg.DATA.SEARCH.SIZE} settings.center_jitter_factor = {'template': cfg.DATA.TEMPLATE.CENTER_JITTER, 'search': cfg.DATA.SEARCH.CENTER_JITTER} settings.scale_jitter_factor = {'template': cfg.DATA.TEMPLATE.SCALE_JITTER, 'search': cfg.DATA.SEARCH.SCALE_JITTER} settings.grad_clip_norm = cfg.TRAIN.GRAD_CLIP_NORM settings.print_stats = None settings.batchsize = cfg.TRAIN.BATCH_SIZE settings.scheduler_type = cfg.TRAIN.SCHEDULER.TYPE settings.save_interval = cfg.TRAIN.SAVE_INTERVAL def names2datasets(name_list: list, settings, image_loader): assert isinstance(name_list, list) datasets = [] for name in name_list: # assert name in ["LASOT", "GOT10K_vottrain", "GOT10K_votval", "GOT10K_train_full", "GOT10K_official_val", # "COCO17", "VID", "TRACKINGNET"] if name == "LASOT": if settings.use_lmdb: print("Building lasot dataset from lmdb") datasets.append(Lasot_lmdb(settings.env.lasot_lmdb_dir, split='train', image_loader=image_loader, env_num=settings.env_num)) else: datasets.append( Lasot(settings.env.lasot_dir, split='train', image_loader=image_loader, env_num=settings.env_num)) if name == "GOT10K_vottrain": if settings.use_lmdb: print("Building got10k from lmdb") datasets.append(Got10k_lmdb(settings.env.got10k_lmdb_dir, split='vottrain', image_loader=image_loader, env_num=settings.env_num)) else: datasets.append(Got10k(settings.env.got10k_dir, split='vottrain', image_loader=image_loader, env_num=settings.env_num)) if name == "GOT10K_train_full": if settings.use_lmdb: print("Building got10k_train_full from lmdb") datasets.append( Got10k_lmdb(settings.env.got10k_lmdb_dir, split='train_full', image_loader=image_loader, env_num=settings.env_num)) else: datasets.append(Got10k(settings.env.got10k_dir, split='train_full', image_loader=image_loader, env_num=settings.env_num)) if name == "GOT10K_votval": if settings.use_lmdb: print("Building got10k from lmdb") datasets.append(Got10k_lmdb(settings.env.got10k_lmdb_dir, split='votval', image_loader=image_loader, env_num=settings.env_num)) else: datasets.append(Got10k(settings.env.got10k_dir, split='votval', image_loader=image_loader, env_num=settings.env_num)) if name == "GOT10K_official_val": if settings.use_lmdb: raise ValueError("Not implement") else: datasets.append(Got10k(settings.env.got10k_val_dir, split=None, image_loader=image_loader, env_num=settings.env_num)) if name == "COCO17": if settings.use_lmdb: print("Building COCO2017 from lmdb")
# datasets related def update_settings(settings, cfg): settings.print_interval = cfg.TRAIN.PRINT_INTERVAL settings.search_area_factor = {'template': cfg.DATA.TEMPLATE.FACTOR, 'search': cfg.DATA.SEARCH.FACTOR} settings.output_sz = {'template': cfg.DATA.TEMPLATE.SIZE, 'search': cfg.DATA.SEARCH.SIZE} settings.center_jitter_factor = {'template': cfg.DATA.TEMPLATE.CENTER_JITTER, 'search': cfg.DATA.SEARCH.CENTER_JITTER} settings.scale_jitter_factor = {'template': cfg.DATA.TEMPLATE.SCALE_JITTER, 'search': cfg.DATA.SEARCH.SCALE_JITTER} settings.grad_clip_norm = cfg.TRAIN.GRAD_CLIP_NORM settings.print_stats = None settings.batchsize = cfg.TRAIN.BATCH_SIZE settings.scheduler_type = cfg.TRAIN.SCHEDULER.TYPE settings.save_interval = cfg.TRAIN.SAVE_INTERVAL def names2datasets(name_list: list, settings, image_loader): assert isinstance(name_list, list) datasets = [] for name in name_list: # assert name in ["LASOT", "GOT10K_vottrain", "GOT10K_votval", "GOT10K_train_full", "GOT10K_official_val", # "COCO17", "VID", "TRACKINGNET"] if name == "LASOT": if settings.use_lmdb: print("Building lasot dataset from lmdb") datasets.append(Lasot_lmdb(settings.env.lasot_lmdb_dir, split='train', image_loader=image_loader, env_num=settings.env_num)) else: datasets.append( Lasot(settings.env.lasot_dir, split='train', image_loader=image_loader, env_num=settings.env_num)) if name == "GOT10K_vottrain": if settings.use_lmdb: print("Building got10k from lmdb") datasets.append(Got10k_lmdb(settings.env.got10k_lmdb_dir, split='vottrain', image_loader=image_loader, env_num=settings.env_num)) else: datasets.append(Got10k(settings.env.got10k_dir, split='vottrain', image_loader=image_loader, env_num=settings.env_num)) if name == "GOT10K_train_full": if settings.use_lmdb: print("Building got10k_train_full from lmdb") datasets.append( Got10k_lmdb(settings.env.got10k_lmdb_dir, split='train_full', image_loader=image_loader, env_num=settings.env_num)) else: datasets.append(Got10k(settings.env.got10k_dir, split='train_full', image_loader=image_loader, env_num=settings.env_num)) if name == "GOT10K_votval": if settings.use_lmdb: print("Building got10k from lmdb") datasets.append(Got10k_lmdb(settings.env.got10k_lmdb_dir, split='votval', image_loader=image_loader, env_num=settings.env_num)) else: datasets.append(Got10k(settings.env.got10k_dir, split='votval', image_loader=image_loader, env_num=settings.env_num)) if name == "GOT10K_official_val": if settings.use_lmdb: raise ValueError("Not implement") else: datasets.append(Got10k(settings.env.got10k_val_dir, split=None, image_loader=image_loader, env_num=settings.env_num)) if name == "COCO17": if settings.use_lmdb: print("Building COCO2017 from lmdb")
datasets.append(MSCOCOSeq_lmdb(settings.env.coco_lmdb_dir, version="2017", image_loader=image_loader,
12
2023-10-08 11:44:32+00:00
24k
LiyaoTang/ERDA
utils/trainer.py
[ { "identifier": "log_config", "path": "config/utils.py", "snippet": "def log_config(config, title='', f_out=None, prefix='', base=None):\n if f_out is None:\n f_out = sys.stdout\n if base is None:\n root = os.path.join(os.getcwd(), os.path.dirname(__file__), '../')\n sys.path += [] if root in sys.path or os.path.realpath(root) in sys.path else [root]\n from config.base import Base as base\n\n print(f'\\n{prefix}<<< ======= {config._cls} ======= {title if title else config.name}', file=f_out)\n max_len = max([len(k) for k in dir(config) if not k.startswith('_')] + [0])\n for k in config.keys(): # dir would sort\n # if k.startswith('_') or _is_method(getattr(config, k)):\n # continue\n cur_attr = getattr(config, k)\n if isinstance(cur_attr, list) and len(str(cur_attr)) > 200: # overlong list\n cur_attr = '[' + f'\\n{prefix}\\t\\t'.join([''] + [str(s) for s in cur_attr]) + f'\\n{prefix}\\t]'\n\n print('\\t%s%s\\t= %s' % (prefix + k, ' ' * (max_len-len(k)), str(cur_attr)), file=f_out)\n if is_config(cur_attr, base=base):\n log_config(cur_attr, f_out=f_out, prefix=prefix+'\\t', base=base)\n print('\\n', file=f_out, flush=True)" }, { "identifier": "print_dict", "path": "utils/logger.py", "snippet": "def print_dict(d, prefix='', except_k=[], fn=None, head=None, dict_type=(dict,), list_type=(list, tuple), expand_len=120):\n if head is not None:\n d = {head: d}\n for k, v in d.items():\n if k in except_k:\n continue\n if isinstance(d[k], dict_type):\n print(f'{prefix}{str(k)}:')\n print_dict(d[k], prefix=f'{prefix}\\t', except_k=except_k, fn=fn, expand_len=120)\n else:\n if fn:\n rst = None\n try:\n if isinstance(v, list_type):\n rst = v.__class__([fn(vv) for vv in v])\n else:\n rst = fn(v)\n except:\n pass\n v = rst if rst else v\n line = f'{prefix}{str(k)}\\t{str(v)}'\n if isinstance(v, list_type) and expand_len and len(str(line)) > expand_len: # overlong\n line_pre = f'{prefix}{str(k)}\\t' + ('[' if isinstance(v, list) else '(')\n line_post = f'\\n{prefix}\\t' + (']' if isinstance(v, list) else ')')\n if set(dict_type).issuperset(set([type(s) for s in v])): # all dict in list\n print(line_pre)\n for s in v[:-1]:\n print_dict(s, prefix=f'{prefix}\\t\\t')\n print(f'{prefix}\\t\\t,')\n print_dict(v[-1], prefix=f'{prefix}\\t\\t')\n line = line_post\n else:\n line = line_pre + f'\\n{prefix}\\t\\t'.join([''] + [str(s) for s in v]) + line_post\n\n print(line)" }, { "identifier": "print_table", "path": "utils/logger.py", "snippet": "def print_table(t, prefix='', sep=' '): # assume a 2D-list\n max_len = np.array([[len(str(ii)) for ii in l] for l in t], dtype=int).max(axis=0)\n for line in t:\n print(prefix + sep.join([str(ii) + ' ' * (max_len[i] - len(str(ii))) for i, ii in enumerate(line)]))" }, { "identifier": "read_ply", "path": "utils/ply.py", "snippet": "def read_ply(filename, triangular_mesh=False):\n \"\"\"\n Read \".ply\" files\n\n Parameters\n ----------\n filename : string\n the name of the file to read.\n\n Returns\n -------\n result : array\n data stored in the file\n\n Examples\n --------\n Store data in file\n\n >>> points = np.random.rand(5, 3)\n >>> values = np.random.randint(2, size=10)\n >>> write_ply('example.ply', [points, values], ['x', 'y', 'z', 'values'])\n\n Read the file\n\n >>> data = read_ply('example.ply')\n >>> values = data['values']\n array([0, 0, 1, 1, 0])\n \n >>> points = np.vstack((data['x'], data['y'], data['z'])).T\n array([[ 0.466 0.595 0.324]\n [ 0.538 0.407 0.654]\n [ 0.850 0.018 0.988]\n [ 0.395 0.394 0.363]\n [ 0.873 0.996 0.092]])\n\n \"\"\"\n\n with open(filename, 'rb') as plyfile:\n\n\n # Check if the file start with ply\n if b'ply' not in plyfile.readline():\n raise ValueError('The file does not start whith the word ply')\n\n # get binary_little/big or ascii\n fmt = plyfile.readline().split()[1].decode()\n if fmt == \"ascii\":\n raise ValueError('The file is not binary')\n\n # get extension for building the numpy dtypes\n ext = valid_formats[fmt]\n\n # PointCloud reader vs mesh reader\n if triangular_mesh:\n\n # Parse header\n num_points, num_faces, properties = parse_mesh_header(plyfile, ext)\n\n # Get point data\n vertex_data = np.fromfile(plyfile, dtype=properties, count=num_points)\n\n # Get face data\n face_properties = [('k', ext + 'u1'),\n ('v1', ext + 'i4'),\n ('v2', ext + 'i4'),\n ('v3', ext + 'i4')]\n faces_data = np.fromfile(plyfile, dtype=face_properties, count=num_faces)\n\n # Return vertex data and concatenated faces\n faces = np.vstack((faces_data['v1'], faces_data['v2'], faces_data['v3'])).T\n data = [vertex_data, faces]\n\n else:\n\n # Parse header\n num_points, properties = parse_header(plyfile, ext)\n\n # Get data\n data = np.fromfile(plyfile, dtype=properties, count=num_points)\n\n return data" }, { "identifier": "write_ply", "path": "utils/ply.py", "snippet": "def write_ply(filename, field_list, field_names, triangular_faces=None):\n \"\"\"\n Write \".ply\" files\n\n Parameters\n ----------\n filename : string\n the name of the file to which the data is saved. A '.ply' extension will be appended to the \n file name if it does no already have one.\n\n field_list : list, tuple, numpy array\n the fields to be saved in the ply file. Either a numpy array, a list of numpy arrays or a \n tuple of numpy arrays. Each 1D numpy array and each column of 2D numpy arrays are considered \n as one field. \n\n field_names : list\n the name of each fields as a list of strings. Has to be the same length as the number of \n fields.\n\n Examples\n --------\n >>> points = np.random.rand(10, 3)\n >>> write_ply('example1.ply', points, ['x', 'y', 'z'])\n\n >>> values = np.random.randint(2, size=10)\n >>> write_ply('example2.ply', [points, values], ['x', 'y', 'z', 'values'])\n\n >>> colors = np.random.randint(255, size=(10,3), dtype=np.uint8)\n >>> field_names = ['x', 'y', 'z', 'red', 'green', 'blue', values']\n >>> write_ply('example3.ply', [points, colors, values], field_names)\n\n \"\"\"\n\n # Format list input to the right form\n field_list = list(field_list) if (type(field_list) == list or type(field_list) == tuple) else list((field_list,))\n for i, field in enumerate(field_list):\n if field.ndim < 2:\n field_list[i] = field.reshape(-1, 1)\n if field.ndim > 2:\n print('fields have more than 2 dimensions')\n return False \n\n # check all fields have the same number of data\n n_points = [field.shape[0] for field in field_list]\n if not np.all(np.equal(n_points, n_points[0])):\n print('wrong field dimensions')\n return False \n\n # Check if field_names and field_list have same nb of column\n n_fields = np.sum([field.shape[1] for field in field_list])\n if (n_fields != len(field_names)):\n print('wrong number of field names')\n return False\n\n # Add extension if not there\n if not filename.endswith('.ply'):\n filename += '.ply'\n\n # open in text mode to write the header\n with open(filename, 'w') as plyfile:\n\n # First magical word\n header = ['ply']\n\n # Encoding format\n header.append('format binary_' + sys.byteorder + '_endian 1.0')\n\n # Points properties description\n header.extend(header_properties(field_list, field_names))\n\n # Add faces if needded\n if triangular_faces is not None:\n header.append('element face {:d}'.format(triangular_faces.shape[0]))\n header.append('property list uchar int vertex_indices')\n\n # End of header\n header.append('end_header')\n\n # Write all lines\n for line in header:\n plyfile.write(\"%s\\n\" % line)\n\n # open in binary/append to use tofile\n with open(filename, 'ab') as plyfile:\n\n # Create a structured array\n i = 0\n type_list = []\n for fields in field_list:\n for field in fields.T:\n type_list += [(field_names[i], field.dtype.str)]\n i += 1\n data = np.empty(field_list[0].shape[0], dtype=type_list)\n i = 0\n for fields in field_list:\n for field in fields.T:\n data[field_names[i]] = field\n i += 1\n\n data.tofile(plyfile)\n\n if triangular_faces is not None:\n triangular_faces = triangular_faces.astype(np.int32)\n type_list = [('k', 'uint8')] + [(str(ind), 'int32') for ind in range(3)]\n data = np.empty(triangular_faces.shape[0], dtype=type_list)\n data['k'] = np.full((triangular_faces.shape[0],), 3, dtype=np.uint8)\n data['0'] = triangular_faces[:, 0]\n data['1'] = triangular_faces[:, 1]\n data['2'] = triangular_faces[:, 2]\n data.tofile(plyfile)\n\n return True" }, { "identifier": "ModelTester", "path": "utils/tester.py", "snippet": "class ModelTester:\n\n # Initiation methods\n # ------------------------------------------------------------------------------------------------------------------\n\n def __init__(self, config, verbose=True):\n self.config = config\n self.verbose = verbose\n\n self.save_extra = {} # for saving with extra ops\n\n if config.dataset in ['S3DIS', 'ScanNet', 'SensatUrban']:\n self.val_running_vote = self.val_running_vote_seg\n self.val_vote = self.val_vote_seg\n self.test_vote = self.test_vote_seg\n else:\n raise NotImplementedError(f'not supported dataset: {config.dataset}')\n\n def init_pointcloud_log(self, dataset, split, d, dtype=np.float32, init_fn=np.zeros):\n shape = lambda l: [l, d] if d else [l] # d - size of last dimension => each point d-dim [N, d] (d = None to have [N])\n log = [init_fn(shape=shape(t.data.shape[0]), dtype=dtype) for t in dataset.input_trees[split]]\n return log\n\n def initialize(self, ops, dataset, model, split):\n # initialize cum_dict & ops\n config = self.config\n ncls = config.num_classes\n\n run_ops = {k: ops['result_dict'][k] for k in ['inputs', 'seg']} # assumes per-gpu rst - support multi-gpu\n cum_dict = {\n 'prob': self.init_pointcloud_log(dataset, split, ncls)\n }\n\n extra_ops = [k for k in config.extra_ops.split('-') if k]\n extra_ops_solved = extra_ops.copy()\n for k in extra_ops:\n if k in ['prob', 'conf']:\n continue\n else:\n raise ValueError(f'not supported extra ops k = {k} from {config.extra_ops}')\n\n return run_ops, cum_dict, extra_ops_solved\n\n # Val methods\n # ------------------------------------------------------------------------------------------------------------------\n\n def val_running_vote_seg(self, sess, ops, dataset, model, validation_probs, epoch=1):\n \"\"\"\n One epoch validating - running voting used during training, main task results only\n \"\"\"\n\n val_smooth = 0.95 # Choose validation smoothing parameter (0 for no smothing, 0.99 for big smoothing)\n\n result_dict = {k: ops['result_dict'][k] for k in ['inputs', 'seg']} # result dict for seg\n val_ops = {'loss_dict': ops['loss_dict'], 'result_dict': result_dict}\n feed_dict = {ops['is_training']: False}\n\n # Initialise iterator\n sess.run(ops['val_init_op'])\n\n ep = 0\n loss_meter = {k: AverageMeter() for k in val_ops['loss_dict']} if 'loss_dict' in val_ops else{}\n cum_dict = {\n 'conf': 0, # conf from current validation\n 'prob': validation_probs, # accumulating probs\n }\n while ep < epoch:\n try:\n rst = sess.run(val_ops, feed_dict=feed_dict)\n\n loss_dict = rst['loss_dict'] if 'loss_dict' in rst else {}\n cur_rst = rst['result_dict'] # per-gpu result\n\n for k, v in loss_dict.items():\n loss_meter[k].update(v)\n\n # Stack all validation predictions for each class separately - iterate over each gpu & cloud\n self.cumulate_probs(dataset, model, cur_rst, cum_dict, task='seg', smooth=val_smooth)\n\n except tf.errors.OutOfRangeError:\n ep += 1\n pass\n\n if loss_meter:\n print(f'val loss avg:', ' '.join([f'{loss_n} = {meter.avg:.3f}' for loss_n, meter in loss_meter.items()]))\n\n label_to_idx = dataset.label_to_idx\n proportions = dataset.val_proportions\n cur_m = metrics_from_confusions(cum_dict['conf'], proportions=proportions) # use sampled pred-label of current epoch\n vote_m = metrics_from_result(validation_probs, dataset.input_labels['validation'], dataset.num_classes, label_to_idx=label_to_idx, proportions=proportions) # use the accumulated per-point voting\n\n print(f'metrics - current {cur_m}\\n'\n f' - accumulated {vote_m}', flush=True)\n return cur_m\n\n\n def val_vote_seg(self, sess, ops, dataset, model, num_votes=20):\n \"\"\"\n Voting validating\n \"\"\"\n\n feed_dict = {ops['is_training']: False}\n\n # Smoothing parameter for votes\n val_smooth = 0.95\n\n # Initialise iterator with val data\n sess.run(ops['val_init_op'])\n\n # Initiate global prediction over val clouds\n label_to_idx = dataset.label_to_idx\n proportions = dataset.val_proportions\n val_ops, cum_dict, extra_ops = self.initialize(ops, dataset, model, 'validation')\n val_probs = cum_dict['prob']\n\n vote_ind = 0\n last_min = -0.5\n if self.config.debug:\n print_dict(val_ops, head='val_vote_seg - val_ops')\n while last_min < num_votes:\n try:\n cur_rst = sess.run(val_ops, feed_dict=feed_dict)\n # Stack all validation predictions for each class separately - iterate over each gpu & cloud\n self.cumulate_probs(dataset, model, cur_rst, cum_dict, task='seg', smooth=val_smooth)\n\n except tf.errors.OutOfRangeError:\n new_min = np.min(dataset.min_potentials['validation'])\n if self.verbose:\n print(f'Step {vote_ind:3d}, end. Min potential = {new_min:.1f}', flush=True)\n if last_min + 1 < new_min:\n # Update last_min\n last_min += 1\n\n if self.verbose > 1:\n # Show vote results on subcloud (match original label to valid) => not the good values here\n vote_m = metrics_from_result(val_probs, dataset.input_labels['validation'], dataset.num_classes, label_to_idx=label_to_idx, proportions=proportions)\n print('==> Confusion on sub clouds: ', vote_m.scalar_str)\n\n if self.verbose > 1 and int(np.ceil(new_min)) % 2 == 0:\n # Project predictions\n vote_m = metrics_from_result(val_probs, dataset.validation_labels, dataset.num_classes, label_to_idx=label_to_idx, projections=dataset.validation_proj)\n print('==> Confusion on full clouds:', vote_m)\n\n sess.run(ops['val_init_op'])\n vote_ind += 1\n\n vote_m = metrics_from_result(val_probs, dataset.input_labels['validation'], dataset.num_classes, label_to_idx=label_to_idx, proportions=proportions)\n print('==> Confusion on sub clouds - final: ', vote_m.scalar_str)\n\n # Project predictions\n print('==> Confusion on full clouds - final:')\n vote_m = metrics_from_result(val_probs, dataset.validation_labels, dataset.num_classes, label_to_idx=label_to_idx, projections=dataset.validation_proj)\n vote_m.print()\n print('\\nfinished\\n', flush=True)\n\n return\n\n\n # Test methods\n # ------------------------------------------------------------------------------------------------------------------\n\n def test_classification(self, model, dataset, num_votes=100):\n\n # Initialise iterator with test data\n self.sess.run(dataset.test_init_op)\n\n # Number of classes predicted by the model\n nc_model = config.num_classes\n\n # Initiate votes\n average_probs = np.zeros((len(dataset.input_labels['test']), nc_model))\n average_counts = np.zeros((len(dataset.input_labels['test']), nc_model))\n\n mean_dt = np.zeros(2)\n last_display = time.time()\n while np.min(average_counts) < num_votes:\n\n # Run model on all test examples\n # ******************************\n\n # Initiate result containers\n probs = []\n targets = []\n obj_inds = []\n count = 0\n\n while True:\n try:\n\n # Run one step of the model\n t = [time.time()]\n ops = (self.prob_logits, model.labels, model.inputs['object_inds'])\n prob, labels, inds = self.sess.run(ops, {model.dropout_prob: 1.0})\n t += [time.time()]\n\n # Get probs and labels\n probs += [prob]\n targets += [labels]\n obj_inds += [inds]\n count += prob.shape[0]\n\n # Average timing\n t += [time.time()]\n mean_dt = 0.95 * mean_dt + 0.05 * (np.array(t[1:]) - np.array(t[:-1]))\n\n # Display\n if (t[-1] - last_display) > self.gap_display:\n last_display = t[-1]\n message = 'Vote {:.0f} : {:.1f}% (timings : {:4.2f} {:4.2f})'\n print(message.format(np.min(average_counts),\n 100 * count / dataset.num_test,\n 1000 * (mean_dt[0]),\n 1000 * (mean_dt[1])))\n\n except tf.errors.OutOfRangeError:\n break\n\n # Average votes\n # *************\n\n # Stack all validation predictions\n probs = np.vstack(probs)\n targets = np.hstack(targets)\n obj_inds = np.hstack(obj_inds)\n\n if np.any(dataset.input_labels['test'][obj_inds] != targets):\n raise ValueError('wrong object indices')\n\n # Compute incremental average (predictions are always ordered)\n average_counts[obj_inds] += 1\n average_probs[obj_inds] += (probs - average_probs[obj_inds]) / (average_counts[obj_inds])\n\n # Save/Display temporary results\n # ******************************\n\n test_labels = np.array(dataset.label_values)\n\n # Compute classification results\n C1 = confusion_matrix(dataset.input_labels['test'],\n np.argmax(average_probs, axis=1),\n test_labels)\n\n ACC = 100 * np.sum(np.diag(C1)) / (np.sum(C1) + 1e-6)\n print('Test Accuracy = {:.1f}%'.format(ACC))\n\n s = ''\n for cc in C1:\n for c in cc:\n s += '{:d} '.format(c)\n s += '\\n'\n print(s)\n\n\n\n # Initialise iterator with test data\n self.sess.run(dataset.test_init_op)\n\n return\n\n def test_multi_segmentation(self, model, dataset, num_votes=100, num_saves=10):\n\n ##################\n # Pre-computations\n ##################\n\n print('Preparing test structures')\n t1 = time.time()\n\n # Collect original test file names\n original_path = join(dataset.path, 'test_ply')\n test_names = [f[:-4] for f in listdir(original_path) if f[-4:] == '.ply']\n test_names = np.sort(test_names)\n\n original_labels = []\n original_points = []\n projection_inds = []\n for i, cloud_name in enumerate(test_names):\n\n # Read data in ply file\n data = read_ply(join(original_path, cloud_name + '.ply'))\n points = np.vstack((data['x'], -data['z'], data['y'])).T\n original_labels += [data['label'] - 1]\n original_points += [points]\n\n # Create tree structure to compute neighbors\n tree = KDTree(dataset.input_points['test'][i])\n projection_inds += [np.squeeze(tree.query(points, return_distance=False))]\n\n t2 = time.time()\n print('Done in {:.1f} s\\n'.format(t2 - t1))\n\n ##########\n # Initiate\n ##########\n\n # Test saving path\n if config.save_test:\n test_path = join(model.saving_path, 'test')\n if not exists(test_path):\n makedirs(test_path)\n else:\n test_path = None\n\n # Initialise iterator with test data\n self.sess.run(dataset.test_init_op)\n\n # Initiate result containers\n average_predictions = [np.zeros((1, 1), dtype=np.float32) for _ in test_names]\n\n #####################\n # Network predictions\n #####################\n\n mean_dt = np.zeros(2)\n last_display = time.time()\n for v in range(num_votes):\n\n # Run model on all test examples\n # ******************************\n\n # Initiate result containers\n all_predictions = []\n all_obj_inds = []\n\n while True:\n try:\n\n # Run one step of the model\n t = [time.time()]\n ops = (self.prob_logits,\n model.labels,\n model.inputs['super_labels'],\n model.inputs['object_inds'],\n model.inputs['in_batches'])\n preds, labels, obj_labels, o_inds, batches = self.sess.run(ops, {model.dropout_prob: 1.0})\n t += [time.time()]\n\n # Stack all predictions for each class separately\n max_ind = np.max(batches)\n for b_i, b in enumerate(batches):\n\n # Eliminate shadow indices\n b = b[b < max_ind - 0.5]\n\n # Get prediction (only for the concerned parts)\n obj = obj_labels[b[0]]\n predictions = preds[b][:, :config.num_classes[obj]]\n\n # Stack all results\n all_predictions += [predictions]\n all_obj_inds += [o_inds[b_i]]\n\n # Average timing\n t += [time.time()]\n mean_dt = 0.95 * mean_dt + 0.05 * (np.array(t[1:]) - np.array(t[:-1]))\n\n # Display\n if (t[-1] - last_display) > self.gap_display:\n last_display = t[-1]\n message = 'Vote {:d} : {:.1f}% (timings : {:4.2f} {:4.2f})'\n print(message.format(v,\n 100 * len(all_predictions) / dataset.num_test,\n 1000 * (mean_dt[0]),\n 1000 * (mean_dt[1])))\n\n except tf.errors.OutOfRangeError:\n break\n\n # Project predictions on original point clouds\n # ********************************************\n\n print('\\nGetting test confusions')\n t1 = time.time()\n\n for i, probs in enumerate(all_predictions):\n\n # Interpolate prediction from current positions to original points\n obj_i = all_obj_inds[i]\n proj_predictions = probs[projection_inds[obj_i]]\n\n # Average prediction across votes\n average_predictions[obj_i] = average_predictions[obj_i] + \\\n (proj_predictions - average_predictions[obj_i]) / (v + 1)\n\n Confs = []\n for obj_i, avg_probs in enumerate(average_predictions):\n\n # Compute confusion matrices\n parts = [j for j in range(avg_probs.shape[1])]\n Confs += [confusion_matrix(original_labels[obj_i], np.argmax(avg_probs, axis=1), parts)]\n\n\n t2 = time.time()\n print('Done in {:.1f} s\\n'.format(t2 - t1))\n\n # Save the best/worst segmentations per class\n # *******************************************\n\n print('Saving test examples')\n t1 = time.time()\n\n # Regroup confusions per object class\n Confs = np.array(Confs)\n obj_mIoUs = []\n for l in dataset.label_values:\n\n # Get confusions for this object\n obj_inds = np.where(dataset.input_labels['test'] == l)[0]\n obj_confs = np.stack(Confs[obj_inds])\n\n # Get IoU\n obj_IoUs = IoU_from_confusions(obj_confs)\n obj_mIoUs += [np.mean(obj_IoUs, axis=-1)]\n\n # Get X best and worst prediction\n order = np.argsort(obj_mIoUs[-1])\n worst_inds = obj_inds[order[:num_saves]]\n best_inds = obj_inds[order[:-num_saves-1:-1]]\n worst_IoUs = obj_IoUs[order[:num_saves]]\n best_IoUs = obj_IoUs[order[:-num_saves-1:-1]]\n\n # Save the names in a file\n if config.save_test:\n obj_path = join(test_path, dataset.label_to_names[l])\n if not exists(obj_path):\n makedirs(obj_path)\n worst_file = join(obj_path, 'worst_inds.txt')\n best_file = join(obj_path, 'best_inds.txt')\n with open(worst_file, \"w\") as text_file:\n for w_i, w_IoUs in zip(worst_inds, worst_IoUs):\n text_file.write('{:d} {:s} :'.format(w_i, test_names[w_i]))\n for IoU in w_IoUs:\n text_file.write(' {:.1f}'.format(100*IoU))\n text_file.write('\\n')\n\n with open(best_file, \"w\") as text_file:\n for b_i, b_IoUs in zip(best_inds, best_IoUs):\n text_file.write('{:d} {:s} :'.format(b_i, test_names[b_i]))\n for IoU in b_IoUs:\n text_file.write(' {:.1f}'.format(100*IoU))\n text_file.write('\\n')\n\n # Save the clouds\n for i, w_i in enumerate(worst_inds):\n filename = join(obj_path, 'worst_{:02d}.ply'.format(i+1))\n preds = np.argmax(average_predictions[w_i], axis=1).astype(np.int32)\n write_ply(filename,\n [original_points[w_i], original_labels[w_i], preds],\n ['x', 'y', 'z', 'gt', 'pre'])\n\n for i, b_i in enumerate(best_inds):\n filename = join(obj_path, 'best_{:02d}.ply'.format(i+1))\n preds = np.argmax(average_predictions[b_i], axis=1).astype(np.int32)\n write_ply(filename,\n [original_points[b_i], original_labels[b_i], preds],\n ['x', 'y', 'z', 'gt', 'pre'])\n\n t2 = time.time()\n print('Done in {:.1f} s\\n'.format(t2 - t1))\n\n # Display results\n # ***************\n\n objs_average = [np.mean(mIoUs) for mIoUs in obj_mIoUs]\n instance_average = np.mean(np.hstack(obj_mIoUs))\n class_average = np.mean(objs_average)\n\n print('Objs | Inst | Air Bag Cap Car Cha Ear Gui Kni Lam Lap Mot Mug Pis Roc Ska Tab')\n print('-----|------|--------------------------------------------------------------------------------')\n\n s = '{:4.1f} | {:4.1f} | '.format(100 * class_average, 100 * instance_average)\n for AmIoU in objs_average:\n s += '{:4.1f} '.format(100 * AmIoU)\n print(s + '\\n')\n\n # Initialise iterator with test data\n self.sess.run(dataset.test_init_op)\n\n return\n\n def test_vote_seg(self, sess, ops, dataset, model, num_votes=20, test_path=None, make_zip=True):\n\n config = self.config\n assert os.path.isdir(config.saving_path), f'not a dir: {config.saving_path}'\n if test_path is None:\n test_path = os.path.join(config.saving_path, 'test')\n os.makedirs(test_path, exist_ok=True)\n\n options = None # tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n run_metadata = None # tf.RunMetadata()\n feed_dict = {ops['is_training']: False}\n\n # Smoothing parameter for votes\n test_smooth = 0.98\n\n # Initialise iterator with test data\n sess.run(ops['test_init_op'])\n\n # Initiate global prediction over val clouds\n test_ops, cum_dict, extra_ops = self.initialize(ops, dataset, model, 'test')\n test_probs = cum_dict['prob']\n\n vote_ind = 0\n last_min = -0.5 \n if config.num_votes:\n num_votes = config.num_votes\n while last_min < num_votes:\n try:\n cur_rst = sess.run(test_ops, feed_dict=feed_dict, options=options, run_metadata=run_metadata)\n # Stack all test predictions for each class separately - iterate over each gpu & cloud\n self.cumulate_probs(dataset, model, cur_rst, cum_dict, task='seg', smooth=test_smooth)\n\n except tf.errors.OutOfRangeError:\n # NOTE: need to check\n new_min = np.min(dataset.min_potentials['test'])\n if self.verbose:\n print(f'Step {vote_ind:3d}, end. Min potential = {new_min:.1f}', flush=True)\n\n if last_min + 1 < new_min:\n # Update last_min\n last_min += 1\n\n # if int(last_min) > 0 and int(last_min) // 5 == 0: # periodic test results\n # self.project_test_predictions(dataset, test_path)\n\n sess.run(ops['test_init_op'])\n vote_ind += 1\n\n if self.verbose:\n new_min = np.min(dataset.min_potentials['test'])\n print(f'Step {vote_ind:3d}, end. Min potential = {new_min:.1f}', flush=True)\n\n self.project_test_predictions(dataset, test_probs, test_path)\n print('\\nfinished\\n', flush=True)\n\n if make_zip:\n zip_name = test_path.split(os.sep) # cfg name / Log_* / test_*\n zip_name = '_'.join([i for i in ['test', *zip_name[-3:-1], zip_name[-1][len('test'):].strip('_')] if i])\n # include test_* dir (except Semantic3D, ScanNet)\n j = 'j' if config.dataset in ['ScanNet', 'Semantic3D', 'SensatUrban'] else ''\n os.system(f'cd {os.path.dirname(test_path)}; zip -rmTq{j} {zip_name}.zip {test_path.split(os.sep)[-1]}/*') # -m to move, -j junk file, -T test integrity, -q quiet\n os.system(f'rm -r {test_path}')\n return\n\n def project_test_predictions(self, dataset, test_probs, test_path):\n\n # Project predictions\n t1 = time.time()\n files = dataset.test_files\n ignored_inds = None\n if hasattr(dataset, 'ignored_labels_test'):\n ignored_inds = dataset.label_to_idx[[l for l in dataset.ignored_labels_test if l not in dataset.ignored_labels]].astype(int)\n\n config = self.config\n if config.save_test:\n pred_path = os.sep.join([*test_path.split(os.sep)[:-1], test_path.split(os.sep)[-1].replace('test', 'predictions')]) # model pred\n os.makedirs(pred_path, exist_ok=True)\n\n for i_test, file_path in enumerate(files):\n\n # Reproject probs\n probs = test_probs[i_test][dataset.test_proj[i_test], :]\n\n # Remove invalid classes in test\n if ignored_inds is not None:\n probs[:, ignored_inds] = 0\n\n # Get the predicted labels\n preds = dataset.idx_to_label[np.argmax(probs, axis=-1)]\n\n # Save plys - predictions & probs\n cloud_name = file_path.split('/')[-1]\n if config.save_test:\n points = dataset.load_evaluation_points(file_path) # test original points\n pots = dataset.potentials['test'][i_test][dataset.test_proj[i_test]] # project potentials on original points\n test_name = os.path.join(pred_path, cloud_name)\n prob_names = ['_'.join(dataset.label_to_names[label].split()) for label in dataset.label_values if label not in dataset.ignored_labels]\n write_ply(test_name,\n [points, preds, pots, probs],\n ['x', 'y', 'z', 'preds', 'pots'] + prob_names)\n\n # Save ascii preds - submission files\n if config.dataset == 'Semantic3D':\n ascii_name = os.path.join(test_path, dataset.ascii_files[cloud_name])\n np.savetxt(ascii_name, preds, fmt='%d')\n elif config.dataset == 'SensatUrban':\n ascii_name = os.path.join(test_path, f'{cloud_name[:-4]}.label')\n preds.astype(np.uint8).tofile(ascii_name)\n else:\n ascii_name = os.path.join(test_path, cloud_name[:-4] + '.txt')\n np.savetxt(ascii_name, preds, fmt='%d')\n\n t2 = time.time()\n if self.verbose:\n print('\\nReproject Vote in {:.1f}s\\n'.format(t2-t1))\n\n\n # Utilities\n # ------------------------------------------------------------------------------------------------------------------\n\n def cumulate_probs(self, dataset, model, rst, cum_dict, task, smooth):\n # cum_dict - {cum_dict name : {args : rst_dict}}\n\n # iterate over gpu\n for gpu_i, cloud_inds in enumerate(rst['inputs']['cloud_inds']):\n point_inds = rst['inputs']['point_inds'][gpu_i]\n\n b_start = 0\n # iterate over clouds\n for b_i, c_i in enumerate(cloud_inds): # [B]\n if 'batches_len' in rst['inputs']: # [BxN] - stacked\n b_len = rst['inputs']['batches_len'][gpu_i][0][b_i] # npoints in cloud\n b_i = np.arange(b_start, b_start + b_len)\n b_start += b_len\n else: # [B, N] - batched\n pass\n inds = point_inds[b_i] # input point inds\n\n probs = rst[task]['probs'][gpu_i][b_i]\n labels = rst[task]['labels'][gpu_i][b_i]\n if np.all(labels == -1):\n # c_pts = np.array(dataset.input_trees['validation'][c_i].data, copy=False)[inds].mean(axis=0)\n # unique_l_cnt = np.unique(dataset.input_labels['validation'][c_i][inds], return_counts=True)\n # raise ValueError(f'all invalid labels found in cumulate_prob: cloud_inds={c_i}, center_pts={c_pts}'\n # f'input_labels & counts - {unique_l_cnt}')\n continue\n if 'conf' in cum_dict:\n cur_conf = confusion_matrix(labels, np.argmax(probs, axis=-1).astype(np.int), labels=np.arange(dataset.num_classes))\n cum_dict['conf'] += cur_conf\n if 'prob' in cum_dict:\n cum_dict['prob'][c_i][inds] = smooth * cum_dict['prob'][c_i][inds] + (1 - smooth) * probs\n if 'feature' in cum_dict:\n cum_dict['feature'][c_i][inds] = smooth * cum_dict['feature'][c_i][inds] + (1 - smooth) * rst[task]['latent'][gpu_i][b_i]\n\n def _search_func(self, k_r, cloud_idx, split, dataset, neighbor_dict, verbose=True): # create tf_ops of generating neighbor_idx & get result\n if cloud_idx in neighbor_dict[k_r]:\n return neighbor_dict[k_r][cloud_idx]\n\n config = self.config\n points = np.array(dataset.input_trees[split][cloud_idx].data, copy=False) # [N, 3]\n\n from ops import get_tf_func\n func = get_tf_func(config.search, verbose=verbose)\n\n if config.search in ['knn']:\n tf_ops = tf.squeeze(func(points[None, ...], points[None, ...], k_r), axis=0)\n elif config.search in ['radius']:\n tf_ops = func(points, points, [len(points)], [len(points)], k_r)\n # if hasattr(dataset, 'neighborhood_limits'):\n # print('neighborhood_limits', dataset.neighborhood_limits[0])\n # tf_ops = tf_ops[..., :dataset.neighborhood_limits[0]]\n else:\n raise\n\n if verbose:\n print_mem(f'k = {k_r} - start', check_time=True, check_sys=True, flush=True)\n with tf.Session(config=tf.ConfigProto(device_count={'GPU': 0}, allow_soft_placement=True)) as s:\n neighbor_idx = s.run(tf_ops)\n if verbose:\n print_mem(f'neighbor_idx {neighbor_idx.shape}', check_time=True, check_sys=True, flush=True)\n\n neighbor_dict[k_r][cloud_idx] = neighbor_idx # neighbor idx - np arr\n return neighbor_idx" }, { "identifier": "average_gradients", "path": "utils/average_gradients.py", "snippet": "def average_gradients(tower_grads, grad_norm, raise_on_none=True, grad_reduce=None, device=None):\n \"\"\"Calculate the average gradient for each shared variable across all towers.\n Note that this function provides a synchronization point across all towers.\n From tensorflow tutorial: cifar10/cifar10_multi_gpu_train.py\n Args:\n tower_grads: List of lists of (gradient, variable) tuples. The outer list\n is over individual gradients. The inner list is over the gradient\n calculation for each tower.\n - [[(g,v), ... at gpu 0], ..., [(g,v), ... at gpu N]]\n Returns:\n List of pairs of (gradient, variable) where the gradient has been averaged\n across all towers.\n \"\"\"\n if device:\n with tf.device(device):\n return average_gradients(tower_grads, grad_norm, raise_on_none, grad_reduce, None)\n\n use_clip = grad_norm and grad_norm > 0\n average_grads = []\n for grad_and_vars in zip(*tower_grads):\n # Note that each grad_and_vars containes (grad, var) calculated at each gpu, looks like the following:\n # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))\n grads = []\n for g, v in grad_and_vars:\n if g is not None:\n if use_clip:\n g = tf.clip_by_norm(g, grad_norm)\n elif raise_on_none:\n raise ValueError(f'variable {v} got None gradients')\n else:\n continue\n # g = tf.zeros_like(v)\n\n # Append on a 'tower' dimension which we will average over below.\n grads.append(g)\n\n # Average over the 'tower' dimension.\n if len(grads) > 1 and (grad_reduce == 'concat' or not grad_reduce):\n # Add 0 dimension to the gradients to represent the tower.\n # grad = tf.stack(grads)\n grads = [tf.expand_dims(g, 0) for g in grads]\n grad = tf.concat(axis=0, values=grads)\n grad = tf.reduce_mean(grad, 0)\n elif len(grads) > 1 and grad_reduce == 'mean':\n # Direct mean\n grad = tf.accumulate_n(grads) / len(grads)\n elif len(grads) == 1:\n # skip if only 1 gpu\n grad = grads[0]\n elif len(grads) == 0:\n grad = None\n else:\n raise ValueError(f'not support grad_reduce = {grad_reduce}')\n\n # Keep in mind that the Variables are redundant because they are shared\n # across towers. So .. we will just return the first tower's pointer to\n # the Variable.\n v = grad_and_vars[0][1]\n grad_and_var = (grad, v)\n average_grads.append(grad_and_var)\n return average_grads" }, { "identifier": "AdamWeightDecayOptimizer", "path": "utils/AdamWOptimizer.py", "snippet": "class AdamWeightDecayOptimizer(tf.train.Optimizer):\n \"\"\"A basic Adam optimizer that includes \"correct\" L2 weight decay.\"\"\"\n\n def __init__(self,\n learning_rate,\n weight_decay_rate=0.0,\n beta_1=0.9,\n beta_2=0.999,\n epsilon=1e-6,\n exclude_from_weight_decay=None,\n name=\"AdamWeightDecayOptimizer\"):\n \"\"\"Constructs a AdamWeightDecayOptimizer.\"\"\"\n super(AdamWeightDecayOptimizer, self).__init__(False, name)\n\n self.learning_rate = learning_rate\n self.weight_decay_rate = weight_decay_rate\n self.beta_1 = beta_1\n self.beta_2 = beta_2\n self.epsilon = epsilon\n self.exclude_from_weight_decay = exclude_from_weight_decay\n\n def apply_gradients(self, grads_and_vars, global_step=None, name=None):\n \"\"\"See base class.\"\"\"\n assignments = []\n for (grad, param) in grads_and_vars:\n if grad is None or param is None:\n continue\n\n param_name = self._get_variable_name(param.name)\n\n m = tf.get_variable(\n name=param_name + \"/adam_m\",\n shape=param.shape.as_list(),\n dtype=tf.float32,\n trainable=False,\n initializer=tf.zeros_initializer())\n v = tf.get_variable(\n name=param_name + \"/adam_v\",\n shape=param.shape.as_list(),\n dtype=tf.float32,\n trainable=False,\n initializer=tf.zeros_initializer())\n\n # Standard Adam update.\n next_m = (\n tf.multiply(self.beta_1, m) + tf.multiply(1.0 - self.beta_1, grad))\n next_v = (\n tf.multiply(self.beta_2, v) + tf.multiply(1.0 - self.beta_2,\n tf.square(grad)))\n\n update = next_m / (tf.sqrt(next_v) + self.epsilon)\n\n # Just adding the square of the weights to the loss function is *not*\n # the correct way of using L2 regularization/weight decay with Adam,\n # since that will interact with the m and v parameters in strange ways.\n #\n # Instead we want ot decay the weights in a manner that doesn't interact\n # with the m/v parameters. This is equivalent to adding the square\n # of the weights to the loss with plain (non-momentum) SGD.\n if self._do_use_weight_decay(param_name):\n update += self.weight_decay_rate * param\n\n update_with_lr = self.learning_rate * update\n\n next_param = param - update_with_lr\n\n assignments.extend(\n [param.assign(next_param),\n m.assign(next_m),\n v.assign(next_v)])\n return tf.group(*assignments, name=name)\n\n def _do_use_weight_decay(self, param_name):\n \"\"\"Whether to use L2 weight decay for `param_name`.\"\"\"\n if not self.weight_decay_rate:\n return False\n if self.exclude_from_weight_decay:\n for r in self.exclude_from_weight_decay:\n if re.search(r, param_name) is not None:\n return False\n return True\n\n def _get_variable_name(self, param_name):\n \"\"\"Get the variable name from the tensor name.\"\"\"\n m = re.match(\"^(.*):\\\\d+$\", param_name)\n if m is not None:\n param_name = m.group(1)\n return param_name" }, { "identifier": "setup_logger", "path": "utils/logger.py", "snippet": "@functools.lru_cache()\ndef setup_logger(\n output=None, distributed_rank=0, *, color=True, name=\"\", abbrev_name=None\n):\n \"\"\"\n Initialize the detectron2 logger and set its verbosity level to \"INFO\".\n\n Args:\n output (str): a file name or a directory to save log. If None, will not save log file.\n If ends with \".txt\" or \".log\", assumed to be a file name.\n Otherwise, logs will be saved to `output/log.txt`.\n name (str): the root module name of this logger\n\n Returns:\n logging.Logger: a logger\n \"\"\"\n logger = logging.getLogger(name) # a global named logger\n logger.setLevel(logging.DEBUG)\n logger.propagate = False\n\n if abbrev_name is None:\n abbrev_name = name\n\n plain_formatter = logging.Formatter(\n \"[%(asctime)s] %(name)s %(levelname)s: %(message)s\", datefmt=\"%m/%d %H:%M:%S\"\n )\n # stdout logging: master only\n if distributed_rank == 0:\n ch = logging.StreamHandler(stream=sys.stdout)\n ch.setLevel(logging.DEBUG)\n if color:\n formatter = _ColorfulFormatter(\n colored(\"[%(asctime)s %(name)s]: \", \"green\") + \"%(message)s\",\n datefmt=\"%m/%d %H:%M:%S\",\n root_name=name,\n abbrev_name=str(abbrev_name),\n )\n else:\n formatter = plain_formatter\n ch.setFormatter(formatter)\n logger.addHandler(ch)\n\n # file logging: all workers\n if output is not None:\n if output.endswith(\".txt\") or output.endswith(\".log\"):\n filename = output\n else:\n filename = os.path.join(output, \"log.txt\")\n if distributed_rank > 0:\n filename = filename + f\".rank{distributed_rank}\"\n os.makedirs(os.path.dirname(filename), exist_ok=True)\n\n fh = logging.StreamHandler(_cached_log_stream(filename))\n fh.setLevel(logging.DEBUG)\n fh.setFormatter(plain_formatter)\n logger.addHandler(fh)\n\n return logger" }, { "identifier": "StepScheduler", "path": "utils/scheduler.py", "snippet": "class StepScheduler(object):\n def __init__(self, name, base_value, decay_rate, decay_step, max_steps, clip_min=0):\n self.name = name\n self.clip_min = clip_min\n self.cur_step = 0\n self.values = [base_value * decay_rate ** (i // decay_step) for i in range(max_steps)]\n\n def reset(self):\n self.cur_step = 0\n\n def step(self):\n # cur_value = self.base_value * self.decay_rate ** (cur_step // decay_step)\n cur_value = max(self.values[self.cur_step], self.clip_min)\n self.cur_step += 1\n return cur_value" }, { "identifier": "LrScheduler", "path": "utils/scheduler.py", "snippet": "class LrScheduler(object):\n def __init__(self, config):\n self.config = config\n self.start_lr = float(config.learning_rate)\n self.clip_min = config.clip_min if config.clip_min else 0\n\n self.decay = config.decay\n if self.decay.startswith('cos'):\n self._get_lr = self._get_lr_cos\n\n self.reset()\n\n # from matplotlib import pyplot as plt\n # plt.plot(self.to_list(config.max_epoch))\n # plt.savefig(config.name)\n\n def reset(self):\n self.cur_ep = 0\n self.cur_step = 0\n self.learning_rate = None # None to denote not initalized\n self.learning_rate = self._get_lr()\n\n def _get_lr_cos(self):\n # simple implementation for cos annealing (epoch based)\n # borrowing from https://github.com/katsura-jp/pytorch-cosine-annealing-with-warmup/blob/master/cosine_annealing_warmup/scheduler.py\n # e.g. cos_w10, cos_w10_c3_m2_g.5\n cfg = self.config\n cur_ep = self.cur_ep\n total_ep = cfg.max_epoch\n max_lr = self.start_lr\n base_lr = self.clip_min if self.clip_min > 0 else 1e-5 # starting lr (min)\n\n warm_ep = re.search('w\\d+', self.decay)\n warm_ep = float(warm_ep.group()[1:]) if warm_ep else 0\n if 0 < warm_ep and warm_ep < 1:\n warm_ep = total_ep * warm_ep\n\n # solve cycle\n cycle_ep = re.search('c\\d+', self.decay)\n cycle_ep = int(cycle_ep.group()[1:]) if cycle_ep else 0 # total num of cycles\n cycle_m = re.search('m\\d+', self.decay)\n cycle_m = float(cycle_m.group()[1:]) if cycle_m else 1 # extending len per cycle\n if cycle_m > 1:\n assert cycle_ep > 0, f'#cycle must > 0'\n cycle_ep_base = total_ep * (cycle_m - 1) / (cycle_m ** cycle_ep - 1) # solving the first cycle len - sum of geometric sequence (等比求和)\n cycle_ep = [cycle_ep_base * cycle_m ** i for i in range(cycle_ep)]\n cycle_n = len([i for i in np.cumsum(cycle_ep) if i < cur_ep]) # num of cycles\n cycle_base = np.sum(cycle_ep[:cycle_n]) # start ep of current cycle\n cycle_ep = cycle_ep[cycle_n] # current cycle length\n elif cycle_ep:\n assert total_ep % cycle_ep == 0, f'#cycle={cycle_ep} does not align with #total={total_ep}'\n cycle_ep = total_ep / cycle_ep # length of each cycle - default to total_ep (1 cycle)\n cycle_n = int(cur_ep / cycle_ep)\n cycle_base = cycle_n * cycle_ep\n else:\n cycle_ep, cycle_n, cycle_base = total_ep, 0, 0\n cur_ep = cur_ep - cycle_base\n\n # modulate max lr\n gamma = [i[1:] for i in self.decay.split('_') if i.startswith('g')]\n gamma = float(gamma[0]) if gamma else 1\n max_lr = max_lr * gamma ** cycle_n\n\n if cur_ep < warm_ep:\n # warmup stage - linear increasing\n return cur_ep / warm_ep * (max_lr - base_lr) + base_lr\n else:\n # cos decay stage\n cur_ep = cur_ep - warm_ep\n cycle_ep = cycle_ep - warm_ep\n decay = (1 + np.cos(np.pi * cur_ep / cycle_ep)) / 2 # rescaled cos weight in [0, 1]\n return base_lr + (max_lr - base_lr) * decay\n\n def _get_lr(self):\n # exponential decay (default)\n cfg = self.config\n cur_ep = self.cur_ep\n base_lr = self.clip_min if self.clip_min > 0 else 1e-5\n\n warm_ep = re.search('w\\d+', self.decay)\n warm_ep = float(warm_ep.group()[1:]) if warm_ep else 0\n\n if cur_ep < warm_ep:\n # warmup stage - linear increasing\n return cur_ep / warm_ep * (self.start_lr - base_lr) + base_lr\n\n # normal decay\n cur_ep = cur_ep - warm_ep\n if cfg.decay_step:\n times = self.cur_step // cfg.decay_step if isinstance(cfg.decay_step, int) else (np.array(cfg.decay_step) <= self.cur_step).sum()\n else:\n decay_epoch = cfg.decay_epoch if cfg.decay_epoch else 1 # decay per epoch by default\n if isinstance(decay_epoch, (list, tuple)):\n assert all(i >= 1 for i in decay_epoch), f'need to specify as real epoch, not {decay_epoch}'\n times = cur_ep // decay_epoch if isinstance(decay_epoch, int) else (np.array(decay_epoch) <= cur_ep).sum()\n\n cum_decay = (cfg.decay_rate ** times) if type(cfg.decay_rate) in [int, float] else np.prod(cfg.decay_rate[:times]) # np.prod([]) = 1.0\n cur_lr = self.start_lr * cum_decay\n return cur_lr\n\n def to_list(self, max_epoch=None):\n lrs = []\n max_epoch = max_epoch if max_epoch is not None else self.config.max_epoch\n for i in range(max_epoch):\n self.cur_ep = i\n lrs.append(self._get_lr())\n self.learning_rate = lrs[-1]\n self.reset()\n return lrs\n\n def step(self, epoch, step):\n self.cur_ep += epoch\n self.cur_step += step\n cur_lr = max(self._get_lr(), self.clip_min)\n self.learning_rate = cur_lr\n return cur_lr\n\n def to_plot(self, max_epoch=None):\n lrs = []\n max_epoch = max_epoch if max_epoch is not None else self.config.max_epoch\n for i in range(max_epoch):\n self.cur_ep = i\n lrs.append(self._get_lr())\n self.learning_rate = lrs[-1]\n self.reset()\n import matplotlib.pyplot as plt\n plt.plot(lrs)\n plt.show()\n return " }, { "identifier": "AverageMeter", "path": "utils/metrics.py", "snippet": "class AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n \n @property\n def avg(self):\n return self.sum / self.count" }, { "identifier": "GraphBuilder", "path": "utils/tf_graph_builder.py", "snippet": "class GraphBuilder(object):\n\n def __init__(self, config, graph=None, verbose=True):\n \"\"\"\n get the full compute graph including dataset, model inference, loss, optimizer, lr scheduler and required ops\n \"\"\"\n\n if graph is not None: # if graph specified\n with graph.as_default():\n return self.__init__(config, None, verbose)\n\n if isinstance(config.rand_seed, int): # set seed\n tf.set_random_seed(config.rand_seed)\n np.random.seed(config.rand_seed)\n if verbose:\n print(f'==> np random seed = {np.random.get_state()[1][0]}')\n\n # model & dataset fn\n self.get_dataset = getattr(datasets, f'{config.dataset}Dataset') # datasets.[name]Dataset\n self.get_model = models.get_model\n # if config.distribute == 'tf_device': # full compute graph (handle devices & platforms)\n # self.build = self.build_devices\n # else:\n # raise NotImplementedError(f'not supported type of distributing graphs: config.distribute={config.distribute}')\n\n # Get dataset\n if verbose:\n print('==> Preparing datasets...')\n dataset = self.get_dataset(config, verbose)\n dataset.initialize(verbose)\n if verbose:\n print('==> setting dataset info:')\n print_dict(dataset.info, prefix='\\t')\n print_mem('>>> dataset built')\n config.update(dataset.info)\n\n # placeholder\n is_training = tf.placeholder(tf.bool, shape=())\n learning_rate = tf.placeholder(tf.float32, shape=(), name='learning_rate')\n # learning_rate = tf.get_variable('learning_rate', [], initializer=tf.constant_initializer(float('nan')), trainable=False)\n\n # # build model\n # grads, total_loss_dict, total_result_dict, model = self.build(dataset, is_training, config, verbose=verbose)\n\n # -------------------------------------------\n # Get model and loss on multiple GPU devices\n # -------------------------------------------\n # Allocating variables on CPU first will greatly accelerate multi-gpu training.\n # Ref: https://github.com/kuza55/keras-extras/issues/21\n flat_inputs = dataset.flat_inputs\n if config.cpu_variables:\n self.get_model(flat_inputs[0], is_training, config=config, verbose=verbose)\n tower_grads = []\n total_losses = []\n total_result = []\n for igpu in range(config.gpu_num):\n with tf.variable_scope(tf.get_variable_scope(), reuse=True if config.cpu_variables else tf.AUTO_REUSE):\n name_scope = f'gpu_{igpu}' if config.cpu_variables or igpu > 0 else ''\n verbose = not bool(name_scope)\n with tf.device(f'/gpu:{igpu}'), tf.name_scope(name_scope) as scope:\n flat_inputs_i = flat_inputs[igpu]\n model = self.get_model(flat_inputs_i, is_training, config=config, scope=scope, verbose=verbose) # inference model\n\n # collect per-gpu info\n result_dict = model.get_result() # inference result\n total_result.append(result_dict)\n\n loss_dict = model.get_loss() # loss\n total_losses.append(loss_dict)\n\n var_list = tf.trainable_variables() # vars & grads\n var_list = self.collect_vars(var_list, include_k=config.vars_train, except_k=config.vars_freeze)\n grads = tf.gradients(loss_dict['loss'], var_list, colocate_gradients_with_ops=config.colocate_gradients_with_ops) # normally, should NOT co-locate\n grads = list(zip(grads, var_list))\n tower_grads.append(grads)\n total_inputs = dict_list(flat_inputs)\n total_result = dict_list(total_result)\n total_losses = dict_list(total_losses)\n\n # average losses from multiple GPUs\n with tf.variable_scope('losses'):\n total_losses = {k: tf.reduce_mean(v, name=k) if len(v) > 1 else v[0] for k, v in total_losses.items()}\n\n # average grad\n with tf.variable_scope('gradients'):\n # [(gradient, variable), ...] - gradient averaged over gpu towers (if >1)\n grads = average_gradients(tower_grads, grad_norm=config.grad_norm, raise_on_none=config.grad_raise_none, grad_reduce=config.grad_reduce)\n\n # setup optimizer\n with tf.variable_scope('optimizer'):\n if config.optimizer == 'sgd':\n optimizer = tf.train.MomentumOptimizer(learning_rate, momentum=config.momentum)\n elif config.optimizer == 'adam':\n optimizer = tf.train.AdamOptimizer(learning_rate)\n elif config.optimizer == 'adamW':\n from utils.AdamWOptimizer import AdamWeightDecayOptimizer\n optimizer = AdamWeightDecayOptimizer(learning_rate=learning_rate, weight_decay_rate=config.weight_decay, exclude_from_weight_decay=[\"bias\"])\n\n # if config.mixed_precision:\n # optimizer = tf.train.experimental.enable_mixed_precision_graph_rewrite(optimizer)\n\n # momentume as update ops\n update_ops = self.get_momentum_update(model, config, total_inputs, total_result)\n for ops in update_ops: # add to collection\n tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, ops)\n\n # train op\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_op = optimizer.apply_gradients(grads)\n # train_op = optimizer.apply_gradients(grads)\n # train_op = tf.group([train_op, update_ops])\n\n # saver\n save_vars = None\n if config.save_compact:\n save_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='model')\n if isinstance(config.save_compact, bool):\n pass\n elif isinstance(config.save_compact, str) and config.save_compact == 'trained':\n vars_grads = {v: g for g, v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='model')}\n save_vars = [v for v in save_vars if v in vars_grads and vars_grads[v] is not None] # save only trained\n else:\n raise ValueError(f'not support save_compact={config.save_compact}')\n saver = tf.train.Saver(save_vars, max_to_keep=int(config.max_to_keep))\n\n # summary\n with tf.variable_scope('summary'):\n if config.summary and isinstance(config.summary, str):\n inputs = model.inputs\n if 'summary' not in inputs:\n inputs['summary'] = defaultdict(lambda: [])\n if config.summary == 'loss':\n inputs['summary']['per_step'] += [tf.summary.scalar(k, v) for k, v in total_losses.items()]\n # log grads - debug use\n # inputs = model.inputs\n # inputs['summary'] = defaultdict(lambda: [])\n # from models.utils import tf_Print\n # for i, (g, v) in enumerate(grads):\n # if config.summary:\n # inputs['summary']['per_step'] += [tf.summary.histogram(f'{v.name}/v', v)]\n # inputs['summary']['per_step'] += [tf.summary.histogram(f'{v.name}/g', g)]\n # if v.name in [\n # 'model/resnet_scene_segmentation_head/up_conv3/weights:0',\n # 'model/resnet_scene_segmentation_head/segmentation_head/weights:0',\n # ]:\n # print(f'print grad - {v.name}')\n # g = tf_Print(g, [f'grads - {v.name}', g])\n # grads[i] = (g, v)\n # input('\\nprint above grads')\n # summary - merge\n summary_dict = {} # {level : merged op}\n if config.summary:\n sum_levels = ['per_step', 'per_log', 'per_epoch']\n summary_ops = model.inputs['summary'] if 'summary' in model.inputs else {k: [] for k in sum_levels}\n assert all([k in sum_levels for k in summary_ops]), f'undesired keys in summary ops: {summary_ops.keys()}'\n for i in range(len(sum_levels)):\n lv = sum_levels[-i - 1]\n ops = sum([summary_ops[k] for k in sum_levels[:len(sum_levels)-i]], [])\n summary_dict[lv] = tf.summary.merge(ops) if len(ops) > 0 else tf.no_op()\n\n # Create a session\n cProto = tf.ConfigProto()\n if config.gpu_allow_growth:\n cProto.gpu_options.allow_growth = True\n if config.debug_single:\n cProto.device_count['CPU'] = 1\n # config.intra_op_parallelism_threads = config.inter_op_parallelism_threads = psutil.cpu_count(logical=False) # set to num of physical (default to logical) cpu cores\n cProto.allow_soft_placement = bool(config.allow_soft_placement) or not bool(config.gpu_devices) # if specified or cpu-only\n cProto.log_device_placement = False\n sess = tf.Session(config=cProto)\n\n ops = {\n 'train_init_op': dataset.train_init_op,\n 'val_init_op': dataset.val_init_op,\n 'test_init_op': dataset.test_init_op,\n\n 'train_op': train_op,\n 'is_training': is_training,\n 'learning_rate': learning_rate,\n\n 'inputs': dict(total_inputs),\n 'loss_dict': dict(total_losses),\n 'result_dict': dict(total_result),\n 'summary_dict': dict(summary_dict),\n }\n if verbose:\n print_mem('>>> model built')\n print('\\n -------- inputs {')\n print_dict(model.inputs, prefix='\\t')\n print('} --------- inputs')\n print('\\n -------- loss_dict {')\n print_dict(total_losses, prefix='\\t')\n print('} --------- loss_dict')\n print('\\n -------- result_dict {')\n print_dict(total_result, prefix='\\t')\n print('} --------- result_dict')\n\n self.ops = ops\n self.sess = sess\n self.grads = grads\n self.saver = saver\n\n self.model = model\n self.dataset = dataset\n\n # -------------------------------------------\n # Other utils & interfaces\n # -------------------------------------------\n\n def collect_vars(self, var_list, include_k=[], except_k=[], match='search'):\n # collect specified vars - default to all vars\n var_collect = []\n match_func = getattr(re, match)\n include_k = [include_k] if include_k and isinstance(include_k, str) else include_k\n except_k = [include_k] if except_k and isinstance(except_k, str) else except_k\n for v in var_list:\n if include_k and not any(match_func(k, v.name) for k in include_k):\n continue\n if except_k and any(match_func(k, v.name) for k in except_k):\n continue\n var_collect.append(v)\n return var_collect\n\n def get_momentum_update(self, model, config, total_inputs, total_result):\n # collect update ops for momentum update\n update_ops = []\n\n # update ops - momentum dict\n # NOTE - can be done in per-head fashion\n # => check only sepcial 'momentum_update_stage'\n for head_n, head_d in total_result.items():\n if 'momentum_dict' not in head_d or 'momentum_dict' not in total_inputs: continue\n if head_n not in total_inputs['momentum_dict']:\n raise KeyError(f'building momentum cycle for head {head_n}: missing tensor for momentum dict')\n head_cfg = model.head_dict['config'][head_n]\n\n # per-device input/output\n mom_in = total_inputs['momentum_dict'][head_n] # {k : [v = tensor]}, with inputs['momentum_dict'] = {head_n: {k : placeholder/vars}}\n mom_out = head_d['momentum_dict'] # {k: [v = tensor]}\n for k, v_out in mom_out.items():\n v_in = mom_in[k]\n\n # collect for update\n mom_avg = head_cfg.momentum_update\n mom_avg = float(mom_avg) if isinstance(mom_avg, (str, int)) else mom_avg # can be variable\n with tf.variable_scope(f'mom_dict_update/{head_n}/{k}'):\n if head_cfg.momentum_update_stage == 'glb_avg':\n # average over devices\n v_out = tf.reduce_mean(tf.stack(v_out, axis=0), axis=0)\n v_out = [v_in[i] * mom_avg + v_out * (1 - mom_avg) for i in range(config.gpu_num)]\n\n elif head_cfg.momentum_update_stage == 'glb_sum':\n # sum over devices\n v_out = tf.reduce_sum(tf.stack(v_out, axis=0), axis=0)\n v_out = [v_in[i] * mom_avg + v_out * (1 - mom_avg) for i in range(config.gpu_num)]\n\n # create update ops\n for igpu in range(config.gpu_num): # assign to each device input\n with tf.variable_scope(f'gpu_{igpu}/mom_dict_update/{head_n}/{k}', reuse=True):\n update_ops += [tf.assign(v_in[igpu], v_out[igpu])]\n\n return update_ops\n\n\n\n def restore(self, *args, **kwargs):\n argspec = inspect.getfullargspec(restore)\n kwargs.update(zip(argspec.args, args))\n kw_self = {'session': self.sess} # , 'saver': self.saver\n for k, v in kw_self.items():\n if k not in kwargs:\n kwargs[k] = v\n return restore(**kwargs)\n\n def close(self):\n self.sess.close()\n tf.reset_default_graph()" } ]
import os, re, gc, sys, time, pickle, psutil, subprocess import numpy as np import tensorflow as tf from config import log_config from utils.logger import print_dict, print_table from utils.ply import read_ply, write_ply from utils.tester import ModelTester from utils.average_gradients import average_gradients from utils.AdamWOptimizer import AdamWeightDecayOptimizer from utils.logger import setup_logger from utils.scheduler import StepScheduler, LrScheduler from utils.metrics import AverageMeter from utils.tf_graph_builder import GraphBuilder
17,484
if tf.__version__.split('.')[0] == '2': tf = tf.compat.v1 tf.disable_v2_behavior() # PLY reader FILE_DIR = os.path.abspath(__file__) BASE_DIR = os.path.dirname(FILE_DIR) ROOT_DIR = os.path.dirname(BASE_DIR) sys.path.insert(0, ROOT_DIR) sys.path.insert(0, BASE_DIR) sys.path.insert(0, os.path.join(ROOT_DIR, 'models')) sys.path.insert(0, os.path.join(ROOT_DIR, 'utils')) DEBUG = False class ModelTrainer: """ get & train the model (potential multi-gpu training) """ def __init__(self, config, verbose=True): self.config = config self.verbose = verbose self.tester = ModelTester(config, verbose=False) def add_summary(self, model): with tf.variable_scope('summary'): summary = model.summary log_content = self.config.log_content if 'var' in log_content: summary['per_log'] += [tf.summary.histogram(v.name, v) for g, v in gvs] if 'gard' in log_content: summary['per_log'] += [tf.summary.histogram(f'{v.name}_grad', g) for g, v in gvs] sum_levels = ['per_step', 'per_log', 'per_epoch'] assert all([k in sum_levels for k in summary.keys()]), f'undesired keys in summary dict: {str(summary.keys())}' for i in range(len(sum_levels)): summary[lv] = tf.summary.merge(summary[lv]) if summary[lv] else [tf.no_op] self.summary = summary return # Training main method # ------------------------------------------------------------------------------------------------------------------ def train(self): config = self.config with tf.Graph().as_default(): # use one graph # prepare compute graph g = GraphBuilder(config, verbose=self.verbose) ops, sess, grads, saver = g.ops, g.sess, g.grads, g.saver model, dataset = g.model, g.dataset self.model = model # printing model parameters if self.verbose: print('\n --------- printing grads {') re_list = ['.*bias:.*', '.*batch_normalization.*'] # skipping
if tf.__version__.split('.')[0] == '2': tf = tf.compat.v1 tf.disable_v2_behavior() # PLY reader FILE_DIR = os.path.abspath(__file__) BASE_DIR = os.path.dirname(FILE_DIR) ROOT_DIR = os.path.dirname(BASE_DIR) sys.path.insert(0, ROOT_DIR) sys.path.insert(0, BASE_DIR) sys.path.insert(0, os.path.join(ROOT_DIR, 'models')) sys.path.insert(0, os.path.join(ROOT_DIR, 'utils')) DEBUG = False class ModelTrainer: """ get & train the model (potential multi-gpu training) """ def __init__(self, config, verbose=True): self.config = config self.verbose = verbose self.tester = ModelTester(config, verbose=False) def add_summary(self, model): with tf.variable_scope('summary'): summary = model.summary log_content = self.config.log_content if 'var' in log_content: summary['per_log'] += [tf.summary.histogram(v.name, v) for g, v in gvs] if 'gard' in log_content: summary['per_log'] += [tf.summary.histogram(f'{v.name}_grad', g) for g, v in gvs] sum_levels = ['per_step', 'per_log', 'per_epoch'] assert all([k in sum_levels for k in summary.keys()]), f'undesired keys in summary dict: {str(summary.keys())}' for i in range(len(sum_levels)): summary[lv] = tf.summary.merge(summary[lv]) if summary[lv] else [tf.no_op] self.summary = summary return # Training main method # ------------------------------------------------------------------------------------------------------------------ def train(self): config = self.config with tf.Graph().as_default(): # use one graph # prepare compute graph g = GraphBuilder(config, verbose=self.verbose) ops, sess, grads, saver = g.ops, g.sess, g.grads, g.saver model, dataset = g.model, g.dataset self.model = model # printing model parameters if self.verbose: print('\n --------- printing grads {') re_list = ['.*bias:.*', '.*batch_normalization.*'] # skipping
print_table([(v.name, g) for g, v in grads if not any([bool(re.fullmatch(expr, v.name)) for expr in re_list])], prefix='\t')
2
2023-10-13 08:03:07+00:00
24k
bilibini/Lovely_Image_Downloader
py/Python38/site-packages/urllib3/poolmanager.py
[ { "identifier": "HTTPHeaderDict", "path": "py/Python38/site-packages/urllib3/_collections.py", "snippet": "class HTTPHeaderDict(typing.MutableMapping[str, str]):\n \"\"\"\n :param headers:\n An iterable of field-value pairs. Must not contain multiple field names\n when compared case-insensitively.\n\n :param kwargs:\n Additional field-value pairs to pass in to ``dict.update``.\n\n A ``dict`` like container for storing HTTP Headers.\n\n Field names are stored and compared case-insensitively in compliance with\n RFC 7230. Iteration provides the first case-sensitive key seen for each\n case-insensitive pair.\n\n Using ``__setitem__`` syntax overwrites fields that compare equal\n case-insensitively in order to maintain ``dict``'s api. For fields that\n compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``\n in a loop.\n\n If multiple fields that are equal case-insensitively are passed to the\n constructor or ``.update``, the behavior is undefined and some will be\n lost.\n\n >>> headers = HTTPHeaderDict()\n >>> headers.add('Set-Cookie', 'foo=bar')\n >>> headers.add('set-cookie', 'baz=quxx')\n >>> headers['content-length'] = '7'\n >>> headers['SET-cookie']\n 'foo=bar, baz=quxx'\n >>> headers['Content-Length']\n '7'\n \"\"\"\n\n _container: typing.MutableMapping[str, list[str]]\n\n def __init__(self, headers: ValidHTTPHeaderSource | None = None, **kwargs: str):\n super().__init__()\n self._container = {} # 'dict' is insert-ordered in Python 3.7+\n if headers is not None:\n if isinstance(headers, HTTPHeaderDict):\n self._copy_from(headers)\n else:\n self.extend(headers)\n if kwargs:\n self.extend(kwargs)\n\n def __setitem__(self, key: str, val: str) -> None:\n # avoid a bytes/str comparison by decoding before httplib\n if isinstance(key, bytes):\n key = key.decode(\"latin-1\")\n self._container[key.lower()] = [key, val]\n\n def __getitem__(self, key: str) -> str:\n val = self._container[key.lower()]\n return \", \".join(val[1:])\n\n def __delitem__(self, key: str) -> None:\n del self._container[key.lower()]\n\n def __contains__(self, key: object) -> bool:\n if isinstance(key, str):\n return key.lower() in self._container\n return False\n\n def setdefault(self, key: str, default: str = \"\") -> str:\n return super().setdefault(key, default)\n\n def __eq__(self, other: object) -> bool:\n maybe_constructable = ensure_can_construct_http_header_dict(other)\n if maybe_constructable is None:\n return False\n else:\n other_as_http_header_dict = type(self)(maybe_constructable)\n\n return {k.lower(): v for k, v in self.itermerged()} == {\n k.lower(): v for k, v in other_as_http_header_dict.itermerged()\n }\n\n def __ne__(self, other: object) -> bool:\n return not self.__eq__(other)\n\n def __len__(self) -> int:\n return len(self._container)\n\n def __iter__(self) -> typing.Iterator[str]:\n # Only provide the originally cased names\n for vals in self._container.values():\n yield vals[0]\n\n def discard(self, key: str) -> None:\n try:\n del self[key]\n except KeyError:\n pass\n\n def add(self, key: str, val: str, *, combine: bool = False) -> None:\n \"\"\"Adds a (name, value) pair, doesn't overwrite the value if it already\n exists.\n\n If this is called with combine=True, instead of adding a new header value\n as a distinct item during iteration, this will instead append the value to\n any existing header value with a comma. If no existing header value exists\n for the key, then the value will simply be added, ignoring the combine parameter.\n\n >>> headers = HTTPHeaderDict(foo='bar')\n >>> headers.add('Foo', 'baz')\n >>> headers['foo']\n 'bar, baz'\n >>> list(headers.items())\n [('foo', 'bar'), ('foo', 'baz')]\n >>> headers.add('foo', 'quz', combine=True)\n >>> list(headers.items())\n [('foo', 'bar, baz, quz')]\n \"\"\"\n # avoid a bytes/str comparison by decoding before httplib\n if isinstance(key, bytes):\n key = key.decode(\"latin-1\")\n key_lower = key.lower()\n new_vals = [key, val]\n # Keep the common case aka no item present as fast as possible\n vals = self._container.setdefault(key_lower, new_vals)\n if new_vals is not vals:\n # if there are values here, then there is at least the initial\n # key/value pair\n assert len(vals) >= 2\n if combine:\n vals[-1] = vals[-1] + \", \" + val\n else:\n vals.append(val)\n\n def extend(self, *args: ValidHTTPHeaderSource, **kwargs: str) -> None:\n \"\"\"Generic import function for any type of header-like object.\n Adapted version of MutableMapping.update in order to insert items\n with self.add instead of self.__setitem__\n \"\"\"\n if len(args) > 1:\n raise TypeError(\n f\"extend() takes at most 1 positional arguments ({len(args)} given)\"\n )\n other = args[0] if len(args) >= 1 else ()\n\n if isinstance(other, HTTPHeaderDict):\n for key, val in other.iteritems():\n self.add(key, val)\n elif isinstance(other, typing.Mapping):\n for key, val in other.items():\n self.add(key, val)\n elif isinstance(other, typing.Iterable):\n other = typing.cast(typing.Iterable[typing.Tuple[str, str]], other)\n for key, value in other:\n self.add(key, value)\n elif hasattr(other, \"keys\") and hasattr(other, \"__getitem__\"):\n # THIS IS NOT A TYPESAFE BRANCH\n # In this branch, the object has a `keys` attr but is not a Mapping or any of\n # the other types indicated in the method signature. We do some stuff with\n # it as though it partially implements the Mapping interface, but we're not\n # doing that stuff safely AT ALL.\n for key in other.keys():\n self.add(key, other[key])\n\n for key, value in kwargs.items():\n self.add(key, value)\n\n @typing.overload\n def getlist(self, key: str) -> list[str]:\n ...\n\n @typing.overload\n def getlist(self, key: str, default: _DT) -> list[str] | _DT:\n ...\n\n def getlist(\n self, key: str, default: _Sentinel | _DT = _Sentinel.not_passed\n ) -> list[str] | _DT:\n \"\"\"Returns a list of all the values for the named field. Returns an\n empty list if the key doesn't exist.\"\"\"\n try:\n vals = self._container[key.lower()]\n except KeyError:\n if default is _Sentinel.not_passed:\n # _DT is unbound; empty list is instance of List[str]\n return []\n # _DT is bound; default is instance of _DT\n return default\n else:\n # _DT may or may not be bound; vals[1:] is instance of List[str], which\n # meets our external interface requirement of `Union[List[str], _DT]`.\n return vals[1:]\n\n def _prepare_for_method_change(self) -> Self:\n \"\"\"\n Remove content-specific header fields before changing the request\n method to GET or HEAD according to RFC 9110, Section 15.4.\n \"\"\"\n content_specific_headers = [\n \"Content-Encoding\",\n \"Content-Language\",\n \"Content-Location\",\n \"Content-Type\",\n \"Content-Length\",\n \"Digest\",\n \"Last-Modified\",\n ]\n for header in content_specific_headers:\n self.discard(header)\n return self\n\n # Backwards compatibility for httplib\n getheaders = getlist\n getallmatchingheaders = getlist\n iget = getlist\n\n # Backwards compatibility for http.cookiejar\n get_all = getlist\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}({dict(self.itermerged())})\"\n\n def _copy_from(self, other: HTTPHeaderDict) -> None:\n for key in other:\n val = other.getlist(key)\n self._container[key.lower()] = [key, *val]\n\n def copy(self) -> HTTPHeaderDict:\n clone = type(self)()\n clone._copy_from(self)\n return clone\n\n def iteritems(self) -> typing.Iterator[tuple[str, str]]:\n \"\"\"Iterate over all header lines, including duplicate ones.\"\"\"\n for key in self:\n vals = self._container[key.lower()]\n for val in vals[1:]:\n yield vals[0], val\n\n def itermerged(self) -> typing.Iterator[tuple[str, str]]:\n \"\"\"Iterate over all headers, merging duplicate ones together.\"\"\"\n for key in self:\n val = self._container[key.lower()]\n yield val[0], \", \".join(val[1:])\n\n def items(self) -> HTTPHeaderDictItemView: # type: ignore[override]\n return HTTPHeaderDictItemView(self)\n\n def _has_value_for_header(self, header_name: str, potential_value: str) -> bool:\n if header_name in self:\n return potential_value in self._container[header_name.lower()][1:]\n return False\n\n def __ior__(self, other: object) -> HTTPHeaderDict:\n # Supports extending a header dict in-place using operator |=\n # combining items with add instead of __setitem__\n maybe_constructable = ensure_can_construct_http_header_dict(other)\n if maybe_constructable is None:\n return NotImplemented\n self.extend(maybe_constructable)\n return self\n\n def __or__(self, other: object) -> HTTPHeaderDict:\n # Supports merging header dicts using operator |\n # combining items with add instead of __setitem__\n maybe_constructable = ensure_can_construct_http_header_dict(other)\n if maybe_constructable is None:\n return NotImplemented\n result = self.copy()\n result.extend(maybe_constructable)\n return result\n\n def __ror__(self, other: object) -> HTTPHeaderDict:\n # Supports merging header dicts using operator | when other is on left side\n # combining items with add instead of __setitem__\n maybe_constructable = ensure_can_construct_http_header_dict(other)\n if maybe_constructable is None:\n return NotImplemented\n result = type(self)(maybe_constructable)\n result.extend(self)\n return result" }, { "identifier": "RecentlyUsedContainer", "path": "py/Python38/site-packages/urllib3/_collections.py", "snippet": "class RecentlyUsedContainer(typing.Generic[_KT, _VT], typing.MutableMapping[_KT, _VT]):\n \"\"\"\n Provides a thread-safe dict-like container which maintains up to\n ``maxsize`` keys while throwing away the least-recently-used keys beyond\n ``maxsize``.\n\n :param maxsize:\n Maximum number of recent elements to retain.\n\n :param dispose_func:\n Every time an item is evicted from the container,\n ``dispose_func(value)`` is called. Callback which will get called\n \"\"\"\n\n _container: typing.OrderedDict[_KT, _VT]\n _maxsize: int\n dispose_func: typing.Callable[[_VT], None] | None\n lock: RLock\n\n def __init__(\n self,\n maxsize: int = 10,\n dispose_func: typing.Callable[[_VT], None] | None = None,\n ) -> None:\n super().__init__()\n self._maxsize = maxsize\n self.dispose_func = dispose_func\n self._container = OrderedDict()\n self.lock = RLock()\n\n def __getitem__(self, key: _KT) -> _VT:\n # Re-insert the item, moving it to the end of the eviction line.\n with self.lock:\n item = self._container.pop(key)\n self._container[key] = item\n return item\n\n def __setitem__(self, key: _KT, value: _VT) -> None:\n evicted_item = None\n with self.lock:\n # Possibly evict the existing value of 'key'\n try:\n # If the key exists, we'll overwrite it, which won't change the\n # size of the pool. Because accessing a key should move it to\n # the end of the eviction line, we pop it out first.\n evicted_item = key, self._container.pop(key)\n self._container[key] = value\n except KeyError:\n # When the key does not exist, we insert the value first so that\n # evicting works in all cases, including when self._maxsize is 0\n self._container[key] = value\n if len(self._container) > self._maxsize:\n # If we didn't evict an existing value, and we've hit our maximum\n # size, then we have to evict the least recently used item from\n # the beginning of the container.\n evicted_item = self._container.popitem(last=False)\n\n # After releasing the lock on the pool, dispose of any evicted value.\n if evicted_item is not None and self.dispose_func:\n _, evicted_value = evicted_item\n self.dispose_func(evicted_value)\n\n def __delitem__(self, key: _KT) -> None:\n with self.lock:\n value = self._container.pop(key)\n\n if self.dispose_func:\n self.dispose_func(value)\n\n def __len__(self) -> int:\n with self.lock:\n return len(self._container)\n\n def __iter__(self) -> typing.NoReturn:\n raise NotImplementedError(\n \"Iteration over this class is unlikely to be threadsafe.\"\n )\n\n def clear(self) -> None:\n with self.lock:\n # Copy pointers to all values, then wipe the mapping\n values = list(self._container.values())\n self._container.clear()\n\n if self.dispose_func:\n for value in values:\n self.dispose_func(value)\n\n def keys(self) -> set[_KT]: # type: ignore[override]\n with self.lock:\n return set(self._container.keys())" }, { "identifier": "RequestMethods", "path": "py/Python38/site-packages/urllib3/_request_methods.py", "snippet": "class RequestMethods:\n \"\"\"\n Convenience mixin for classes who implement a :meth:`urlopen` method, such\n as :class:`urllib3.HTTPConnectionPool` and\n :class:`urllib3.PoolManager`.\n\n Provides behavior for making common types of HTTP request methods and\n decides which type of request field encoding to use.\n\n Specifically,\n\n :meth:`.request_encode_url` is for sending requests whose fields are\n encoded in the URL (such as GET, HEAD, DELETE).\n\n :meth:`.request_encode_body` is for sending requests whose fields are\n encoded in the *body* of the request using multipart or www-form-urlencoded\n (such as for POST, PUT, PATCH).\n\n :meth:`.request` is for making any kind of request, it will look up the\n appropriate encoding format and use one of the above two methods to make\n the request.\n\n Initializer parameters:\n\n :param headers:\n Headers to include with all requests, unless other headers are given\n explicitly.\n \"\"\"\n\n _encode_url_methods = {\"DELETE\", \"GET\", \"HEAD\", \"OPTIONS\"}\n\n def __init__(self, headers: typing.Mapping[str, str] | None = None) -> None:\n self.headers = headers or {}\n\n def urlopen(\n self,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n headers: typing.Mapping[str, str] | None = None,\n encode_multipart: bool = True,\n multipart_boundary: str | None = None,\n **kw: typing.Any,\n ) -> BaseHTTPResponse: # Abstract\n raise NotImplementedError(\n \"Classes extending RequestMethods must implement \"\n \"their own ``urlopen`` method.\"\n )\n\n def request(\n self,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n fields: _TYPE_FIELDS | None = None,\n headers: typing.Mapping[str, str] | None = None,\n json: typing.Any | None = None,\n **urlopen_kw: typing.Any,\n ) -> BaseHTTPResponse:\n \"\"\"\n Make a request using :meth:`urlopen` with the appropriate encoding of\n ``fields`` based on the ``method`` used.\n\n This is a convenience method that requires the least amount of manual\n effort. It can be used in most situations, while still having the\n option to drop down to more specific methods when necessary, such as\n :meth:`request_encode_url`, :meth:`request_encode_body`,\n or even the lowest level :meth:`urlopen`.\n \"\"\"\n method = method.upper()\n\n if json is not None and body is not None:\n raise TypeError(\n \"request got values for both 'body' and 'json' parameters which are mutually exclusive\"\n )\n\n if json is not None:\n if headers is None:\n headers = self.headers.copy() # type: ignore\n if not (\"content-type\" in map(str.lower, headers.keys())):\n headers[\"Content-Type\"] = \"application/json\" # type: ignore\n\n body = _json.dumps(json, separators=(\",\", \":\"), ensure_ascii=False).encode(\n \"utf-8\"\n )\n\n if body is not None:\n urlopen_kw[\"body\"] = body\n\n if method in self._encode_url_methods:\n return self.request_encode_url(\n method,\n url,\n fields=fields, # type: ignore[arg-type]\n headers=headers,\n **urlopen_kw,\n )\n else:\n return self.request_encode_body(\n method, url, fields=fields, headers=headers, **urlopen_kw\n )\n\n def request_encode_url(\n self,\n method: str,\n url: str,\n fields: _TYPE_ENCODE_URL_FIELDS | None = None,\n headers: typing.Mapping[str, str] | None = None,\n **urlopen_kw: str,\n ) -> BaseHTTPResponse:\n \"\"\"\n Make a request using :meth:`urlopen` with the ``fields`` encoded in\n the url. This is useful for request methods like GET, HEAD, DELETE, etc.\n \"\"\"\n if headers is None:\n headers = self.headers\n\n extra_kw: dict[str, typing.Any] = {\"headers\": headers}\n extra_kw.update(urlopen_kw)\n\n if fields:\n url += \"?\" + urlencode(fields)\n\n return self.urlopen(method, url, **extra_kw)\n\n def request_encode_body(\n self,\n method: str,\n url: str,\n fields: _TYPE_FIELDS | None = None,\n headers: typing.Mapping[str, str] | None = None,\n encode_multipart: bool = True,\n multipart_boundary: str | None = None,\n **urlopen_kw: str,\n ) -> BaseHTTPResponse:\n \"\"\"\n Make a request using :meth:`urlopen` with the ``fields`` encoded in\n the body. This is useful for request methods like POST, PUT, PATCH, etc.\n\n When ``encode_multipart=True`` (default), then\n :func:`urllib3.encode_multipart_formdata` is used to encode\n the payload with the appropriate content type. Otherwise\n :func:`urllib.parse.urlencode` is used with the\n 'application/x-www-form-urlencoded' content type.\n\n Multipart encoding must be used when posting files, and it's reasonably\n safe to use it in other times too. However, it may break request\n signing, such as with OAuth.\n\n Supports an optional ``fields`` parameter of key/value strings AND\n key/filetuple. A filetuple is a (filename, data, MIME type) tuple where\n the MIME type is optional. For example::\n\n fields = {\n 'foo': 'bar',\n 'fakefile': ('foofile.txt', 'contents of foofile'),\n 'realfile': ('barfile.txt', open('realfile').read()),\n 'typedfile': ('bazfile.bin', open('bazfile').read(),\n 'image/jpeg'),\n 'nonamefile': 'contents of nonamefile field',\n }\n\n When uploading a file, providing a filename (the first parameter of the\n tuple) is optional but recommended to best mimic behavior of browsers.\n\n Note that if ``headers`` are supplied, the 'Content-Type' header will\n be overwritten because it depends on the dynamic random boundary string\n which is used to compose the body of the request. The random boundary\n string can be explicitly set with the ``multipart_boundary`` parameter.\n \"\"\"\n if headers is None:\n headers = self.headers\n\n extra_kw: dict[str, typing.Any] = {\"headers\": HTTPHeaderDict(headers)}\n body: bytes | str\n\n if fields:\n if \"body\" in urlopen_kw:\n raise TypeError(\n \"request got values for both 'fields' and 'body', can only specify one.\"\n )\n\n if encode_multipart:\n body, content_type = encode_multipart_formdata(\n fields, boundary=multipart_boundary\n )\n else:\n body, content_type = (\n urlencode(fields), # type: ignore[arg-type]\n \"application/x-www-form-urlencoded\",\n )\n\n extra_kw[\"body\"] = body\n extra_kw[\"headers\"].setdefault(\"Content-Type\", content_type)\n\n extra_kw.update(urlopen_kw)\n\n return self.urlopen(method, url, **extra_kw)" }, { "identifier": "ProxyConfig", "path": "py/Python38/site-packages/urllib3/connection.py", "snippet": " class BaseSSLError(BaseException): # type: ignore[no-redef]\nclass HTTPConnection(_HTTPConnection):\nclass HTTPSConnection(HTTPConnection):\nclass _WrappedAndVerifiedSocket(typing.NamedTuple):\nclass DummyConnection:\nRECENT_DATE = datetime.date(2022, 1, 1)\n_CONTAINS_CONTROL_CHAR_RE = re.compile(r\"[^-!#$%&'*+.^_`|~0-9a-zA-Z]\")\n_HAS_SYS_AUDIT = hasattr(sys, \"audit\")\n def __init__(\n self,\n host: str,\n port: int | None = None,\n *,\n timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n source_address: tuple[str, int] | None = None,\n blocksize: int = 16384,\n socket_options: None\n | (connection._TYPE_SOCKET_OPTIONS) = default_socket_options,\n proxy: Url | None = None,\n proxy_config: ProxyConfig | None = None,\n ) -> None:\n def host(self) -> str:\n def host(self, value: str) -> None:\n def _new_conn(self) -> socket.socket:\n def set_tunnel(\n self,\n host: str,\n port: int | None = None,\n headers: typing.Mapping[str, str] | None = None,\n scheme: str = \"http\",\n ) -> None:\n def connect(self) -> None:\n def is_closed(self) -> bool:\n def is_connected(self) -> bool:\n def has_connected_to_proxy(self) -> bool:\n def close(self) -> None:\n def putrequest(\n self,\n method: str,\n url: str,\n skip_host: bool = False,\n skip_accept_encoding: bool = False,\n ) -> None:\n def putheader(self, header: str, *values: str) -> None:\n def request( # type: ignore[override]\n self,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n headers: typing.Mapping[str, str] | None = None,\n *,\n chunked: bool = False,\n preload_content: bool = True,\n decode_content: bool = True,\n enforce_content_length: bool = True,\n ) -> None:\n def request_chunked(\n self,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n headers: typing.Mapping[str, str] | None = None,\n ) -> None:\n def getresponse( # type: ignore[override]\n self,\n ) -> HTTPResponse:\n def __init__(\n self,\n host: str,\n port: int | None = None,\n *,\n timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n source_address: tuple[str, int] | None = None,\n blocksize: int = 16384,\n socket_options: None\n | (connection._TYPE_SOCKET_OPTIONS) = HTTPConnection.default_socket_options,\n proxy: Url | None = None,\n proxy_config: ProxyConfig | None = None,\n cert_reqs: int | str | None = None,\n assert_hostname: None | str | Literal[False] = None,\n assert_fingerprint: str | None = None,\n server_hostname: str | None = None,\n ssl_context: ssl.SSLContext | None = None,\n ca_certs: str | None = None,\n ca_cert_dir: str | None = None,\n ca_cert_data: None | str | bytes = None,\n ssl_minimum_version: int | None = None,\n ssl_maximum_version: int | None = None,\n ssl_version: int | str | None = None, # Deprecated\n cert_file: str | None = None,\n key_file: str | None = None,\n key_password: str | None = None,\n ) -> None:\n def set_cert(\n self,\n key_file: str | None = None,\n cert_file: str | None = None,\n cert_reqs: int | str | None = None,\n key_password: str | None = None,\n ca_certs: str | None = None,\n assert_hostname: None | str | Literal[False] = None,\n assert_fingerprint: str | None = None,\n ca_cert_dir: str | None = None,\n ca_cert_data: None | str | bytes = None,\n ) -> None:\n def connect(self) -> None:\n def _connect_tls_proxy(self, hostname: str, sock: socket.socket) -> ssl.SSLSocket:\ndef _ssl_wrap_socket_and_match_hostname(\n sock: socket.socket,\n *,\n cert_reqs: None | str | int,\n ssl_version: None | str | int,\n ssl_minimum_version: int | None,\n ssl_maximum_version: int | None,\n cert_file: str | None,\n key_file: str | None,\n key_password: str | None,\n ca_certs: str | None,\n ca_cert_dir: str | None,\n ca_cert_data: None | str | bytes,\n assert_hostname: None | str | Literal[False],\n assert_fingerprint: str | None,\n server_hostname: str | None,\n ssl_context: ssl.SSLContext | None,\n tls_in_tls: bool = False,\n) -> _WrappedAndVerifiedSocket:\ndef _match_hostname(\n cert: _TYPE_PEER_CERT_RET_DICT | None,\n asserted_hostname: str,\n hostname_checks_common_name: bool = False,\n) -> None:\ndef _wrap_proxy_error(err: Exception, proxy_scheme: str | None) -> ProxyError:\ndef _get_default_user_agent() -> str:\ndef _url_from_connection(\n conn: HTTPConnection | HTTPSConnection, path: str | None = None\n) -> str:" }, { "identifier": "HTTPConnectionPool", "path": "py/Python38/site-packages/urllib3/connectionpool.py", "snippet": "_TYPE_TIMEOUT = typing.Union[Timeout, float, _TYPE_DEFAULT, None]\nclass ConnectionPool:\nclass HTTPConnectionPool(ConnectionPool, RequestMethods):\nclass HTTPSConnectionPool(HTTPConnectionPool):\n def __init__(self, host: str, port: int | None = None) -> None:\n def __str__(self) -> str:\n def __enter__(self: _SelfT) -> _SelfT:\n def __exit__(\n self,\n exc_type: type[BaseException] | None,\n exc_val: BaseException | None,\n exc_tb: TracebackType | None,\n ) -> Literal[False]:\n def close(self) -> None:\n def __init__(\n self,\n host: str,\n port: int | None = None,\n timeout: _TYPE_TIMEOUT | None = _DEFAULT_TIMEOUT,\n maxsize: int = 1,\n block: bool = False,\n headers: typing.Mapping[str, str] | None = None,\n retries: Retry | bool | int | None = None,\n _proxy: Url | None = None,\n _proxy_headers: typing.Mapping[str, str] | None = None,\n _proxy_config: ProxyConfig | None = None,\n **conn_kw: typing.Any,\n ):\n def _new_conn(self) -> BaseHTTPConnection:\n def _get_conn(self, timeout: float | None = None) -> BaseHTTPConnection:\n def _put_conn(self, conn: BaseHTTPConnection | None) -> None:\n def _validate_conn(self, conn: BaseHTTPConnection) -> None:\n def _prepare_proxy(self, conn: BaseHTTPConnection) -> None:\n def _get_timeout(self, timeout: _TYPE_TIMEOUT) -> Timeout:\n def _raise_timeout(\n self,\n err: BaseSSLError | OSError | SocketTimeout,\n url: str,\n timeout_value: _TYPE_TIMEOUT | None,\n ) -> None:\n def _make_request(\n self,\n conn: BaseHTTPConnection,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n headers: typing.Mapping[str, str] | None = None,\n retries: Retry | None = None,\n timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n chunked: bool = False,\n response_conn: BaseHTTPConnection | None = None,\n preload_content: bool = True,\n decode_content: bool = True,\n enforce_content_length: bool = True,\n ) -> BaseHTTPResponse:\n def close(self) -> None:\n def is_same_host(self, url: str) -> bool:\n def urlopen( # type: ignore[override]\n self,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n headers: typing.Mapping[str, str] | None = None,\n retries: Retry | bool | int | None = None,\n redirect: bool = True,\n assert_same_host: bool = True,\n timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n pool_timeout: int | None = None,\n release_conn: bool | None = None,\n chunked: bool = False,\n body_pos: _TYPE_BODY_POSITION | None = None,\n preload_content: bool = True,\n decode_content: bool = True,\n **response_kw: typing.Any,\n ) -> BaseHTTPResponse:\n def __init__(\n self,\n host: str,\n port: int | None = None,\n timeout: _TYPE_TIMEOUT | None = _DEFAULT_TIMEOUT,\n maxsize: int = 1,\n block: bool = False,\n headers: typing.Mapping[str, str] | None = None,\n retries: Retry | bool | int | None = None,\n _proxy: Url | None = None,\n _proxy_headers: typing.Mapping[str, str] | None = None,\n key_file: str | None = None,\n cert_file: str | None = None,\n cert_reqs: int | str | None = None,\n key_password: str | None = None,\n ca_certs: str | None = None,\n ssl_version: int | str | None = None,\n ssl_minimum_version: ssl.TLSVersion | None = None,\n ssl_maximum_version: ssl.TLSVersion | None = None,\n assert_hostname: str | Literal[False] | None = None,\n assert_fingerprint: str | None = None,\n ca_cert_dir: str | None = None,\n **conn_kw: typing.Any,\n ) -> None:\n def _prepare_proxy(self, conn: HTTPSConnection) -> None: # type: ignore[override]\n def _new_conn(self) -> BaseHTTPSConnection:\n def _validate_conn(self, conn: BaseHTTPConnection) -> None:\ndef connection_from_url(url: str, **kw: typing.Any) -> HTTPConnectionPool:\ndef _normalize_host(host: None, scheme: str | None) -> None:\ndef _normalize_host(host: str, scheme: str | None) -> str:\ndef _normalize_host(host: str | None, scheme: str | None) -> str | None:\ndef _url_from_pool(\n pool: HTTPConnectionPool | HTTPSConnectionPool, path: str | None = None\n) -> str:\ndef _close_pool_connections(pool: queue.LifoQueue[typing.Any]) -> None:" }, { "identifier": "LocationValueError", "path": "py/Python38/site-packages/urllib3/exceptions.py", "snippet": "class LocationValueError(ValueError, HTTPError):\n \"\"\"Raised when there is something wrong with a given URL input.\"\"\"" }, { "identifier": "MaxRetryError", "path": "py/Python38/site-packages/urllib3/exceptions.py", "snippet": "class MaxRetryError(RequestError):\n \"\"\"Raised when the maximum number of retries is exceeded.\n\n :param pool: The connection pool\n :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool`\n :param str url: The requested Url\n :param reason: The underlying error\n :type reason: :class:`Exception`\n\n \"\"\"\n\n def __init__(\n self, pool: ConnectionPool, url: str, reason: Exception | None = None\n ) -> None:\n self.reason = reason\n\n message = f\"Max retries exceeded with url: {url} (Caused by {reason!r})\"\n\n super().__init__(pool, url, message)" }, { "identifier": "ProxySchemeUnknown", "path": "py/Python38/site-packages/urllib3/exceptions.py", "snippet": "class ProxySchemeUnknown(AssertionError, URLSchemeUnknown):\n \"\"\"ProxyManager does not support the supplied scheme\"\"\"\n\n # TODO(t-8ch): Stop inheriting from AssertionError in v2.0.\n\n def __init__(self, scheme: str | None) -> None:\n # 'localhost' is here because our URL parser parses\n # localhost:8080 -> scheme=localhost, remove if we fix this.\n if scheme == \"localhost\":\n scheme = None\n if scheme is None:\n message = \"Proxy URL had no scheme, should start with http:// or https://\"\n else:\n message = f\"Proxy URL had unsupported scheme {scheme}, should use http:// or https://\"\n super().__init__(message)" }, { "identifier": "URLSchemeUnknown", "path": "py/Python38/site-packages/urllib3/exceptions.py", "snippet": "class URLSchemeUnknown(LocationValueError):\n \"\"\"Raised when a URL input has an unsupported scheme.\"\"\"\n\n def __init__(self, scheme: str):\n message = f\"Not supported URL scheme {scheme}\"\n super().__init__(message)\n\n self.scheme = scheme" }, { "identifier": "BaseHTTPResponse", "path": "py/Python38/site-packages/urllib3/response.py", "snippet": "class BaseHTTPResponse(io.IOBase):\n CONTENT_DECODERS = [\"gzip\", \"deflate\"]\n if brotli is not None:\n CONTENT_DECODERS += [\"br\"]\n if zstd is not None:\n CONTENT_DECODERS += [\"zstd\"]\n REDIRECT_STATUSES = [301, 302, 303, 307, 308]\n\n DECODER_ERROR_CLASSES: tuple[type[Exception], ...] = (IOError, zlib.error)\n if brotli is not None:\n DECODER_ERROR_CLASSES += (brotli.error,)\n\n if zstd is not None:\n DECODER_ERROR_CLASSES += (zstd.ZstdError,)\n\n def __init__(\n self,\n *,\n headers: typing.Mapping[str, str] | typing.Mapping[bytes, bytes] | None = None,\n status: int,\n version: int,\n reason: str | None,\n decode_content: bool,\n request_url: str | None,\n retries: Retry | None = None,\n ) -> None:\n if isinstance(headers, HTTPHeaderDict):\n self.headers = headers\n else:\n self.headers = HTTPHeaderDict(headers) # type: ignore[arg-type]\n self.status = status\n self.version = version\n self.reason = reason\n self.decode_content = decode_content\n self._has_decoded_content = False\n self._request_url: str | None = request_url\n self.retries = retries\n\n self.chunked = False\n tr_enc = self.headers.get(\"transfer-encoding\", \"\").lower()\n # Don't incur the penalty of creating a list and then discarding it\n encodings = (enc.strip() for enc in tr_enc.split(\",\"))\n if \"chunked\" in encodings:\n self.chunked = True\n\n self._decoder: ContentDecoder | None = None\n\n def get_redirect_location(self) -> str | None | Literal[False]:\n \"\"\"\n Should we redirect and where to?\n\n :returns: Truthy redirect location string if we got a redirect status\n code and valid location. ``None`` if redirect status and no\n location. ``False`` if not a redirect status code.\n \"\"\"\n if self.status in self.REDIRECT_STATUSES:\n return self.headers.get(\"location\")\n return False\n\n @property\n def data(self) -> bytes:\n raise NotImplementedError()\n\n def json(self) -> typing.Any:\n \"\"\"\n Parses the body of the HTTP response as JSON.\n\n To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to the decoder.\n\n This method can raise either `UnicodeDecodeError` or `json.JSONDecodeError`.\n\n Read more :ref:`here <json>`.\n \"\"\"\n data = self.data.decode(\"utf-8\")\n return _json.loads(data)\n\n @property\n def url(self) -> str | None:\n raise NotImplementedError()\n\n @url.setter\n def url(self, url: str | None) -> None:\n raise NotImplementedError()\n\n @property\n def connection(self) -> HTTPConnection | None:\n raise NotImplementedError()\n\n @property\n def retries(self) -> Retry | None:\n return self._retries\n\n @retries.setter\n def retries(self, retries: Retry | None) -> None:\n # Override the request_url if retries has a redirect location.\n if retries is not None and retries.history:\n self.url = retries.history[-1].redirect_location\n self._retries = retries\n\n def stream(\n self, amt: int | None = 2**16, decode_content: bool | None = None\n ) -> typing.Iterator[bytes]:\n raise NotImplementedError()\n\n def read(\n self,\n amt: int | None = None,\n decode_content: bool | None = None,\n cache_content: bool = False,\n ) -> bytes:\n raise NotImplementedError()\n\n def read_chunked(\n self,\n amt: int | None = None,\n decode_content: bool | None = None,\n ) -> typing.Iterator[bytes]:\n raise NotImplementedError()\n\n def release_conn(self) -> None:\n raise NotImplementedError()\n\n def drain_conn(self) -> None:\n raise NotImplementedError()\n\n def close(self) -> None:\n raise NotImplementedError()\n\n def _init_decoder(self) -> None:\n \"\"\"\n Set-up the _decoder attribute if necessary.\n \"\"\"\n # Note: content-encoding value should be case-insensitive, per RFC 7230\n # Section 3.2\n content_encoding = self.headers.get(\"content-encoding\", \"\").lower()\n if self._decoder is None:\n if content_encoding in self.CONTENT_DECODERS:\n self._decoder = _get_decoder(content_encoding)\n elif \",\" in content_encoding:\n encodings = [\n e.strip()\n for e in content_encoding.split(\",\")\n if e.strip() in self.CONTENT_DECODERS\n ]\n if encodings:\n self._decoder = _get_decoder(content_encoding)\n\n def _decode(\n self, data: bytes, decode_content: bool | None, flush_decoder: bool\n ) -> bytes:\n \"\"\"\n Decode the data passed in and potentially flush the decoder.\n \"\"\"\n if not decode_content:\n if self._has_decoded_content:\n raise RuntimeError(\n \"Calling read(decode_content=False) is not supported after \"\n \"read(decode_content=True) was called.\"\n )\n return data\n\n try:\n if self._decoder:\n data = self._decoder.decompress(data)\n self._has_decoded_content = True\n except self.DECODER_ERROR_CLASSES as e:\n content_encoding = self.headers.get(\"content-encoding\", \"\").lower()\n raise DecodeError(\n \"Received response with content-encoding: %s, but \"\n \"failed to decode it.\" % content_encoding,\n e,\n ) from e\n if flush_decoder:\n data += self._flush_decoder()\n\n return data\n\n def _flush_decoder(self) -> bytes:\n \"\"\"\n Flushes the decoder. Should only be called if the decoder is actually\n being used.\n \"\"\"\n if self._decoder:\n return self._decoder.decompress(b\"\") + self._decoder.flush()\n return b\"\"\n\n # Compatibility methods for `io` module\n def readinto(self, b: bytearray) -> int:\n temp = self.read(len(b))\n if len(temp) == 0:\n return 0\n else:\n b[: len(temp)] = temp\n return len(temp)\n\n # Compatibility methods for http.client.HTTPResponse\n def getheaders(self) -> HTTPHeaderDict:\n warnings.warn(\n \"HTTPResponse.getheaders() is deprecated and will be removed \"\n \"in urllib3 v2.1.0. Instead access HTTPResponse.headers directly.\",\n category=DeprecationWarning,\n stacklevel=2,\n )\n return self.headers\n\n def getheader(self, name: str, default: str | None = None) -> str | None:\n warnings.warn(\n \"HTTPResponse.getheader() is deprecated and will be removed \"\n \"in urllib3 v2.1.0. Instead use HTTPResponse.headers.get(name, default).\",\n category=DeprecationWarning,\n stacklevel=2,\n )\n return self.headers.get(name, default)\n\n # Compatibility method for http.cookiejar\n def info(self) -> HTTPHeaderDict:\n return self.headers\n\n def geturl(self) -> str | None:\n return self.url" }, { "identifier": "_TYPE_SOCKET_OPTIONS", "path": "py/Python38/site-packages/urllib3/util/connection.py", "snippet": "_TYPE_SOCKET_OPTIONS = typing.Sequence[typing.Tuple[int, int, typing.Union[int, bytes]]]" }, { "identifier": "connection_requires_http_tunnel", "path": "py/Python38/site-packages/urllib3/util/proxy.py", "snippet": "def connection_requires_http_tunnel(\n proxy_url: Url | None = None,\n proxy_config: ProxyConfig | None = None,\n destination_scheme: str | None = None,\n) -> bool:\n \"\"\"\n Returns True if the connection requires an HTTP CONNECT through the proxy.\n\n :param URL proxy_url:\n URL of the proxy.\n :param ProxyConfig proxy_config:\n Proxy configuration from poolmanager.py\n :param str destination_scheme:\n The scheme of the destination. (i.e https, http, etc)\n \"\"\"\n # If we're not using a proxy, no way to use a tunnel.\n if proxy_url is None:\n return False\n\n # HTTP destinations never require tunneling, we always forward.\n if destination_scheme == \"http\":\n return False\n\n # Support for forwarding with HTTPS proxies and HTTPS destinations.\n if (\n proxy_url.scheme == \"https\"\n and proxy_config\n and proxy_config.use_forwarding_for_https\n ):\n return False\n\n # Otherwise always use a tunnel.\n return True" }, { "identifier": "Retry", "path": "py/Python38/site-packages/urllib3/util/retry.py", "snippet": "class Retry:\n \"\"\"Retry configuration.\n\n Each retry attempt will create a new Retry object with updated values, so\n they can be safely reused.\n\n Retries can be defined as a default for a pool:\n\n .. code-block:: python\n\n retries = Retry(connect=5, read=2, redirect=5)\n http = PoolManager(retries=retries)\n response = http.request(\"GET\", \"https://example.com/\")\n\n Or per-request (which overrides the default for the pool):\n\n .. code-block:: python\n\n response = http.request(\"GET\", \"https://example.com/\", retries=Retry(10))\n\n Retries can be disabled by passing ``False``:\n\n .. code-block:: python\n\n response = http.request(\"GET\", \"https://example.com/\", retries=False)\n\n Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless\n retries are disabled, in which case the causing exception will be raised.\n\n :param int total:\n Total number of retries to allow. Takes precedence over other counts.\n\n Set to ``None`` to remove this constraint and fall back on other\n counts.\n\n Set to ``0`` to fail on the first retry.\n\n Set to ``False`` to disable and imply ``raise_on_redirect=False``.\n\n :param int connect:\n How many connection-related errors to retry on.\n\n These are errors raised before the request is sent to the remote server,\n which we assume has not triggered the server to process the request.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int read:\n How many times to retry on read errors.\n\n These errors are raised after the request was sent to the server, so the\n request may have side-effects.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int redirect:\n How many redirects to perform. Limit this to avoid infinite redirect\n loops.\n\n A redirect is a HTTP response with a status code 301, 302, 303, 307 or\n 308.\n\n Set to ``0`` to fail on the first retry of this type.\n\n Set to ``False`` to disable and imply ``raise_on_redirect=False``.\n\n :param int status:\n How many times to retry on bad status codes.\n\n These are retries made on responses, where status code matches\n ``status_forcelist``.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int other:\n How many times to retry on other errors.\n\n Other errors are errors that are not connect, read, redirect or status errors.\n These errors might be raised after the request was sent to the server, so the\n request might have side-effects.\n\n Set to ``0`` to fail on the first retry of this type.\n\n If ``total`` is not set, it's a good idea to set this to 0 to account\n for unexpected edge cases and avoid infinite retry loops.\n\n :param Collection allowed_methods:\n Set of uppercased HTTP method verbs that we should retry on.\n\n By default, we only retry on methods which are considered to be\n idempotent (multiple requests with the same parameters end with the\n same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`.\n\n Set to a ``None`` value to retry on any verb.\n\n :param Collection status_forcelist:\n A set of integer HTTP status codes that we should force a retry on.\n A retry is initiated if the request method is in ``allowed_methods``\n and the response status code is in ``status_forcelist``.\n\n By default, this is disabled with ``None``.\n\n :param float backoff_factor:\n A backoff factor to apply between attempts after the second try\n (most errors are resolved immediately by a second try without a\n delay). urllib3 will sleep for::\n\n {backoff factor} * (2 ** ({number of previous retries}))\n\n seconds. If `backoff_jitter` is non-zero, this sleep is extended by::\n\n random.uniform(0, {backoff jitter})\n\n seconds. For example, if the backoff_factor is 0.1, then :func:`Retry.sleep` will\n sleep for [0.0s, 0.2s, 0.4s, 0.8s, ...] between retries. No backoff will ever\n be longer than `backoff_max`.\n\n By default, backoff is disabled (factor set to 0).\n\n :param bool raise_on_redirect: Whether, if the number of redirects is\n exhausted, to raise a MaxRetryError, or to return a response with a\n response code in the 3xx range.\n\n :param bool raise_on_status: Similar meaning to ``raise_on_redirect``:\n whether we should raise an exception, or return a response,\n if status falls in ``status_forcelist`` range and retries have\n been exhausted.\n\n :param tuple history: The history of the request encountered during\n each call to :meth:`~Retry.increment`. The list is in the order\n the requests occurred. Each list item is of class :class:`RequestHistory`.\n\n :param bool respect_retry_after_header:\n Whether to respect Retry-After header on status codes defined as\n :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.\n\n :param Collection remove_headers_on_redirect:\n Sequence of headers to remove from the request when a response\n indicating a redirect is returned before firing off the redirected\n request.\n \"\"\"\n\n #: Default methods to be used for ``allowed_methods``\n DEFAULT_ALLOWED_METHODS = frozenset(\n [\"HEAD\", \"GET\", \"PUT\", \"DELETE\", \"OPTIONS\", \"TRACE\"]\n )\n\n #: Default status codes to be used for ``status_forcelist``\n RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])\n\n #: Default headers to be used for ``remove_headers_on_redirect``\n DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset([\"Cookie\", \"Authorization\"])\n\n #: Default maximum backoff time.\n DEFAULT_BACKOFF_MAX = 120\n\n # Backward compatibility; assigned outside of the class.\n DEFAULT: typing.ClassVar[Retry]\n\n def __init__(\n self,\n total: bool | int | None = 10,\n connect: int | None = None,\n read: int | None = None,\n redirect: bool | int | None = None,\n status: int | None = None,\n other: int | None = None,\n allowed_methods: typing.Collection[str] | None = DEFAULT_ALLOWED_METHODS,\n status_forcelist: typing.Collection[int] | None = None,\n backoff_factor: float = 0,\n backoff_max: float = DEFAULT_BACKOFF_MAX,\n raise_on_redirect: bool = True,\n raise_on_status: bool = True,\n history: tuple[RequestHistory, ...] | None = None,\n respect_retry_after_header: bool = True,\n remove_headers_on_redirect: typing.Collection[\n str\n ] = DEFAULT_REMOVE_HEADERS_ON_REDIRECT,\n backoff_jitter: float = 0.0,\n ) -> None:\n self.total = total\n self.connect = connect\n self.read = read\n self.status = status\n self.other = other\n\n if redirect is False or total is False:\n redirect = 0\n raise_on_redirect = False\n\n self.redirect = redirect\n self.status_forcelist = status_forcelist or set()\n self.allowed_methods = allowed_methods\n self.backoff_factor = backoff_factor\n self.backoff_max = backoff_max\n self.raise_on_redirect = raise_on_redirect\n self.raise_on_status = raise_on_status\n self.history = history or ()\n self.respect_retry_after_header = respect_retry_after_header\n self.remove_headers_on_redirect = frozenset(\n h.lower() for h in remove_headers_on_redirect\n )\n self.backoff_jitter = backoff_jitter\n\n def new(self, **kw: typing.Any) -> Retry:\n params = dict(\n total=self.total,\n connect=self.connect,\n read=self.read,\n redirect=self.redirect,\n status=self.status,\n other=self.other,\n allowed_methods=self.allowed_methods,\n status_forcelist=self.status_forcelist,\n backoff_factor=self.backoff_factor,\n backoff_max=self.backoff_max,\n raise_on_redirect=self.raise_on_redirect,\n raise_on_status=self.raise_on_status,\n history=self.history,\n remove_headers_on_redirect=self.remove_headers_on_redirect,\n respect_retry_after_header=self.respect_retry_after_header,\n backoff_jitter=self.backoff_jitter,\n )\n\n params.update(kw)\n return type(self)(**params) # type: ignore[arg-type]\n\n @classmethod\n def from_int(\n cls,\n retries: Retry | bool | int | None,\n redirect: bool | int | None = True,\n default: Retry | bool | int | None = None,\n ) -> Retry:\n \"\"\"Backwards-compatibility for the old retries format.\"\"\"\n if retries is None:\n retries = default if default is not None else cls.DEFAULT\n\n if isinstance(retries, Retry):\n return retries\n\n redirect = bool(redirect) and None\n new_retries = cls(retries, redirect=redirect)\n log.debug(\"Converted retries value: %r -> %r\", retries, new_retries)\n return new_retries\n\n def get_backoff_time(self) -> float:\n \"\"\"Formula for computing the current backoff\n\n :rtype: float\n \"\"\"\n # We want to consider only the last consecutive errors sequence (Ignore redirects).\n consecutive_errors_len = len(\n list(\n takewhile(lambda x: x.redirect_location is None, reversed(self.history))\n )\n )\n if consecutive_errors_len <= 1:\n return 0\n\n backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))\n if self.backoff_jitter != 0.0:\n backoff_value += random.random() * self.backoff_jitter\n return float(max(0, min(self.backoff_max, backoff_value)))\n\n def parse_retry_after(self, retry_after: str) -> float:\n seconds: float\n # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4\n if re.match(r\"^\\s*[0-9]+\\s*$\", retry_after):\n seconds = int(retry_after)\n else:\n retry_date_tuple = email.utils.parsedate_tz(retry_after)\n if retry_date_tuple is None:\n raise InvalidHeader(f\"Invalid Retry-After header: {retry_after}\")\n\n retry_date = email.utils.mktime_tz(retry_date_tuple)\n seconds = retry_date - time.time()\n\n seconds = max(seconds, 0)\n\n return seconds\n\n def get_retry_after(self, response: BaseHTTPResponse) -> float | None:\n \"\"\"Get the value of Retry-After in seconds.\"\"\"\n\n retry_after = response.headers.get(\"Retry-After\")\n\n if retry_after is None:\n return None\n\n return self.parse_retry_after(retry_after)\n\n def sleep_for_retry(self, response: BaseHTTPResponse) -> bool:\n retry_after = self.get_retry_after(response)\n if retry_after:\n time.sleep(retry_after)\n return True\n\n return False\n\n def _sleep_backoff(self) -> None:\n backoff = self.get_backoff_time()\n if backoff <= 0:\n return\n time.sleep(backoff)\n\n def sleep(self, response: BaseHTTPResponse | None = None) -> None:\n \"\"\"Sleep between retry attempts.\n\n This method will respect a server's ``Retry-After`` response header\n and sleep the duration of the time requested. If that is not present, it\n will use an exponential backoff. By default, the backoff factor is 0 and\n this method will return immediately.\n \"\"\"\n\n if self.respect_retry_after_header and response:\n slept = self.sleep_for_retry(response)\n if slept:\n return\n\n self._sleep_backoff()\n\n def _is_connection_error(self, err: Exception) -> bool:\n \"\"\"Errors when we're fairly sure that the server did not receive the\n request, so it should be safe to retry.\n \"\"\"\n if isinstance(err, ProxyError):\n err = err.original_error\n return isinstance(err, ConnectTimeoutError)\n\n def _is_read_error(self, err: Exception) -> bool:\n \"\"\"Errors that occur after the request has been started, so we should\n assume that the server began processing it.\n \"\"\"\n return isinstance(err, (ReadTimeoutError, ProtocolError))\n\n def _is_method_retryable(self, method: str) -> bool:\n \"\"\"Checks if a given HTTP method should be retried upon, depending if\n it is included in the allowed_methods\n \"\"\"\n if self.allowed_methods and method.upper() not in self.allowed_methods:\n return False\n return True\n\n def is_retry(\n self, method: str, status_code: int, has_retry_after: bool = False\n ) -> bool:\n \"\"\"Is this method/status code retryable? (Based on allowlists and control\n variables such as the number of total retries to allow, whether to\n respect the Retry-After header, whether this header is present, and\n whether the returned status code is on the list of status codes to\n be retried upon on the presence of the aforementioned header)\n \"\"\"\n if not self._is_method_retryable(method):\n return False\n\n if self.status_forcelist and status_code in self.status_forcelist:\n return True\n\n return bool(\n self.total\n and self.respect_retry_after_header\n and has_retry_after\n and (status_code in self.RETRY_AFTER_STATUS_CODES)\n )\n\n def is_exhausted(self) -> bool:\n \"\"\"Are we out of retries?\"\"\"\n retry_counts = [\n x\n for x in (\n self.total,\n self.connect,\n self.read,\n self.redirect,\n self.status,\n self.other,\n )\n if x\n ]\n if not retry_counts:\n return False\n\n return min(retry_counts) < 0\n\n def increment(\n self,\n method: str | None = None,\n url: str | None = None,\n response: BaseHTTPResponse | None = None,\n error: Exception | None = None,\n _pool: ConnectionPool | None = None,\n _stacktrace: TracebackType | None = None,\n ) -> Retry:\n \"\"\"Return a new Retry object with incremented retry counters.\n\n :param response: A response object, or None, if the server did not\n return a response.\n :type response: :class:`~urllib3.response.BaseHTTPResponse`\n :param Exception error: An error encountered during the request, or\n None if the response was received successfully.\n\n :return: A new ``Retry`` object.\n \"\"\"\n if self.total is False and error:\n # Disabled, indicate to re-raise the error.\n raise reraise(type(error), error, _stacktrace)\n\n total = self.total\n if total is not None:\n total -= 1\n\n connect = self.connect\n read = self.read\n redirect = self.redirect\n status_count = self.status\n other = self.other\n cause = \"unknown\"\n status = None\n redirect_location = None\n\n if error and self._is_connection_error(error):\n # Connect retry?\n if connect is False:\n raise reraise(type(error), error, _stacktrace)\n elif connect is not None:\n connect -= 1\n\n elif error and self._is_read_error(error):\n # Read retry?\n if read is False or method is None or not self._is_method_retryable(method):\n raise reraise(type(error), error, _stacktrace)\n elif read is not None:\n read -= 1\n\n elif error:\n # Other retry?\n if other is not None:\n other -= 1\n\n elif response and response.get_redirect_location():\n # Redirect retry?\n if redirect is not None:\n redirect -= 1\n cause = \"too many redirects\"\n response_redirect_location = response.get_redirect_location()\n if response_redirect_location:\n redirect_location = response_redirect_location\n status = response.status\n\n else:\n # Incrementing because of a server error like a 500 in\n # status_forcelist and the given method is in the allowed_methods\n cause = ResponseError.GENERIC_ERROR\n if response and response.status:\n if status_count is not None:\n status_count -= 1\n cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status)\n status = response.status\n\n history = self.history + (\n RequestHistory(method, url, error, status, redirect_location),\n )\n\n new_retry = self.new(\n total=total,\n connect=connect,\n read=read,\n redirect=redirect,\n status=status_count,\n other=other,\n history=history,\n )\n\n if new_retry.is_exhausted():\n reason = error or ResponseError(cause)\n raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type]\n\n log.debug(\"Incremented Retry for (url='%s'): %r\", url, new_retry)\n\n return new_retry\n\n def __repr__(self) -> str:\n return (\n f\"{type(self).__name__}(total={self.total}, connect={self.connect}, \"\n f\"read={self.read}, redirect={self.redirect}, status={self.status})\"\n )" }, { "identifier": "Timeout", "path": "py/Python38/site-packages/urllib3/util/timeout.py", "snippet": "class Timeout:\n \"\"\"Timeout configuration.\n\n Timeouts can be defined as a default for a pool:\n\n .. code-block:: python\n\n import urllib3\n\n timeout = urllib3.util.Timeout(connect=2.0, read=7.0)\n\n http = urllib3.PoolManager(timeout=timeout)\n\n resp = http.request(\"GET\", \"https://example.com/\")\n\n print(resp.status)\n\n Or per-request (which overrides the default for the pool):\n\n .. code-block:: python\n\n response = http.request(\"GET\", \"https://example.com/\", timeout=Timeout(10))\n\n Timeouts can be disabled by setting all the parameters to ``None``:\n\n .. code-block:: python\n\n no_timeout = Timeout(connect=None, read=None)\n response = http.request(\"GET\", \"https://example.com/\", timeout=no_timeout)\n\n\n :param total:\n This combines the connect and read timeouts into one; the read timeout\n will be set to the time leftover from the connect attempt. In the\n event that both a connect timeout and a total are specified, or a read\n timeout and a total are specified, the shorter timeout will be applied.\n\n Defaults to None.\n\n :type total: int, float, or None\n\n :param connect:\n The maximum amount of time (in seconds) to wait for a connection\n attempt to a server to succeed. Omitting the parameter will default the\n connect timeout to the system default, probably `the global default\n timeout in socket.py\n <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.\n None will set an infinite timeout for connection attempts.\n\n :type connect: int, float, or None\n\n :param read:\n The maximum amount of time (in seconds) to wait between consecutive\n read operations for a response from the server. Omitting the parameter\n will default the read timeout to the system default, probably `the\n global default timeout in socket.py\n <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.\n None will set an infinite timeout.\n\n :type read: int, float, or None\n\n .. note::\n\n Many factors can affect the total amount of time for urllib3 to return\n an HTTP response.\n\n For example, Python's DNS resolver does not obey the timeout specified\n on the socket. Other factors that can affect total request time include\n high CPU load, high swap, the program running at a low priority level,\n or other behaviors.\n\n In addition, the read and total timeouts only measure the time between\n read operations on the socket connecting the client and the server,\n not the total amount of time for the request to return a complete\n response. For most requests, the timeout is raised because the server\n has not sent the first byte in the specified time. This is not always\n the case; if a server streams one byte every fifteen seconds, a timeout\n of 20 seconds will not trigger, even though the request will take\n several minutes to complete.\n\n If your goal is to cut off any request after a set amount of wall clock\n time, consider having a second \"watcher\" thread to cut off a slow\n request.\n \"\"\"\n\n #: A sentinel object representing the default timeout value\n DEFAULT_TIMEOUT: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT\n\n def __init__(\n self,\n total: _TYPE_TIMEOUT = None,\n connect: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n read: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n ) -> None:\n self._connect = self._validate_timeout(connect, \"connect\")\n self._read = self._validate_timeout(read, \"read\")\n self.total = self._validate_timeout(total, \"total\")\n self._start_connect: float | None = None\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}(connect={self._connect!r}, read={self._read!r}, total={self.total!r})\"\n\n # __str__ provided for backwards compatibility\n __str__ = __repr__\n\n @staticmethod\n def resolve_default_timeout(timeout: _TYPE_TIMEOUT) -> float | None:\n return getdefaulttimeout() if timeout is _DEFAULT_TIMEOUT else timeout\n\n @classmethod\n def _validate_timeout(cls, value: _TYPE_TIMEOUT, name: str) -> _TYPE_TIMEOUT:\n \"\"\"Check that a timeout attribute is valid.\n\n :param value: The timeout value to validate\n :param name: The name of the timeout attribute to validate. This is\n used to specify in error messages.\n :return: The validated and casted version of the given value.\n :raises ValueError: If it is a numeric value less than or equal to\n zero, or the type is not an integer, float, or None.\n \"\"\"\n if value is None or value is _DEFAULT_TIMEOUT:\n return value\n\n if isinstance(value, bool):\n raise ValueError(\n \"Timeout cannot be a boolean value. It must \"\n \"be an int, float or None.\"\n )\n try:\n float(value)\n except (TypeError, ValueError):\n raise ValueError(\n \"Timeout value %s was %s, but it must be an \"\n \"int, float or None.\" % (name, value)\n ) from None\n\n try:\n if value <= 0:\n raise ValueError(\n \"Attempted to set %s timeout to %s, but the \"\n \"timeout cannot be set to a value less \"\n \"than or equal to 0.\" % (name, value)\n )\n except TypeError:\n raise ValueError(\n \"Timeout value %s was %s, but it must be an \"\n \"int, float or None.\" % (name, value)\n ) from None\n\n return value\n\n @classmethod\n def from_float(cls, timeout: _TYPE_TIMEOUT) -> Timeout:\n \"\"\"Create a new Timeout from a legacy timeout value.\n\n The timeout value used by httplib.py sets the same timeout on the\n connect(), and recv() socket requests. This creates a :class:`Timeout`\n object that sets the individual timeouts to the ``timeout`` value\n passed to this function.\n\n :param timeout: The legacy timeout value.\n :type timeout: integer, float, :attr:`urllib3.util.Timeout.DEFAULT_TIMEOUT`, or None\n :return: Timeout object\n :rtype: :class:`Timeout`\n \"\"\"\n return Timeout(read=timeout, connect=timeout)\n\n def clone(self) -> Timeout:\n \"\"\"Create a copy of the timeout object\n\n Timeout properties are stored per-pool but each request needs a fresh\n Timeout object to ensure each one has its own start/stop configured.\n\n :return: a copy of the timeout object\n :rtype: :class:`Timeout`\n \"\"\"\n # We can't use copy.deepcopy because that will also create a new object\n # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to\n # detect the user default.\n return Timeout(connect=self._connect, read=self._read, total=self.total)\n\n def start_connect(self) -> float:\n \"\"\"Start the timeout clock, used during a connect() attempt\n\n :raises urllib3.exceptions.TimeoutStateError: if you attempt\n to start a timer that has been started already.\n \"\"\"\n if self._start_connect is not None:\n raise TimeoutStateError(\"Timeout timer has already been started.\")\n self._start_connect = time.monotonic()\n return self._start_connect\n\n def get_connect_duration(self) -> float:\n \"\"\"Gets the time elapsed since the call to :meth:`start_connect`.\n\n :return: Elapsed time in seconds.\n :rtype: float\n :raises urllib3.exceptions.TimeoutStateError: if you attempt\n to get duration for a timer that hasn't been started.\n \"\"\"\n if self._start_connect is None:\n raise TimeoutStateError(\n \"Can't get connect duration for timer that has not started.\"\n )\n return time.monotonic() - self._start_connect\n\n @property\n def connect_timeout(self) -> _TYPE_TIMEOUT:\n \"\"\"Get the value to use when setting a connection timeout.\n\n This will be a positive float or integer, the value None\n (never timeout), or the default system timeout.\n\n :return: Connect timeout.\n :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None\n \"\"\"\n if self.total is None:\n return self._connect\n\n if self._connect is None or self._connect is _DEFAULT_TIMEOUT:\n return self.total\n\n return min(self._connect, self.total) # type: ignore[type-var]\n\n @property\n def read_timeout(self) -> float | None:\n \"\"\"Get the value for the read timeout.\n\n This assumes some time has elapsed in the connection timeout and\n computes the read timeout appropriately.\n\n If self.total is set, the read timeout is dependent on the amount of\n time taken by the connect timeout. If the connection time has not been\n established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be\n raised.\n\n :return: Value to use for the read timeout.\n :rtype: int, float or None\n :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`\n has not yet been called on this object.\n \"\"\"\n if (\n self.total is not None\n and self.total is not _DEFAULT_TIMEOUT\n and self._read is not None\n and self._read is not _DEFAULT_TIMEOUT\n ):\n # In case the connect timeout has not yet been established.\n if self._start_connect is None:\n return self._read\n return max(0, min(self.total - self.get_connect_duration(), self._read))\n elif self.total is not None and self.total is not _DEFAULT_TIMEOUT:\n return max(0, self.total - self.get_connect_duration())\n else:\n return self.resolve_default_timeout(self._read)" }, { "identifier": "Url", "path": "py/Python38/site-packages/urllib3/util/url.py", "snippet": "class Url(\n typing.NamedTuple(\n \"Url\",\n [\n (\"scheme\", typing.Optional[str]),\n (\"auth\", typing.Optional[str]),\n (\"host\", typing.Optional[str]),\n (\"port\", typing.Optional[int]),\n (\"path\", typing.Optional[str]),\n (\"query\", typing.Optional[str]),\n (\"fragment\", typing.Optional[str]),\n ],\n )\n):\n \"\"\"\n Data structure for representing an HTTP URL. Used as a return value for\n :func:`parse_url`. Both the scheme and host are normalized as they are\n both case-insensitive according to RFC 3986.\n \"\"\"\n\n def __new__( # type: ignore[no-untyped-def]\n cls,\n scheme: str | None = None,\n auth: str | None = None,\n host: str | None = None,\n port: int | None = None,\n path: str | None = None,\n query: str | None = None,\n fragment: str | None = None,\n ):\n if path and not path.startswith(\"/\"):\n path = \"/\" + path\n if scheme is not None:\n scheme = scheme.lower()\n return super().__new__(cls, scheme, auth, host, port, path, query, fragment)\n\n @property\n def hostname(self) -> str | None:\n \"\"\"For backwards-compatibility with urlparse. We're nice like that.\"\"\"\n return self.host\n\n @property\n def request_uri(self) -> str:\n \"\"\"Absolute path including the query string.\"\"\"\n uri = self.path or \"/\"\n\n if self.query is not None:\n uri += \"?\" + self.query\n\n return uri\n\n @property\n def authority(self) -> str | None:\n \"\"\"\n Authority component as defined in RFC 3986 3.2.\n This includes userinfo (auth), host and port.\n\n i.e.\n userinfo@host:port\n \"\"\"\n userinfo = self.auth\n netloc = self.netloc\n if netloc is None or userinfo is None:\n return netloc\n else:\n return f\"{userinfo}@{netloc}\"\n\n @property\n def netloc(self) -> str | None:\n \"\"\"\n Network location including host and port.\n\n If you need the equivalent of urllib.parse's ``netloc``,\n use the ``authority`` property instead.\n \"\"\"\n if self.host is None:\n return None\n if self.port:\n return f\"{self.host}:{self.port}\"\n return self.host\n\n @property\n def url(self) -> str:\n \"\"\"\n Convert self into a url\n\n This function should more or less round-trip with :func:`.parse_url`. The\n returned url may not be exactly the same as the url inputted to\n :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls\n with a blank port will have : removed).\n\n Example:\n\n .. code-block:: python\n\n import urllib3\n\n U = urllib3.util.parse_url(\"https://google.com/mail/\")\n\n print(U.url)\n # \"https://google.com/mail/\"\n\n print( urllib3.util.Url(\"https\", \"username:password\",\n \"host.com\", 80, \"/path\", \"query\", \"fragment\"\n ).url\n )\n # \"https://username:[email protected]:80/path?query#fragment\"\n \"\"\"\n scheme, auth, host, port, path, query, fragment = self\n url = \"\"\n\n # We use \"is not None\" we want things to happen with empty strings (or 0 port)\n if scheme is not None:\n url += scheme + \"://\"\n if auth is not None:\n url += auth + \"@\"\n if host is not None:\n url += host\n if port is not None:\n url += \":\" + str(port)\n if path is not None:\n url += path\n if query is not None:\n url += \"?\" + query\n if fragment is not None:\n url += \"#\" + fragment\n\n return url\n\n def __str__(self) -> str:\n return self.url" }, { "identifier": "parse_url", "path": "py/Python38/site-packages/urllib3/util/url.py", "snippet": "def parse_url(url: str) -> Url:\n \"\"\"\n Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is\n performed to parse incomplete urls. Fields not provided will be None.\n This parser is RFC 3986 and RFC 6874 compliant.\n\n The parser logic and helper functions are based heavily on\n work done in the ``rfc3986`` module.\n\n :param str url: URL to parse into a :class:`.Url` namedtuple.\n\n Partly backwards-compatible with :mod:`urllib.parse`.\n\n Example:\n\n .. code-block:: python\n\n import urllib3\n\n print( urllib3.util.parse_url('http://google.com/mail/'))\n # Url(scheme='http', host='google.com', port=None, path='/mail/', ...)\n\n print( urllib3.util.parse_url('google.com:80'))\n # Url(scheme=None, host='google.com', port=80, path=None, ...)\n\n print( urllib3.util.parse_url('/foo?bar'))\n # Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)\n \"\"\"\n if not url:\n # Empty\n return Url()\n\n source_url = url\n if not _SCHEME_RE.search(url):\n url = \"//\" + url\n\n scheme: str | None\n authority: str | None\n auth: str | None\n host: str | None\n port: str | None\n port_int: int | None\n path: str | None\n query: str | None\n fragment: str | None\n\n try:\n scheme, authority, path, query, fragment = _URI_RE.match(url).groups() # type: ignore[union-attr]\n normalize_uri = scheme is None or scheme.lower() in _NORMALIZABLE_SCHEMES\n\n if scheme:\n scheme = scheme.lower()\n\n if authority:\n auth, _, host_port = authority.rpartition(\"@\")\n auth = auth or None\n host, port = _HOST_PORT_RE.match(host_port).groups() # type: ignore[union-attr]\n if auth and normalize_uri:\n auth = _encode_invalid_chars(auth, _USERINFO_CHARS)\n if port == \"\":\n port = None\n else:\n auth, host, port = None, None, None\n\n if port is not None:\n port_int = int(port)\n if not (0 <= port_int <= 65535):\n raise LocationParseError(url)\n else:\n port_int = None\n\n host = _normalize_host(host, scheme)\n\n if normalize_uri and path:\n path = _remove_path_dot_segments(path)\n path = _encode_invalid_chars(path, _PATH_CHARS)\n if normalize_uri and query:\n query = _encode_invalid_chars(query, _QUERY_CHARS)\n if normalize_uri and fragment:\n fragment = _encode_invalid_chars(fragment, _FRAGMENT_CHARS)\n\n except (ValueError, AttributeError) as e:\n raise LocationParseError(source_url) from e\n\n # For the sake of backwards compatibility we put empty\n # string values for path if there are any defined values\n # beyond the path in the URL.\n # TODO: Remove this when we break backwards compatibility.\n if not path:\n if query is not None or fragment is not None:\n path = \"\"\n else:\n path = None\n\n return Url(\n scheme=scheme,\n auth=auth,\n host=host,\n port=port_int,\n path=path,\n query=query,\n fragment=fragment,\n )" } ]
import functools import logging import typing import warnings import ssl from types import TracebackType from urllib.parse import urljoin from ._collections import HTTPHeaderDict, RecentlyUsedContainer from ._request_methods import RequestMethods from .connection import ProxyConfig from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme from .exceptions import ( LocationValueError, MaxRetryError, ProxySchemeUnknown, URLSchemeUnknown, ) from .response import BaseHTTPResponse from .util.connection import _TYPE_SOCKET_OPTIONS from .util.proxy import connection_requires_http_tunnel from .util.retry import Retry from .util.timeout import Timeout from .util.url import Url, parse_url from typing_extensions import Literal
20,142
from __future__ import annotations if typing.TYPE_CHECKING: __all__ = ["PoolManager", "ProxyManager", "proxy_from_url"] log = logging.getLogger(__name__) SSL_KEYWORDS = ( "key_file", "cert_file", "cert_reqs", "ca_certs", "ssl_version", "ssl_minimum_version", "ssl_maximum_version", "ca_cert_dir", "ssl_context", "key_password", "server_hostname", ) # Default value for `blocksize` - a new parameter introduced to # http.client.HTTPConnection & http.client.HTTPSConnection in Python 3.7 _DEFAULT_BLOCKSIZE = 16384 _SelfT = typing.TypeVar("_SelfT") class PoolKey(typing.NamedTuple): """ All known keyword arguments that could be provided to the pool manager, its pools, or the underlying connections. All custom key schemes should include the fields in this key at a minimum. """ key_scheme: str key_host: str key_port: int | None key_timeout: Timeout | float | int | None key_retries: Retry | bool | int | None key_block: bool | None key_source_address: tuple[str, int] | None key_key_file: str | None key_key_password: str | None key_cert_file: str | None key_cert_reqs: str | None key_ca_certs: str | None key_ssl_version: int | str | None key_ssl_minimum_version: ssl.TLSVersion | None key_ssl_maximum_version: ssl.TLSVersion | None key_ca_cert_dir: str | None key_ssl_context: ssl.SSLContext | None key_maxsize: int | None key_headers: frozenset[tuple[str, str]] | None key__proxy: Url | None key__proxy_headers: frozenset[tuple[str, str]] | None
from __future__ import annotations if typing.TYPE_CHECKING: __all__ = ["PoolManager", "ProxyManager", "proxy_from_url"] log = logging.getLogger(__name__) SSL_KEYWORDS = ( "key_file", "cert_file", "cert_reqs", "ca_certs", "ssl_version", "ssl_minimum_version", "ssl_maximum_version", "ca_cert_dir", "ssl_context", "key_password", "server_hostname", ) # Default value for `blocksize` - a new parameter introduced to # http.client.HTTPConnection & http.client.HTTPSConnection in Python 3.7 _DEFAULT_BLOCKSIZE = 16384 _SelfT = typing.TypeVar("_SelfT") class PoolKey(typing.NamedTuple): """ All known keyword arguments that could be provided to the pool manager, its pools, or the underlying connections. All custom key schemes should include the fields in this key at a minimum. """ key_scheme: str key_host: str key_port: int | None key_timeout: Timeout | float | int | None key_retries: Retry | bool | int | None key_block: bool | None key_source_address: tuple[str, int] | None key_key_file: str | None key_key_password: str | None key_cert_file: str | None key_cert_reqs: str | None key_ca_certs: str | None key_ssl_version: int | str | None key_ssl_minimum_version: ssl.TLSVersion | None key_ssl_maximum_version: ssl.TLSVersion | None key_ca_cert_dir: str | None key_ssl_context: ssl.SSLContext | None key_maxsize: int | None key_headers: frozenset[tuple[str, str]] | None key__proxy: Url | None key__proxy_headers: frozenset[tuple[str, str]] | None
key__proxy_config: ProxyConfig | None
3
2023-10-11 09:08:57+00:00
24k
MTgeophysics/mtpy-v2
tests/core/test_mt_stations.py
[ { "identifier": "MTLocation", "path": "mtpy/core/mt_location.py", "snippet": "class MTLocation:\n \"\"\"\n Location for a MT site or point measurement\n\n \"\"\"\n\n def __init__(self, survey_metadata=None, **kwargs):\n\n self.logger = logger\n if survey_metadata is None:\n self._survey_metadata = self._initiate_metadata()\n else:\n self._survey_metadata = self._validate_metadata(survey_metadata)\n\n self._east = 0\n self._north = 0\n self._datum_crs = CRS.from_epsg(4326)\n self._utm_crs = None\n self._geoid_crs = None\n self.model_east = 0\n self.model_north = 0\n self.model_elevation = 0\n self.profile_offset = 0\n\n self._key_attrs = [\n \"latitude\",\n \"longitude\",\n \"elevation\",\n \"east\",\n \"north\",\n \"model_east\",\n \"model_north\",\n \"model_elevation\",\n \"datum_crs\",\n \"utm_crs\",\n \"datum_epsg\",\n \"utm_epsg\",\n \"profile_offset\",\n ]\n\n for key, value in kwargs.items():\n if key in self._key_attrs:\n setattr(self, key, value)\n\n if self.east != 0 and self.north != None:\n if self.utm_crs is None:\n raise ValueError(\n \"Need to input UTM CRS if only setting east and north\"\n )\n\n def _initiate_metadata(self):\n survey_metadata = Survey(id=0)\n survey_metadata.add_station(Station(id=0))\n survey_metadata.stations[0].add_run(Run(id=0))\n\n return survey_metadata\n\n def _validate_metadata(self, survey_metadata):\n if not isinstance(survey_metadata, Survey):\n raise TypeError(\n \"Input metadata must be type \"\n \"mt_metadata.transfer_functions.tf.Survey, \"\n f\"not {type(survey_metadata)}.\"\n )\n if len(survey_metadata.stations) < 1:\n survey_metadata.add_station(Station(id=0))\n\n if len(survey_metadata.stations[0].runs) < 1:\n survey_metadata.stations[0].add_run(Run(id=0))\n\n return survey_metadata\n\n def __str__(self):\n lines = [\"MT Location: \", \"-\" * 20]\n lines.append(f\" Latitude (deg): {self.latitude:.6f}\")\n lines.append(f\" Longitude (deg): {self.longitude:.6f}\")\n lines.append(f\" Elevation (m): {self.elevation:.4f}\")\n lines.append(f\" Datum crs: {self.datum_crs}\")\n lines.append(\"\")\n lines.append(f\" Easting (m): {self.east:.3f}\")\n lines.append(f\" Northing (m): {self.north:.3f}\")\n lines.append(f\" UTM crs: {self.utm_crs}\")\n lines.append(\"\")\n lines.append(f\" Model Easting (m): {self.model_east:.3f}\")\n lines.append(f\" Model Northing (m): {self.model_north:.3f}\")\n lines.append(f\" Model Elevation (m): {self.model_elevation:.3f}\")\n lines.append(f\" Profile Offset (m): {self.profile_offset:.3f}\")\n\n return \"\\n\".join(lines)\n\n def __repr__(self):\n return self.__str__()\n\n def __eq__(self, other):\n \"\"\"\n equals\n :param other: DESCRIPTION\n :type other: TYPE\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n if not isinstance(other, MTLocation):\n raise TypeError(f\"Can not compare MTLocation with {type(other)}\")\n\n for key in self._key_attrs:\n og_value = getattr(self, key)\n other_value = getattr(other, key)\n\n if isinstance(og_value, float):\n if not np.isclose(og_value, other_value):\n self.logger.info(\n f\"{key} not equal {og_value} != {other_value}\"\n )\n return False\n else:\n if not og_value == other_value:\n self.logger.info(\n f\"{key} not equal {og_value} != {other_value}\"\n )\n return False\n return True\n\n def copy(self):\n copied = type(self)()\n copied._survey_metadata = self._survey_metadata.copy()\n # not sure why this is needed, survey metadata copies fine, but here\n # it does not.\n if len(copied._survey_metadata.stations) == 0:\n copied._survey_metadata.add_station(\n self._survey_metadata.stations[0]\n )\n for key in self._key_attrs:\n setattr(copied, key, deepcopy(getattr(self, key)))\n\n return copied\n\n @property\n def datum_crs(self):\n if self._datum_crs is not None:\n return self._datum_crs\n\n @property\n def datum_name(self):\n if self._datum_crs is not None:\n return self._datum_crs.name\n\n @property\n def datum_epsg(self):\n if self._datum_crs is not None:\n return self._datum_crs.to_epsg()\n\n @datum_epsg.setter\n def datum_epsg(self, value):\n if value not in [\"\", None, \"None\"]:\n self.datum_crs = value\n\n @datum_crs.setter\n def datum_crs(self, value):\n if value in [None, \"None\", \"none\", \"null\", \"\"]:\n return\n\n new_crs = CRS.from_user_input(value)\n\n if new_crs != self._datum_crs:\n if (\n self._datum_crs is not None\n and self.latitude != 0\n and self.longitude != 0\n ):\n (\n self._survey_metadata.stations[0].location.longitude,\n self._survey_metadata.stations[0].location.latitude,\n ) = project_point(\n self.longitude, self.latitude, self._datum_crs, new_crs\n )\n\n self._east, self._north = project_point(\n self.longitude, self.latitude, new_crs, self.utm_crs\n )\n\n elif (\n self.datum_crs is not None\n and self.east != 0\n and self.north != 0\n and self.latitude == 0\n and self.longitude == 0\n ):\n (\n self._survey_metadata.stations[0].location.longitude,\n self._survey_metadata.stations[0].location.latitude,\n ) = project_point(\n self.east,\n self.north,\n self.utm_crs,\n new_crs,\n )\n self._datum_crs = new_crs\n\n @property\n def utm_crs(self):\n if self._utm_crs is not None:\n return self._utm_crs\n\n @property\n def utm_name(self):\n if self._utm_crs is not None:\n return self._utm_crs.name\n\n @property\n def utm_epsg(self):\n if self._utm_crs is not None:\n return self._utm_crs.to_epsg()\n\n @utm_epsg.setter\n def utm_epsg(self, value):\n if value not in [\"\", None, \"None\"]:\n self.utm_crs = value\n\n @property\n def utm_zone(self):\n if self._utm_crs is not None:\n return self._utm_crs.utm_zone\n\n @utm_crs.setter\n def utm_crs(self, value):\n if value in [None, \"None\", \"none\", \"null\", \"\"]:\n return\n\n new_crs = CRS.from_user_input(value)\n if value != self._utm_crs:\n # reproject easting, northing to new zone\n if (\n self._utm_crs is not None\n and self.east != 0\n and self.north != 0\n ):\n self._east, self._north = project_point(\n self.east, self.north, self._utm_crs, new_crs\n )\n\n if (\n self.datum_crs is not None\n and self.east != 0\n and self.north != 0\n ):\n # reproject lat and lon base on new UTM datum\n (\n self._survey_metadata.stations[0].location.longitude,\n self._survey_metadata.stations[0].location.latitude,\n ) = project_point(\n self.east,\n self.north,\n new_crs,\n self.datum_crs,\n )\n\n # if east and north == 0 and lat and lon != 0 project to utm\n elif (\n self.datum_crs is not None\n and self.east == 0\n and self.north == 0\n and self.latitude != 0\n and self.longitude != 0\n ):\n self._east, self._north = project_point(\n self.longitude,\n self.latitude,\n self.datum_crs,\n new_crs,\n )\n\n self._utm_crs = new_crs\n\n @property\n def east(self):\n \"\"\"easting\"\"\"\n return self._east\n\n @east.setter\n def east(self, value):\n \"\"\"set east\"\"\"\n self._east = value\n if (\n self.datum_crs is not None\n and self.utm_crs is not None\n and self._north != 0\n ):\n (\n self._survey_metadata.stations[0].location.longitude,\n self._survey_metadata.stations[0].location.latitude,\n ) = project_point(\n self._east, self._north, self.utm_crs, self.datum_crs\n )\n\n @property\n def north(self):\n \"\"\"northing\"\"\"\n return self._north\n\n @north.setter\n def north(self, value):\n \"\"\"set north\"\"\"\n self._north = value\n if (\n self.datum_crs is not None\n and self.utm_crs is not None\n and self._east != 0\n ):\n (\n self._survey_metadata.stations[0].location.longitude,\n self._survey_metadata.stations[0].location.latitude,\n ) = project_point(\n self._east, self._north, self.utm_crs, self.datum_crs\n )\n\n @property\n def latitude(self):\n return self._survey_metadata.stations[0].location.latitude\n\n @latitude.setter\n def latitude(self, lat):\n self._survey_metadata.stations[0].location.latitude = lat\n if (\n self.utm_crs is not None\n and self.datum_crs is not None\n and self._survey_metadata.stations[0].location.longitude != 0\n ):\n self._east, self._north = project_point(\n self._survey_metadata.stations[0].location.longitude,\n self._survey_metadata.stations[0].location.latitude,\n self.datum_crs,\n self.utm_crs,\n )\n\n @property\n def longitude(self):\n return self._survey_metadata.stations[0].location.longitude\n\n @longitude.setter\n def longitude(self, lon):\n self._survey_metadata.stations[0].location.longitude = lon\n if (\n self.utm_crs is not None\n and self.datum_crs is not None\n and self._survey_metadata.stations[0].location.latitude != 0\n ):\n self._east, self._north = project_point(\n self._survey_metadata.stations[0].location.longitude,\n self._survey_metadata.stations[0].location.latitude,\n self.datum_crs,\n self.utm_crs,\n )\n\n @property\n def elevation(self):\n return self._survey_metadata.stations[0].location.elevation\n\n @elevation.setter\n def elevation(self, elev):\n self._survey_metadata.stations[0].location.elevation = elev\n\n @property\n def model_east(self):\n return self._model_east\n\n @model_east.setter\n def model_east(self, value):\n try:\n self._model_east = float(value)\n except (TypeError, ValueError):\n raise ValueError(f\"Input should be a float not type {type(value)}\")\n\n @property\n def model_north(self):\n return self._model_north\n\n @model_north.setter\n def model_north(self, value):\n try:\n self._model_north = float(value)\n except (TypeError, ValueError):\n raise ValueError(f\"Input should be a float not type {type(value)}\")\n\n @property\n def model_elevation(self):\n return self._model_elevation\n\n @model_elevation.setter\n def model_elevation(self, value):\n try:\n self._model_elevation = float(value)\n except (TypeError, ValueError):\n raise ValueError(f\"Input should be a float not type {type(value)}\")\n\n def compute_model_location(self, center_location):\n \"\"\"\n compute model location based on model center and model epsg\n\n :param model_center: DESCRIPTION\n :type model_center: TYPE\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n self.model_east = self.east - center_location.model_east\n self.model_north = self.north - center_location.model_north\n self.model_elevation = self.elevation - center_location.model_elevation\n\n def project_onto_profile_line(self, profile_slope, profile_intersection):\n \"\"\"\n\n :param profile_slope: DESCRIPTION\n :type profile_slope: TYPE\n :param profile_intersection: DESCRIPTION\n :type profile_intersection: TYPE\n :param units: DESCRIPTION, defaults to \"deg\"\n :type units: TYPE, optional\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n if self.utm_crs is None:\n raise ValueError(\n \"utm_crs is None, cannot project onto profile line.\"\n )\n\n profile_vector = np.array([1, profile_slope], dtype=float)\n profile_vector /= np.linalg.norm(profile_vector)\n\n station_vector = np.array(\n [self.east, self.north - profile_intersection]\n )\n\n self.profile_offset = np.linalg.norm(\n np.dot(profile_vector, station_vector) * profile_vector\n )\n\n def get_elevation_from_national_map(self):\n \"\"\"\n Get elevation from DEM data of the US National Map. Plan to extend\n this to the globe.\n\n Pulls data from the USGS national map DEM\n\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n elev = get_nm_elev(self.latitude, self.longitude)\n if elev != 0:\n self.elevation = elev\n else:\n self.logger.warning(\n \"Could not get elevation data, not setting elevation\"\n )" }, { "identifier": "MTStations", "path": "mtpy/core/mt_stations.py", "snippet": "class MTStations:\n \"\"\"\n Object to deal with station location and geographic projection.\n\n Geographic projections are done using pyproj.CRS objects.\n\n Takes in a list of :class:`mtpy.core.mt.MT` objects which are inherit\n :class:`mtpy.core.mt_location.MTLocation` objects, which deal with\n transformation of point data using pyproj.\n\n \"\"\"\n\n def __init__(self, utm_epsg, datum_epsg=None, **kwargs):\n self.logger = logger\n\n self.dtype = dict(\n [\n (\"survey\", \"U50\"),\n (\"station\", \"U50\"),\n (\"latitude\", float),\n (\"longitude\", float),\n (\"elevation\", float),\n (\"datum_epsg\", \"U6\"),\n (\"east\", float),\n (\"north\", float),\n (\"utm_epsg\", \"U6\"),\n (\"model_east\", float),\n (\"model_north\", float),\n (\"model_elevation\", float),\n (\"profile_offset\", float),\n ]\n )\n self._datum_crs = CRS.from_epsg(4326)\n self._utm_crs = None\n self._center_lat = None\n self._center_lon = None\n self._center_elev = 0.0\n self.shift_east = 0\n self.shift_north = 0\n self.rotation_angle = 0.0\n self.mt_list = None\n self.utm_epsg = utm_epsg\n\n for key in list(kwargs.keys()):\n if hasattr(self, key):\n setattr(self, key, kwargs[key])\n\n if self.mt_list is not None:\n if len(self.mt_list) > 0:\n self.compute_relative_locations()\n self.station_locations\n\n def __str__(self):\n if self.mt_list is None:\n return \"\"\n elif len(self.mt_list) == 0:\n return \"\"\n\n fmt_dict = dict(\n [\n (\"survey\", \"<8\"),\n (\"station\", \"<8\"),\n (\"latitude\", \"<10.4f\"),\n (\"longitude\", \"<10.4f\"),\n (\"elevation\", \"<8.2f\"),\n (\"model_east\", \"<13.2f\"),\n (\"model_north\", \"<13.2f\"),\n (\"model_elevation\", \"<13.2f\"),\n (\"profile_offset\", \"<13.2f\"),\n (\"east\", \"<12.2f\"),\n (\"north\", \"<12.2f\"),\n (\"utm_epsg\", \"<6\"),\n (\"datum_epsg\", \"<6\"),\n ]\n )\n lines = [\" \".join([n for n in self.station_locations.columns])]\n lines.append(\"-\" * 72)\n for row in self.station_locations.itertuples():\n l = []\n for key in self.station_locations.columns:\n l.append(f\"{getattr(row, key):{fmt_dict[key]}}\")\n lines.append(\"\".join(l))\n\n lines.append(\"\\nModel Center:\")\n l = []\n for n in [\n \"latitude\",\n \"longitude\",\n \"elevation\",\n \"east\",\n \"north\",\n \"utm_epsg\",\n ]:\n l.append(f\"{getattr(self.center_point, n):{fmt_dict[n]}}\")\n lines.append(\"\".join(l))\n\n lines.append(\"\\nMean Values:\")\n l = []\n for n in [\"latitude\", \"longitude\", \"elevation\", \"east\", \"north\"]:\n l.append(f\"{self.station_locations[n].mean():{fmt_dict[n]}}\")\n\n return \"\\n\".join(lines)\n\n def __repr__(self):\n return self.__str__()\n\n def __eq__(self, other):\n if not isinstance(other, MTStations):\n raise TypeError(f\"Can not compare {type(other)} to MTStations\")\n\n if not (self.station_locations == other.station_locations).all().all():\n return False\n\n if not self.center_point == other.center_point:\n return False\n\n return True\n\n def __len__(self):\n if self.mt_list is None:\n return 0\n else:\n return len(self.mt_list)\n\n def copy(self):\n \"\"\"\n create a deep copy of the MTStations object.\n\n .. note:: At the moment this is very slow because it is making a lot\n of deep copies. Use sparingly.\n\n :return: deep copy of MTStation object\n :rtype: :class:`mtpy.core.mt_stations.MTStations`\n\n \"\"\"\n\n if self.mt_list is not None:\n mt_list_copy = [m.copy() for m in self.mt_list]\n else:\n mt_list_copy = None\n copied = MTStations(None, mt_list=mt_list_copy)\n for key in [\n \"utm_crs\",\n \"datum_crs\",\n \"_center_lat\",\n \"_center_lon\",\n \"_center_elev\",\n \"shift_east\",\n \"shift_north\",\n \"rotation_angle\",\n ]:\n setattr(copied, key, deepcopy(getattr(self, key)))\n\n return copied\n\n @property\n def model_epsg(self):\n \"\"\"\n\n :return: model epsg number from the model_crs object\n :rtype: int\n\n \"\"\"\n return self.utm_epsg\n\n @model_epsg.setter\n def model_epsg(self, value):\n \"\"\"\n\n :param value: EPSG number for the model\n :type value: integer or string\n\n \"\"\"\n self.utm_epsg = value\n\n @property\n def utm_crs(self):\n \"\"\"\n\n :return: UTM CRS object\n :rtype: :class:`pyproj.CRS`\n\n \"\"\"\n if self._utm_crs is not None:\n return self._utm_crs\n\n @property\n def utm_name(self):\n \"\"\"\n\n :return: UTM CRS name\n :rtype: string\n\n \"\"\"\n if self._utm_crs is not None:\n return self._utm_crs.name\n\n @property\n def utm_epsg(self):\n \"\"\"\n\n :return: UTM EPSG number\n :rtype: int\n\n \"\"\"\n if self._utm_crs is not None:\n return self._utm_crs.to_epsg()\n\n @utm_epsg.setter\n def utm_epsg(self, value):\n \"\"\"\n\n :param value: EPSG number\n :type value: int or str\n\n \"\"\"\n self.utm_crs = value\n\n @property\n def utm_zone(self):\n \"\"\"\n\n :return: UTM Zone number\n :rtype: str\n\n \"\"\"\n if self._utm_crs is not None:\n return self._utm_crs.utm_zone\n\n @utm_crs.setter\n def utm_crs(self, value):\n \"\"\"\n\n :param value: UTM CRS object, EPSG number, proj4 string\n :type value: :class:`pyproj.CRS`, int, str\n\n \"\"\"\n if value in [None, \"None\", \"none\", \"null\"]:\n return\n\n self._utm_crs = CRS.from_user_input(value)\n if self.mt_list is not None:\n for mt_obj in self.mt_list:\n mt_obj.utm_crs = value\n\n @property\n def datum_crs(self):\n \"\"\"\n\n :return: Datum CRS object\n :rtype: :class:`pyproj.CRS`\n\n \"\"\"\n if self._datum_crs is not None:\n return self._datum_crs\n\n @property\n def datum_name(self):\n \"\"\"\n\n :return: Datum well known name\n :rtype: str\n\n \"\"\"\n if self._datum_crs is not None:\n return self._datum_crs.name\n\n @property\n def datum_epsg(self):\n \"\"\"\n\n :return: Datum EPSG number\n :rtype: int\n\n \"\"\"\n if self._datum_crs is not None:\n return self._datum_crs.to_epsg()\n\n @datum_epsg.setter\n def datum_epsg(self, value):\n \"\"\"\n\n :param value: Datum EPSG number\n :type value: int or str\n\n \"\"\"\n self.datum_crs = value\n\n @datum_crs.setter\n def datum_crs(self, value):\n \"\"\"\n set the model epsg number an project east, north\n\n :param value: Datum CRS object, EPSG number, proj4 string\n :type value: :class:`pyproj.CRS`, int, str\n \"\"\"\n if value in [None, \"None\", \"none\", \"null\"]:\n return\n\n self._datum_crs = CRS.from_user_input(value)\n if self.mt_list is not None:\n for mt_obj in self.mt_list:\n mt_obj.datum_crs = value\n\n @property\n def station_locations(self):\n \"\"\"\n\n :return: Dataframe of station location information\n :rtype: :class:`pandas.DataFrame`\n\n \"\"\"\n\n # make a structured array to put station location information into\n if self.mt_list is None:\n return\n\n entries = dict(\n [\n (col, np.zeros(len(self.mt_list), dtype))\n for col, dtype in self.dtype.items()\n ]\n )\n # get station locations in meters\n for ii, mt_obj in enumerate(self.mt_list):\n entries[\"survey\"][ii] = mt_obj.survey\n entries[\"station\"][ii] = mt_obj.station\n entries[\"latitude\"][ii] = mt_obj.latitude\n entries[\"longitude\"][ii] = mt_obj.longitude\n entries[\"elevation\"][ii] = mt_obj.elevation\n entries[\"datum_epsg\"][ii] = mt_obj.datum_epsg\n entries[\"east\"][ii] = mt_obj.east\n entries[\"north\"][ii] = mt_obj.north\n entries[\"utm_epsg\"][ii] = mt_obj.utm_epsg\n entries[\"model_east\"][ii] = mt_obj.model_east\n entries[\"model_north\"][ii] = mt_obj.model_north\n entries[\"model_elevation\"][ii] = mt_obj.model_elevation\n entries[\"profile_offset\"][ii] = mt_obj.profile_offset\n\n station_df = pd.DataFrame(entries)\n self.datum_epsg = self._validate_epsg(station_df, key=\"datum\")\n self.utm_epsg = self._validate_epsg(station_df, key=\"utm\")\n\n return station_df\n\n def _validate_epsg(self, df, key=\"datum\"):\n \"\"\"\n Make sure that there is only one EPSG number for each of the Datum\n and UTM. If there are more than one use the median value or the\n first in a unique list of EPSG numbers\n\n :param df: station_location dataframe\n :type df: :class:`pandas.DataFrame`\n :return: EPSG number\n :rtype: int\n\n \"\"\"\n\n key = f\"{key}_epsg\"\n if len(df[key].unique()) > 1:\n epsg = df[key].astype(int).median()\n self.logger.warning(\n f\"Found more than one {key} number, using median EPSG number {epsg}\"\n )\n return epsg\n else:\n if getattr(self, key) is None:\n epsg = df[key].unique()[0]\n if epsg in [None, \"None\", \"none\", \"NONE\", \"null\"]:\n return None\n return int(epsg)\n\n def compute_relative_locations(self):\n \"\"\"\n Calculate model station locations relative to the center point in meters.\n\n Uses `mtpy.core.MTLocation.compute_model_location` to calculate the\n relative distance.\n\n Computes inplace.\n\n \"\"\"\n\n for mt_obj in self.mt_list:\n mt_obj.compute_model_location(self.center_point)\n\n # make center point a get property, can't set it.\n @property\n def center_point(self):\n \"\"\"\n calculate the center point from the given station locations\n\n If _center attributes are set, that is returned as the center point.\n\n Otherwise, looks for non-zero locations in E-N first, then Lat/Lon and\n estimates the center point as (max - min) / 2.\n\n :return: Center point\n :rtype: :class:`mtpy.core.MTLocation`\n\n \"\"\"\n\n center_location = MTLocation()\n if self._center_lat is not None and self._center_lon is not None:\n self.logger.debug(\"assigning center from user set values\")\n center_location.latitude = self._center_lat\n center_location.longitude = self._center_lon\n center_location.elevation = self._center_elev\n center_location.utm_epsg = self.utm_epsg\n center_location.model_east = center_location.east\n center_location.model_north = center_location.north\n center_location.model_elevation = self._center_elev\n\n return center_location\n\n else:\n center_location.datum_epsg = self.datum_epsg\n center_location.utm_epsg = self.utm_epsg\n st_df = self.station_locations.copy()\n\n st_en = st_df.loc[(st_df.east != 0) & (st_df.north != 0)]\n if st_en.empty:\n st_ll = st_df.loc[\n (st_df.latitude != 0) & (st_df.longitude != 0)\n ]\n if st_ll.empty:\n raise ValueError(\n \"Station locations are all 0 cannot find center.\"\n )\n\n else:\n self.logger.debug(\n \"locating center from latitude and longitude\"\n )\n center_location.latitude = (\n st_ll.latitude.max() + st_ll.latitude.min()\n ) / 2\n center_location.longitude = (\n st_ll.longitude.max() + st_ll.longitude.min()\n ) / 2\n\n else:\n self.logger.debug(\"locating center from UTM grid\")\n center_location.east = (\n st_en.east.max() + st_en.east.min()\n ) / 2\n center_location.north = (\n st_en.north.max() + st_en.north.min()\n ) / 2\n\n center_location.model_east = center_location.east\n center_location.model_north = center_location.north\n center_location.model_elevation = self._center_elev\n\n return center_location\n\n def rotate_stations(self, rotation_angle):\n \"\"\"\n Rotate stations model postions only assuming N is 0 and east is 90.\n\n .. note:: Computes in place and rotates according to already set\n rotation angle. Therefore if the station locations have already been\n rotated the function will rotate the already rotate stations. For\n example if you rotate the stations 15 degrees, then again by 20 degrees\n the resulting station locations will be 35 degrees rotated from the\n original locations.\n\n :param rotation_angle: rotation angle in degrees assuming N=0, E=90.\n Positive clockwise.\n :type rotation_angle: float\n\n \"\"\"\n\n cos_ang = np.cos(np.deg2rad(rotation_angle))\n sin_ang = np.sin(np.deg2rad(rotation_angle))\n rot_matrix = np.array([[cos_ang, sin_ang], [-sin_ang, cos_ang]])\n\n for mt_obj in self.mt_list:\n coords = np.array(\n [\n mt_obj.model_east,\n mt_obj.model_north,\n ]\n )\n\n # rotate the relative station locations\n new_coords = np.array(np.dot(rot_matrix, coords))\n\n mt_obj.model_east = new_coords[0]\n mt_obj.model_north = new_coords[1]\n\n self.rotation_angle += rotation_angle\n\n self.logger.info(\n f\"Rotated stations by {rotation_angle:.1f} deg clockwise from N. \"\n f\"Total rotation = {self.rotation_angle:.1f} deg.\"\n )\n\n def center_stations(self, model_obj):\n \"\"\"\n Center station locations to the middle of cells, is useful for\n topography cause it reduces edge effects of stations close to cell edges.\n Recalculates rel_east, rel_north to center of model cell.\n\n :param model_obj: :class:`mtpy.modeling.Structured` object of the model\n :type model_obj: :class:`mtpy.modeling.modem.Model`\n\n\n \"\"\"\n\n for mt_obj in self.mt_list:\n e_index = (\n np.where(model_obj.grid_east >= mt_obj.model_east)[0][0] - 1\n )\n n_index = (\n np.where(model_obj.grid_north >= mt_obj.model_north)[0][0] - 1\n )\n\n mt_obj.model_east = model_obj.grid_east[\n e_index : e_index + 2\n ].mean()\n mt_obj.model_north = model_obj.grid_north[\n n_index : n_index + 2\n ].mean()\n\n def project_stations_on_topography(\n self,\n model_object,\n air_resistivity=1e12,\n sea_resistivity=0.3,\n ocean_bottom=False,\n ):\n \"\"\"\n Project stations on topography of a given model\n\n :param model_obj: :class:`mtpy.modeling.modem.Model` object of the model\n :type model_obj: :class:`mtpy.modeling.modem.Model`\n :param air_resistivity: resistivity value of air cells in the model\n :type air_resistivity: float\n :param sea_resistivity: resistivity of sea\n :type sea_resistivity: float\n :param ocean_bottom: If True places stations at bottom of sea cells\n :type ocean_bottom: boolean\n\n Recaluclates rel_elev\n \"\"\"\n\n # find index of each station on grid\n for mt_obj in self.mt_list:\n # relative locations of stations\n sx = mt_obj.model_east\n sy = mt_obj.model_north\n\n # indices of stations on model grid\n sxi = np.where(\n (sx <= model_object.grid_east[1:])\n & (sx > model_object.grid_east[:-1])\n )[0][0]\n\n syi = np.where(\n (sy <= model_object.grid_north[1:])\n & (sy > model_object.grid_north[:-1])\n )[0][0]\n\n # first, check if there are any air cells\n if np.any(\n model_object.res_model[syi, sxi] > 0.95 * air_resistivity\n ):\n szi = np.amin(\n np.where(\n (\n model_object.res_model[syi, sxi]\n < 0.95 * air_resistivity\n )\n )[0]\n )\n # otherwise place station at the top of the model\n else:\n szi = 0\n\n # JP: estimate ocean bottom stations if requested\n if ocean_bottom:\n if np.any(model_object.res_model[syi, sxi] <= sea_resistivity):\n szi = np.amax(\n np.where(\n (\n model_object.res_model[syi, sxi]\n <= sea_resistivity\n )\n )[0]\n )\n\n # get relevant grid point elevation\n topoval = model_object.grid_z[szi]\n\n # update elevation in station locations and data array, +1 m as\n # data elevation needs to be below the topography (as advised by Naser)\n mt_obj.model_elevation = topoval + 0.001\n\n # BM: After applying topography, center point of grid becomes\n # highest point of surface model.\n self._center_elev = model_object.grid_z[0]\n\n def to_geopd(self):\n \"\"\"\n create a geopandas dataframe\n\n :return: Geopandas DataFrame with points from latitude and longitude\n :rtype: :class:`geopandas.DataFrame`\n\n \"\"\"\n\n gdf = gpd.GeoDataFrame(\n self.station_locations,\n geometry=gpd.points_from_xy(\n self.station_locations.longitude,\n self.station_locations.latitude,\n ),\n crs=self.center_point.datum_crs,\n )\n\n return gdf\n\n def to_shp(self, shp_fn):\n \"\"\"\n Write a shape file of the station locations using geopandas which only takes\n in epsg numbers\n\n :param shp_fn: full path to new shapefile\n :type shp_fn: string\n\n \"\"\"\n sdf = self.to_geopd()\n\n sdf.to_file(shp_fn)\n return shp_fn\n\n def to_csv(self, csv_fn, geometry=False):\n \"\"\"\n Write a shape file of the station locations using geopandas which only takes\n in epsg numbers\n\n :param csv_fn: full path to new shapefile\n :type csv_fn: string\n\n \"\"\"\n sdf = self.to_geopd()\n use_columns = list(sdf.columns)\n if not geometry:\n use_columns.remove(\"geometry\")\n sdf.to_csv(csv_fn, index=False, columns=use_columns)\n\n def to_vtk(\n self,\n vtk_fn=None,\n vtk_save_path=None,\n vtk_fn_basename=\"ModEM_stations\",\n geographic=False,\n shift_east=0,\n shift_north=0,\n shift_elev=0,\n units=\"km\",\n coordinate_system=\"nez+\",\n ):\n \"\"\"\n\n :param vtk_save_path: directory to save vtk file to, defaults to None\n :type vtk_save_path: string or Path, optional\n :param vtk_fn_basename: filename basename of vtk file, note that .vtr\n extension is automatically added, defaults to \"ModEM_stations\"\n :type vtk_fn_basename: string, optional\n :param geographic: If true puts the grid on geographic coordinates based\n on the model_utm_zone, defaults to False\n :type geographic: boolean, optional\n :param shift_east: shift in east directions in meters, defaults to 0\n :type shift_east: float, optional\n :param shift_north: shift in north direction in meters, defaults to 0\n :type shift_north: float, optional\n :param shift_elev: shift in elevation + down in meters, defaults to 0\n :type shift_elev: float, optional\n :param units: Units of the spatial grid [ km | m | ft ], defaults to \"km\"\n :type units: string, optional\n :type : string\n :param coordinate_system: coordinate system for the station, either the\n normal MT right-hand coordinate system with z+ down or the sinister\n z- down [ nez+ | enz- ], defaults to nez+\n :return: full path to VTK file\n :rtype: Path\n\n Write VTK file\n >>> md.write_vtk_station_file(vtk_fn_basename=\"modem_stations\")\n\n Write VTK file in geographic coordinates\n >>> md.write_vtk_station_file(vtk_fn_basename=\"modem_stations\",\n >>> ... geographic=True)\n\n Write VTK file in geographic coordinates with z+ up\n >>> md.write_vtk_station_file(vtk_fn_basename=\"modem_stations\",\n >>> ... geographic=True,\n >>> ... coordinate_system='enz-')\n\n \"\"\"\n\n if isinstance(units, str):\n if units.lower() == \"km\":\n scale = 1.0 / 1000.00\n elif units.lower() == \"m\":\n scale = 1.0\n elif units.lower() == \"ft\":\n scale = 3.2808\n elif isinstance(units, (int, float)):\n scale = units\n\n if vtk_fn is None:\n if vtk_save_path is None:\n raise ValueError(\"Need to input vtk_save_path\")\n vtk_fn = Path(vtk_save_path, vtk_fn_basename)\n else:\n vtk_fn = Path(vtk_fn)\n\n if vtk_fn.suffix != \"\":\n vtk_fn = vtk_fn.parent.joinpath(vtk_fn.stem)\n\n sdf = self.station_locations.copy()\n\n if not geographic:\n if coordinate_system == \"nez+\":\n vtk_x = (sdf.model_north + shift_north) * scale\n vtk_y = (sdf.model_east + shift_east) * scale\n vtk_z = (sdf.model_elevation + shift_elev) * scale\n extra = (sdf.model_elevation + shift_elev) * scale\n elif coordinate_system == \"enz-\":\n vtk_x = (sdf.model_north + shift_north) * scale\n vtk_y = (sdf.model_east + shift_east) * scale\n vtk_z = -1 * (sdf.model_elevation + shift_elev) * scale\n extra = -1 * (sdf.model_elevation + shift_elev) * scale\n\n else:\n if coordinate_system == \"nez+\":\n vtk_y = (sdf.north + shift_north) * scale\n vtk_x = (sdf.east + shift_east) * scale\n vtk_z = -1 * (sdf.elevation + shift_elev) * scale\n extra = -1 * (sdf.elevation + shift_elev)\n elif coordinate_system == \"enz-\":\n vtk_y = (sdf.north + shift_north) * scale\n vtk_x = (sdf.east + shift_east) * scale\n vtk_z = (sdf.elevation + shift_elev) * scale\n extra = sdf.elevation + shift_elev\n\n # write file\n pointsToVTK(\n vtk_fn.as_posix(),\n vtk_x.to_numpy(),\n vtk_y.to_numpy(),\n vtk_z.to_numpy(),\n data={\"elevation\": extra.to_numpy()},\n )\n\n self.logger.info(f\"Wrote station VTK file to {vtk_fn}.vtu\")\n return vtk_fn\n\n def generate_profile(self, units=\"deg\"):\n \"\"\"\n Estimate a profile from the data\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n if units == \"deg\":\n x = self.station_locations.longitude\n y = self.station_locations.latitude\n\n elif units == \"m\":\n if self.utm_crs is not None:\n x = self.station_locations.east\n y = self.station_locations.north\n else:\n raise ValueError(\"Must input a UTM CRS or EPSG\")\n\n # check regression for 2 profile orientations:\n # horizontal (N=N(E)) or vertical(E=E(N))\n # use the one with the lower standard deviation\n profile1 = stats.linregress(x, y)\n profile2 = stats.linregress(y, x)\n # if the profile is rather E=E(N), the parameters have to converted\n # into N=N(E) form:\n if profile2.stderr < profile1.stderr:\n profile_line = {\n \"slope\": 1.0 / profile2.slope,\n \"intercept\": -profile2.intercept / profile2.slope,\n }\n else:\n profile_line = {\n \"slope\": profile1.slope,\n \"intercept\": profile1.intercept,\n }\n\n x1 = x.min()\n x2 = x.max()\n y1 = profile_line[\"slope\"] * x1 + profile_line[\"intercept\"]\n y2 = profile_line[\"slope\"] * x2 + profile_line[\"intercept\"]\n\n return x1, y1, x2, y2, profile_line\n\n def generate_profile_from_strike(self, strike, units=\"deg\"):\n \"\"\"\n Estimate a profile line from a given geoelectric strike\n\n :param units: DESCRIPTION, defaults to \"deg\"\n :type units: TYPE, optional\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n if units == \"deg\":\n x = self.station_locations.longitude\n y = self.station_locations.latitude\n\n elif units == \"m\":\n if self.utm_crs is not None:\n x = self.station_locations.east\n y = self.station_locations.north\n else:\n raise ValueError(\"Must input a UTM CRS or EPSG\")\n\n profile_line = {\"slope\": np.arctan(np.deg2rad(90 - strike))}\n profile_line[\"intercept\"] = y.min() - profile_line[\"slope\"] * x.min()\n\n x1 = x.min()\n x2 = x.max()\n y1 = profile_line[\"slope\"] * x1 + profile_line[\"intercept\"]\n y2 = profile_line[\"slope\"] * x2 + profile_line[\"intercept\"]\n\n return x1, y1, x2, y2, profile_line\n\n def _extract_profile(self, x1, y1, x2, y2, radius):\n \"\"\"\n extract stations along a profile line that lie with in the given\n radius\n\n :param point1: DESCRIPTION\n :type point1: TYPE\n :param point2: DESCRIPTION\n :type point2: TYPE\n :param radius: DESCRIPTION\n :type radius: TYPE\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n if np.abs(x2 - x1) < 100:\n if self.utm_crs is None:\n raise ValueError(\"Must input UTM CRS or EPSG.\")\n point_1 = MTLocation(\n longitude=x1, latitude=y1, utm_crs=self.utm_crs\n )\n point_2 = MTLocation(\n longitude=x2, latitude=y2, utm_crs=self.utm_crs\n )\n x1 = point_1.east\n y1 = point_1.north\n x2 = point_2.east\n y2 = point_2.north\n\n if radius is None:\n radius = 1e12\n\n def distance(x, y):\n return np.abs(\n (x2 - x1) * (y1 - y) - (x1 - x) * (y2 - y1)\n ) / np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)\n\n slope = (y2 - y1) / (x2 - x1)\n intersection = y1 - slope * x1\n\n profile_list = []\n offsets = []\n for mt_obj in self.mt_list:\n d = distance(mt_obj.east, mt_obj.north)\n\n if d <= radius:\n mt_obj.project_onto_profile_line(slope, intersection)\n profile_list.append(mt_obj)\n offsets.append(mt_obj.profile_offset)\n\n offsets = np.array(offsets)\n indexes = np.argsort(offsets)\n\n sorted_profile_list = []\n for index in indexes:\n profile_list[index].profile_offset -= offsets.min()\n sorted_profile_list.append(profile_list[index])\n\n return sorted_profile_list" }, { "identifier": "MT", "path": "mtpy/core/mt.py", "snippet": "class MT(TF, MTLocation):\n \"\"\"\n Basic MT container to hold all information necessary for a MT station\n including the following parameters.\n\n\n \"\"\"\n\n def __init__(self, fn=None, **kwargs):\n TF.__init__(self)\n MTLocation.__init__(self, survey_metadata=self._survey_metadata)\n\n # MTLocation.__init__(self)\n # TF.__init__(self)\n\n self.fn = fn\n\n self._Z = Z()\n self._Tipper = Tipper()\n self._rotation_angle = 0\n\n self.save_dir = Path.cwd()\n\n for key, value in kwargs.items():\n setattr(self, key, value)\n\n def clone_empty(self):\n \"\"\"\n copy metadata but not the transfer function estimates\n \"\"\"\n\n new_mt_obj = MT()\n new_mt_obj.survey_metadata.update(self.survey_metadata)\n new_mt_obj.station_metadata.update(self.station_metadata)\n new_mt_obj.station_metadata.runs = self.station_metadata.runs\n new_mt_obj._datum_crs = self._datum_crs\n new_mt_obj._utm_crs = self._utm_crs\n new_mt_obj._east = self._east\n new_mt_obj._north = self._north\n new_mt_obj.model_east = self.model_east\n new_mt_obj.model_north = self.model_north\n new_mt_obj.model_elevation = self.model_elevation\n new_mt_obj._rotation_angle = self._rotation_angle\n\n return new_mt_obj\n\n def __deepcopy__(self, memo):\n cls = self.__class__\n result = cls.__new__(cls)\n memo[id(self)] = result\n for k, v in self.__dict__.items():\n if k in [\"logger\"]:\n continue\n\n setattr(result, k, deepcopy(v, memo))\n return result\n\n def copy(self):\n return deepcopy(self)\n\n @property\n def rotation_angle(self):\n \"\"\"rotation angle in degrees from north\"\"\"\n return self._rotation_angle\n\n @rotation_angle.setter\n def rotation_angle(self, theta_r):\n \"\"\"\n set rotation angle in degrees assuming North is 0 measuring clockwise\n positive to East as 90.\n\n upon setting rotates Z and Tipper\n\n TODO figure this out with xarray\n \"\"\"\n\n self.rotate(theta_r)\n self._rotation_angle += theta_r\n\n def rotate(self, theta_r, inplace=True):\n \"\"\"\n Rotate the data in degrees assuming North is 0 measuring clockwise\n positive to East as 90.\n\n :param theta_r: DESCRIPTION\n :type theta_r: TYPE\n :param inplace: DESCRIPTION, defaults to True\n :type inplace: TYPE, optional\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n if inplace:\n if self.has_impedance():\n self.Z = self.Z.rotate(theta_r)\n if self.has_tipper():\n self.Tipper = self.Tipper.rotate(theta_r)\n\n self._rotation_angle = theta_r\n\n self.logger.info(\n f\"Rotated transfer function by: {self._rotation_angle:.3f} degrees clockwise\"\n )\n else:\n new_m = self.clone_empty()\n if self.has_impedance():\n new_m.Z = self.Z.rotate(theta_r)\n if self.has_tipper():\n new_m.Tipper = self.Tipper.rotate(theta_r)\n new_m._rotation_angle = self._rotation_angle\n return new_m\n\n @property\n def Z(self):\n \"\"\"mtpy.core.z.Z object to hold impedance tensor\"\"\"\n\n if self.has_impedance():\n return Z(\n z=self.impedance.to_numpy(),\n z_error=self.impedance_error.to_numpy(),\n frequency=self.frequency,\n z_model_error=self.impedance_model_error.to_numpy(),\n )\n return Z()\n\n @Z.setter\n def Z(self, z_object):\n \"\"\"\n set z_object\n\n recalculate phase tensor and invariants, which shouldn't change except\n for strike angle\n \"\"\"\n if not isinstance(z_object.frequency, type(None)):\n if self.frequency.size != z_object.frequency.shape:\n self.frequency = z_object.frequency\n\n elif not (self.frequency == z_object.frequency).all():\n self.frequency = z_object.frequency\n self.impedance = z_object.z\n self.impedance_error = z_object.z_error\n self.impedance_model_error = z_object.z_model_error\n\n @property\n def Tipper(self):\n \"\"\"mtpy.core.z.Tipper object to hold tipper information\"\"\"\n\n if self.has_tipper():\n return Tipper(\n tipper=self.tipper.to_numpy(),\n tipper_error=self.tipper_error.to_numpy(),\n frequency=self.frequency,\n tipper_model_error=self.tipper_model_error.to_numpy(),\n )\n\n @Tipper.setter\n def Tipper(self, t_object):\n \"\"\"\n set tipper object\n\n recalculate tipper angle and magnitude\n \"\"\"\n\n if t_object is None:\n return\n\n if not isinstance(t_object.frequency, type(None)):\n if not (self.frequency == t_object.frequency).all():\n self.frequency = t_object.frequency\n self.tipper = t_object.tipper\n self.tipper_error = t_object.tipper_error\n self.tipper_model_error = t_object.tipper_model_error\n\n @property\n def pt(self):\n \"\"\"mtpy.analysis.pt.PhaseTensor object to hold phase tensor\"\"\"\n return self.Z.phase_tensor\n\n @property\n def ex_metadata(self):\n \"\"\"EX metadata\"\"\"\n return self.station_metadata.runs[0].ex\n\n @ex_metadata.setter\n def ex_metadata(self, value):\n \"\"\"set EX metadata\"\"\"\n self.station_metadata.runs[0].ex = value\n\n @property\n def ey_metadata(self):\n \"\"\"EY metadata\"\"\"\n return self.station_metadata.runs[0].ey\n\n @ey_metadata.setter\n def ey_metadata(self, value):\n \"\"\"set EY metadata\"\"\"\n self.station_metadata.runs[0].ey = value\n\n @property\n def hx_metadata(self):\n \"\"\"HX metadata\"\"\"\n return self.station_metadata.runs[0].hx\n\n @hx_metadata.setter\n def hx_metadata(self, value):\n \"\"\"set hx metadata\"\"\"\n self.station_metadata.runs[0].hx = value\n\n @property\n def hy_metadata(self):\n \"\"\"HY metadata\"\"\"\n return self.station_metadata.runs[0].hy\n\n @hy_metadata.setter\n def hy_metadata(self, value):\n \"\"\"set hy metadata\"\"\"\n self.station_metadata.runs[0].hy = value\n\n @property\n def hz_metadata(self):\n \"\"\"HZ metadata\"\"\"\n return self.station_metadata.runs[0].hz\n\n @hz_metadata.setter\n def hz_metadata(self, value):\n \"\"\"set hz metadata\"\"\"\n self.station_metadata.runs[0].hz = value\n\n @property\n def rrhx_metadata(self):\n \"\"\"RRHX metadata\"\"\"\n return self.station_metadata.runs[0].rrhx\n\n @property\n def rrhy_metadata(self):\n \"\"\"RRHY metadata\"\"\"\n return self.station_metadata.runs[0].rrhy\n\n def remove_distortion(\n self, n_frequencies=None, comp=\"det\", only_2d=False, inplace=False\n ):\n \"\"\"\n remove distortion following Bibby et al. [2005].\n\n :param n_frequencies: number of frequencies to look for distortion from the\n highest frequency\n :type n_frequencies: int\n\n :returns: Distortion matrix\n :rtype: np.ndarray(2, 2, dtype=real)\n\n :returns: Z with distortion removed\n :rtype: mtpy.core.z.Z\n\n :Remove distortion and write new .edi file: ::\n\n >>> import mtpy.core.mt as mt\n >>> mt1 = mt.MT(fn=r\"/home/mt/edi_files/mt01.edi\")\n >>> D, new_z = mt1.remove_distortion()\n >>> mt1.write_mt_file(new_fn=r\"/home/mt/edi_files/mt01_dr.edi\",\\\n >>> new_Z=new_z)\n\n \"\"\"\n if inplace:\n self.Z = self.Z.remove_distortion(\n n_frequencies=n_frequencies,\n comp=comp,\n only_2d=only_2d,\n inplace=False,\n )\n else:\n new_mt = self.clone_empty()\n new_mt.Z = self.Z.remove_distortion(\n n_frequencies=n_frequencies,\n comp=comp,\n only_2d=only_2d,\n inplace=False,\n )\n new_mt.Tipper = self.Tipper\n return new_mt\n\n def remove_static_shift(self, ss_x=1.0, ss_y=1.0, inplace=False):\n \"\"\"\n Remove static shift from the apparent resistivity\n\n Assume the original observed tensor Z is built by a static shift S\n and an unperturbated \"correct\" Z0 :\n\n * Z = S * Z0\n\n therefore the correct Z will be :\n * Z0 = S^(-1) * Z\n\n\n :param ss_x: correction factor for x component\n :type ss_x: float\n\n :param ss_y: correction factor for y component\n :type ss_y: float\n\n :returns: new Z object with static shift removed\n :rtype: mtpy.core.z.Z\n\n .. note:: The factors are in resistivity scale, so the\n entries of the matrix \"S\" need to be given by their\n square-roots!\n\n :Remove Static Shift: ::\n\n >>> import mtpy.core.mt as mt\n >>> mt_obj = mt.MT(r\"/home/mt/mt01.edi\")\n >>> new_z_obj = mt.remove_static_shift(ss_x=.5, ss_y=1.2)\n >>> mt_obj.write_mt_file(new_fn=r\"/home/mt/mt01_ss.edi\",\n >>> ... new_Z_obj=new_z_obj)\n \"\"\"\n\n if inplace:\n self.Z = self.Z.remove_ss(\n reduce_res_factor_x=ss_x,\n reduce_res_factor_y=ss_y,\n inplace=inplace,\n )\n\n else:\n new_mt = self.clone_empty()\n new_mt.Z = self.Z.remove_ss(\n reduce_res_factor_x=ss_x,\n reduce_res_factor_y=ss_y,\n inplace=inplace,\n )\n new_mt.Tipper = self.Tipper\n return new_mt\n\n def interpolate(\n self,\n new_period,\n method=\"cubic\",\n bounds_error=True,\n f_type=\"period\",\n **kwargs,\n ):\n \"\"\"\n Interpolate the impedance tensor onto different frequencies\n\n :param new_period: a 1-d array of frequencies to interpolate on\n to. Must be with in the bounds of the existing frequency range,\n anything outside and an error will occur.\n :type new_period: np.ndarray\n :param method: method to interpolate by, defaults to \"cubic\"\n :type method: string, optional\n :param bounds_error: check for if input frequencies are within the\n original frequencies, defaults to True\n :type bounds_error: boolean, optional\n :param f_type: frequency type can be [ 'frequency' | 'period' ]\n :type f_type: string, defaults to 'period'\n :param **kwargs: key word arguments for `interp`\n :type **kwargs: dictionary\n :raises ValueError: If input frequencies are out of bounds\n :return: New MT object with interpolated values.\n :rtype: :class:`mtpy.core.MT`\n\n\n .. note:: 'cubic' seems to work the best, the 'slinear' seems to do\n the same as 'linear' when using the `interp` in xarray.\n\n :Interpolate over frequency: ::\n\n >>> mt_obj = MT()\n >>> new_frequency = np.logspace(-3, 3, 20)\n >>> new_mt_obj = mt_obj.interpolate(new_frequency, f_type=\"frequency\")\n\n \"\"\"\n\n if f_type not in [\"frequency\", \"freq\", \"period\", \"per\"]:\n raise ValueError(\n \"f_type must be either 'frequency' or 'period' not {f_type}\"\n )\n\n # make sure the input is a numpy array\n if not isinstance(new_period, np.ndarray):\n new_period = np.array(new_period)\n\n if f_type in [\"frequency\", \"freq\"]:\n new_period = 1.0 / new_period\n\n # check the bounds of the new frequency array\n if bounds_error:\n if self.period.min() > new_period.min():\n raise ValueError(\n f\"New period minimum of {new_period.min():.5g} \"\n \"is smaller than old period minimum of \"\n f\"{self.period.min():.5g}. The new period range \"\n \"needs to be within the bounds of the old one.\"\n )\n if self.period.max() < new_period.max():\n raise ValueError(\n f\"New period maximum of {new_period.max():.5g} \"\n \"is smaller than old frequency maximum of \"\n f\"{self.period.max():.5g}. The new period range \"\n \"needs to be within the bounds of the old one.\"\n )\n\n new_m = self.clone_empty()\n if self.has_impedance():\n new_m.Z = self.Z.interpolate(new_period, method=method, **kwargs)\n if new_m.has_impedance():\n if np.all(np.isnan(new_m.Z.z)):\n self.logger.warning(\n f\"Station {self.station}: Interpolated Z values are all NaN, \"\n \"consider an alternative interpolation method. \"\n \"See scipy.interpolate.interp1d for more information.\"\n )\n if self.has_tipper():\n new_m.Tipper = self.Tipper.interpolate(\n new_period, method=method, **kwargs\n )\n if new_m.has_tipper():\n if np.all(np.isnan(new_m.Tipper.tipper)):\n self.logger.warning(\n f\"Station {self.station}: Interpolated T values are all NaN, \"\n \"consider an alternative interpolation method. \"\n \"See scipy.interpolate.interp1d for more information.\"\n )\n\n return new_m\n\n def plot_mt_response(self, **kwargs):\n \"\"\"\n Returns a mtpy.imaging.plotresponse.PlotResponse object\n\n :Plot Response: ::\n\n >>> mt_obj = mt.MT(edi_file)\n >>> pr = mt.plot_mt_response()\n >>> # if you need more info on plot_mt_response\n >>> help(pr)\n\n \"\"\"\n\n plot_obj = PlotMTResponse(\n z_object=self.Z,\n t_object=self.Tipper,\n pt_obj=self.pt,\n station=self.station,\n **kwargs,\n )\n\n return plot_obj\n\n def plot_phase_tensor(self, **kwargs):\n \"\"\"\n\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n kwargs[\"ellipse_size\"] = 0.5\n return PlotPhaseTensor(self.pt, station=self.station, **kwargs)\n\n def plot_depth_of_penetration(self, **kwargs):\n \"\"\"\n Plot Depth of Penetration estimated from Niblett-Bostick estimation\n\n :param **kwargs: DESCRIPTION\n :type **kwargs: TYPE\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n return PlotPenetrationDepth1D(self, **kwargs)\n\n def to_dataframe(self, utm_crs=None, cols=None):\n \"\"\"\n Create a dataframe from the transfer function for use with plotting\n and modeling.\n\n :parameter utm_crs: the utm zone to project station to, could be a\n name, pyproj.CRS, EPSG number, or anything that pyproj.CRS can intake.\n :type utm_crs: string, int, :class:`pyproj.CRS`\n\n \"\"\"\n if utm_crs is not None:\n self.utm_crs = utm_crs\n\n n_entries = self.period.size\n mt_df = MTDataFrame(n_entries=n_entries)\n\n mt_df.survey = self.survey\n mt_df.station = self.station\n mt_df.latitude = self.latitude\n mt_df.longitude = self.longitude\n mt_df.elevation = self.elevation\n mt_df.datum_epsg = self.datum_epsg\n mt_df.east = self.east\n mt_df.north = self.north\n mt_df.utm_epsg = self.utm_epsg\n mt_df.model_east = self.model_east\n mt_df.model_north = self.model_north\n mt_df.model_elevation = self.model_elevation\n mt_df.profile_offset = self.profile_offset\n\n mt_df.dataframe.loc[:, \"period\"] = self.period\n if self.has_impedance():\n mt_df.from_z_object(self.Z)\n if self.has_tipper():\n mt_df.from_t_object(self.Tipper)\n\n return mt_df\n\n def from_dataframe(self, mt_df):\n \"\"\"\n fill transfer function attributes from a dataframe for a single station\n\n :param df: DESCRIPTION\n :type df: TYPE\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n if not isinstance(mt_df, MTDataFrame):\n try:\n mt_df = MTDataFrame(mt_df)\n except TypeError:\n raise TypeError(\n f\"Input dataframe must be an MTDataFrame not {type(mt_df)}\"\n )\n except ValueError as error:\n raise ValueError(error)\n\n for key in [\n \"survey\",\n \"station\",\n \"latitude\",\n \"longitude\",\n \"elevation\",\n \"east\",\n \"north\",\n \"utm_epsg\",\n \"model_north\",\n \"model_east\",\n \"model_elevation\",\n \"profile_offset\",\n ]:\n try:\n setattr(self, key, getattr(mt_df, key))\n except KeyError:\n continue\n\n self.tf_id = self.station\n\n self.Z = mt_df.to_z_object()\n self.Tipper = mt_df.to_t_object()\n\n def compute_model_z_errors(\n self, error_value=5, error_type=\"geometric_mean\", floor=True\n ):\n \"\"\"\n Compute mode errors based on the error type\n\n ========================== ===========================================\n key definition\n ========================== ===========================================\n egbert error_value * sqrt(Zxy * Zyx)\n geometric_mean error_value * sqrt(Zxy * Zyx)\n arithmetic_mean error_value * (Zxy + Zyx) / 2\n mean_od error_value * (Zxy + Zyx) / 2\n off_diagonals zxx_error == zxy_error, zyx_error == zyy_error\n median error_value * median(z)\n eigen error_value * mean(eigen(z))\n percent error_value * z\n absolute error_value\n ========================== ===========================================\n\n :param error_value: DESCRIPTION, defaults to 5\n :type error_value: TYPE, optional\n :param error_type: DESCRIPTION, defaults to \"geometric_mean\"\n :type error_type: TYPE, optional\n :param floor: DESCRIPTION, defaults to True\n :type floor: TYPE, optional\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n if not self.has_impedance():\n self.logger.warning(\n \"MT Object contains no impedance data, cannot comput errors\"\n )\n return\n\n z_model_error = ModelErrors(\n data=self.impedance,\n measurement_error=self.impedance_error,\n error_value=error_value,\n error_type=error_type,\n floor=floor,\n mode=\"impedance\",\n )\n\n err = z_model_error.compute_error()\n\n if len(err.shape) == 1:\n z_error = np.zeros_like(self.impedance, dtype=float)\n z_error[:, 0, 0] = err\n z_error[:, 0, 1] = err\n z_error[:, 1, 0] = err\n z_error[:, 1, 1] = err\n\n else:\n z_error = err\n\n self.impedance_model_error = z_error\n\n def compute_model_t_errors(\n self, error_value=0.02, error_type=\"absolute\", floor=False\n ):\n \"\"\"\n Compute mode errors based on the error type\n\n ========================== ===========================================\n key definition\n ========================== ===========================================\n percent error_value * t\n absolute error_value\n ========================== ===========================================\n\n :param error_value: DESCRIPTION, defaults to .02\n :type error_value: TYPE, optional\n :param error_type: DESCRIPTION, defaults to \"absolute\"\n :type error_type: TYPE, optional\n :param floor: DESCRIPTION, defaults to True\n :type floor: TYPE, optional\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n if not self.has_tipper():\n self.logger.warning(\n f\"MT object for {self.station} contains no Tipper, cannot \"\n \"compute model errors\"\n )\n return\n\n t_model_error = ModelErrors(\n data=self.tipper,\n measurement_error=self.tipper_error,\n error_value=error_value,\n error_type=error_type,\n floor=floor,\n mode=\"tipper\",\n )\n\n err = t_model_error.compute_error()\n\n if len(err.shape) == 1:\n t_error = np.zeros_like(self.tipper, dtype=float)\n t_error[:, 0, 0] = err\n t_error[:, 0, 1] = err\n\n else:\n t_error = err\n\n self.tipper_model_error = t_error\n\n def add_model_error(self, comp=[], z_value=5, t_value=0.05, periods=None):\n \"\"\"\n\n Add error to a station's components for given period range\n\n :param station: name of station(s) to add error to\n :type station: string or list of strings\n :param comp: list of components to add data to, valid components are\n zxx, zxy, zyx, zyy, tx, ty\n :type comp: string or list of strings\n :param periods: the period range to add to, if None all periods, otherwise\n enter as a tuple as (minimum, maximum) period in seconds\n :type periods: tuple (minimum, maxmum)\n :return: data array with added errors\n :rtype: np.ndarray\n\n >>> d = Data()\n >>> d.read_data_file(r\"example/data.dat\")\n >>> d.data = d.add_error(\"mt01\", comp=[\"zxx\", \"zxy\", \"tx\"], z_value=7, t_value=.05)\n\n \"\"\"\n c_dict = {\n \"zxx\": (0, 0),\n \"zxy\": (0, 1),\n \"zyx\": (1, 0),\n \"zyy\": (1, 1),\n \"tx\": (0, 0),\n \"ty\": (0, 1),\n }\n\n if isinstance(comp, str):\n comp = [comp]\n if periods is not None:\n if len(periods) != 2:\n msg = \"Must enter a minimum and maximum period value\"\n self.logger.error(msg)\n raise ValueError(msg)\n p_min = np.where(self.period >= min(periods))[0][0]\n p_max = np.where(self.period <= max(periods))[0][-1]\n else:\n p_min = 0\n p_max = len(self.period) - 1\n\n z_model_error = self.impedance_model_error.copy().data\n t_model_error = self.tipper_model_error.copy().data\n for cc in comp:\n try:\n ii, jj = c_dict[cc]\n except KeyError:\n msg = f\"Component {cc} is not a valid component, skipping\"\n self.logger.warning(msg)\n continue\n if \"z\" in cc:\n z_model_error[p_min:p_max, ii, jj] *= z_value\n\n elif \"t\" in cc:\n t_model_error[p_min:p_max, ii, jj] += t_value\n\n self.impedance_model_error = z_model_error\n self.tipper_model_error = t_model_error\n\n def flip_phase(\n self,\n zxx=False,\n zxy=False,\n zyx=False,\n zyy=False,\n tzx=False,\n tzy=False,\n inplace=False,\n ):\n \"\"\"\n Flip the phase of a station in case its plotting in the wrong quadrant\n\n :param station: name(s) of station to flip phase\n :type station: string or list of strings\n :param station: station name or list of station names\n :type station: string or list\n :param zxx: Z_xx, defaults to False\n :type zxx: TYPE, optional\n :param zxy: Z_xy, defaults to False\n :type zxy: TYPE, optional\n :param zyy: Z_yx, defaults to False\n :type zyy: TYPE, optional\n :param zyx: Z_yy, defaults to False\n :type zyx: TYPE, optional\n :param tx: T_zx, defaults to False\n :type tx: TYPE, optional\n :param ty: T_zy, defaults to False\n :type ty: TYPE, optional\n :return: new_data\n :rtype: np.ndarray\n :return: new mt_dict with components removed\n :rtype: dictionary\n\n >>> d = Data()\n >>> d.read_data_file(r\"example/data.dat\")\n >>> d.data, d.mt_dict = d.flip_phase(\"mt01\", comp=[\"zx\", \"tx\"])\n\n \"\"\"\n c_dict = {\n \"zxx\": {\"index\": (0, 0), \"bool\": zxx},\n \"zxy\": {\"index\": (0, 1), \"bool\": zxy},\n \"zyx\": {\"index\": (1, 0), \"bool\": zyx},\n \"zyy\": {\"index\": (1, 1), \"bool\": zyy},\n \"tzx\": {\"index\": (0, 0), \"bool\": tzx},\n \"tzy\": {\"index\": (0, 1), \"bool\": tzy},\n }\n\n z_obj = self.Z.copy()\n t_obj = self.Tipper.copy()\n\n z_change = False\n t_change = False\n for ckey, dd in c_dict.items():\n if dd[\"bool\"]:\n ii, jj = dd[\"index\"]\n if \"z\" in ckey:\n z_change = True\n try:\n z_obj.z[:, ii, jj] *= -1\n except TypeError:\n self.logger.debug(\"z is None, cannot flip\")\n try:\n z_obj.z_error[:, ii, jj] *= -1\n except TypeError:\n self.logger.debug(\"z_error is None, cannot flip\")\n try:\n z_obj.z_model_error[:, ii, jj] *= -1\n except TypeError:\n self.logger.debug(\"z_model_error is None, cannot flip\")\n\n elif \"t\" in ckey:\n t_change = True\n try:\n t_obj.tipper[:, ii, jj] *= -1\n except TypeError:\n self.logger.debug(\"tipper is None, cannot flip\")\n try:\n t_obj.tipper_error[:, ii, jj] *= -1\n except TypeError:\n self.logger.debug(\"tipper_error is None, cannot flip\")\n try:\n t_obj.tipper_model_error[:, ii, jj] *= -1\n except TypeError:\n self.logger.debug(\n \"tipper_model_error is None, cannot flip\"\n )\n if inplace:\n if z_change:\n self.Z = z_obj\n if t_change:\n self.Tipper = t_obj\n else:\n return_obj = self.copy()\n if z_change:\n return_obj.Z = z_obj\n if t_change:\n return_obj.Tipper = t_obj\n return return_obj\n\n def remove_component(\n self,\n zxx=False,\n zxy=False,\n zyy=False,\n zyx=False,\n tzx=False,\n tzy=False,\n inplace=False,\n ):\n \"\"\"\n Remove a component for a given station(s)\n\n :param station: station name or list of station names\n :type station: string or list\n :param zxx: Z_xx, defaults to False\n :type zxx: TYPE, optional\n :param zxy: Z_xy, defaults to False\n :type zxy: TYPE, optional\n :param zyy: Z_yx, defaults to False\n :type zyy: TYPE, optional\n :param zyx: Z_yy, defaults to False\n :type zyx: TYPE, optional\n :param tx: T_zx, defaults to False\n :type tx: TYPE, optional\n :param ty: T_zy, defaults to False\n :type ty: TYPE, optional\n :return: new data array with components removed\n :rtype: np.ndarray\n :return: new mt_dict with components removed\n :rtype: dictionary\n\n >>> d = Data()\n >>> d.read_data_file(r\"example/data.dat\")\n >>> d.data, d.mt_dict = d.remove_component(\"mt01\", zxx=True, tx=True)\n\n \"\"\"\n c_dict = {\n \"zxx\": {\"index\": (0, 0), \"bool\": zxx},\n \"zxy\": {\"index\": (0, 1), \"bool\": zxy},\n \"zyx\": {\"index\": (1, 0), \"bool\": zyx},\n \"zyy\": {\"index\": (1, 1), \"bool\": zyy},\n \"tzx\": {\"index\": (0, 0), \"bool\": tzx},\n \"tzy\": {\"index\": (0, 1), \"bool\": tzy},\n }\n\n z_obj = self.Z.copy()\n t_obj = self.Tipper.copy()\n\n z_change = False\n t_change = False\n for ckey, dd in c_dict.items():\n if dd[\"bool\"]:\n ii, jj = dd[\"index\"]\n if \"z\" in ckey:\n z_change = True\n try:\n z_obj.z[:, ii, jj] = 0\n except TypeError:\n self.logger.debug(\"z is None, cannot remove\")\n try:\n z_obj.z_error[:, ii, jj] = 0\n except TypeError:\n self.logger.debug(\"z_error is None, cannot remove\")\n try:\n z_obj.z_model_error[:, ii, jj] = 0\n except TypeError:\n self.logger.debug(\n \"z_model_error is None, cannot remove\"\n )\n\n elif \"t\" in ckey:\n t_change = True\n try:\n t_obj.tipper[:, ii, jj] = 0\n except TypeError:\n self.logger.debug(\"tipper is None, cannot remove\")\n try:\n t_obj.tipper_error[:, ii, jj] = 0\n except TypeError:\n self.logger.debug(\n \"tipper_error is None, cannot remove\"\n )\n try:\n t_obj.tipper_model_error[:, ii, jj] = 0\n except TypeError:\n self.logger.debug(\n \"tipper_model_error is None, cannot remove\"\n )\n\n if inplace:\n if z_change:\n self.Z = z_obj\n if t_change:\n self.Tipper = t_obj\n else:\n return_obj = self.copy()\n if z_change:\n return_obj.Z = z_obj\n if t_change:\n return_obj.Tipper = t_obj\n return return_obj\n\n def add_white_noise(self, value, inplace=True):\n \"\"\"\n Add white noise to the data, useful for synthetic tests.\n\n :param value: DESCRIPTION\n :type value: TYPE\n :param inplace: DESCRIPTION, defaults to True\n :type inplace: TYPE, optional\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n if value > 1:\n value = value / 100.0\n\n if not inplace:\n new_mt_obj = self.clone_empty()\n\n tf_shape = self._transfer_function.transfer_function.shape\n noise_real = 1 + np.random.random(tf_shape) * value * (-1) ** (\n np.random.randint(0, 3, tf_shape)\n )\n noise_imag = 1 + np.random.random(tf_shape) * value * (-1) ** (\n np.random.randint(0, 3, tf_shape)\n )\n\n if inplace:\n self._transfer_function[\n \"transfer_function\"\n ] = self._transfer_function.transfer_function.real * (\n noise_real\n ) + (\n 1j\n * self._transfer_function.transfer_function.imag\n * noise_imag\n )\n\n self._transfer_function[\"transfer_function_error\"] = (\n self._transfer_function.transfer_function_error + value\n )\n\n else:\n new_mt_obj._transfer_function = self._transfer_function.copy()\n new_mt_obj._transfer_function[\n \"transfer_function\"\n ] = self._transfer_function.transfer_function.real * (\n noise_real\n ) + (\n 1j\n * self._transfer_function.transfer_function.imag\n * noise_imag\n )\n\n self._transfer_function[\"transfer_function_error\"] = (\n self._transfer_function.transfer_function_error + value\n )\n return new_mt_obj\n\n def to_occam1d(self, data_filename=None, mode=\"det\"):\n \"\"\"\n write an Occam1DData data file\n\n :param data_filename: path to write file, if None returns Occam1DData\n object.\n :type data_filename: string or Path\n :param mode: [ 'te', 'tm', 'det', 'tez', 'tmz', 'detz'], defaults to \"det\"\n :type mode: string, optional\n :return: Occam1DData object\n :rtype: :class:`mtpy.modeling.occam1d.Occam1DData`\n\n\n :Example:\n\n >>> mt_object = MT()\n >>> mt_object.read(r\"/path/to/tranfer_function/file\")\n >>> mt_object.compute_model_z_error()\n >>> occam_data = mt_object.to_occam1d(data_filename=r\"/path/to/data_file.dat\")\n\n\n \"\"\"\n\n occam_data = Occam1DData(self.to_dataframe(), mode=mode)\n if data_filename is not None:\n occam_data.write_data_file(data_filename)\n\n return occam_data\n\n def to_simpeg_1d(self, mode=\"det\", **kwargs):\n \"\"\"\n helper method to run a 1D inversion using Simpeg\n\n default is smooth parameters\n\n :To run sharp inversion:\n\n >>> mt_object.to_simpeg_1d({\"p_s\": 2, \"p_z\": 0, \"use_irls\": True})\n\n :To run sharp inversion adn compact:\n\n >>> mt_object.to_simpeg_1d({\"p_s\": 0, \"p_z\": 0, \"use_irls\": True})\n\n\n :param **kwargs: DESCRIPTION\n :type **kwargs: TYPE\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n if not self.Z._has_tf_model_error():\n self.compute_model_z_errors()\n self.logger.info(\"Using default errors for impedance\")\n simpeg_1d = Simpeg1D(self.to_dataframe(), mode=mode, **kwargs)\n simpeg_1d.run_fixed_layer_inversion(**kwargs)\n simpeg_1d.plot_model_fitting(fig_num=1)\n simpeg_1d.plot_response(fig_num=2)\n\n return simpeg_1d" } ]
import unittest import pandas as pd import numpy as np from mtpy.core import MTStations, MTLocation from mtpy import MT
20,616
# -*- coding: utf-8 -*- """ Created on Tue Sep 5 16:27:01 2023 @author: jpeacock """ # ============================================================================= # Imports # ============================================================================= # ============================================================================= class TestMTStationGrid(unittest.TestCase): @classmethod def setUpClass(self): self.east = 243900.352 self.north = 4432069.056898517 self.utm_epsg = 32611 self.center = MTLocation( latitude=40.036594, longitude=-119.978167, utm_epsg=32611, model_east=245900.352, model_north=4436069.057, ) dx = 1000 dy = 2000 count = 1 mt_list = [] for ii in range(5): for jj in range(5):
# -*- coding: utf-8 -*- """ Created on Tue Sep 5 16:27:01 2023 @author: jpeacock """ # ============================================================================= # Imports # ============================================================================= # ============================================================================= class TestMTStationGrid(unittest.TestCase): @classmethod def setUpClass(self): self.east = 243900.352 self.north = 4432069.056898517 self.utm_epsg = 32611 self.center = MTLocation( latitude=40.036594, longitude=-119.978167, utm_epsg=32611, model_east=245900.352, model_north=4436069.057, ) dx = 1000 dy = 2000 count = 1 mt_list = [] for ii in range(5): for jj in range(5):
mt_obj = MT(
2
2023-10-11 22:24:50+00:00
24k
weavel-ai/promptmodel-python
promptmodel/llms/llm_proxy.py
[ { "identifier": "LLM", "path": "promptmodel/llms/llm.py", "snippet": "class LLM:\n def __init__(self):\n pass\n\n @classmethod\n def __parse_output_pattern__(\n cls,\n raw_output: Optional[str] = None,\n parsing_type: Optional[ParsingType] = None,\n ) -> ParseResult:\n if parsing_type is None:\n return ParseResult(parsed_outputs={}, error=False, error_log=None)\n if raw_output is None:\n return ParseResult(parsed_outputs={}, error=True, error_log=\"No content\")\n parsing_pattern = get_pattern_by_type(parsing_type)\n whole_pattern = parsing_pattern[\"whole\"]\n parsed_results = re.findall(whole_pattern, raw_output, flags=re.DOTALL)\n parsed_outputs = {}\n error: bool = False\n error_log: str = None\n\n try:\n for parsed_result in parsed_results:\n key = parsed_result[0]\n type_str = parsed_result[1]\n value = convert_str_to_type(parsed_result[2], type_str)\n parsed_outputs[key] = value\n except Exception as e:\n error = True\n error_log = str(e)\n\n return ParseResult(\n parsed_outputs=parsed_outputs,\n error=error,\n error_log=error_log,\n )\n\n def __validate_openai_messages(\n self, messages: List[Dict[str, str]]\n ) -> List[OpenAIMessage]:\n \"\"\"Validate and convert list of dictionaries to list of OpenAIMessage.\"\"\"\n res = []\n for message in messages:\n res.append(OpenAIMessage(**message))\n return res\n\n def run(\n self,\n messages: List[Dict[str, str]],\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n model: Optional[str] = DEFAULT_MODEL,\n api_key: Optional[str] = None,\n *args,\n **kwargs,\n ) -> LLMResponse:\n \"\"\"Return the response from openai chat completion.\"\"\"\n response = None\n if functions == []:\n functions = None\n try:\n response: ModelResponse = completion(\n model=model,\n messages=[\n message.model_dump(exclude_none=True)\n for message in self.__validate_openai_messages(messages)\n ],\n functions=functions,\n tools=tools,\n api_key=api_key,\n )\n\n content: Optional[str] = getattr(\n response.choices[0].message, \"content\", None\n )\n\n call_func: Optional[FunctionCall] = getattr(\n response.choices[0].message, \"function_call\", None\n )\n\n call_tools: Optional[List[ChatCompletionMessageToolCall]] = getattr(\n response.choices[0].message, \"tool_calls\", None\n )\n\n return LLMResponse(\n api_response=response,\n raw_output=content,\n function_call=call_func if call_func else None,\n tool_calls=call_tools if call_tools else None,\n )\n except Exception as e:\n if response is not None:\n return LLMResponse(api_response=response, error=True, error_log=str(e))\n else:\n return LLMResponse(api_response=None, error=True, error_log=str(e))\n\n async def arun(\n self,\n messages: List[Dict[str, str]],\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n model: Optional[str] = DEFAULT_MODEL,\n api_key: Optional[str] = None,\n *args,\n **kwargs,\n ) -> LLMResponse:\n \"\"\"Return the response from openai chat completion.\"\"\"\n if functions == []:\n functions = None\n response = None\n try:\n response: ModelResponse = await acompletion(\n model=model,\n messages=[\n message.model_dump(exclude_none=True)\n for message in self.__validate_openai_messages(messages)\n ],\n functions=functions,\n tools=tools,\n api_key=api_key,\n )\n content: Optional[str] = getattr(\n response.choices[0].message, \"content\", None\n )\n\n call_func: Optional[FunctionCall] = getattr(\n response.choices[0].message, \"function_call\", None\n )\n\n call_tools: Optional[ChatCompletionMessageToolCall] = getattr(\n response.choices[0].message, \"tool_calls\", None\n )\n\n return LLMResponse(\n api_response=response,\n raw_output=content,\n function_call=call_func if call_func else None,\n tool_calls=call_tools if call_tools else None,\n )\n\n except Exception as e:\n if response is not None:\n return LLMResponse(api_response=response, error=True, error_log=str(e))\n else:\n return LLMResponse(api_response=None, error=True, error_log=str(e))\n\n def stream(\n self,\n messages: List[Dict[str, str]], # input\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n model: Optional[str] = DEFAULT_MODEL,\n api_key: Optional[str] = None,\n *args,\n **kwargs,\n ) -> Generator[LLMStreamResponse, None, None]:\n \"\"\"Stream openai chat completion.\"\"\"\n if functions == []:\n functions = None\n response = None\n try:\n # load_prompt()\n start_time = datetime.datetime.now()\n response = completion(\n model=model,\n messages=[\n message.model_dump(exclude_none=True)\n for message in self.__validate_openai_messages(messages)\n ],\n stream=True,\n functions=functions,\n tools=tools,\n api_key=api_key,\n )\n\n for chunk in self.__llm_stream_response_generator__(\n messages, response, start_time, functions, tools\n ):\n yield chunk\n except Exception as e:\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n async def astream(\n self,\n messages: List[Dict[str, str]],\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n model: Optional[str] = DEFAULT_MODEL,\n api_key: Optional[str] = None,\n *args,\n **kwargs,\n ) -> AsyncGenerator[LLMStreamResponse, None]:\n \"\"\"Parse & stream output from openai chat completion.\"\"\"\n if functions == []:\n functions = None\n response = None\n try:\n start_time = datetime.datetime.now()\n response = await acompletion(\n model=model,\n messages=[\n message.model_dump(exclude_none=True)\n for message in self.__validate_openai_messages(messages)\n ],\n stream=True,\n functions=functions,\n tools=tools,\n api_key=api_key,\n )\n\n async for chunk in self.__llm_stream_response_agenerator__(\n messages, response, start_time, functions, tools\n ):\n yield chunk\n except Exception as e:\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n def run_and_parse(\n self,\n messages: List[Dict[str, str]],\n parsing_type: Optional[ParsingType] = None,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n output_keys: Optional[List[str]] = None,\n model: Optional[str] = DEFAULT_MODEL,\n api_key: Optional[str] = None,\n ) -> LLMResponse:\n \"\"\"Parse and return output from openai chat completion.\"\"\"\n if functions == []:\n functions = None\n response = None\n parsed_success = True\n parse_result = None\n error_log = None\n try:\n response: ModelResponse = completion(\n model=model,\n messages=[\n message.model_dump(exclude_none=True)\n for message in self.__validate_openai_messages(messages)\n ],\n functions=functions,\n tools=tools,\n api_key=api_key,\n )\n raw_output = getattr(response.choices[0].message, \"content\", None)\n\n call_func: Optional[FunctionCall] = getattr(\n response.choices[0].message, \"function_call\", None\n )\n\n call_tools: Optional[List[ChatCompletionMessageToolCall]] = getattr(\n response.choices[0].message, \"tool_calls\", None\n )\n\n if not call_func and not call_tools:\n # function call does not appear in output\n\n parse_result: ParseResult = self.__parse_output_pattern__(\n raw_output, parsing_type\n )\n\n # if output_keys exist & parsed_outputs does not match with output_keys -> error\n # if parse_result.error -> error\n if (\n output_keys is not None\n and set(parse_result.parsed_outputs.keys()) != set(output_keys)\n ) or parse_result.error:\n parsed_success = False\n error_log = (\n \"Output keys do not match with parsed output keys\"\n if not parse_result.error_log\n else parse_result.error_log\n )\n\n return LLMResponse(\n api_response=response,\n raw_output=raw_output,\n parsed_outputs=parse_result.parsed_outputs if parse_result else None,\n function_call=call_func if call_func else None,\n tool_calls=call_tools if call_tools else None,\n error=not parsed_success,\n error_log=error_log,\n )\n except Exception as e:\n if response is not None:\n return LLMResponse(api_response=response, error=True, error_log=str(e))\n else:\n return LLMResponse(api_response=None, error=True, error_log=str(e))\n\n async def arun_and_parse(\n self,\n messages: List[Dict[str, str]],\n parsing_type: Optional[ParsingType] = None,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n output_keys: Optional[List[str]] = None,\n model: Optional[str] = DEFAULT_MODEL,\n api_key: Optional[str] = None,\n ) -> LLMResponse:\n \"\"\"Generate openai chat completion asynchronously, and parse the output.\n Example prompt is as follows:\n -----\n Given a topic, you are required to generate a story.\n You must follow the provided output format.\n\n Topic:\n {topic}\n\n Output format:\n [Story]\n ...\n [/Story]\n\n Now generate the output:\n \"\"\"\n if functions == []:\n functions = None\n response = None\n parsed_success = True\n parse_result = None\n error_log = None\n try:\n response: ModelResponse = await acompletion(\n model=model,\n messages=[\n message.model_dump(exclude_none=True)\n for message in self.__validate_openai_messages(messages)\n ],\n functions=functions,\n tools=tools,\n api_key=api_key,\n )\n raw_output = getattr(response.choices[0].message, \"content\", None)\n\n call_func: Optional[FunctionCall] = getattr(\n response.choices[0].message, \"function_call\", None\n )\n\n call_tools: Optional[List[ChatCompletionMessageToolCall]] = getattr(\n response.choices[0].message, \"tool_calls\", None\n )\n\n if not call_func and not call_tools:\n # function call does not appear in output\n parse_result: ParseResult = self.__parse_output_pattern__(\n raw_output, parsing_type\n )\n\n # if output_keys exist & parsed_outputs does not match with output_keys -> error\n # if parse_result.error -> error\n if (\n output_keys is not None\n and set(parse_result.parsed_outputs.keys()) != set(output_keys)\n ) or parse_result.error:\n parsed_success = False\n error_log = (\n \"Output keys do not match with parsed output keys\"\n if not parse_result.error_log\n else parse_result.error_log\n )\n\n return LLMResponse(\n api_response=response,\n raw_output=raw_output,\n parsed_outputs=parse_result.parsed_outputs if parse_result else None,\n function_call=call_func if call_func else None,\n tool_calls=call_tools if call_tools else None,\n error=not parsed_success,\n error_log=error_log,\n )\n except Exception as e:\n if response is not None:\n return LLMResponse(api_response=response, error=True, error_log=str(e))\n else:\n return LLMResponse(api_response=None, error=True, error_log=str(e))\n\n def stream_and_parse(\n self,\n messages: List[Dict[str, str]],\n parsing_type: Optional[ParsingType] = None,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n output_keys: Optional[List[str]] = None,\n model: Optional[str] = DEFAULT_MODEL,\n api_key: Optional[str] = None,\n **kwargs,\n ) -> Generator[LLMStreamResponse, None, None]:\n \"\"\"Parse & stream output from openai chat completion.\"\"\"\n if functions == []:\n functions = None\n response = None\n try:\n if parsing_type == ParsingType.COLON.value:\n # cannot stream colon type\n yield LLMStreamResponse(\n error=True, error_log=\"Cannot stream colon type\"\n )\n return\n start_time = datetime.datetime.now()\n response = completion(\n model=model,\n messages=[\n message.model_dump(exclude_none=True)\n for message in self.__validate_openai_messages(messages)\n ],\n stream=True,\n functions=functions,\n tools=tools,\n api_key=api_key,\n )\n\n parsed_outputs = {}\n error_occurs = False\n error_log = None\n\n if (functions and len(functions) > 0) or (tools and len(tools) > 0):\n # if function exists, cannot parsing in stream time\n # just stream raw output and parse after stream\n streamed_outputs = {\n \"content\": \"\",\n \"function_call\": None,\n \"api_response\": None,\n }\n response_with_api_res = None\n for chunk in self.__llm_stream_response_generator__(\n messages, response, start_time, functions, tools\n ):\n if chunk.raw_output:\n streamed_outputs[\"content\"] += chunk.raw_output\n if chunk.function_call:\n streamed_outputs[\"function_call\"] = chunk.function_call\n if (\n chunk.api_response\n and getattr(chunk.api_response.choices[0], \"delta\", None)\n is None\n ): # only get the last api_response, not delta response\n streamed_outputs[\"api_response\"] = chunk.api_response\n response_with_api_res = chunk\n else:\n yield chunk\n\n if chunk.error and not error_occurs:\n error_occurs = True\n error_log = chunk.error_log\n\n if not streamed_outputs[\"function_call\"]:\n # if function call does not exist in output\n # able to parse\n parse_result: ParseResult = self.__parse_output_pattern__(\n streamed_outputs[\"content\"], parsing_type\n )\n\n error_occurs = parse_result.error or error_occurs\n error_log = parse_result.error_log if not error_log else error_log\n\n if (\n output_keys is not None\n and set(parse_result.parsed_outputs.keys()) != set(output_keys)\n ) or error_occurs:\n error_occurs = True\n error_log = (\n \"Output keys do not match with parsed output keys\"\n if not error_log\n else error_log\n )\n yield LLMStreamResponse(\n api_response=streamed_outputs[\"api_response\"],\n error=True,\n error_log=error_log,\n )\n else:\n response_with_api_res.parsed_outputs = (\n parse_result.parsed_outputs\n )\n yield response_with_api_res\n else:\n yield response_with_api_res\n else:\n if parsing_type is None:\n for chunk in self.__llm_stream_response_generator__(\n messages, response, start_time, functions, tools\n ):\n yield chunk\n\n if chunk.error and not error_occurs:\n error_occurs = True\n error_log = chunk.error_log\n\n elif parsing_type == ParsingType.DOUBLE_SQUARE_BRACKET.value:\n for chunk in self.__double_type_sp_generator__(\n messages, response, parsing_type, start_time, functions, tools\n ):\n yield chunk\n if chunk.parsed_outputs:\n parsed_outputs = update_dict(\n parsed_outputs, chunk.parsed_outputs\n )\n if chunk.error and not error_occurs:\n error_occurs = True\n error_log = chunk.error_log\n else:\n for chunk in self.__single_type_sp_generator__(\n messages, response, parsing_type, start_time, functions, tools\n ):\n yield chunk\n if chunk.parsed_outputs:\n parsed_outputs = update_dict(\n parsed_outputs, chunk.parsed_outputs\n )\n if chunk.error and not error_occurs:\n error_occurs = True\n error_log = chunk.error_log\n\n if (\n output_keys is not None\n and set(parsed_outputs.keys()) != set(output_keys)\n ) and not error_occurs:\n error_occurs = True\n error_log = \"Output keys do not match with parsed output keys\"\n yield LLMStreamResponse(error=True, error_log=error_log)\n\n except Exception as e:\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n async def astream_and_parse(\n self,\n messages: List[Dict[str, str]],\n parsing_type: Optional[ParsingType] = None,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n output_keys: Optional[List[str]] = None,\n model: Optional[str] = DEFAULT_MODEL,\n api_key: Optional[str] = None,\n ) -> AsyncGenerator[LLMStreamResponse, None]:\n \"\"\"Parse & stream output from openai chat completion.\"\"\"\n if functions == []:\n functions = None\n response = None\n try:\n if parsing_type == ParsingType.COLON.value:\n # cannot stream colon type\n yield LLMStreamResponse(\n error=True, error_log=\"Cannot stream colon type\"\n )\n return\n start_time = datetime.datetime.now()\n response = await acompletion(\n model=model,\n messages=[\n message.model_dump(exclude_none=True)\n for message in self.__validate_openai_messages(messages)\n ],\n stream=True,\n functions=functions,\n tools=tools,\n api_key=api_key,\n )\n\n parsed_outputs = {}\n error_occurs = False # error in stream time\n error_log = None\n if (functions and len(functions) > 0) or (tools and len(tools) > 0):\n # if function exists, cannot parsing in stream time\n # just stream raw output and parse after stream\n streamed_outputs = {\n \"content\": \"\",\n \"function_call\": None,\n \"api_response\": None,\n }\n response_with_api_res = None\n async for chunk in self.__llm_stream_response_agenerator__(\n messages, response, start_time, functions, tools\n ):\n if chunk.raw_output:\n streamed_outputs[\"content\"] += chunk.raw_output\n if chunk.function_call:\n streamed_outputs[\"function_call\"] = chunk.function_call\n if (\n chunk.api_response\n and getattr(chunk.api_response.choices[0], \"delta\", None)\n is None\n ):\n streamed_outputs[\"api_response\"] = chunk.api_response\n response_with_api_res = chunk\n else:\n yield chunk\n\n if chunk.error and not error_occurs:\n error_occurs = True\n error_log = chunk.error_log\n\n if not streamed_outputs[\"function_call\"]:\n # if function call does not exist in output\n # able to parse\n parse_result: ParseResult = self.__parse_output_pattern__(\n streamed_outputs[\"content\"], parsing_type\n )\n\n error_occurs = parse_result.error or error_occurs\n error_log = parse_result.error_log if not error_log else error_log\n if (\n output_keys is not None\n and set(parse_result.parsed_outputs.keys()) != set(output_keys)\n ) or error_occurs:\n error_occurs = True\n error_log = (\n \"Output keys do not match with parsed output keys\"\n if not error_log\n else error_log\n )\n yield LLMStreamResponse(\n api_response=streamed_outputs[\"api_response\"],\n error=True,\n error_log=error_log,\n )\n else:\n response_with_api_res.parsed_outputs = (\n parse_result.parsed_outputs\n )\n yield response_with_api_res\n else:\n yield response_with_api_res\n else:\n if parsing_type is None:\n async for chunk in self.__llm_stream_response_agenerator__(\n messages, response, start_time, functions, tools\n ):\n yield chunk\n\n if chunk.error and not error_occurs:\n error_occurs = True\n error_log = chunk.error_log\n\n elif parsing_type == ParsingType.DOUBLE_SQUARE_BRACKET.value:\n async for chunk in self.__double_type_sp_agenerator__(\n messages, response, parsing_type, start_time, functions, tools\n ):\n yield chunk\n if chunk.parsed_outputs:\n parsed_outputs = update_dict(\n parsed_outputs, chunk.parsed_outputs\n )\n if chunk.error and not error_occurs:\n error_occurs = True\n else:\n async for chunk in self.__single_type_sp_agenerator__(\n messages, response, parsing_type, start_time, functions, tools\n ):\n yield chunk\n if chunk.parsed_outputs:\n parsed_outputs = update_dict(\n parsed_outputs, chunk.parsed_outputs\n )\n if chunk.error and not error_occurs:\n error_occurs = True\n\n if (\n output_keys is not None\n and set(parsed_outputs.keys()) != set(output_keys)\n ) and not error_occurs:\n error_occurs = True\n error_log = \"Output keys do not match with parsed output keys\"\n yield LLMStreamResponse(error=True, error_log=error_log)\n\n except Exception as e:\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n def make_model_response(\n self,\n chunk: ModelResponse,\n response_ms,\n messages: List[Dict[str, str]],\n raw_output: str,\n functions: Optional[List[Any]] = None,\n function_call: Optional[Dict[str, Any]] = None,\n tools: Optional[List[Any]] = None,\n tool_calls: Optional[List[Dict[str, Any]]] = None,\n ) -> ModelResponse:\n count_start_time = datetime.datetime.now()\n prompt_token: int = num_tokens_for_messages(\n messages=messages, model=chunk[\"model\"]\n )\n completion_token: int = num_tokens_for_messages(\n model=chunk[\"model\"],\n messages=[{\"role\": \"assistant\", \"content\": raw_output}],\n )\n\n if functions and len(functions) > 0:\n functions_token = num_tokens_from_functions_input(\n functions=functions, model=chunk[\"model\"]\n )\n prompt_token += functions_token\n\n if tools and len(tools) > 0:\n tools_token = num_tokens_from_functions_input(\n functions=[tool[\"function\"] for tool in tools], model=chunk[\"model\"]\n )\n prompt_token += tools_token\n # if function_call:\n # function_call_token = num_tokens_from_function_call_output(\n # function_call_output=function_call, model=chunk[\"model\"]\n # )\n # completion_token += function_call_token\n\n count_end_time = datetime.datetime.now()\n logger.debug(\n f\"counting token time : {(count_end_time - count_start_time).total_seconds() * 1000} ms\"\n )\n\n usage = Usage(\n **{\n \"prompt_tokens\": prompt_token,\n \"completion_tokens\": completion_token,\n \"total_tokens\": prompt_token + completion_token,\n }\n )\n\n last_message = Message(\n role=chunk.choices[0].delta.role\n if getattr(chunk.choices[0].delta, \"role\", None)\n else \"assistant\",\n content=raw_output if raw_output != \"\" else None,\n function_call=function_call if function_call else None,\n tool_calls=tool_calls if tool_calls else None,\n )\n choices = [\n Choices(finish_reason=chunk.choices[0].finish_reason, message=last_message)\n ]\n\n res = ModelResponse(\n id=chunk[\"id\"],\n created=chunk[\"created\"],\n model=chunk[\"model\"],\n stream=True,\n )\n res.choices = choices\n res.usage = usage\n res._response_ms = response_ms\n\n return res\n\n def __llm_stream_response_generator__(\n self,\n messages: List[Dict[str, str]],\n response: Generator[ModelResponse, None, None],\n start_time: datetime.datetime,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n ) -> Generator[LLMStreamResponse, None, None]:\n raw_output = \"\"\n function_call = {\"name\": \"\", \"arguments\": \"\"}\n tool_calls = []\n\n try:\n for chunk in response:\n yield_api_response_with_fc = False\n if getattr(chunk.choices[0].delta, \"function_call\", None) is not None:\n for key, value in (\n chunk.choices[0].delta.function_call.model_dump().items()\n ):\n if value is not None:\n function_call[key] += value\n\n yield LLMStreamResponse(\n api_response=chunk,\n function_call=chunk.choices[0].delta.function_call,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"tool_calls\", None) is not None:\n # tool_calls: list\n tool_calls_delta: List[Any] = chunk.choices[0].delta.tool_calls\n index = tool_calls_delta[0].index\n if index == len(tool_calls):\n tool_calls.append(\n {\n \"id\": tool_calls_delta[0].id,\n \"function\": {},\n \"type\": \"function\",\n }\n )\n tool_delta: ChoiceDeltaToolCallFunction = tool_calls_delta[\n 0\n ].function\n tool_calls[index][\"function\"] = update_dict(\n tool_calls[index][\"function\"], tool_delta.model_dump()\n )\n\n yield LLMStreamResponse(\n api_response=chunk,\n tool_calls=chunk.choices[0].delta.tool_calls,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"content\", None) is not None:\n raw_output += chunk.choices[0].delta.content\n yield LLMStreamResponse(\n api_response=chunk if not yield_api_response_with_fc else None,\n raw_output=chunk.choices[0].delta.content,\n )\n\n if chunk.choices[0].finish_reason != None:\n end_time = datetime.datetime.now()\n response_ms = (end_time - start_time).total_seconds() * 1000\n yield LLMStreamResponse(\n api_response=self.make_model_response(\n chunk,\n response_ms,\n messages,\n raw_output,\n functions=functions,\n function_call=function_call\n if chunk.choices[0].finish_reason == \"function_call\"\n else None,\n tools=tools,\n tool_calls=tool_calls\n if chunk.choices[0].finish_reason == \"tool_calls\"\n else None,\n )\n )\n except Exception as e:\n logger.error(e)\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n def __single_type_sp_generator__(\n self,\n messages: List[Dict[str, str]],\n response: Generator[ModelResponse, None, None],\n parsing_type: ParsingType,\n start_time: datetime.datetime,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n ) -> Generator[LLMStreamResponse, None, None]:\n try:\n parsing_pattern = get_pattern_by_type(parsing_type)\n start_tag = parsing_pattern[\"start\"]\n start_fstring = parsing_pattern[\"start_fstring\"]\n end_fstring = parsing_pattern[\"end_fstring\"]\n start_token = parsing_pattern[\"start_token\"]\n end_token = parsing_pattern[\"end_token\"]\n\n buffer = \"\"\n raw_output = \"\"\n active_key = None\n stream_pause = False\n end_tag = None\n function_call = {\"name\": \"\", \"arguments\": \"\"}\n tool_calls = []\n\n for chunk in response:\n yield_api_response_with_fc = False\n if getattr(chunk.choices[0].delta, \"function_call\", None) is not None:\n for key, value in (\n chunk.choices[0].delta.function_call.model_dump().items()\n ):\n if value is not None:\n function_call[key] += value\n\n yield LLMStreamResponse(\n api_response=chunk,\n function_call=chunk.choices[0].delta.function_call,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"tool_calls\", None) is not None:\n # tool_calls: list\n tool_calls_delta: List[Any] = chunk.choices[0].delta.tool_calls\n index = tool_calls_delta[0].index\n if index == len(tool_calls):\n tool_calls.append(\n {\n \"id\": tool_calls_delta[0].id,\n \"function\": {},\n \"type\": \"function\",\n }\n )\n tool_delta: ChoiceDeltaToolCallFunction = tool_calls_delta[\n 0\n ].function\n tool_calls[index][\"function\"] = update_dict(\n tool_calls[index][\"function\"], tool_delta.model_dump()\n )\n\n yield LLMStreamResponse(\n api_response=chunk,\n tool_calls=chunk.choices[0].delta.tool_calls,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"content\", None) is not None:\n stream_value: str = chunk.choices[0].delta.content\n raw_output += stream_value\n yield LLMStreamResponse(\n api_response=chunk if not yield_api_response_with_fc else None,\n raw_output=stream_value,\n )\n\n buffer += stream_value\n while True:\n if active_key is None:\n keys = re.findall(start_tag, buffer, flags=re.DOTALL)\n if len(keys) == 0:\n break # no key\n active_key, active_type = keys[\n 0\n ] # Updated to unpack both key and type\n end_tag = end_fstring.format(key=active_key)\n # delete start tag from buffer\n start_pattern = start_fstring.format(\n key=active_key, type=active_type\n )\n buffer = buffer.split(start_pattern)[-1]\n else:\n if (\n stream_value.find(start_token) != -1\n ): # start token appers in chunk -> pause\n stream_pause = True\n break\n elif stream_pause:\n if (\n buffer.find(end_tag) != -1\n ): # if end tag appears in buffer\n yield LLMStreamResponse(\n parsed_outputs={\n active_key: buffer.split(end_tag)[\n 0\n ].replace(end_tag, \"\")\n }\n )\n buffer = buffer.split(end_tag)[-1]\n active_key = None\n stream_pause = False\n elif (\n stream_value.find(end_token) != -1\n ): # if pattern ends = (\"[blah]\" != end_pattern) appeared in buffer\n if (\n active_type == \"List\"\n or active_type == \"Dict\"\n and end_token.find(\"]\") != -1\n ):\n try:\n buffer_dict = json.loads(buffer)\n stream_pause = False\n continue\n except Exception as exception:\n logger.error(exception)\n yield LLMStreamResponse(\n error=True,\n error_log=\"Parsing error : Invalid end tag detected\",\n parsed_outputs={\n active_key: buffer.split(\n start_token\n )[0]\n },\n )\n stream_pause = False\n buffer = \"\"\n yield LLMStreamResponse(\n error=True,\n error_log=\"Parsing error : Invalid end tag detected\",\n parsed_outputs={active_key: buffer},\n )\n stream_pause = False\n buffer = \"\"\n break\n else:\n # no start token, no stream_pause (not inside of tag)\n if buffer:\n yield LLMStreamResponse(\n parsed_outputs={active_key: buffer}\n )\n buffer = \"\"\n break\n\n if chunk.choices[0].finish_reason != None:\n end_time = datetime.datetime.now()\n response_ms = (end_time - start_time).total_seconds() * 1000\n yield LLMStreamResponse(\n api_response=self.make_model_response(\n chunk,\n response_ms,\n messages,\n raw_output,\n functions=functions,\n function_call=function_call\n if chunk.choices[0].finish_reason == \"function_call\"\n else None,\n tools=tools,\n tool_calls=tool_calls\n if chunk.choices[0].finish_reason == \"tool_calls\"\n else None,\n )\n )\n except Exception as e:\n logger.error(e)\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n def __double_type_sp_generator__(\n self,\n messages: List[Dict[str, str]],\n response: Generator[ModelResponse, None, None],\n parsing_type: ParsingType,\n start_time: datetime.datetime,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n ) -> Generator[LLMStreamResponse, None, None]:\n try:\n parsing_pattern = get_pattern_by_type(parsing_type)\n start_tag = parsing_pattern[\"start\"]\n start_fstring = parsing_pattern[\"start_fstring\"]\n end_fstring = parsing_pattern[\"end_fstring\"]\n start_token = parsing_pattern[\"start_token\"]\n end_token = parsing_pattern[\"end_token\"]\n\n buffer = \"\"\n raw_output = \"\"\n active_key = None\n stream_pause = False\n end_tag = None\n function_call = {\"name\": \"\", \"arguments\": \"\"}\n tool_calls = []\n\n for chunk in response:\n yield_api_response_with_fc = False\n if getattr(chunk.choices[0].delta, \"function_call\", None) is not None:\n for key, value in (\n chunk.choices[0].delta.function_call.model_dump().items()\n ):\n if value is not None:\n function_call[key] += value\n\n yield LLMStreamResponse(\n api_response=chunk,\n function_call=chunk.choices[0].delta.function_call,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"tool_calls\", None) is not None:\n # tool_calls: list\n tool_calls_delta: List[Any] = chunk.choices[0].delta.tool_calls\n index = tool_calls_delta[0].index\n if index == len(tool_calls):\n tool_calls.append(\n {\n \"id\": tool_calls_delta[0].id,\n \"function\": {},\n \"type\": \"function\",\n }\n )\n tool_delta: ChoiceDeltaToolCallFunction = tool_calls_delta[\n 0\n ].function\n tool_calls[index][\"function\"] = update_dict(\n tool_calls[index][\"function\"], tool_delta.model_dump()\n )\n\n yield LLMStreamResponse(\n api_response=chunk,\n tool_calls=chunk.choices[0].delta.tool_calls,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"content\", None) is not None:\n stream_value: str = chunk.choices[0].delta.content\n raw_output += stream_value\n yield LLMStreamResponse(\n api_response=chunk if not yield_api_response_with_fc else None,\n raw_output=stream_value,\n )\n\n buffer += stream_value\n\n while True:\n if active_key is None:\n keys = re.findall(start_tag, buffer, flags=re.DOTALL)\n if len(keys) == 0:\n break # no key\n active_key, active_type = keys[0]\n end_tag = end_fstring.format(key=active_key)\n # delete start tag from buffer\n start_pattern = start_fstring.format(\n key=active_key, type=active_type\n )\n buffer = buffer.split(start_pattern)[-1]\n\n else:\n if (\n stream_value.find(start_token) != -1\n ): # start token appers in chunk -> pause\n stream_pause = True\n break\n elif stream_pause:\n if (\n buffer.find(end_tag) != -1\n ): # if end tag appears in buffer\n yield LLMStreamResponse(\n parsed_outputs={\n active_key: buffer.split(end_tag)[0]\n }\n )\n buffer = buffer.split(end_tag)[-1]\n active_key = None\n stream_pause = False\n elif (\n stream_value.find(end_token) != -1\n ): # if (\"[blah]\" != end_pattern) appeared in buffer\n if (\n buffer.find(end_token + end_token) != -1\n ): # if ]] in buffer -> error\n yield LLMStreamResponse(\n error=True,\n error_log=\"Parsing error : Invalid end tag detected\",\n parsed_outputs={\n active_key: buffer.split(start_token)[0]\n },\n )\n buffer = buffer.split(end_token + end_token)[-1]\n stream_pause = False\n break\n else:\n if (\n buffer.find(start_token + start_token) != -1\n ): # if [[ in buffer -> pause\n break\n else:\n # if [ in buffer (== [blah]) -> stream\n yield LLMStreamResponse(\n parsed_outputs={active_key: buffer}\n )\n buffer = \"\"\n stream_pause = False\n break\n break\n else:\n # no start token, no stream_pause (not inside of tag)\n if buffer:\n yield LLMStreamResponse(\n parsed_outputs={active_key: buffer}\n )\n buffer = \"\"\n break\n\n if chunk.choices[0].finish_reason != None:\n end_time = datetime.datetime.now()\n response_ms = (end_time - start_time).total_seconds() * 1000\n yield LLMStreamResponse(\n api_response=self.make_model_response(\n chunk,\n response_ms,\n messages,\n raw_output,\n functions=functions,\n function_call=function_call\n if chunk.choices[0].finish_reason == \"function_call\"\n else None,\n tools=tools,\n tool_calls=tool_calls\n if chunk.choices[0].finish_reason == \"tool_calls\"\n else None,\n )\n )\n except Exception as e:\n logger.error(e)\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n async def __llm_stream_response_agenerator__(\n self,\n messages: List[Dict[str, str]],\n response: AsyncGenerator[ModelResponse, None],\n start_time: datetime.datetime,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n ) -> AsyncGenerator[LLMStreamResponse, None]:\n raw_output = \"\"\n function_call = {\"name\": \"\", \"arguments\": \"\"}\n tool_calls = []\n try:\n async for chunk in response:\n yield_api_response_with_fc = False\n if getattr(chunk.choices[0].delta, \"function_call\", None) is not None:\n for key, value in (\n chunk.choices[0].delta.function_call.model_dump().items()\n ):\n if value is not None:\n function_call[key] += value\n\n yield LLMStreamResponse(\n api_response=chunk,\n function_call=chunk.choices[0].delta.function_call,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"tool_calls\", None) is not None:\n # tool_calls: list\n tool_calls_delta: List[Any] = chunk.choices[0].delta.tool_calls\n index = tool_calls_delta[0].index\n if index == len(tool_calls):\n tool_calls.append(\n {\n \"id\": tool_calls_delta[0].id,\n \"function\": {},\n \"type\": \"function\",\n }\n )\n tool_delta: ChoiceDeltaToolCallFunction = tool_calls_delta[\n 0\n ].function\n tool_calls[index][\"function\"] = update_dict(\n tool_calls[index][\"function\"], tool_delta.model_dump()\n )\n\n yield LLMStreamResponse(\n api_response=chunk,\n tool_calls=chunk.choices[0].delta.tool_calls,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"content\", None) is not None:\n stream_value: str = chunk.choices[0].delta.content\n raw_output += stream_value\n yield LLMStreamResponse(\n api_response=chunk if not yield_api_response_with_fc else None,\n raw_output=stream_value,\n )\n\n if chunk.choices[0].finish_reason != None:\n end_time = datetime.datetime.now()\n response_ms = (end_time - start_time).total_seconds() * 1000\n yield LLMStreamResponse(\n api_response=self.make_model_response(\n chunk,\n response_ms,\n messages,\n raw_output,\n functions=functions,\n function_call=function_call\n if chunk.choices[0].finish_reason == \"function_call\"\n else None,\n tools=tools,\n tool_calls=tool_calls\n if chunk.choices[0].finish_reason == \"tool_calls\"\n else None,\n )\n )\n except Exception as e:\n logger.error(e)\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n async def __single_type_sp_agenerator__(\n self,\n messages: List[Dict[str, str]],\n response: AsyncGenerator[ModelResponse, None],\n parsing_type: ParsingType,\n start_time: datetime.datetime,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n ) -> AsyncGenerator[LLMStreamResponse, None]:\n try:\n parsing_pattern = get_pattern_by_type(parsing_type)\n start_tag = parsing_pattern[\"start\"]\n start_fstring = parsing_pattern[\"start_fstring\"]\n end_fstring = parsing_pattern[\"end_fstring\"]\n start_token = parsing_pattern[\"start_token\"]\n end_token = parsing_pattern[\"end_token\"]\n\n buffer = \"\"\n raw_output = \"\"\n active_key = None\n stream_pause = False\n end_tag = None\n function_call = {\"name\": \"\", \"arguments\": \"\"}\n tool_calls = []\n\n async for chunk in response:\n yield_api_response_with_fc = False\n if getattr(chunk.choices[0].delta, \"function_call\", None) is not None:\n for key, value in (\n chunk.choices[0].delta.function_call.model_dump().items()\n ):\n if value is not None:\n function_call[key] += value\n\n yield LLMStreamResponse(\n api_response=chunk,\n function_call=chunk.choices[0].delta.function_call,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"tool_calls\", None) is not None:\n # tool_calls: list\n tool_calls_delta: List[Any] = chunk.choices[0].delta.tool_calls\n index = tool_calls_delta[0].index\n if index == len(tool_calls):\n tool_calls.append(\n {\n \"id\": tool_calls_delta[0].id,\n \"function\": {},\n \"type\": \"function\",\n }\n )\n tool_delta: ChoiceDeltaToolCallFunction = tool_calls_delta[\n 0\n ].function\n tool_calls[index][\"function\"] = update_dict(\n tool_calls[index][\"function\"], tool_delta.model_dump()\n )\n\n yield LLMStreamResponse(\n api_response=chunk,\n tool_calls=chunk.choices[0].delta.tool_calls,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"content\", None) is not None:\n stream_value: str = chunk.choices[0].delta.content\n raw_output += stream_value\n yield LLMStreamResponse(\n api_response=chunk if not yield_api_response_with_fc else None,\n raw_output=stream_value,\n )\n\n buffer += stream_value\n\n while True:\n if active_key is None:\n keys = re.findall(start_tag, buffer, flags=re.DOTALL)\n if len(keys) == 0:\n break # no key\n\n active_key, active_type = keys[\n 0\n ] # Updated to unpack both key and type\n end_tag = end_fstring.format(key=active_key)\n # delete start tag from buffer\n start_pattern = start_fstring.format(\n key=active_key, type=active_type\n )\n buffer = buffer.split(start_pattern)[-1]\n\n else:\n if (\n stream_value.find(start_token) != -1\n ): # start token appers in chunk -> pause\n stream_pause = True\n break\n elif stream_pause:\n if (\n buffer.find(end_tag) != -1\n ): # if end tag appears in buffer\n yield LLMStreamResponse(\n parsed_outputs={\n active_key: buffer.split(end_tag)[\n 0\n ].replace(end_tag, \"\")\n }\n )\n buffer = buffer.split(end_tag)[-1]\n active_key = None\n stream_pause = False\n elif (\n stream_value.find(end_token) != -1\n ): # if pattern ends = (\"[blah]\" != end_pattern) appeared in buffer\n if (\n active_type == \"List\"\n or active_type == \"Dict\"\n and end_token.find(\"]\") != -1\n ):\n try:\n buffer_dict = json.loads(buffer)\n stream_pause = False\n continue\n except Exception as exception:\n logger.error(exception)\n yield LLMStreamResponse(\n error=True,\n error_log=\"Parsing error : Invalid end tag detected\",\n parsed_outputs={\n active_key: buffer.split(\n start_token\n )[0]\n },\n )\n stream_pause = False\n buffer = \"\"\n yield LLMStreamResponse(\n error=True,\n error_log=\"Parsing error : Invalid end tag detected\",\n parsed_outputs={active_key: buffer},\n )\n stream_pause = False\n buffer = \"\"\n break\n else:\n # no start token, no stream_pause (not inside of tag)\n if buffer:\n yield LLMStreamResponse(\n parsed_outputs={active_key: buffer}\n )\n buffer = \"\"\n break\n\n if chunk.choices[0].finish_reason != None:\n end_time = datetime.datetime.now()\n response_ms = (end_time - start_time).total_seconds() * 1000\n yield LLMStreamResponse(\n api_response=self.make_model_response(\n chunk,\n response_ms,\n messages,\n raw_output,\n functions=functions,\n function_call=function_call\n if chunk.choices[0].finish_reason == \"function_call\"\n else None,\n tools=tools,\n tool_calls=tool_calls\n if chunk.choices[0].finish_reason == \"tool_calls\"\n else None,\n )\n )\n except Exception as e:\n logger.error(e)\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n async def __double_type_sp_agenerator__(\n self,\n messages: List[Dict[str, str]],\n response: AsyncGenerator[ModelResponse, None],\n parsing_type: ParsingType,\n start_time: datetime.datetime,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n ) -> AsyncGenerator[LLMStreamResponse, None]:\n try:\n parsing_pattern = get_pattern_by_type(parsing_type)\n start_tag = parsing_pattern[\"start\"]\n start_fstring = parsing_pattern[\"start_fstring\"]\n end_fstring = parsing_pattern[\"end_fstring\"]\n start_token = parsing_pattern[\"start_token\"]\n end_token = parsing_pattern[\"end_token\"]\n\n buffer = \"\"\n raw_output = \"\"\n active_key = None\n stream_pause = False\n end_tag = None\n function_call = {\"name\": \"\", \"arguments\": \"\"}\n tool_calls = []\n\n async for chunk in response:\n yield_api_response_with_fc = False\n if getattr(chunk.choices[0].delta, \"function_call\", None) is not None:\n for key, value in (\n chunk.choices[0].delta.function_call.model_dump().items()\n ):\n if value is not None:\n function_call[key] += value\n\n yield LLMStreamResponse(\n api_response=chunk,\n function_call=chunk.choices[0].delta.function_call,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"tool_calls\", None) is not None:\n # tool_calls: list\n tool_calls_delta: List[Any] = chunk.choices[0].delta.tool_calls\n index = tool_calls_delta[0].index\n if index == len(tool_calls):\n tool_calls.append(\n {\n \"id\": tool_calls_delta[0].id,\n \"function\": {},\n \"type\": \"function\",\n }\n )\n tool_delta: ChoiceDeltaToolCallFunction = tool_calls_delta[\n 0\n ].function\n tool_calls[index][\"function\"] = update_dict(\n tool_calls[index][\"function\"], tool_delta.model_dump()\n )\n\n yield LLMStreamResponse(\n api_response=chunk,\n tool_calls=chunk.choices[0].delta.tool_calls,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"content\", None) is not None:\n stream_value: str = chunk.choices[0].delta.content\n raw_output += stream_value\n yield LLMStreamResponse(\n api_response=chunk if not yield_api_response_with_fc else None,\n raw_output=stream_value,\n )\n\n buffer += stream_value\n\n while True:\n if active_key is None:\n keys = re.findall(start_tag, buffer, flags=re.DOTALL)\n # if len(keys) > 1:\n # yield LLMStreamResponse(\n # error=True,\n # error_log=\"Parsing error : Nested key detected\",\n # )\n # break\n if len(keys) == 0:\n break # no key\n active_key, active_type = keys[0]\n end_tag = end_fstring.format(key=active_key)\n # delete start tag from buffer\n start_pattern = start_fstring.format(\n key=active_key, type=active_type\n )\n buffer = buffer.split(start_pattern)[-1]\n\n else:\n if (\n stream_value.find(start_token) != -1\n ): # start token appers in chunk -> pause\n stream_pause = True\n break\n elif stream_pause:\n if (\n buffer.find(end_tag) != -1\n ): # if end tag appears in buffer\n yield LLMStreamResponse(\n parsed_outputs={\n active_key: buffer.split(end_tag)[0]\n }\n )\n buffer = buffer.split(end_tag)[-1]\n active_key = None\n stream_pause = False\n # break\n elif (\n stream_value.find(end_token) != -1\n ): # if (\"[blah]\" != end_pattern) appeared in buffer\n if (\n buffer.find(end_token + end_token) != -1\n ): # if ]] in buffer -> error\n yield LLMStreamResponse(\n error=True,\n error_log=\"Parsing error : Invalid end tag detected\",\n parsed_outputs={\n active_key: buffer.split(start_token)[0]\n },\n )\n buffer = buffer.split(end_token + end_token)[-1]\n stream_pause = False\n break\n else:\n if (\n buffer.find(start_token + start_token) != -1\n ): # if [[ in buffer -> pause\n break\n else:\n # if [ in buffer (== [blah]) -> stream\n yield LLMStreamResponse(\n parsed_outputs={active_key: buffer}\n )\n buffer = \"\"\n stream_pause = False\n break\n break\n else:\n # no start token, no stream_pause (not inside of tag)\n if buffer:\n yield LLMStreamResponse(\n parsed_outputs={active_key: buffer}\n )\n buffer = \"\"\n break\n\n if chunk.choices[0].finish_reason != None:\n end_time = datetime.datetime.now()\n response_ms = (end_time - start_time).total_seconds() * 1000\n yield LLMStreamResponse(\n api_response=self.make_model_response(\n chunk,\n response_ms,\n messages,\n raw_output,\n functions=functions,\n function_call=function_call\n if chunk.choices[0].finish_reason == \"function_call\"\n else None,\n tools=tools,\n tool_calls=tool_calls\n if chunk.choices[0].finish_reason == \"tool_calls\"\n else None,\n )\n )\n except Exception as e:\n logger.error(e)\n yield LLMStreamResponse(error=True, error_log=str(e))" }, { "identifier": "DeployedPrompt", "path": "promptmodel/database/models.py", "snippet": "class DeployedPrompt(BaseModel):\n id = AutoField()\n version_uuid = ForeignKeyField(\n DeployedFunctionModelVersion,\n field=DeployedFunctionModelVersion.uuid,\n backref=\"prompts\",\n on_delete=\"CASCADE\",\n )\n role = CharField()\n step = IntegerField()\n content = TextField()" }, { "identifier": "DeployedFunctionModel", "path": "promptmodel/database/models.py", "snippet": "class DeployedFunctionModel(BaseModel):\n uuid = UUIDField(unique=True, default=uuid4)\n name = CharField()" }, { "identifier": "DeployedFunctionModelVersion", "path": "promptmodel/database/models.py", "snippet": "class DeployedFunctionModelVersion(BaseModel):\n uuid = UUIDField(unique=True, default=uuid4)\n version = IntegerField(null=False)\n from_version = IntegerField(null=True)\n function_model_uuid = ForeignKeyField(\n DeployedFunctionModel,\n field=DeployedFunctionModel.uuid,\n backref=\"versions\",\n on_delete=\"CASCADE\",\n )\n model = CharField()\n is_published = BooleanField(default=False)\n is_ab_test = BooleanField(default=False)\n ratio = FloatField(null=True)\n parsing_type = CharField(\n null=True,\n default=None,\n constraints=[\n Check(\n f\"parsing_type IN ('{ParsingType.COLON.value}', '{ParsingType.SQUARE_BRACKET.value}', '{ParsingType.DOUBLE_SQUARE_BRACKET.value}')\"\n )\n ],\n )\n output_keys = JSONField(null=True, default=None)\n functions = JSONField(default=[])" }, { "identifier": "get_deployed_prompts", "path": "promptmodel/database/crud.py", "snippet": "def get_deployed_prompts(function_model_name: str) -> Tuple[List[DeployedPrompt], str]:\n try:\n with db.atomic():\n versions: List[DeployedFunctionModelVersion] = list(\n DeployedFunctionModelVersion.select()\n .join(DeployedFunctionModel)\n .where(\n DeployedFunctionModelVersion.function_model_uuid\n == DeployedFunctionModel.get(\n DeployedFunctionModel.name == function_model_name\n ).uuid\n )\n )\n prompts: List[DeployedPrompt] = list(\n DeployedPrompt.select()\n .where(\n DeployedPrompt.version_uuid.in_(\n [version.uuid for version in versions]\n )\n )\n .order_by(DeployedPrompt.step.asc())\n )\n # select version by ratio\n selected_version = select_version_by_ratio(\n [version.__data__ for version in versions]\n )\n selected_prompts = list(\n filter(\n lambda prompt: str(prompt.version_uuid.uuid)\n == str(selected_version[\"uuid\"]),\n prompts,\n )\n )\n\n version_details = {\n \"model\": selected_version[\"model\"],\n \"version\" : selected_version[\"version\"],\n \"uuid\": selected_version[\"uuid\"],\n \"parsing_type\": selected_version[\"parsing_type\"],\n \"output_keys\": selected_version[\"output_keys\"],\n }\n\n return selected_prompts, version_details\n except Exception as e:\n logger.error(e)\n return None, None" }, { "identifier": "CacheManager", "path": "promptmodel/promptmodel_init.py", "snippet": "class CacheManager:\n _instance = None\n _lock = threading.Lock()\n\n def __new__(cls):\n with cls._lock:\n if cls._instance is None:\n instance = super(CacheManager, cls).__new__(cls)\n instance.last_update_time = 0 # to manage update frequency\n instance.update_interval = 60 * 60 * 6 # seconds, 6 hours\n instance.program_alive = True\n instance.background_tasks = []\n initialize_db()\n atexit.register(instance._terminate)\n asyncio.run(instance.update_cache()) # updae cache first synchronously\n instance.cache_thread = threading.Thread(\n target=instance._run_cache_loop\n )\n instance.cache_thread.daemon = True\n instance.cache_thread.start()\n cls._instance = instance\n return cls._instance\n\n def cache_update_background_task(self, config):\n asyncio.run(update_deployed_db(config))\n\n def _run_cache_loop(self):\n asyncio.run(self._update_cache_periodically())\n\n async def _update_cache_periodically(self):\n while True:\n await asyncio.sleep(self.update_interval) # Non-blocking sleep\n await self.update_cache()\n\n async def update_cache(self):\n # Current time\n current_time = time.time()\n config = read_config()\n\n if not config:\n upsert_config({\"version\": 0}, section=\"project\")\n config = {\"project\": {\"version\": 0}}\n if \"project\" not in config:\n upsert_config({\"version\": 0}, section=\"project\")\n config = {\"project\": {\"version\": 0}}\n\n if \"version\" not in config[\"project\"]:\n upsert_config({\"version\": 0}, section=\"project\")\n config = {\"project\": {\"version\": 0}}\n\n # Check if we need to update the cache\n if current_time - self.last_update_time > self.update_interval:\n # Update cache logic\n try:\n await update_deployed_db(config)\n except:\n # try once more\n await update_deployed_db(config)\n # Update the last update time\n self.last_update_time = current_time\n\n def _terminate(self):\n self.program_alive = False\n\n # async def cleanup_background_tasks(self):\n # for task in self.background_tasks:\n # if not task.done():\n # task.cancel()\n # try:\n # await task\n # except asyncio.CancelledError:\n # pass # 작업이 취소됨" }, { "identifier": "read_config", "path": "promptmodel/utils/config_utils.py", "snippet": "def read_config():\n \"\"\"\n Reads the configuration from the given filename.\n\n :return: A dictionary containing the configuration.\n \"\"\"\n if not os.path.exists(CONFIG_FILE):\n return {}\n\n with open(CONFIG_FILE, \"r\") as file:\n config = yaml.safe_load(file) or {}\n return config" }, { "identifier": "upsert_config", "path": "promptmodel/utils/config_utils.py", "snippet": "def upsert_config(new_config: Dict[str, Any], section: str = None):\n \"\"\"\n Upserts the given configuration file with the given configuration.\n\n :param new_config: A dictionary containing the new configuration.\n :param section: The section of the configuration to update.\n \"\"\"\n config = read_config()\n if section:\n config_section = config.get(section, {})\n new_config = {section: merge_dict(config_section, new_config)}\n config = merge_dict(config, new_config)\n # If . directory does not exist, create it\n if not os.path.exists(\"./.promptmodel\"):\n os.mkdir(\"./.promptmodel\")\n\n with open(CONFIG_FILE, \"w\") as file:\n yaml.safe_dump(config, file, default_flow_style=False)" }, { "identifier": "select_version_by_ratio", "path": "promptmodel/utils/random_utils.py", "snippet": "def select_version_by_ratio(versions):\n epsilon = 1e-10\n ratios = [version[\"ratio\"] for version in versions]\n\n if not abs(sum(ratios) - 1.0) <= epsilon:\n raise ValueError(f\"Sum of ratios must be 1.0, now {sum(ratios)}\")\n\n cumulative_ratios = []\n cumulative_sum = 0\n for ratio in ratios:\n cumulative_sum += ratio\n cumulative_ratios.append(cumulative_sum)\n\n random_value = random.random()\n for idx, cumulative_ratio in enumerate(cumulative_ratios):\n if random_value <= cumulative_ratio:\n return versions[idx]" }, { "identifier": "logger", "path": "promptmodel/utils/logger.py", "snippet": "def debug(msg: Any, *args):\ndef success(msg: Any, *args):\ndef info(msg: Any, *args):\ndef warning(msg: Any, *args):\ndef error(msg: Any, *args):" }, { "identifier": "run_async_in_sync", "path": "promptmodel/utils/async_utils.py", "snippet": "def run_async_in_sync(coro: Coroutine):\n try:\n loop = asyncio.get_running_loop()\n except RuntimeError: # No running loop\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n result = loop.run_until_complete(coro)\n # loop.close()\n return result\n\n return loop.run_until_complete(coro)" }, { "identifier": "num_tokens_for_messages_for_each", "path": "promptmodel/utils/token_counting.py", "snippet": "def num_tokens_for_messages_for_each(\n messages: List[Dict[str, str]], model: str = \"gpt-3.5-turbo-0613\"\n) -> List[int]:\n processed_messages = [\n {**message, \"function_call\": str(message[\"function_call\"])}\n if \"function_call\" in message\n else message\n for message in messages\n ]\n processed_messages = [\n {**message, \"tool_calls\": str(message[\"tool_calls\"])}\n if \"tool_calls\" in message\n else message\n for message in processed_messages\n ]\n return [\n token_counter(model=model, messages=[message]) for message in processed_messages\n ]" }, { "identifier": "num_tokens_from_functions_input", "path": "promptmodel/utils/token_counting.py", "snippet": "def num_tokens_from_functions_input(\n functions: Optional[List[Any]] = None, model=\"gpt-3.5-turbo-0613\"\n) -> int:\n \"\"\"Return the number of tokens used by a list of functions.\"\"\"\n if functions is None:\n return 0\n num_tokens = 0\n for function in functions:\n function_tokens = token_counter(model=model, text=function[\"name\"])\n function_tokens += token_counter(model=model, text=function[\"description\"])\n\n if \"parameters\" in function:\n parameters = function[\"parameters\"]\n if \"properties\" in parameters:\n for properties_key in parameters[\"properties\"]:\n function_tokens += token_counter(model=model, text=properties_key)\n v = parameters[\"properties\"][properties_key]\n for field in v:\n if field == \"type\":\n function_tokens += 2\n function_tokens += token_counter(\n model=model, text=v[\"type\"]\n )\n elif field == \"description\":\n function_tokens += 2\n function_tokens += token_counter(\n model=model, text=v[\"description\"]\n )\n elif field == \"enum\":\n function_tokens -= 3\n for o in v[\"enum\"]:\n function_tokens += 3\n function_tokens += token_counter(model=model, text=o)\n else:\n print(f\"Warning: not supported field {field}\")\n function_tokens += 11\n\n num_tokens += function_tokens\n\n num_tokens += 12\n return num_tokens" }, { "identifier": "update_dict", "path": "promptmodel/utils/output_utils.py", "snippet": "def update_dict(\n target: Dict[str, str],\n source: Dict[str, str],\n):\n for key, value in source.items():\n if value is not None:\n if key not in target:\n target[key] = value\n else:\n target[key] += value\n return target" }, { "identifier": "AsyncAPIClient", "path": "promptmodel/apis/base.py", "snippet": "class AsyncAPIClient:\n \"\"\"\n A class to represent an Async API request client.\n Used in Deployment stage.\n\n ...\n\n Methods\n -------\n get_headers():\n Generates headers for the API request.\n execute(method=\"GET\", params=None, data=None, json=None, **kwargs):\n Executes the API request.\n \"\"\"\n\n @classmethod\n async def _get_headers(cls, use_cli_key: bool = True) -> Dict:\n \"\"\"\n Reads, decrypts the api_key, and returns headers for API request.\n\n Returns\n -------\n dict\n a dictionary containing the Authorization header\n \"\"\"\n config = read_config()\n if use_cli_key:\n if \"connection\" not in config:\n print(\n \"User not logged in. Please run [violet]prompt login[/violet] first.\"\n )\n exit()\n\n encrypted_key = config[\"connection\"][\"encrypted_api_key\"]\n if encrypted_key is None:\n raise Exception(\"No API key found. Please run 'prompt login' first.\")\n decrypted_key = decrypt_message(encrypted_key)\n else:\n decrypted_key = os.environ.get(\"PROMPTMODEL_API_KEY\")\n if decrypted_key is None:\n raise Exception(\n \"PROMPTMODEL_API_KEY was not found in the current environment.\"\n )\n headers = {\"Authorization\": f\"Bearer {decrypted_key}\"}\n return headers\n\n @classmethod\n async def execute(\n cls,\n path: str,\n method=\"GET\",\n params: Dict = None,\n data: Dict = None,\n json: Dict = None,\n ignore_auth_error: bool = False,\n use_cli_key: bool = True,\n **kwargs,\n ) -> requests.Response:\n \"\"\"\n Executes the API request with the decrypted API key in the headers.\n\n Parameters\n ----------\n method : str, optional\n The HTTP method of the request (default is \"GET\")\n params : dict, optional\n The URL parameters to be sent with the request\n data : dict, optional\n The request body to be sent with the request\n json : dict, optional\n The JSON-encoded request body to be sent with the request\n ignore_auth_error: bool, optional\n Whether to ignore authentication errors (default is False)\n **kwargs : dict\n Additional arguments to pass to the requests.request function\n\n Returns\n -------\n requests.Response\n The response object returned by the requests library\n \"\"\"\n url = f\"{ENDPOINT_URL}{path}\"\n headers = await cls._get_headers(use_cli_key)\n try:\n async with httpx.AsyncClient(http2=True) as _client:\n response = await _client.request(\n method,\n url,\n headers=headers,\n params=params,\n data=data,\n json=json,\n **kwargs,\n )\n if not response:\n print(f\"[red]Error: {response}[/red]\")\n if response.status_code == 200:\n return response\n elif response.status_code == 403:\n if not ignore_auth_error:\n print(\"[red]Authentication failed.[/red]\")\n else:\n print(f\"[red]Error: {response}[/red]\")\n\n return response\n except requests.exceptions.ConnectionError:\n print(\"[red]Could not connect to the Promptmodel API.[/red]\")\n except requests.exceptions.Timeout:\n print(\"[red]The request timed out.[/red]\")\n except Exception as exception:\n print(f\"[red]Error: {exception}[/red]\")" }, { "identifier": "LLMResponse", "path": "promptmodel/types/response.py", "snippet": "class LLMResponse(OpenAIObject):\n api_response: Optional[ModelResponse] = None\n raw_output: Optional[str] = None\n parsed_outputs: Optional[Dict[str, Any]] = None\n error: Optional[bool] = None\n error_log: Optional[str] = None\n function_call: Optional[FunctionCall] = None\n tool_calls: Optional[List[ChatCompletionMessageToolCall]] = None\n pm_detail: Optional[PMDetail] = None" }, { "identifier": "LLMStreamResponse", "path": "promptmodel/types/response.py", "snippet": "class LLMStreamResponse(OpenAIObject):\n api_response: Optional[ModelResponse] = None\n raw_output: Optional[str] = None\n parsed_outputs: Optional[Dict[str, Any]] = None\n error: Optional[bool] = None\n error_log: Optional[str] = None\n function_call: Optional[ChoiceDeltaFunctionCall] = None\n tool_calls: Optional[List[ChoiceDeltaToolCall]] = None\n pm_detail: Optional[PMDetail] = None" }, { "identifier": "FunctionModelConfig", "path": "promptmodel/types/response.py", "snippet": "class FunctionModelConfig(BaseModel):\n \"\"\"Response Class for FunctionModel.get_config()\n prompts: List[Dict[str, Any]] = []\n each prompt can have role, content, name, function_call, and tool_calls\n version_detail: Dict[str, Any] = {}\n version_detail has \"model\", \"uuid\", \"parsing_type\" and \"output_keys\".\n model: str\n model name (e.g. \"gpt-3.5-turbo\")\n name: str\n name of the FunctionModel.\n version_uuid: str\n version uuid of the FunctionModel.\n version: int\n version id of the FunctionModel.\n parsing_type: Optional[str] = None\n parsing type of the FunctionModel.\n output_keys: Optional[List[str]] = None\n output keys of the FunctionModel.\n \"\"\"\n\n prompts: List[Dict[str, Any]]\n model: str\n name: str\n version_uuid: str\n version: int\n parsing_type: Optional[str] = None\n output_keys: Optional[List[str]] = None" }, { "identifier": "ChatModelConfig", "path": "promptmodel/types/response.py", "snippet": "class ChatModelConfig(BaseModel):\n system_prompt: str\n model: str\n name: str\n version_uuid: str\n version: int\n message_logs: Optional[List[Dict]] = []" }, { "identifier": "UnitConfig", "path": "promptmodel/types/response.py", "snippet": "class UnitConfig(BaseModel):\n \"\"\"Response Class for UnitLogger.get_config().\n Created after calling UnitLogger.log_start()\n name: str\n name of the UnitLogger.\n version_uuid: str\n version uuid of the UnitLogger.\n version: int\n version id of the UnitLogger.\n log_uuid: str\n log_uuid for current trace.\n \"\"\"\n\n name: str\n version_uuid: str\n log_uuid: str\n version: int" }, { "identifier": "PMDetail", "path": "promptmodel/types/response.py", "snippet": "class PMDetail(BaseModel):\n model: str\n name: str\n version_uuid: str\n version: int\n log_uuid: str" }, { "identifier": "ChatLogRequest", "path": "promptmodel/types/request.py", "snippet": "class ChatLogRequest(BaseModel):\n uuid: Optional[str] = None\n message: Dict[str, Any]\n metadata: Optional[Dict] = None\n api_response: Optional[ModelResponse] = None\n\n def __post_init__(\n self,\n ):\n if self.api_response is not None and self.message is None:\n self.message = self.api_response.choices[0].message.model_dump()" } ]
from typing import ( Any, AsyncGenerator, Callable, Dict, Generator, List, Optional, Tuple, Union, ) from uuid import UUID from threading import Thread from rich import print from uuid import uuid4 from litellm.utils import ModelResponse, get_max_tokens from promptmodel.llms.llm import LLM from promptmodel.database.models import ( DeployedPrompt, DeployedFunctionModel, DeployedFunctionModelVersion, ) from promptmodel.database.crud import ( get_deployed_prompts, ) from promptmodel.promptmodel_init import CacheManager from promptmodel.utils.config_utils import read_config, upsert_config from promptmodel.utils.random_utils import select_version_by_ratio from promptmodel.utils import logger from promptmodel.utils.async_utils import run_async_in_sync from promptmodel.utils.token_counting import ( num_tokens_for_messages_for_each, num_tokens_from_functions_input, ) from promptmodel.utils.output_utils import update_dict from promptmodel.apis.base import AsyncAPIClient from promptmodel.types.response import ( LLMResponse, LLMStreamResponse, FunctionModelConfig, ChatModelConfig, UnitConfig, PMDetail, ) from promptmodel.types.request import ChatLogRequest
19,959
inputs: Dict[str, Any] = {}, functions: Optional[List[Any]] = None, tools: Optional[List[Any]] = None, api_key: Optional[str] = None, ) -> AsyncGenerator[LLMStreamResponse, None]: kwargs = self.make_kwargs(functions=functions, api_key=api_key, tools=tools) return self._wrap_async_gen(super().astream_and_parse)(inputs, **kwargs) def chat_run( self, session_uuid: str, functions: Optional[List[Any]] = None, tools: Optional[List[Any]] = None, api_key: Optional[str] = None, ) -> LLMResponse: kwargs = self.make_kwargs(functions=functions, api_key=api_key, tools=tools) return self._wrap_chat(super().run)(session_uuid, **kwargs) def chat_arun( self, session_uuid: str, functions: Optional[List[Any]] = None, tools: Optional[List[Any]] = None, api_key: Optional[str] = None, ) -> LLMResponse: kwargs = self.make_kwargs(functions=functions, api_key=api_key, tools=tools) return self._wrap_async_chat(super().arun)(session_uuid, **kwargs) def chat_stream( self, session_uuid: str, functions: Optional[List[Any]] = None, tools: Optional[List[Any]] = None, api_key: Optional[str] = None, ) -> LLMResponse: kwargs = self.make_kwargs(functions=functions, api_key=api_key, tools=tools) return self._wrap_chat_gen(super().stream)(session_uuid, **kwargs) def chat_astream( self, session_uuid: str, functions: Optional[List[Any]] = None, tools: Optional[List[Any]] = None, api_key: Optional[str] = None, ) -> LLMResponse: kwargs = self.make_kwargs(functions=functions, api_key=api_key, tools=tools) return self._wrap_async_chat_gen(super().astream)(session_uuid, **kwargs) @staticmethod async def fetch_prompts( name, version: Optional[Union[str, int]] = "deploy", ) -> Tuple[List[Dict[str, str]], Dict[str, Any]]: """fetch prompts. Args: name (str): name of FunctionModel Returns: Tuple[List[Dict[str, str]], Optional[Dict[str, Any]]]: (prompts, version_detail) """ # Check connection activate config = read_config() if ( "connection" in config and "initializing" in config["connection"] and config["connection"]["initializing"] == True ): return [], {} elif ( "connection" in config and "reloading" in config["connection"] and config["connection"]["reloading"] == True ): return [], {} else: if ( "project" in config and "use_cache" in config["project"] and config["project"]["use_cache"] == True and version == "deploy" ): cache_manager = CacheManager() # call update_local API in background task cache_update_thread = Thread( target=cache_manager.cache_update_background_task, args=(config,) ) cache_update_thread.daemon = True cache_update_thread.start() # get prompt from local DB by ratio prompt_rows, version_detail = get_deployed_prompts(name) if prompt_rows is None: return [], {} return [ {"role": prompt.role, "content": prompt.content} for prompt in prompt_rows ], version_detail else: try: config_list = await AsyncAPIClient.execute( method="GET", path="/function_model_versions", params={"function_model_name": name, "version": version}, use_cli_key=False, ) config_list = config_list.json() except Exception as e: raise e function_model_versions = [ x["function_model_version"] for x in config_list ] if version == "deploy": for version in function_model_versions: if version["is_published"] is True: version["ratio"] = 1.0
class LLMProxy(LLM): def __init__( self, name: str, version: Optional[Union[str, int]] = "deploy", unit_config: Optional[UnitConfig] = None ): super().__init__() self._name = name self.version = version self.unit_config = unit_config def _wrap_gen(self, gen: Callable[..., Any]) -> Callable[..., Any]: def wrapper(inputs: Dict[str, Any], **kwargs): prompts, version_details = run_async_in_sync( LLMProxy.fetch_prompts(self._name, self.version) ) call_args = self._prepare_call_args( prompts, version_details, inputs, kwargs ) log_uuid = str(uuid4()) # Call the generator with the arguments stream_response: Generator[LLMStreamResponse, None, None] = gen(**call_args) api_response = None dict_cache = {} # to store aggregated dictionary values string_cache = "" # to store aggregated string values error_occurs = False error_log = None for item in stream_response: if ( item.api_response and "delta" not in item.api_response.choices[0] ): # only get the last api_response, not delta response api_response = item.api_response if item.parsed_outputs: dict_cache = update_dict(dict_cache, item.parsed_outputs) if item.raw_output: string_cache += item.raw_output if item.error and not error_occurs: error_occurs = True error_log = item.error_log if error_occurs: # delete all promptmodel data in item item.raw_output = None item.parsed_outputs = None item.function_call = None item.pm_detail = PMDetail( model=version_details["model"], name=self._name, version_uuid=str(version_details["uuid"]), version=version_details["version"], log_uuid=log_uuid, ) yield item metadata = { "error": error_occurs, "error_log": error_log, } run_async_in_sync( self._async_log_to_cloud( log_uuid=log_uuid, version_uuid=version_details["uuid"], inputs=inputs, api_response=api_response, parsed_outputs=dict_cache, metadata=metadata, ) ) return wrapper def _wrap_async_gen(self, async_gen: Callable[..., Any]) -> Callable[..., Any]: async def wrapper(inputs: Dict[str, Any], **kwargs): prompts, version_details = await LLMProxy.fetch_prompts( self._name, self.version ) call_args = self._prepare_call_args( prompts, version_details, inputs, kwargs ) # Call async_gen with the arguments stream_response: AsyncGenerator[LLMStreamResponse, None] = async_gen( **call_args ) log_uuid = str(uuid4()) api_response = None dict_cache = {} # to store aggregated dictionary values string_cache = "" # to store aggregated string values error_occurs = False error_log = None api_response: Optional[ModelResponse] = None async for item in stream_response: if ( item.api_response and "delta" not in item.api_response.choices[0] ): # only get the last api_response, not delta response api_response = item.api_response if item.parsed_outputs: dict_cache = update_dict(dict_cache, item.parsed_outputs) if item.raw_output: string_cache += item.raw_output if item.error and not error_occurs: error_occurs = True error_log = item.error_log item.pm_detail = PMDetail( model=version_details["model"], name=self._name, version_uuid=str(version_details["uuid"]), version=version_details["version"], log_uuid=log_uuid, ) yield item # # add string_cache in model_response # if api_response: # if "message" not in api_response.choices[0]: # api_response.choices[0].message = {} # if "content" not in api_response.choices[0].message: # api_response.choices[0].message["content"] = string_cache # api_response.choices[0].message["role"] = "assistant" metadata = { "error": error_occurs, "error_log": error_log, } await self._async_log_to_cloud( log_uuid=log_uuid, version_uuid=version_details["uuid"], inputs=inputs, api_response=api_response, parsed_outputs=dict_cache, metadata=metadata, ) # raise Exception("error_log") return wrapper def _wrap_method(self, method: Callable[..., Any]) -> Callable[..., Any]: def wrapper(inputs: Dict[str, Any], **kwargs): prompts, version_details = run_async_in_sync( LLMProxy.fetch_prompts(self._name, self.version) ) call_args = self._prepare_call_args( prompts, version_details, inputs, kwargs ) # Call the method with the arguments llm_response: LLMResponse = method(**call_args) error_occurs = llm_response.error error_log = llm_response.error_log metadata = { "error": error_occurs, "error_log": error_log, } log_uuid = str(uuid4()) if llm_response.parsed_outputs: run_async_in_sync( self._async_log_to_cloud( log_uuid=log_uuid, version_uuid=version_details["uuid"], inputs=inputs, api_response=llm_response.api_response, parsed_outputs=llm_response.parsed_outputs, metadata=metadata, ) ) else: run_async_in_sync( self._async_log_to_cloud( log_uuid=log_uuid, version_uuid=version_details["uuid"], inputs=inputs, api_response=llm_response.api_response, parsed_outputs={}, metadata=metadata, ) ) if error_occurs: # delete all promptmodel data in llm_response llm_response.raw_output = None llm_response.parsed_outputs = None llm_response.function_call = None llm_response.pm_detail = PMDetail( model=version_details["model"], name=self._name, version_uuid=str(version_details["uuid"]), version=version_details["version"], log_uuid=log_uuid, ) return llm_response return wrapper def _wrap_async_method(self, method: Callable[..., Any]) -> Callable[..., Any]: async def async_wrapper(inputs: Dict[str, Any], **kwargs): prompts, version_details = await LLMProxy.fetch_prompts( self._name, self.version ) # messages, model, uuid = self._fetch_prompts() call_args = self._prepare_call_args( prompts, version_details, inputs, kwargs ) # Call the method with the arguments llm_response: LLMResponse = await method(**call_args) error_occurs = llm_response.error error_log = llm_response.error_log metadata = { "error": error_occurs, "error_log": error_log, } log_uuid = str(uuid4()) if llm_response.parsed_outputs: await self._async_log_to_cloud( log_uuid=log_uuid, version_uuid=version_details["uuid"], inputs=inputs, api_response=llm_response.api_response, parsed_outputs=llm_response.parsed_outputs, metadata=metadata, ) else: await self._async_log_to_cloud( log_uuid=log_uuid, version_uuid=version_details["uuid"], inputs=inputs, api_response=llm_response.api_response, parsed_outputs={}, metadata=metadata, ) if error_occurs: # delete all promptmodel data in llm_response llm_response.raw_output = None llm_response.parsed_outputs = None llm_response.function_call = None llm_response.pm_detail = PMDetail( model=version_details["model"], name=self._name, version_uuid=str(version_details["uuid"]), version=version_details["version"], log_uuid=log_uuid, ) return llm_response return async_wrapper def _wrap_chat(self, method: Callable[..., Any]) -> Callable[..., Any]: def wrapper(session_uuid: str, **kwargs): instruction, version_details, message_logs = run_async_in_sync( LLMProxy.fetch_chat_model(self._name, session_uuid, self.version) ) call_args = self._prepare_call_args_for_chat( message_logs, version_details, kwargs ) # Call the method with the arguments llm_response: LLMResponse = method(**call_args) error_occurs = llm_response.error error_log = llm_response.error_log metadata = { "error": error_occurs, "error_log": error_log, } api_response = None if llm_response.api_response: api_response = llm_response.api_response log_uuid = str(uuid4()) run_async_in_sync( self._async_chat_log_to_cloud( session_uuid=session_uuid, version_uuid=version_details["uuid"], chat_log_request_list=[ ChatLogRequest( message=llm_response.api_response.choices[ 0 ].message.model_dump(), uuid=log_uuid, metadata=metadata, api_response=api_response, ) ], ) ) if error_occurs: # delete all promptmodel data in llm_response llm_response.raw_output = None llm_response.parsed_outputs = None llm_response.function_call = None llm_response.pm_detail = PMDetail( model=version_details["model"], name=self._name, version_uuid=str(version_details["uuid"]), version=version_details["version"], log_uuid=log_uuid, ) return llm_response return wrapper def _wrap_async_chat(self, method: Callable[..., Any]) -> Callable[..., Any]: async def async_wrapper(session_uuid: str, **kwargs): ( instruction, version_details, message_logs, ) = await LLMProxy.fetch_chat_model(self._name, session_uuid, self.version) call_args = self._prepare_call_args_for_chat( message_logs, version_details, kwargs ) # Call the method with the arguments llm_response: LLMResponse = await method(**call_args) error_occurs = llm_response.error error_log = llm_response.error_log metadata = { "error": error_occurs, "error_log": error_log, } api_response = None if llm_response.api_response: api_response = llm_response.api_response log_uuid = str(uuid4()) await self._async_chat_log_to_cloud( session_uuid=session_uuid, version_uuid=version_details["uuid"], chat_log_request_list=[ ChatLogRequest( uuid=log_uuid, message=llm_response.api_response.choices[ 0 ].message.model_dump(), metadata=metadata, api_response=api_response, ) ], ) if error_occurs: # delete all promptmodel data in llm_response llm_response.raw_output = None llm_response.parsed_outputs = None llm_response.function_call = None llm_response.pm_detail = PMDetail( model=version_details["model"], name=self._name, version_uuid=str(version_details["uuid"]), version=version_details["version"], log_uuid=log_uuid, ) return llm_response return async_wrapper def _wrap_chat_gen(self, gen: Callable[..., Any]) -> Callable[..., Any]: def wrapper(session_uuid: str, **kwargs): instruction, version_details, message_logs = run_async_in_sync( LLMProxy.fetch_chat_model(self._name, session_uuid, self.version) ) call_args = self._prepare_call_args_for_chat( message_logs, version_details, kwargs ) # Call the generator with the arguments stream_response: Generator[LLMStreamResponse, None, None] = gen(**call_args) api_response = None error_occurs = False error_log = None log_uuid = str(uuid4()) for item in stream_response: if ( item.api_response and "delta" not in item.api_response.choices[0] ): # only get the last api_response, not delta response api_response = item.api_response if item.error and not error_occurs: error_occurs = True error_log = item.error_log if error_occurs: # delete all promptmodel data in item item.raw_output = None item.parsed_outputs = None item.function_call = None item.pm_detail = PMDetail( model=version_details["model"], name=self._name, version_uuid=str(version_details["uuid"]), version=version_details["version"], log_uuid=log_uuid, ) yield item metadata = { "error": error_occurs, "error_log": error_log, } run_async_in_sync( self._async_chat_log_to_cloud( session_uuid=session_uuid, version_uuid=version_details["uuid"], chat_log_request_list=[ ChatLogRequest( uuid=log_uuid, message=api_response.choices[0].message.model_dump(), metadata=metadata, api_response=api_response, ) ], ) ) return wrapper def _wrap_async_chat_gen(self, async_gen: Callable[..., Any]) -> Callable[..., Any]: async def wrapper(session_uuid: str, **kwargs): ( instruction, version_details, message_logs, ) = await LLMProxy.fetch_chat_model(self._name, session_uuid, self.version) call_args = self._prepare_call_args_for_chat( message_logs, version_details, kwargs ) # Call the generator with the arguments stream_response: AsyncGenerator[LLMStreamResponse, None] = async_gen( **call_args ) api_response = None error_occurs = False error_log = None log_uuid = str(uuid4()) async for item in stream_response: if ( item.api_response and "delta" not in item.api_response.choices[0] ): # only get the last api_response, not delta response api_response = item.api_response if item.error and not error_occurs: error_occurs = True error_log = item.error_log if error_occurs: # delete all promptmodel data in item item.raw_output = None item.parsed_outputs = None item.function_call = None item.pm_detail = PMDetail( model=version_details["model"], name=self._name, version_uuid=str(version_details["uuid"]), version=version_details["version"], log_uuid=log_uuid, ) yield item metadata = { "error": error_occurs, "error_log": error_log, } await self._async_chat_log_to_cloud( session_uuid=session_uuid, version_uuid=version_details["uuid"], chat_log_request_list=[ ChatLogRequest( uuid=log_uuid, message=api_response.choices[0].message.model_dump(), metadata=metadata, api_response=api_response, ) ], ) return wrapper def _prepare_call_args( self, prompts: List[Dict[str, str]], version_detail: Dict[str, Any], inputs: Dict[str, Any], kwargs, ): stringified_inputs = {key: str(value) for key, value in inputs.items()} messages = [ { "content": prompt["content"].format(**stringified_inputs), "role": prompt["role"], } for prompt in prompts ] call_args = { "messages": messages, "model": version_detail["model"] if version_detail else None, "parsing_type": version_detail["parsing_type"] if version_detail else None, "output_keys": version_detail["output_keys"] if version_detail else None, } if call_args["parsing_type"] is None: del call_args["parsing_type"] del call_args["output_keys"] if "functions" in kwargs: call_args["functions"] = kwargs["functions"] if "tools" in kwargs: call_args["tools"] = kwargs["tools"] if "api_key" in kwargs: call_args["api_key"] = kwargs["api_key"] return call_args def _prepare_call_args_for_chat( self, messages: List[Dict[str, Any]], version_detail: Dict[str, Any], kwargs, ): call_args = {} token_per_tools = 0 if "functions" in kwargs: call_args["functions"] = kwargs["functions"] token_per_tools = num_tokens_from_functions_input( functions=kwargs["functions"], model=version_detail["model"] if version_detail else "gpt-3.5-turbo", ) if "tools" in kwargs: call_args["tools"] = kwargs["tools"] token_per_tools = num_tokens_from_functions_input( functions=kwargs["tools"], model=version_detail["model"] if version_detail else "gpt-3.5-turbo", ) # truncate messages to make length <= model's max length model_max_tokens = get_max_tokens( model=version_detail["model"] if version_detail else "gpt-3.5-turbo" ) token_per_messages = num_tokens_for_messages_for_each( messages, version_detail["model"] ) token_limit_exceeded = ( sum(token_per_messages) + token_per_tools ) - model_max_tokens if token_limit_exceeded > 0: while token_limit_exceeded > 0: # erase the second oldest message (first one is system prompt, so it should not be erased) if len(messages) == 1: # if there is only one message, Error cannot be solved. Just call LLM and get error response break token_limit_exceeded -= token_per_messages[1] del messages[1] del token_per_messages[1] call_args["messages"] = messages call_args["model"] = version_detail["model"] if version_detail else None if "api_key" in kwargs: call_args["api_key"] = kwargs["api_key"] if "tools" in kwargs: call_args["tools"] = kwargs["tools"] return call_args async def _async_log_to_cloud( self, version_uuid: str, log_uuid: str, inputs: Optional[Dict] = None, api_response: Optional[ModelResponse] = None, parsed_outputs: Optional[Dict] = None, metadata: Optional[Dict] = None, ): config = read_config() if ( "project" in config and "mask_inputs" in config["project"] and config["project"]["mask_inputs"] == True ): inputs = {key: "PRIVATE LOGGING" for key, value in inputs.items()} # Perform the logging asynchronously if api_response: api_response_dict = api_response.model_dump() api_response_dict["response_ms"] = api_response._response_ms api_response_dict["_response_ms"] = api_response._response_ms else: api_response_dict = None run_log_request_body = { "uuid": log_uuid, "api_response": api_response_dict, "inputs": inputs, "parsed_outputs": parsed_outputs, "metadata": metadata, } res = await AsyncAPIClient.execute( method="POST", path="/run_log", params={ "version_uuid": version_uuid, }, json=run_log_request_body, use_cli_key=False, ) if res.status_code != 200: print(f"[red]Failed to log to cloud: {res.json()}[/red]"); if self.unit_config: res_connect = await AsyncAPIClient.execute( method="POST", path="/unit/connect", json={ "unit_log_uuid": self.unit_config.log_uuid, "run_log_uuid": log_uuid, }, use_cli_key=False, ) if res_connect.status_code != 200: print(f"[red]Failed to connect prompt component to run log: {res_connect.json()}[/red]") return res async def _async_chat_log_to_cloud( self, session_uuid: str, version_uuid: Optional[str] = None, chat_log_request_list: List[ChatLogRequest] = [], ): # Perform the logging asynchronously res = await AsyncAPIClient.execute( method="POST", path="/chat_log", params={ "session_uuid": session_uuid, "version_uuid": version_uuid, }, json=[r.model_dump() for r in chat_log_request_list], use_cli_key=False, ) if res.status_code != 200: print(f"[red]Failed to log to cloud: {res.json()}[/red]") return res async def _async_make_session_cloud( self, session_uuid: str, version_uuid: Optional[str] = None, ): # Perform the logging asynchronously res = await AsyncAPIClient.execute( method="POST", path="/make_session", params={ "session_uuid": session_uuid, "version_uuid": version_uuid, }, use_cli_key=False, ) if res.status_code != 200: print(f"[red]Failed to make ChatSession in cloud: {res.json()}[/red]") return res def make_kwargs(self, **kwargs): res = {} for key, value in kwargs.items(): if value is not None: res[key] = value return res def run( self, inputs: Dict[str, Any] = {}, functions: Optional[List[Any]] = None, tools: Optional[List[Any]] = None, api_key: Optional[str] = None, ) -> LLMResponse: kwargs = self.make_kwargs(functions=functions, api_key=api_key, tools=tools) return self._wrap_method(super().run)(inputs, **kwargs) def arun( self, inputs: Dict[str, Any] = {}, functions: Optional[List[Any]] = None, tools: Optional[List[Any]] = None, api_key: Optional[str] = None, ) -> LLMResponse: kwargs = self.make_kwargs(functions=functions, api_key=api_key, tools=tools) return self._wrap_async_method(super().arun)(inputs, **kwargs) def stream( self, inputs: Dict[str, Any] = {}, functions: Optional[List[Any]] = None, tools: Optional[List[Any]] = None, api_key: Optional[str] = None, ) -> Generator[LLMStreamResponse, None, None]: kwargs = self.make_kwargs(functions=functions, api_key=api_key, tools=tools) return self._wrap_gen(super().stream)(inputs, **kwargs) def astream( self, inputs: Optional[Dict[str, Any]] = {}, functions: Optional[List[Any]] = None, tools: Optional[List[Any]] = None, api_key: Optional[str] = None, ) -> AsyncGenerator[LLMStreamResponse, None]: kwargs = self.make_kwargs(functions=functions, api_key=api_key, tools=tools) return self._wrap_async_gen(super().astream)(inputs, **kwargs) def run_and_parse( self, inputs: Dict[str, Any] = {}, functions: Optional[List[Any]] = None, tools: Optional[List[Any]] = None, api_key: Optional[str] = None, ) -> LLMResponse: kwargs = self.make_kwargs(functions=functions, api_key=api_key, tools=tools) return self._wrap_method(super().run_and_parse)(inputs, **kwargs) def arun_and_parse( self, inputs: Dict[str, Any] = {}, functions: Optional[List[Any]] = None, tools: Optional[List[Any]] = None, api_key: Optional[str] = None, ) -> LLMResponse: kwargs = self.make_kwargs(functions=functions, api_key=api_key, tools=tools) return self._wrap_async_method(super().arun_and_parse)(inputs, **kwargs) def stream_and_parse( self, inputs: Dict[str, Any] = {}, functions: Optional[List[Any]] = None, tools: Optional[List[Any]] = None, api_key: Optional[str] = None, ) -> Generator[LLMStreamResponse, None, None]: kwargs = self.make_kwargs(functions=functions, api_key=api_key, tools=tools) return self._wrap_gen(super().stream_and_parse)(inputs, **kwargs) def astream_and_parse( self, inputs: Dict[str, Any] = {}, functions: Optional[List[Any]] = None, tools: Optional[List[Any]] = None, api_key: Optional[str] = None, ) -> AsyncGenerator[LLMStreamResponse, None]: kwargs = self.make_kwargs(functions=functions, api_key=api_key, tools=tools) return self._wrap_async_gen(super().astream_and_parse)(inputs, **kwargs) def chat_run( self, session_uuid: str, functions: Optional[List[Any]] = None, tools: Optional[List[Any]] = None, api_key: Optional[str] = None, ) -> LLMResponse: kwargs = self.make_kwargs(functions=functions, api_key=api_key, tools=tools) return self._wrap_chat(super().run)(session_uuid, **kwargs) def chat_arun( self, session_uuid: str, functions: Optional[List[Any]] = None, tools: Optional[List[Any]] = None, api_key: Optional[str] = None, ) -> LLMResponse: kwargs = self.make_kwargs(functions=functions, api_key=api_key, tools=tools) return self._wrap_async_chat(super().arun)(session_uuid, **kwargs) def chat_stream( self, session_uuid: str, functions: Optional[List[Any]] = None, tools: Optional[List[Any]] = None, api_key: Optional[str] = None, ) -> LLMResponse: kwargs = self.make_kwargs(functions=functions, api_key=api_key, tools=tools) return self._wrap_chat_gen(super().stream)(session_uuid, **kwargs) def chat_astream( self, session_uuid: str, functions: Optional[List[Any]] = None, tools: Optional[List[Any]] = None, api_key: Optional[str] = None, ) -> LLMResponse: kwargs = self.make_kwargs(functions=functions, api_key=api_key, tools=tools) return self._wrap_async_chat_gen(super().astream)(session_uuid, **kwargs) @staticmethod async def fetch_prompts( name, version: Optional[Union[str, int]] = "deploy", ) -> Tuple[List[Dict[str, str]], Dict[str, Any]]: """fetch prompts. Args: name (str): name of FunctionModel Returns: Tuple[List[Dict[str, str]], Optional[Dict[str, Any]]]: (prompts, version_detail) """ # Check connection activate config = read_config() if ( "connection" in config and "initializing" in config["connection"] and config["connection"]["initializing"] == True ): return [], {} elif ( "connection" in config and "reloading" in config["connection"] and config["connection"]["reloading"] == True ): return [], {} else: if ( "project" in config and "use_cache" in config["project"] and config["project"]["use_cache"] == True and version == "deploy" ): cache_manager = CacheManager() # call update_local API in background task cache_update_thread = Thread( target=cache_manager.cache_update_background_task, args=(config,) ) cache_update_thread.daemon = True cache_update_thread.start() # get prompt from local DB by ratio prompt_rows, version_detail = get_deployed_prompts(name) if prompt_rows is None: return [], {} return [ {"role": prompt.role, "content": prompt.content} for prompt in prompt_rows ], version_detail else: try: config_list = await AsyncAPIClient.execute( method="GET", path="/function_model_versions", params={"function_model_name": name, "version": version}, use_cli_key=False, ) config_list = config_list.json() except Exception as e: raise e function_model_versions = [ x["function_model_version"] for x in config_list ] if version == "deploy": for version in function_model_versions: if version["is_published"] is True: version["ratio"] = 1.0
selected_version = select_version_by_ratio(function_model_versions)
8
2023-10-09 03:35:44+00:00
24k
MachinePerceptionLab/Attentive_DFPrior
src/DF_Prior.py
[ { "identifier": "config", "path": "src/config.py", "snippet": "def load_config(path, default_path=None):\ndef update_recursive(dict1, dict2):\ndef get_model(cfg):" }, { "identifier": "Mapper", "path": "src/Mapper.py", "snippet": "class Mapper(object):\n \"\"\"\n Mapper thread. \n\n \"\"\"\n\n def __init__(self, cfg, args, slam\n ):\n\n self.cfg = cfg\n self.args = args\n\n self.idx = slam.idx\n self.c = slam.shared_c\n self.bound = slam.bound\n self.logger = slam.logger\n self.mesher = slam.mesher\n self.output = slam.output\n self.verbose = slam.verbose\n self.renderer = slam.renderer\n self.low_gpu_mem = slam.low_gpu_mem\n self.mapping_idx = slam.mapping_idx\n self.mapping_cnt = slam.mapping_cnt\n self.decoders = slam.shared_decoders\n self.estimate_c2w_list = slam.estimate_c2w_list\n self.mapping_first_frame = slam.mapping_first_frame\n self.scene_id = slam.scene_id\n with torch.no_grad():\n self.tsdf_volume_shared = slam.tsdf_volume_shared\n self.tsdf_bnds = slam.tsdf_bnds\n \n \n self.scale = cfg['scale']\n self.occupancy = cfg['occupancy']\n self.sync_method = cfg['sync_method']\n\n self.device = cfg['mapping']['device']\n self.fix_high = cfg['mapping']['fix_high']\n self.eval_rec = cfg['meshing']['eval_rec']\n \n \n self.mesh_freq = cfg['mapping']['mesh_freq']\n self.ckpt_freq = cfg['mapping']['ckpt_freq']\n self.fix_color = cfg['mapping']['fix_color']\n self.mapping_pixels = cfg['mapping']['pixels']\n self.num_joint_iters = cfg['mapping']['iters']\n self.clean_mesh = cfg['meshing']['clean_mesh']\n self.every_frame = cfg['mapping']['every_frame']\n self.color_refine = cfg['mapping']['color_refine']\n self.w_color_loss = cfg['mapping']['w_color_loss']\n self.keyframe_every = cfg['mapping']['keyframe_every']\n self.high_iter_ratio = cfg['mapping']['high_iter_ratio']\n self.low_iter_ratio = cfg['mapping']['low_iter_ratio']\n self.mapping_window_size = cfg['mapping']['mapping_window_size']\n self.no_vis_on_first_frame = cfg['mapping']['no_vis_on_first_frame']\n self.no_log_on_first_frame = cfg['mapping']['no_log_on_first_frame']\n self.no_mesh_on_first_frame = cfg['mapping']['no_mesh_on_first_frame']\n self.frustum_feature_selection = cfg['mapping']['frustum_feature_selection']\n self.keyframe_selection_method = cfg['mapping']['keyframe_selection_method']\n self.save_selected_keyframes_info = cfg['mapping']['save_selected_keyframes_info']\n if self.save_selected_keyframes_info:\n self.selected_keyframes = {}\n\n\n self.keyframe_dict = []\n self.keyframe_list = []\n self.frame_reader = get_dataset(\n cfg, args, self.scale, device=self.device)\n self.n_img = len(self.frame_reader)\n if 'Demo' not in self.output: # disable this visualization in demo\n self.visualizer = Visualizer(freq=cfg['mapping']['vis_freq'], inside_freq=cfg['mapping']['vis_inside_freq'],\n vis_dir=os.path.join(self.output, 'mapping_vis'), renderer=self.renderer,\n verbose=self.verbose, device=self.device)\n self.H, self.W, self.fx, self.fy, self.cx, self.cy = slam.H, slam.W, slam.fx, slam.fy, slam.cx, slam.cy\n\n def get_mask_from_c2w(self, c2w, key, val_shape, depth_np):\n \"\"\"\n Frustum feature selection based on current camera pose and depth image.\n\n Args:\n c2w (tensor): camera pose of current frame.\n key (str): name of this feature grid.\n val_shape (tensor): shape of the grid.\n depth_np (numpy.array): depth image of current frame.\n\n Returns:\n mask (tensor): mask for selected optimizable feature.\n points (tensor): corresponding point coordinates.\n \"\"\"\n H, W, fx, fy, cx, cy, = self.H, self.W, self.fx, self.fy, self.cx, self.cy\n X, Y, Z = torch.meshgrid(torch.linspace(self.bound[0][0], self.bound[0][1], val_shape[2]),\n torch.linspace(self.bound[1][0], self.bound[1][1], val_shape[1]),\n torch.linspace(self.bound[2][0], self.bound[2][1], val_shape[0]))\n\n points = torch.stack([X, Y, Z], dim=-1).reshape(-1, 3)\n points_bak = points.clone()\n c2w = c2w.cpu().numpy()\n w2c = np.linalg.inv(c2w)\n ones = np.ones_like(points[:, 0]).reshape(-1, 1)\n homo_vertices = np.concatenate(\n [points, ones], axis=1).reshape(-1, 4, 1)\n cam_cord_homo = w2c@homo_vertices\n cam_cord = cam_cord_homo[:, :3]\n K = np.array([[fx, .0, cx], [.0, fy, cy], [.0, .0, 1.0]]).reshape(3, 3)\n cam_cord[:, 0] *= -1\n uv = K@cam_cord\n z = uv[:, -1:]+1e-5\n uv = uv[:, :2]/z\n uv = uv.astype(np.float32)\n\n remap_chunk = int(3e4)\n depths = []\n for i in range(0, uv.shape[0], remap_chunk):\n depths += [cv2.remap(depth_np,\n uv[i:i+remap_chunk, 0],\n uv[i:i+remap_chunk, 1],\n interpolation=cv2.INTER_LINEAR)[:, 0].reshape(-1, 1)]\n depths = np.concatenate(depths, axis=0)\n\n edge = 0\n mask = (uv[:, 0] < W-edge)*(uv[:, 0] > edge) * \\\n (uv[:, 1] < H-edge)*(uv[:, 1] > edge)\n\n # For ray with depth==0, fill it with maximum depth\n zero_mask = (depths == 0)\n depths[zero_mask] = np.max(depths)\n\n # depth test\n mask = mask & (0 <= -z[:, :, 0]) & (-z[:, :, 0] <= depths+0.5)\n mask = mask.reshape(-1)\n\n # add feature grid near cam center\n ray_o = c2w[:3, 3]\n ray_o = torch.from_numpy(ray_o).unsqueeze(0)\n\n dist = points_bak-ray_o\n dist = torch.sum(dist*dist, axis=1)\n mask2 = dist < 0.5*0.5\n mask2 = mask2.cpu().numpy()\n mask = mask | mask2\n\n points = points[mask]\n mask = mask.reshape(val_shape[2], val_shape[1], val_shape[0])\n return mask\n\n def keyframe_selection_overlap(self, gt_color, gt_depth, c2w, keyframe_dict, k, N_samples=16, pixels=100):\n \"\"\"\n Select overlapping keyframes to the current camera observation.\n\n Args:\n gt_color (tensor): ground truth color image of the current frame.\n gt_depth (tensor): ground truth depth image of the current frame.\n c2w (tensor): camera to world matrix (3*4 or 4*4 both fine).\n keyframe_dict (list): a list containing info for each keyframe.\n k (int): number of overlapping keyframes to select.\n N_samples (int, optional): number of samples/points per ray. Defaults to 16.\n pixels (int, optional): number of pixels to sparsely sample \n from the image of the current camera. Defaults to 100.\n Returns:\n selected_keyframe_list (list): list of selected keyframe id.\n \"\"\"\n device = self.device\n H, W, fx, fy, cx, cy = self.H, self.W, self.fx, self.fy, self.cx, self.cy\n\n rays_o, rays_d, gt_depth, gt_color = get_samples(\n 0, H, 0, W, pixels, H, W, fx, fy, cx, cy, c2w, gt_depth, gt_color, self.device)\n\n gt_depth = gt_depth.reshape(-1, 1)\n gt_depth = gt_depth.repeat(1, N_samples)\n t_vals = torch.linspace(0., 1., steps=N_samples).to(device)\n near = gt_depth*0.8\n far = gt_depth+0.5\n z_vals = near * (1.-t_vals) + far * (t_vals)\n pts = rays_o[..., None, :] + rays_d[..., None, :] * \\\n z_vals[..., :, None] # [N_rays, N_samples, 3]\n vertices = pts.reshape(-1, 3).cpu().numpy()\n list_keyframe = []\n for keyframeid, keyframe in enumerate(keyframe_dict):\n c2w = keyframe['est_c2w'].cpu().numpy()\n w2c = np.linalg.inv(c2w)\n ones = np.ones_like(vertices[:, 0]).reshape(-1, 1)\n homo_vertices = np.concatenate(\n [vertices, ones], axis=1).reshape(-1, 4, 1) # (N, 4)\n cam_cord_homo = w2c@homo_vertices # (N, 4, 1)=(4,4)*(N, 4, 1)\n cam_cord = cam_cord_homo[:, :3] # (N, 3, 1)\n K = np.array([[fx, .0, cx], [.0, fy, cy],\n [.0, .0, 1.0]]).reshape(3, 3)\n cam_cord[:, 0] *= -1\n uv = K@cam_cord\n z = uv[:, -1:]+1e-5\n uv = uv[:, :2]/z\n uv = uv.astype(np.float32)\n edge = 20\n mask = (uv[:, 0] < W-edge)*(uv[:, 0] > edge) * \\\n (uv[:, 1] < H-edge)*(uv[:, 1] > edge)\n mask = mask & (z[:, :, 0] < 0)\n mask = mask.reshape(-1)\n percent_inside = mask.sum()/uv.shape[0]\n list_keyframe.append(\n {'id': keyframeid, 'percent_inside': percent_inside})\n\n list_keyframe = sorted(\n list_keyframe, key=lambda i: i['percent_inside'], reverse=True)\n selected_keyframe_list = [dic['id']\n for dic in list_keyframe if dic['percent_inside'] > 0.00]\n selected_keyframe_list = list(np.random.permutation(\n np.array(selected_keyframe_list))[:k])\n return selected_keyframe_list\n \n def eval_points(self, p, decoders, tsdf_volume, tsdf_bnds, c=None, stage='color', device='cuda:0'):\n \"\"\"\n Evaluates the occupancy and/or color value for the points.\n\n Args:\n p (tensor, N*3): point coordinates.\n decoders (nn.module decoders): decoders.\n c (dicts, optional): feature grids. Defaults to None.\n stage (str, optional): query stage, corresponds to different levels. Defaults to 'color'.\n device (str, optional): device name to compute on. Defaults to 'cuda:0'.\n\n Returns:\n ret (tensor): occupancy (and color) value of input points.\n \"\"\"\n\n p_split = torch.split(p, 500)\n bound = self.bound\n rets = []\n for pi in p_split:\n # mask for points out of bound\n mask_x = (pi[:, 0] < bound[0][1]) & (pi[:, 0] > bound[0][0])\n mask_y = (pi[:, 1] < bound[1][1]) & (pi[:, 1] > bound[1][0])\n mask_z = (pi[:, 2] < bound[2][1]) & (pi[:, 2] > bound[2][0])\n mask = mask_x & mask_y & mask_z\n\n pi = pi.unsqueeze(0)\n ret, _ = decoders(pi, c_grid=c, tsdf_volume=tsdf_volume, tsdf_bnds=tsdf_bnds, stage=stage)\n \n ret = ret.squeeze(0)\n if len(ret.shape) == 1 and ret.shape[0] == 4:\n ret = ret.unsqueeze(0)\n\n ret[~mask, 3] = 100\n rets.append(ret)\n\n ret = torch.cat(rets, dim=0)\n return ret\n\n def optimize_map(self, num_joint_iters, lr_factor, idx, cur_gt_color, cur_gt_depth, gt_cur_c2w, keyframe_dict, keyframe_list, tsdf_volume, cur_c2w):\n \"\"\"\n Mapping iterations. Sample pixels from selected keyframes,\n then optimize scene representation.\n\n Args:\n num_joint_iters (int): number of mapping iterations.\n lr_factor (float): the factor to times on current lr.\n idx (int): the index of current frame\n cur_gt_color (tensor): gt_color image of the current camera.\n cur_gt_depth (tensor): gt_depth image of the current camera.\n gt_cur_c2w (tensor): groundtruth camera to world matrix corresponding to current frame.\n keyframe_dict (list): list of keyframes info dictionary.\n keyframe_list (list): list ofkeyframe index.\n tsdf_volume (tensor): tsdf volume.\n cur_c2w (tensor): the estimated camera to world matrix of current frame. \n\n Returns:\n return None\n \"\"\"\n H, W, fx, fy, cx, cy = self.H, self.W, self.fx, self.fy, self.cx, self.cy\n c = self.c\n cfg = self.cfg\n device = self.device\n tsdf_bnds = self.tsdf_bnds.to(device)\n\n if len(keyframe_dict) == 0:\n optimize_frame = []\n else:\n if self.keyframe_selection_method == 'global':\n num = self.mapping_window_size-2\n optimize_frame = random_select(len(self.keyframe_dict)-1, num)\n elif self.keyframe_selection_method == 'overlap':\n num = self.mapping_window_size-2\n optimize_frame = self.keyframe_selection_overlap(\n cur_gt_color, cur_gt_depth, cur_c2w, keyframe_dict[:-1], num)\n\n # add the last keyframe and the current frame(use -1 to denote)\n oldest_frame = None\n if len(keyframe_list) > 0:\n optimize_frame = optimize_frame + [len(keyframe_list)-1]\n oldest_frame = min(optimize_frame)\n optimize_frame += [-1]\n\n if self.save_selected_keyframes_info:\n keyframes_info = []\n for id, frame in enumerate(optimize_frame):\n if frame != -1:\n frame_idx = keyframe_list[frame]\n tmp_gt_c2w = keyframe_dict[frame]['gt_c2w']\n tmp_est_c2w = keyframe_dict[frame]['est_c2w']\n else:\n frame_idx = idx\n tmp_gt_c2w = gt_cur_c2w\n tmp_est_c2w = cur_c2w\n keyframes_info.append(\n {'idx': frame_idx, 'gt_c2w': tmp_gt_c2w, 'est_c2w': tmp_est_c2w})\n self.selected_keyframes[idx] = keyframes_info\n\n pixs_per_image = self.mapping_pixels//len(optimize_frame)\n\n mlp_para_list = []\n decoders_para_list = []\n low_grid_para = []\n high_grid_para = []\n color_grid_para = []\n gt_depth_np = cur_gt_depth.cpu().numpy()\n if True:\n if self.frustum_feature_selection:\n masked_c_grad = {}\n mask_c2w = cur_c2w\n for key, val in c.items():\n if not self.frustum_feature_selection:\n val = Variable(val.to(device), requires_grad=True)\n c[key] = val\n if key == 'grid_low':\n low_grid_para.append(val)\n elif key == 'grid_high':\n high_grid_para.append(val)\n elif key == 'grid_color':\n color_grid_para.append(val)\n\n else:\n mask = self.get_mask_from_c2w(\n mask_c2w, key, val.shape[2:], gt_depth_np)\n mask = torch.from_numpy(mask).permute(2, 1, 0).unsqueeze(\n 0).unsqueeze(0).repeat(1, val.shape[1], 1, 1, 1)\n val = val.to(device)\n # val_grad is the optimizable part, other parameters will be fixed\n val_grad = val[mask].clone()\n val_grad = Variable(val_grad.to(\n device), requires_grad=True)\n masked_c_grad[key] = val_grad\n masked_c_grad[key+'mask'] = mask\n if key == 'grid_low':\n low_grid_para.append(val_grad)\n elif key == 'grid_high':\n high_grid_para.append(val_grad)\n elif key == 'grid_color':\n color_grid_para.append(val_grad)\n\n\n if not self.fix_high:\n decoders_para_list += list(\n self.decoders.high_decoder.parameters())\n if not self.fix_color:\n decoders_para_list += list(\n self.decoders.color_decoder.parameters())\n mlp_para_list += list(\n self.decoders.mlp.parameters())\n \n\n optimizer = torch.optim.Adam([{'params': decoders_para_list, 'lr': 0},\n {'params': mlp_para_list, 'lr': 0},\n {'params': low_grid_para, 'lr': 0},\n {'params': high_grid_para, 'lr': 0},\n {'params': color_grid_para, 'lr': 0}])\n \n\n for joint_iter in range(num_joint_iters):\n if self.frustum_feature_selection:\n for key, val in c.items():\n val_grad = masked_c_grad[key]\n mask = masked_c_grad[key+'mask']\n val = val.to(device)\n val[mask] = val_grad\n c[key] = val\n\n if joint_iter <= int(num_joint_iters*self.low_iter_ratio):\n self.stage = 'low'\n elif joint_iter <= int(num_joint_iters*self.high_iter_ratio):\n self.stage = 'high'\n else:\n self.stage = 'color'\n\n optimizer.param_groups[0]['lr'] = cfg['mapping']['stage'][self.stage]['decoders_lr']*lr_factor\n optimizer.param_groups[1]['lr'] = cfg['mapping']['stage'][self.stage]['mlp_lr']*lr_factor\n optimizer.param_groups[2]['lr'] = cfg['mapping']['stage'][self.stage]['low_lr']*lr_factor\n optimizer.param_groups[3]['lr'] = cfg['mapping']['stage'][self.stage]['high_lr']*lr_factor\n optimizer.param_groups[4]['lr'] = cfg['mapping']['stage'][self.stage]['color_lr']*lr_factor\n \n if (not (idx == 0 and self.no_vis_on_first_frame)) and ('Demo' not in self.output):\n self.visualizer.vis(\n idx, joint_iter, cur_gt_depth, cur_gt_color, cur_c2w, self.c, self.decoders, tsdf_volume, tsdf_bnds)\n\n optimizer.zero_grad()\n batch_rays_d_list = []\n batch_rays_o_list = []\n batch_gt_depth_list = []\n batch_gt_color_list = []\n\n camera_tensor_id = 0\n for frame in optimize_frame:\n if frame != -1:\n gt_depth = keyframe_dict[frame]['depth'].to(device)\n gt_color = keyframe_dict[frame]['color'].to(device)\n c2w = keyframe_dict[frame]['est_c2w']\n\n else:\n gt_depth = cur_gt_depth.to(device)\n gt_color = cur_gt_color.to(device)\n c2w = cur_c2w\n\n batch_rays_o, batch_rays_d, batch_gt_depth, batch_gt_color = get_samples(\n 0, H, 0, W, pixs_per_image, H, W, fx, fy, cx, cy, c2w, gt_depth, gt_color, self.device)\n batch_rays_o_list.append(batch_rays_o.float())\n batch_rays_d_list.append(batch_rays_d.float())\n batch_gt_depth_list.append(batch_gt_depth.float())\n batch_gt_color_list.append(batch_gt_color.float())\n\n batch_rays_d = torch.cat(batch_rays_d_list)\n batch_rays_o = torch.cat(batch_rays_o_list)\n batch_gt_depth = torch.cat(batch_gt_depth_list)\n batch_gt_color = torch.cat(batch_gt_color_list)\n\n\n # should pre-filter those out of bounding box depth value\n with torch.no_grad():\n det_rays_o = batch_rays_o.clone().detach().unsqueeze(-1) # (N, 3, 1)\n det_rays_d = batch_rays_d.clone().detach().unsqueeze(-1) # (N, 3, 1)\n t = (self.bound.unsqueeze(0).to(\n device)-det_rays_o)/det_rays_d\n t, _ = torch.min(torch.max(t, dim=2)[0], dim=1)\n inside_mask = t >= batch_gt_depth\n batch_rays_d = batch_rays_d[inside_mask]\n batch_rays_o = batch_rays_o[inside_mask]\n batch_gt_depth = batch_gt_depth[inside_mask]\n batch_gt_color = batch_gt_color[inside_mask]\n\n ret = self.renderer.render_batch_ray(c, self.decoders, batch_rays_d,\n batch_rays_o, device, tsdf_volume, tsdf_bnds, self.stage,\n batch_gt_depth)\n depth, uncertainty, color, weight = ret\n\n\n depth_mask = (batch_gt_depth > 0)\n \n if joint_iter > int(num_joint_iters*self.low_iter_ratio) and joint_iter <= int(num_joint_iters*self.low_iter_ratio)+5 and idx <= 1:\n loss = torch.abs(\n batch_gt_depth[depth_mask]-depth[depth_mask]).sum() + torch.abs(weight-torch.ones(weight.shape).to(device)).sum()\n else:\n loss = torch.abs(\n batch_gt_depth[depth_mask]-depth[depth_mask]).sum()\n \n if self.stage == 'color':\n color_loss = torch.abs(batch_gt_color - color).sum()\n weighted_color_loss = self.w_color_loss*color_loss\n loss += weighted_color_loss\n\n loss.backward(retain_graph=False)\n optimizer.step()\n optimizer.zero_grad()\n\n # put selected and updated features back to the grid\n if self.frustum_feature_selection:\n for key, val in c.items():\n val_grad = masked_c_grad[key]\n mask = masked_c_grad[key+'mask']\n val = val.detach()\n val[mask] = val_grad.clone().detach()\n c[key] = val\n\n return None\n\n\n def run(self):\n cfg = self.cfg\n idx, gt_color, gt_depth, gt_c2w = self.frame_reader[0]\n\n self.estimate_c2w_list[0] = gt_c2w.cpu()\n init = True\n prev_idx = -1\n tsdf_volume = self.tsdf_volume_shared\n \n while (1):\n while True:\n idx = self.idx[0].clone()\n if idx == self.n_img-1:\n break\n if self.sync_method == 'strict':\n if idx % self.every_frame == 0 and idx != prev_idx:\n break\n elif self.sync_method == 'loose':\n if idx == 0 or idx >= prev_idx+self.every_frame//2:\n break\n elif self.sync_method == 'free':\n break\n time.sleep(0.1)\n prev_idx = idx\n\n if self.verbose:\n print(Fore.GREEN)\n prefix = ''\n print(prefix+\"Mapping Frame \", idx.item())\n print(Style.RESET_ALL)\n\n _, gt_color, gt_depth, gt_c2w = self.frame_reader[idx]\n\n # valid c2w\n valid_c2w = gt_c2w.clone().cpu().numpy()\n if not np.isfinite(valid_c2w).any():\n self.mapping_idx[0] = idx\n continue\n\n\n if not init:\n lr_factor = cfg['mapping']['lr_factor']\n num_joint_iters = cfg['mapping']['iters']\n\n # here provides a color refinement postprocess\n if idx == self.n_img-1 and self.color_refine:\n outer_joint_iters = 5\n self.mapping_window_size *= 2\n self.low_iter_ratio = 0.0\n self.high_iter_ratio = 0.0\n num_joint_iters *= 5\n self.fix_color = True\n self.frustum_feature_selection = False\n else:\n outer_joint_iters = 1\n \n\n else:\n outer_joint_iters = 1\n lr_factor = cfg['mapping']['lr_first_factor']\n num_joint_iters = cfg['mapping']['iters_first']\n\n cur_c2w = self.estimate_c2w_list[idx].to(self.device)\n num_joint_iters = num_joint_iters//outer_joint_iters\n \n for outer_joint_iter in range(outer_joint_iters):\n\n\n _ = self.optimize_map(num_joint_iters, lr_factor, idx, gt_color, gt_depth,\n gt_c2w, self.keyframe_dict, self.keyframe_list, tsdf_volume, cur_c2w=cur_c2w)\n \n\n # add new frame to keyframe set\n if outer_joint_iter == outer_joint_iters-1:\n if (idx % self.keyframe_every == 0 or (idx == self.n_img-2)) \\\n and (idx not in self.keyframe_list):\n self.keyframe_list.append(idx)\n self.keyframe_dict.append({'gt_c2w': gt_c2w.cpu(), 'idx': idx, 'color': gt_color.cpu(\n ), 'depth': gt_depth.cpu(), 'est_c2w': cur_c2w.clone()})\n\n if self.low_gpu_mem:\n torch.cuda.empty_cache()\n\n init = False\n # mapping of first frame is done, can begin tracking\n self.mapping_first_frame[0] = 1\n\n if True:\n if ((not (idx == 0 and self.no_log_on_first_frame)) and idx % self.ckpt_freq == 0) \\\n or idx == self.n_img-1 or (idx == 4640 and self.scene_id==50):\n self.logger.log(idx, self.keyframe_dict, self.keyframe_list,\n selected_keyframes=self.selected_keyframes\n if self.save_selected_keyframes_info else None)\n\n self.mapping_idx[0] = idx\n self.mapping_cnt[0] += 1\n\n if (idx % self.mesh_freq == 0) and (not (idx == 0 and self.no_mesh_on_first_frame)):\n mesh_out_file = f'{self.output}/mesh/{idx:05d}_mesh.ply'\n self.mesher.get_mesh(mesh_out_file, self.c, self.decoders, self.keyframe_dict, self.estimate_c2w_list,\n idx, tsdf_volume, self.device,\n clean_mesh=self.clean_mesh, get_mask_use_all_frames=False)\n\n if idx == self.n_img-1 or (idx == 4640 and self.scene_id==50):\n mesh_out_file = f'{self.output}/mesh/final_mesh.ply'\n self.mesher.get_mesh(mesh_out_file, self.c, self.decoders, self.keyframe_dict, self.estimate_c2w_list,\n idx, tsdf_volume, self.device,\n clean_mesh=self.clean_mesh, get_mask_use_all_frames=False)\n os.system(\n f\"cp {mesh_out_file} {self.output}/mesh/{idx:05d}_mesh.ply\")\n if self.eval_rec:\n mesh_out_file = f'{self.output}/mesh/final_mesh_eval_rec.ply'\n self.mesher.get_mesh(mesh_out_file, self.c, self.decoders, self.keyframe_dict,\n self.estimate_c2w_list, idx, tsdf_volume, self.device,\n clean_mesh=self.clean_mesh, get_mask_use_all_frames=True)\n break\n\n if idx == self.n_img-1 or (idx == 4640 and self.scene_id==50):\n break" }, { "identifier": "Tracker", "path": "src/Tracker.py", "snippet": "class Tracker(object):\n def __init__(self, cfg, args, slam\n ):\n self.cfg = cfg\n self.args = args\n\n self.scale = cfg['scale']\n self.occupancy = cfg['occupancy']\n self.sync_method = cfg['sync_method']\n\n self.idx = slam.idx\n self.bound = slam.bound\n self.mesher = slam.mesher\n self.output = slam.output\n self.verbose = slam.verbose\n self.shared_c = slam.shared_c\n self.renderer = slam.renderer\n self.gt_c2w_list = slam.gt_c2w_list\n self.low_gpu_mem = slam.low_gpu_mem\n self.mapping_idx = slam.mapping_idx\n self.mapping_cnt = slam.mapping_cnt\n self.shared_decoders = slam.shared_decoders\n self.estimate_c2w_list = slam.estimate_c2w_list\n with torch.no_grad():\n self.tsdf_volume_shared = slam.tsdf_volume_shared\n self.tsdf_bnds = slam.tsdf_bnds\n\n\n self.cam_lr = cfg['tracking']['lr']\n self.device = cfg['tracking']['device']\n self.num_cam_iters = cfg['tracking']['iters']\n self.gt_camera = cfg['tracking']['gt_camera']\n self.tracking_pixels = cfg['tracking']['pixels']\n self.seperate_LR = cfg['tracking']['seperate_LR']\n self.w_color_loss = cfg['tracking']['w_color_loss']\n self.ignore_edge_W = cfg['tracking']['ignore_edge_W']\n self.ignore_edge_H = cfg['tracking']['ignore_edge_H']\n self.handle_dynamic = cfg['tracking']['handle_dynamic']\n self.use_color_in_tracking = cfg['tracking']['use_color_in_tracking']\n self.const_speed_assumption = cfg['tracking']['const_speed_assumption']\n\n self.every_frame = cfg['mapping']['every_frame'] \n self.no_vis_on_first_frame = cfg['mapping']['no_vis_on_first_frame'] # ori mapping\n\n self.prev_mapping_idx = -1\n self.frame_reader = get_dataset(\n cfg, args, self.scale, device=self.device)\n self.n_img = len(self.frame_reader)\n self.frame_loader = DataLoader(\n self.frame_reader, batch_size=1, shuffle=False, num_workers=1)\n self.visualizer = Visualizer(freq=cfg['tracking']['vis_freq'], inside_freq=cfg['tracking']['vis_inside_freq'],\n vis_dir=os.path.join(self.output, 'vis' if 'Demo' in self.output else 'tracking_vis'),\n renderer=self.renderer, verbose=self.verbose, device=self.device)\n self.H, self.W, self.fx, self.fy, self.cx, self.cy = slam.H, slam.W, slam.fx, slam.fy, slam.cx, slam.cy\n\n def optimize_cam_in_batch(self, camera_tensor, gt_color, gt_depth, batch_size, optimizer, tsdf_volume):\n \"\"\"\n Do one iteration of camera iteration. Sample pixels, render depth/color, calculate loss and backpropagation.\n\n Args:\n camera_tensor (tensor): camera tensor.\n gt_color (tensor): ground truth color image of the current frame.\n gt_depth (tensor): ground truth depth image of the current frame.\n batch_size (int): batch size, number of sampling rays.\n optimizer (torch.optim): camera optimizer.\n tsdf_volume (tensor): tsdf volume\n\n Returns:\n loss (float): The value of loss.\n \"\"\"\n device = self.device\n H, W, fx, fy, cx, cy = self.H, self.W, self.fx, self.fy, self.cx, self.cy\n optimizer.zero_grad()\n c2w = get_camera_from_tensor(camera_tensor)\n tsdf_bnds = self.tsdf_bnds.to(device)\n Wedge = self.ignore_edge_W\n Hedge = self.ignore_edge_H\n batch_rays_o, batch_rays_d, batch_gt_depth, batch_gt_color = get_samples(\n Hedge, H-Hedge, Wedge, W-Wedge, batch_size, H, W, fx, fy, cx, cy, c2w, gt_depth, gt_color, self.device)\n \n # should pre-filter those out of bounding box depth value\n with torch.no_grad():\n det_rays_o = batch_rays_o.clone().detach().unsqueeze(-1) # (N, 3, 1)\n det_rays_d = batch_rays_d.clone().detach().unsqueeze(-1) # (N, 3, 1)\n t = (self.bound.unsqueeze(0).to(device)-det_rays_o)/det_rays_d\n t, _ = torch.min(torch.max(t, dim=2)[0], dim=1)\n inside_mask = t >= batch_gt_depth\n batch_rays_d = batch_rays_d[inside_mask]\n batch_rays_o = batch_rays_o[inside_mask]\n batch_gt_depth = batch_gt_depth[inside_mask]\n batch_gt_color = batch_gt_color[inside_mask]\n\n ret = self.renderer.render_batch_ray(\n self.c, self.decoders, batch_rays_d, batch_rays_o, self.device, tsdf_volume, tsdf_bnds, stage='color', gt_depth=batch_gt_depth) #color\n depth, uncertainty, color, _ = ret\n\n uncertainty = uncertainty.detach()\n if self.handle_dynamic:\n tmp = torch.abs(batch_gt_depth-depth)/torch.sqrt(uncertainty+1e-10)\n mask = (tmp < 10*tmp.median()) & (batch_gt_depth > 0)\n else:\n mask = batch_gt_depth > 0\n\n loss = (torch.abs(batch_gt_depth-depth) /\n torch.sqrt(uncertainty+1e-10))[mask].sum()\n\n if self.use_color_in_tracking:\n color_loss = torch.abs(\n batch_gt_color - color)[mask].sum()\n loss += self.w_color_loss*color_loss\n \n loss.backward(retain_graph=False)\n optimizer.step()\n optimizer.zero_grad()\n return loss.item()\n\n def update_para_from_mapping(self):\n \"\"\"\n Update the parameters of scene representation from the mapping thread.\n\n \"\"\"\n if self.mapping_idx[0] != self.prev_mapping_idx:\n if self.verbose:\n print('Tracking: update the parameters from mapping')\n self.decoders = copy.deepcopy(self.shared_decoders).to(self.device)\n for key, val in self.shared_c.items():\n val = val.clone().to(self.device)\n self.c[key] = val\n self.prev_mapping_idx = self.mapping_idx[0].clone()\n\n def run(self):\n device = self.device\n tsdf_volume = self.tsdf_volume_shared\n tsdf_bnds = self.tsdf_bnds.to(device)\n \n self.c = {}\n if self.verbose:\n pbar = self.frame_loader\n else:\n pbar = tqdm(self.frame_loader)\n\n for idx, gt_color, gt_depth, gt_c2w in pbar:\n if not self.verbose:\n pbar.set_description(f\"Tracking Frame {idx[0]}\")\n\n idx = idx[0]\n gt_depth = gt_depth[0]\n gt_color = gt_color[0]\n gt_c2w = gt_c2w[0]\n\n if self.sync_method == 'strict':\n # strictly mapping and then tracking\n # initiate mapping every self.every_frame frames\n if idx > 0 and (idx % self.every_frame == 1 or self.every_frame == 1):\n while self.mapping_idx[0] != idx-1:\n time.sleep(0.1)\n pre_c2w = self.estimate_c2w_list[idx-1].to(device)\n elif self.sync_method == 'loose':\n # mapping idx can be later than tracking idx is within the bound of\n # [-self.every_frame-self.every_frame//2, -self.every_frame+self.every_frame//2]\n while self.mapping_idx[0] < idx-self.every_frame-self.every_frame//2:\n time.sleep(0.1)\n elif self.sync_method == 'free':\n # pure parallel, if mesh/vis happens may cause inbalance\n pass\n\n self.update_para_from_mapping()\n\n if self.verbose:\n print(Fore.MAGENTA)\n print(\"Tracking Frame \", idx.item())\n print(Style.RESET_ALL)\n \n \n\n if idx == 0 or self.gt_camera:\n c2w = gt_c2w\n if not self.no_vis_on_first_frame:\n self.visualizer.vis(\n idx, 0, gt_depth, gt_color, c2w, self.c, self.decoders, tsdf_volume, tsdf_bnds)\n \n else:\n gt_camera_tensor = get_tensor_from_camera(gt_c2w)\n if self.const_speed_assumption and idx-2 >= 0:\n pre_c2w = pre_c2w.float()\n delta = [email protected]_c2w_list[idx-2].to(\n device).float().inverse()\n estimated_new_cam_c2w = delta@pre_c2w\n else:\n estimated_new_cam_c2w = pre_c2w\n\n camera_tensor = get_tensor_from_camera(\n estimated_new_cam_c2w.detach())\n if self.seperate_LR:\n camera_tensor = camera_tensor.to(device).detach()\n T = camera_tensor[-3:]\n quad = camera_tensor[:4]\n cam_para_list_quad = [quad]\n quad = Variable(quad, requires_grad=True)\n T = Variable(T, requires_grad=True)\n camera_tensor = torch.cat([quad, T], 0)\n cam_para_list_T = [T]\n cam_para_list_quad = [quad]\n optimizer_camera = torch.optim.Adam([{'params': cam_para_list_T, 'lr': self.cam_lr},\n {'params': cam_para_list_quad, 'lr': self.cam_lr*0.2}])\n else:\n camera_tensor = Variable(\n camera_tensor.to(device), requires_grad=True)\n cam_para_list = [camera_tensor]\n optimizer_camera = torch.optim.Adam(\n cam_para_list, lr=self.cam_lr)\n\n initial_loss_camera_tensor = torch.abs(\n gt_camera_tensor.to(device)-camera_tensor).mean().item()\n candidate_cam_tensor = None\n current_min_loss = 10000000000.\n\n \n\n for cam_iter in range(self.num_cam_iters):\n if self.seperate_LR:\n camera_tensor = torch.cat([quad, T], 0).to(self.device)\n\n self.visualizer.vis(\n idx, cam_iter, gt_depth, gt_color, camera_tensor, self.c, self.decoders, tsdf_volume, tsdf_bnds)\n\n loss = self.optimize_cam_in_batch(\n camera_tensor, gt_color, gt_depth, self.tracking_pixels, optimizer_camera, tsdf_volume)\n\n if cam_iter == 0:\n initial_loss = loss\n\n loss_camera_tensor = torch.abs(\n gt_camera_tensor.to(device)-camera_tensor).mean().item()\n if self.verbose:\n if cam_iter == self.num_cam_iters-1:\n print(\n f'Re-rendering loss: {initial_loss:.2f}->{loss:.2f} ' +\n f'camera tensor error: {initial_loss_camera_tensor:.4f}->{loss_camera_tensor:.4f}')\n if loss < current_min_loss:\n current_min_loss = loss\n candidate_cam_tensor = camera_tensor.clone().detach()\n bottom = torch.from_numpy(np.array([0, 0, 0, 1.]).reshape(\n [1, 4])).type(torch.float32).to(self.device)\n c2w = get_camera_from_tensor(\n candidate_cam_tensor.clone().detach())\n c2w = torch.cat([c2w, bottom], dim=0)\n\n \n self.estimate_c2w_list[idx] = c2w.clone().cpu()\n self.gt_c2w_list[idx] = gt_c2w.clone().cpu()\n pre_c2w = c2w.clone()\n self.idx[0] = idx\n if self.low_gpu_mem:\n torch.cuda.empty_cache()" }, { "identifier": "get_dataset", "path": "src/utils/datasets.py", "snippet": "def get_dataset(cfg, args, scale, device='cuda:0'):\n return dataset_dict[cfg['dataset']](cfg, args, scale, device=device)" }, { "identifier": "Logger", "path": "src/utils/Logger.py", "snippet": "class Logger(object):\n \"\"\"\n Save checkpoints to file.\n\n \"\"\"\n\n def __init__(self, cfg, args, slam\n ):\n self.verbose = slam.verbose\n self.ckptsdir = slam.ckptsdir\n self.shared_c = slam.shared_c\n self.gt_c2w_list = slam.gt_c2w_list\n self.shared_decoders = slam.shared_decoders\n self.estimate_c2w_list = slam.estimate_c2w_list\n self.tsdf_volume = slam.tsdf_volume_shared\n\n def log(self, idx, keyframe_dict, keyframe_list, selected_keyframes=None):\n path = os.path.join(self.ckptsdir, '{:05d}.tar'.format(idx))\n torch.save({\n 'c': self.shared_c,\n 'decoder_state_dict': self.shared_decoders.state_dict(),\n 'gt_c2w_list': self.gt_c2w_list,\n 'estimate_c2w_list': self.estimate_c2w_list,\n 'keyframe_list': keyframe_list,\n 'keyframe_dict': keyframe_dict, # to save keyframe_dict into ckpt, uncomment this line\n 'selected_keyframes': selected_keyframes,\n 'idx': idx,\n 'tsdf_volume': self.tsdf_volume,\n }, path, _use_new_zipfile_serialization=False)\n\n if self.verbose:\n print('Saved checkpoints at', path)" }, { "identifier": "Mesher", "path": "src/utils/Mesher.py", "snippet": "class Mesher(object):\n\n def __init__(self, cfg, args, slam, points_batch_size=500000, ray_batch_size=100000):\n \"\"\"\n Mesher class, given a scene representation, the mesher extracts the mesh from it.\n\n Args:\n cfg (dict): parsed config dict.\n args (class 'argparse.Namespace'): argparse arguments.\n slam (class DF_Prior): DF_Prior main class.\n points_batch_size (int): maximum points size for query in one batch. \n Used to alleviate GPU memeory usage. Defaults to 500000.\n ray_batch_size (int): maximum ray size for query in one batch. \n Used to alleviate GPU memeory usage. Defaults to 100000.\n \"\"\"\n self.points_batch_size = points_batch_size\n self.ray_batch_size = ray_batch_size\n self.renderer = slam.renderer\n self.scale = cfg['scale']\n self.occupancy = cfg['occupancy']\n \n self.resolution = cfg['meshing']['resolution']\n self.level_set = cfg['meshing']['level_set']\n self.clean_mesh_bound_scale = cfg['meshing']['clean_mesh_bound_scale']\n self.remove_small_geometry_threshold = cfg['meshing']['remove_small_geometry_threshold']\n self.color_mesh_extraction_method = cfg['meshing']['color_mesh_extraction_method']\n self.get_largest_components = cfg['meshing']['get_largest_components']\n self.depth_test = cfg['meshing']['depth_test']\n \n self.bound = slam.bound\n self.verbose = slam.verbose\n \n\n self.marching_cubes_bound = torch.from_numpy(\n np.array(cfg['mapping']['marching_cubes_bound']) * self.scale)\n\n self.frame_reader = get_dataset(cfg, args, self.scale, device='cpu')\n self.n_img = len(self.frame_reader)\n\n self.H, self.W, self.fx, self.fy, self.cx, self.cy = slam.H, slam.W, slam.fx, slam.fy, slam.cx, slam.cy\n\n self.sample_mode = 'bilinear'\n self.tsdf_bnds = slam.tsdf_bnds\n\n\n\n def point_masks(self, input_points, keyframe_dict, estimate_c2w_list,\n idx, device, get_mask_use_all_frames=False):\n \"\"\"\n Split the input points into seen, unseen, and forcast,\n according to the estimated camera pose and depth image.\n\n Args:\n input_points (tensor): input points.\n keyframe_dict (list): list of keyframe info dictionary.\n estimate_c2w_list (tensor): estimated camera pose.\n idx (int): current frame index.\n device (str): device name to compute on.\n\n Returns:\n seen_mask (tensor): the mask for seen area.\n forecast_mask (tensor): the mask for forecast area.\n unseen_mask (tensor): the mask for unseen area.\n \"\"\"\n H, W, fx, fy, cx, cy = self.H, self.W, self.fx, self.fy, self.cx, self.cy\n if not isinstance(input_points, torch.Tensor):\n input_points = torch.from_numpy(input_points)\n input_points = input_points.clone().detach()\n seen_mask_list = []\n forecast_mask_list = []\n unseen_mask_list = []\n for i, pnts in enumerate(\n torch.split(input_points, self.points_batch_size, dim=0)):\n points = pnts.to(device).float()\n # should divide the points into three parts, seen and forecast and unseen\n # seen: union of all the points in the viewing frustum of keyframes\n # forecast: union of all the points in the extended edge of the viewing frustum of keyframes\n # unseen: all the other points\n\n seen_mask = torch.zeros((points.shape[0])).bool().to(device)\n forecast_mask = torch.zeros((points.shape[0])).bool().to(device)\n if get_mask_use_all_frames:\n for i in range(0, idx + 1, 1):\n c2w = estimate_c2w_list[i].cpu().numpy()\n w2c = np.linalg.inv(c2w)\n w2c = torch.from_numpy(w2c).to(device).float()\n ones = torch.ones_like(\n points[:, 0]).reshape(-1, 1).to(device)\n homo_points = torch.cat([points, ones], dim=1).reshape(\n -1, 4, 1).to(device).float() # (N, 4)\n # (N, 4, 1)=(4,4)*(N, 4, 1)\n cam_cord_homo = w2c @ homo_points\n cam_cord = cam_cord_homo[:, :3] # (N, 3, 1)\n\n K = torch.from_numpy(\n np.array([[fx, .0, cx], [.0, fy, cy],\n [.0, .0, 1.0]]).reshape(3, 3)).to(device)\n cam_cord[:, 0] *= -1\n uv = K.float() @ cam_cord.float()\n z = uv[:, -1:] + 1e-8\n uv = uv[:, :2] / z\n uv = uv.float()\n edge = 0\n cur_mask_seen = (uv[:, 0] < W - edge) & (\n uv[:, 0] > edge) & (uv[:, 1] < H - edge) & (uv[:, 1] > edge)\n cur_mask_seen = cur_mask_seen & (z[:, :, 0] < 0)\n\n edge = -1000\n cur_mask_forecast = (uv[:, 0] < W - edge) & (\n uv[:, 0] > edge) & (uv[:, 1] < H - edge) & (uv[:, 1] > edge)\n cur_mask_forecast = cur_mask_forecast & (z[:, :, 0] < 0)\n\n # forecast\n cur_mask_forecast = cur_mask_forecast.reshape(-1)\n # seen\n cur_mask_seen = cur_mask_seen.reshape(-1)\n\n seen_mask |= cur_mask_seen\n forecast_mask |= cur_mask_forecast\n else:\n for keyframe in keyframe_dict:\n c2w = keyframe['est_c2w'].cpu().numpy()\n w2c = np.linalg.inv(c2w)\n w2c = torch.from_numpy(w2c).to(device).float()\n ones = torch.ones_like(\n points[:, 0]).reshape(-1, 1).to(device)\n homo_points = torch.cat([points, ones], dim=1).reshape(\n -1, 4, 1).to(device).float()\n cam_cord_homo = w2c @ homo_points\n cam_cord = cam_cord_homo[:, :3]\n\n K = torch.from_numpy(\n np.array([[fx, .0, cx], [.0, fy, cy],\n [.0, .0, 1.0]]).reshape(3, 3)).to(device)\n cam_cord[:, 0] *= -1\n uv = K.float() @ cam_cord.float()\n z = uv[:, -1:] + 1e-8\n uv = uv[:, :2] / z\n uv = uv.float()\n edge = 0\n cur_mask_seen = (uv[:, 0] < W - edge) & (\n uv[:, 0] > edge) & (uv[:, 1] < H - edge) & (uv[:, 1] > edge)\n cur_mask_seen = cur_mask_seen & (z[:, :, 0] < 0)\n\n edge = -1000\n cur_mask_forecast = (uv[:, 0] < W - edge) & (\n uv[:, 0] > edge) & (uv[:, 1] < H - edge) & (uv[:, 1] > edge)\n cur_mask_forecast = cur_mask_forecast & (z[:, :, 0] < 0)\n\n if self.depth_test:\n gt_depth = keyframe['depth'].to(\n device).reshape(1, 1, H, W)\n vgrid = uv.reshape(1, 1, -1, 2)\n # normalized to [-1, 1]\n vgrid[..., 0] = (vgrid[..., 0] / (W-1) * 2.0 - 1.0)\n vgrid[..., 1] = (vgrid[..., 1] / (H-1) * 2.0 - 1.0)\n depth_sample = F.grid_sample(\n gt_depth, vgrid, padding_mode='zeros', align_corners=True)\n depth_sample = depth_sample.reshape(-1)\n max_depth = torch.max(depth_sample)\n # forecast\n cur_mask_forecast = cur_mask_forecast.reshape(-1)\n proj_depth_forecast = -cam_cord[cur_mask_forecast,\n 2].reshape(-1)\n cur_mask_forecast[cur_mask_forecast.clone()] &= proj_depth_forecast < max_depth\n # seen\n cur_mask_seen = cur_mask_seen.reshape(-1)\n proj_depth_seen = - cam_cord[cur_mask_seen, 2].reshape(-1)\n cur_mask_seen[cur_mask_seen.clone()] &= \\\n (proj_depth_seen < depth_sample[cur_mask_seen]+2.4) \\\n & (depth_sample[cur_mask_seen]-2.4 < proj_depth_seen)\n else:\n max_depth = torch.max(keyframe['depth'])*1.1\n\n # forecast\n cur_mask_forecast = cur_mask_forecast.reshape(-1)\n proj_depth_forecast = -cam_cord[cur_mask_forecast,\n 2].reshape(-1)\n cur_mask_forecast[\n cur_mask_forecast.clone()] &= proj_depth_forecast < max_depth\n\n # seen\n cur_mask_seen = cur_mask_seen.reshape(-1)\n proj_depth_seen = - \\\n cam_cord[cur_mask_seen, 2].reshape(-1)\n cur_mask_seen[cur_mask_seen.clone(\n )] &= proj_depth_seen < max_depth\n\n seen_mask |= cur_mask_seen\n forecast_mask |= cur_mask_forecast\n\n forecast_mask &= ~seen_mask\n unseen_mask = ~(seen_mask | forecast_mask)\n\n seen_mask = seen_mask.cpu().numpy()\n forecast_mask = forecast_mask.cpu().numpy()\n unseen_mask = unseen_mask.cpu().numpy()\n\n seen_mask_list.append(seen_mask)\n forecast_mask_list.append(forecast_mask)\n unseen_mask_list.append(unseen_mask)\n\n seen_mask = np.concatenate(seen_mask_list, axis=0)\n forecast_mask = np.concatenate(forecast_mask_list, axis=0)\n unseen_mask = np.concatenate(unseen_mask_list, axis=0)\n return seen_mask, forecast_mask, unseen_mask\n\n def get_bound_from_frames(self, keyframe_dict, scale=1):\n \"\"\"\n Get the scene bound (convex hull),\n using sparse estimated camera poses and corresponding depth images.\n\n Args:\n keyframe_dict (list): list of keyframe info dictionary.\n scale (float): scene scale.\n\n Returns:\n return_mesh (trimesh.Trimesh): the convex hull.\n \"\"\"\n\n H, W, fx, fy, cx, cy = self.H, self.W, self.fx, self.fy, self.cx, self.cy\n\n if version.parse(o3d.__version__) >= version.parse('0.13.0'):\n # for new version as provided in environment.yaml\n volume = o3d.pipelines.integration.ScalableTSDFVolume(\n voxel_length=4.0 * scale / 512.0,\n sdf_trunc=0.04 * scale,\n color_type=o3d.pipelines.integration.TSDFVolumeColorType.RGB8)\n else:\n # for lower version\n volume = o3d.integration.ScalableTSDFVolume(\n voxel_length=4.0 * scale / 512.0,\n sdf_trunc=0.04 * scale,\n color_type=o3d.integration.TSDFVolumeColorType.RGB8)\n cam_points = []\n for keyframe in keyframe_dict:\n c2w = keyframe['est_c2w'].cpu().numpy()\n # convert to open3d camera pose\n c2w[:3, 1] *= -1.0\n c2w[:3, 2] *= -1.0\n w2c = np.linalg.inv(c2w)\n cam_points.append(c2w[:3, 3])\n depth = keyframe['depth'].cpu().numpy()\n color = keyframe['color'].cpu().numpy()\n\n depth = o3d.geometry.Image(depth.astype(np.float32))\n color = o3d.geometry.Image(np.array(\n (color * 255).astype(np.uint8)))\n\n intrinsic = o3d.camera.PinholeCameraIntrinsic(W, H, fx, fy, cx, cy)\n rgbd = o3d.geometry.RGBDImage.create_from_color_and_depth(\n color,\n depth,\n depth_scale=1,\n depth_trunc=1000,\n convert_rgb_to_intensity=False)\n volume.integrate(rgbd, intrinsic, w2c)\n\n cam_points = np.stack(cam_points, axis=0)\n mesh = volume.extract_triangle_mesh()\n mesh_points = np.array(mesh.vertices)\n points = np.concatenate([cam_points, mesh_points], axis=0)\n o3d_pc = o3d.geometry.PointCloud(o3d.utility.Vector3dVector(points))\n mesh, _ = o3d_pc.compute_convex_hull()\n mesh.compute_vertex_normals()\n if version.parse(o3d.__version__) >= version.parse('0.13.0'):\n mesh = mesh.scale(self.clean_mesh_bound_scale, mesh.get_center())\n else:\n mesh = mesh.scale(self.clean_mesh_bound_scale, center=True)\n points = np.array(mesh.vertices)\n faces = np.array(mesh.triangles)\n return_mesh = trimesh.Trimesh(vertices=points, faces=faces)\n return return_mesh\n\n def eval_points(self, p, decoders, tsdf_volume, tsdf_bnds, c=None, stage='color', device='cuda:0'):\n \"\"\"\n Evaluates the occupancy and/or color value for the points.\n\n Args:\n p (tensor, N*3): point coordinates.\n decoders (nn.module decoders): decoders.\n tsdf_volume (tensor): tsdf volume.\n tsdf_bnds (tensor): tsdf volume bounds.\n c (dicts, optional): feature grids. Defaults to None.\n stage (str, optional): query stage, corresponds to different levels. Defaults to 'color'.\n device (str, optional): device name to compute on. Defaults to 'cuda:0'.\n\n Returns:\n ret (tensor): occupancy (and color) value of input points.\n \"\"\"\n\n p_split = torch.split(p, self.points_batch_size)\n bound = self.bound\n rets = []\n\n for pi in p_split:\n # mask for points out of bound\n mask_x = (pi[:, 0] < bound[0][1]) & (pi[:, 0] > bound[0][0])\n mask_y = (pi[:, 1] < bound[1][1]) & (pi[:, 1] > bound[1][0])\n mask_z = (pi[:, 2] < bound[2][1]) & (pi[:, 2] > bound[2][0])\n mask = mask_x & mask_y & mask_z\n\n pi = pi.unsqueeze(0)\n ret, _ = decoders(pi, c_grid=c, tsdf_volume=tsdf_volume, tsdf_bnds=tsdf_bnds, stage=stage)\n \n ret = ret.squeeze(0)\n if len(ret.shape) == 1 and ret.shape[0] == 4:\n ret = ret.unsqueeze(0)\n\n ret[~mask, 3] = 100\n rets.append(ret)\n\n ret = torch.cat(rets, dim=0)\n\n return ret\n\n def sample_grid_tsdf(self, p, tsdf_volume, device='cuda:0'):\n\n p_nor = normalize_3d_coordinate(p.clone(), self.tsdf_bnds)\n p_nor = p_nor.unsqueeze(0)\n vgrid = p_nor[:, :, None, None].float()\n # acutally trilinear interpolation if mode = 'bilinear'\n tsdf_value = F.grid_sample(tsdf_volume.to(device), vgrid.to(device), padding_mode='border', align_corners=True,\n mode='bilinear').squeeze(-1).squeeze(-1)\n return tsdf_value\n\n\n def eval_points_tsdf(self, p, tsdf_volume, device='cuda:0'):\n \"\"\"\n Evaluates the occupancy and/or color value for the points.\n\n Args:\n p (tensor, N*3): Point coordinates.\n tsdf_volume (tensor): tsdf volume.\n\n Returns:\n ret (tensor): tsdf value of input points.\n \"\"\"\n\n p_split = torch.split(p, self.points_batch_size)\n tsdf_vals = []\n for pi in p_split:\n pi = pi.unsqueeze(0)\n tsdf_volume_tensor = tsdf_volume\n\n tsdf_val = self.sample_grid_tsdf(pi, tsdf_volume_tensor, device)\n tsdf_val = tsdf_val.squeeze(0)\n tsdf_vals.append(tsdf_val)\n\n tsdf_values = torch.cat(tsdf_vals, dim=1)\n return tsdf_values\n\n\n def get_grid_uniform(self, resolution):\n \"\"\"\n Get query point coordinates for marching cubes.\n\n Args:\n resolution (int): marching cubes resolution.\n\n Returns:\n (dict): points coordinates and sampled coordinates for each axis.\n \"\"\"\n bound = self.marching_cubes_bound\n\n padding = 0.05\n x = np.linspace(bound[0][0] - padding, bound[0][1] + padding,\n resolution)\n y = np.linspace(bound[1][0] - padding, bound[1][1] + padding,\n resolution)\n z = np.linspace(bound[2][0] - padding, bound[2][1] + padding,\n resolution)\n\n xx, yy, zz = np.meshgrid(x, y, z)\n grid_points = np.vstack([xx.ravel(), yy.ravel(), zz.ravel()]).T\n grid_points = torch.tensor(np.vstack(\n [xx.ravel(), yy.ravel(), zz.ravel()]).T,\n dtype=torch.float)\n\n\n\n return {\"grid_points\": grid_points, \"xyz\": [x, y, z]}\n\n def get_mesh(self,\n mesh_out_file,\n c,\n decoders,\n keyframe_dict,\n estimate_c2w_list,\n idx,\n tsdf_volume,\n device='cuda:0',\n color=True,\n clean_mesh=True,\n get_mask_use_all_frames=False):\n \"\"\"\n Extract mesh from scene representation and save mesh to file.\n\n Args:\n mesh_out_file (str): output mesh filename.\n c (dicts): feature grids.\n decoders (nn.module): decoders.\n keyframe_dict (list): list of keyframe info.\n estimate_c2w_list (tensor): estimated camera pose.\n idx (int): current processed camera ID.\n tsdf volume (tensor): tsdf volume.\n device (str, optional): device name to compute on. Defaults to 'cuda:0'.\n color (bool, optional): whether to extract colored mesh. Defaults to True.\n clean_mesh (bool, optional): whether to clean the output mesh \n (remove outliers outside the convexhull and small geometry noise). \n Defaults to True.\n get_mask_use_all_frames (bool, optional): \n whether to use all frames or just keyframes when getting the seen/unseen mask. Defaults to False.\n \"\"\"\n with torch.no_grad():\n\n grid = self.get_grid_uniform(self.resolution) \n points = grid['grid_points']\n points = points.to(device)\n eval_tsdf_volume = tsdf_volume\n\n mesh_bound = self.get_bound_from_frames(\n keyframe_dict, self.scale)\n z = []\n mask = []\n for i, pnts in enumerate(torch.split(points, self.points_batch_size, dim=0)):\n mask.append(mesh_bound.contains(pnts.cpu().numpy()))\n mask = np.concatenate(mask, axis=0)\n for i, pnts in enumerate(torch.split(points, self.points_batch_size, dim=0)):\n eval_tsdf = self.eval_points_tsdf(pnts, eval_tsdf_volume, device)\n eval_tsdf_mask = ((eval_tsdf > -1.0+1e-4) & (eval_tsdf < 1.0-1e-4)).cpu().numpy()\n ret = self.eval_points(pnts, decoders, tsdf_volume, self.tsdf_bnds, c, 'high', device)\n ret = ret.cpu().numpy()[:, -1]\n\n eval_tsdf_mask = eval_tsdf_mask.reshape(ret.shape)\n z.append(ret)\n \n z = np.concatenate(z, axis=0)\n z[~mask] = 100\n z = z.astype(np.float32)\n\n z_uni_m = z.reshape(\n grid['xyz'][1].shape[0], grid['xyz'][0].shape[0],\n grid['xyz'][2].shape[0]).transpose([1, 0, 2])\n\n print('begin marching cube...')\n combine_occ_tsdf = z_uni_m\n\n try:\n if version.parse(\n skimage.__version__) > version.parse('0.15.0'):\n # for new version as provided in environment.yaml\n verts, faces, normals, values = skimage.measure.marching_cubes(\n volume=combine_occ_tsdf,\n level=self.level_set, \n spacing=(grid['xyz'][0][2] - grid['xyz'][0][1],\n grid['xyz'][1][2] - grid['xyz'][1][1],\n grid['xyz'][2][2] - grid['xyz'][2][1]))\n else:\n # for lower version\n verts, faces, normals, values = skimage.measure.marching_cubes_lewiner(\n volume=combine_occ_tsdf,\n level=self.level_set, \n spacing=(grid['xyz'][0][2] - grid['xyz'][0][1],\n grid['xyz'][1][2] - grid['xyz'][1][1],\n grid['xyz'][2][2] - grid['xyz'][2][1]))\n except:\n print(\n 'marching_cubes error. Possibly no surface extracted from the level set.'\n )\n return\n\n # convert back to world coordinates\n vertices = verts + np.array(\n [grid['xyz'][0][0], grid['xyz'][1][0], grid['xyz'][2][0]])\n\n if clean_mesh:\n points = vertices\n mesh = trimesh.Trimesh(vertices=vertices,\n faces=faces,\n process=False)\n seen_mask, _, unseen_mask = self.point_masks(\n points, keyframe_dict, estimate_c2w_list, idx, device=device, \n get_mask_use_all_frames=get_mask_use_all_frames)\n unseen_mask = ~seen_mask\n face_mask = unseen_mask[mesh.faces].all(axis=1)\n mesh.update_faces(~face_mask)\n\n # get connected components\n components = mesh.split(only_watertight=False)\n if self.get_largest_components:\n areas = np.array([c.area for c in components], dtype=np.float)\n mesh = components[areas.argmax()]\n else:\n new_components = []\n for comp in components:\n if comp.area > self.remove_small_geometry_threshold * self.scale * self.scale:\n new_components.append(comp)\n mesh = trimesh.util.concatenate(new_components)\n vertices = mesh.vertices\n faces = mesh.faces\n\n if color:\n if self.color_mesh_extraction_method == 'direct_point_query':\n # color is extracted by passing the coordinates of mesh vertices through the network\n points = torch.from_numpy(vertices)\n z = []\n for i, pnts in enumerate(\n torch.split(points, self.points_batch_size, dim=0)):\n ret = self.eval_points(\n pnts.to(device).float(), decoders, tsdf_volume, self.tsdf_bnds, c, 'color',\n device)\n z_color = ret.cpu()[..., :3]\n z.append(z_color)\n z = torch.cat(z, axis=0)\n vertex_colors = z.numpy()\n\n vertex_colors = np.clip(vertex_colors, 0, 1) * 255\n vertex_colors = vertex_colors.astype(np.uint8)\n\n\n else:\n vertex_colors = None\n\n vertices /= self.scale\n mesh = trimesh.Trimesh(vertices, faces, vertex_colors=vertex_colors)\n mesh.export(mesh_out_file)\n if self.verbose:\n print('Saved mesh at', mesh_out_file)\n\n return z_uni_m" }, { "identifier": "Renderer", "path": "src/utils/Renderer.py", "snippet": "class Renderer(object):\n def __init__(self, cfg, args, slam, points_batch_size=500000, ray_batch_size=100000):\n self.ray_batch_size = ray_batch_size\n self.points_batch_size = points_batch_size\n\n self.lindisp = cfg['rendering']['lindisp']\n self.perturb = cfg['rendering']['perturb']\n self.N_samples = cfg['rendering']['N_samples']\n self.N_surface = cfg['rendering']['N_surface']\n self.N_importance = cfg['rendering']['N_importance']\n\n self.scale = cfg['scale']\n self.occupancy = cfg['occupancy']\n self.bound = slam.bound\n self.sample_mode = 'bilinear'\n self.tsdf_bnds = slam.vol_bnds\n\n self.H, self.W, self.fx, self.fy, self.cx, self.cy = slam.H, slam.W, slam.fx, slam.fy, slam.cx, slam.cy\n\n self.resolution = cfg['meshing']['resolution']\n\n def eval_points(self, p, decoders, tsdf_volume, tsdf_bnds, c=None, stage='color', device='cuda:0'):\n \"\"\"\n Evaluates the occupancy and/or color value for the points.\n\n Args:\n p (tensor, N*3): Point coordinates.\n decoders (nn.module decoders): Decoders.\n tsdf_volume (tensor): tsdf volume.\n tsdf_bnds (tensor): tsdf volume bounds.\n c (dicts, optional): Feature grids. Defaults to None.\n stage (str, optional): Query stage, corresponds to different levels. Defaults to 'color'.\n device (str, optional): CUDA device. Defaults to 'cuda:0'.\n\n Returns:\n ret (tensor): occupancy (and color) value of input points.\n \"\"\"\n\n p_split = torch.split(p, self.points_batch_size)\n bound = self.bound\n rets = []\n weights = []\n\n for pi in p_split:\n # mask for points out of bound\n mask_x = (pi[:, 0] < bound[0][1]) & (pi[:, 0] > bound[0][0])\n mask_y = (pi[:, 1] < bound[1][1]) & (pi[:, 1] > bound[1][0])\n mask_z = (pi[:, 2] < bound[2][1]) & (pi[:, 2] > bound[2][0])\n mask = mask_x & mask_y & mask_z\n\n pi = pi.unsqueeze(0)\n ret, w = decoders(pi, c_grid=c, tsdf_volume=tsdf_volume, tsdf_bnds=tsdf_bnds, stage=stage)\n ret = ret.squeeze(0)\n\n\n if len(ret.shape) == 1 and ret.shape[0] == 4:\n ret = ret.unsqueeze(0)\n\n ret[~mask, 3] = 100 \n rets.append(ret)\n weights.append(w)\n\n ret = torch.cat(rets, dim=0)\n weight = torch.cat(weights, dim=0)\n\n return ret, weight \n\n def sample_grid_tsdf(self, p, tsdf_volume, device='cuda:0'):\n\n p_nor = normalize_3d_coordinate(p.clone(), self.tsdf_bnds)\n p_nor = p_nor.unsqueeze(0)\n vgrid = p_nor[:, :, None, None].float()\n # acutally trilinear interpolation if mode = 'bilinear'\n tsdf_value = F.grid_sample(tsdf_volume.to(device), vgrid.to(device), padding_mode='border', align_corners=True,\n mode='bilinear').squeeze(-1).squeeze(-1)\n return tsdf_value\n\n\n def eval_points_tsdf(self, p, tsdf_volume, device='cuda:0'):\n \"\"\"\n Evaluates the occupancy and/or color value for the points.\n\n Args:\n p (tensor, N*3): Point coordinates.\n \n\n Returns:\n ret (tensor): tsdf value of input points.\n \"\"\"\n\n p_split = torch.split(p, self.points_batch_size)\n tsdf_vals = []\n for pi in p_split:\n pi = pi.unsqueeze(0)\n tsdf_volume_tensor = tsdf_volume\n\n tsdf_val = self.sample_grid_tsdf(pi, tsdf_volume_tensor, device)\n tsdf_val = tsdf_val.squeeze(0)\n tsdf_vals.append(tsdf_val)\n\n tsdf_values = torch.cat(tsdf_vals, dim=1)\n return tsdf_values\n\n\n def render_batch_ray(self, c, decoders, rays_d, rays_o, device, tsdf_volume, tsdf_bnds, stage, gt_depth=None):\n \"\"\"\n Render color, depth and uncertainty of a batch of rays.\n\n Args:\n c (dict): feature grids.\n decoders (nn.module): decoders.\n rays_d (tensor, N*3): rays direction.\n rays_o (tensor, N*3): rays origin.\n device (str): device name to compute on.\n tsdf_volume (tensor): tsdf volume.\n tsdf_bnds (tensor): tsdf volume bounds.\n stage (str): query stage.\n gt_depth (tensor, optional): sensor depth image. Defaults to None.\n\n Returns:\n depth (tensor): rendered depth.\n uncertainty (tensor): rendered uncertainty.\n color (tensor): rendered color.\n weight (tensor): attention weight.\n \"\"\"\n eval_tsdf_volume = tsdf_volume\n \n\n N_samples = self.N_samples\n N_surface = self.N_surface\n N_importance = self.N_importance\n\n N_rays = rays_o.shape[0]\n\n if gt_depth is None:\n N_surface = 0\n near = 0.01\n else:\n gt_depth = gt_depth.reshape(-1, 1)\n gt_depth_samples = gt_depth.repeat(1, N_samples)\n near = gt_depth_samples*0.01\n\n with torch.no_grad():\n det_rays_o = rays_o.clone().detach().unsqueeze(-1) # (N, 3, 1)\n det_rays_d = rays_d.clone().detach().unsqueeze(-1) # (N, 3, 1)\n t = (self.bound.unsqueeze(0).to(device) -\n det_rays_o)/det_rays_d # (N, 3, 2)\n far_bb, _ = torch.min(torch.max(t, dim=2)[0], dim=1)\n far_bb = far_bb.unsqueeze(-1)\n far_bb += 0.01\n\n if gt_depth is not None:\n # in case the bound is too large\n far = torch.clamp(far_bb, 0, torch.max(gt_depth*1.2))\n\n else:\n far = far_bb\n if N_surface > 0:\n if False:\n # this naive implementation downgrades performance\n gt_depth_surface = gt_depth.repeat(1, N_surface)\n t_vals_surface = torch.linspace(\n 0., 1., steps=N_surface).to(device)\n z_vals_surface = 0.95*gt_depth_surface * \\\n (1.-t_vals_surface) + 1.05 * \\\n gt_depth_surface * (t_vals_surface)\n else:\n # since we want to colorize even on regions with no depth sensor readings,\n # meaning colorize on interpolated geometry region,\n # we sample all pixels (not using depth mask) for color loss.\n # Therefore, for pixels with non-zero depth value, we sample near the surface,\n # since it is not a good idea to sample 16 points near (half even behind) camera,\n # for pixels with zero depth value, we sample uniformly from camera to max_depth.\n gt_none_zero_mask = gt_depth > 0\n gt_none_zero = gt_depth[gt_none_zero_mask]\n gt_none_zero = gt_none_zero.unsqueeze(-1)\n gt_depth_surface = gt_none_zero.repeat(1, N_surface)\n t_vals_surface = torch.linspace(\n 0., 1., steps=N_surface).double().to(device)\n # emperical range 0.05*depth\n z_vals_surface_depth_none_zero = 0.95*gt_depth_surface * \\\n (1.-t_vals_surface) + 1.05 * \\\n gt_depth_surface * (t_vals_surface)\n z_vals_surface = torch.zeros(\n gt_depth.shape[0], N_surface).to(device).double()\n gt_none_zero_mask = gt_none_zero_mask.squeeze(-1)\n z_vals_surface[gt_none_zero_mask,\n :] = z_vals_surface_depth_none_zero\n near_surface = 0.001\n far_surface = torch.max(gt_depth)\n z_vals_surface_depth_zero = near_surface * \\\n (1.-t_vals_surface) + far_surface * (t_vals_surface)\n z_vals_surface_depth_zero.unsqueeze(\n 0).repeat((~gt_none_zero_mask).sum(), 1)\n z_vals_surface[~gt_none_zero_mask,\n :] = z_vals_surface_depth_zero\n\n t_vals = torch.linspace(0., 1., steps=N_samples, device=device)\n\n if not self.lindisp:\n z_vals = near * (1.-t_vals) + far * (t_vals)\n else:\n z_vals = 1./(1./near * (1.-t_vals) + 1./far * (t_vals))\n\n if self.perturb > 0.:\n # get intervals between samples\n mids = .5 * (z_vals[..., 1:] + z_vals[..., :-1])\n upper = torch.cat([mids, z_vals[..., -1:]], -1)\n lower = torch.cat([z_vals[..., :1], mids], -1)\n # stratified samples in those intervals\n t_rand = torch.rand(z_vals.shape).to(device)\n z_vals = lower + (upper - lower) * t_rand\n\n if N_surface > 0:\n z_vals, _ = torch.sort(\n torch.cat([z_vals, z_vals_surface.double()], -1), -1)\n\n pts = rays_o[..., None, :] + rays_d[..., None, :] * \\\n z_vals[..., :, None] # [N_rays, N_samples+N_surface, 3]\n pointsf = pts.reshape(-1, 3)\n \n raw, weight = self.eval_points(pointsf, decoders, tsdf_volume, tsdf_bnds, c, stage, device)\n raw = raw.reshape(N_rays, N_samples+N_surface, -1)\n weight = weight.reshape(N_rays, N_samples+N_surface, -1)\n\n\n depth, uncertainty, color, weights = raw2outputs_nerf_color(\n raw, z_vals, rays_d, occupancy=self.occupancy, device=device)\n \n if N_importance > 0:\n z_vals_mid = .5 * (z_vals[..., 1:] + z_vals[..., :-1])\n z_samples = sample_pdf(\n z_vals_mid, weights[..., 1:-1], N_importance, det=(self.perturb == 0.), device=device)\n z_samples = z_samples.detach()\n z_vals, _ = torch.sort(torch.cat([z_vals, z_samples], -1), -1)\n\n pts = rays_o[..., None, :] + \\\n rays_d[..., None, :] * z_vals[..., :, None]\n pts = pts.reshape(-1, 3)\n \n raw, weight = self.eval_points(pointsf, decoders, tsdf_volume, tsdf_bnds, c, stage, device)\n raw = raw.reshape(N_rays, N_samples+N_surface, -1)\n weight = weight.reshape(N_rays, N_samples+N_surface, -1)\n\n depth, uncertainty, color, weights = raw2outputs_nerf_color(\n raw, z_vals, rays_d, occupancy=self.occupancy, device=device)\n return depth, uncertainty, color, weight\n\n\n return depth, uncertainty, color, weight\n\n\n def render_img(self, c, decoders, c2w, device, tsdf_volume, tsdf_bnds, stage, gt_depth=None):\n \"\"\"\n Renders out depth, uncertainty, and color images.\n\n Args:\n c (dict): feature grids.\n decoders (nn.module): decoders.\n c2w (tensor): camera to world matrix of current frame.\n device (str): device name to compute on.\n tsdf_volume (tensor): tsdf volume.\n tsdf_bnds (tensor): tsdf volume bounds.\n stage (str): query stage.\n gt_depth (tensor, optional): sensor depth image. Defaults to None.\n\n Returns:\n depth (tensor, H*W): rendered depth image.\n uncertainty (tensor, H*W): rendered uncertainty image.\n color (tensor, H*W*3): rendered color image.\n \"\"\"\n \n with torch.no_grad():\n H = self.H\n W = self.W\n rays_o, rays_d = get_rays(\n H, W, self.fx, self.fy, self.cx, self.cy, c2w, device)\n rays_o = rays_o.reshape(-1, 3)\n rays_d = rays_d.reshape(-1, 3)\n\n depth_list = []\n uncertainty_list = []\n color_list = []\n\n\n ray_batch_size = self.ray_batch_size\n gt_depth = gt_depth.reshape(-1)\n\n for i in range(0, rays_d.shape[0], ray_batch_size):\n rays_d_batch = rays_d[i:i+ray_batch_size]\n rays_o_batch = rays_o[i:i+ray_batch_size]\n\n iter = 10\n\n if gt_depth is None:\n ret = self.render_batch_ray(\n c, decoders, rays_d_batch, rays_o_batch, device, tsdf_volume, tsdf_bnds, stage, gt_depth=None)\n else:\n gt_depth_batch = gt_depth[i:i+ray_batch_size]\n ret = self.render_batch_ray(\n c, decoders, rays_d_batch, rays_o_batch, device, tsdf_volume, tsdf_bnds, stage, gt_depth=gt_depth_batch)\n\n depth, uncertainty, color, _= ret\n\n \n depth_list.append(depth.double())\n uncertainty_list.append(uncertainty.double())\n color_list.append(color)\n \n \n\n\n\n depth = torch.cat(depth_list, dim=0)\n uncertainty = torch.cat(uncertainty_list, dim=0)\n color = torch.cat(color_list, dim=0)\n \n depth = depth.reshape(H, W)\n uncertainty = uncertainty.reshape(H, W)\n color = color.reshape(H, W, 3)\n\n return depth, uncertainty, color " } ]
import os import time import numpy as np import torch import torch.multiprocessing import torch.multiprocessing as mp from src import config from src.Mapper import Mapper from src.Tracker import Tracker from src.utils.datasets import get_dataset from src.utils.Logger import Logger from src.utils.Mesher import Mesher from src.utils.Renderer import Renderer
20,631
# import src.fusion as fusion # import open3d as o3d torch.multiprocessing.set_sharing_strategy('file_system') class DF_Prior(): """ DF_Prior main class. Mainly allocate shared resources, and dispatch mapping and tracking process. """ def __init__(self, cfg, args): self.cfg = cfg self.args = args self.occupancy = cfg['occupancy'] self.low_gpu_mem = cfg['low_gpu_mem'] self.verbose = cfg['verbose'] self.dataset = cfg['dataset'] if args.output is None: self.output = cfg['data']['output'] else: self.output = args.output self.ckptsdir = os.path.join(self.output, 'ckpts') os.makedirs(self.output, exist_ok=True) os.makedirs(self.ckptsdir, exist_ok=True) os.makedirs(f'{self.output}/mesh', exist_ok=True) self.H, self.W, self.fx, self.fy, self.cx, self.cy = cfg['cam']['H'], cfg['cam'][ 'W'], cfg['cam']['fx'], cfg['cam']['fy'], cfg['cam']['cx'], cfg['cam']['cy'] self.update_cam() model = config.get_model(cfg) self.shared_decoders = model self.scale = cfg['scale'] self.load_bound(cfg) self.load_pretrain(cfg) self.grid_init(cfg) # need to use spawn try: mp.set_start_method('spawn', force=True) except RuntimeError: pass self.frame_reader = get_dataset(cfg, args, self.scale) self.n_img = len(self.frame_reader) self.estimate_c2w_list = torch.zeros((self.n_img, 4, 4)) self.estimate_c2w_list.share_memory_() dataset = self.cfg['data']['dataset'] scene_id = self.cfg['data']['id'] self.scene_id = scene_id print(scene_id) # load tsdf grid if dataset == 'scannet': self.tsdf_volume_shared = torch.load(f'scannet_tsdf_volume/scene{scene_id}_tsdf_volume.pt') elif dataset == 'replica': self.tsdf_volume_shared = torch.load(f'replica_tsdf_volume/{scene_id}_tsdf_volume.pt') self.tsdf_volume_shared = self.tsdf_volume_shared.to(self.cfg['mapping']['device']) self.tsdf_volume_shared.share_memory_() # load tsdf grid bound if dataset == 'scannet': self.tsdf_bnds = torch.load(f'scannet_tsdf_volume/scene{scene_id}_bounds.pt') elif dataset == 'replica': self.tsdf_bnds = torch.load(f'replica_tsdf_volume/{scene_id}_bounds.pt') self.tsdf_bnds = torch.tensor(self.tsdf_bnds).to(self.cfg['mapping']['device']) self.tsdf_bnds.share_memory_() self.vol_bnds = self.tsdf_bnds self.vol_bnds.share_memory_() self.gt_c2w_list = torch.zeros((self.n_img, 4, 4)) self.gt_c2w_list.share_memory_() self.idx = torch.zeros((1)).int() self.idx.share_memory_() self.mapping_first_frame = torch.zeros((1)).int() self.mapping_first_frame.share_memory_() # the id of the newest frame Mapper is processing self.mapping_idx = torch.zeros((1)).int() self.mapping_idx.share_memory_() self.mapping_cnt = torch.zeros((1)).int() # counter for mapping self.mapping_cnt.share_memory_() for key, val in self.shared_c.items(): val = val.to(self.cfg['mapping']['device']) val.share_memory_() self.shared_c[key] = val self.shared_decoders = self.shared_decoders.to( self.cfg['mapping']['device']) self.shared_decoders.share_memory() self.renderer = Renderer(cfg, args, self) self.mesher = Mesher(cfg, args, self)
# import src.fusion as fusion # import open3d as o3d torch.multiprocessing.set_sharing_strategy('file_system') class DF_Prior(): """ DF_Prior main class. Mainly allocate shared resources, and dispatch mapping and tracking process. """ def __init__(self, cfg, args): self.cfg = cfg self.args = args self.occupancy = cfg['occupancy'] self.low_gpu_mem = cfg['low_gpu_mem'] self.verbose = cfg['verbose'] self.dataset = cfg['dataset'] if args.output is None: self.output = cfg['data']['output'] else: self.output = args.output self.ckptsdir = os.path.join(self.output, 'ckpts') os.makedirs(self.output, exist_ok=True) os.makedirs(self.ckptsdir, exist_ok=True) os.makedirs(f'{self.output}/mesh', exist_ok=True) self.H, self.W, self.fx, self.fy, self.cx, self.cy = cfg['cam']['H'], cfg['cam'][ 'W'], cfg['cam']['fx'], cfg['cam']['fy'], cfg['cam']['cx'], cfg['cam']['cy'] self.update_cam() model = config.get_model(cfg) self.shared_decoders = model self.scale = cfg['scale'] self.load_bound(cfg) self.load_pretrain(cfg) self.grid_init(cfg) # need to use spawn try: mp.set_start_method('spawn', force=True) except RuntimeError: pass self.frame_reader = get_dataset(cfg, args, self.scale) self.n_img = len(self.frame_reader) self.estimate_c2w_list = torch.zeros((self.n_img, 4, 4)) self.estimate_c2w_list.share_memory_() dataset = self.cfg['data']['dataset'] scene_id = self.cfg['data']['id'] self.scene_id = scene_id print(scene_id) # load tsdf grid if dataset == 'scannet': self.tsdf_volume_shared = torch.load(f'scannet_tsdf_volume/scene{scene_id}_tsdf_volume.pt') elif dataset == 'replica': self.tsdf_volume_shared = torch.load(f'replica_tsdf_volume/{scene_id}_tsdf_volume.pt') self.tsdf_volume_shared = self.tsdf_volume_shared.to(self.cfg['mapping']['device']) self.tsdf_volume_shared.share_memory_() # load tsdf grid bound if dataset == 'scannet': self.tsdf_bnds = torch.load(f'scannet_tsdf_volume/scene{scene_id}_bounds.pt') elif dataset == 'replica': self.tsdf_bnds = torch.load(f'replica_tsdf_volume/{scene_id}_bounds.pt') self.tsdf_bnds = torch.tensor(self.tsdf_bnds).to(self.cfg['mapping']['device']) self.tsdf_bnds.share_memory_() self.vol_bnds = self.tsdf_bnds self.vol_bnds.share_memory_() self.gt_c2w_list = torch.zeros((self.n_img, 4, 4)) self.gt_c2w_list.share_memory_() self.idx = torch.zeros((1)).int() self.idx.share_memory_() self.mapping_first_frame = torch.zeros((1)).int() self.mapping_first_frame.share_memory_() # the id of the newest frame Mapper is processing self.mapping_idx = torch.zeros((1)).int() self.mapping_idx.share_memory_() self.mapping_cnt = torch.zeros((1)).int() # counter for mapping self.mapping_cnt.share_memory_() for key, val in self.shared_c.items(): val = val.to(self.cfg['mapping']['device']) val.share_memory_() self.shared_c[key] = val self.shared_decoders = self.shared_decoders.to( self.cfg['mapping']['device']) self.shared_decoders.share_memory() self.renderer = Renderer(cfg, args, self) self.mesher = Mesher(cfg, args, self)
self.logger = Logger(cfg, args, self)
4
2023-10-13 00:49:57+00:00
24k
fury-05/BookRecomendApp
.pythonlibs/lib/python3.10/site-packages/sklearn/linear_model/_base.py
[ { "identifier": "BaseEstimator", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/base.py", "snippet": "class BaseEstimator(_MetadataRequester):\n \"\"\"Base class for all estimators in scikit-learn.\n\n Notes\n -----\n All estimators should specify all the parameters that can be set\n at the class level in their ``__init__`` as explicit keyword\n arguments (no ``*args`` or ``**kwargs``).\n \"\"\"\n\n @classmethod\n def _get_param_names(cls):\n \"\"\"Get parameter names for the estimator\"\"\"\n # fetch the constructor or the original constructor before\n # deprecation wrapping if any\n init = getattr(cls.__init__, \"deprecated_original\", cls.__init__)\n if init is object.__init__:\n # No explicit constructor to introspect\n return []\n\n # introspect the constructor arguments to find the model parameters\n # to represent\n init_signature = inspect.signature(init)\n # Consider the constructor parameters excluding 'self'\n parameters = [\n p\n for p in init_signature.parameters.values()\n if p.name != \"self\" and p.kind != p.VAR_KEYWORD\n ]\n for p in parameters:\n if p.kind == p.VAR_POSITIONAL:\n raise RuntimeError(\n \"scikit-learn estimators should always \"\n \"specify their parameters in the signature\"\n \" of their __init__ (no varargs).\"\n \" %s with constructor %s doesn't \"\n \" follow this convention.\" % (cls, init_signature)\n )\n # Extract and sort argument names excluding 'self'\n return sorted([p.name for p in parameters])\n\n def get_params(self, deep=True):\n \"\"\"\n Get parameters for this estimator.\n\n Parameters\n ----------\n deep : bool, default=True\n If True, will return the parameters for this estimator and\n contained subobjects that are estimators.\n\n Returns\n -------\n params : dict\n Parameter names mapped to their values.\n \"\"\"\n out = dict()\n for key in self._get_param_names():\n value = getattr(self, key)\n if deep and hasattr(value, \"get_params\") and not isinstance(value, type):\n deep_items = value.get_params().items()\n out.update((key + \"__\" + k, val) for k, val in deep_items)\n out[key] = value\n return out\n\n def set_params(self, **params):\n \"\"\"Set the parameters of this estimator.\n\n The method works on simple estimators as well as on nested objects\n (such as :class:`~sklearn.pipeline.Pipeline`). The latter have\n parameters of the form ``<component>__<parameter>`` so that it's\n possible to update each component of a nested object.\n\n Parameters\n ----------\n **params : dict\n Estimator parameters.\n\n Returns\n -------\n self : estimator instance\n Estimator instance.\n \"\"\"\n if not params:\n # Simple optimization to gain speed (inspect is slow)\n return self\n valid_params = self.get_params(deep=True)\n\n nested_params = defaultdict(dict) # grouped by prefix\n for key, value in params.items():\n key, delim, sub_key = key.partition(\"__\")\n if key not in valid_params:\n local_valid_params = self._get_param_names()\n raise ValueError(\n f\"Invalid parameter {key!r} for estimator {self}. \"\n f\"Valid parameters are: {local_valid_params!r}.\"\n )\n\n if delim:\n nested_params[key][sub_key] = value\n else:\n setattr(self, key, value)\n valid_params[key] = value\n\n for key, sub_params in nested_params.items():\n # TODO(1.4): remove specific handling of \"base_estimator\".\n # The \"base_estimator\" key is special. It was deprecated and\n # renamed to \"estimator\" for several estimators. This means we\n # need to translate it here and set sub-parameters on \"estimator\",\n # but only if the user did not explicitly set a value for\n # \"base_estimator\".\n if (\n key == \"base_estimator\"\n and valid_params[key] == \"deprecated\"\n and self.__module__.startswith(\"sklearn.\")\n ):\n warnings.warn(\n (\n f\"Parameter 'base_estimator' of {self.__class__.__name__} is\"\n \" deprecated in favor of 'estimator'. See\"\n f\" {self.__class__.__name__}'s docstring for more details.\"\n ),\n FutureWarning,\n stacklevel=2,\n )\n key = \"estimator\"\n valid_params[key].set_params(**sub_params)\n\n return self\n\n def __sklearn_clone__(self):\n return _clone_parametrized(self)\n\n def __repr__(self, N_CHAR_MAX=700):\n # N_CHAR_MAX is the (approximate) maximum number of non-blank\n # characters to render. We pass it as an optional parameter to ease\n # the tests.\n\n from .utils._pprint import _EstimatorPrettyPrinter\n\n N_MAX_ELEMENTS_TO_SHOW = 30 # number of elements to show in sequences\n\n # use ellipsis for sequences with a lot of elements\n pp = _EstimatorPrettyPrinter(\n compact=True,\n indent=1,\n indent_at_name=True,\n n_max_elements_to_show=N_MAX_ELEMENTS_TO_SHOW,\n )\n\n repr_ = pp.pformat(self)\n\n # Use bruteforce ellipsis when there are a lot of non-blank characters\n n_nonblank = len(\"\".join(repr_.split()))\n if n_nonblank > N_CHAR_MAX:\n lim = N_CHAR_MAX // 2 # apprx number of chars to keep on both ends\n regex = r\"^(\\s*\\S){%d}\" % lim\n # The regex '^(\\s*\\S){%d}' % n\n # matches from the start of the string until the nth non-blank\n # character:\n # - ^ matches the start of string\n # - (pattern){n} matches n repetitions of pattern\n # - \\s*\\S matches a non-blank char following zero or more blanks\n left_lim = re.match(regex, repr_).end()\n right_lim = re.match(regex, repr_[::-1]).end()\n\n if \"\\n\" in repr_[left_lim:-right_lim]:\n # The left side and right side aren't on the same line.\n # To avoid weird cuts, e.g.:\n # categoric...ore',\n # we need to start the right side with an appropriate newline\n # character so that it renders properly as:\n # categoric...\n # handle_unknown='ignore',\n # so we add [^\\n]*\\n which matches until the next \\n\n regex += r\"[^\\n]*\\n\"\n right_lim = re.match(regex, repr_[::-1]).end()\n\n ellipsis = \"...\"\n if left_lim + len(ellipsis) < len(repr_) - right_lim:\n # Only add ellipsis if it results in a shorter repr\n repr_ = repr_[:left_lim] + \"...\" + repr_[-right_lim:]\n\n return repr_\n\n def __getstate__(self):\n if getattr(self, \"__slots__\", None):\n raise TypeError(\n \"You cannot use `__slots__` in objects inheriting from \"\n \"`sklearn.base.BaseEstimator`.\"\n )\n\n try:\n state = super().__getstate__()\n if state is None:\n # For Python 3.11+, empty instance (no `__slots__`,\n # and `__dict__`) will return a state equal to `None`.\n state = self.__dict__.copy()\n except AttributeError:\n # Python < 3.11\n state = self.__dict__.copy()\n\n if type(self).__module__.startswith(\"sklearn.\"):\n return dict(state.items(), _sklearn_version=__version__)\n else:\n return state\n\n def __setstate__(self, state):\n if type(self).__module__.startswith(\"sklearn.\"):\n pickle_version = state.pop(\"_sklearn_version\", \"pre-0.18\")\n if pickle_version != __version__:\n warnings.warn(\n InconsistentVersionWarning(\n estimator_name=self.__class__.__name__,\n current_sklearn_version=__version__,\n original_sklearn_version=pickle_version,\n ),\n )\n try:\n super().__setstate__(state)\n except AttributeError:\n self.__dict__.update(state)\n\n def _more_tags(self):\n return _DEFAULT_TAGS\n\n def _get_tags(self):\n collected_tags = {}\n for base_class in reversed(inspect.getmro(self.__class__)):\n if hasattr(base_class, \"_more_tags\"):\n # need the if because mixins might not have _more_tags\n # but might do redundant work in estimators\n # (i.e. calling more tags on BaseEstimator multiple times)\n more_tags = base_class._more_tags(self)\n collected_tags.update(more_tags)\n return collected_tags\n\n def _check_n_features(self, X, reset):\n \"\"\"Set the `n_features_in_` attribute, or check against it.\n\n Parameters\n ----------\n X : {ndarray, sparse matrix} of shape (n_samples, n_features)\n The input samples.\n reset : bool\n If True, the `n_features_in_` attribute is set to `X.shape[1]`.\n If False and the attribute exists, then check that it is equal to\n `X.shape[1]`. If False and the attribute does *not* exist, then\n the check is skipped.\n .. note::\n It is recommended to call reset=True in `fit` and in the first\n call to `partial_fit`. All other methods that validate `X`\n should set `reset=False`.\n \"\"\"\n try:\n n_features = _num_features(X)\n except TypeError as e:\n if not reset and hasattr(self, \"n_features_in_\"):\n raise ValueError(\n \"X does not contain any features, but \"\n f\"{self.__class__.__name__} is expecting \"\n f\"{self.n_features_in_} features\"\n ) from e\n # If the number of features is not defined and reset=True,\n # then we skip this check\n return\n\n if reset:\n self.n_features_in_ = n_features\n return\n\n if not hasattr(self, \"n_features_in_\"):\n # Skip this check if the expected number of expected input features\n # was not recorded by calling fit first. This is typically the case\n # for stateless transformers.\n return\n\n if n_features != self.n_features_in_:\n raise ValueError(\n f\"X has {n_features} features, but {self.__class__.__name__} \"\n f\"is expecting {self.n_features_in_} features as input.\"\n )\n\n def _check_feature_names(self, X, *, reset):\n \"\"\"Set or check the `feature_names_in_` attribute.\n\n .. versionadded:: 1.0\n\n Parameters\n ----------\n X : {ndarray, dataframe} of shape (n_samples, n_features)\n The input samples.\n\n reset : bool\n Whether to reset the `feature_names_in_` attribute.\n If False, the input will be checked for consistency with\n feature names of data provided when reset was last True.\n .. note::\n It is recommended to call `reset=True` in `fit` and in the first\n call to `partial_fit`. All other methods that validate `X`\n should set `reset=False`.\n \"\"\"\n\n if reset:\n feature_names_in = _get_feature_names(X)\n if feature_names_in is not None:\n self.feature_names_in_ = feature_names_in\n elif hasattr(self, \"feature_names_in_\"):\n # Delete the attribute when the estimator is fitted on a new dataset\n # that has no feature names.\n delattr(self, \"feature_names_in_\")\n return\n\n fitted_feature_names = getattr(self, \"feature_names_in_\", None)\n X_feature_names = _get_feature_names(X)\n\n if fitted_feature_names is None and X_feature_names is None:\n # no feature names seen in fit and in X\n return\n\n if X_feature_names is not None and fitted_feature_names is None:\n warnings.warn(\n f\"X has feature names, but {self.__class__.__name__} was fitted without\"\n \" feature names\"\n )\n return\n\n if X_feature_names is None and fitted_feature_names is not None:\n warnings.warn(\n \"X does not have valid feature names, but\"\n f\" {self.__class__.__name__} was fitted with feature names\"\n )\n return\n\n # validate the feature names against the `feature_names_in_` attribute\n if len(fitted_feature_names) != len(X_feature_names) or np.any(\n fitted_feature_names != X_feature_names\n ):\n message = (\n \"The feature names should match those that were passed during fit.\\n\"\n )\n fitted_feature_names_set = set(fitted_feature_names)\n X_feature_names_set = set(X_feature_names)\n\n unexpected_names = sorted(X_feature_names_set - fitted_feature_names_set)\n missing_names = sorted(fitted_feature_names_set - X_feature_names_set)\n\n def add_names(names):\n output = \"\"\n max_n_names = 5\n for i, name in enumerate(names):\n if i >= max_n_names:\n output += \"- ...\\n\"\n break\n output += f\"- {name}\\n\"\n return output\n\n if unexpected_names:\n message += \"Feature names unseen at fit time:\\n\"\n message += add_names(unexpected_names)\n\n if missing_names:\n message += \"Feature names seen at fit time, yet now missing:\\n\"\n message += add_names(missing_names)\n\n if not missing_names and not unexpected_names:\n message += (\n \"Feature names must be in the same order as they were in fit.\\n\"\n )\n\n raise ValueError(message)\n\n def _validate_data(\n self,\n X=\"no_validation\",\n y=\"no_validation\",\n reset=True,\n validate_separately=False,\n cast_to_ndarray=True,\n **check_params,\n ):\n \"\"\"Validate input data and set or check the `n_features_in_` attribute.\n\n Parameters\n ----------\n X : {array-like, sparse matrix, dataframe} of shape \\\n (n_samples, n_features), default='no validation'\n The input samples.\n If `'no_validation'`, no validation is performed on `X`. This is\n useful for meta-estimator which can delegate input validation to\n their underlying estimator(s). In that case `y` must be passed and\n the only accepted `check_params` are `multi_output` and\n `y_numeric`.\n\n y : array-like of shape (n_samples,), default='no_validation'\n The targets.\n\n - If `None`, `check_array` is called on `X`. If the estimator's\n requires_y tag is True, then an error will be raised.\n - If `'no_validation'`, `check_array` is called on `X` and the\n estimator's requires_y tag is ignored. This is a default\n placeholder and is never meant to be explicitly set. In that case\n `X` must be passed.\n - Otherwise, only `y` with `_check_y` or both `X` and `y` are\n checked with either `check_array` or `check_X_y` depending on\n `validate_separately`.\n\n reset : bool, default=True\n Whether to reset the `n_features_in_` attribute.\n If False, the input will be checked for consistency with data\n provided when reset was last True.\n .. note::\n It is recommended to call reset=True in `fit` and in the first\n call to `partial_fit`. All other methods that validate `X`\n should set `reset=False`.\n\n validate_separately : False or tuple of dicts, default=False\n Only used if y is not None.\n If False, call validate_X_y(). Else, it must be a tuple of kwargs\n to be used for calling check_array() on X and y respectively.\n\n `estimator=self` is automatically added to these dicts to generate\n more informative error message in case of invalid input data.\n\n cast_to_ndarray : bool, default=True\n Cast `X` and `y` to ndarray with checks in `check_params`. If\n `False`, `X` and `y` are unchanged and only `feature_names_in_` and\n `n_features_in_` are checked.\n\n **check_params : kwargs\n Parameters passed to :func:`sklearn.utils.check_array` or\n :func:`sklearn.utils.check_X_y`. Ignored if validate_separately\n is not False.\n\n `estimator=self` is automatically added to these params to generate\n more informative error message in case of invalid input data.\n\n Returns\n -------\n out : {ndarray, sparse matrix} or tuple of these\n The validated input. A tuple is returned if both `X` and `y` are\n validated.\n \"\"\"\n self._check_feature_names(X, reset=reset)\n\n if y is None and self._get_tags()[\"requires_y\"]:\n raise ValueError(\n f\"This {self.__class__.__name__} estimator \"\n \"requires y to be passed, but the target y is None.\"\n )\n\n no_val_X = isinstance(X, str) and X == \"no_validation\"\n no_val_y = y is None or isinstance(y, str) and y == \"no_validation\"\n\n if no_val_X and no_val_y:\n raise ValueError(\"Validation should be done on X, y or both.\")\n\n default_check_params = {\"estimator\": self}\n check_params = {**default_check_params, **check_params}\n\n if not cast_to_ndarray:\n if not no_val_X and no_val_y:\n out = X\n elif no_val_X and not no_val_y:\n out = y\n else:\n out = X, y\n elif not no_val_X and no_val_y:\n out = check_array(X, input_name=\"X\", **check_params)\n elif no_val_X and not no_val_y:\n out = _check_y(y, **check_params)\n else:\n if validate_separately:\n # We need this because some estimators validate X and y\n # separately, and in general, separately calling check_array()\n # on X and y isn't equivalent to just calling check_X_y()\n # :(\n check_X_params, check_y_params = validate_separately\n if \"estimator\" not in check_X_params:\n check_X_params = {**default_check_params, **check_X_params}\n X = check_array(X, input_name=\"X\", **check_X_params)\n if \"estimator\" not in check_y_params:\n check_y_params = {**default_check_params, **check_y_params}\n y = check_array(y, input_name=\"y\", **check_y_params)\n else:\n X, y = check_X_y(X, y, **check_params)\n out = X, y\n\n if not no_val_X and check_params.get(\"ensure_2d\", True):\n self._check_n_features(X, reset=reset)\n\n return out\n\n def _validate_params(self):\n \"\"\"Validate types and values of constructor parameters\n\n The expected type and values must be defined in the `_parameter_constraints`\n class attribute, which is a dictionary `param_name: list of constraints`. See\n the docstring of `validate_parameter_constraints` for a description of the\n accepted constraints.\n \"\"\"\n validate_parameter_constraints(\n self._parameter_constraints,\n self.get_params(deep=False),\n caller_name=self.__class__.__name__,\n )\n\n @property\n def _repr_html_(self):\n \"\"\"HTML representation of estimator.\n\n This is redundant with the logic of `_repr_mimebundle_`. The latter\n should be favorted in the long term, `_repr_html_` is only\n implemented for consumers who do not interpret `_repr_mimbundle_`.\n \"\"\"\n if get_config()[\"display\"] != \"diagram\":\n raise AttributeError(\n \"_repr_html_ is only defined when the \"\n \"'display' configuration option is set to \"\n \"'diagram'\"\n )\n return self._repr_html_inner\n\n def _repr_html_inner(self):\n \"\"\"This function is returned by the @property `_repr_html_` to make\n `hasattr(estimator, \"_repr_html_\") return `True` or `False` depending\n on `get_config()[\"display\"]`.\n \"\"\"\n return estimator_html_repr(self)\n\n def _repr_mimebundle_(self, **kwargs):\n \"\"\"Mime bundle used by jupyter kernels to display estimator\"\"\"\n output = {\"text/plain\": repr(self)}\n if get_config()[\"display\"] == \"diagram\":\n output[\"text/html\"] = estimator_html_repr(self)\n return output" }, { "identifier": "ClassifierMixin", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/base.py", "snippet": "class ClassifierMixin:\n \"\"\"Mixin class for all classifiers in scikit-learn.\"\"\"\n\n _estimator_type = \"classifier\"\n\n def score(self, X, y, sample_weight=None):\n \"\"\"\n Return the mean accuracy on the given test data and labels.\n\n In multi-label classification, this is the subset accuracy\n which is a harsh metric since you require for each sample that\n each label set be correctly predicted.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Test samples.\n\n y : array-like of shape (n_samples,) or (n_samples, n_outputs)\n True labels for `X`.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights.\n\n Returns\n -------\n score : float\n Mean accuracy of ``self.predict(X)`` w.r.t. `y`.\n \"\"\"\n from .metrics import accuracy_score\n\n return accuracy_score(y, self.predict(X), sample_weight=sample_weight)\n\n def _more_tags(self):\n return {\"requires_y\": True}" }, { "identifier": "MultiOutputMixin", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/base.py", "snippet": "class MultiOutputMixin:\n \"\"\"Mixin to mark estimators that support multioutput.\"\"\"\n\n def _more_tags(self):\n return {\"multioutput\": True}" }, { "identifier": "RegressorMixin", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/base.py", "snippet": "class RegressorMixin:\n \"\"\"Mixin class for all regression estimators in scikit-learn.\"\"\"\n\n _estimator_type = \"regressor\"\n\n def score(self, X, y, sample_weight=None):\n \"\"\"Return the coefficient of determination of the prediction.\n\n The coefficient of determination :math:`R^2` is defined as\n :math:`(1 - \\\\frac{u}{v})`, where :math:`u` is the residual\n sum of squares ``((y_true - y_pred)** 2).sum()`` and :math:`v`\n is the total sum of squares ``((y_true - y_true.mean()) ** 2).sum()``.\n The best possible score is 1.0 and it can be negative (because the\n model can be arbitrarily worse). A constant model that always predicts\n the expected value of `y`, disregarding the input features, would get\n a :math:`R^2` score of 0.0.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Test samples. For some estimators this may be a precomputed\n kernel matrix or a list of generic objects instead with shape\n ``(n_samples, n_samples_fitted)``, where ``n_samples_fitted``\n is the number of samples used in the fitting for the estimator.\n\n y : array-like of shape (n_samples,) or (n_samples, n_outputs)\n True values for `X`.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights.\n\n Returns\n -------\n score : float\n :math:`R^2` of ``self.predict(X)`` w.r.t. `y`.\n\n Notes\n -----\n The :math:`R^2` score used when calling ``score`` on a regressor uses\n ``multioutput='uniform_average'`` from version 0.23 to keep consistent\n with default value of :func:`~sklearn.metrics.r2_score`.\n This influences the ``score`` method of all the multioutput\n regressors (except for\n :class:`~sklearn.multioutput.MultiOutputRegressor`).\n \"\"\"\n\n from .metrics import r2_score\n\n y_pred = self.predict(X)\n return r2_score(y, y_pred, sample_weight=sample_weight)\n\n def _more_tags(self):\n return {\"requires_y\": True}" }, { "identifier": "_fit_context", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/base.py", "snippet": "def _fit_context(*, prefer_skip_nested_validation):\n \"\"\"Decorator to run the fit methods of estimators within context managers.\n\n Parameters\n ----------\n prefer_skip_nested_validation : bool\n If True, the validation of parameters of inner estimators or functions\n called during fit will be skipped.\n\n This is useful to avoid validating many times the parameters passed by the\n user from the public facing API. It's also useful to avoid validating\n parameters that we pass internally to inner functions that are guaranteed to\n be valid by the test suite.\n\n It should be set to True for most estimators, except for those that receive\n non-validated objects as parameters, such as meta-estimators that are given\n estimator objects.\n\n Returns\n -------\n decorated_fit : method\n The decorated fit method.\n \"\"\"\n\n def decorator(fit_method):\n @functools.wraps(fit_method)\n def wrapper(estimator, *args, **kwargs):\n global_skip_validation = get_config()[\"skip_parameter_validation\"]\n\n # we don't want to validate again for each call to partial_fit\n partial_fit_and_fitted = (\n fit_method.__name__ == \"partial_fit\" and _is_fitted(estimator)\n )\n\n if not global_skip_validation and not partial_fit_and_fitted:\n estimator._validate_params()\n\n with config_context(\n skip_parameter_validation=(\n prefer_skip_nested_validation or global_skip_validation\n )\n ):\n return fit_method(estimator, *args, **kwargs)\n\n return wrapper\n\n return decorator" }, { "identifier": "_is_constant_feature", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/preprocessing/_data.py", "snippet": "def _is_constant_feature(var, mean, n_samples):\n \"\"\"Detect if a feature is indistinguishable from a constant feature.\n\n The detection is based on its computed variance and on the theoretical\n error bounds of the '2 pass algorithm' for variance computation.\n\n See \"Algorithms for computing the sample variance: analysis and\n recommendations\", by Chan, Golub, and LeVeque.\n \"\"\"\n # In scikit-learn, variance is always computed using float64 accumulators.\n eps = np.finfo(np.float64).eps\n\n upper_bound = n_samples * eps * var + (n_samples * mean * eps) ** 2\n return var <= upper_bound" }, { "identifier": "check_array", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/validation.py", "snippet": "def check_array(\n array,\n accept_sparse=False,\n *,\n accept_large_sparse=True,\n dtype=\"numeric\",\n order=None,\n copy=False,\n force_all_finite=True,\n ensure_2d=True,\n allow_nd=False,\n ensure_min_samples=1,\n ensure_min_features=1,\n estimator=None,\n input_name=\"\",\n):\n \"\"\"Input validation on an array, list, sparse matrix or similar.\n\n By default, the input is checked to be a non-empty 2D array containing\n only finite values. If the dtype of the array is object, attempt\n converting to float, raising on failure.\n\n Parameters\n ----------\n array : object\n Input object to check / convert.\n\n accept_sparse : str, bool or list/tuple of str, default=False\n String[s] representing allowed sparse matrix formats, such as 'csc',\n 'csr', etc. If the input is sparse but not in the allowed format,\n it will be converted to the first listed format. True allows the input\n to be any format. False means that a sparse matrix input will\n raise an error.\n\n accept_large_sparse : bool, default=True\n If a CSR, CSC, COO or BSR sparse matrix is supplied and accepted by\n accept_sparse, accept_large_sparse=False will cause it to be accepted\n only if its indices are stored with a 32-bit dtype.\n\n .. versionadded:: 0.20\n\n dtype : 'numeric', type, list of type or None, default='numeric'\n Data type of result. If None, the dtype of the input is preserved.\n If \"numeric\", dtype is preserved unless array.dtype is object.\n If dtype is a list of types, conversion on the first type is only\n performed if the dtype of the input is not in the list.\n\n order : {'F', 'C'} or None, default=None\n Whether an array will be forced to be fortran or c-style.\n When order is None (default), then if copy=False, nothing is ensured\n about the memory layout of the output array; otherwise (copy=True)\n the memory layout of the returned array is kept as close as possible\n to the original array.\n\n copy : bool, default=False\n Whether a forced copy will be triggered. If copy=False, a copy might\n be triggered by a conversion.\n\n force_all_finite : bool or 'allow-nan', default=True\n Whether to raise an error on np.inf, np.nan, pd.NA in array. The\n possibilities are:\n\n - True: Force all values of array to be finite.\n - False: accepts np.inf, np.nan, pd.NA in array.\n - 'allow-nan': accepts only np.nan and pd.NA values in array. Values\n cannot be infinite.\n\n .. versionadded:: 0.20\n ``force_all_finite`` accepts the string ``'allow-nan'``.\n\n .. versionchanged:: 0.23\n Accepts `pd.NA` and converts it into `np.nan`\n\n ensure_2d : bool, default=True\n Whether to raise a value error if array is not 2D.\n\n allow_nd : bool, default=False\n Whether to allow array.ndim > 2.\n\n ensure_min_samples : int, default=1\n Make sure that the array has a minimum number of samples in its first\n axis (rows for a 2D array). Setting to 0 disables this check.\n\n ensure_min_features : int, default=1\n Make sure that the 2D array has some minimum number of features\n (columns). The default value of 1 rejects empty datasets.\n This check is only enforced when the input data has effectively 2\n dimensions or is originally 1D and ``ensure_2d`` is True. Setting to 0\n disables this check.\n\n estimator : str or estimator instance, default=None\n If passed, include the name of the estimator in warning messages.\n\n input_name : str, default=\"\"\n The data name used to construct the error message. In particular\n if `input_name` is \"X\" and the data has NaN values and\n allow_nan is False, the error message will link to the imputer\n documentation.\n\n .. versionadded:: 1.1.0\n\n Returns\n -------\n array_converted : object\n The converted and validated array.\n \"\"\"\n if isinstance(array, np.matrix):\n raise TypeError(\n \"np.matrix is not supported. Please convert to a numpy array with \"\n \"np.asarray. For more information see: \"\n \"https://numpy.org/doc/stable/reference/generated/numpy.matrix.html\"\n )\n\n xp, is_array_api_compliant = get_namespace(array)\n\n # store reference to original array to check if copy is needed when\n # function returns\n array_orig = array\n\n # store whether originally we wanted numeric dtype\n dtype_numeric = isinstance(dtype, str) and dtype == \"numeric\"\n\n dtype_orig = getattr(array, \"dtype\", None)\n if not is_array_api_compliant and not hasattr(dtype_orig, \"kind\"):\n # not a data type (e.g. a column named dtype in a pandas DataFrame)\n dtype_orig = None\n\n # check if the object contains several dtypes (typically a pandas\n # DataFrame), and store them. If not, store None.\n dtypes_orig = None\n pandas_requires_conversion = False\n if hasattr(array, \"dtypes\") and hasattr(array.dtypes, \"__array__\"):\n # throw warning if columns are sparse. If all columns are sparse, then\n # array.sparse exists and sparsity will be preserved (later).\n with suppress(ImportError):\n from pandas import SparseDtype\n\n def is_sparse(dtype):\n return isinstance(dtype, SparseDtype)\n\n if not hasattr(array, \"sparse\") and array.dtypes.apply(is_sparse).any():\n warnings.warn(\n \"pandas.DataFrame with sparse columns found.\"\n \"It will be converted to a dense numpy array.\"\n )\n\n dtypes_orig = list(array.dtypes)\n pandas_requires_conversion = any(\n _pandas_dtype_needs_early_conversion(i) for i in dtypes_orig\n )\n if all(isinstance(dtype_iter, np.dtype) for dtype_iter in dtypes_orig):\n dtype_orig = np.result_type(*dtypes_orig)\n elif pandas_requires_conversion and any(d == object for d in dtypes_orig):\n # Force object if any of the dtypes is an object\n dtype_orig = object\n\n elif (_is_extension_array_dtype(array) or hasattr(array, \"iloc\")) and hasattr(\n array, \"dtype\"\n ):\n # array is a pandas series\n pandas_requires_conversion = _pandas_dtype_needs_early_conversion(array.dtype)\n if isinstance(array.dtype, np.dtype):\n dtype_orig = array.dtype\n else:\n # Set to None to let array.astype work out the best dtype\n dtype_orig = None\n\n if dtype_numeric:\n if (\n dtype_orig is not None\n and hasattr(dtype_orig, \"kind\")\n and dtype_orig.kind == \"O\"\n ):\n # if input is object, convert to float.\n dtype = xp.float64\n else:\n dtype = None\n\n if isinstance(dtype, (list, tuple)):\n if dtype_orig is not None and dtype_orig in dtype:\n # no dtype conversion required\n dtype = None\n else:\n # dtype conversion required. Let's select the first element of the\n # list of accepted types.\n dtype = dtype[0]\n\n if pandas_requires_conversion:\n # pandas dataframe requires conversion earlier to handle extension dtypes with\n # nans\n # Use the original dtype for conversion if dtype is None\n new_dtype = dtype_orig if dtype is None else dtype\n array = array.astype(new_dtype)\n # Since we converted here, we do not need to convert again later\n dtype = None\n\n if dtype is not None and _is_numpy_namespace(xp):\n dtype = np.dtype(dtype)\n\n if force_all_finite not in (True, False, \"allow-nan\"):\n raise ValueError(\n 'force_all_finite should be a bool or \"allow-nan\". Got {!r} instead'.format(\n force_all_finite\n )\n )\n\n if dtype is not None and _is_numpy_namespace(xp):\n # convert to dtype object to conform to Array API to be use `xp.isdtype` later\n dtype = np.dtype(dtype)\n\n estimator_name = _check_estimator_name(estimator)\n context = \" by %s\" % estimator_name if estimator is not None else \"\"\n\n # When all dataframe columns are sparse, convert to a sparse array\n if hasattr(array, \"sparse\") and array.ndim > 1:\n with suppress(ImportError):\n from pandas import SparseDtype # noqa: F811\n\n def is_sparse(dtype):\n return isinstance(dtype, SparseDtype)\n\n if array.dtypes.apply(is_sparse).all():\n # DataFrame.sparse only supports `to_coo`\n array = array.sparse.to_coo()\n if array.dtype == np.dtype(\"object\"):\n unique_dtypes = set([dt.subtype.name for dt in array_orig.dtypes])\n if len(unique_dtypes) > 1:\n raise ValueError(\n \"Pandas DataFrame with mixed sparse extension arrays \"\n \"generated a sparse matrix with object dtype which \"\n \"can not be converted to a scipy sparse matrix.\"\n \"Sparse extension arrays should all have the same \"\n \"numeric type.\"\n )\n\n if sp.issparse(array):\n _ensure_no_complex_data(array)\n array = _ensure_sparse_format(\n array,\n accept_sparse=accept_sparse,\n dtype=dtype,\n copy=copy,\n force_all_finite=force_all_finite,\n accept_large_sparse=accept_large_sparse,\n estimator_name=estimator_name,\n input_name=input_name,\n )\n else:\n # If np.array(..) gives ComplexWarning, then we convert the warning\n # to an error. This is needed because specifying a non complex\n # dtype to the function converts complex to real dtype,\n # thereby passing the test made in the lines following the scope\n # of warnings context manager.\n with warnings.catch_warnings():\n try:\n warnings.simplefilter(\"error\", ComplexWarning)\n if dtype is not None and xp.isdtype(dtype, \"integral\"):\n # Conversion float -> int should not contain NaN or\n # inf (numpy#14412). We cannot use casting='safe' because\n # then conversion float -> int would be disallowed.\n array = _asarray_with_order(array, order=order, xp=xp)\n if xp.isdtype(array.dtype, (\"real floating\", \"complex floating\")):\n _assert_all_finite(\n array,\n allow_nan=False,\n msg_dtype=dtype,\n estimator_name=estimator_name,\n input_name=input_name,\n )\n array = xp.astype(array, dtype, copy=False)\n else:\n array = _asarray_with_order(array, order=order, dtype=dtype, xp=xp)\n except ComplexWarning as complex_warning:\n raise ValueError(\n \"Complex data not supported\\n{}\\n\".format(array)\n ) from complex_warning\n\n # It is possible that the np.array(..) gave no warning. This happens\n # when no dtype conversion happened, for example dtype = None. The\n # result is that np.array(..) produces an array of complex dtype\n # and we need to catch and raise exception for such cases.\n _ensure_no_complex_data(array)\n\n if ensure_2d:\n # If input is scalar raise error\n if array.ndim == 0:\n raise ValueError(\n \"Expected 2D array, got scalar array instead:\\narray={}.\\n\"\n \"Reshape your data either using array.reshape(-1, 1) if \"\n \"your data has a single feature or array.reshape(1, -1) \"\n \"if it contains a single sample.\".format(array)\n )\n # If input is 1D raise error\n if array.ndim == 1:\n raise ValueError(\n \"Expected 2D array, got 1D array instead:\\narray={}.\\n\"\n \"Reshape your data either using array.reshape(-1, 1) if \"\n \"your data has a single feature or array.reshape(1, -1) \"\n \"if it contains a single sample.\".format(array)\n )\n\n if dtype_numeric and hasattr(array.dtype, \"kind\") and array.dtype.kind in \"USV\":\n raise ValueError(\n \"dtype='numeric' is not compatible with arrays of bytes/strings.\"\n \"Convert your data to numeric values explicitly instead.\"\n )\n if not allow_nd and array.ndim >= 3:\n raise ValueError(\n \"Found array with dim %d. %s expected <= 2.\"\n % (array.ndim, estimator_name)\n )\n\n if force_all_finite:\n _assert_all_finite(\n array,\n input_name=input_name,\n estimator_name=estimator_name,\n allow_nan=force_all_finite == \"allow-nan\",\n )\n\n if ensure_min_samples > 0:\n n_samples = _num_samples(array)\n if n_samples < ensure_min_samples:\n raise ValueError(\n \"Found array with %d sample(s) (shape=%s) while a\"\n \" minimum of %d is required%s.\"\n % (n_samples, array.shape, ensure_min_samples, context)\n )\n\n if ensure_min_features > 0 and array.ndim == 2:\n n_features = array.shape[1]\n if n_features < ensure_min_features:\n raise ValueError(\n \"Found array with %d feature(s) (shape=%s) while\"\n \" a minimum of %d is required%s.\"\n % (n_features, array.shape, ensure_min_features, context)\n )\n\n if copy:\n if _is_numpy_namespace(xp):\n # only make a copy if `array` and `array_orig` may share memory`\n if np.may_share_memory(array, array_orig):\n array = _asarray_with_order(\n array, dtype=dtype, order=order, copy=True, xp=xp\n )\n else:\n # always make a copy for non-numpy arrays\n array = _asarray_with_order(\n array, dtype=dtype, order=order, copy=True, xp=xp\n )\n\n return array" }, { "identifier": "check_random_state", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/validation.py", "snippet": "def check_random_state(seed):\n \"\"\"Turn seed into a np.random.RandomState instance.\n\n Parameters\n ----------\n seed : None, int or instance of RandomState\n If seed is None, return the RandomState singleton used by np.random.\n If seed is an int, return a new RandomState instance seeded with seed.\n If seed is already a RandomState instance, return it.\n Otherwise raise ValueError.\n\n Returns\n -------\n :class:`numpy:numpy.random.RandomState`\n The random state object based on `seed` parameter.\n \"\"\"\n if seed is None or seed is np.random:\n return np.random.mtrand._rand\n if isinstance(seed, numbers.Integral):\n return np.random.RandomState(seed)\n if isinstance(seed, np.random.RandomState):\n return seed\n raise ValueError(\n \"%r cannot be used to seed a numpy.random.RandomState instance\" % seed\n )" }, { "identifier": "get_namespace", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/_array_api.py", "snippet": "def get_namespace(*arrays):\n \"\"\"Get namespace of arrays.\n\n Introspect `arrays` arguments and return their common Array API\n compatible namespace object, if any. NumPy 1.22 and later can\n construct such containers using the `numpy.array_api` namespace\n for instance.\n\n See: https://numpy.org/neps/nep-0047-array-api-standard.html\n\n If `arrays` are regular numpy arrays, an instance of the\n `_NumPyAPIWrapper` compatibility wrapper is returned instead.\n\n Namespace support is not enabled by default. To enabled it\n call:\n\n sklearn.set_config(array_api_dispatch=True)\n\n or:\n\n with sklearn.config_context(array_api_dispatch=True):\n # your code here\n\n Otherwise an instance of the `_NumPyAPIWrapper`\n compatibility wrapper is always returned irrespective of\n the fact that arrays implement the `__array_namespace__`\n protocol or not.\n\n Parameters\n ----------\n *arrays : array objects\n Array objects.\n\n Returns\n -------\n namespace : module\n Namespace shared by array objects. If any of the `arrays` are not arrays,\n the namespace defaults to NumPy.\n\n is_array_api_compliant : bool\n True if the arrays are containers that implement the Array API spec.\n Always False when array_api_dispatch=False.\n \"\"\"\n array_api_dispatch = get_config()[\"array_api_dispatch\"]\n if not array_api_dispatch:\n return _NUMPY_API_WRAPPER_INSTANCE, False\n\n _check_array_api_dispatch(array_api_dispatch)\n\n # array-api-compat is a required dependency of scikit-learn only when\n # configuring `array_api_dispatch=True`. Its import should therefore be\n # protected by _check_array_api_dispatch to display an informative error\n # message in case it is missing.\n import array_api_compat\n\n namespace, is_array_api_compliant = array_api_compat.get_namespace(*arrays), True\n\n if namespace.__name__ in {\"numpy.array_api\", \"cupy.array_api\"}:\n namespace = _ArrayAPIWrapper(namespace)\n\n return namespace, is_array_api_compliant" }, { "identifier": "_incremental_mean_and_var", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/extmath.py", "snippet": "def _incremental_mean_and_var(\n X, last_mean, last_variance, last_sample_count, sample_weight=None\n):\n \"\"\"Calculate mean update and a Youngs and Cramer variance update.\n\n If sample_weight is given, the weighted mean and variance is computed.\n\n Update a given mean and (possibly) variance according to new data given\n in X. last_mean is always required to compute the new mean.\n If last_variance is None, no variance is computed and None return for\n updated_variance.\n\n From the paper \"Algorithms for computing the sample variance: analysis and\n recommendations\", by Chan, Golub, and LeVeque.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Data to use for variance update.\n\n last_mean : array-like of shape (n_features,)\n\n last_variance : array-like of shape (n_features,)\n\n last_sample_count : array-like of shape (n_features,)\n The number of samples encountered until now if sample_weight is None.\n If sample_weight is not None, this is the sum of sample_weight\n encountered.\n\n sample_weight : array-like of shape (n_samples,) or None\n Sample weights. If None, compute the unweighted mean/variance.\n\n Returns\n -------\n updated_mean : ndarray of shape (n_features,)\n\n updated_variance : ndarray of shape (n_features,)\n None if last_variance was None.\n\n updated_sample_count : ndarray of shape (n_features,)\n\n Notes\n -----\n NaNs are ignored during the algorithm.\n\n References\n ----------\n T. Chan, G. Golub, R. LeVeque. Algorithms for computing the sample\n variance: recommendations, The American Statistician, Vol. 37, No. 3,\n pp. 242-247\n\n Also, see the sparse implementation of this in\n `utils.sparsefuncs.incr_mean_variance_axis` and\n `utils.sparsefuncs_fast.incr_mean_variance_axis0`\n \"\"\"\n # old = stats until now\n # new = the current increment\n # updated = the aggregated stats\n last_sum = last_mean * last_sample_count\n X_nan_mask = np.isnan(X)\n if np.any(X_nan_mask):\n sum_op = np.nansum\n else:\n sum_op = np.sum\n if sample_weight is not None:\n # equivalent to np.nansum(X * sample_weight, axis=0)\n # safer because np.float64(X*W) != np.float64(X)*np.float64(W)\n new_sum = _safe_accumulator_op(\n np.matmul, sample_weight, np.where(X_nan_mask, 0, X)\n )\n new_sample_count = _safe_accumulator_op(\n np.sum, sample_weight[:, None] * (~X_nan_mask), axis=0\n )\n else:\n new_sum = _safe_accumulator_op(sum_op, X, axis=0)\n n_samples = X.shape[0]\n new_sample_count = n_samples - np.sum(X_nan_mask, axis=0)\n\n updated_sample_count = last_sample_count + new_sample_count\n\n updated_mean = (last_sum + new_sum) / updated_sample_count\n\n if last_variance is None:\n updated_variance = None\n else:\n T = new_sum / new_sample_count\n temp = X - T\n if sample_weight is not None:\n # equivalent to np.nansum((X-T)**2 * sample_weight, axis=0)\n # safer because np.float64(X*W) != np.float64(X)*np.float64(W)\n correction = _safe_accumulator_op(\n np.matmul, sample_weight, np.where(X_nan_mask, 0, temp)\n )\n temp **= 2\n new_unnormalized_variance = _safe_accumulator_op(\n np.matmul, sample_weight, np.where(X_nan_mask, 0, temp)\n )\n else:\n correction = _safe_accumulator_op(sum_op, temp, axis=0)\n temp **= 2\n new_unnormalized_variance = _safe_accumulator_op(sum_op, temp, axis=0)\n\n # correction term of the corrected 2 pass algorithm.\n # See \"Algorithms for computing the sample variance: analysis\n # and recommendations\", by Chan, Golub, and LeVeque.\n new_unnormalized_variance -= correction**2 / new_sample_count\n\n last_unnormalized_variance = last_variance * last_sample_count\n\n with np.errstate(divide=\"ignore\", invalid=\"ignore\"):\n last_over_new_count = last_sample_count / new_sample_count\n updated_unnormalized_variance = (\n last_unnormalized_variance\n + new_unnormalized_variance\n + last_over_new_count\n / updated_sample_count\n * (last_sum / last_over_new_count - new_sum) ** 2\n )\n\n zeros = last_sample_count == 0\n updated_unnormalized_variance[zeros] = new_unnormalized_variance[zeros]\n updated_variance = updated_unnormalized_variance / updated_sample_count\n\n return updated_mean, updated_variance, updated_sample_count" }, { "identifier": "safe_sparse_dot", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/extmath.py", "snippet": "def safe_sparse_dot(a, b, *, dense_output=False):\n \"\"\"Dot product that handle the sparse matrix case correctly.\n\n Parameters\n ----------\n a : {ndarray, sparse matrix}\n b : {ndarray, sparse matrix}\n dense_output : bool, default=False\n When False, ``a`` and ``b`` both being sparse will yield sparse output.\n When True, output will always be a dense array.\n\n Returns\n -------\n dot_product : {ndarray, sparse matrix}\n Sparse if ``a`` and ``b`` are sparse and ``dense_output=False``.\n \"\"\"\n if a.ndim > 2 or b.ndim > 2:\n if sparse.issparse(a):\n # sparse is always 2D. Implies b is 3D+\n # [i, j] @ [k, ..., l, m, n] -> [i, k, ..., l, n]\n b_ = np.rollaxis(b, -2)\n b_2d = b_.reshape((b.shape[-2], -1))\n ret = a @ b_2d\n ret = ret.reshape(a.shape[0], *b_.shape[1:])\n elif sparse.issparse(b):\n # sparse is always 2D. Implies a is 3D+\n # [k, ..., l, m] @ [i, j] -> [k, ..., l, j]\n a_2d = a.reshape(-1, a.shape[-1])\n ret = a_2d @ b\n ret = ret.reshape(*a.shape[:-1], b.shape[1])\n else:\n ret = np.dot(a, b)\n else:\n ret = a @ b\n\n if (\n sparse.issparse(a)\n and sparse.issparse(b)\n and dense_output\n and hasattr(ret, \"toarray\")\n ):\n return ret.toarray()\n return ret" }, { "identifier": "Parallel", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/parallel.py", "snippet": "class Parallel(joblib.Parallel):\n \"\"\"Tweak of :class:`joblib.Parallel` that propagates the scikit-learn configuration.\n\n This subclass of :class:`joblib.Parallel` ensures that the active configuration\n (thread-local) of scikit-learn is propagated to the parallel workers for the\n duration of the execution of the parallel tasks.\n\n The API does not change and you can refer to :class:`joblib.Parallel`\n documentation for more details.\n\n .. versionadded:: 1.3\n \"\"\"\n\n def __call__(self, iterable):\n \"\"\"Dispatch the tasks and return the results.\n\n Parameters\n ----------\n iterable : iterable\n Iterable containing tuples of (delayed_function, args, kwargs) that should\n be consumed.\n\n Returns\n -------\n results : list\n List of results of the tasks.\n \"\"\"\n # Capture the thread-local scikit-learn configuration at the time\n # Parallel.__call__ is issued since the tasks can be dispatched\n # in a different thread depending on the backend and on the value of\n # pre_dispatch and n_jobs.\n config = get_config()\n iterable_with_config = (\n (_with_config(delayed_func, config), args, kwargs)\n for delayed_func, args, kwargs in iterable\n )\n return super().__call__(iterable_with_config)" }, { "identifier": "delayed", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/parallel.py", "snippet": "def delayed(function):\n \"\"\"Decorator used to capture the arguments of a function.\n\n This alternative to `joblib.delayed` is meant to be used in conjunction\n with `sklearn.utils.parallel.Parallel`. The latter captures the the scikit-\n learn configuration by calling `sklearn.get_config()` in the current\n thread, prior to dispatching the first task. The captured configuration is\n then propagated and enabled for the duration of the execution of the\n delayed function in the joblib workers.\n\n .. versionchanged:: 1.3\n `delayed` was moved from `sklearn.utils.fixes` to `sklearn.utils.parallel`\n in scikit-learn 1.3.\n\n Parameters\n ----------\n function : callable\n The function to be delayed.\n\n Returns\n -------\n output: tuple\n Tuple containing the delayed function, the positional arguments, and the\n keyword arguments.\n \"\"\"\n\n @functools.wraps(function)\n def delayed_function(*args, **kwargs):\n return _FuncWrapper(function), args, kwargs\n\n return delayed_function" }, { "identifier": "inplace_column_scale", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/sparsefuncs.py", "snippet": "def inplace_column_scale(X, scale):\n \"\"\"Inplace column scaling of a CSC/CSR matrix.\n\n Scale each feature of the data matrix by multiplying with specific scale\n provided by the caller assuming a (n_samples, n_features) shape.\n\n Parameters\n ----------\n X : sparse matrix of shape (n_samples, n_features)\n Matrix to normalize using the variance of the features. It should be\n of CSC or CSR format.\n\n scale : ndarray of shape (n_features,), dtype={np.float32, np.float64}\n Array of precomputed feature-wise values to use for scaling.\n \"\"\"\n if sp.issparse(X) and X.format == \"csc\":\n inplace_csr_row_scale(X.T, scale)\n elif sp.issparse(X) and X.format == \"csr\":\n inplace_csr_column_scale(X, scale)\n else:\n _raise_typeerror(X)" }, { "identifier": "mean_variance_axis", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/sparsefuncs.py", "snippet": "def mean_variance_axis(X, axis, weights=None, return_sum_weights=False):\n \"\"\"Compute mean and variance along an axis on a CSR or CSC matrix.\n\n Parameters\n ----------\n X : sparse matrix of shape (n_samples, n_features)\n Input data. It can be of CSR or CSC format.\n\n axis : {0, 1}\n Axis along which the axis should be computed.\n\n weights : ndarray of shape (n_samples,) or (n_features,), default=None\n If axis is set to 0 shape is (n_samples,) or\n if axis is set to 1 shape is (n_features,).\n If it is set to None, then samples are equally weighted.\n\n .. versionadded:: 0.24\n\n return_sum_weights : bool, default=False\n If True, returns the sum of weights seen for each feature\n if `axis=0` or each sample if `axis=1`.\n\n .. versionadded:: 0.24\n\n Returns\n -------\n\n means : ndarray of shape (n_features,), dtype=floating\n Feature-wise means.\n\n variances : ndarray of shape (n_features,), dtype=floating\n Feature-wise variances.\n\n sum_weights : ndarray of shape (n_features,), dtype=floating\n Returned if `return_sum_weights` is `True`.\n \"\"\"\n _raise_error_wrong_axis(axis)\n\n if sp.issparse(X) and X.format == \"csr\":\n if axis == 0:\n return _csr_mean_var_axis0(\n X, weights=weights, return_sum_weights=return_sum_weights\n )\n else:\n return _csc_mean_var_axis0(\n X.T, weights=weights, return_sum_weights=return_sum_weights\n )\n elif sp.issparse(X) and X.format == \"csc\":\n if axis == 0:\n return _csc_mean_var_axis0(\n X, weights=weights, return_sum_weights=return_sum_weights\n )\n else:\n return _csr_mean_var_axis0(\n X.T, weights=weights, return_sum_weights=return_sum_weights\n )\n else:\n _raise_typeerror(X)" }, { "identifier": "FLOAT_DTYPES", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/validation.py", "snippet": "FLOAT_DTYPES = (np.float64, np.float32, np.float16)" }, { "identifier": "_check_sample_weight", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/validation.py", "snippet": "def _check_sample_weight(\n sample_weight, X, dtype=None, copy=False, only_non_negative=False\n):\n \"\"\"Validate sample weights.\n\n Note that passing sample_weight=None will output an array of ones.\n Therefore, in some cases, you may want to protect the call with:\n if sample_weight is not None:\n sample_weight = _check_sample_weight(...)\n\n Parameters\n ----------\n sample_weight : {ndarray, Number or None}, shape (n_samples,)\n Input sample weights.\n\n X : {ndarray, list, sparse matrix}\n Input data.\n\n only_non_negative : bool, default=False,\n Whether or not the weights are expected to be non-negative.\n\n .. versionadded:: 1.0\n\n dtype : dtype, default=None\n dtype of the validated `sample_weight`.\n If None, and the input `sample_weight` is an array, the dtype of the\n input is preserved; otherwise an array with the default numpy dtype\n is be allocated. If `dtype` is not one of `float32`, `float64`,\n `None`, the output will be of dtype `float64`.\n\n copy : bool, default=False\n If True, a copy of sample_weight will be created.\n\n Returns\n -------\n sample_weight : ndarray of shape (n_samples,)\n Validated sample weight. It is guaranteed to be \"C\" contiguous.\n \"\"\"\n n_samples = _num_samples(X)\n\n if dtype is not None and dtype not in [np.float32, np.float64]:\n dtype = np.float64\n\n if sample_weight is None:\n sample_weight = np.ones(n_samples, dtype=dtype)\n elif isinstance(sample_weight, numbers.Number):\n sample_weight = np.full(n_samples, sample_weight, dtype=dtype)\n else:\n if dtype is None:\n dtype = [np.float64, np.float32]\n sample_weight = check_array(\n sample_weight,\n accept_sparse=False,\n ensure_2d=False,\n dtype=dtype,\n order=\"C\",\n copy=copy,\n input_name=\"sample_weight\",\n )\n if sample_weight.ndim != 1:\n raise ValueError(\"Sample weights must be 1D array or scalar\")\n\n if sample_weight.shape != (n_samples,):\n raise ValueError(\n \"sample_weight.shape == {}, expected {}!\".format(\n sample_weight.shape, (n_samples,)\n )\n )\n\n if only_non_negative:\n check_non_negative(sample_weight, \"`sample_weight`\")\n\n return sample_weight" }, { "identifier": "check_is_fitted", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/validation.py", "snippet": "def check_is_fitted(estimator, attributes=None, *, msg=None, all_or_any=all):\n \"\"\"Perform is_fitted validation for estimator.\n\n Checks if the estimator is fitted by verifying the presence of\n fitted attributes (ending with a trailing underscore) and otherwise\n raises a NotFittedError with the given message.\n\n If an estimator does not set any attributes with a trailing underscore, it\n can define a ``__sklearn_is_fitted__`` method returning a boolean to specify if the\n estimator is fitted or not.\n\n Parameters\n ----------\n estimator : estimator instance\n Estimator instance for which the check is performed.\n\n attributes : str, list or tuple of str, default=None\n Attribute name(s) given as string or a list/tuple of strings\n Eg.: ``[\"coef_\", \"estimator_\", ...], \"coef_\"``\n\n If `None`, `estimator` is considered fitted if there exist an\n attribute that ends with a underscore and does not start with double\n underscore.\n\n msg : str, default=None\n The default error message is, \"This %(name)s instance is not fitted\n yet. Call 'fit' with appropriate arguments before using this\n estimator.\"\n\n For custom messages if \"%(name)s\" is present in the message string,\n it is substituted for the estimator name.\n\n Eg. : \"Estimator, %(name)s, must be fitted before sparsifying\".\n\n all_or_any : callable, {all, any}, default=all\n Specify whether all or any of the given attributes must exist.\n\n Raises\n ------\n TypeError\n If the estimator is a class or not an estimator instance\n\n NotFittedError\n If the attributes are not found.\n \"\"\"\n if isclass(estimator):\n raise TypeError(\"{} is a class, not an instance.\".format(estimator))\n if msg is None:\n msg = (\n \"This %(name)s instance is not fitted yet. Call 'fit' with \"\n \"appropriate arguments before using this estimator.\"\n )\n\n if not hasattr(estimator, \"fit\"):\n raise TypeError(\"%s is not an estimator instance.\" % (estimator))\n\n if not _is_fitted(estimator, attributes, all_or_any):\n raise NotFittedError(msg % {\"name\": type(estimator).__name__})" } ]
import numbers import warnings import numpy as np import scipy.sparse as sp from abc import ABCMeta, abstractmethod from numbers import Integral from scipy import linalg, optimize, sparse from scipy.sparse.linalg import lsqr from scipy.special import expit from ..base import ( BaseEstimator, ClassifierMixin, MultiOutputMixin, RegressorMixin, _fit_context, ) from ..preprocessing._data import _is_constant_feature from ..utils import check_array, check_random_state from ..utils._array_api import get_namespace from ..utils._seq_dataset import ( ArrayDataset32, ArrayDataset64, CSRDataset32, CSRDataset64, ) from ..utils.extmath import _incremental_mean_and_var, safe_sparse_dot from ..utils.parallel import Parallel, delayed from ..utils.sparsefuncs import inplace_column_scale, mean_variance_axis from ..utils.validation import FLOAT_DTYPES, _check_sample_weight, check_is_fitted
17,924
.. versionadded:: 0.24 Attributes ---------- coef_ : array of shape (n_features, ) or (n_targets, n_features) Estimated coefficients for the linear regression problem. If multiple targets are passed during the fit (y 2D), this is a 2D array of shape (n_targets, n_features), while if only one target is passed, this is a 1D array of length n_features. rank_ : int Rank of matrix `X`. Only available when `X` is dense. singular_ : array of shape (min(X, y),) Singular values of `X`. Only available when `X` is dense. intercept_ : float or array of shape (n_targets,) Independent term in the linear model. Set to 0.0 if `fit_intercept = False`. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. .. versionadded:: 1.0 See Also -------- Ridge : Ridge regression addresses some of the problems of Ordinary Least Squares by imposing a penalty on the size of the coefficients with l2 regularization. Lasso : The Lasso is a linear model that estimates sparse coefficients with l1 regularization. ElasticNet : Elastic-Net is a linear regression model trained with both l1 and l2 -norm regularization of the coefficients. Notes ----- From the implementation point of view, this is just plain Ordinary Least Squares (scipy.linalg.lstsq) or Non Negative Least Squares (scipy.optimize.nnls) wrapped as a predictor object. Examples -------- >>> import numpy as np >>> from sklearn.linear_model import LinearRegression >>> X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]]) >>> # y = 1 * x_0 + 2 * x_1 + 3 >>> y = np.dot(X, np.array([1, 2])) + 3 >>> reg = LinearRegression().fit(X, y) >>> reg.score(X, y) 1.0 >>> reg.coef_ array([1., 2.]) >>> reg.intercept_ 3.0... >>> reg.predict(np.array([[3, 5]])) array([16.]) """ _parameter_constraints: dict = { "fit_intercept": ["boolean"], "copy_X": ["boolean"], "n_jobs": [None, Integral], "positive": ["boolean"], } def __init__( self, *, fit_intercept=True, copy_X=True, n_jobs=None, positive=False, ): self.fit_intercept = fit_intercept self.copy_X = copy_X self.n_jobs = n_jobs self.positive = positive @_fit_context(prefer_skip_nested_validation=True) def fit(self, X, y, sample_weight=None): """ Fit linear model. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training data. y : array-like of shape (n_samples,) or (n_samples, n_targets) Target values. Will be cast to X's dtype if necessary. sample_weight : array-like of shape (n_samples,), default=None Individual weights for each sample. .. versionadded:: 0.17 parameter *sample_weight* support to LinearRegression. Returns ------- self : object Fitted Estimator. """ n_jobs_ = self.n_jobs accept_sparse = False if self.positive else ["csr", "csc", "coo"] X, y = self._validate_data( X, y, accept_sparse=accept_sparse, y_numeric=True, multi_output=True ) has_sw = sample_weight is not None if has_sw:
""" Generalized Linear Models. """ # Author: Alexandre Gramfort <[email protected]> # Fabian Pedregosa <[email protected]> # Olivier Grisel <[email protected]> # Vincent Michel <[email protected]> # Peter Prettenhofer <[email protected]> # Mathieu Blondel <[email protected]> # Lars Buitinck # Maryan Morel <[email protected]> # Giorgio Patrini <[email protected]> # Maria Telenczuk <https://github.com/maikia> # License: BSD 3 clause # TODO: bayesian_ridge_regression and bayesian_regression_ard # should be squashed into its respective objects. SPARSE_INTERCEPT_DECAY = 0.01 # For sparse data intercept updates are scaled by this decay factor to avoid # intercept oscillation. # TODO(1.4): remove # parameter 'normalize' should be removed from linear models def _deprecate_normalize(normalize, estimator_name): """Normalize is to be deprecated from linear models and a use of a pipeline with a StandardScaler is to be recommended instead. Here the appropriate message is selected to be displayed to the user depending on the default normalize value (as it varies between the linear models and normalize value selected by the user). Parameters ---------- normalize : bool, normalize value passed by the user estimator_name : str name of the linear estimator which calls this function. The name will be used for writing the deprecation warnings Returns ------- normalize : bool, normalize value which should further be used by the estimator at this stage of the depreciation process Notes ----- This function should be completely removed in 1.4. """ if normalize not in [True, False, "deprecated"]: raise ValueError( "Leave 'normalize' to its default value or set it to True or False" ) if normalize == "deprecated": _normalize = False else: _normalize = normalize pipeline_msg = ( "If you wish to scale the data, use Pipeline with a StandardScaler " "in a preprocessing stage. To reproduce the previous behavior:\n\n" "from sklearn.pipeline import make_pipeline\n\n" "model = make_pipeline(StandardScaler(with_mean=False), " f"{estimator_name}())\n\n" "If you wish to pass a sample_weight parameter, you need to pass it " "as a fit parameter to each step of the pipeline as follows:\n\n" "kwargs = {s[0] + '__sample_weight': sample_weight for s " "in model.steps}\n" "model.fit(X, y, **kwargs)\n\n" ) alpha_msg = "" if "LassoLars" in estimator_name: alpha_msg = "Set parameter alpha to: original_alpha * np.sqrt(n_samples). " if normalize != "deprecated" and normalize: warnings.warn( "'normalize' was deprecated in version 1.2 and will be removed in 1.4.\n" + pipeline_msg + alpha_msg, FutureWarning, ) elif not normalize: warnings.warn( ( "'normalize' was deprecated in version 1.2 and will be " "removed in 1.4. " "Please leave the normalize parameter to its default value to " "silence this warning. The default behavior of this estimator " "is to not do any normalization. If normalization is needed " "please use sklearn.preprocessing.StandardScaler instead." ), FutureWarning, ) return _normalize def make_dataset(X, y, sample_weight, random_state=None): """Create ``Dataset`` abstraction for sparse and dense inputs. This also returns the ``intercept_decay`` which is different for sparse datasets. Parameters ---------- X : array-like, shape (n_samples, n_features) Training data y : array-like, shape (n_samples, ) Target values. sample_weight : numpy array of shape (n_samples,) The weight of each sample random_state : int, RandomState instance or None (default) Determines random number generation for dataset random sampling. It is not used for dataset shuffling. Pass an int for reproducible output across multiple function calls. See :term:`Glossary <random_state>`. Returns ------- dataset The ``Dataset`` abstraction intercept_decay The intercept decay """ rng = check_random_state(random_state) # seed should never be 0 in SequentialDataset64 seed = rng.randint(1, np.iinfo(np.int32).max) if X.dtype == np.float32: CSRData = CSRDataset32 ArrayData = ArrayDataset32 else: CSRData = CSRDataset64 ArrayData = ArrayDataset64 if sp.issparse(X): dataset = CSRData(X.data, X.indptr, X.indices, y, sample_weight, seed=seed) intercept_decay = SPARSE_INTERCEPT_DECAY else: X = np.ascontiguousarray(X) dataset = ArrayData(X, y, sample_weight, seed=seed) intercept_decay = 1.0 return dataset, intercept_decay def _preprocess_data( X, y, fit_intercept, normalize=False, copy=True, copy_y=True, sample_weight=None, check_input=True, ): """Center and scale data. Centers data to have mean zero along axis 0. If fit_intercept=False or if the X is a sparse matrix, no centering is done, but normalization can still be applied. The function returns the statistics necessary to reconstruct the input data, which are X_offset, y_offset, X_scale, such that the output X = (X - X_offset) / X_scale X_scale is the L2 norm of X - X_offset. If sample_weight is not None, then the weighted mean of X and y is zero, and not the mean itself. If fit_intercept=True, the mean, eventually weighted, is returned, independently of whether X was centered (option used for optimization with sparse data in coordinate_descend). This is here because nearly all linear models will want their data to be centered. This function also systematically makes y consistent with X.dtype Returns ------- X_out : {ndarray, sparse matrix} of shape (n_samples, n_features) If copy=True a copy of the input X is triggered, otherwise operations are inplace. If input X is dense, then X_out is centered. If normalize is True, then X_out is rescaled (dense and sparse case) y_out : {ndarray, sparse matrix} of shape (n_samples,) or (n_samples, n_targets) Centered version of y. Likely performed inplace on input y. X_offset : ndarray of shape (n_features,) The mean per column of input X. y_offset : float or ndarray of shape (n_features,) X_scale : ndarray of shape (n_features,) The standard deviation per column of input X. """ if isinstance(sample_weight, numbers.Number): sample_weight = None if sample_weight is not None: sample_weight = np.asarray(sample_weight) if check_input: X = check_array(X, copy=copy, accept_sparse=["csr", "csc"], dtype=FLOAT_DTYPES) y = check_array(y, dtype=X.dtype, copy=copy_y, ensure_2d=False) else: y = y.astype(X.dtype, copy=copy_y) if copy: if sp.issparse(X): X = X.copy() else: X = X.copy(order="K") if fit_intercept: if sp.issparse(X): X_offset, X_var = mean_variance_axis(X, axis=0, weights=sample_weight) else: if normalize: X_offset, X_var, _ = _incremental_mean_and_var( X, last_mean=0.0, last_variance=0.0, last_sample_count=0.0, sample_weight=sample_weight, ) else: X_offset = np.average(X, axis=0, weights=sample_weight) X_offset = X_offset.astype(X.dtype, copy=False) X -= X_offset if normalize: X_var = X_var.astype(X.dtype, copy=False) # Detect constant features on the computed variance, before taking # the np.sqrt. Otherwise constant features cannot be detected with # sample weights. constant_mask = _is_constant_feature(X_var, X_offset, X.shape[0]) if sample_weight is None: X_var *= X.shape[0] else: X_var *= sample_weight.sum() X_scale = np.sqrt(X_var, out=X_var) X_scale[constant_mask] = 1.0 if sp.issparse(X): inplace_column_scale(X, 1.0 / X_scale) else: X /= X_scale else: X_scale = np.ones(X.shape[1], dtype=X.dtype) y_offset = np.average(y, axis=0, weights=sample_weight) y -= y_offset else: X_offset = np.zeros(X.shape[1], dtype=X.dtype) X_scale = np.ones(X.shape[1], dtype=X.dtype) if y.ndim == 1: y_offset = X.dtype.type(0) else: y_offset = np.zeros(y.shape[1], dtype=X.dtype) return X, y, X_offset, y_offset, X_scale # TODO: _rescale_data should be factored into _preprocess_data. # Currently, the fact that sag implements its own way to deal with # sample_weight makes the refactoring tricky. def _rescale_data(X, y, sample_weight, inplace=False): """Rescale data sample-wise by square root of sample_weight. For many linear models, this enables easy support for sample_weight because (y - X w)' S (y - X w) with S = diag(sample_weight) becomes ||y_rescaled - X_rescaled w||_2^2 when setting y_rescaled = sqrt(S) y X_rescaled = sqrt(S) X Returns ------- X_rescaled : {array-like, sparse matrix} y_rescaled : {array-like, sparse matrix} """ # Assume that _validate_data and _check_sample_weight have been called by # the caller. n_samples = X.shape[0] sample_weight_sqrt = np.sqrt(sample_weight) if sp.issparse(X) or sp.issparse(y): sw_matrix = sparse.dia_matrix( (sample_weight_sqrt, 0), shape=(n_samples, n_samples) ) if sp.issparse(X): X = safe_sparse_dot(sw_matrix, X) else: if inplace: X *= sample_weight_sqrt[:, np.newaxis] else: X = X * sample_weight_sqrt[:, np.newaxis] if sp.issparse(y): y = safe_sparse_dot(sw_matrix, y) else: if inplace: if y.ndim == 1: y *= sample_weight_sqrt else: y *= sample_weight_sqrt[:, np.newaxis] else: if y.ndim == 1: y = y * sample_weight_sqrt else: y = y * sample_weight_sqrt[:, np.newaxis] return X, y, sample_weight_sqrt class LinearModel(BaseEstimator, metaclass=ABCMeta): """Base class for Linear Models""" @abstractmethod def fit(self, X, y): """Fit model.""" def _decision_function(self, X): check_is_fitted(self) X = self._validate_data(X, accept_sparse=["csr", "csc", "coo"], reset=False) return safe_sparse_dot(X, self.coef_.T, dense_output=True) + self.intercept_ def predict(self, X): """ Predict using the linear model. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) Samples. Returns ------- C : array, shape (n_samples,) Returns predicted values. """ return self._decision_function(X) def _set_intercept(self, X_offset, y_offset, X_scale): """Set the intercept_""" if self.fit_intercept: # We always want coef_.dtype=X.dtype. For instance, X.dtype can differ from # coef_.dtype if warm_start=True. self.coef_ = np.divide(self.coef_, X_scale, dtype=X_scale.dtype) self.intercept_ = y_offset - np.dot(X_offset, self.coef_.T) else: self.intercept_ = 0.0 def _more_tags(self): return {"requires_y": True} # XXX Should this derive from LinearModel? It should be a mixin, not an ABC. # Maybe the n_features checking can be moved to LinearModel. class LinearClassifierMixin(ClassifierMixin): """Mixin for linear classifiers. Handles prediction for sparse and dense X. """ def decision_function(self, X): """ Predict confidence scores for samples. The confidence score for a sample is proportional to the signed distance of that sample to the hyperplane. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The data matrix for which we want to get the confidence scores. Returns ------- scores : ndarray of shape (n_samples,) or (n_samples, n_classes) Confidence scores per `(n_samples, n_classes)` combination. In the binary case, confidence score for `self.classes_[1]` where >0 means this class would be predicted. """ check_is_fitted(self) xp, _ = get_namespace(X) X = self._validate_data(X, accept_sparse="csr", reset=False) scores = safe_sparse_dot(X, self.coef_.T, dense_output=True) + self.intercept_ return xp.reshape(scores, (-1,)) if scores.shape[1] == 1 else scores def predict(self, X): """ Predict class labels for samples in X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The data matrix for which we want to get the predictions. Returns ------- y_pred : ndarray of shape (n_samples,) Vector containing the class labels for each sample. """ xp, _ = get_namespace(X) scores = self.decision_function(X) if len(scores.shape) == 1: indices = xp.astype(scores > 0, int) else: indices = xp.argmax(scores, axis=1) return xp.take(self.classes_, indices) def _predict_proba_lr(self, X): """Probability estimation for OvR logistic regression. Positive class probabilities are computed as 1. / (1. + np.exp(-self.decision_function(X))); multiclass is handled by normalizing that over all classes. """ prob = self.decision_function(X) expit(prob, out=prob) if prob.ndim == 1: return np.vstack([1 - prob, prob]).T else: # OvR normalization, like LibLinear's predict_probability prob /= prob.sum(axis=1).reshape((prob.shape[0], -1)) return prob class SparseCoefMixin: """Mixin for converting coef_ to and from CSR format. L1-regularizing estimators should inherit this. """ def densify(self): """ Convert coefficient matrix to dense array format. Converts the ``coef_`` member (back) to a numpy.ndarray. This is the default format of ``coef_`` and is required for fitting, so calling this method is only required on models that have previously been sparsified; otherwise, it is a no-op. Returns ------- self Fitted estimator. """ msg = "Estimator, %(name)s, must be fitted before densifying." check_is_fitted(self, msg=msg) if sp.issparse(self.coef_): self.coef_ = self.coef_.toarray() return self def sparsify(self): """ Convert coefficient matrix to sparse format. Converts the ``coef_`` member to a scipy.sparse matrix, which for L1-regularized models can be much more memory- and storage-efficient than the usual numpy.ndarray representation. The ``intercept_`` member is not converted. Returns ------- self Fitted estimator. Notes ----- For non-sparse models, i.e. when there are not many zeros in ``coef_``, this may actually *increase* memory usage, so use this method with care. A rule of thumb is that the number of zero elements, which can be computed with ``(coef_ == 0).sum()``, must be more than 50% for this to provide significant benefits. After calling this method, further fitting with the partial_fit method (if any) will not work until you call densify. """ msg = "Estimator, %(name)s, must be fitted before sparsifying." check_is_fitted(self, msg=msg) self.coef_ = sp.csr_matrix(self.coef_) return self class LinearRegression(MultiOutputMixin, RegressorMixin, LinearModel): """ Ordinary least squares Linear Regression. LinearRegression fits a linear model with coefficients w = (w1, ..., wp) to minimize the residual sum of squares between the observed targets in the dataset, and the targets predicted by the linear approximation. Parameters ---------- fit_intercept : bool, default=True Whether to calculate the intercept for this model. If set to False, no intercept will be used in calculations (i.e. data is expected to be centered). copy_X : bool, default=True If True, X will be copied; else, it may be overwritten. n_jobs : int, default=None The number of jobs to use for the computation. This will only provide speedup in case of sufficiently large problems, that is if firstly `n_targets > 1` and secondly `X` is sparse or if `positive` is set to `True`. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. positive : bool, default=False When set to ``True``, forces the coefficients to be positive. This option is only supported for dense arrays. .. versionadded:: 0.24 Attributes ---------- coef_ : array of shape (n_features, ) or (n_targets, n_features) Estimated coefficients for the linear regression problem. If multiple targets are passed during the fit (y 2D), this is a 2D array of shape (n_targets, n_features), while if only one target is passed, this is a 1D array of length n_features. rank_ : int Rank of matrix `X`. Only available when `X` is dense. singular_ : array of shape (min(X, y),) Singular values of `X`. Only available when `X` is dense. intercept_ : float or array of shape (n_targets,) Independent term in the linear model. Set to 0.0 if `fit_intercept = False`. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. .. versionadded:: 1.0 See Also -------- Ridge : Ridge regression addresses some of the problems of Ordinary Least Squares by imposing a penalty on the size of the coefficients with l2 regularization. Lasso : The Lasso is a linear model that estimates sparse coefficients with l1 regularization. ElasticNet : Elastic-Net is a linear regression model trained with both l1 and l2 -norm regularization of the coefficients. Notes ----- From the implementation point of view, this is just plain Ordinary Least Squares (scipy.linalg.lstsq) or Non Negative Least Squares (scipy.optimize.nnls) wrapped as a predictor object. Examples -------- >>> import numpy as np >>> from sklearn.linear_model import LinearRegression >>> X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]]) >>> # y = 1 * x_0 + 2 * x_1 + 3 >>> y = np.dot(X, np.array([1, 2])) + 3 >>> reg = LinearRegression().fit(X, y) >>> reg.score(X, y) 1.0 >>> reg.coef_ array([1., 2.]) >>> reg.intercept_ 3.0... >>> reg.predict(np.array([[3, 5]])) array([16.]) """ _parameter_constraints: dict = { "fit_intercept": ["boolean"], "copy_X": ["boolean"], "n_jobs": [None, Integral], "positive": ["boolean"], } def __init__( self, *, fit_intercept=True, copy_X=True, n_jobs=None, positive=False, ): self.fit_intercept = fit_intercept self.copy_X = copy_X self.n_jobs = n_jobs self.positive = positive @_fit_context(prefer_skip_nested_validation=True) def fit(self, X, y, sample_weight=None): """ Fit linear model. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training data. y : array-like of shape (n_samples,) or (n_samples, n_targets) Target values. Will be cast to X's dtype if necessary. sample_weight : array-like of shape (n_samples,), default=None Individual weights for each sample. .. versionadded:: 0.17 parameter *sample_weight* support to LinearRegression. Returns ------- self : object Fitted Estimator. """ n_jobs_ = self.n_jobs accept_sparse = False if self.positive else ["csr", "csc", "coo"] X, y = self._validate_data( X, y, accept_sparse=accept_sparse, y_numeric=True, multi_output=True ) has_sw = sample_weight is not None if has_sw:
sample_weight = _check_sample_weight(
16
2023-10-07 13:19:48+00:00
24k
hellloxiaotian/KDNet
train_KDNet.py
[ { "identifier": "attempt_load", "path": "models/experimental.py", "snippet": "def attempt_load(weights, map_location=None):\n # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a\n model = Ensemble()\n # print('weights', weights) # /runs/train/yolov7_distillation19/weights/epoch_074.pt\n for w in weights if isinstance(weights, list) else [weights]:\n # attempt_download(w) # /runs/train/yolov7_distillation19/weights/epoch_074.pt\n ckpt = torch.load(w, map_location=map_location) # load\n model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model\n \n # Compatibility updates\n for m in model.modules():\n if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:\n m.inplace = True # pytorch 1.7.0 compatibility\n elif type(m) is nn.Upsample:\n m.recompute_scale_factor = None # torch 1.11.0 compatibility\n elif type(m) is Conv:\n m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility\n \n if len(model) == 1:\n return model[-1] # return model\n else:\n print('Ensemble created with %s\\n' % weights)\n for k in ['names', 'stride']:\n setattr(model, k, getattr(model[-1], k))\n return model # return ensemble" }, { "identifier": "attempt_loadv5", "path": "models/experimental.py", "snippet": "def attempt_loadv5(weights, device=None, inplace=True, fuse=True):\n # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a\n from models.yolo import Detect, Model\n\n model = Ensemble()\n for w in weights if isinstance(weights, list) else [weights]:\n ckpt = torch.load(attempt_download(w), map_location='cpu') # load\n ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float() # FP32 model\n\n # Model compatibility updates\n if not hasattr(ckpt, 'stride'):\n ckpt.stride = torch.tensor([32.])\n if hasattr(ckpt, 'names') and isinstance(ckpt.names, (list, tuple)):\n ckpt.names = dict(enumerate(ckpt.names)) # convert to dict\n\n model.append(ckpt.fuse().eval() if fuse and hasattr(ckpt, 'fuse') else ckpt.eval()) # model in eval mode\n\n # Module compatibility updates\n for m in model.modules():\n t = type(m)\n if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):\n m.inplace = inplace # torch 1.7.0 compatibility\n if t is Detect and not isinstance(m.anchor_grid, list):\n delattr(m, 'anchor_grid')\n setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)\n elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):\n m.recompute_scale_factor = None # torch 1.11.0 compatibility\n\n # Return model\n if len(model) == 1:\n return model[-1]\n\n # Return detection ensemble\n print(f'Ensemble created with {weights}\\n')\n for k in 'names', 'nc', 'yaml':\n setattr(model, k, getattr(model[0], k))\n model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride\n assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}'\n return model" }, { "identifier": "attempt_load_zxy", "path": "models/experimental.py", "snippet": "def attempt_load_zxy(weights, device, map_location=None):\n # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a\n model = Ensemble()\n for w in weights if isinstance(weights, list) else [weights]:\n attempt_download(w)\n ckpt = torch.load(w, map_location=map_location) # load\n model.append(ckpt['ema' if ckpt.get('ema') else 'model'].to(device).float().fuse().eval()) # FP32 model\n\n # Compatibility updates\n for m in model.modules():\n if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:\n m.inplace = True # pytorch 1.7.0 compatibility\n elif type(m) is nn.Upsample:\n m.recompute_scale_factor = None # torch 1.11.0 compatibility\n elif type(m) is Conv:\n m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility\n\n if len(model) == 1:\n return model[-1] # return model\n else:\n print('Ensemble created with %s\\n' % weights)\n for k in ['names', 'stride']:\n setattr(model, k, getattr(model[-1], k))\n return model # return ensemble" }, { "identifier": "Model", "path": "models/yolo.py", "snippet": "class Model(nn.Module):\n # def __init__(self, cfg='yolor-csp-c.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes\n def __init__(self, cfg='yolor-csp-c.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes\n super(Model, self).__init__()\n self.traced = False\n if isinstance(cfg, dict):\n self.yaml = cfg # model dict\n else: # is *.yaml\n import yaml # for torch hub\n self.yaml_file = Path(cfg).name\n with open(cfg) as f:\n self.yaml = yaml.load(f, Loader=yaml.SafeLoader) # model dict\n\n # Define model\n ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels\n if nc and nc != self.yaml['nc']:\n logger.info(f\"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}\")\n self.yaml['nc'] = nc # override yaml value\n if anchors:\n logger.info(f'Overriding model.yaml anchors with anchors={anchors}')\n self.yaml['anchors'] = round(anchors) # override yaml value\n self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist\n # self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]).cuda() # model, savelist\n self.names = [str(i) for i in range(self.yaml['nc'])] # default names\n # print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))])\n\n # Build strides, anchors\n # m = self.model[-1] # Detect()\n m = self.model[-1] # Detect()\n if isinstance(m, Detect):\n s = 256 # 2x min stride\n m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward\n check_anchor_order(m)\n m.anchors /= m.stride.view(-1, 1, 1)\n self.stride = m.stride\n self._initialize_biases() # only run once\n # print('Strides: %s' % m.stride.tolist())\n if isinstance(m, IDetect):\n print('yolo.py-IDetect')\n # print('m', m) # m IDetect\n m.cuda()\n s = 256 # 2x min stride\n # m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward\n m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]).cuda() # forward\n # print('m.device2', m.device)\n check_anchor_order(m)\n # print('m.device3', m.device)\n m.anchors /= m.stride.view(-1, 1, 1)\n self.stride = m.stride\n self._initialize_biases() # only run once\n # print('Strides: %s' % m.stride.tolist())\n if isinstance(m, IAuxDetect):\n s = 256 # 2x min stride\n m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))[:4]]) # forward\n #print(m.stride)\n check_anchor_order(m)\n m.anchors /= m.stride.view(-1, 1, 1)\n self.stride = m.stride\n self._initialize_aux_biases() # only run once\n # print('Strides: %s' % m.stride.tolist())\n if isinstance(m, IBin):\n s = 256 # 2x min stride\n m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward\n check_anchor_order(m)\n m.anchors /= m.stride.view(-1, 1, 1)\n self.stride = m.stride\n self._initialize_biases_bin() # only run once\n # print('Strides: %s' % m.stride.tolist())\n if isinstance(m, IKeypoint):\n s = 256 # 2x min stride\n m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward\n check_anchor_order(m)\n m.anchors /= m.stride.view(-1, 1, 1)\n self.stride = m.stride\n self._initialize_biases_kpt() # only run once\n # print('Strides: %s' % m.stride.tolist())\n\n # Init weights, biases\n initialize_weights(self)\n self.info()\n logger.info('')\n\n def forward(self, x, augment=False, profile=False):\n # print('x', x.shape)\n if augment:\n img_size = x.shape[-2:] # height, width\n s = [1, 0.83, 0.67] # scales\n f = [None, 3, None] # flips (2-ud, 3-lr)\n y = [] # outputs\n for si, fi in zip(s, f):\n xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))\n yi = self.forward_once(xi)[0] # forward\n # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save\n yi[..., :4] /= si # de-scale\n if fi == 2:\n yi[..., 1] = img_size[0] - yi[..., 1] # de-flip ud\n elif fi == 3:\n yi[..., 0] = img_size[1] - yi[..., 0] # de-flip lr\n y.append(yi)\n # print('y', y.shape)\n return torch.cat(y, 1), None # augmented inference, train\n else:\n return self.forward_once(x, profile) # single-scale inference, train\n\n def forward_once(self, x, profile=False):\n # print('x1', x.shape)\n y, dt = [], [] # outputs\n for m in self.model:\n if m.f != -1: # if not from previous layer\n x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers\n\n if not hasattr(self, 'traced'):\n self.traced=False\n\n if self.traced:\n if isinstance(m, Detect) or isinstance(m, IDetect) or isinstance(m, IAuxDetect) or isinstance(m, IKeypoint):\n break\n\n # print('profile', profile) # Flase\n if profile:\n c = isinstance(m, (Detect, IDetect, IAuxDetect, IBin))\n o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPS\n # print('o', o.shape)\n for _ in range(10):\n m(x.copy() if c else x)\n t = time_synchronized()\n for _ in range(10):\n m(x.copy() if c else x)\n dt.append((time_synchronized() - t) * 100)\n print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type))\n\n # print('x3', x.shape)\n # print('m.i', m.i) # =len(y)\n x = m(x) # run\\\n \n y.append(x if m.i in self.save else None) # save output\n # print('x4', x.shape)\n\n if profile:\n print('%.1fms total' % sum(dt))\n\n # print('x', len(x)) # 3\n return x\n\n def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency\n # https://arxiv.org/abs/1708.02002 section 3.3\n # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.\n m = self.model[-1] # Detect() module\n for mi, s in zip(m.m, m.stride): # from\n b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)\n b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)\n b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls\n mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)\n\n def _initialize_aux_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency\n # https://arxiv.org/abs/1708.02002 section 3.3\n # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.\n m = self.model[-1] # Detect() module\n for mi, mi2, s in zip(m.m, m.m2, m.stride): # from\n b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)\n b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)\n b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls\n mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)\n b2 = mi2.bias.view(m.na, -1) # conv.bias(255) to (3,85)\n b2.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)\n b2.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls\n mi2.bias = torch.nn.Parameter(b2.view(-1), requires_grad=True)\n\n def _initialize_biases_bin(self, cf=None): # initialize biases into Detect(), cf is class frequency\n # https://arxiv.org/abs/1708.02002 section 3.3\n # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.\n m = self.model[-1] # Bin() module\n bc = m.bin_count\n for mi, s in zip(m.m, m.stride): # from\n b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)\n old = b[:, (0,1,2,bc+3)].data\n obj_idx = 2*bc+4\n b[:, :obj_idx].data += math.log(0.6 / (bc + 1 - 0.99))\n b[:, obj_idx].data += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)\n b[:, (obj_idx+1):].data += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls\n b[:, (0,1,2,bc+3)].data = old\n mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)\n\n def _initialize_biases_kpt(self, cf=None): # initialize biases into Detect(), cf is class frequency\n # https://arxiv.org/abs/1708.02002 section 3.3\n # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.\n m = self.model[-1] # Detect() module\n for mi, s in zip(m.m, m.stride): # from\n b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)\n b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)\n b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls\n mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)\n\n def _print_biases(self):\n m = self.model[-1] # Detect() module\n for mi in m.m: # from\n b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)\n print(('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))\n\n # def _print_weights(self):\n # for m in self.model.modules():\n # if type(m) is Bottleneck:\n # print('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights\n\n def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers\n print('Fusing layers... ')\n for m in self.model.modules():\n if isinstance(m, RepConv):\n #print(f\" fuse_repvgg_block\")\n m.fuse_repvgg_block()\n elif isinstance(m, RepConv_OREPA):\n #print(f\" switch_to_deploy\")\n m.switch_to_deploy()\n elif type(m) is Conv and hasattr(m, 'bn'):\n m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv\n delattr(m, 'bn') # remove batchnorm\n m.forward = m.fuseforward # update forward\n elif isinstance(m, (IDetect, IAuxDetect)):\n m.fuse()\n m.forward = m.fuseforward\n self.info()\n return self\n\n def nms(self, mode=True): # add or remove NMS module\n present = type(self.model[-1]) is NMS # last layer is NMS\n if mode and not present:\n print('Adding NMS... ')\n m = NMS() # module\n m.f = -1 # from\n m.i = self.model[-1].i + 1 # index\n self.model.add_module(name='%s' % m.i, module=m) # add\n self.eval()\n elif not mode and present:\n print('Removing NMS... ')\n self.model = self.model[:-1] # remove\n return self\n\n def autoshape(self): # add autoShape module\n print('Adding autoShape... ')\n m = autoShape(self) # wrap model\n copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes\n return m\n\n def info(self, verbose=False, img_size=640): # print model information\n model_info(self, verbose, img_size)" }, { "identifier": "check_anchors", "path": "utils/autoanchor.py", "snippet": "def check_anchors(dataset, model, thr=4.0, imgsz=640):\n # Check anchor fit to data, recompute if necessary\n prefix = colorstr('autoanchor: ')\n print(f'\\n{prefix}Analyzing anchors... ', end='')\n m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()\n shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)\n scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale\n wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh\n\n def metric(k): # compute metric\n r = wh[:, None] / k[None]\n x = torch.min(r, 1. / r).min(2)[0] # ratio metric\n best = x.max(1)[0] # best_x\n aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold\n bpr = (best > 1. / thr).float().mean() # best possible recall\n return bpr, aat\n\n anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors\n bpr, aat = metric(anchors)\n print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='')\n if bpr < 0.98: # threshold to recompute\n print('. Attempting to improve anchors, please wait...')\n na = m.anchor_grid.numel() // 2 # number of anchors\n try:\n anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)\n except Exception as e:\n print(f'{prefix}ERROR: {e}')\n new_bpr = metric(anchors)[0]\n if new_bpr > bpr: # replace anchors\n anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)\n m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference\n check_anchor_order(m)\n m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss\n print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.')\n else:\n print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.')\n print('') # newline" }, { "identifier": "create_dataloader", "path": "utils/datasets.py", "snippet": "def create_dataloader(path, imgsz, batch_size, stride, opt, hyp=None, augment=False, cache=False, pad=0.0, rect=False,\n rank=-1, world_size=1, workers=8, image_weights=False, quad=False, prefix=''):\n # Make sure only the first process in DDP process the dataset first, and the following others can use the cache\n with torch_distributed_zero_first(rank):\n dataset = LoadImagesAndLabels(path, imgsz, batch_size,\n augment=augment, # augment images\n hyp=hyp, # augmentation hyperparameters\n rect=rect, # rectangular training\n cache_images=cache,\n single_cls=opt.single_cls,\n stride=int(stride),\n pad=pad,\n image_weights=image_weights,\n prefix=prefix)\n\n batch_size = min(batch_size, len(dataset))\n nw = min([os.cpu_count() // world_size, batch_size if batch_size > 1 else 0, workers]) # number of workers\n sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None\n loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader\n # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader()\n dataloader = loader(dataset,\n batch_size=batch_size,\n num_workers=nw,\n sampler=sampler,\n pin_memory=True,\n collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn)\n return dataloader, dataset" }, { "identifier": "labels_to_class_weights", "path": "utils/general.py", "snippet": "def set_logging(rank=-1):\ndef init_seeds(seed=0):\ndef get_latest_run(search_dir='.'):\ndef isdocker():\ndef emojis(str=''):\ndef check_online():\ndef check_git_status():\ndef check_requirements(requirements='requirements.txt', exclude=()):\ndef check_img_size(img_size, s=32):\ndef check_imshow():\ndef check_file(file):\ndef check_dataset(dict):\ndef make_divisible(x, divisor):\ndef clean_str(s):\ndef one_cycle(y1=0.0, y2=1.0, steps=100):\ndef colorstr(*input):\ndef labels_to_class_weights(labels, nc=80):\ndef labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):\ndef coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)\ndef xyxy2xywh(x):\ndef xywh2xyxy(x):\ndef xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):\ndef xyn2xy(x, w=640, h=640, padw=0, padh=0):\ndef segment2box(segment, width=640, height=640):\ndef segments2boxes(segments):\ndef resample_segments(segments, n=1000):\ndef scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):\ndef clip_coords(boxes, img_shape):\ndef bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):\ndef bbox_alpha_iou(box1, box2, x1y1x2y2=False, GIoU=False, DIoU=False, CIoU=False, alpha=2, eps=1e-9):\ndef box_iou(box1, box2):\n def box_area(box):\ndef wh_iou(wh1, wh2):\ndef box_giou(box1, box2):\n def box_area(box):\ndef box_ciou(box1, box2, eps: float = 1e-7):\n def box_area(box):\ndef box_diou(box1, box2, eps: float = 1e-7):\n def box_area(box):\ndef non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,\n labels=()):\ndef non_max_suppression_kpt(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,\n labels=(), kpt_label=False, nc=None, nkpt=None):\ndef strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer()\ndef print_mutation(hyp, results, yaml_file='hyp_evolved.yaml', bucket=''):\ndef apply_classifier(x, model, img, im0):\ndef increment_path(path, exist_ok=True, sep=''):" }, { "identifier": "attempt_download", "path": "utils/google_utils.py", "snippet": "def attempt_download(file, repo='WongKinYiu/yolov7'):\n # Attempt file download if does not exist\n file = Path(str(file).strip().replace(\"'\", '').lower())\n\n if not file.exists():\n try:\n response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api\n assets = [x['name'] for x in response['assets']] # release assets\n tag = response['tag_name'] # i.e. 'v1.0'\n except: # fallback plan\n assets = ['yolov7.pt', 'yolov7-tiny.pt', 'yolov7x.pt', 'yolov7-d6.pt', 'yolov7-e6.pt', \n 'yolov7-e6e.pt', 'yolov7-w6.pt']\n tag = subprocess.check_output('git tag', shell=True).decode().split()[-1]\n\n name = file.name\n if name in assets:\n msg = f'{file} missing, try downloading from https://github.com/{repo}/releases/'\n redundant = False # second download option\n try: # GitHub\n url = f'https://github.com/{repo}/releases/download/{tag}/{name}'\n print(f'Downloading {url} to {file}...')\n torch.hub.download_url_to_file(url, file)\n assert file.exists() and file.stat().st_size > 1E6 # check\n except Exception as e: # GCP\n print(f'Download error: {e}')\n assert redundant, 'No secondary mirror'\n url = f'https://storage.googleapis.com/{repo}/ckpt/{name}'\n print(f'Downloading {url} to {file}...')\n os.system(f'curl -L {url} -o {file}') # torch.hub.download_url_to_file(url, weights)\n finally:\n if not file.exists() or file.stat().st_size < 1E6: # check\n file.unlink(missing_ok=True) # remove partial downloads\n print(f'ERROR: Download failure: {msg}')\n print('')\n return" }, { "identifier": "ComputeLoss", "path": "utils/loss.py", "snippet": "class ComputeLoss:\n # Compute losses\n def __init__(self, model, autobalance=False):\n super(ComputeLoss, self).__init__()\n device = next(model.parameters()).device # get model device\n h = model.hyp # hyperparameters\n\n # Define criteria\n BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))\n BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))\n\n # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3\n self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets\n\n # Focal loss\n g = h['fl_gamma'] # focal loss gamma\n if g > 0:\n BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)\n\n det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module\n self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7\n #self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.1, .05]) # P3-P7\n #self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.5, 0.4, .1]) # P3-P7\n self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index\n self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance\n for k in 'na', 'nc', 'nl', 'anchors':\n setattr(self, k, getattr(det, k))\n\n def __call__(self, p, targets): # predictions, targets, model\n device = targets.device\n lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)\n tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets\n\n # Losses\n for i, pi in enumerate(p): # layer index, layer predictions\n b, a, gj, gi = indices[i] # image, anchor, gridy, gridx\n tobj = torch.zeros_like(pi[..., 0], device=device) # target obj\n\n n = b.shape[0] # number of targets\n if n:\n ps = pi[b, a, gj, gi] # prediction subset corresponding to targets\n\n # Regression\n pxy = ps[:, :2].sigmoid() * 2. - 0.5\n pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]\n pbox = torch.cat((pxy, pwh), 1) # predicted box\n iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target)\n lbox += (1.0 - iou).mean() # iou loss\n\n # Objectness\n tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio\n\n # Classification\n if self.nc > 1: # cls loss (only if multiple classes)\n t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets\n t[range(n), tcls[i]] = self.cp\n #t[t==self.cp] = iou.detach().clamp(0).type(t.dtype)\n lcls += self.BCEcls(ps[:, 5:], t) # BCE\n\n # Append targets to text file\n # with open('targets.txt', 'a') as file:\n # [file.write('%11.5g ' * 4 % tuple(x) + '\\n') for x in torch.cat((txy[i], twh[i]), 1)]\n\n obji = self.BCEobj(pi[..., 4], tobj)\n lobj += obji * self.balance[i] # obj loss\n if self.autobalance:\n self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()\n\n if self.autobalance:\n self.balance = [x / self.balance[self.ssi] for x in self.balance]\n lbox *= self.hyp['box']\n lobj *= self.hyp['obj']\n lcls *= self.hyp['cls']\n bs = tobj.shape[0] # batch size\n\n loss = lbox + lobj + lcls\n return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()\n\n def build_targets(self, p, targets):\n # Build targets for compute_loss(), input targets(image,class,x,y,w,h)\n na, nt = self.na, targets.shape[0] # number of anchors, targets\n tcls, tbox, indices, anch = [], [], [], []\n gain = torch.ones(7, device=targets.device).long() # normalized to gridspace gain\n ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)\n targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices\n\n g = 0.5 # bias\n off = torch.tensor([[0, 0],\n [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m\n # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm\n ], device=targets.device).float() * g # offsets\n\n for i in range(self.nl):\n anchors = self.anchors[i]\n gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain\n\n # Match targets to anchors\n t = targets * gain\n if nt:\n # Matches\n r = t[:, :, 4:6] / anchors[:, None] # wh ratio\n j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare\n # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))\n t = t[j] # filter\n\n # Offsets\n gxy = t[:, 2:4] # grid xy\n gxi = gain[[2, 3]] - gxy # inverse\n j, k = ((gxy % 1. < g) & (gxy > 1.)).T\n l, m = ((gxi % 1. < g) & (gxi > 1.)).T\n j = torch.stack((torch.ones_like(j), j, k, l, m))\n t = t.repeat((5, 1, 1))[j]\n offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]\n else:\n t = targets[0]\n offsets = 0\n\n # Define\n b, c = t[:, :2].long().T # image, class\n gxy = t[:, 2:4] # grid xy\n gwh = t[:, 4:6] # grid wh\n gij = (gxy - offsets).long()\n gi, gj = gij.T # grid xy indices\n\n # Append\n a = t[:, 6].long() # anchor indices\n indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices\n tbox.append(torch.cat((gxy - gij, gwh), 1)) # box\n anch.append(anchors[a]) # anchors\n tcls.append(c) # class\n\n return tcls, tbox, indices, anch" }, { "identifier": "ComputeLossOTA", "path": "utils/loss.py", "snippet": "class ComputeLossOTA:\n # Compute losses\n def __init__(self, model, autobalance=False):\n super(ComputeLossOTA, self).__init__()\n device = next(model.parameters()).device # get model device\n h = model.hyp # hyperparameters\n\n # Define criteria\n BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))\n BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))\n\n # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3\n self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets\n\n # Focal loss\n g = h['fl_gamma'] # focal loss gamma\n if g > 0:\n BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)\n\n det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module\n self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7\n self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index\n self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance\n for k in 'na', 'nc', 'nl', 'anchors', 'stride':\n setattr(self, k, getattr(det, k))\n\n def __call__(self, p, targets, imgs): # predictions, targets, model \n device = targets.device\n lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)\n bs, as_, gjs, gis, targets, anchors = self.build_targets(p, targets, imgs)\n pre_gen_gains = [torch.tensor(pp.shape, device=device)[[3, 2, 3, 2]] for pp in p] \n \n\n # Losses\n for i, pi in enumerate(p): # layer index, layer predictions\n b, a, gj, gi = bs[i], as_[i], gjs[i], gis[i] # image, anchor, gridy, gridx\n tobj = torch.zeros_like(pi[..., 0], device=device) # target obj\n\n n = b.shape[0] # number of targets\n if n:\n ps = pi[b, a, gj, gi] # prediction subset corresponding to targets\n\n # Regression\n grid = torch.stack([gi, gj], dim=1)\n pxy = ps[:, :2].sigmoid() * 2. - 0.5\n #pxy = ps[:, :2].sigmoid() * 3. - 1.\n pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]\n pbox = torch.cat((pxy, pwh), 1) # predicted box\n selected_tbox = targets[i][:, 2:6] * pre_gen_gains[i]\n selected_tbox[:, :2] -= grid\n iou = bbox_iou(pbox.T, selected_tbox, x1y1x2y2=False, CIoU=True) # iou(prediction, target)\n lbox += (1.0 - iou).mean() # iou loss\n\n # Objectness\n tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio\n\n # Classification\n selected_tcls = targets[i][:, 1].long()\n if self.nc > 1: # cls loss (only if multiple classes)\n t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets\n t[range(n), selected_tcls] = self.cp\n lcls += self.BCEcls(ps[:, 5:], t) # BCE\n\n # Append targets to text file\n # with open('targets.txt', 'a') as file:\n # [file.write('%11.5g ' * 4 % tuple(x) + '\\n') for x in torch.cat((txy[i], twh[i]), 1)]\n\n obji = self.BCEobj(pi[..., 4], tobj)\n lobj += obji * self.balance[i] # obj loss\n if self.autobalance:\n self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()\n\n if self.autobalance:\n self.balance = [x / self.balance[self.ssi] for x in self.balance]\n lbox *= self.hyp['box']\n lobj *= self.hyp['obj']\n lcls *= self.hyp['cls']\n bs = tobj.shape[0] # batch size\n\n loss = lbox + lobj + lcls\n return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()\n\n def build_targets(self, p, targets, imgs):\n \n #indices, anch = self.find_positive(p, targets)\n indices, anch = self.find_3_positive(p, targets)\n #indices, anch = self.find_4_positive(p, targets)\n #indices, anch = self.find_5_positive(p, targets)\n #indices, anch = self.find_9_positive(p, targets)\n device = torch.device(targets.device)\n matching_bs = [[] for pp in p]\n matching_as = [[] for pp in p]\n matching_gjs = [[] for pp in p]\n matching_gis = [[] for pp in p]\n matching_targets = [[] for pp in p]\n matching_anchs = [[] for pp in p]\n \n nl = len(p) \n \n for batch_idx in range(p[0].shape[0]):\n \n b_idx = targets[:, 0]==batch_idx\n this_target = targets[b_idx]\n if this_target.shape[0] == 0:\n continue\n \n txywh = this_target[:, 2:6] * imgs[batch_idx].shape[1]\n txyxy = xywh2xyxy(txywh)\n\n pxyxys = []\n p_cls = []\n p_obj = []\n from_which_layer = []\n all_b = []\n all_a = []\n all_gj = []\n all_gi = []\n all_anch = []\n \n for i, pi in enumerate(p):\n \n b, a, gj, gi = indices[i]\n idx = (b == batch_idx)\n b, a, gj, gi = b[idx], a[idx], gj[idx], gi[idx] \n all_b.append(b)\n all_a.append(a)\n all_gj.append(gj)\n all_gi.append(gi)\n all_anch.append(anch[i][idx])\n from_which_layer.append((torch.ones(size=(len(b),)) * i).to(device))\n \n fg_pred = pi[b, a, gj, gi] \n p_obj.append(fg_pred[:, 4:5])\n p_cls.append(fg_pred[:, 5:])\n \n grid = torch.stack([gi, gj], dim=1)\n pxy = (fg_pred[:, :2].sigmoid() * 2. - 0.5 + grid) * self.stride[i] #/ 8.\n #pxy = (fg_pred[:, :2].sigmoid() * 3. - 1. + grid) * self.stride[i]\n pwh = (fg_pred[:, 2:4].sigmoid() * 2) ** 2 * anch[i][idx] * self.stride[i] #/ 8.\n pxywh = torch.cat([pxy, pwh], dim=-1)\n pxyxy = xywh2xyxy(pxywh)\n pxyxys.append(pxyxy)\n \n pxyxys = torch.cat(pxyxys, dim=0)\n if pxyxys.shape[0] == 0:\n continue\n p_obj = torch.cat(p_obj, dim=0)\n p_cls = torch.cat(p_cls, dim=0)\n from_which_layer = torch.cat(from_which_layer, dim=0)\n all_b = torch.cat(all_b, dim=0)\n all_a = torch.cat(all_a, dim=0)\n all_gj = torch.cat(all_gj, dim=0)\n all_gi = torch.cat(all_gi, dim=0)\n all_anch = torch.cat(all_anch, dim=0)\n \n pair_wise_iou = box_iou(txyxy, pxyxys)\n\n pair_wise_iou_loss = -torch.log(pair_wise_iou + 1e-8)\n\n top_k, _ = torch.topk(pair_wise_iou, min(10, pair_wise_iou.shape[1]), dim=1)\n dynamic_ks = torch.clamp(top_k.sum(1).int(), min=1)\n\n gt_cls_per_image = (\n F.one_hot(this_target[:, 1].to(torch.int64), self.nc)\n .float()\n .unsqueeze(1)\n .repeat(1, pxyxys.shape[0], 1)\n )\n\n num_gt = this_target.shape[0]\n cls_preds_ = (\n p_cls.float().unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()\n * p_obj.unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()\n )\n\n y = cls_preds_.sqrt_()\n pair_wise_cls_loss = F.binary_cross_entropy_with_logits(\n torch.log(y/(1-y)) , gt_cls_per_image, reduction=\"none\"\n ).sum(-1)\n del cls_preds_\n \n cost = (\n pair_wise_cls_loss\n + 3.0 * pair_wise_iou_loss\n )\n\n matching_matrix = torch.zeros_like(cost, device=device)\n\n for gt_idx in range(num_gt):\n _, pos_idx = torch.topk(\n cost[gt_idx], k=dynamic_ks[gt_idx].item(), largest=False\n )\n matching_matrix[gt_idx][pos_idx] = 1.0\n\n del top_k, dynamic_ks\n anchor_matching_gt = matching_matrix.sum(0)\n if (anchor_matching_gt > 1).sum() > 0:\n _, cost_argmin = torch.min(cost[:, anchor_matching_gt > 1], dim=0)\n matching_matrix[:, anchor_matching_gt > 1] *= 0.0\n matching_matrix[cost_argmin, anchor_matching_gt > 1] = 1.0\n fg_mask_inboxes = (matching_matrix.sum(0) > 0.0).to(device)\n matched_gt_inds = matching_matrix[:, fg_mask_inboxes].argmax(0)\n \n from_which_layer = from_which_layer[fg_mask_inboxes]\n all_b = all_b[fg_mask_inboxes]\n all_a = all_a[fg_mask_inboxes]\n all_gj = all_gj[fg_mask_inboxes]\n all_gi = all_gi[fg_mask_inboxes]\n all_anch = all_anch[fg_mask_inboxes]\n \n this_target = this_target[matched_gt_inds]\n \n for i in range(nl):\n layer_idx = from_which_layer == i\n matching_bs[i].append(all_b[layer_idx])\n matching_as[i].append(all_a[layer_idx])\n matching_gjs[i].append(all_gj[layer_idx])\n matching_gis[i].append(all_gi[layer_idx])\n matching_targets[i].append(this_target[layer_idx])\n matching_anchs[i].append(all_anch[layer_idx])\n\n for i in range(nl):\n if matching_targets[i] != []:\n matching_bs[i] = torch.cat(matching_bs[i], dim=0)\n matching_as[i] = torch.cat(matching_as[i], dim=0)\n matching_gjs[i] = torch.cat(matching_gjs[i], dim=0)\n matching_gis[i] = torch.cat(matching_gis[i], dim=0)\n matching_targets[i] = torch.cat(matching_targets[i], dim=0)\n matching_anchs[i] = torch.cat(matching_anchs[i], dim=0)\n else:\n matching_bs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)\n matching_as[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)\n matching_gjs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)\n matching_gis[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)\n matching_targets[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)\n matching_anchs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)\n\n return matching_bs, matching_as, matching_gjs, matching_gis, matching_targets, matching_anchs \n\n def find_3_positive(self, p, targets):\n # Build targets for compute_loss(), input targets(image,class,x,y,w,h)\n na, nt = self.na, targets.shape[0] # number of anchors, targets\n indices, anch = [], []\n gain = torch.ones(7, device=targets.device).long() # normalized to gridspace gain\n ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)\n targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices\n\n g = 0.5 # bias\n off = torch.tensor([[0, 0],\n [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m\n # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm\n ], device=targets.device).float() * g # offsets\n\n for i in range(self.nl):\n anchors = self.anchors[i]\n gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain\n\n # Match targets to anchors\n t = targets * gain\n if nt:\n # Matches\n r = t[:, :, 4:6] / anchors[:, None] # wh ratio\n j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare\n # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))\n t = t[j] # filter\n\n # Offsets\n gxy = t[:, 2:4] # grid xy\n gxi = gain[[2, 3]] - gxy # inverse\n j, k = ((gxy % 1. < g) & (gxy > 1.)).T\n l, m = ((gxi % 1. < g) & (gxi > 1.)).T\n j = torch.stack((torch.ones_like(j), j, k, l, m))\n t = t.repeat((5, 1, 1))[j]\n offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]\n else:\n t = targets[0]\n offsets = 0\n\n # Define\n b, c = t[:, :2].long().T # image, class\n gxy = t[:, 2:4] # grid xy\n gwh = t[:, 4:6] # grid wh\n gij = (gxy - offsets).long()\n gi, gj = gij.T # grid xy indices\n\n # Append\n a = t[:, 6].long() # anchor indices\n indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices\n anch.append(anchors[a]) # anchors\n\n return indices, anch" }, { "identifier": "plot_images", "path": "utils/plots.py", "snippet": "def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16):\n # Plot image grid with labels\n\n if isinstance(images, torch.Tensor):\n images = images.cpu().float().numpy()\n if isinstance(targets, torch.Tensor):\n targets = targets.cpu().numpy()\n\n # un-normalise\n if np.max(images[0]) <= 1:\n images *= 255\n\n tl = 3 # line thickness\n tf = max(tl - 1, 1) # font thickness\n bs, _, h, w = images.shape # batch size, _, height, width\n bs = min(bs, max_subplots) # limit plot images\n ns = np.ceil(bs ** 0.5) # number of subplots (square)\n\n # Check if we should resize\n scale_factor = max_size / max(h, w)\n if scale_factor < 1:\n h = math.ceil(scale_factor * h)\n w = math.ceil(scale_factor * w)\n\n colors = color_list() # list of colors\n mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init\n for i, img in enumerate(images):\n if i == max_subplots: # if last batch has fewer images than we expect\n break\n\n block_x = int(w * (i // ns))\n block_y = int(h * (i % ns))\n\n img = img.transpose(1, 2, 0)\n if scale_factor < 1:\n img = cv2.resize(img, (w, h))\n\n mosaic[block_y:block_y + h, block_x:block_x + w, :] = img\n if len(targets) > 0:\n image_targets = targets[targets[:, 0] == i]\n boxes = xywh2xyxy(image_targets[:, 2:6]).T\n classes = image_targets[:, 1].astype('int')\n labels = image_targets.shape[1] == 6 # labels if no conf column\n conf = None if labels else image_targets[:, 6] # check for confidence presence (label vs pred)\n\n if boxes.shape[1]:\n if boxes.max() <= 1.01: # if normalized with tolerance 0.01\n boxes[[0, 2]] *= w # scale to pixels\n boxes[[1, 3]] *= h\n elif scale_factor < 1: # absolute coords need scale if image scales\n boxes *= scale_factor\n boxes[[0, 2]] += block_x\n boxes[[1, 3]] += block_y\n for j, box in enumerate(boxes.T):\n cls = int(classes[j])\n color = colors[cls % len(colors)]\n cls = names[cls] if names else cls\n if labels or conf[j] > 0.25: # 0.25 conf thresh\n label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j])\n plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl)\n\n # Draw image filename labels\n if paths:\n label = Path(paths[i]).name[:40] # trim to 40 char\n t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]\n cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf,\n lineType=cv2.LINE_AA)\n\n # Image border\n cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3)\n\n if fname:\n r = min(1280. / max(h, w) / ns, 1.0) # ratio to limit image size\n mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA)\n # cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB)) # cv2 save\n Image.fromarray(mosaic).save(fname) # PIL save\n return mosaic" }, { "identifier": "plot_labels", "path": "utils/plots.py", "snippet": "def plot_labels(labels, names=(), save_dir=Path(''), loggers=None):\n # plot dataset labels\n print('Plotting labels... ')\n c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes\n nc = int(c.max() + 1) # number of classes\n colors = color_list()\n x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])\n\n # seaborn correlogram\n sns.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))\n plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)\n plt.close()\n\n # matplotlib labels\n matplotlib.use('svg') # faster\n ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()\n ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)\n ax[0].set_ylabel('instances')\n if 0 < len(names) < 30:\n ax[0].set_xticks(range(len(names)))\n ax[0].set_xticklabels(names, rotation=90, fontsize=10)\n else:\n ax[0].set_xlabel('classes')\n sns.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)\n sns.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)\n\n # rectangles\n labels[:, 1:3] = 0.5 # center\n labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000\n img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)\n for cls, *box in labels[:1000]:\n ImageDraw.Draw(img).rectangle(box, width=1, outline=colors[int(cls) % 10]) # plot\n ax[1].imshow(img)\n ax[1].axis('off')\n\n for a in [0, 1, 2, 3]:\n for s in ['top', 'right', 'left', 'bottom']:\n ax[a].spines[s].set_visible(False)\n\n plt.savefig(save_dir / 'labels.jpg', dpi=200)\n matplotlib.use('Agg')\n plt.close()\n\n # loggers\n for k, v in loggers.items() or {}:\n if k == 'wandb' and v:\n v.log({\"Labels\": [v.Image(str(x), caption=x.name) for x in save_dir.glob('*labels*.jpg')]}, commit=False)" }, { "identifier": "plot_results", "path": "utils/plots.py", "snippet": "def plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''):\n # Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp')\n fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)\n ax = ax.ravel()\n s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall',\n 'val Box', 'val Objectness', 'val Classification', '[email protected]', '[email protected]:0.95']\n if bucket:\n # files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]\n files = ['results%g.txt' % x for x in id]\n c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id)\n os.system(c)\n else:\n files = list(Path(save_dir).glob('results*.txt'))\n assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir)\n for fi, f in enumerate(files):\n try:\n results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T\n n = results.shape[1] # number of rows\n x = range(start, min(stop, n) if stop else n)\n for i in range(10):\n y = results[i, x]\n if i in [0, 1, 2, 5, 6, 7]:\n y[y == 0] = np.nan # don't show zero loss values\n # y /= y[0] # normalize\n label = labels[fi] if len(labels) else f.stem\n ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8)\n ax[i].set_title(s[i])\n # if i in [5, 6, 7]: # share train and val loss y axes\n # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])\n except Exception as e:\n print('Warning: Plotting error for %s; %s' % (f, e))\n\n ax[1].legend()\n fig.savefig(Path(save_dir) / 'results.png', dpi=200)" }, { "identifier": "plot_evolution", "path": "utils/plots.py", "snippet": "def plot_evolution(yaml_file='data/hyp.finetune.yaml'): # from utils.plots import *; plot_evolution()\n # Plot hyperparameter evolution results in evolve.txt\n with open(yaml_file) as f:\n hyp = yaml.load(f, Loader=yaml.SafeLoader)\n x = np.loadtxt('evolve.txt', ndmin=2)\n f = fitness(x)\n # weights = (f - f.min()) ** 2 # for weighted results\n plt.figure(figsize=(10, 12), tight_layout=True)\n matplotlib.rc('font', **{'size': 8})\n for i, (k, v) in enumerate(hyp.items()):\n y = x[:, i + 7]\n # mu = (y * weights).sum() / weights.sum() # best weighted result\n mu = y[f.argmax()] # best single result\n plt.subplot(6, 5, i + 1)\n plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none')\n plt.plot(mu, f.max(), 'k+', markersize=15)\n plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters\n if i % 5 != 0:\n plt.yticks([])\n print('%15s: %.3g' % (k, mu))\n plt.savefig('evolve.png', dpi=200)\n print('\\nPlot saved as evolve.png')" }, { "identifier": "ModelEMA", "path": "utils/torch_utils.py", "snippet": "class ModelEMA:\n \"\"\" Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models\n Keep a moving average of everything in the model state_dict (parameters and buffers).\n This is intended to allow functionality like\n https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage\n A smoothed version of the weights is necessary for some training schemes to perform well.\n This class is sensitive where it is initialized in the sequence of model init,\n GPU assignment and distributed training wrappers.\n \"\"\"\n\n def __init__(self, model, decay=0.9999, updates=0):\n # Create EMA\n self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA\n # if next(model.parameters()).device.type != 'cpu':\n # self.ema.half() # FP16 EMA\n self.updates = updates # number of EMA updates\n self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs)\n for p in self.ema.parameters():\n p.requires_grad_(False)\n\n def update(self, model):\n # Update EMA parameters\n with torch.no_grad():\n self.updates += 1\n d = self.decay(self.updates)\n\n msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict\n for k, v in self.ema.state_dict().items():\n if v.dtype.is_floating_point:\n v *= d\n v += (1. - d) * msd[k].detach()\n\n def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):\n # Update EMA attributes\n copy_attr(self.ema, model, include, exclude)" }, { "identifier": "select_device", "path": "utils/torch_utils.py", "snippet": "def select_device(device='', batch_size=None):\n # device = 'cpu' or '0' or '0,1,2,3'\n s = f'YOLOR 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string\n cpu = device.lower() == 'cpu'\n if cpu:\n os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False\n elif device: # non-cpu device requested\n os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable\n assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability\n\n cuda = not cpu and torch.cuda.is_available()\n if cuda:\n n = torch.cuda.device_count()\n if n > 1 and batch_size: # check that batch_size is compatible with device_count\n assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'\n space = ' ' * len(s)\n for i, d in enumerate(device.split(',') if device else range(n)):\n p = torch.cuda.get_device_properties(i)\n s += f\"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\\n\" # bytes to MB\n else:\n s += 'CPU\\n'\n\n logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe\n return torch.device('cuda:0' if cuda else 'cpu')" }, { "identifier": "intersect_dicts", "path": "utils/torch_utils.py", "snippet": "def intersect_dicts(da, db, exclude=()):\n # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values\n return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}" }, { "identifier": "torch_distributed_zero_first", "path": "utils/torch_utils.py", "snippet": "@contextmanager\ndef torch_distributed_zero_first(local_rank: int):\n \"\"\"\n Decorator to make all processes in distributed training wait for each local_master to do something.\n \"\"\"\n if local_rank not in [-1, 0]:\n torch.distributed.barrier()\n yield\n if local_rank == 0:\n torch.distributed.barrier()" }, { "identifier": "is_parallel", "path": "utils/torch_utils.py", "snippet": "def is_parallel(model):\n return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)" }, { "identifier": "getMask", "path": "utils/distill_utils.py", "snippet": "def getMask(batch_size, gt_boxes, img_size, feat, anchors, max_num_box, device):\r\n # [b, K, 4]\r\n gt_boxes = make_gt_boxes(gt_boxes, max_num_box, batch_size, img_size)\r\n feat_stride = img_size[0] / feat.size(2)\r\n anchors = torch.from_numpy(generate_anchors(feat_stride, anchors))\r\n feat = feat.cpu()\r\n height, width = feat.size(2), feat.size(3)\r\n feat_height, feat_width = feat.size(2), feat.size(3)\r\n shift_x = np.arange(0, feat_width) * feat_stride\r\n shift_y = np.arange(0, feat_height) * feat_stride\r\n shift_x, shift_y = np.meshgrid(shift_x, shift_y)\r\n shifts = torch.from_numpy(np.vstack((shift_x.ravel(), shift_y.ravel(),\r\n shift_x.ravel(), shift_y.ravel())).transpose())\r\n shifts = shifts.contiguous().type_as(feat).float()\r\n\r\n # num of anchors [3]\r\n A = anchors.size(0)\r\n K = shifts.size(0)\r\n\r\n anchors = anchors.type_as(gt_boxes)\r\n # all_anchors [K, A, 4]\r\n all_anchors = anchors.view(1, A, 4) + shifts.view(K, 1, 4)\r\n all_anchors = all_anchors.view(K * A, 4)\r\n # compute iou [all_anchors, gt_boxes]\r\n IOU_map = bbox_overlaps_batch(all_anchors, gt_boxes, img_size).view(batch_size, height, width, A, gt_boxes.shape[1])\r\n\r\n mask_batch = []\r\n for i in range(batch_size):\r\n max_iou, _ = torch.max(IOU_map[i].view(height * width * A, gt_boxes.shape[1]), dim=0)\r\n mask_per_im = torch.zeros([height, width], dtype=torch.int64).to(device)\r\n for k in range(gt_boxes.shape[1]):\r\n if torch.sum(gt_boxes[i][k]) == 0:\r\n break\r\n max_iou_per_gt = max_iou[k] * 0.5\r\n mask_per_gt = torch.sum(IOU_map[i][:, :, :, k] > max_iou_per_gt, dim=2)\r\n mask_per_im += mask_per_gt.to(device)\r\n mask_batch.append(mask_per_im)\r\n return mask_batch\r" }, { "identifier": "compute_mask_loss", "path": "utils/distill_utils.py", "snippet": "def compute_mask_loss(mask_batch, student_feature, teacher_feature, imitation_loss_weight):\r\n mask_list = []\r\n for mask in mask_batch:\r\n mask = (mask > 0).float().unsqueeze(0)\r\n mask_list.append(mask)\r\n mask_batch = torch.stack(mask_list, dim=0)\r\n norms = mask_batch.sum() * 2\r\n mask_batch_s = mask_batch.unsqueeze(4)\r\n no = student_feature.size(-1)\r\n bs, na, height, width, _ = mask_batch_s.shape\r\n mask_batch_no = mask_batch_s.expand((bs, na, height, width, no))\r\n sup_loss = (torch.pow(teacher_feature - student_feature, 2) * mask_batch_no).sum() / norms\r\n sup_loss = sup_loss * imitation_loss_weight\r\n return sup_loss\r" } ]
import argparse import logging import math import os import random import time import numpy as np import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.optim.lr_scheduler as lr_scheduler import torch.utils.data import yaml import test # import test.py to get mAP after each epoch from copy import deepcopy from pathlib import Path from threading import Thread from torch.cuda import amp from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from models.experimental import attempt_load from models.experimental import attempt_loadv5 from models.experimental import attempt_load_zxy from models.yolo import Model from utils.autoanchor import check_anchors from utils.datasets import create_dataloader from utils.general import labels_to_class_weights, increment_path, labels_to_image_weights, init_seeds, \ fitness, strip_optimizer, get_latest_run, check_dataset, check_file, check_git_status, check_img_size, \ check_requirements, print_mutation, set_logging, one_cycle, colorstr from utils.google_utils import attempt_download from utils.loss import ComputeLoss, ComputeLossOTA from utils.plots import plot_images, plot_labels, plot_results, plot_evolution from utils.torch_utils import ModelEMA, select_device, intersect_dicts, torch_distributed_zero_first, is_parallel from utils.wandb_logging.wandb_utils import WandbLogger, check_wandb_resume from utils.distill_utils import getMask, compute_mask_loss
20,371
names = ['item'] if opt.single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check # Model pretrained = weights.endswith('.pt') # load teacher model teacher = attempt_load_zxy(opt.teacher_weights, device=device) if pretrained: with torch_distributed_zero_first(rank): attempt_download(weights) # download if not found locally ckpt = torch.load(weights, map_location=device) # load checkpoint model = Model(opt.cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create exclude = ['anchor'] if (opt.cfg or hyp.get('anchors')) and not opt.resume else [] # exclude keys state_dict = ckpt['model'].float().state_dict() # to FP32 state_dict = intersect_dicts(state_dict, model.state_dict(), exclude=exclude) # intersect model.load_state_dict(state_dict, strict=False) # load logger.info('Transferred %g/%g items from %s' % (len(state_dict), len(model.state_dict()), weights)) # report else: model = Model(opt.cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create with torch_distributed_zero_first(rank): check_dataset(data_dict) # check train_path = data_dict['train'] test_path = data_dict['val'] # Freeze freeze = [f'model.{x}.' for x in (freeze if len(freeze) > 1 else range(freeze[0]))] # parameter names to freeze (full or partial) for k, v in model.named_parameters(): v.requires_grad = True # train all layers if any(x in k for x in freeze): print('freezing %s' % k) v.requires_grad = False # Optimizer nbs = 64 # nominal batch size accumulate = max(round(nbs / total_batch_size), 1) # accumulate loss before optimizing hyp['weight_decay'] *= total_batch_size * accumulate / nbs # scale weight_decay logger.info(f"Scaled weight_decay = {hyp['weight_decay']}") pg0, pg1, pg2 = [], [], [] # optimizer parameter groups for k, v in model.named_modules(): if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter): pg2.append(v.bias) # biases if isinstance(v, nn.BatchNorm2d): pg0.append(v.weight) # no decay elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter): pg1.append(v.weight) # apply decay if hasattr(v, 'im'): if hasattr(v.im, 'implicit'): pg0.append(v.im.implicit) else: for iv in v.im: pg0.append(iv.implicit) if hasattr(v, 'imc'): if hasattr(v.imc, 'implicit'): pg0.append(v.imc.implicit) else: for iv in v.imc: pg0.append(iv.implicit) if hasattr(v, 'imb'): if hasattr(v.imb, 'implicit'): pg0.append(v.imb.implicit) else: for iv in v.imb: pg0.append(iv.implicit) if hasattr(v, 'imo'): if hasattr(v.imo, 'implicit'): pg0.append(v.imo.implicit) else: for iv in v.imo: pg0.append(iv.implicit) if hasattr(v, 'ia'): if hasattr(v.ia, 'implicit'): pg0.append(v.ia.implicit) else: for iv in v.ia: pg0.append(iv.implicit) if hasattr(v, 'attn'): if hasattr(v.attn, 'logit_scale'): pg0.append(v.attn.logit_scale) if hasattr(v.attn, 'q_bias'): pg0.append(v.attn.q_bias) if hasattr(v.attn, 'v_bias'): pg0.append(v.attn.v_bias) if hasattr(v.attn, 'relative_position_bias_table'): pg0.append(v.attn.relative_position_bias_table) if hasattr(v, 'rbr_dense'): if hasattr(v.rbr_dense, 'weight_rbr_origin'): pg0.append(v.rbr_dense.weight_rbr_origin) if hasattr(v.rbr_dense, 'weight_rbr_avg_conv'): pg0.append(v.rbr_dense.weight_rbr_avg_conv) if hasattr(v.rbr_dense, 'weight_rbr_pfir_conv'): pg0.append(v.rbr_dense.weight_rbr_pfir_conv) if hasattr(v.rbr_dense, 'weight_rbr_1x1_kxk_idconv1'): pg0.append(v.rbr_dense.weight_rbr_1x1_kxk_idconv1) if hasattr(v.rbr_dense, 'weight_rbr_1x1_kxk_conv2'): pg0.append(v.rbr_dense.weight_rbr_1x1_kxk_conv2) if hasattr(v.rbr_dense, 'weight_rbr_gconv_dw'): pg0.append(v.rbr_dense.weight_rbr_gconv_dw) if hasattr(v.rbr_dense, 'weight_rbr_gconv_pw'): pg0.append(v.rbr_dense.weight_rbr_gconv_pw) if hasattr(v.rbr_dense, 'vector'): pg0.append(v.rbr_dense.vector) if opt.adam: optimizer = optim.Adam(pg0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum else: optimizer = optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True) optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']}) # add pg1 with weight_decay optimizer.add_param_group({'params': pg2}) # add pg2 (biases) logger.info('Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(pg2), len(pg1), len(pg0))) del pg0, pg1, pg2 # Scheduler https://arxiv.org/pdf/1812.01187.pdf # https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html#OneCycleLR if opt.linear_lr: lf = lambda x: (1 - x / (epochs - 1)) * (1.0 - hyp['lrf']) + hyp['lrf'] # linear else:
logger = logging.getLogger(__name__) def train(hyp, opt, device, tb_writer=None): logger.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items())) save_dir, epochs, batch_size, total_batch_size, weights, rank, freeze = \ Path(opt.save_dir), opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.global_rank, opt.freeze # Directories wdir = save_dir / 'weights' wdir.mkdir(parents=True, exist_ok=True) # make dir last = wdir / 'last.pt' best = wdir / 'best.pt' results_file = save_dir / 'results.txt' # Save run settings with open(save_dir / 'hyp.yaml', 'w') as f: yaml.dump(hyp, f, sort_keys=False) with open(save_dir / 'opt.yaml', 'w') as f: yaml.dump(vars(opt), f, sort_keys=False) # Configure plots = not opt.evolve # create plots cuda = device.type != 'cpu' init_seeds(2 + rank) with open(opt.data) as f: data_dict = yaml.load(f, Loader=yaml.SafeLoader) # data dict is_coco = opt.data.endswith('coco.yaml') # Logging- Doing this before checking the dataset. Might update data_dict loggers = {'wandb': None} # loggers dict if rank in [-1, 0]: opt.hyp = hyp # add hyperparameters run_id = torch.load(weights, map_location=device).get('wandb_id') if weights.endswith('.pt') and os.path.isfile( weights) else None wandb_logger = WandbLogger(opt, Path(opt.save_dir).stem, run_id, data_dict) loggers['wandb'] = wandb_logger.wandb data_dict = wandb_logger.data_dict if wandb_logger.wandb: weights, epochs, hyp = opt.weights, opt.epochs, opt.hyp # WandbLogger might update weights, epochs if resuming nc = 1 if opt.single_cls else int(data_dict['nc']) # number of classes names = ['item'] if opt.single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check # Model pretrained = weights.endswith('.pt') # load teacher model teacher = attempt_load_zxy(opt.teacher_weights, device=device) if pretrained: with torch_distributed_zero_first(rank): attempt_download(weights) # download if not found locally ckpt = torch.load(weights, map_location=device) # load checkpoint model = Model(opt.cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create exclude = ['anchor'] if (opt.cfg or hyp.get('anchors')) and not opt.resume else [] # exclude keys state_dict = ckpt['model'].float().state_dict() # to FP32 state_dict = intersect_dicts(state_dict, model.state_dict(), exclude=exclude) # intersect model.load_state_dict(state_dict, strict=False) # load logger.info('Transferred %g/%g items from %s' % (len(state_dict), len(model.state_dict()), weights)) # report else: model = Model(opt.cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create with torch_distributed_zero_first(rank): check_dataset(data_dict) # check train_path = data_dict['train'] test_path = data_dict['val'] # Freeze freeze = [f'model.{x}.' for x in (freeze if len(freeze) > 1 else range(freeze[0]))] # parameter names to freeze (full or partial) for k, v in model.named_parameters(): v.requires_grad = True # train all layers if any(x in k for x in freeze): print('freezing %s' % k) v.requires_grad = False # Optimizer nbs = 64 # nominal batch size accumulate = max(round(nbs / total_batch_size), 1) # accumulate loss before optimizing hyp['weight_decay'] *= total_batch_size * accumulate / nbs # scale weight_decay logger.info(f"Scaled weight_decay = {hyp['weight_decay']}") pg0, pg1, pg2 = [], [], [] # optimizer parameter groups for k, v in model.named_modules(): if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter): pg2.append(v.bias) # biases if isinstance(v, nn.BatchNorm2d): pg0.append(v.weight) # no decay elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter): pg1.append(v.weight) # apply decay if hasattr(v, 'im'): if hasattr(v.im, 'implicit'): pg0.append(v.im.implicit) else: for iv in v.im: pg0.append(iv.implicit) if hasattr(v, 'imc'): if hasattr(v.imc, 'implicit'): pg0.append(v.imc.implicit) else: for iv in v.imc: pg0.append(iv.implicit) if hasattr(v, 'imb'): if hasattr(v.imb, 'implicit'): pg0.append(v.imb.implicit) else: for iv in v.imb: pg0.append(iv.implicit) if hasattr(v, 'imo'): if hasattr(v.imo, 'implicit'): pg0.append(v.imo.implicit) else: for iv in v.imo: pg0.append(iv.implicit) if hasattr(v, 'ia'): if hasattr(v.ia, 'implicit'): pg0.append(v.ia.implicit) else: for iv in v.ia: pg0.append(iv.implicit) if hasattr(v, 'attn'): if hasattr(v.attn, 'logit_scale'): pg0.append(v.attn.logit_scale) if hasattr(v.attn, 'q_bias'): pg0.append(v.attn.q_bias) if hasattr(v.attn, 'v_bias'): pg0.append(v.attn.v_bias) if hasattr(v.attn, 'relative_position_bias_table'): pg0.append(v.attn.relative_position_bias_table) if hasattr(v, 'rbr_dense'): if hasattr(v.rbr_dense, 'weight_rbr_origin'): pg0.append(v.rbr_dense.weight_rbr_origin) if hasattr(v.rbr_dense, 'weight_rbr_avg_conv'): pg0.append(v.rbr_dense.weight_rbr_avg_conv) if hasattr(v.rbr_dense, 'weight_rbr_pfir_conv'): pg0.append(v.rbr_dense.weight_rbr_pfir_conv) if hasattr(v.rbr_dense, 'weight_rbr_1x1_kxk_idconv1'): pg0.append(v.rbr_dense.weight_rbr_1x1_kxk_idconv1) if hasattr(v.rbr_dense, 'weight_rbr_1x1_kxk_conv2'): pg0.append(v.rbr_dense.weight_rbr_1x1_kxk_conv2) if hasattr(v.rbr_dense, 'weight_rbr_gconv_dw'): pg0.append(v.rbr_dense.weight_rbr_gconv_dw) if hasattr(v.rbr_dense, 'weight_rbr_gconv_pw'): pg0.append(v.rbr_dense.weight_rbr_gconv_pw) if hasattr(v.rbr_dense, 'vector'): pg0.append(v.rbr_dense.vector) if opt.adam: optimizer = optim.Adam(pg0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum else: optimizer = optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True) optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']}) # add pg1 with weight_decay optimizer.add_param_group({'params': pg2}) # add pg2 (biases) logger.info('Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(pg2), len(pg1), len(pg0))) del pg0, pg1, pg2 # Scheduler https://arxiv.org/pdf/1812.01187.pdf # https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html#OneCycleLR if opt.linear_lr: lf = lambda x: (1 - x / (epochs - 1)) * (1.0 - hyp['lrf']) + hyp['lrf'] # linear else:
lf = one_cycle(1, hyp['lrf'], epochs) # cosine 1->hyp['lrf']
6
2023-10-08 13:05:58+00:00
24k
falesiani/torch_ga
tests/test_keras.py
[ { "identifier": "GeometricProductDense", "path": "torch_ga/layers.py", "snippet": "class GeometricProductDense(GeometricAlgebraLayer):\n \"\"\"Analagous to Keras' Dense layer but using multivector-valued matrices\n instead of scalar ones and geometric multiplication instead of standard\n multiplication.\n\n Args:\n algebra: GeometricAlgebra instance to use for the parameters\n blade_indices_kernel: Blade indices to use for the kernel parameter\n blade_indices_bias: Blade indices to use for the bias parameter (if used)\n \"\"\"\n\n def __init__(\n self,\n algebra: GeometricAlgebra,\n units: int,\n blade_indices_kernel: List[int],\n blade_indices_bias: Union[None, List[int]] = None,\n activation='None',\n use_bias=True,\n **kwargs\n ):\n super().__init__(algebra=algebra, **kwargs)\n\n self.units = units\n self.blade_indices_kernel = torch.tensor(blade_indices_kernel, dtype=torch.int64)\n if use_bias: self.blade_indices_bias = torch.tensor(blade_indices_bias, dtype=torch.int64)\n # self.blade_indices_kernel = blade_indices_kernel.to(dtype=torch.int64)\n # if use_bias: self.blade_indices_bias = blade_indices_bias.to(dtype=torch.int64) \n\n self.activation = activation\n self.use_bias = use_bias\n self.activation_fn = activations.get(activation)\n self.built = False\n\n def build(self, input_shape: list):\n if False: print(f\"input_shape={input_shape}\")\n self.num_input_units = input_shape[-2]\n shape_kernel = [\n self.units,\n self.num_input_units,\n int(self.blade_indices_kernel.shape[0])\n ]\n if False: print(f\"shape_kernel={shape_kernel}\")\n self.kernel = nn.Parameter(1./np.prod(shape_kernel)*torch.randn(size=shape_kernel)).to(dtype=torch.float)\n if self.use_bias:\n shape_bias = [self.units, self.blade_indices_bias.shape[0]]\n self.bias = nn.Parameter(1./np.prod(shape_bias)*torch.randn(size=shape_bias)).to(dtype=torch.float)\n else:\n self.bias = None\n self.built = True\n\n def compute_output_shape(self, input_shape):\n return [*input_shape[:-2], self.units, self.algebra.num_blades]\n\n def forward(self, inputs):\n if not self.built: self.build(inputs.shape)\n w_geom = self.algebra.from_tensor(self.kernel, self.blade_indices_kernel)\n\n # Perform a matrix-multiply, but using geometric product instead of\n # standard multiplication. To do this we do the geometric product\n # elementwise and then sum over the common axis.\n # [..., 1, I, X] * [..., O, I, X] -> [..., O, I, X] -> [..., O, X]\n # inputs_expanded = tf.expand_dims(inputs, axis=inputs.shape.ndims - 2)\n # result = tf.reduce_sum(self.algebra.geom_prod(\n # inputs_expanded, w_geom), axis=-2)\n\n inputs_expanded = inputs.unsqueeze(len(inputs.shape) - 2)\n result = self.algebra.geom_prod(inputs_expanded, w_geom).sum(dim=-2)\n if self.bias is not None:\n b_geom = self.algebra.from_tensor(self.bias, self.blade_indices_bias)\n result += b_geom\n if self.activation_fn:\n result = self.activation_fn(result)\n return result\n\n def get_config(self):\n config = super().get_config()\n config.update({\n \"blade_indices_kernel\":\n self.blade_indices_kernel.cpu().detach().numpy(),\n \"blade_indices_bias\":\n self.blade_indices_bias.cpu().detach().numpy(),\n \"units\":\n self.units,\n # \"activation\":\n # activations.serialize(self.activation),\n \"use_bias\":\n self.use_bias,\n })\n return config" }, { "identifier": "GeometricSandwichProductDense", "path": "torch_ga/layers.py", "snippet": "class GeometricSandwichProductDense(GeometricProductDense):\n \"\"\"Analagous to Keras' Dense layer but using multivector-valued matrices\n instead of scalar ones and geometric sandwich multiplication instead of\n standard multiplication.\n\n Args:\n algebra: GeometricAlgebra instance to use for the parameters\n blade_indices_kernel: Blade indices to use for the kernel parameter\n blade_indices_bias: Blade indices to use for the bias parameter (if used)\n \"\"\"\n\n def __init__(\n self, algebra, units, blade_indices_kernel, blade_indices_bias=None,\n activation=None, use_bias=True, \n # kernel_initializer=\"glorot_uniform\",\n # bias_initializer=\"zeros\", kernel_regularizer=None,\n # bias_regularizer=None, activity_regularizer=None,\n # kernel_constraint=None, bias_constraint=None, \n **kwargs\n ):\n super().__init__(\n algebra, units,\n blade_indices_kernel,\n blade_indices_bias=blade_indices_bias,\n activation=activation,\n use_bias=use_bias,\n # kernel_initializer=kernel_initializer,\n # bias_initializer=bias_initializer,\n # kernel_regularizer=kernel_regularizer,\n # bias_regularizer=bias_regularizer,\n # activity_regularizer=activity_regularizer,\n # kernel_constraint=kernel_constraint,\n # bias_constraint=bias_constraint, \n **kwargs\n )\n self.built = False\n\n def forward(self, inputs):\n if not self.built: self.build(inputs.shape)\n w_geom = self.algebra.from_tensor(self.kernel, self.blade_indices_kernel)\n\n # Same as GeometricProductDense but using R*x*~R instead of just R*x\n # inputs_expanded = tf.expand_dims(inputs, axis=inputs.shape.ndims - 2)\n # result = tf.reduce_sum(\n # self.algebra.geom_prod(\n # w_geom,\n # self.algebra.geom_prod(\n # inputs_expanded,\n # self.algebra.reversion(w_geom)\n # )\n # ),\n # axis=-2\n # )\n # if self.bias is not None:\n # b_geom = self.algebra.from_tensor(\n # self.bias, self.blade_indices_bias)\n # result += b_geom\n\n # return self.activation(result)\n\n inputs_expanded = inputs.unsqueeze(len(inputs.shape) - 2)\n result = self.algebra.geom_prod( w_geom, self.algebra.geom_prod(inputs_expanded, self.algebra.reversion(w_geom))).sum(dim=-2)\n if self.bias is not None:\n b_geom = self.algebra.from_tensor(self.bias, self.blade_indices_bias)\n result += b_geom\n if self.activation_fn:\n result = self.activation_fn(result)\n return result" }, { "identifier": "GeometricProductElementwise", "path": "torch_ga/layers.py", "snippet": "class GeometricProductElementwise(GeometricAlgebraLayer):\n \"\"\"Performs the elementwise geometric product with a list of multivectors\n with as many elements as there are input units.\n\n Args:\n algebra: GeometricAlgebra instance to use for the parameters\n blade_indices_kernel: Blade indices to use for the kernel parameter\n blade_indices_bias: Blade indices to use for the bias parameter (if used)\n \"\"\"\n\n def __init__(\n self,\n algebra: GeometricAlgebra,\n blade_indices_kernel: List[int],\n blade_indices_bias: Union[None, List[int]] = None,\n activation=None,\n use_bias=True,\n # kernel_initializer=\"glorot_uniform\",\n # bias_initializer=\"zeros\",\n # kernel_regularizer=None,\n # bias_regularizer=None,\n # activity_regularizer=None,\n # kernel_constraint=None,\n # bias_constraint=None,\n **kwargs\n ):\n # super().__init__(algebra=algebra, activity_regularizer=activity_regularizer, **kwargs)\n super().__init__(algebra=algebra, **kwargs)\n\n self.blade_indices_kernel = torch.tensor(blade_indices_kernel, dtype=torch.int64)\n if use_bias:\n self.blade_indices_bias = torch.tensor(blade_indices_bias, dtype=torch.int64)\n \n # self.blade_indices_kernel = blade_indices_kernel.to(dtype=torch.int64)\n # if use_bias:\n # self.blade_indices_bias = blade_indices_bias.to(dtype=torch.int64)\n\n self.activation_fn = activations.get(activation)\n self.use_bias = use_bias\n # self.kernel_initializer = initializers.get(kernel_initializer)\n # self.bias_initializer = initializers.get(bias_initializer)\n # self.kernel_regularizer = regularizers.get(kernel_regularizer)\n # self.bias_regularizer = regularizers.get(bias_regularizer)\n # self.kernel_constraint = constraints.get(kernel_constraint)\n # self.bias_constraint = constraints.get(bias_constraint)\n self.built = False\n\n def build(self, input_shape: torch.Size):\n self.num_input_units = input_shape[-2]\n shape_kernel = [\n self.num_input_units,\n self.blade_indices_kernel.shape[0]\n ]\n self.kernel = nn.Parameter(1./np.prod(shape_kernel)*torch.randn(shape_kernel)).to(dtype=torch.float)\n if self.use_bias:\n shape_bias = [self.num_input_units,self.blade_indices_bias.shape[0]]\n self.bias = nn.Parameter(1./np.prod(shape_bias)*torch.randn(shape_bias)).to(dtype=torch.float)\n else:\n self.bias = None\n\n # self.kernel = self.add_weight(\n # \"kernel\",\n # shape=shape_kernel,\n # initializer=self.kernel_initializer,\n # regularizer=self.kernel_regularizer,\n # constraint=self.kernel_constraint,\n # dtype=self.dtype,\n # trainable=True\n # )\n # if self.use_bias:\n # shape_bias = [self.num_input_units,\n # self.blade_indices_bias.shape[0]]\n # self.bias = self.add_weight(\n # \"bias\",\n # shape=shape_bias,\n # initializer=self.bias_initializer,\n # regularizer=self.bias_regularizer,\n # constraint=self.bias_constraint,\n # dtype=self.dtype,\n # trainable=True\n # )\n # else:\n # self.bias = None\n self.built = True\n\n def compute_output_shape(self, input_shape):\n return torch.Size([*input_shape[:-1], self.algebra.num_blades])\n\n def forward(self, inputs):\n if not self.built: self.build(inputs.shape)\n w_geom = self.algebra.from_tensor(\n self.kernel, self.blade_indices_kernel)\n\n # Elementwise multiplication for each unit with a multivector.\n # [..., U, X] * [U, X] -> [..., U, X]\n result = self.algebra.geom_prod(inputs, w_geom)\n\n if self.bias is not None:\n b_geom = self.algebra.from_tensor(\n self.bias, self.blade_indices_bias)\n result += b_geom\n\n if self.activation_fn:\n result = self.activation_fn(result)\n return result\n\n def get_config(self):\n config = super().get_config()\n config.update({\n \"blade_indices_kernel\":\n self.blade_indices_kernel.cpu().detach().numpy(),\n \"blade_indices_bias\":\n self.blade_indices_bias.cpu().detach().numpy(),\n # \"activation\":\n # self.activation,\n # activations.serialize(self.activation),\n \"use_bias\":\n self.use_bias,\n # \"kernel_initializer\":\n # initializers.serialize(self.kernel_initializer),\n # \"bias_initializer\":\n # initializers.serialize(self.bias_initializer),\n # \"kernel_regularizer\":\n # regularizers.serialize(self.kernel_regularizer),\n # \"bias_regularizer\":\n # regularizers.serialize(self.bias_regularizer),\n # \"activity_regularizer\":\n # regularizers.serialize(self.activity_regularizer),\n # \"kernel_constraint\":\n # constraints.serialize(self.kernel_constraint),\n # \"bias_constraint\":\n # constraints.serialize(self.bias_constraint)\n })\n return config" }, { "identifier": "GeometricSandwichProductElementwise", "path": "torch_ga/layers.py", "snippet": "class GeometricSandwichProductElementwise(GeometricProductElementwise):\n \"\"\"Performs the elementwise geometric sandwich product with a list of\n multivectors with as many elements as there are input units.\n\n Args:\n algebra: GeometricAlgebra instance to use for the parameters\n blade_indices_kernel: Blade indices to use for the kernel parameter\n blade_indices_bias: Blade indices to use for the bias parameter (if used)\n \"\"\"\n\n def __init__(\n self, algebra, blade_indices_kernel, blade_indices_bias=None,\n activation=None, use_bias=True, \n # kernel_initializer=\"glorot_uniform\",\n # bias_initializer=\"zeros\", kernel_regularizer=None,\n # bias_regularizer=None, activity_regularizer=None,\n # kernel_constraint=None, bias_constraint=None, \n **kwargs\n ):\n super().__init__(\n algebra,\n blade_indices_kernel,\n blade_indices_bias=blade_indices_bias,\n activation=activation,\n use_bias=use_bias,\n # kernel_initializer=kernel_initializer,\n # bias_initializer=bias_initializer,\n # kernel_regularizer=kernel_regularizer,\n # bias_regularizer=bias_regularizer,\n # activity_regularizer=activity_regularizer,\n # kernel_constraint=kernel_constraint,\n # bias_constraint=bias_constraint, \n **kwargs\n )\n\n def forward(self, inputs):\n if not self.built: self.build(inputs.shape)\n w_geom = self.algebra.from_tensor( self.kernel, self.blade_indices_kernel)\n\n # Elementwise multiplication Rx~R for each unit with a multivector.\n # [..., U, X] * [U, X] -> [..., U, X]\n result = self.algebra.geom_prod(\n w_geom,\n self.algebra.geom_prod(\n inputs,\n self.algebra.reversion(w_geom)\n )\n )\n\n if self.bias is not None:\n b_geom = self.algebra.from_tensor(\n self.bias, self.blade_indices_bias)\n result += b_geom\n\n if self.activation_fn:\n result = self.activation_fn(result)\n return result" }, { "identifier": "GeometricProductConv1D", "path": "torch_ga/layers.py", "snippet": "class GeometricProductConv1D(GeometricAlgebraLayer):\n \"\"\"Analagous to Keras' Conv1D layer but using multivector-valued kernels\n instead of scalar ones and geometric product instead of\n standard multiplication.\n\n Args:\n algebra: GeometricAlgebra instance to use for the parameters\n filters: How many channels the output will have\n kernel_size: Size for the convolution kernel\n stride: Stride to use for the convolution\n padding: \"SAME\" (zero-pad input length so output\n length == input length / stride) or \"VALID\" (no padding)\n blade_indices_kernel: Blade indices to use for the kernel parameter\n blade_indices_bias: Blade indices to use for the bias parameter (if used)\n \"\"\"\n\n def __init__(\n self,\n algebra: GeometricAlgebra,\n filters: int,\n kernel_size: int,\n stride: int,\n padding: str,\n blade_indices_kernel: List[int],\n blade_indices_bias: Union[None, List[int]] = None,\n dilations: Union[None, int] = None,\n activation=None,\n use_bias=True,\n # kernel_initializer=\"glorot_uniform\",\n # bias_initializer=\"zeros\",\n # kernel_regularizer=None,\n # bias_regularizer=None,\n # activity_regularizer=None,\n # kernel_constraint=None,\n # bias_constraint=None,\n **kwargs\n ):\n super().__init__(\n algebra=algebra,\n # activity_regularizer=activity_regularizer,\n **kwargs\n )\n\n self.filters = filters\n self.kernel_size = kernel_size\n self.stride = stride\n self.padding = padding\n self.dilations = dilations\n\n self.blade_indices_kernel = torch.tensor( blade_indices_kernel, dtype=torch.int64)\n if use_bias:\n self.blade_indices_bias = torch.tensor( blade_indices_bias, dtype=torch.int64)\n # self.blade_indices_kernel = blade_indices_kernel.to(dtype=torch.int64)\n # if use_bias:\n # self.blade_indices_bias = blade_indices_bias.to(dtype=torch.int64)\n\n self.activation_fn = activations.get(activation)\n self.use_bias = use_bias\n # self.kernel_initializer = initializers.get(kernel_initializer)\n # self.bias_initializer = initializers.get(bias_initializer)\n # self.kernel_regularizer = regularizers.get(kernel_regularizer)\n # self.bias_regularizer = regularizers.get(bias_regularizer)\n # self.kernel_constraint = constraints.get(kernel_constraint)\n # self.bias_constraint = constraints.get(bias_constraint)\n self.built = False\n\n def build(self, input_shape: torch.Size):\n # I: [..., S, C, B]\n self.num_input_filters = input_shape[-2]\n\n # K: [K, IC, OC, B]\n shape_kernel = [\n self.kernel_size,\n self.num_input_filters,\n self.filters,\n self.blade_indices_kernel.shape[0]\n ]\n self.kernel = nn.Parameter(1./np.prod(shape_kernel)*torch.randn(size=shape_kernel)).to(dtype=torch.float)\n if self.use_bias:\n shape_bias = [self.filters, self.blade_indices_bias.shape[0]]\n self.bias = nn.Parameter(1./np.prod(shape_bias)*torch.randn(size=shape_bias)).to(dtype=torch.float)\n else:\n self.bias = None\n\n # self.kernel = self.add_weight(\n # \"kernel\",\n # shape=shape_kernel,\n # initializer=self.kernel_initializer,\n # regularizer=self.kernel_regularizer,\n # constraint=self.kernel_constraint,\n # dtype=self.dtype,\n # trainable=True\n # )\n # if self.use_bias:\n # shape_bias = [self.filters, self.blade_indices_bias.shape[0]]\n # self.bias = self.add_weight(\n # \"bias\",\n # shape=shape_bias,\n # initializer=self.bias_initializer,\n # regularizer=self.bias_regularizer,\n # constraint=self.bias_constraint,\n # dtype=self.dtype,\n # trainable=True\n # )\n # else:\n # self.bias = None\n self.built = True\n\n def forward(self, inputs):\n if not self.built: \n self.build(inputs.shape)\n k_geom = self.algebra.from_tensor(\n self.kernel, self.blade_indices_kernel)\n\n result = self.algebra.geom_conv1d(\n inputs, k_geom,\n stride=self.stride, padding=self.padding,\n dilations=self.dilations\n )\n\n if self.bias is not None:\n b_geom = self.algebra.from_tensor(\n self.bias, self.blade_indices_bias)\n result += b_geom\n\n if self.activation_fn:\n result = self.activation_fn(result)\n return result\n\n def get_config(self):\n config = super().get_config()\n config.update({\n \"filters\":\n self.filters,\n \"kernel_size\":\n self.kernel_size,\n \"stride\":\n self.stride,\n \"padding\":\n self.padding,\n \"dilations\":\n self.dilations,\n \"blade_indices_kernel\":\n self.blade_indices_kernel.numpy(),\n \"blade_indices_bias\":\n self.blade_indices_bias.numpy(),\n # \"activation\":\n # activations.serialize(self.activation),\n \"use_bias\":\n self.use_bias,\n # \"kernel_initializer\":\n # initializers.serialize(self.kernel_initializer),\n # \"bias_initializer\":\n # initializers.serialize(self.bias_initializer),\n # \"kernel_regularizer\":\n # regularizers.serialize(self.kernel_regularizer),\n # \"bias_regularizer\":\n # regularizers.serialize(self.bias_regularizer),\n # \"activity_regularizer\":\n # regularizers.serialize(self.activity_regularizer),\n # \"kernel_constraint\":\n # constraints.serialize(self.kernel_constraint),\n # \"bias_constraint\":\n # constraints.serialize(self.bias_constraint)\n\n })\n\n return config" }, { "identifier": "GeometricAlgebraExp", "path": "torch_ga/layers.py", "snippet": "class GeometricAlgebraExp(GeometricAlgebraLayer):\n \"\"\"Calculates the exponential function of the input. Input must square to\n a scalar.\n\n Args:\n algebra: GeometricAlgebra instance to use\n square_scalar_tolerance: Tolerance to use for the square scalar check\n or None if the check should be skipped\n \"\"\"\n\n def __init__(\n self,\n algebra: GeometricAlgebra,\n square_scalar_tolerance: Union[float, None] = 1e-4,\n **kwargs\n ):\n super().__init__(algebra=algebra, **kwargs)\n self.square_scalar_tolerance = square_scalar_tolerance\n self.built = False\n\n def compute_output_shape(self, input_shape):\n return torch.Size([*input_shape[:-1], self.algebra.num_blades])\n\n def build(self,inputs_shape): self.built = True\n\n def forward(self, inputs):\n if not self.built: self.build(inputs.shape)\n return self.algebra.exp(\n inputs, square_scalar_tolerance=self.square_scalar_tolerance\n )\n\n def get_config(self):\n config = super().get_config()\n config.update({\n \"square_scalar_tolerance\": self.square_scalar_tolerance\n })\n return config" }, { "identifier": "GeometricToTensor", "path": "torch_ga/layers.py", "snippet": "class GeometricToTensor(GeometricAlgebraLayer):\n \"\"\"Layer for extracting given blades from geometric algebra tensors.\n\n Args:\n algebra: GeometricAlgebra instance to use\n blade_indices: blade indices to extract\n \"\"\"\n\n def __init__(self, algebra: GeometricAlgebra, blade_indices: List[int],\n **kwargs):\n super().__init__(algebra=algebra, **kwargs)\n self.blade_indices = torch.tensor(blade_indices).to(dtype=torch.int64)\n # self.blade_indices = blade_indices.to(dtype=torch.int64) \n self.built = False\n\n def compute_output_shape(self, input_shape):\n return [*input_shape[:-1], self.blade_indices.shape[0]]\n def build(self,input_shape): self.built = True\n\n def forward(self, inputs):\n if not self.build: self.build(inputs.shape)\n # return torch.select(inputs, self.blade_indices, axis=-1)\n x = inputs[...,self.blade_indices]\n return x\n\n def get_config(self):\n config = super().get_config()\n config.update({\n \"blade_indices\": self.blade_indices.numpy()\n })\n return config" }, { "identifier": "GeometricToTensorWithKind", "path": "torch_ga/layers.py", "snippet": "class GeometricToTensorWithKind(GeometricToTensor):\n \"\"\"Layer for extracting blades of a kind from geometric algebra tensors.\n\n Args:\n algebra: GeometricAlgebra instance to use\n kind: blade indices of kind to extract\n \"\"\"\n\n def __init__(self, algebra: GeometricAlgebra, kind: BladeKind,\n **kwargs):\n blade_indices = algebra.get_kind_blade_indices(kind)\n super().__init__(algebra=algebra, blade_indices=blade_indices,\n **kwargs)" }, { "identifier": "TensorToGeometric", "path": "torch_ga/layers.py", "snippet": "class TensorToGeometric(GeometricAlgebraLayer):\n \"\"\"Layer for converting tensors with given blade indices to\n geometric algebra tensors.\n\n Args:\n algebra: GeometricAlgebra instance to use\n blade_indices: blade indices to interpret the last axis of the\n input tensor as\n \"\"\"\n\n def __init__(self, algebra: GeometricAlgebra, blade_indices: List[int],\n **kwargs):\n super().__init__(algebra=algebra, **kwargs)\n\n self.blade_indices = torch.tensor(blade_indices, dtype=torch.int64)\n # self.blade_indices = blade_indices.to(dtype=torch.int64) \n self.built = False\n\n def compute_output_shape(self, input_shape):\n return [*input_shape[:-1], self.algebra.num_blades]\n\n def forward(self, inputs):\n if not self.build: self.build(inputs.shape)\n return self.algebra.from_tensor(inputs, blade_indices=self.blade_indices)\n def build(self,input_shape): self.built = True\n def get_config(self):\n config = super().get_config()\n config.update({\n \"blade_indices\": self.blade_indices.numpy()\n })\n return config" }, { "identifier": "TensorWithKindToGeometric", "path": "torch_ga/layers.py", "snippet": "class TensorWithKindToGeometric(GeometricAlgebraLayer):\n \"\"\"Layer for converting tensors with given blade kind to\n geometric algebra tensors.\n\n Args:\n algebra: GeometricAlgebra instance to use\n kind: blade kind indices to interpret the last axis of the\n input tensor as\n \"\"\"\n\n def __init__(self, algebra: GeometricAlgebra, kind: BladeKind,\n **kwargs):\n super().__init__(algebra=algebra, **kwargs)\n self.kind = kind\n self.built = False\n\n def compute_output_shape(self, input_shape):\n return [*input_shape[:-1], self.algebra.get_kind_blade_indices(self.kind).shape[0]]\n\n def build(self,input_shape): self.built = True\n def forward(self, inputs):\n if not self.build: self.build(inputs.shape)\n\n return self.algebra.from_tensor_with_kind(inputs, kind=self.kind)\n\n def get_config(self):\n config = super().get_config()\n config.update({\n \"kind\": self.kind\n })\n return config" }, { "identifier": "BladeKind", "path": "torch_ga/blades.py", "snippet": "class BladeKind(Enum):\n \"\"\"Kind of blade depending on its degree.\"\"\"\n MV = \"mv\"\n EVEN = \"even\"\n ODD = \"odd\"\n SCALAR = \"scalar\"\n VECTOR = \"vector\"\n BIVECTOR = \"bivector\"\n TRIVECTOR = \"trivector\"\n PSEUDOSCALAR = \"pseudoscalar\"\n PSEUDOVECTOR = \"pseudovector\"\n PSEUDOBIVECTOR = \"pseudobivector\"\n PSEUDOTRIVECTOR = \"pseudotrivector\"" }, { "identifier": "GeometricAlgebra", "path": "torch_ga/torch_ga.py", "snippet": "class GeometricAlgebra:\n \"\"\"Class used for performing geometric algebra operations on `torch.Tensor` instances.\n Exposes methods for operating on `torch.Tensor` instances where their last\n axis is interpreted as blades of the algebra.\n Holds the metric and other quantities derived from it.\n \"\"\"\n\n def __init__(self, metric: List[float]):\n \"\"\"Creates a GeometricAlgebra object given a metric.\n The algebra will have as many basis vectors as there are\n elements in the metric.\n\n Args:\n metric: Metric as a list. Specifies what basis vectors square to\n \"\"\"\n self._metric = torch.tensor(metric, dtype=torch.float32)\n\n self._num_bases = len(metric)\n self._bases = list(map(str, range(self._num_bases)))\n\n self._blades, self._blade_degrees = blades_from_bases(self._bases)\n self._blade_degrees = torch.tensor(self._blade_degrees)\n self._num_blades = len(self._blades)\n self._max_degree = self._blade_degrees.max()\n\n # [Blades, Blades, Blades]\n _list = get_cayley_tensor(self.metric, self._bases, self._blades)\n # print(_list)\n if type(_list) in [list,tuple]:\n _list = np.array(_list)\n self._cayley, self._cayley_inner, self._cayley_outer = torch.tensor(\n _list,\n dtype=torch.float32\n )\n\n self._blade_mvs = torch.eye(self._num_blades)\n self._basis_mvs = self._blade_mvs[1:1+self._num_bases]\n\n # Find the dual by looking at the anti-diagonal in the Cayley tensor.\n self._dual_blade_indices = []\n self._dual_blade_signs = []\n\n for blade_index in range(self._num_blades):\n dual_index = self.num_blades - blade_index - 1\n anti_diag = self._cayley[blade_index, dual_index]\n # dual_sign = tf.gather(anti_diag, tf.where(\n # anti_diag != 0.0)[..., 0])[..., 0]\n dual_sign = anti_diag[torch.where(anti_diag != 0.0)]\n\n self._dual_blade_indices.append(dual_index)\n self._dual_blade_signs.append(dual_sign)\n\n self._dual_blade_indices = torch.tensor(\n self._dual_blade_indices, dtype=torch.int64)\n self._dual_blade_signs = torch.tensor(\n self._dual_blade_signs, dtype=torch.float32)\n\n def print(self, *args, **kwargs):\n \"\"\"Same as the default `print` function but formats `torch.Tensor`\n instances that have as many elements on their last axis\n as the algebra has blades using `mv_repr()`.\n \"\"\"\n def _is_mv(arg):\n return isinstance(arg, torch.Tensor) and len(arg.shape) > 0 and arg.shape[-1] == self.num_blades\n new_args = [self.mv_repr(arg) if _is_mv(arg) else arg for arg in args]\n\n print(*new_args, **kwargs)\n\n @property\n def metric(self) -> torch.Tensor:\n \"\"\"Metric list which contains the number that each\n basis vector in the algebra squares to\n (ie. the diagonal of the metric tensor).\n \"\"\"\n return self._metric\n\n @property\n def cayley(self) -> torch.Tensor:\n \"\"\"`MxMxM` tensor where `M` is the number of basis\n blades in the algebra. Used for calculating the\n geometric product:\n\n `a_i, b_j, cayley_ijk -> c_k`\n \"\"\"\n return self._cayley\n\n @property\n def cayley_inner(self) -> torch.Tensor:\n \"\"\"Analagous to cayley but for inner product.\"\"\"\n return self._cayley_inner\n\n @property\n def cayley_outer(self) -> torch.Tensor:\n \"\"\"Analagous to cayley but for outer product.\"\"\"\n return self._cayley_outer\n\n @property\n def blades(self) -> List[str]:\n \"\"\"List of all blade names.\n\n Blades are all possible independent combinations of\n basis vectors. Basis vectors are named starting\n from `\"0\"` and counting up. The scalar blade is the\n empty string `\"\"`.\n\n Example\n - Bases: `[\"0\", \"1\", \"2\"]`\n - Blades: `[\"\", \"0\", \"1\", \"2\", \"01\", \"02\", \"12\", \"012\"]`\n \"\"\"\n return self._blades\n\n @property\n def blade_mvs(self) -> torch.Tensor:\n \"\"\"List of all blade tensors in the algebra.\"\"\"\n return self._blade_mvs\n\n @property\n def dual_blade_indices(self) -> torch.Tensor:\n \"\"\"Indices of the dual blades for each blade.\"\"\"\n return self._dual_blade_indices\n\n @property\n def dual_blade_signs(self) -> torch.Tensor:\n \"\"\"Signs of the dual blades for each blade.\"\"\"\n return self._dual_blade_signs\n\n @property\n def num_blades(self) -> int:\n \"\"\"Total number of blades in the algebra.\"\"\"\n return self._num_blades\n\n @property\n def blade_degrees(self) -> torch.Tensor:\n \"\"\"List of blade-degree for each blade in the algebra.\"\"\"\n return self._blade_degrees\n\n @property\n def max_degree(self) -> int:\n \"\"\"Highest blade degree in the algebra.\"\"\"\n return self._max_degree\n\n @property\n def basis_mvs(self) -> torch.Tensor:\n \"\"\"List of basis vectors as torch.Tensor.\"\"\"\n return self._basis_mvs\n\n def get_kind_blade_indices(self, kind: BladeKind, invert: bool = False) -> torch.Tensor:\n \"\"\"Find all indices of blades of a given kind in the algebra.\n\n Args:\n kind: kind of blade to give indices for\n invert: whether to return all blades not of the kind\n\n Returns:\n indices of blades of a given kind in the algebra\n \"\"\"\n return get_blade_of_kind_indices(self.blade_degrees, kind, self.max_degree, invert=invert)\n\n def get_blade_indices_of_degree(self, degree: int) -> torch.Tensor:\n \"\"\"Find all indices of blades of the given degree.\n\n Args:\n degree: degree to return blades for\n\n Returns:\n indices of blades with the given degree in the algebra\n \"\"\"\n # return tf.gather(tf.range(self.num_blades), tf.where(self.blade_degrees == degree)[..., 0])\n return torch.range(self.num_blades)[torch.where(self.blade_degrees == degree)[..., 0]]\n\n def is_pure(self, tensor: torch.Tensor, blade_indices: torch.Tensor) -> bool:\n \"\"\"Returns whether the given tensor is purely of the given blades\n and has no non-zero values for blades not in the given blades.\n\n Args:\n tensor: tensor to check purity for\n blade_indices: blade indices to check purity for\n\n Returns:\n Whether the tensor is purely of the given blades\n and has no non-zero values for blades not in the given blades\n \"\"\"\n # tensor = torch.tensor(tensor, dtype=torch.float32)\n tensor = tensor.to(dtype=torch.float32)\n if not type(blade_indices) in [torch.Tensor]:\n blade_indices = torch.tensor(blade_indices)\n \n blade_indices = blade_indices.to(dtype=torch.int64)\n\n # blade_indices = torch.tensor(\n # blade_indices, dtype=torch.int64)\n\n inverted_blade_indices = invert_blade_indices(\n self.num_blades, blade_indices)\n\n # return tf.reduce_all(tf.gather(\n # tensor,\n # inverted_blade_indices,\n # axis=-1\n # ) == 0)\n return (tensor[inverted_blade_indices]==0).sum(dim=-1)\n\n def is_pure_kind(self, tensor: torch.Tensor, kind: BladeKind) -> bool:\n \"\"\"Returns whether the given tensor is purely of a given kind\n and has no non-zero values for blades not of the kind.\n\n Args:\n tensor: tensor to check purity for\n kind: kind of blade to check purity for\n\n Returns:\n Whether the tensor is purely of a given kind\n and has no non-zero values for blades not of the kind\n \"\"\"\n # tensor = torch.tensor(tensor, dtype=torch.float32)\n tensor = tensor.to(dtype=torch.float32)\n inverted_kind_indices = self.get_kind_blade_indices(kind, invert=True)\n # print(f\"tensor={tensor}\")\n # print(f\"kind={kind}\")\n # print(f\"inverted_kind_indices={inverted_kind_indices.T}\")\n # print(f\"inverted_kind_indices.shape={inverted_kind_indices.shape}\")\n # print(f\"tensor[inverted_kind_indices]={tensor[inverted_kind_indices].T}\")\n # print(f\"tensor[inverted_kind_indices].shape={tensor[inverted_kind_indices].shape}\")\n # print(f\"tensor[inverted_kind_indices]==0={tensor[inverted_kind_indices].T==0}\")\n\n # return tf.reduce_all(tf.gather(\n # tensor,\n # inverted_kind_indices,\n # axis=-1\n # ) == 0)\n return (tensor[inverted_kind_indices]==0).sum(dim=-1)\n\n # def from_tensor(self, tensor: torch.Tensor, blade_indices: torch.Tensor) -> torch.Tensor:\n # \"\"\"Creates a geometric algebra torch.Tensor from a torch.Tensor and blade\n # indices. The blade indices have to align with the last axis of the\n # tensor.\n\n # Args:\n # tensor: torch.Tensor to take as values for the geometric algebra tensor\n # blade_indices: Blade indices corresponding to the tensor. Can\n # be obtained from blade names eg. using get_kind_blade_indices()\n # or as indices from the blades list property.\n\n # Returns:\n # Geometric algebra torch.Tensor from tensor and blade indices\n # \"\"\"\n # blade_indices = torch.tensor(blade_indices, dtype=torch.int64).to(dtype=torch.int64)\n # tensor = torch.tensor(tensor, dtype=torch.float32)\n # # print(f\"blade_indices={blade_indices}\")\n # # print(f\"tensor={tensor}\")\n \n # _shape = tensor.shape\n # is_scalar = False\n # if len(_shape)==1 :\n # _shape_final = [1]+ [self.num_blades] \n # is_scalar = True\n # else:\n # _shape_final = list(_shape[:-1]) + [self.num_blades] \n # b = torch.zeros(_shape_final)\n \n\n # # i = blade_indices.view([-1,1])\n # # v = tensor.flatten().view([-1,1])\n # i = blade_indices.nonzero().flatten()\n # v = tensor.flatten().unsqueeze(1)\n # b = b.view([-1,self.num_blades])\n # # b[:,i] = v\n # try:\n # b[:,i] = v\n # except:\n # print(f\"_shape={_shape},_shape_final={_shape_final}\")\n # print(f\"i.shape={i.shape},v.shape={v.shape},b.shape={b.shape}\")\n # print(f\"i={i},v={v},b={b}\")\n # raise\n # # raise \"whatever\"\n # b = b.reshape(_shape_final)\n\n # # _shape_tmp = list(v.shape) + [self.num_blades] \n # # print(f\"i,v,_shape_tmp,_shape_final={i},{v},{_shape_tmp},{_shape_final},i.shape={i.shape}\")\n # # b = torch.sparse_coo_tensor(i, v, size=_shape_tmp)\n # # print(f\"b={b}\")\n # # b = torch.sparse_coo_tensor(i, v, size=_shape_tmp).to_dense()\n # # b = b.reshape(_shape_final)\n # if is_scalar:\n # b=b.unsqueeze(0)\n # return b\n\n # # # Put last axis on first axis so scatter_nd becomes easier.\n # # # Later undo the transposition again.\n # # # t = tf.concat([[tensor.shape.ndims - 1],\n # # # tf.range(0, tensor.shape.ndims - 1)], axis=0)\n # # # t_inv = tf.concat([tf.range(1, tensor.shape.ndims), [0]], axis=0)\n\n # # # tensor = tf.transpose(tensor, t)\n\n # # # shape = tf.concat([\n # # # torch.tensor([self.num_blades], dtype=torch.int64),\n # # # tf.shape(tensor, torch.int64)[1:]\n # # # ], axis=0)\n\n # # # tensor = tf.scatter_nd(\n # # # tf.expand_dims(blade_indices, axis=-1),\n # # # tensor,\n # # # shape\n # # # )\n\n # # # return tf.transpose(tensor, t_inv)\n # # # t = torch.concat([torch.tensor([len(tensor.shape) - 1]), torch.range(0, len(tensor.shape)- 1)], axis=0)\n # # # t_inv = torch.concat([torch.range(1, len(tensor.shape)), torch.tensor([0])], axis=0)\n # # t = [len(tensor.shape) - 1] + list(range(0, len(tensor.shape)- 1))\n # # t_inv = list(range(1, len(tensor.shape))) + [0]\n\n # # tensor = torch.permute(tensor, t)\n\n # # a= torch.tensor([self.num_blades], dtype=torch.int64)\n # # b = torch.tensor(tensor, dtype=torch.int64)[1:]\n # # print(\"a,b:\", a,b, tensor)\n\n\n # # shape = torch.concat([\n # # torch.tensor([self.num_blades], dtype=torch.int64),\n # # torch.tensor(tensor, dtype=torch.int64)[1:]\n # # ], axis=0)\n\n\n # # # tensor = torch.scatter_nd(\n # # # blade_indices.unsqueeze(-1),\n # # # tensor,\n # # # shape\n # # # )\n # # a = torch.zeros(shape)\n # # a[blade_indices] = tensor\n # # tensor = a\n\n # # return torch.permute(tensor, t_inv) \n \n\n def from_tensor(self, tensor: torch.Tensor, blade_indices: torch.Tensor) -> torch.Tensor:\n \"\"\"Creates a geometric algebra torch.Tensor from a torch.Tensor and blade\n indices. The blade indices have to align with the last axis of the\n tensor.\n\n Args:\n tensor: torch.Tensor to take as values for the geometric algebra tensor\n blade_indices: Blade indices corresponding to the tensor. Can\n be obtained from blade names eg. using get_kind_blade_indices()\n or as indices from the blades list property.\n\n Returns:\n Geometric algebra torch.Tensor from tensor and blade indices\n \"\"\"\n # blade_indices = torch.tensor(blade_indices, dtype=torch.int64).to(dtype=torch.int64)\n # tensor = torch.tensor(tensor, dtype=torch.float32)\n blade_indices = blade_indices.to(dtype=torch.int64)\n tensor = tensor.to(dtype=torch.float32)\n # print(f\"blade_indices={blade_indices}\")\n # print(f\"tensor={tensor}\")\n \n _shape = tensor.shape\n is_scalar = False\n if len(_shape)==1 :\n _shape_final = [1]+ [self.num_blades] \n is_scalar = True\n else:\n _shape_final = list(_shape[:-1]) + [self.num_blades] \n b = torch.zeros(_shape_final)\n\n if False:\n print(f\"blade_indices.shape={blade_indices.shape}\")\n print(f\"tensor.shape={tensor.shape}\")\n print(f\"_shape_final={_shape_final}\")\n \n\n\n # i = blade_indices.view([-1,1])\n # v = tensor.flatten().view([-1,1])\n # i = blade_indices.nonzero().flatten()\n i = blade_indices.flatten()\n # v = tensor.flatten().unsqueeze(1)\n v = tensor.view([-1,_shape[-1]])\n b = b.view([-1,self.num_blades])\n if False:\n print(f\"_shape={_shape},_shape_final={_shape_final}\")\n print(f\"i.shape={i.shape},v.shape={v.shape},b.shape={b.shape}\")\n print(f\"i={i},v={v},b={b}\")\n\n # b[:,i] = v\n try:\n b[:,i] = v\n except:\n print(f\"_shape={_shape},_shape_final={_shape_final}\")\n print(f\"i.shape={i.shape},v.shape={v.shape},b.shape={b.shape}\")\n print(f\"i={i},v={v},b={b}\")\n raise\n b = b.reshape(_shape_final)\n\n if False:\n print(f\"b.shape={b.shape}\")\n\n if is_scalar:\n # b=b.unsqueeze(0)\n b=b.squeeze(0)\n return b\n\n\n # # i = blade_indices.view([-1,1])\n # # v = tensor.flatten().view([-1,1])\n # i = blade_indices.nonzero().flatten()\n # v = tensor.flatten().unsqueeze(1)\n # b = b.view([-1,self.num_blades])\n # # b[:,i] = v\n # try:\n # b[:,i] = v\n # except:\n # print(f\"_shape={_shape},_shape_final={_shape_final}\")\n # print(f\"i.shape={i.shape},v.shape={v.shape},b.shape={b.shape}\")\n # print(f\"i={i},v={v},b={b}\")\n # raise\n # b = b.reshape(_shape_final)\n\n # if is_scalar:\n # b=b.unsqueeze(0)\n # return b\n\n \n\n def from_tensor_with_kind(self, tensor: torch.Tensor, kind: BladeKind) -> torch.Tensor:\n \"\"\"Creates a geometric algebra torch.Tensor from a torch.Tensor and a kind.\n The kind's blade indices have to align with the last axis of the\n tensor.\n\n Args:\n tensor: torch.Tensor to take as values for the geometric algebra tensor\n kind: Kind corresponding to the tensor\n\n Returns:\n Geometric algebra torch.Tensor from tensor and kind\n \"\"\"\n # Put last axis on first axis so scatter_nd becomes easier.\n # Later undo the transposition again.\n # tensor = torch.tensor(tensor, dtype=torch.float32)\n tensor = tensor.to(dtype=torch.float32)\n kind_indices = self.get_kind_blade_indices(kind)\n if False:\n print(f\"tensor={tensor}\")\n print(f\"kind_indices={kind_indices}\")\n return self.from_tensor(tensor, kind_indices)\n\n def from_scalar(self, scalar: numbers.Number) -> torch.Tensor:\n \"\"\"Creates a geometric algebra torch.Tensor with scalar elements.\n\n Args:\n scalar: Elements to be used as scalars\n\n Returns:\n Geometric algebra torch.Tensor from scalars\n \"\"\"\n # return self.from_tensor_with_kind(tf.expand_dims(scalar, axis=-1), BladeKind.SCALAR)\n # print(\"torch.tensor([scalar]).unsqueeze(-1).shape\",torch.tensor([scalar]).unsqueeze(-1).shape)\n return self.from_tensor_with_kind(torch.tensor([scalar]).unsqueeze(-1), BladeKind.SCALAR).squeeze(0)\n\n def e(self, *blades: List[str]) -> torch.Tensor:\n \"\"\"Returns a geometric algebra torch.Tensor with the given blades set\n to 1.\n\n Args:\n blades: list of blade names, can be unnormalized\n\n Returns:\n torch.Tensor with blades set to 1\n \"\"\"\n blade_signs, blade_indices = get_blade_indices_from_names(\n blades, self.blades)\n\n assert type(blade_indices) in [torch.Tensor], \"should be a tensor\"\n if False: blade_indices = torch.tensor(blade_indices)\n\n # # Don't allow duplicate indices\n # tf.Assert(\n # blade_indices.shape[0] == tf.unique(blade_indices)[0].shape[0],\n # [blades]\n # )\n\n # x = (\n # tf.expand_dims(blade_signs, axis=-1) *\n # tf.gather(self.blade_mvs, blade_indices)\n # )\n\n # # a, b -> b\n # return tf.reduce_sum(x, axis=-2)\n\n # print(f\"blade_indices={blade_indices}\")\n # print(f\"torch.unique(blade_indices)={torch.unique(blade_indices)}\")\n # print(f\"torch.unique(blade_indices)[0]={torch.unique(blade_indices)[0]}\")\n # Don't allow duplicate indices\n # assert(\n # blade_indices.shape[0] == torch.unique(blade_indices).shape[0],\n # [blades]\n # )\n assert blade_indices.shape[0] == torch.unique(blade_indices).shape[0], \"indexes not unique\"\n\n x = blade_signs.unsqueeze(-1) * self.blade_mvs[blade_indices]\n\n # a, b -> b\n return x.sum(dim=-2) \n\n def __getattr__(self, name: str) -> torch.Tensor:\n \"\"\"Returns basis blade tensors if name was a basis.\"\"\"\n if name.startswith(\"e\") and (name[1:] == \"\" or int(name[1:]) >= 0):\n return self.e(name[1:])\n raise AttributeError\n\n def dual(self, tensor: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the dual of the geometric algebra tensor.\n\n Args:\n tensor: Geometric algebra tensor to return dual for\n\n Returns:\n Dual of the geometric algebra tensor\n \"\"\"\n tensor = torch.tensor(tensor, dtype=torch.float32)\n # return self.dual_blade_signs * tf.gather(tensor, self.dual_blade_indices, axis=-1)\n return self.dual_blade_signs * tensor[...,self.dual_blade_indices]\n\n def grade_automorphism(self, tensor: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the geometric algebra tensor with odd grades negated.\n See https://en.wikipedia.org/wiki/Paravector#Grade_automorphism.\n\n Args:\n tensor: Geometric algebra tensor to return grade automorphism for\n\n Returns:\n Geometric algebra tensor with odd grades negated\n \"\"\"\n tensor = tensor.to(dtype=torch.float32)\n return mv_grade_automorphism(tensor, self.blade_degrees)\n\n def reversion(self, tensor: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the grade-reversed geometric algebra tensor.\n See https://en.wikipedia.org/wiki/Paravector#Reversion_conjugation.\n\n Args:\n tensor: Geometric algebra tensor to return grade-reversion for\n\n Returns:\n Grade-reversed geometric algebra tensor\n \"\"\"\n tensor = tensor.to(dtype=torch.float32)\n\n return mv_reversion(tensor, self.blade_degrees)\n\n def conjugation(self, tensor: torch.Tensor) -> torch.Tensor:\n \"\"\"Combines reversion and grade automorphism.\n See https://en.wikipedia.org/wiki/Paravector#Clifford_conjugation.\n\n Args:\n tensor: Geometric algebra tensor to return conjugate for\n\n Returns:\n Geometric algebra tensor after `reversion()` and `grade_automorphism()`\n \"\"\"\n tensor = tensor.to(dtype=torch.float32)\n return self.grade_automorphism(self.reversion(tensor))\n\n def simple_inverse(self, a: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the inverted geometric algebra tensor\n `X^-1` such that `X * X^-1 = 1`. Only works for elements that\n square to scalars. Faster than the general inverse.\n\n Args:\n a: Geometric algebra tensor to return inverse for\n\n Returns:\n inverted geometric algebra tensor\n \"\"\"\n a = a.to(dtype=torch.float32)\n\n\n rev_a = self.reversion(a)\n divisor = self.geom_prod(a, rev_a)\n # print(f\"divisor={divisor}\")\n # print(f\"self.is_pure_kind(divisor, BladeKind.SCALAR)={self.is_pure_kind(divisor, BladeKind.SCALAR)}\")\n if not self.is_pure_kind(divisor, BladeKind.SCALAR):\n raise Exception(\n \"Can't invert multi-vector (inversion divisor V ~V not scalar: %s).\" % divisor)\n\n # Divide by scalar part\n return rev_a / divisor[..., :1]\n\n def reg_prod(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the regressive product of two geometric\n algebra tensors.\n\n Args:\n a: Geometric algebra tensor on the left hand side of\n the regressive product\n b: Geometric algebra tensor on the right hand side of\n the regressive product\n\n Returns:\n regressive product of a and b\n \"\"\"\n a = torch.tensor(a, dtype=torch.float32)\n b = torch.tensor(b, dtype=torch.float32)\n\n return self.dual(self.ext_prod(self.dual(a), self.dual(b)))\n\n def ext_prod(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the exterior product of two geometric\n algebra tensors.\n\n Args:\n a: Geometric algebra tensor on the left hand side of\n the exterior product\n b: Geometric algebra tensor on the right hand side of\n the exterior product\n\n Returns:\n exterior product of a and b\n \"\"\"\n a = a.to(dtype=torch.float32)\n b = b.to(dtype=torch.float32)\n\n return mv_multiply(a, b, self._cayley_outer)\n\n def geom_prod(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the geometric product of two geometric\n algebra tensors.\n\n Args:\n a: Geometric algebra tensor on the left hand side of\n the geometric product\n b: Geometric algebra tensor on the right hand side of\n the geometric product\n\n Returns:\n geometric product of a and b\n \"\"\"\n # a = torch.tensor(a, dtype=torch.float32)\n # b = torch.tensor(b, dtype=torch.float32)\n\n # a = torch.tensor(a)\n # b = torch.tensor(b)\n\n a = a.to(dtype=torch.float32)\n b = b.to(dtype=torch.float32)\n return mv_multiply(a, b, self._cayley)\n\n \n def element_wise_prod(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the element-wise product of two geometric\n algebra tensors.\n\n Args:\n a: Geometric algebra tensor on the left hand side of\n the geometric product\n b: Geometric algebra tensor on the right hand side of\n the geometric product\n\n Returns:\n geometric product of a and b\n \"\"\"\n # a = torch.tensor(a, dtype=torch.float32)\n # b = torch.tensor(b, dtype=torch.float32)\n\n # a = torch.tensor(a)\n # b = torch.tensor(b)\n\n a = a.to(dtype=torch.float32)\n b = b.to(dtype=torch.float32)\n return mv_multiply_element_wise(a, b, self._cayley)\n\n\n def inner_prod(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the inner product of two geometric\n algebra tensors.\n\n Args:\n a: Geometric algebra tensor on the left hand side of\n the inner product\n b: Geometric algebra tensor on the right hand side of\n the inner product\n\n Returns:\n inner product of a and b\n \"\"\"\n a = a.to(dtype=torch.float32)\n b = b.to(dtype=torch.float32)\n\n return mv_multiply(a, b, self._cayley_inner)\n\n def geom_conv1d(self, a: torch.Tensor, k: torch.Tensor,\n stride: int, padding: str,\n dilations: Union[int, None] = None) -> torch.Tensor:\n \"\"\"Returns the 1D convolution of a sequence with a geometric algebra\n tensor kernel. The convolution is performed using the geometric\n product.\n\n Args:\n a: Input geometric algebra tensor of shape\n [..., Length, ChannelsIn, Blades]\n k: Geometric algebra tensor for the convolution kernel of shape\n [KernelSize, ChannelsIn, ChannelsOut, Blades]\n stride: Stride to use for the convolution\n padding: \"SAME\" (zero-pad input length so output\n length == input length / stride) or \"VALID\" (no padding)\n Returns:\n Geometric algbra tensor of shape\n [..., OutputLength, ChannelsOut, Blades]\n representing `a` convolved with `k`\n \"\"\"\n a = a.to(dtype=torch.float32)\n k = k.to(dtype=torch.float32)\n\n # return mv_conv1d(a, k, self._cayley, stride=stride, padding=padding)\n return f_mv_conv1d(a, k, self._cayley, stride=stride, padding=padding)\n\n def mv_repr(self, a: torch.Tensor) -> str:\n \"\"\"Returns a string representation for the given\n geometric algebra tensor.\n\n Args:\n a: Geometric algebra tensor to return the representation for\n\n Returns:\n string representation for `a`\n \"\"\"\n a = a.to(dtype=torch.float32)\n\n\n if len(a.shape) == 1:\n return \"MultiVector[%s]\" % \" + \".join(\n \"%.2f*%s\" % (value, get_blade_repr(blade_name))\n for value, blade_name\n in zip(a, self.blades)\n if value != 0\n )\n else:\n return f\"MultiVector[batch_shape={a.shape[:-1]}]\"\n\n def approx_exp(self, a: torch.Tensor, order: int = 50) -> torch.Tensor:\n \"\"\"Returns an approximation of the exponential using a centered taylor series.\n\n Args:\n a: Geometric algebra tensor to return exponential for\n order: order of the approximation\n\n Returns:\n Approximation of `exp(a)`\n \"\"\"\n a = a.to(dtype=torch.float32)\n\n v = self.from_scalar(1.0)\n result = self.from_scalar(1.0)\n for i in range(1, order + 1):\n v = self.geom_prod(a, v)\n # i_factorial = tf.exp(tf.math.lgamma(i + 1.0))\n i_factorial = torch.exp(torch.lgamma(torch.tensor([i + 1.0])))\n result += v / i_factorial\n return result\n\n def exp(self, a: torch.Tensor, square_scalar_tolerance: Union[float, None] = 1e-4) -> torch.Tensor:\n \"\"\"Returns the exponential of the passed geometric algebra tensor.\n Only works for multivectors that square to scalars.\n\n Args:\n a: Geometric algebra tensor to return exponential for\n square_scalar_tolerance: Tolerance to use for the square scalar check\n or None if the check should be skipped\n\n Returns:\n `exp(a)`\n \"\"\"\n # See https://www.euclideanspace.com/maths/algebra/clifford/algebra/functions/exponent/index.htm\n # for an explanation of how to exponentiate multivectors.\n\n self_sq = self.geom_prod(a, a)\n\n if square_scalar_tolerance is not None:\n # tf.Assert(tf.reduce_all(\n # tf.abs(self_sq[..., 1:]) < square_scalar_tolerance\n # ), [self_sq])\n \n # assert torch.equal(torch.all(self_sq[..., 1:].abs() < square_scalar_tolerance),[self_sq]), \"not sure what\"\n assert torch.all(self_sq[..., 1:].abs() < square_scalar_tolerance), \"square_scalar_tolerance not met\"\n\n scalar_self_sq = self_sq[..., :1]\n\n # \"Complex\" square root (argument can be negative)\n s_sqrt = torch.sign(scalar_self_sq) * torch.sqrt(torch.abs(scalar_self_sq))\n\n # Square to +1: cosh(sqrt(||a||)) + a / sqrt(||a||) sinh(sqrt(||a||))\n # Square to -1: cos(sqrt(||a||)) + a / sqrt(||a||) sin(sqrt(||a||))\n # TODO: Does this work for values other than 1 too? eg. square to +0.5?\n # TODO: Find a solution that doesnt require calculating all possibilities\n # first.\n non_zero_result = torch.where(\n scalar_self_sq < 0,\n (self.from_tensor(torch.cos(s_sqrt), torch.tensor([0])) + a / s_sqrt * torch.sin(s_sqrt)),\n (self.from_tensor(torch.cosh(s_sqrt), torch.tensor([0])) + a / s_sqrt * torch.sinh(s_sqrt))\n )\n\n return torch.where(scalar_self_sq == 0, self.from_scalar(1.0) + a, non_zero_result)\n\n def approx_log(self, a: torch.Tensor, order: int = 50) -> torch.Tensor:\n \"\"\"Returns an approximation of the natural logarithm using a centered\n taylor series. Only converges for multivectors where `||mv - 1|| < 1`.\n\n Args:\n a: Geometric algebra tensor to return logarithm for\n order: order of the approximation\n\n Returns:\n Approximation of `log(a)`\n \"\"\"\n a = a.to(dtype=torch.float32)\n\n result = self.from_scalar(0.0)\n\n a_minus_one = a - self.from_scalar(1.0)\n v = None\n\n for i in range(1, order + 1):\n v = a_minus_one if v is None else v * a_minus_one\n result += (((-1.0) ** i) / i) * v\n\n return -result\n\n def int_pow(self, a: torch.Tensor, n: int) -> torch.Tensor:\n \"\"\"Returns the geometric algebra tensor to the power of an integer\n using repeated multiplication.\n\n Args:\n a: Geometric algebra tensor to raise\n n: integer power to raise the multivector to\n\n Returns:\n `a` to the power of `n`\n \"\"\"\n a = a.to(dtype=torch.float32)\n\n\n if not isinstance(n, int):\n raise Exception(\"n must be an integer.\")\n if n < 0:\n raise Exception(\"Can't raise to negative powers.\")\n\n if n == 0:\n # TODO: more efficient (ones only in scalar)\n return torch.ones_like(a) * self.e(\"\")\n\n result = a\n for i in range(n - 1):\n result = self.geom_prod(result, a)\n return result\n\n def keep_blades(self, a: torch.Tensor, blade_indices: List[int]) -> torch.Tensor:\n \"\"\"Takes a geometric algebra tensor and returns it with only the given\n blade_indices as non-zeros.\n\n Args:\n a: Geometric algebra tensor to copy\n blade_indices: Indices for blades to keep\n\n Returns:\n `a` with only `blade_indices` components as non-zeros\n \"\"\"\n a = a.to(dtype=torch.float32)\n blade_indices = blade_indices.to(dtype=torch.int64)\n\n # blade_values = tf.gather(a, blade_indices, axis=-1)\n blade_values = a[...,blade_indices]\n if True: \n b = self.from_tensor(blade_values, blade_indices)\n else:\n blade_mask = torch.zeros(self.num_blades)\n blade_mask[blade_indices] = 1\n b = self.from_tensor(blade_values, blade_mask)\n # print(f\"blade_values, blade_indices, b={blade_values}, {blade_indices}, {b}\")\n # print(f\"blade_mask={blade_mask}\")\n return b\n\n # return self.from_tensor(blade_values, blade_indices)\n\n def keep_blades_with_name(self, a: torch.Tensor, blade_names: Union[List[str], str]) -> torch.Tensor:\n \"\"\"Takes a geometric algebra tensor and returns it with only the given\n blades as non-zeros.\n\n Args:\n a: Geometric algebra tensor to copy\n blade_names: Blades to keep\n\n Returns:\n `a` with only `blade_names` components as non-zeros\n \"\"\"\n if isinstance(blade_names, str):\n blade_names = [blade_names]\n\n _, blade_indices = get_blade_indices_from_names(blade_names, self.blades)\n\n if False:\n print(f\"self.blades={self.blades}\")\n print(f\"blade_names={blade_names}\")\n print(f\"blade_indices={blade_indices}\")\n\n return self.keep_blades(a, blade_indices)\n\n def select_blades(self, a: torch.Tensor, blade_indices: List[int]) -> torch.Tensor:\n \"\"\"Takes a geometric algebra tensor and returns a `torch.Tensor` with the\n blades in blade_indices on the last axis.\n\n\n Args:\n a: Geometric algebra tensor to copy\n blade_indices: Indices for blades to select\n\n Returns:\n `torch.Tensor` based on `a` with `blade_indices` on last axis.\n \"\"\"\n a = a.to(dtype=torch.float32) \n # blade_indices = torch.tensor(blade_indices, dtype=torch.int64).to(dtype=torch.int64)\n blade_indices = blade_indices.to(dtype=torch.int64)\n\n # result = tf.gather(a, blade_indices, axis=-1)\n try:\n if len(a.shape)==1 or a.shape[-1]==a.size().numel():\n result = a.squeeze()[blade_indices]\n else:\n result = a[...,blade_indices]\n except:\n print(f\"a={a},blade_indices={blade_indices}\")\n print(f\"a.shape={a.shape},blade_indices.shape={blade_indices.shape},a.size().numel()={a.size().numel()}\")\n raise\n \n return result\n\n def select_blades_with_name(self, a: torch.Tensor, blade_names: Union[List[str], str]) -> torch.Tensor:\n \"\"\"Takes a geometric algebra tensor and returns a `torch.Tensor` with the\n blades in blade_names on the last axis.\n\n\n Args:\n a: Geometric algebra tensor to copy\n blade_names: Blades to keep\n\n Returns:\n `torch.Tensor` based on `a` with `blade_names` on last axis.\n \"\"\"\n a = a.to(dtype=torch.float32)\n\n is_single_blade = isinstance(blade_names, str)\n if is_single_blade:\n blade_names = [blade_names]\n\n blade_signs, blade_indices = get_blade_indices_from_names(\n blade_names, self.blades)\n\n result = blade_signs * self.select_blades(a, blade_indices)\n # if True:\n # print(f\"\")\n\n if is_single_blade:\n return result[..., 0]\n\n return result\n\n def inverse(self, a: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the inverted geometric algebra tensor\n `X^-1` such that `X * X^-1 = 1`.\n\n Using Shirokov's inverse algorithm that works in arbitrary dimensions,\n see https://arxiv.org/abs/2005.04015 Theorem 4.\n\n Args:\n a: Geometric algebra tensor to return inverse for\n\n Returns:\n inverted geometric algebra tensor\n \"\"\"\n # a = torch.tensor(a, dtype=torch.float32)\n a = a.to(dtype=torch.float32)\n if False:\n print(f\"a={a}\")\n\n n = 2 ** ((len(self.metric) + 1) // 2)\n\n # u = a.clone()\n u = a\n for k in range(1, n):\n # c = n / k * self.keep_blades_with_name(u, \"\")\n d = self.keep_blades_with_name(u, \"\")\n c = n / k * d\n u_minus_c = u - c\n if False:\n print(f\"a,d,c,u_minus_c, u = {a},{d},{c},{u_minus_c}, {u}\")\n u = self.geom_prod(a, u_minus_c)\n if False:\n print(f\"u={u}\")\n \n if False:\n print(f\"n={n}\")\n print(f\"a={a}\")\n print(f\"u={u}\")\n if not torch.all(self.is_pure_kind(u, BladeKind.SCALAR)):\n raise Exception(\n \"Can't invert multi-vector (det U not scalar: %s).\" % u)\n\n # adj / det\n return u_minus_c / u[..., :1]\n\n def __call__(self, a: torch.Tensor) -> MultiVector:\n \"\"\"Creates a `MultiVector` from a geometric algebra tensor.\n Mainly used as a wrapper for the algebra's functions for convenience.\n\n Args:\n a: Geometric algebra tensor to return `MultiVector` for\n\n Returns:\n `MultiVector` for `a`\n \"\"\"\n a = a.to(dtype=torch.float32)\n return MultiVector(a, self)\n # return MultiVector(torch.tensor(a), self)" } ]
import unittest as ut import h5py import torch import torch.nn as nn import torch.nn.functional as F import torch from io import BytesIO from torch_ga.layers import ( GeometricProductDense, GeometricSandwichProductDense, GeometricProductElementwise, GeometricSandwichProductElementwise, GeometricProductConv1D, GeometricAlgebraExp, GeometricToTensor, GeometricToTensorWithKind, TensorToGeometric, TensorWithKindToGeometric, ) from torch_ga.blades import BladeKind from torch_ga import GeometricAlgebra
17,289
torch.manual_seed(0) class TestKerasLayers(ut.TestCase): def assertTensorsEqual(self, a, b): # self.assertTrue(tf.reduce_all(a == b), "%s not equal to %s" % (a, b)) print(f"assertTensorsEqual(a={a},b={b})") assert torch.all(a.squeeze() == b.squeeze()), "%s not equal to %s" % (a, b) def test_tensor_to_geometric(self): sta = GeometricAlgebra([1, -1, -1, -1]) tensor = torch.ones([32, 4]) gt_geom_tensor = torch.concat( [torch.zeros([32, 1]), torch.ones([32, 4]), torch.zeros([32, 11])], axis=-1 ) vector_blade_indices = [1, 2, 3, 4] tensor_to_geom_layer = TensorToGeometric(sta, vector_blade_indices) self.assertTensorsEqual(tensor_to_geom_layer(tensor), gt_geom_tensor) def test_tensor_with_kind_to_geometric(self): sta = GeometricAlgebra([1, -1, -1, -1]) tensor = torch.ones([32, 4]) gt_geom_tensor = torch.concat( [torch.zeros([32, 1]), torch.ones([32, 4]), torch.zeros([32, 11])], axis=-1 ) vector_blade_indices = [1, 2, 3, 4] tensor_kind_to_geom_layer = TensorWithKindToGeometric( sta, BladeKind.VECTOR) self.assertTensorsEqual( tensor_kind_to_geom_layer(tensor), gt_geom_tensor) def test_geometric_to_tensor(self): sta = GeometricAlgebra([1, -1, -1, -1]) gt_tensor = torch.ones([32, 4]) geom_tensor = torch.concat( [torch.zeros([32, 1]), torch.ones([32, 4]), torch.zeros([32, 11])], axis=-1 ) vector_blade_indices = [1, 2, 3, 4] geom_to_tensor_layer = GeometricToTensor(sta, vector_blade_indices) self.assertTensorsEqual(geom_to_tensor_layer(geom_tensor), gt_tensor) def test_geometric_to_tensor_with_kind(self): sta = GeometricAlgebra([1, -1, -1, -1]) gt_tensor = torch.ones([32, 4]) geom_tensor = torch.concat( [torch.zeros([32, 1]), torch.ones([32, 4]), torch.zeros([32, 11])], axis=-1 ) vector_blade_indices = [1, 2, 3, 4] geom_to_tensor_kind_layer = GeometricToTensorWithKind( sta, BladeKind.VECTOR) self.assertTensorsEqual( geom_to_tensor_kind_layer(geom_tensor), gt_tensor) def test_geometric_product_dense_v_v(self): sta = GeometricAlgebra([1, -1, -1, -1]) geom_tensor = torch.concat( [torch.zeros([32, 6, 1]), torch.ones([32, 6, 4]), torch.zeros([32, 6, 11])], axis=-1 ) vector_blade_indices = [1, 2, 3, 4]
torch.manual_seed(0) class TestKerasLayers(ut.TestCase): def assertTensorsEqual(self, a, b): # self.assertTrue(tf.reduce_all(a == b), "%s not equal to %s" % (a, b)) print(f"assertTensorsEqual(a={a},b={b})") assert torch.all(a.squeeze() == b.squeeze()), "%s not equal to %s" % (a, b) def test_tensor_to_geometric(self): sta = GeometricAlgebra([1, -1, -1, -1]) tensor = torch.ones([32, 4]) gt_geom_tensor = torch.concat( [torch.zeros([32, 1]), torch.ones([32, 4]), torch.zeros([32, 11])], axis=-1 ) vector_blade_indices = [1, 2, 3, 4] tensor_to_geom_layer = TensorToGeometric(sta, vector_blade_indices) self.assertTensorsEqual(tensor_to_geom_layer(tensor), gt_geom_tensor) def test_tensor_with_kind_to_geometric(self): sta = GeometricAlgebra([1, -1, -1, -1]) tensor = torch.ones([32, 4]) gt_geom_tensor = torch.concat( [torch.zeros([32, 1]), torch.ones([32, 4]), torch.zeros([32, 11])], axis=-1 ) vector_blade_indices = [1, 2, 3, 4] tensor_kind_to_geom_layer = TensorWithKindToGeometric( sta, BladeKind.VECTOR) self.assertTensorsEqual( tensor_kind_to_geom_layer(tensor), gt_geom_tensor) def test_geometric_to_tensor(self): sta = GeometricAlgebra([1, -1, -1, -1]) gt_tensor = torch.ones([32, 4]) geom_tensor = torch.concat( [torch.zeros([32, 1]), torch.ones([32, 4]), torch.zeros([32, 11])], axis=-1 ) vector_blade_indices = [1, 2, 3, 4] geom_to_tensor_layer = GeometricToTensor(sta, vector_blade_indices) self.assertTensorsEqual(geom_to_tensor_layer(geom_tensor), gt_tensor) def test_geometric_to_tensor_with_kind(self): sta = GeometricAlgebra([1, -1, -1, -1]) gt_tensor = torch.ones([32, 4]) geom_tensor = torch.concat( [torch.zeros([32, 1]), torch.ones([32, 4]), torch.zeros([32, 11])], axis=-1 ) vector_blade_indices = [1, 2, 3, 4] geom_to_tensor_kind_layer = GeometricToTensorWithKind( sta, BladeKind.VECTOR) self.assertTensorsEqual( geom_to_tensor_kind_layer(geom_tensor), gt_tensor) def test_geometric_product_dense_v_v(self): sta = GeometricAlgebra([1, -1, -1, -1]) geom_tensor = torch.concat( [torch.zeros([32, 6, 1]), torch.ones([32, 6, 4]), torch.zeros([32, 6, 11])], axis=-1 ) vector_blade_indices = [1, 2, 3, 4]
geom_prod_layer = GeometricProductDense(
0
2023-10-07 13:34:07+00:00
24k
Significant-Gravitas/autostandup
bot.py
[ { "identifier": "StreaksDB", "path": "streaks/streaks_db.py", "snippet": "class StreaksDB(BaseDB):\n \"\"\"\n StreaksDB class handles all operations related to the 'streaks' table.\n Inherits from the BaseDB class.\n \"\"\"\n\n def __init__(self, host, user, password, database, port):\n \"\"\"\n Initializes the StreaksDB class and creates the 'streaks' table if it doesn't exist.\n\n :param host: The MySQL host address.\n :param user: The MySQL user.\n :param password: The MySQL password.\n :param database: The MySQL database name.\n :param port: The MySQL port number.\n \"\"\"\n super().__init__(host, user, password, database, port)\n self._create_streaks_table()\n\n def _create_streaks_table(self):\n \"\"\"\n Creates the 'streaks' table if it doesn't already exist.\n \"\"\"\n query = '''\n CREATE TABLE IF NOT EXISTS streaks (\n discord_id BIGINT PRIMARY KEY,\n current_streak INT DEFAULT 0,\n FOREIGN KEY (discord_id) REFERENCES team_members(discord_id) ON DELETE CASCADE\n );\n '''\n try:\n self.execute_query(query)\n finally:\n self.close()\n\n def update_streak(self, discord_id: int, new_streak: int):\n \"\"\"\n Updates the streak for a given user.\n\n :param discord_id: The Discord ID of the user.\n :param new_streak: The new streak count.\n \"\"\"\n query = \"\"\"\n INSERT INTO streaks (discord_id, current_streak)\n VALUES (%s, %s)\n ON DUPLICATE KEY UPDATE current_streak = %s\n \"\"\"\n params = (discord_id, new_streak, new_streak)\n try:\n self.execute_query(query, params)\n finally:\n self.close()\n\n def get_streak(self, discord_id: int) -> int:\n \"\"\"\n Fetches the current streak for a given user.\n\n :param discord_id: The Discord ID of the user.\n :return: The current streak count.\n \"\"\"\n if not self.conn.is_connected():\n print(\"Reconnecting to MySQL\")\n self.connect()\n c = self.conn.cursor()\n query = \"SELECT current_streak FROM streaks WHERE discord_id = %s\"\n params = (discord_id,)\n try:\n c.execute(query, params)\n row = c.fetchone()\n return row[0] if row else 0\n finally:\n c.close()\n self.close()" }, { "identifier": "TeamMemberDB", "path": "team_members/team_member_db.py", "snippet": "class TeamMemberDB(BaseDB):\n \"\"\"\n TeamMemberDB class handles operations related to the 'team_members' table.\n\n :param host: The MySQL host address.\n :param user: The MySQL user.\n :param password: The MySQL password.\n :param database: The MySQL database name.\n :param port: The MySQL port number.\n \"\"\"\n\n def __init__(self, host: str, user: str, password: str, database: str, port: str):\n \"\"\"\n Initializes the TeamMemberDB class and creates the 'team_members' table if it doesn't exist.\n \"\"\"\n super().__init__(host, user, password, database, port)\n self._create_team_members_table()\n\n def _create_team_members_table(self):\n \"\"\"\n Creates the 'team_members' table if it doesn't already exist.\n \"\"\"\n query = '''\n CREATE TABLE IF NOT EXISTS team_members (\n discord_id BIGINT PRIMARY KEY,\n name VARCHAR(255) NOT NULL,\n time_zone VARCHAR(50) NOT NULL,\n github_username VARCHAR(255),\n on_vacation BOOLEAN DEFAULT FALSE\n );\n '''\n try:\n self.execute_query(query)\n finally:\n self.close()\n\n def insert_new_member(self, discord_id: int, name: str, time_zone: str, github_username: str):\n \"\"\"\n Inserts a new team member into the 'team_members' table.\n\n :param discord_id: The Discord ID of the team member.\n :param name: The name of the team member.\n :param time_zone: The time zone of the team member.\n :param github_username: The GitHub username of the team member.\n \"\"\"\n query = \"\"\"\n INSERT INTO team_members (discord_id, name, time_zone, github_username)\n VALUES (%s, %s, %s, %s)\n ON DUPLICATE KEY UPDATE name = %s, time_zone = %s, github_username = %s\n \"\"\"\n params = (discord_id, name, time_zone, github_username, name, time_zone, github_username)\n try:\n self.execute_query(query, params)\n finally:\n self.close()\n\n def remove_member(self, discord_id: int):\n \"\"\"\n Removes a team member from the 'team_members' table.\n\n :param discord_id: The Discord ID of the team member to remove.\n \"\"\"\n query = \"DELETE FROM team_members WHERE discord_id = %s\"\n params = (discord_id,)\n try:\n self.execute_query(query, params)\n finally:\n self.close()\n\n def list_all_members(self) -> List[Tuple[int, str, str, str, bool]]:\n \"\"\"\n Fetches all team members from the 'team_members' table.\n\n :return: A list of tuples, each containing the Discord ID, name, time zone, GitHub username, and vacation status of a team member.\n \"\"\"\n if not self.conn.is_connected():\n print(\"Reconnecting to MySQL\")\n self.connect()\n c = self.conn.cursor()\n try:\n c.execute(\"SELECT discord_id, name, time_zone, github_username, on_vacation FROM team_members\")\n return c.fetchall()\n finally:\n c.close()\n self.close()\n\n def update_member_timezone(self, discord_id: int, new_time_zone: str):\n \"\"\"\n Updates the timezone of a team member in the 'team_members' table.\n\n :param discord_id: The Discord ID of the team member.\n :param new_time_zone: The new timezone to be set for the team member.\n \"\"\"\n query = \"UPDATE team_members SET time_zone = %s WHERE discord_id = %s\"\n params = (new_time_zone, discord_id)\n try:\n self.execute_query(query, params)\n finally:\n self.close()\n\n def set_vacation_status(self, discord_id: int, on_vacation: bool):\n \"\"\"\n Sets the vacation status of a team member in the 'team_members' table.\n\n :param discord_id: The Discord ID of the team member.\n :param on_vacation: The vacation status to be set for the team member.\n \"\"\"\n query = \"UPDATE team_members SET on_vacation = %s WHERE discord_id = %s\"\n params = (on_vacation, discord_id)\n try:\n self.execute_query(query, params)\n finally:\n self.close()" }, { "identifier": "UpdatesDB", "path": "updates/updates_db.py", "snippet": "class UpdatesDB(BaseDB):\n \"\"\"\n Database class for handling operations related to the 'updates' table.\n \"\"\"\n\n def __init__(self, host: str, user: str, password: str, database: str, port: str):\n \"\"\"\n Initializes the UpdatesDB class and creates the 'updates' table if it doesn't exist.\n\n :param host: The MySQL host address.\n :param user: The MySQL user.\n :param password: The MySQL password.\n :param database: The MySQL database name.\n :param port: The MySQL port number.\n \"\"\"\n super().__init__(host, user, password, database, port)\n self._create_updates_table()\n\n def _create_updates_table(self):\n \"\"\"\n Creates the 'updates' table if it doesn't already exist.\n \"\"\"\n query = '''\n CREATE TABLE IF NOT EXISTS updates (\n id INT AUTO_INCREMENT PRIMARY KEY,\n discord_id BIGINT,\n status TEXT NOT NULL,\n summarized_status TEXT,\n timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n time_zone VARCHAR(255),\n FOREIGN KEY (discord_id) REFERENCES team_members(discord_id) ON DELETE CASCADE\n )\n '''\n try:\n self.execute_query(query)\n finally:\n self.close()\n\n def insert_status(self, discord_id: int, status: str, time_zone: str):\n \"\"\"\n Inserts a new status update into the 'updates' table.\n\n :param discord_id: The Discord ID of the team member.\n :param status: The status update.\n :param time_zone: The time zone of the user.\n \"\"\"\n # Convert current UTC time to user's local time zone\n utc_now = datetime.utcnow().replace(tzinfo=pytz.utc)\n local_now = utc_now.astimezone(pytz.timezone(time_zone))\n\n query = \"INSERT INTO updates (discord_id, status, timestamp, time_zone) VALUES (%s, %s, %s, %s)\"\n params = (discord_id, status, local_now, time_zone)\n try:\n self.execute_query(query, params)\n finally:\n self.close()\n\n def update_summarized_status(self, discord_id: int, summarized_status: str):\n \"\"\"\n Updates the summarized_status for the most recent update for a given user.\n\n :param discord_id: The Discord ID of the team member.\n :param summarized_status: The summarized status update.\n \"\"\"\n query = \"\"\"\n UPDATE updates\n SET summarized_status = %s\n WHERE discord_id = %s\n ORDER BY timestamp DESC\n LIMIT 1\n \"\"\"\n params = (summarized_status, discord_id)\n try:\n self.execute_query(query, params)\n finally:\n self.close()\n \n def get_weekly_checkins_count(self, discord_id: int, time_zone: str) -> int:\n \"\"\"\n Fetches the number of check-ins for a given user in the current week.\n\n :param discord_id: The Discord ID of the user.\n :param time_zone: The time zone of the user.\n :return: The count of check-ins in the current week.\n \"\"\"\n if not self.conn.is_connected():\n print(\"Reconnecting to MySQL\")\n self.connect()\n\n c = self.conn.cursor()\n \n # Adjusting the current time to the user's time zone\n local_tz = pytz.timezone(time_zone)\n local_now = datetime.now(local_tz)\n \n # Getting the Monday of the current week in the user's time zone\n monday = local_now - timedelta(days=local_now.weekday())\n monday = monday.replace(hour=0, minute=0, second=0, microsecond=0)\n\n query = \"\"\"\n SELECT COUNT(*) FROM updates\n WHERE discord_id = %s AND timestamp >= %s\n \"\"\"\n params = (discord_id, monday)\n try:\n c.execute(query, params)\n \n row = c.fetchone()\n return row[0] if row else 0\n finally:\n c.close()\n self.close()\n\n def get_statuses_in_date_range(self, discord_id: int, start_date: datetime, end_date: datetime) -> List[str]:\n \"\"\"\n Fetches all raw status updates for a given user within a specified date range.\n\n Args:\n discord_id: The Discord ID of the user.\n start_date: The start date of the date range.\n end_date: The end date of the date range.\n\n Returns:\n A list of raw status updates.\n \"\"\"\n if not self.conn.is_connected():\n print(\"Reconnecting to MySQL\")\n self.connect()\n\n c = self.conn.cursor()\n \n query = \"\"\"\n SELECT summarized_status FROM updates\n WHERE discord_id = %s AND timestamp >= %s AND timestamp <= %s\n \"\"\"\n params = (discord_id, start_date, end_date)\n try:\n c.execute(query, params)\n \n statuses = [row[0] for row in c.fetchall()]\n return statuses\n finally:\n c.close()\n self.close()\n \n def get_all_statuses_for_user(self, discord_id: int) -> List[dict]:\n \"\"\"\n Fetches all status updates (both raw and summarized) for a given user.\n\n Args:\n discord_id: The Discord ID of the user.\n\n Returns:\n A list of dictionaries, each containing the status update details for a given record.\n \"\"\"\n if not self.conn.is_connected():\n print(\"Reconnecting to MySQL\")\n self.connect()\n\n c = self.conn.cursor(dictionary=True) # Set dictionary=True to return results as dictionaries\n \n query = \"\"\"\n SELECT id, discord_id, status, summarized_status, timestamp \n FROM updates\n WHERE discord_id = %s\n ORDER BY timestamp DESC\n \"\"\"\n params = (discord_id,)\n try:\n c.execute(query, params)\n \n statuses = c.fetchall()\n return statuses\n finally:\n c.close()\n self.close()\n \n def get_last_update_timestamp(self, discord_id: int) -> Tuple[datetime, str]:\n \"\"\"\n Fetches the timestamp and time zone of the last status update for a given user.\n\n Args:\n discord_id: The Discord ID of the user.\n\n Returns:\n A tuple containing the timestamp of the last update and its time zone, or (None, None) if there are no updates.\n \"\"\"\n if not self.conn.is_connected():\n print(\"Reconnecting to MySQL\")\n self.connect()\n\n c = self.conn.cursor()\n \n query = \"\"\"\n SELECT timestamp, time_zone FROM updates\n WHERE discord_id = %s\n ORDER BY timestamp DESC\n LIMIT 1\n \"\"\"\n params = (discord_id,)\n try:\n c.execute(query, params)\n \n row = c.fetchone()\n return (row[0], row[1]) if row else (None, None)\n finally:\n c.close()\n self.close()\n \n def delete_newest_status(self, discord_id: int) -> None:\n \"\"\"\n Deletes the most recent status update for a given user.\n\n Args:\n discord_id: The Discord ID of the user.\n \"\"\"\n if not self.conn.is_connected():\n print(\"Reconnecting to MySQL\")\n self.connect()\n\n c = self.conn.cursor()\n \n # Fetch the ID of the newest status update for the given user\n query_get_id = \"\"\"\n SELECT id FROM updates\n WHERE discord_id = %s\n ORDER BY timestamp DESC\n LIMIT 1\n \"\"\"\n try:\n c.execute(query_get_id, (discord_id,))\n \n row = c.fetchone()\n if row:\n status_id = row[0]\n \n # Now, delete the status update using its ID\n query_delete = \"\"\"\n DELETE FROM updates WHERE id = %s\n \"\"\"\n c.execute(query_delete, (status_id,))\n \n self.conn.commit()\n finally:\n c.close()\n self.close()" }, { "identifier": "WeeklyPostsDB", "path": "weekly_posts/weekly_posts_db.py", "snippet": "class WeeklyPostsDB(BaseDB):\n \"\"\"\n Database class that handles operations related to the 'weekly_posts' table.\n \"\"\"\n\n def __init__(self, host: str, user: str, password: str, database: str, port: str):\n \"\"\"\n Initializes the WeeklyPostsDB class, connects to the MySQL database,\n and creates the 'weekly_posts' table if it doesn't exist.\n\n :param host: The MySQL host address.\n :param user: The MySQL user.\n :param password: The MySQL password.\n :param database: The MySQL database name.\n :param port: The MySQL port number.\n \"\"\"\n super().__init__(host, user, password, database, port)\n self._create_weekly_posts_table()\n\n def _create_weekly_posts_table(self):\n \"\"\"\n Creates the 'weekly_posts' table if it doesn't already exist.\n \"\"\"\n query = '''\n CREATE TABLE IF NOT EXISTS weekly_posts (\n post_id BIGINT PRIMARY KEY,\n timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n );\n '''\n try:\n self.execute_query(query)\n finally:\n self.close()\n\n def get_weekly_post_data(self) -> Optional[Dict[str, datetime.datetime]]:\n \"\"\"\n Fetches the most recent weekly post data from the 'weekly_posts' table.\n\n :return: A dictionary containing the post ID and timestamp, or None if no data exists.\n \"\"\"\n query = \"SELECT post_id, timestamp FROM weekly_posts ORDER BY timestamp DESC LIMIT 1\"\n \n if not self.conn.is_connected():\n print(\"Reconnecting to MySQL\")\n self.connect()\n\n c = self.conn.cursor()\n try:\n c.execute(query)\n row = c.fetchone()\n\n if row:\n return {'post_id': row[0], 'timestamp': row[1]}\n return None\n finally:\n c.close()\n self.close()\n\n def save_weekly_post_data(self, post_id: int, timestamp: datetime.datetime):\n \"\"\"\n Inserts or updates the weekly post data in the 'weekly_posts' table.\n\n :param post_id: The ID of the weekly post.\n :param timestamp: The timestamp of the weekly post.\n \"\"\"\n query = \"\"\"\n INSERT INTO weekly_posts (post_id, timestamp)\n VALUES (%s, %s)\n ON DUPLICATE KEY UPDATE timestamp = %s\n \"\"\"\n params = (post_id, timestamp, timestamp)\n try:\n self.execute_query(query, params)\n finally:\n self.close()" }, { "identifier": "StreaksManager", "path": "streaks/streaks_manager.py", "snippet": "class StreaksManager:\n \"\"\"\n Manages the streaks for team members.\n \"\"\"\n \n def __init__(self, streaks_db: StreaksDB):\n \"\"\"\n Initializes a new StreaksManager instance.\n\n Args:\n streaks_db: The StreaksDB object that handles database operations.\n \"\"\"\n self.streaks_db = streaks_db\n \n def get_streak(self, discord_id: int) -> int:\n \"\"\"\n Fetches the current streak for a given user.\n\n Args:\n discord_id: The Discord ID of the user.\n\n Returns:\n The current streak count.\n \"\"\"\n return self.streaks_db.get_streak(discord_id)\n\n def update_streak(self, discord_id: int, new_streak: int):\n \"\"\"\n Updates the streak for a given user.\n\n Args:\n discord_id: The Discord ID of the user.\n new_streak: The new streak count.\n \"\"\"\n self.streaks_db.update_streak(discord_id, new_streak)\n \n def reset_streak(self, discord_id: int):\n \"\"\"\n Resets the streak for a given user to zero.\n\n Args:\n discord_id: The Discord ID of the user.\n \"\"\"\n self.streaks_db.update_streak(discord_id, 0)" }, { "identifier": "TeamMemberManager", "path": "team_members/team_member_manager.py", "snippet": "class TeamMemberManager:\n \"\"\"\n Manages operations related to team members.\n \"\"\"\n\n def __init__(self, db: TeamMemberDB):\n \"\"\"\n Initialize a TeamMemberManager object.\n\n :param db: TeamMemberDB object for interacting with the database.\n \"\"\"\n self.db = db\n self.team_members = self.load_team_members()\n\n def load_team_members(self) -> List[TeamMember]:\n \"\"\"\n Load team members from the MySQL database into a list of TeamMember objects.\n\n :return: List of TeamMember objects.\n \"\"\"\n team_members = []\n members_data = self.db.list_all_members()\n\n for member_data in members_data:\n member = TeamMember(\n discord_id=member_data[0],\n time_zone=member_data[2],\n name=member_data[1],\n github_username=member_data[3],\n on_vacation=member_data[4]\n )\n team_members.append(member)\n\n return team_members\n\n def find_member(self, discord_id: int) -> TeamMember:\n \"\"\"\n Find and return a team member by their Discord ID.\n\n :param discord_id: The Discord ID of the team member.\n :return: A TeamMember object if found, otherwise None.\n \"\"\"\n for member in self.team_members:\n if member.discord_id == discord_id:\n return member\n return None\n\n def add_member(self, discord_id: int, name: str, time_zone: str, github_username: str):\n \"\"\"\n Add a new team member to the list and the database.\n\n :param discord_id: The Discord ID of the new member.\n :param name: The name of the new member.\n :param time_zone: The time zone of the new member.\n :param github_username: The GitHub username of the new member.\n \"\"\"\n new_member = TeamMember(discord_id, time_zone, name, github_username)\n self.db.insert_new_member(discord_id, name, time_zone, github_username)\n self.team_members.append(new_member)\n\n def remove_member(self, discord_id: int):\n \"\"\"\n Remove a team member from the list and the database.\n\n :param discord_id: The Discord ID of the member to remove.\n \"\"\"\n self.db.remove_member(discord_id)\n self.team_members = [member for member in self.team_members if member.discord_id != discord_id]\n\n def update_member_timezone(self, discord_id: int, new_time_zone: str):\n \"\"\"\n Update the timezone of a team member in the database and the list.\n\n :param discord_id: The Discord ID of the member to update.\n :param new_time_zone: The new timezone string to set for the member.\n \"\"\"\n # Update the timezone in the database\n self.db.update_member_timezone(discord_id, new_time_zone)\n\n # Find the member in the team_members list and update their timezone\n member = self.find_member(discord_id)\n if member:\n member.time_zone = new_time_zone\n\n def set_member_vacation_status(self, discord_id: int, on_vacation: bool):\n \"\"\"\n Sets the vacation status of a team member.\n\n :param discord_id: The Discord ID of the team member.\n :param on_vacation: The vacation status to be set for the team member.\n \"\"\"\n # Update the vacation status in the database\n self.db.set_vacation_status(discord_id, on_vacation)\n\n # Find the member in the team_members list and update their vacation status\n member = self.find_member(discord_id)\n if member:\n member.on_vacation = on_vacation" }, { "identifier": "UpdatesManager", "path": "updates/updates_manager.py", "snippet": "class UpdatesManager:\n \"\"\"\n Manages status updates for team members.\n \"\"\"\n\n def __init__(self, updates_db: UpdatesDB):\n \"\"\"\n Initializes a new UpdatesManager instance.\n\n Args:\n updates_db: The UpdatesDB object that handles database operations.\n \"\"\"\n self.updates_db = updates_db\n\n def insert_status(self, discord_id: int, status: str, time_zone: str):\n \"\"\"\n Inserts a new status update.\n\n Args:\n discord_id: The Discord ID of the team member.\n status: The status update.\n \"\"\"\n self.updates_db.insert_status(discord_id, status, time_zone)\n\n def update_summarized_status(self, discord_id: int, summarized_status: str):\n \"\"\"\n Updates the summarized status for the most recent update for a given user.\n\n Args:\n discord_id: The Discord ID of the team member.\n summarized_status: The summarized status update.\n \"\"\"\n self.updates_db.update_summarized_status(discord_id, summarized_status)\n\n def get_weekly_checkins_count(self, discord_id: int, time_zone: str) -> int:\n \"\"\"\n Fetches the number of check-ins for a given user in the current week.\n\n Args:\n discord_id: The Discord ID of the user.\n time_zone: The time zone of the user.\n\n Returns:\n The count of check-ins in the current week.\n \"\"\"\n return self.updates_db.get_weekly_checkins_count(discord_id, time_zone)\n \n def get_all_statuses_for_user(self, discord_id: int) -> List[dict]:\n \"\"\"\n Fetches all status updates (both raw and summarized) for a given user.\n\n Args:\n discord_id: The Discord ID of the user.\n\n Returns:\n A list of dictionaries, each containing the status update details for a given record.\n \"\"\"\n return self.updates_db.get_all_statuses_for_user(discord_id)\n\n def get_last_update_timestamp(self, discord_id: int) -> Tuple[datetime, str]:\n \"\"\"\n Fetches the timestamp and time zone of the last status update for a given user.\n\n Args:\n discord_id: The Discord ID of the user.\n\n Returns:\n A tuple containing the timestamp of the last update and its time zone, or (None, None) if there are no updates.\n \"\"\"\n return self.updates_db.get_last_update_timestamp(discord_id)\n\n def delete_newest_status(self, discord_id: int) -> None:\n \"\"\"\n Deletes the most recent status update for a given user.\n\n Args:\n discord_id: The Discord ID of the user.\n \"\"\"\n self.updates_db.delete_newest_status(discord_id)\n\n async def generate_daily_summary(self, user_message: str) -> str:\n \"\"\"\n Generates a daily summary of the user's message using a large language model.\n\n Args:\n user_message: The user's message that needs to be summarized.\n\n Returns:\n The summarized message.\n \"\"\"\n # Prepare a system message to guide OpenAI's model\n system_message = \"Please summarize the user's update into two sections: 'Did' for tasks completed yesterday and 'Do' for tasks planned for today.\"\n \n # Prepare the messages input for ChatCompletion\n messages = [\n {\"role\": \"system\", \"content\": system_message},\n {\"role\": \"user\", \"content\": user_message}\n ]\n \n # Specify the model engine you want to use\n model_engine = \"gpt-3.5-turbo-1106\"\n \n try:\n # Make an API call to OpenAI's ChatCompletion\n response = openai.ChatCompletion.create(\n model=model_engine,\n messages=messages\n )\n \n # Extract the generated text\n summarized_message = response['choices'][0]['message']['content'].strip()\n\n return summarized_message\n \n except Exception as e:\n print(f\"An error occurred while generating the summary: {e}\")\n return \"Error in generating summary\"\n\n async def generate_weekly_summary(self, discord_id: int, start_date: datetime, end_date: datetime) -> str:\n \"\"\"\n Generates a weekly summary of the user's status updates using a large language model.\n\n Args:\n discord_id: The Discord ID of the user.\n start_date: The start date of the date range.\n end_date: The end date of the date range.\n\n Returns:\n The summarized weekly status update.\n \"\"\"\n # Fetch all raw status updates for the specified date range using the new method in UpdatesDB\n weekly_statuses = self.updates_db.get_statuses_in_date_range(discord_id, start_date, end_date)\n\n if not weekly_statuses:\n return \"There are no status updates for this week.\"\n \n # Combine all raw statuses into a single string\n combined_statuses = \"\\n\".join(weekly_statuses)\n \n # Prepare a system message to guide OpenAI's model for weekly summary\n system_message = \"Please generate a comprehensive weekly summary based on the provided daily status updates, including only tasks that have been accomplished. Ignore tasks that are not in the 'Did' section.\"\n \n # Prepare the messages input for ChatCompletion\n messages = [\n {\"role\": \"system\", \"content\": system_message},\n {\"role\": \"user\", \"content\": combined_statuses}\n ]\n \n # Specify the model engine you want to use\n model_engine = \"gpt-4-0613\"\n \n try:\n # Make an API call to OpenAI's ChatCompletion\n response = openai.ChatCompletion.create(\n model=model_engine,\n messages=messages\n )\n \n # Extract the generated text\n weekly_summary = response['choices'][0]['message']['content'].strip()\n\n return weekly_summary\n \n except Exception as e:\n print(f\"An error occurred while generating the weekly summary: {e}\")\n return \"Error in generating weekly summary\"\n \n async def summarize_technical_updates(self, commit_messages: List[str]) -> str:\n \"\"\"\n Summarizes the technical updates based on commit messages.\n\n Args:\n commit_messages: List of commit messages for the day.\n\n Returns:\n A summarized version of the technical updates.\n \"\"\"\n\n # Combine commit messages into a single string for the LLM\n combined_commits = \"\\n\".join(commit_messages)\n\n # If there are no commit messages, return a default message\n if not combined_commits:\n return \"No technical updates found based on commit messages.\"\n\n # Summarization using LLM\n system_message = \"Please provide a concise summary of the technical updates based on the provided commit messages.\"\n\n messages = [\n {\"role\": \"system\", \"content\": system_message},\n {\"role\": \"user\", \"content\": combined_commits}\n ]\n\n model_engine = \"gpt-3.5-turbo-1106\"\n\n try:\n response = openai.ChatCompletion.create(\n model=model_engine,\n messages=messages\n )\n\n # Extract the generated summary\n summarized_message = response['choices'][0]['message']['content'].strip()\n\n return summarized_message\n\n except Exception as e:\n print(f\"An error occurred while generating the technical summary: {e}\")\n return \"Error in generating technical summary.\"\n\n async def summarize_feedback_and_revisions(self, original_report: str, feedback: str) -> str:\n \"\"\"\n Takes the original report and user feedback and generates a revised summary.\n\n Args:\n original_report: The original summarized report.\n feedback: The user's feedback or suggested edits.\n\n Returns:\n The revised summary.\n \"\"\"\n # Prepare a system message to guide OpenAI's model\n system_message = \"Revise the original report based on the user's feedback.\"\n\n # Prepare the messages input for ChatCompletion\n messages = [\n {\"role\": \"system\", \"content\": system_message},\n {\"role\": \"user\", \"content\": f\"Original Report: {original_report}\"},\n {\"role\": \"user\", \"content\": f\"Feedback: {feedback}\"}\n ]\n \n # Specify the model engine you want to use\n model_engine = \"gpt-3.5-turbo-1106\"\n \n try:\n # Make an API call to OpenAI's ChatCompletion\n response = openai.ChatCompletion.create(\n model=model_engine,\n messages=messages\n )\n \n # Extract the generated text\n revised_summary = response['choices'][0]['message']['content'].strip()\n\n return revised_summary\n \n except Exception as e:\n print(f\"An error occurred while generating the revised summary: {e}\")\n return \"Error in generating revised summary\"\n\n async def summarize_non_technical_updates(self, update: str) -> str:\n \"\"\"\n Summarizes a non-technical update using a large language model.\n\n Args:\n update: The raw non-technical update provided by the user.\n\n Returns:\n The summarized non-technical update.\n \"\"\"\n\n # System message to guide the LLM for a concise summary\n system_message = \"Please provide a concise summary of the non-technical update shared by the user.\"\n\n # Prepare the messages input for ChatCompletion\n messages = [\n {\"role\": \"system\", \"content\": system_message},\n {\"role\": \"user\", \"content\": update}\n ]\n\n # Specify the model engine you want to use\n model_engine = \"gpt-3.5-turbo-1106\"\n\n try:\n # Make an API call to OpenAI's ChatCompletion\n response = openai.ChatCompletion.create(\n model=model_engine,\n messages=messages\n )\n\n # Extract the generated summary\n summarized_message = response['choices'][0]['message']['content'].strip()\n\n return summarized_message\n\n except Exception as e:\n print(f\"An error occurred while generating the non-technical summary: {e}\")\n return \"Error in generating summary\"\n\n async def summarize_goals_for_the_day(self, goals: str) -> str:\n \"\"\"\n Summarizes the user's goals for the day using a large language model.\n\n Args:\n goals: The user's raw input on their goals for the day.\n\n Returns:\n The summarized goals for the day.\n \"\"\"\n # Initiate the conversation with the model\n system_message = \"Please provide a concise summary of the user's goals for today.\"\n \n # Prepare the messages input for ChatCompletion\n messages = [\n {\"role\": \"system\", \"content\": system_message},\n {\"role\": \"user\", \"content\": goals}\n ]\n \n # Specify the model engine you want to use (this is an example and can be adjusted based on your needs)\n model_engine = \"gpt-3.5-turbo-1106\"\n \n try:\n # Provide user's input and retrieve model's response\n response = openai.ChatCompletion.create(\n model=model_engine,\n messages=messages\n )\n \n # Extract the generated text\n summarized_goals = response['choices'][0]['message']['content'].strip()\n\n # Return the summary\n return summarized_goals\n \n except Exception as e:\n print(f\"An error occurred while generating the goals summary: {e}\")\n return \"Error in generating goals summary\"\n \n async def evaluate_performance(self, user_message: str) -> str:\n \"\"\"\n Evaluates the performance of the user based on their update.\n\n Args:\n user_message: The user's message that needs to be evaluated.\n\n Returns:\n The evaluation of the user's performance.\n \"\"\"\n # Prepare a system message to guide OpenAI's model\n system_message = \"\"\"\n You are a project manager at a fast-paced tech startup, recognized for providing clear and actionable feedback during stand-up meetings. Your role is to evaluate the quality of team members' daily stand-up reports, with a focus on clear communication, comprehensive planning, and problem-solving abilities.\n It is essential to note that team members should neither be penalized nor rewarded for merely mentioning issues; instead, the emphasis should be on the clarity of the report and the quality of strategies proposed to address these issues.\n Your feedback is candid and aimed at encouraging high-quality reporting and effective planning within the startup environment.\n Please provide a two-sentence summary of the stand-up and assign a grade (A, B, C, D, or F) based on the following criteria:\n\n - A: Excellent - The report is exceptionally clear and detailed, with well-defined tasks and a thorough approach to tackling issues, exemplifying the proactive and problem-solving ethos of our startup.\n - B: Good - The report is clear and adequately detailed, outlining tasks and addressing issues with a reasonable approach, indicating a commitment to momentum and resolution.\n - C: Fair - The report is understandable but lacks detail in some areas, with a basic approach to resolving issues, suggesting a need for further strategy development.\n - D: Poor - The report is vague or missing details, with a limited or unclear approach to issues, necessitating better communication and planning skills.\n - F: Fail - The report is missing, overly vague, or lacks a coherent structure, with no apparent approach to issues, reflecting a need for significant improvement in reporting and strategizing.\n\n A comprehensive stand-up report effectively communicates what was done and what is planned, clearly identifies any issues, and connects daily tasks with broader business objectives.\n\n Provide clear and constructive feedback, aiming to foster a culture of excellence and continuous improvement in how we plan and communicate our daily activities.\n \"\"\"\n \n # Prepare the messages input for ChatCompletion\n messages = [\n {\"role\": \"system\", \"content\": system_message},\n {\"role\": \"user\", \"content\": user_message}\n ]\n \n # Specify the model engine you want to use\n model_engine = \"gpt-3.5-turbo-1106\"\n \n try:\n # Make an API call to OpenAI's ChatCompletion\n response = openai.ChatCompletion.create(\n model=model_engine,\n messages=messages\n )\n \n # Extract the generated text\n performance_evaluation = response['choices'][0]['message']['content'].strip()\n\n return performance_evaluation\n \n except Exception as e:\n print(f\"An error occurred while evaluating the performance: {e}\")\n return \"Error in evaluating performance\"" }, { "identifier": "WeeklyPostManager", "path": "weekly_posts/weekly_post_manager.py", "snippet": "class WeeklyPostManager:\n \"\"\"Manages the status post in a Discord channel.\"\"\"\n \n def __init__(self, channel, weekly_posts_db: WeeklyPostsDB):\n \"\"\"\n Initializes a new WeeklyPostManager instance.\n \"\"\"\n self.channel = channel\n self.weekly_posts_db = weekly_posts_db\n self.editable_weekly_post = None\n self.load_weekly_post_data()\n\n def load_weekly_post_data(self):\n \"\"\"\n Load the weekly post data from the database.\n \n This method queries the 'weekly_posts' table to get the ID and timestamp of \n the last weekly post. If no data exists, it sets the ID and timestamp to None.\n \"\"\"\n data = self.weekly_posts_db.get_weekly_post_data()\n self.editable_weekly_post_id = data.get('post_id', None)\n self.weekly_post_timestamp = data.get('timestamp', None)\n\n def save_weekly_post_data(self):\n \"\"\"\n Save the weekly post data to the database.\n \n This method inserts or updates the ID and timestamp of the current weekly post \n in the 'weekly_posts' table.\n \"\"\"\n self.weekly_posts_db.save_weekly_post_data(self.editable_weekly_post.id, datetime.now())\n\n async def initialize_post(self, team_members: List[TeamMember]):\n \"\"\"\n Initializes or retrieves the weekly status post on Discord.\n\n This function checks if a valid weekly post already exists for the current week.\n If it does, it retrieves that post. Otherwise, it sends a new message in the Discord\n channel with the list of team members and their statuses.\n\n Args:\n team_members: A list of TeamMember objects to be displayed in the post.\n \"\"\"\n current_week_number = datetime.now().isocalendar()[1]\n saved_week_number = self.weekly_post_timestamp.isocalendar()[1] if self.weekly_post_timestamp else None\n\n # Skip initialization if the post already exists and is for the current week\n if self.editable_weekly_post_id and current_week_number == saved_week_number:\n self.editable_weekly_post = await self.channel.fetch_message(self.editable_weekly_post_id)\n return\n\n utc_now = pytz.utc.localize(datetime.utcnow())\n today_weekday = utc_now.weekday()\n last_monday = utc_now - timedelta(days=today_weekday)\n next_sunday = last_monday + timedelta(days=6)\n\n start_date = self.format_date(last_monday)\n end_date = self.format_date(next_sunday)\n\n # Calculate the max name length for alignment purposes\n max_name_length = max([len(m.name) for m in team_members])\n\n member_list = []\n for m in team_members:\n # Include the streak with the fire emoji if the streak is greater than 0\n streak_str = f\" {m.current_streak}🔥\" if m.current_streak > 0 else \"\"\n\n # Construct the new line for the member with the updated information\n new_line = f\"# `{m.name.ljust(max_name_length)} {'❓' * 5} {streak_str}`\"\n member_list.append(new_line)\n\n member_list_str = '\\n'.join(member_list)\n\n await self.channel.send(f\"# Weekly Status Updates\")\n await self.channel.send(f\"## {start_date} to {end_date}\")\n if member_list_str:\n self.editable_weekly_post = await self.channel.send(f\"{member_list_str}\")\n self.save_weekly_post_data() # Save the ID and timestamp after creating the post\n\n async def rebuild_post(self, team_members: List[TeamMember]):\n \"\"\"\n Rebuilds the entire weekly status post from the team members' data.\n\n Args:\n team_members: A list of TeamMember objects with updated statuses and streaks.\n \"\"\"\n # If there are no team members, delete the post and return\n if not team_members:\n if self.editable_weekly_post:\n await self.editable_weekly_post.delete()\n self.editable_weekly_post = None\n return\n\n # Calculate the max name length for alignment purposes\n max_name_length = max([len(m.name) for m in team_members])\n\n member_list = []\n for m in team_members:\n # Get the streak and number of weekly check-ins for the member\n streak = m.current_streak\n check_ins = m.weekly_checkins\n\n # Generate the marks based on the number of check-ins\n marks = \"✅\" * check_ins + \"❓\" * (5 - check_ins)\n\n # Include the streak with the fire emoji if the streak is greater than 0\n streak_str = f\" {streak}🔥\" if streak > 0 else \"\"\n\n # Construct the new line for the member with the updated information\n new_line = f\"# `{m.name.ljust(max_name_length)} {marks} {streak_str}`\"\n member_list.append(new_line)\n\n new_content = '\\n'.join(member_list)\n\n # Update the existing post or create a new one if it doesn't exist\n if self.editable_weekly_post:\n self.editable_weekly_post = await self.editable_weekly_post.edit(content=new_content)\n else:\n self.editable_weekly_post = await self.channel.send(new_content)\n\n # Save the ID and timestamp of the post\n self.save_weekly_post_data()\n\n def format_date(self, dt: datetime) -> str:\n \"\"\"\n Formats a datetime object into a human-readable string.\n\n Args:\n dt: The datetime object to format.\n\n Returns:\n A human-readable date string.\n \"\"\"\n suffix = ['th', 'st', 'nd', 'rd']\n day = int(dt.strftime('%d'))\n if 4 <= day <= 20 or 24 <= day <= 30:\n suffix_index = 0 # use 'th'\n else:\n suffix_index = day % 10 # use 'st', 'nd', 'rd' as appropriate\n\n return dt.strftime(f\"%B {day}{suffix[suffix_index]}\")" }, { "identifier": "Scheduler", "path": "scheduler.py", "snippet": "class Scheduler:\n \"\"\"Scheduler class to manage timed jobs for sending status requests.\n\n Attributes:\n scheduler: The APScheduler object.\n job_ids: A dictionary to store lists of job IDs for each member.\n \"\"\"\n \n def __init__(self) -> None:\n \"\"\"Initialize the Scheduler object and start the APScheduler.\"\"\"\n self.scheduler: AsyncIOScheduler = AsyncIOScheduler()\n self.job_ids: Dict[int, List[str]] = {} # Store job IDs indexed by member's Discord ID\n self.weekly_post_job_id = None # To store the ID of the scheduled weekly post job\n self.scheduler.start()\n\n def add_job(self, func: callable, member: TeamMember, weekly_post_manager: WeeklyPostManager, streaks_manager: StreaksManager, updates_manager: UpdatesManager) -> None:\n \"\"\"Add a new job to the scheduler for a specific team member.\n \n Args:\n func: The function to call when the job is run.\n member: The TeamMember object for whom the job is added.\n \"\"\"\n time_zone = pytz.timezone(member.time_zone)\n \n weekday_trigger = CronTrigger(day_of_week='mon,tue,wed,thu,fri', hour=10, timezone=time_zone)\n weekend_trigger = CronTrigger(day_of_week='sat,sun', hour=11, timezone=time_zone)\n\n weekday_job = self.scheduler.add_job(func, weekday_trigger, args=[member, weekly_post_manager, streaks_manager, updates_manager])\n weekend_job = self.scheduler.add_job(func, weekend_trigger, args=[member, weekly_post_manager, streaks_manager, updates_manager])\n\n self.job_ids.setdefault(member.discord_id, []).extend([weekday_job.id, weekend_job.id])\n\n def remove_job(self, discord_id: int) -> None:\n \"\"\"Remove jobs for a specific team member.\n \n Args:\n discord_id: The Discord ID of the member for whom the job should be removed.\n \"\"\"\n job_ids = self.job_ids.get(discord_id, [])\n for job_id in job_ids:\n self.scheduler.remove_job(job_id)\n\n if discord_id in self.job_ids:\n del self.job_ids[discord_id] # Remove the job IDs from the dictionary\n\n def schedule_weekly_post(self, func: callable, weekly_post_manager: WeeklyPostManager, streaks_manager: StreaksManager, team_members: List[TeamMember]) -> None:\n \"\"\"Schedules the weekly post based on the latest time zone among the team members.\"\"\"\n \n # Determine the latest time zone\n latest_time_zone = max([member.time_zone for member in team_members], key=lambda tz: pytz.timezone(tz).utcoffset(datetime.utcnow()))\n\n # Set the trigger for 9:10 AM in the earliest time zone on Monday\n trigger = CronTrigger(day_of_week='mon', hour=9, minute=10, timezone=latest_time_zone)\n\n # Schedule the function with the trigger\n job = self.scheduler.add_job(func, trigger, args=[weekly_post_manager, streaks_manager, team_members])\n self.weekly_post_job_id = job.id\n\n def unschedule_weekly_post(self) -> None:\n \"\"\"Removes the weekly post job from the scheduler.\"\"\"\n if self.weekly_post_job_id:\n self.scheduler.remove_job(self.weekly_post_job_id)\n self.weekly_post_job_id = None\n\n def get_all_scheduled_jobs(self, team_member_manager) -> List[str]:\n \"\"\"Retrieve all scheduled jobs as a list of strings.\"\"\"\n job_descriptions = []\n\n for job in self.scheduler.get_jobs():\n # Determine the associated team member by looking up the job ID in the job_ids dictionary\n member_discord_id = next((discord_id for discord_id, job_ids in self.job_ids.items() if job.id in job_ids), None)\n member_name = team_member_manager.find_member(member_discord_id).name if member_discord_id else \"Unknown\"\n\n # Calculate the remaining time until the next run\n now = datetime.now(job.next_run_time.tzinfo) # Get the current time with the same timezone as the job's next_run_time\n remaining_time = job.next_run_time - now\n remaining_time_str = str(remaining_time).split('.')[0] # Remove the microseconds part\n\n # If this job is the weekly post job\n if job.id == self.weekly_post_job_id:\n job_descriptions.append(f\"ID: {job.id}, Type: Weekly Post, Next Run: {job.next_run_time}, Remaining Time: {remaining_time_str}, Func: {job.func.__name__}\")\n else:\n job_descriptions.append(f\"ID: {job.id}, Member: {member_name}, Next Run: {job.next_run_time}, Remaining Time: {remaining_time_str}, Func: {job.func.__name__}\")\n\n return job_descriptions" }, { "identifier": "TeamMember", "path": "team_members/team_member.py", "snippet": "class TeamMember:\n \"\"\"TeamMember class to store individual team member details.\n \n Attributes:\n discord_id: The Discord ID of the team member.\n time_zone: The time zone in which the team member resides.\n name: The name of the team member.\n github_username: The GitHub username of the team member.\n current_streak: The current streak of daily updates/check-ins of the team member.\n weekly_checkins: The number of check-ins for the current week.\n \"\"\"\n \n def __init__(self, discord_id: int, time_zone: str, name: str, github_username: str,\n current_streak: int = 0, weekly_checkins: int = 0, on_vacation: bool = False) -> None:\n \"\"\"Initialize a new TeamMember object.\n \n Args:\n discord_id: The Discord ID of the team member.\n time_zone: The time zone of the team member.\n name: The name of the team member.\n github_username: The GitHub username of the team member.\n current_streak: The current streak of daily updates/check-ins. Defaults to 0.\n weekly_checkins: The number of check-ins for the current week. Defaults to 0.\n \"\"\"\n self.discord_id: int = discord_id\n self.time_zone: str = time_zone\n self.name: str = name\n self.github_username: str = github_username\n self.current_streak: int = current_streak\n self.weekly_checkins: int = weekly_checkins\n self.on_vacation: bool = on_vacation\n \n def update_streak(self, streak: int) -> None:\n \"\"\"Update the current streak of the team member.\n \n Args:\n streak: The new streak count.\n \"\"\"\n self.current_streak = streak\n \n def reset_streak(self) -> None:\n \"\"\"Reset the current streak of the team member to 0.\"\"\"\n self.current_streak = 0\n\n def update_weekly_checkins(self, count: int):\n \"\"\"\n Update the weekly check-ins count.\n\n Args:\n count: The new count of weekly check-ins.\n \"\"\"\n self.weekly_checkins = count\n \n def increment_weekly_checkins(self) -> None:\n \"\"\"Increment the number of check-ins for the current week by 1.\"\"\"\n self.weekly_checkins += 1\n \n def reset_weekly_checkins(self) -> None:\n \"\"\"Reset the number of check-ins for the current week to 0.\"\"\"\n self.weekly_checkins = 0" } ]
import os import pytz import asyncio import openai import requests from typing import List from dotenv import load_dotenv from datetime import datetime, timedelta from multiprocessing import Process from streaks.streaks_db import StreaksDB from team_members.team_member_db import TeamMemberDB from updates.updates_db import UpdatesDB from weekly_posts.weekly_posts_db import WeeklyPostsDB from streaks.streaks_manager import StreaksManager from team_members.team_member_manager import TeamMemberManager from updates.updates_manager import UpdatesManager from weekly_posts.weekly_post_manager import WeeklyPostManager from scheduler import Scheduler from team_members.team_member import TeamMember from discord.ext import commands, tasks from discord import Intents, DMChannel from flask import Flask from asyncio import Task, ensure_future, CancelledError
15,369
await ctx.send("You're not authorized to update streaks.") return # Find the member object using the Discord ID member_to_update = team_member_manager.find_member(discord_id) if member_to_update: # Update the streak in the database streaks_manager.update_streak(discord_id, new_streak) member_to_update.update_streak(new_streak) # Update the Discord post using WeeklyPostManager await weekly_post_manager.rebuild_post(team_member_manager.team_members) await ctx.send(f"Streak for user with Discord ID {discord_id} updated to {new_streak}.") else: await ctx.send(f"No user with Discord ID {discord_id} found.") @bot.command(name='forcepostrebuild') async def force_post_rebuild(ctx): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to force a post rebuild.") return # Rebuild the post await weekly_post_manager.rebuild_post(team_member_manager.team_members) await ctx.send("Post rebuilt successfully.") @bot.command(name='deletelateststatus') async def delete_latest_status(ctx, discord_id: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to delete status updates.") return # Find the member object using the Discord ID member = team_member_manager.find_member(discord_id) if not member: await ctx.send(f"No user with Discord ID {discord_id} found.") return # Delete the newest status using the UpdatesManager's method updates_manager.delete_newest_status(discord_id) await ctx.send(f"Latest status update for user with Discord ID {discord_id} deleted successfully.") @bot.command(name='viewuser') async def view_user(ctx, discord_id: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to view user data.") return # Get the member's statuses using the UpdatesManager's method statuses = updates_manager.get_all_statuses_for_user(discord_id) if not statuses: await ctx.send(f"No status updates found for user with Discord ID {discord_id}.") return # Loop through the statuses and send individual messages for status in statuses: await ctx.send(f"### **Timestamp:** {status['timestamp']}") await ctx.send(f"### **Raw Status:** {status['status']}") await ctx.send(f"### **Summarized Status:** \n{status['summarized_status']}") @bot.command(name='setvacationstatus') async def set_vacation_status(ctx, discord_id: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to set vacation status.") return member = team_member_manager.find_member(discord_id) if member: new_status = not member.on_vacation team_member_manager.set_member_vacation_status(discord_id, new_status) await ctx.send(f"Vacation status for user with Discord ID {discord_id} set to {'on vacation' if new_status else 'not on vacation'}.") else: await ctx.send(f"No user with Discord ID {discord_id} found.") @bot.command(name='weeklysummary') async def weekly_summary(ctx, discord_id: int, start_date: str, end_date: str): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to generate weekly summaries.") return # Find the member object using the Discord ID member = team_member_manager.find_member(discord_id) if not member: await ctx.send(f"No user with Discord ID {discord_id} found.") return # Convert the start_date and end_date strings to datetime objects # Adjusting the date format to MM-DD-YYYY and setting the time try: start_date = datetime.strptime(start_date, '%m-%d-%Y') end_date = datetime.strptime(end_date, '%m-%d-%Y') # Setting the time to ensure the whole week is captured start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0) end_date = end_date.replace(hour=23, minute=59, second=59, microsecond=999999) except ValueError: await ctx.send("Invalid date format. Please use MM-DD-YYYY.") return # Generate the weekly summary weekly_summary = await updates_manager.generate_weekly_summary(discord_id, start_date, end_date) # Send the weekly summary to the admin user admin_user = bot.get_user(ADMIN_DISCORD_ID) if admin_user: await admin_user.send(f"**{member.name}'s Weekly Summary for {start_date.strftime('%m-%d-%Y')} to {end_date.strftime('%m-%d-%Y')}:**\n{weekly_summary}") else: await ctx.send("Unable to find the admin user.") @bot.event async def on_ready(): print("Bot is online!") # Log that the bot is online streaks_db = StreaksDB(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB, MYSQL_PORT)
# Import required modules app = Flask(__name__) # Load environment variables from the .env file load_dotenv() # Retrieve bot, guild, and channel tokens from environment variables BOT_TOKEN = os.getenv('DISCORD_BOT_TOKEN') GUILD_TOKEN = int(os.getenv('DISCORD_GUILD_TOKEN')) CHANNEL_TOKEN = int(os.getenv('DISCORD_CHANNEL_TOKEN')) ADMIN_DISCORD_ID = int(os.getenv('ADMIN_DISCORD_ID')) # Retrieve database credentials from environment variables MYSQL_HOST = os.getenv('MYSQL_HOST') MYSQL_USER = os.getenv('MYSQL_USER') MYSQL_PASSWORD = os.getenv('MYSQL_PASSWORD') MYSQL_DB = os.getenv('MYSQL_DB') MYSQL_PORT = os.getenv('MYSQL_PORT') ORG_NAME = os.getenv('GITHUB_ORG_NAME') ORG_TOKEN = os.getenv('GITHUB_ORG_TOKEN') OPENAI_API_KEY = os.getenv('OPENAI_API_KEY') # Initialize bot with default intents intents = Intents.default() intents.members = True intents.message_content = True bot = commands.Bot(command_prefix='!', intents=intents) openai.api_key = OPENAI_API_KEY # TODO: Remove these globals streaks_manager = None weekly_post_manager = None team_member_manager = None updates_manager = None scheduler = None ongoing_status_requests = {} THUMBS_UP_EMOJI = "👍" PENCIL_EMOJI = "✏️" REPORT_SUBMISSION_EMOJI = '📝' async def weekly_state_reset(weekly_post_manager: WeeklyPostManager, streaks_manager: StreaksManager, team_members: List[TeamMember]): # Reset streaks for the previous week for member in team_members: if not member.on_vacation and member.weekly_checkins < 5: streaks_manager.reset_streak(member.discord_id) member.reset_streak() member.reset_weekly_checkins() # Initialize new weekly post await weekly_post_manager.initialize_post(team_members) def get_all_commit_messages_for_user(org_name: str, token: str, member: TeamMember) -> list: """Retrieve all commit messages for a user across all repos in an organization from the last 24 hours.""" headers = { "Authorization": f"token {token}", "Accept": "application/vnd.github.v3+json" } last_update_timestamp, user_time_zone = updates_manager.get_last_update_timestamp(member.discord_id) if last_update_timestamp: # Convert the timestamp to UTC local_tz = pytz.timezone(user_time_zone) localized_timestamp = local_tz.localize(last_update_timestamp) utc_timestamp = localized_timestamp.astimezone(pytz.utc) # Format the timestamp for the GitHub API and append 'Z' since_date = utc_timestamp.isoformat() if not since_date.endswith('Z'): since_date = utc_timestamp.isoformat().replace('+00:00', '') + 'Z' else: # If no updates found, default to last 24 hours since_date = (datetime.utcnow() - timedelta(days=1)).isoformat() + 'Z' all_commit_messages = [] # Paginate through all repositories in the organization repos_url = f"https://api.github.com/orgs/{org_name}/repos?type=all&per_page=100" while repos_url: response = requests.get(repos_url, headers=headers) if response.status_code != 200: # Log error and break loop print(f"Failed to fetch repos: {response.status_code} {response.text}") break repos = response.json() # Iterate over each repository for repo in repos: repo_name = repo["name"] commits_url = f"https://api.github.com/repos/{org_name}/{repo_name}/commits?author={member.github_username}&since={since_date}&per_page=100" # Paginate through commits for the repository while commits_url: response = requests.get(commits_url, headers=headers) if response.status_code != 200: # Log error and continue to the next repository print(f"Failed to fetch commits for {repo_name}: {response.status_code} {response.text}") break commits = response.json() repo_commit_messages = [commit["commit"]["message"] for commit in commits] all_commit_messages.extend(repo_commit_messages) # Check for the 'next' link for commits pagination commits_url = get_pagination_link(response.headers, 'next') # Check for the 'next' link for repositories pagination repos_url = get_pagination_link(response.headers, 'next') return all_commit_messages def get_pagination_link(headers, rel): """Extract pagination link for the 'rel' type from the Link header.""" link = headers.get('Link', None) if link: links = link.split(', ') for link in links: if 'rel="{}"'.format(rel) in link: return link.split('; ')[0].strip('<>') return None async def send_status_request(member: TeamMember, weekly_post_manager: WeeklyPostManager, streaks_manager: StreaksManager, updates_manager: UpdatesManager): if member.weekly_checkins == 5: return # If already completed 5 check-ins, do nothing user = bot.get_user(member.discord_id) if user: # Notify the admin that a status request is being sent admin_user = bot.get_user(ADMIN_DISCORD_ID) if admin_user: await admin_user.send(f"Status request sent to {member.name}.") # Cancel the previous task if it exists ongoing_task: Task = ongoing_status_requests.get(member.discord_id) if ongoing_task: ongoing_task.cancel() # Retrieve all commit messages for the member commit_messages = get_all_commit_messages_for_user(ORG_NAME, ORG_TOKEN, member) if not commit_messages: summarized_report = "You have no commits for the previous working day." msg = f"{summarized_report}\nReact with {THUMBS_UP_EMOJI} to confirm, {PENCIL_EMOJI} to iterate with AI, or {REPORT_SUBMISSION_EMOJI} to submit your own report." else: summarized_report = await updates_manager.summarize_technical_updates(commit_messages) msg = f"Here's your summarized report based on your commits:\n{summarized_report}\nReact with {THUMBS_UP_EMOJI} to confirm, {PENCIL_EMOJI} to iterate with AI, or {REPORT_SUBMISSION_EMOJI} to submit your own report." raw_updates = summarized_report # Send initial message and wait for reaction await user.send( f"# Good morning {member.name}, time for your daily status update!\n" f"### I'm first going to check your commit messages and try to build a technical report for you.\n" f"### Next I will ask you for any non-technical updates from your previous work day.\n" f"### Finally I will ask you what you plan to work on today." ) sent_message = await user.send(msg) await sent_message.add_reaction(THUMBS_UP_EMOJI) await sent_message.add_reaction(PENCIL_EMOJI) await sent_message.add_reaction(REPORT_SUBMISSION_EMOJI) def check(m) -> bool: return m.author == user and isinstance(m.channel, DMChannel) # Store the new wait_for reaction task in the global dictionary ongoing_task = ensure_future(bot.wait_for('reaction_add', check=lambda r, u: u == user and r.message.id == sent_message.id and isinstance(r.message.channel, DMChannel) and str(r.emoji) in [THUMBS_UP_EMOJI, PENCIL_EMOJI, REPORT_SUBMISSION_EMOJI])) ongoing_status_requests[member.discord_id] = ongoing_task reaction, reactor = await ongoing_task ongoing_status_requests.pop(member.discord_id, None) # Remove the task once we get the reaction for emoji in [THUMBS_UP_EMOJI, PENCIL_EMOJI, REPORT_SUBMISSION_EMOJI]: await sent_message.remove_reaction(emoji, bot.user) while str(reaction.emoji) in [PENCIL_EMOJI, REPORT_SUBMISSION_EMOJI]: if str(reaction.emoji) == PENCIL_EMOJI: await user.send("What would you like me to change?") # Store the new wait_for message (feedback) task in the global dictionary ongoing_task = ensure_future(bot.wait_for('message', check=check)) ongoing_status_requests[member.discord_id] = ongoing_task feedback = await ongoing_task ongoing_status_requests.pop(member.discord_id, None) # Remove the task once we get the feedback # Send original + feedback to LLM for reformatting summarized_report = await updates_manager.summarize_feedback_and_revisions(summarized_report, feedback.content) elif str(reaction.emoji) == REPORT_SUBMISSION_EMOJI: await user.send("Please submit your technical report directly.") # Store the new wait_for message (report submission) task in the global dictionary ongoing_task = ensure_future(bot.wait_for('message', check=check)) ongoing_status_requests[member.discord_id] = ongoing_task direct_report = await ongoing_task ongoing_status_requests.pop(member.discord_id, None) # Remove the task once we get the report summarized_report = direct_report.content break # Exit the while loop as the user has submitted their report directly msg = f"Here's the revised report:\n{summarized_report}\nReact with {THUMBS_UP_EMOJI} to confirm, {PENCIL_EMOJI} to iterate with AI, or {REPORT_SUBMISSION_EMOJI} to submit your own report." last_sent_message = await send_long_message(user, msg) if last_sent_message: await last_sent_message.add_reaction(THUMBS_UP_EMOJI) await last_sent_message.add_reaction(PENCIL_EMOJI) await last_sent_message.add_reaction(REPORT_SUBMISSION_EMOJI) # Store the new wait_for reaction task in the global dictionary ongoing_task = ensure_future(bot.wait_for('reaction_add', check=lambda r, u: u == user and r.message.id == last_sent_message.id and isinstance(r.message.channel, DMChannel) and str(r.emoji) in [THUMBS_UP_EMOJI, PENCIL_EMOJI, REPORT_SUBMISSION_EMOJI])) ongoing_status_requests[member.discord_id] = ongoing_task reaction, user = await ongoing_task ongoing_status_requests.pop(member.discord_id, None) # Remove the task once we get the reaction for emoji in [THUMBS_UP_EMOJI, PENCIL_EMOJI, REPORT_SUBMISSION_EMOJI]: await last_sent_message.remove_reaction(emoji, bot.user) # Prompt user for non-technical updates from the previous day non_technical_msg_prompt = "Please provide any non-technical updates from your previous working day, e.g., important meetings, interviews, etc." await user.send(non_technical_msg_prompt) # Store the new wait_for message (non-technical update) task in the global dictionary ongoing_task = ensure_future(bot.wait_for('message', check=check)) ongoing_status_requests[member.discord_id] = ongoing_task non_technical_update_raw = await ongoing_task ongoing_status_requests.pop(member.discord_id, None) # Remove the task once we get the non-technical update raw_updates += f"\n\n{non_technical_update_raw.content}" # Summarize non-technical update with LLM non_technical_update = await updates_manager.summarize_non_technical_updates(non_technical_update_raw.content) # Prompt user for their goals for the day goals_msg_prompt = "What do you plan to work on or accomplish today?" await user.send(goals_msg_prompt) # Store the new wait_for message (goals for the day) task in the global dictionary ongoing_task = ensure_future(bot.wait_for('message', check=check)) ongoing_status_requests[member.discord_id] = ongoing_task goals_for_today_raw = await ongoing_task ongoing_status_requests.pop(member.discord_id, None) # Remove the task once we get the goals # Summarize goals for the day with LLM goals_for_today = await updates_manager.summarize_goals_for_the_day(goals_for_today_raw.content) # Update the streak for this member streak = streaks_manager.get_streak(member.discord_id) streaks_manager.update_streak(member.discord_id, streak + 1) member.update_streak(streaks_manager.get_streak(member.discord_id)) member.increment_weekly_checkins() raw_updates += f"\n\n{goals_for_today_raw.content}" final_updates = f"{summarized_report}\n\n{non_technical_update}\n\n{goals_for_today}" updates_manager.insert_status(member.discord_id, raw_updates, member.time_zone) updates_manager.update_summarized_status(member.discord_id, final_updates) # Update the Discord post using WeeklyPostManager await weekly_post_manager.rebuild_post(team_member_manager.team_members) # Member name update as a header member_update_header = f"## {member.name}'s Update:" # Compile the final report with Markdown formatting final_report = ( f"\n### Technical Update:\n" f"{summarized_report}\n" f"### Non-Technical Update:\n" f"{non_technical_update}\n" f"### Goals for Today:\n" f"{goals_for_today}" ) stand_up_feedback = await updates_manager.evaluate_performance(final_report) # Concatenate the member name update with the final report and send to the designated Discord channel complete_message = f"{member_update_header}{final_report}" guild = bot.get_guild(GUILD_TOKEN) channel_to_post_in = guild.get_channel(CHANNEL_TOKEN) await user.send(stand_up_feedback) await send_long_message(channel_to_post_in, complete_message) async def send_long_message(destination, msg): max_length = 2000 # Discord's max character limit for a message sent_messages = [] # Keep track of all messages sent while len(msg) > 0: # If the message is shorter than the max length, send it as is if len(msg) <= max_length: sent_message = await destination.send(msg) sent_messages.append(sent_message) break # The message is sent, so break out of the loop # Find the nearest newline character before the max_length split_index = msg.rfind('\n', 0, max_length) # If no newline is found, just split at max_length if split_index == -1: split_index = max_length # Split the message at the found index and send the first part part_to_send = msg[:split_index].strip() sent_message = await destination.send(part_to_send) sent_messages.append(sent_message) # Wait a bit to respect Discord's rate limits await asyncio.sleep(1) # Remove the part that was sent from the message msg = msg[split_index:].strip() # Return the last message sent for reaction addition return sent_messages[-1] if sent_messages else None @bot.command(name='viewscheduledjobs') async def view_scheduled_jobs(ctx): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to view scheduled jobs.") return # Get all scheduled jobs using the Scheduler's method scheduled_jobs = scheduler.get_all_scheduled_jobs(team_member_manager) # Send the scheduled jobs to the admin user for job in scheduled_jobs: await ctx.send(job) @bot.command(name='statusrequest') async def status_request(ctx, discord_id: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to request status.") return # Find the member object using the Discord ID member_to_request = team_member_manager.find_member(discord_id) if member_to_request: for member in team_member_manager.team_members: scheduler.remove_job(member.discord_id) scheduler.unschedule_weekly_post() # Send the status request to the member await ctx.send(f"Status request sent to user with Discord ID {discord_id}.") for member in team_member_manager.team_members: scheduler.add_job(send_status_request, member, weekly_post_manager, streaks_manager, updates_manager) scheduler.schedule_weekly_post(weekly_state_reset, weekly_post_manager, streaks_manager, team_member_manager.team_members) await send_status_request(member_to_request, weekly_post_manager, streaks_manager, updates_manager) await ctx.send(f"Status request received from user with Discord ID {discord_id}.") else: await ctx.send(f"No user with Discord ID {discord_id} found.") @bot.command(name='adduser') async def add_user(ctx, discord_id: int, time_zone: str, name: str, github_username: str): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to add users.") return # Add the new member using team_member_manager team_member_manager.add_member(discord_id, name, time_zone, github_username) # Update the weekly post to include the new member new_member = team_member_manager.find_member(discord_id) if new_member: await weekly_post_manager.rebuild_post(team_member_manager.team_members) scheduler.add_job(send_status_request, new_member, weekly_post_manager, streaks_manager, updates_manager) scheduler.unschedule_weekly_post() scheduler.schedule_weekly_post(weekly_state_reset, weekly_post_manager, streaks_manager, team_member_manager.team_members) await ctx.send(f"User {name} added successfully.") @bot.command(name='removeuser') async def remove_user(ctx, discord_id: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to remove users.") return # Find the member object member_to_remove = team_member_manager.find_member(discord_id) if member_to_remove: # Remove the member from the database team_member_manager.remove_member(discord_id) # Update the weekly post to remove the member await weekly_post_manager.rebuild_post(team_member_manager.team_members) scheduler.remove_job(discord_id) scheduler.unschedule_weekly_post() scheduler.schedule_weekly_post(weekly_state_reset, weekly_post_manager, streaks_manager, team_member_manager.team_members) await ctx.send(f"User with Discord ID {discord_id} removed successfully.") else: await ctx.send(f"No user with Discord ID {discord_id} found.") @bot.command(name='listusers') async def list_users(ctx): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to list users.") return # List users using team_member_manager users = [(member.discord_id, member.name, member.time_zone, member.github_username, member.current_streak) for member in team_member_manager.team_members] user_list = '\n'.join([f"Name: {user[1]}, Discord ID: {user[0]}, Time Zone: {user[2]}, GitHub Username: {user[3]}, Current Streak: {user[4]}" for user in users]) await ctx.send(f"List of users:\n{user_list}") @bot.command(name='updatetimezone') async def update_timezone(ctx, discord_id: int, new_time_zone: str): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to update timezones.") return # Find the member object using the Discord ID member_to_update = team_member_manager.find_member(discord_id) if member_to_update: # Update the timezone in the database team_member_manager.update_member_timezone(discord_id, new_time_zone) scheduler.remove_job(discord_id) scheduler.add_job(send_status_request, member_to_update, weekly_post_manager, streaks_manager, updates_manager) scheduler.unschedule_weekly_post() scheduler.schedule_weekly_post(weekly_state_reset, weekly_post_manager, streaks_manager, team_member_manager.team_members) await ctx.send(f"Timezone for user with Discord ID {discord_id} updated to {new_time_zone}.") else: await ctx.send(f"No user with Discord ID {discord_id} found.") @bot.command(name='updatestreak') async def update_streak(ctx, discord_id: int, new_streak: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to update streaks.") return # Find the member object using the Discord ID member_to_update = team_member_manager.find_member(discord_id) if member_to_update: # Update the streak in the database streaks_manager.update_streak(discord_id, new_streak) member_to_update.update_streak(new_streak) # Update the Discord post using WeeklyPostManager await weekly_post_manager.rebuild_post(team_member_manager.team_members) await ctx.send(f"Streak for user with Discord ID {discord_id} updated to {new_streak}.") else: await ctx.send(f"No user with Discord ID {discord_id} found.") @bot.command(name='forcepostrebuild') async def force_post_rebuild(ctx): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to force a post rebuild.") return # Rebuild the post await weekly_post_manager.rebuild_post(team_member_manager.team_members) await ctx.send("Post rebuilt successfully.") @bot.command(name='deletelateststatus') async def delete_latest_status(ctx, discord_id: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to delete status updates.") return # Find the member object using the Discord ID member = team_member_manager.find_member(discord_id) if not member: await ctx.send(f"No user with Discord ID {discord_id} found.") return # Delete the newest status using the UpdatesManager's method updates_manager.delete_newest_status(discord_id) await ctx.send(f"Latest status update for user with Discord ID {discord_id} deleted successfully.") @bot.command(name='viewuser') async def view_user(ctx, discord_id: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to view user data.") return # Get the member's statuses using the UpdatesManager's method statuses = updates_manager.get_all_statuses_for_user(discord_id) if not statuses: await ctx.send(f"No status updates found for user with Discord ID {discord_id}.") return # Loop through the statuses and send individual messages for status in statuses: await ctx.send(f"### **Timestamp:** {status['timestamp']}") await ctx.send(f"### **Raw Status:** {status['status']}") await ctx.send(f"### **Summarized Status:** \n{status['summarized_status']}") @bot.command(name='setvacationstatus') async def set_vacation_status(ctx, discord_id: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to set vacation status.") return member = team_member_manager.find_member(discord_id) if member: new_status = not member.on_vacation team_member_manager.set_member_vacation_status(discord_id, new_status) await ctx.send(f"Vacation status for user with Discord ID {discord_id} set to {'on vacation' if new_status else 'not on vacation'}.") else: await ctx.send(f"No user with Discord ID {discord_id} found.") @bot.command(name='weeklysummary') async def weekly_summary(ctx, discord_id: int, start_date: str, end_date: str): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to generate weekly summaries.") return # Find the member object using the Discord ID member = team_member_manager.find_member(discord_id) if not member: await ctx.send(f"No user with Discord ID {discord_id} found.") return # Convert the start_date and end_date strings to datetime objects # Adjusting the date format to MM-DD-YYYY and setting the time try: start_date = datetime.strptime(start_date, '%m-%d-%Y') end_date = datetime.strptime(end_date, '%m-%d-%Y') # Setting the time to ensure the whole week is captured start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0) end_date = end_date.replace(hour=23, minute=59, second=59, microsecond=999999) except ValueError: await ctx.send("Invalid date format. Please use MM-DD-YYYY.") return # Generate the weekly summary weekly_summary = await updates_manager.generate_weekly_summary(discord_id, start_date, end_date) # Send the weekly summary to the admin user admin_user = bot.get_user(ADMIN_DISCORD_ID) if admin_user: await admin_user.send(f"**{member.name}'s Weekly Summary for {start_date.strftime('%m-%d-%Y')} to {end_date.strftime('%m-%d-%Y')}:**\n{weekly_summary}") else: await ctx.send("Unable to find the admin user.") @bot.event async def on_ready(): print("Bot is online!") # Log that the bot is online streaks_db = StreaksDB(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB, MYSQL_PORT)
team_member_db = TeamMemberDB(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB, MYSQL_PORT)
1
2023-10-12 02:01:46+00:00
24k
azuline/rose
rose/cache_test.py
[ { "identifier": "TEST_COLLAGE_1", "path": "conftest.py", "snippet": "TEST_COLLAGE_1 = TESTDATA / \"Collage 1\"" }, { "identifier": "TEST_PLAYLIST_1", "path": "conftest.py", "snippet": "TEST_PLAYLIST_1 = TESTDATA / \"Playlist 1\"" }, { "identifier": "TEST_RELEASE_1", "path": "conftest.py", "snippet": "TEST_RELEASE_1 = TESTDATA / \"Test Release 1\"" }, { "identifier": "TEST_RELEASE_2", "path": "conftest.py", "snippet": "TEST_RELEASE_2 = TESTDATA / \"Test Release 2\"" }, { "identifier": "TEST_RELEASE_3", "path": "conftest.py", "snippet": "TEST_RELEASE_3 = TESTDATA / \"Test Release 3\"" }, { "identifier": "AudioTags", "path": "rose/audiotags.py", "snippet": "class AudioTags:\n id: str | None\n release_id: str | None\n title: str | None\n year: int | None\n tracknumber: str | None\n tracktotal: int | None\n discnumber: str | None\n disctotal: int | None\n album: str | None\n genre: list[str]\n label: list[str]\n releasetype: str\n\n albumartists: ArtistMapping\n trackartists: ArtistMapping\n\n duration_sec: int\n\n path: Path\n\n @classmethod\n def from_file(cls, p: Path) -> AudioTags:\n \"\"\"Read the tags of an audio file on disk.\"\"\"\n if not any(p.suffix.lower() == ext for ext in SUPPORTED_AUDIO_EXTENSIONS):\n raise UnsupportedFiletypeError(f\"{p.suffix} not a supported filetype\")\n try:\n m = mutagen.File(p) # type: ignore\n except mutagen.MutagenError as e: # type: ignore\n raise UnsupportedFiletypeError(f\"Failed to open file: {e}\") from e\n if isinstance(m, mutagen.mp3.MP3):\n # ID3 returns trackno/discno tags as no/total. We have to parse.\n tracknumber = discnumber = tracktotal = disctotal = None\n if tracknos := _get_tag(m.tags, [\"TRCK\"]):\n try:\n tracknumber, tracktotalstr = tracknos.split(\"/\", 1)\n tracktotal = _parse_int(tracktotalstr)\n except ValueError:\n tracknumber = tracknos\n if discnos := _get_tag(m.tags, [\"TPOS\"]):\n try:\n discnumber, disctotalstr = discnos.split(\"/\", 1)\n disctotal = _parse_int(disctotalstr)\n except ValueError:\n discnumber = discnos\n\n def _get_paired_frame(x: str) -> str | None:\n if not m.tags:\n return None\n for tag in [\"TIPL\", \"IPLS\"]:\n try:\n frame = m.tags[tag]\n except KeyError:\n continue\n return r\" \\\\ \".join([p[1] for p in frame.people if p[0].lower() == x.lower()])\n return None\n\n return AudioTags(\n id=_get_tag(m.tags, [\"TXXX:ROSEID\"]),\n release_id=_get_tag(m.tags, [\"TXXX:ROSERELEASEID\"]),\n title=_get_tag(m.tags, [\"TIT2\"]),\n year=_parse_year(_get_tag(m.tags, [\"TDRC\", \"TYER\"])),\n tracknumber=tracknumber,\n tracktotal=tracktotal,\n discnumber=discnumber,\n disctotal=disctotal,\n album=_get_tag(m.tags, [\"TALB\"]),\n genre=_split_tag(_get_tag(m.tags, [\"TCON\"], split=True)),\n label=_split_tag(_get_tag(m.tags, [\"TPUB\"], split=True)),\n releasetype=_normalize_rtype(_get_tag(m.tags, [\"TXXX:RELEASETYPE\"], first=True)),\n albumartists=parse_artist_string(main=_get_tag(m.tags, [\"TPE2\"], split=True)),\n trackartists=parse_artist_string(\n main=_get_tag(m.tags, [\"TPE1\"], split=True),\n remixer=_get_tag(m.tags, [\"TPE4\"], split=True),\n composer=_get_tag(m.tags, [\"TCOM\"], split=True),\n conductor=_get_tag(m.tags, [\"TPE3\"], split=True),\n producer=_get_paired_frame(\"producer\"),\n dj=_get_paired_frame(\"DJ-mix\"),\n ),\n duration_sec=round(m.info.length),\n path=p,\n )\n if isinstance(m, mutagen.mp4.MP4):\n tracknumber = discnumber = tracktotal = disctotal = None\n with contextlib.suppress(ValueError):\n tracknumber, tracktotalstr = _get_tuple_tag(m.tags, [\"trkn\"]) # type: ignore\n tracktotal = _parse_int(tracktotalstr)\n with contextlib.suppress(ValueError):\n discnumber, disctotalstr = _get_tuple_tag(m.tags, [\"disk\"]) # type: ignore\n disctotal = _parse_int(disctotalstr)\n\n return AudioTags(\n id=_get_tag(m.tags, [\"----:net.sunsetglow.rose:ID\"]),\n release_id=_get_tag(m.tags, [\"----:net.sunsetglow.rose:RELEASEID\"]),\n title=_get_tag(m.tags, [\"\\xa9nam\"]),\n year=_parse_year(_get_tag(m.tags, [\"\\xa9day\"])),\n tracknumber=str(tracknumber),\n tracktotal=tracktotal,\n discnumber=str(discnumber),\n disctotal=disctotal,\n album=_get_tag(m.tags, [\"\\xa9alb\"]),\n genre=_split_tag(_get_tag(m.tags, [\"\\xa9gen\"], split=True)),\n label=_split_tag(_get_tag(m.tags, [\"----:com.apple.iTunes:LABEL\"], split=True)),\n releasetype=_normalize_rtype(\n _get_tag(m.tags, [\"----:com.apple.iTunes:RELEASETYPE\"], first=True)\n ),\n albumartists=parse_artist_string(main=_get_tag(m.tags, [\"aART\"], split=True)),\n trackartists=parse_artist_string(\n main=_get_tag(m.tags, [\"\\xa9ART\"], split=True),\n remixer=_get_tag(m.tags, [\"----:com.apple.iTunes:REMIXER\"], split=True),\n producer=_get_tag(m.tags, [\"----:com.apple.iTunes:PRODUCER\"], split=True),\n composer=_get_tag(m.tags, [\"\\xa9wrt\"], split=True),\n conductor=_get_tag(m.tags, [\"----:com.apple.iTunes:CONDUCTOR\"], split=True),\n dj=_get_tag(m.tags, [\"----:com.apple.iTunes:DJMIXER\"], split=True),\n ),\n duration_sec=round(m.info.length), # type: ignore\n path=p,\n )\n if isinstance(m, (mutagen.flac.FLAC, mutagen.oggvorbis.OggVorbis, mutagen.oggopus.OggOpus)):\n return AudioTags(\n id=_get_tag(m.tags, [\"roseid\"]),\n release_id=_get_tag(m.tags, [\"rosereleaseid\"]),\n title=_get_tag(m.tags, [\"title\"]),\n year=_parse_year(_get_tag(m.tags, [\"date\", \"year\"])),\n tracknumber=_get_tag(m.tags, [\"tracknumber\"], first=True),\n tracktotal=_parse_int(_get_tag(m.tags, [\"tracktotal\"], first=True)),\n discnumber=_get_tag(m.tags, [\"discnumber\"], first=True),\n disctotal=_parse_int(_get_tag(m.tags, [\"disctotal\"], first=True)),\n album=_get_tag(m.tags, [\"album\"]),\n genre=_split_tag(_get_tag(m.tags, [\"genre\"], split=True)),\n label=_split_tag(\n _get_tag(m.tags, [\"organization\", \"label\", \"recordlabel\"], split=True)\n ),\n releasetype=_normalize_rtype(_get_tag(m.tags, [\"releasetype\"], first=True)),\n albumartists=parse_artist_string(\n main=_get_tag(m.tags, [\"albumartist\"], split=True)\n ),\n trackartists=parse_artist_string(\n main=_get_tag(m.tags, [\"artist\"], split=True),\n remixer=_get_tag(m.tags, [\"remixer\"], split=True),\n producer=_get_tag(m.tags, [\"producer\"], split=True),\n composer=_get_tag(m.tags, [\"composer\"], split=True),\n conductor=_get_tag(m.tags, [\"conductor\"], split=True),\n dj=_get_tag(m.tags, [\"djmixer\"], split=True),\n ),\n duration_sec=round(m.info.length), # type: ignore\n path=p,\n )\n raise UnsupportedFiletypeError(f\"{p} is not a supported audio file\")\n\n @no_type_check\n def flush(self, *, validate: bool = True) -> None:\n \"\"\"Flush the current tags to the file on disk.\"\"\"\n m = mutagen.File(self.path)\n if not validate and \"pytest\" not in sys.modules:\n raise Exception(\"Validate can only be turned off by tests.\")\n\n self.releasetype = (self.releasetype or \"unknown\").lower()\n if validate and self.releasetype not in SUPPORTED_RELEASE_TYPES:\n raise UnsupportedTagValueTypeError(\n f\"Release type {self.releasetype} is not a supported release type.\\n\"\n f\"Supported release types: {', '.join(SUPPORTED_RELEASE_TYPES)}\"\n )\n\n if isinstance(m, mutagen.mp3.MP3):\n if m.tags is None:\n m.tags = mutagen.id3.ID3()\n\n def _write_standard_tag(key: str, value: str | None) -> None:\n m.tags.delall(key)\n frame = getattr(mutagen.id3, key)(text=value)\n if value:\n m.tags.add(frame)\n\n def _write_tag_with_description(name: str, value: str | None) -> None:\n key, desc = name.split(\":\", 1)\n # Since the ID3 tags work with the shared prefix key before `:`, manually preserve\n # the other tags with the shared prefix key.\n keep_fields = [f for f in m.tags.getall(key) if getattr(f, \"desc\", None) != desc]\n m.tags.delall(key)\n if value:\n frame = getattr(mutagen.id3, key)(desc=desc, text=value)\n m.tags.add(frame)\n for f in keep_fields:\n m.tags.add(f)\n\n _write_tag_with_description(\"TXXX:ROSEID\", self.id)\n _write_tag_with_description(\"TXXX:ROSERELEASEID\", self.release_id)\n _write_standard_tag(\"TIT2\", self.title)\n _write_standard_tag(\"TDRC\", str(self.year).zfill(4))\n _write_standard_tag(\"TRCK\", self.tracknumber)\n _write_standard_tag(\"TPOS\", self.discnumber)\n _write_standard_tag(\"TALB\", self.album)\n _write_standard_tag(\"TCON\", \";\".join(self.genre))\n _write_standard_tag(\"TPUB\", \";\".join(self.label))\n _write_tag_with_description(\"TXXX:RELEASETYPE\", self.releasetype)\n _write_standard_tag(\"TPE2\", format_artist_string(self.albumartists))\n _write_standard_tag(\"TPE1\", format_artist_string(self.trackartists))\n # Wipe the alt. role artist tags, since we encode the full artist into the main tag.\n m.tags.delall(\"TPE4\")\n m.tags.delall(\"TCOM\")\n m.tags.delall(\"TPE3\")\n # Delete all paired text frames, since these represent additional artist roles. We don't\n # want to preserve them.\n m.tags.delall(\"TIPL\")\n m.tags.delall(\"IPLS\")\n m.save()\n return\n if isinstance(m, mutagen.mp4.MP4):\n if m.tags is None:\n m.tags = mutagen.mp4.MP4Tags()\n m.tags[\"----:net.sunsetglow.rose:ID\"] = (self.id or \"\").encode()\n m.tags[\"----:net.sunsetglow.rose:RELEASEID\"] = (self.release_id or \"\").encode()\n m.tags[\"\\xa9nam\"] = self.title or \"\"\n m.tags[\"\\xa9day\"] = str(self.year).zfill(4)\n m.tags[\"\\xa9alb\"] = self.album or \"\"\n m.tags[\"\\xa9gen\"] = \";\".join(self.genre)\n m.tags[\"----:com.apple.iTunes:LABEL\"] = \";\".join(self.label).encode()\n m.tags[\"----:com.apple.iTunes:RELEASETYPE\"] = self.releasetype.encode()\n m.tags[\"aART\"] = format_artist_string(self.albumartists)\n m.tags[\"\\xa9ART\"] = format_artist_string(self.trackartists)\n # Wipe the alt. role artist tags, since we encode the full artist into the main tag.\n with contextlib.suppress(KeyError):\n del m.tags[\"----:com.apple.iTunes:REMIXER\"]\n with contextlib.suppress(KeyError):\n del m.tags[\"----:com.apple.iTunes:PRODUCER\"]\n with contextlib.suppress(KeyError):\n del m.tags[\"\\xa9wrt\"]\n with contextlib.suppress(KeyError):\n del m.tags[\"----:com.apple.iTunes:CONDUCTOR\"]\n with contextlib.suppress(KeyError):\n del m.tags[\"----:com.apple.iTunes:DJMIXER\"]\n\n # The track and disc numbers in MP4 are a bit annoying, because they must be a\n # single-element list of 2-tuple ints. We preserve the previous tracktotal/disctotal (as\n # Rose does not care about those values), and then attempt to write our own tracknumber\n # and discnumber.\n try:\n prev_tracktotal = m.tags[\"trkn\"][0][1]\n except (KeyError, IndexError):\n prev_tracktotal = 1\n try:\n prev_disctotal = m.tags[\"disk\"][0][1]\n except (KeyError, IndexError):\n prev_disctotal = 1\n try:\n m.tags[\"trkn\"] = [(int(self.tracknumber or \"0\"), prev_tracktotal)]\n m.tags[\"disk\"] = [(int(self.discnumber or \"0\"), prev_disctotal)]\n except ValueError as e:\n raise UnsupportedTagValueTypeError(\n \"Could not write m4a trackno/discno tags: must be integers. \"\n f\"Got: {self.tracknumber=} / {self.discnumber=}\"\n ) from e\n\n m.save()\n return\n if isinstance(m, (mutagen.flac.FLAC, mutagen.oggvorbis.OggVorbis, mutagen.oggopus.OggOpus)):\n if m.tags is None:\n if isinstance(m, mutagen.flac.FLAC):\n m.tags = mutagen.flac.VCFLACDict()\n elif isinstance(m, mutagen.oggvorbis.OggVorbis):\n m.tags = mutagen.oggvorbis.OggVCommentDict()\n else:\n m.tags = mutagen.oggopus.OggOpusVComment()\n assert not isinstance(m.tags, mutagen.flac.MetadataBlock)\n m.tags[\"roseid\"] = self.id or \"\"\n m.tags[\"rosereleaseid\"] = self.release_id or \"\"\n m.tags[\"title\"] = self.title or \"\"\n m.tags[\"date\"] = str(self.year).zfill(4)\n m.tags[\"tracknumber\"] = self.tracknumber or \"\"\n m.tags[\"discnumber\"] = self.discnumber or \"\"\n m.tags[\"album\"] = self.album or \"\"\n m.tags[\"genre\"] = \";\".join(self.genre)\n m.tags[\"organization\"] = \";\".join(self.label)\n m.tags[\"releasetype\"] = self.releasetype\n m.tags[\"albumartist\"] = format_artist_string(self.albumartists)\n m.tags[\"artist\"] = format_artist_string(self.trackartists)\n # Wipe the alt. role artist tags, since we encode the full artist into the main tag.\n with contextlib.suppress(KeyError):\n del m.tags[\"remixer\"]\n with contextlib.suppress(KeyError):\n del m.tags[\"producer\"]\n with contextlib.suppress(KeyError):\n del m.tags[\"composer\"]\n with contextlib.suppress(KeyError):\n del m.tags[\"conductor\"]\n with contextlib.suppress(KeyError):\n del m.tags[\"djmixer\"]\n m.save()\n return\n\n raise RoseError(f\"Impossible: unknown mutagen type: {type(m)=} ({repr(m)=})\")" }, { "identifier": "CACHE_SCHEMA_PATH", "path": "rose/cache.py", "snippet": "CACHE_SCHEMA_PATH = Path(__file__).resolve().parent / \"cache.sql\"" }, { "identifier": "STORED_DATA_FILE_REGEX", "path": "rose/cache.py", "snippet": "STORED_DATA_FILE_REGEX = re.compile(r\"\\.rose\\.([^.]+)\\.toml\")" }, { "identifier": "CachedCollage", "path": "rose/cache.py", "snippet": "class CachedCollage:\n name: str\n source_mtime: str\n release_ids: list[str]" }, { "identifier": "CachedPlaylist", "path": "rose/cache.py", "snippet": "class CachedPlaylist:\n name: str\n source_mtime: str\n cover_path: Path | None\n track_ids: list[str]" }, { "identifier": "CachedRelease", "path": "rose/cache.py", "snippet": "class CachedRelease:\n id: str\n source_path: Path\n cover_image_path: Path | None\n added_at: str # ISO8601 timestamp\n datafile_mtime: str\n albumtitle: str\n releasetype: str\n year: int | None\n new: bool\n disctotal: int\n genres: list[str]\n labels: list[str]\n albumartists: ArtistMapping\n metahash: str\n\n @classmethod\n def from_view(cls, c: Config, row: dict[str, Any], aliases: bool = True) -> CachedRelease:\n return CachedRelease(\n id=row[\"id\"],\n source_path=Path(row[\"source_path\"]),\n cover_image_path=Path(row[\"cover_image_path\"]) if row[\"cover_image_path\"] else None,\n added_at=row[\"added_at\"],\n datafile_mtime=row[\"datafile_mtime\"],\n albumtitle=row[\"albumtitle\"],\n releasetype=row[\"releasetype\"],\n year=row[\"year\"],\n disctotal=row[\"disctotal\"],\n new=bool(row[\"new\"]),\n genres=_split(row[\"genres\"]) if row[\"genres\"] else [],\n labels=_split(row[\"labels\"]) if row[\"labels\"] else [],\n albumartists=_unpack_artists(\n c, row[\"albumartist_names\"], row[\"albumartist_roles\"], aliases=aliases\n ),\n metahash=row[\"metahash\"],\n )\n\n def dump(self) -> dict[str, Any]:\n return {\n \"id\": self.id,\n \"source_path\": str(self.source_path.resolve()),\n \"cover_image_path\": str(self.cover_image_path.resolve())\n if self.cover_image_path\n else None,\n \"added_at\": self.added_at,\n \"albumtitle\": self.albumtitle,\n \"releasetype\": self.releasetype,\n \"year\": self.year,\n \"new\": self.new,\n \"disctotal\": self.disctotal,\n \"genres\": self.genres,\n \"labels\": self.labels,\n \"albumartists\": self.albumartists.dump(),\n }" }, { "identifier": "CachedTrack", "path": "rose/cache.py", "snippet": "class CachedTrack:\n id: str\n source_path: Path\n source_mtime: str\n tracktitle: str\n tracknumber: str\n tracktotal: int\n discnumber: str\n disctotal: int\n duration_seconds: int\n trackartists: ArtistMapping\n metahash: str\n\n release: CachedRelease\n\n @classmethod\n def from_view(\n cls, c: Config, row: dict[str, Any], release: CachedRelease, aliases: bool = True\n ) -> CachedTrack:\n return CachedTrack(\n id=row[\"id\"],\n source_path=Path(row[\"source_path\"]),\n source_mtime=row[\"source_mtime\"],\n tracktitle=row[\"tracktitle\"],\n tracknumber=row[\"tracknumber\"],\n tracktotal=row[\"tracktotal\"],\n discnumber=row[\"discnumber\"],\n disctotal=row[\"disctotal\"],\n duration_seconds=row[\"duration_seconds\"],\n trackartists=_unpack_artists(\n c,\n row[\"trackartist_names\"],\n row[\"trackartist_roles\"],\n aliases=aliases,\n ),\n metahash=row[\"metahash\"],\n release=release,\n )\n\n def dump(self, with_release_info: bool = True) -> dict[str, Any]:\n r = {\n \"id\": self.id,\n \"source_path\": str(self.source_path.resolve()),\n \"tracktitle\": self.tracktitle,\n \"tracknumber\": self.tracknumber,\n \"tracktotal\": self.tracktotal,\n \"discnumber\": self.discnumber,\n \"disctotal\": self.disctotal,\n \"duration_seconds\": self.duration_seconds,\n \"trackartists\": self.trackartists.dump(),\n }\n if with_release_info:\n r.update(\n {\n \"release_id\": self.release.id,\n \"added_at\": self.release.added_at,\n \"albumtitle\": self.release.albumtitle,\n \"releasetype\": self.release.releasetype,\n \"year\": self.release.year,\n \"new\": self.release.new,\n \"genres\": self.release.genres,\n \"labels\": self.release.labels,\n \"albumartists\": self.release.albumartists.dump(),\n }\n )\n return r" }, { "identifier": "_unpack", "path": "rose/cache.py", "snippet": "def _unpack(*xxs: str) -> Iterator[tuple[str, ...]]:\n \"\"\"\n Unpack an arbitrary number of strings, each of which is a \" ¬ \"-delimited list in actuality,\n but encoded as a string. This \" ¬ \"-delimited list-as-a-string is the convention we use to\n return arrayed data from a SQL query without introducing additional disk accesses.\n\n As a concrete example:\n\n >>> _unpack(\"Rose ¬ Lisa ¬ Jisoo ¬ Jennie\", \"vocal ¬ dance ¬ visual ¬ vocal\")\n [(\"Rose\", \"vocal\"), (\"Lisa\", \"dance\"), (\"Jisoo\", \"visual\"), (\"Jennie\", \"vocal\")]\n \"\"\"\n # If the strings are empty, then split will resolve to `[\"\"]`. But we don't want to loop over an\n # empty string, so we specially exit if we hit that case.\n if all(not xs for xs in xxs):\n return []\n yield from zip(*[_split(xs) for xs in xxs])" }, { "identifier": "artist_exists", "path": "rose/cache.py", "snippet": "def artist_exists(c: Config, artist_sanitized: str) -> bool:\n args: list[str] = [artist_sanitized]\n for alias in c.sanitized_artist_aliases_map.get(artist_sanitized, []):\n args.append(alias)\n with connect(c) as conn:\n cursor = conn.execute(\n f\"\"\"\n SELECT EXISTS(\n SELECT * FROM releases_artists\n WHERE artist_sanitized IN ({','.join(['?']*len(args))})\n )\n \"\"\",\n args,\n )\n return bool(cursor.fetchone()[0])" }, { "identifier": "connect", "path": "rose/cache.py", "snippet": "@contextlib.contextmanager\ndef connect(c: Config) -> Iterator[sqlite3.Connection]:\n conn = sqlite3.connect(\n c.cache_database_path,\n detect_types=sqlite3.PARSE_DECLTYPES,\n isolation_level=None,\n timeout=15.0,\n )\n try:\n conn.row_factory = sqlite3.Row\n conn.execute(\"PRAGMA foreign_keys=ON\")\n conn.execute(\"PRAGMA journal_mode=WAL\")\n yield conn\n finally:\n if conn:\n conn.close()" }, { "identifier": "genre_exists", "path": "rose/cache.py", "snippet": "def genre_exists(c: Config, genre_sanitized: str) -> bool:\n with connect(c) as conn:\n cursor = conn.execute(\n \"SELECT EXISTS(SELECT * FROM releases_genres WHERE genre_sanitized = ?)\",\n (genre_sanitized,),\n )\n return bool(cursor.fetchone()[0])" }, { "identifier": "get_collage", "path": "rose/cache.py", "snippet": "def get_collage(c: Config, collage_name: str) -> tuple[CachedCollage, list[CachedRelease]] | None:\n with connect(c) as conn:\n cursor = conn.execute(\n \"SELECT name, source_mtime FROM collages WHERE name = ?\",\n (collage_name,),\n )\n row = cursor.fetchone()\n if not row:\n return None\n collage = CachedCollage(\n name=row[\"name\"],\n source_mtime=row[\"source_mtime\"],\n # Accumulated below when we query the releases.\n release_ids=[],\n )\n cursor = conn.execute(\n \"\"\"\n SELECT r.*\n FROM releases_view r\n JOIN collages_releases cr ON cr.release_id = r.id\n WHERE cr.collage_name = ? AND NOT cr.missing\n ORDER BY cr.position ASC\n \"\"\",\n (collage_name,),\n )\n releases: list[CachedRelease] = []\n for row in cursor:\n collage.release_ids.append(row[\"id\"])\n releases.append(CachedRelease.from_view(c, row))\n\n return (collage, releases)" }, { "identifier": "get_playlist", "path": "rose/cache.py", "snippet": "def get_playlist(c: Config, playlist_name: str) -> tuple[CachedPlaylist, list[CachedTrack]] | None:\n with connect(c) as conn:\n cursor = conn.execute(\n \"\"\"\n SELECT\n name\n , source_mtime\n , cover_path\n FROM playlists\n WHERE name = ?\n \"\"\",\n (playlist_name,),\n )\n row = cursor.fetchone()\n if not row:\n return None\n playlist = CachedPlaylist(\n name=row[\"name\"],\n source_mtime=row[\"source_mtime\"],\n cover_path=Path(row[\"cover_path\"]) if row[\"cover_path\"] else None,\n # Accumulated below when we query the tracks.\n track_ids=[],\n )\n\n cursor = conn.execute(\n \"\"\"\n SELECT t.*\n FROM tracks_view t\n JOIN playlists_tracks pt ON pt.track_id = t.id\n WHERE pt.playlist_name = ? AND NOT pt.missing\n ORDER BY pt.position ASC\n \"\"\",\n (playlist_name,),\n )\n trackrows = cursor.fetchall()\n\n release_ids = [r[\"release_id\"] for r in trackrows]\n cursor = conn.execute(\n f\"\"\"\n SELECT *\n FROM releases_view\n WHERE id IN ({','.join(['?']*len(release_ids))})\n \"\"\",\n release_ids,\n )\n releases_map: dict[str, CachedRelease] = {}\n for row in cursor:\n releases_map[row[\"id\"]] = CachedRelease.from_view(c, row)\n\n tracks: list[CachedTrack] = []\n for row in trackrows:\n playlist.track_ids.append(row[\"id\"])\n tracks.append(CachedTrack.from_view(c, row, releases_map[row[\"release_id\"]]))\n\n return playlist, tracks" }, { "identifier": "get_release", "path": "rose/cache.py", "snippet": "def get_release(c: Config, release_id: str) -> CachedRelease | None:\n with connect(c) as conn:\n cursor = conn.execute(\n \"SELECT * FROM releases_view WHERE id = ?\",\n (release_id,),\n )\n row = cursor.fetchone()\n if not row:\n return None\n return CachedRelease.from_view(c, row)" }, { "identifier": "get_release_logtext", "path": "rose/cache.py", "snippet": "def get_release_logtext(c: Config, release_id: str) -> str | None:\n \"\"\"Get a human-readable identifier for a release suitable for logging.\"\"\"\n with connect(c) as conn:\n cursor = conn.execute(\n \"SELECT albumtitle, year, albumartist_names, albumartist_roles FROM releases_view WHERE id = ?\",\n (release_id,),\n )\n row = cursor.fetchone()\n if not row:\n return None\n return calculate_release_logtext(\n title=row[\"albumtitle\"],\n year=row[\"year\"],\n artists=_unpack_artists(c, row[\"albumartist_names\"], row[\"albumartist_roles\"]),\n )" }, { "identifier": "get_track", "path": "rose/cache.py", "snippet": "def get_track(c: Config, uuid: str) -> CachedTrack | None:\n with connect(c) as conn:\n cursor = conn.execute(\"SELECT * FROM tracks_view WHERE id = ?\", (uuid,))\n trackrow = cursor.fetchone()\n if not trackrow:\n return None\n cursor = conn.execute(\"SELECT * FROM releases_view WHERE id = ?\", (trackrow[\"release_id\"],))\n release = CachedRelease.from_view(c, cursor.fetchone())\n return CachedTrack.from_view(c, trackrow, release)" }, { "identifier": "get_track_logtext", "path": "rose/cache.py", "snippet": "def get_track_logtext(c: Config, track_id: str) -> str | None:\n \"\"\"Get a human-readable identifier for a track suitable for logging.\"\"\"\n with connect(c) as conn:\n cursor = conn.execute(\n \"SELECT tracktitle, source_path, trackartist_names, trackartist_roles FROM tracks_view WHERE id = ?\",\n (track_id,),\n )\n row = cursor.fetchone()\n if not row:\n return None\n return calculate_track_logtext(\n title=row[\"tracktitle\"],\n artists=_unpack_artists(c, row[\"trackartist_names\"], row[\"trackartist_roles\"]),\n suffix=Path(row[\"source_path\"]).suffix,\n )" }, { "identifier": "get_tracks_associated_with_release", "path": "rose/cache.py", "snippet": "def get_tracks_associated_with_release(\n c: Config,\n release: CachedRelease,\n) -> list[CachedTrack]:\n with connect(c) as conn:\n cursor = conn.execute(\n \"\"\"\n SELECT *\n FROM tracks_view\n WHERE release_id = ?\n ORDER BY release_id, FORMAT('%4d.%4d', discnumber, tracknumber)\n \"\"\",\n (release.id,),\n )\n rval = []\n for row in cursor:\n rval.append(CachedTrack.from_view(c, row, release))\n return rval" }, { "identifier": "get_tracks_associated_with_releases", "path": "rose/cache.py", "snippet": "def get_tracks_associated_with_releases(\n c: Config,\n releases: list[CachedRelease],\n) -> list[tuple[CachedRelease, list[CachedTrack]]]:\n releases_map = {r.id: r for r in releases}\n tracks_map: dict[str, list[CachedTrack]] = defaultdict(list)\n with connect(c) as conn:\n cursor = conn.execute(\n f\"\"\"\n SELECT *\n FROM tracks_view\n WHERE release_id IN ({','.join(['?']*len(releases))})\n ORDER BY release_id, FORMAT('%4d.%4d', discnumber, tracknumber)\n \"\"\",\n [r.id for r in releases],\n )\n for row in cursor:\n tracks_map[row[\"release_id\"]].append(\n CachedTrack.from_view(c, row, releases_map[row[\"release_id\"]])\n )\n\n rval = []\n for release in releases:\n tracks = tracks_map[release.id]\n rval.append((release, tracks))\n return rval" }, { "identifier": "label_exists", "path": "rose/cache.py", "snippet": "def label_exists(c: Config, label_sanitized: str) -> bool:\n with connect(c) as conn:\n cursor = conn.execute(\n \"SELECT EXISTS(SELECT * FROM releases_labels WHERE label_sanitized = ?)\",\n (label_sanitized,),\n )\n return bool(cursor.fetchone()[0])" }, { "identifier": "list_artists", "path": "rose/cache.py", "snippet": "def list_artists(c: Config) -> list[tuple[str, str]]:\n with connect(c) as conn:\n cursor = conn.execute(\"SELECT DISTINCT artist, artist_sanitized FROM releases_artists\")\n return [(row[\"artist\"], row[\"artist_sanitized\"]) for row in cursor]" }, { "identifier": "list_collages", "path": "rose/cache.py", "snippet": "def list_collages(c: Config) -> list[str]:\n with connect(c) as conn:\n cursor = conn.execute(\"SELECT DISTINCT name FROM collages\")\n return [r[\"name\"] for r in cursor]" }, { "identifier": "list_genres", "path": "rose/cache.py", "snippet": "def list_genres(c: Config) -> list[tuple[str, str]]:\n with connect(c) as conn:\n cursor = conn.execute(\"SELECT DISTINCT genre, genre_sanitized FROM releases_genres\")\n return [(row[\"genre\"], row[\"genre_sanitized\"]) for row in cursor]" }, { "identifier": "list_labels", "path": "rose/cache.py", "snippet": "def list_labels(c: Config) -> list[tuple[str, str]]:\n with connect(c) as conn:\n cursor = conn.execute(\"SELECT DISTINCT label, label_sanitized FROM releases_labels\")\n return [(row[\"label\"], row[\"label_sanitized\"]) for row in cursor]" }, { "identifier": "list_playlists", "path": "rose/cache.py", "snippet": "def list_playlists(c: Config) -> list[str]:\n with connect(c) as conn:\n cursor = conn.execute(\"SELECT DISTINCT name FROM playlists\")\n return [r[\"name\"] for r in cursor]" }, { "identifier": "list_releases", "path": "rose/cache.py", "snippet": "def list_releases(c: Config, release_ids: list[str] | None = None) -> list[CachedRelease]:\n \"\"\"Fetch data associated with given release IDs. Pass None to fetch all.\"\"\"\n query = \"SELECT * FROM releases_view\"\n args = []\n if release_ids is not None:\n query += f\" WHERE id IN ({','.join(['?']*len(release_ids))})\"\n args = release_ids\n query += \" ORDER BY source_path\"\n with connect(c) as conn:\n cursor = conn.execute(query, args)\n releases: list[CachedRelease] = []\n for row in cursor:\n releases.append(CachedRelease.from_view(c, row))\n return releases" }, { "identifier": "list_tracks", "path": "rose/cache.py", "snippet": "def list_tracks(c: Config, track_ids: list[str] | None = None) -> list[CachedTrack]:\n \"\"\"Fetch data associated with given track IDs. Pass None to fetch all.\"\"\"\n query = \"SELECT * FROM tracks_view\"\n args = []\n if track_ids is not None:\n query += f\" WHERE id IN ({','.join(['?']*len(track_ids))})\"\n args = track_ids\n query += \" ORDER BY source_path\"\n with connect(c) as conn:\n cursor = conn.execute(query, args)\n trackrows = cursor.fetchall()\n\n release_ids = [r[\"release_id\"] for r in trackrows]\n cursor = conn.execute(\n f\"\"\"\n SELECT *\n FROM releases_view\n WHERE id IN ({','.join(['?']*len(release_ids))})\n \"\"\",\n release_ids,\n )\n releases_map: dict[str, CachedRelease] = {}\n for row in cursor:\n releases_map[row[\"id\"]] = CachedRelease.from_view(c, row)\n\n rval = []\n for row in trackrows:\n rval.append(CachedTrack.from_view(c, row, releases_map[row[\"release_id\"]]))\n return rval" }, { "identifier": "lock", "path": "rose/cache.py", "snippet": "@contextlib.contextmanager\ndef lock(c: Config, name: str, timeout: float = 1.0) -> Iterator[None]:\n try:\n while True:\n with connect(c) as conn:\n cursor = conn.execute(\"SELECT MAX(valid_until) FROM locks WHERE name = ?\", (name,))\n row = cursor.fetchone()\n # If a lock exists, sleep until the lock is available. All locks should be very\n # short lived, so this shouldn't be a big performance penalty.\n if row and row[0] and row[0] > time.time():\n sleep = max(0, row[0] - time.time())\n logger.debug(f\"Failed to acquire lock for {name}: sleeping for {sleep}\")\n time.sleep(sleep)\n continue\n logger.debug(f\"Attempting to acquire lock for {name} with timeout {timeout}\")\n valid_until = time.time() + timeout\n try:\n conn.execute(\n \"INSERT INTO locks (name, valid_until) VALUES (?, ?)\", (name, valid_until)\n )\n except sqlite3.IntegrityError as e:\n logger.debug(f\"Failed to acquire lock for {name}, trying again: {e}\")\n continue\n logger.debug(\n f\"Successfully acquired lock for {name} with timeout {timeout} \"\n f\"until {valid_until}\"\n )\n break\n yield\n finally:\n logger.debug(f\"Releasing lock {name}\")\n with connect(c) as conn:\n conn.execute(\"DELETE FROM locks WHERE name = ?\", (name,))" }, { "identifier": "maybe_invalidate_cache_database", "path": "rose/cache.py", "snippet": "def maybe_invalidate_cache_database(c: Config) -> None:\n \"\"\"\n \"Migrate\" the database. If the schema in the database does not match that on disk, then nuke the\n database and recreate it from scratch. Otherwise, no op.\n\n We can do this because the database is just a read cache. It is not source-of-truth for any of\n its own data.\n \"\"\"\n with CACHE_SCHEMA_PATH.open(\"rb\") as fp:\n schema_hash = hashlib.sha256(fp.read()).hexdigest()\n\n # Hash a subset of the config fields to use as the cache hash, which invalidates the cache on\n # change. These are the fields that affect cache population. Invalidating the cache on config\n # change ensures that the cache is consistent with the config.\n config_hash_fields = {\n \"music_source_dir\": str(c.music_source_dir),\n \"cache_dir\": str(c.cache_dir),\n \"cover_art_stems\": c.cover_art_stems,\n \"valid_art_exts\": c.valid_art_exts,\n \"ignore_release_directories\": c.ignore_release_directories,\n }\n config_hash = sha256(json.dumps(config_hash_fields).encode()).hexdigest()\n\n with connect(c) as conn:\n cursor = conn.execute(\n \"\"\"\n SELECT EXISTS(\n SELECT * FROM sqlite_master\n WHERE type = 'table' AND name = '_schema_hash'\n )\n \"\"\"\n )\n if cursor.fetchone()[0]:\n cursor = conn.execute(\"SELECT schema_hash, config_hash, version FROM _schema_hash\")\n row = cursor.fetchone()\n if (\n row\n and row[\"schema_hash\"] == schema_hash\n and row[\"config_hash\"] == config_hash\n and row[\"version\"] == VERSION\n ):\n # Everything matches! Exit!\n return\n\n c.cache_database_path.unlink(missing_ok=True)\n with connect(c) as conn:\n with CACHE_SCHEMA_PATH.open(\"r\") as fp:\n conn.executescript(fp.read())\n conn.execute(\n \"\"\"\n CREATE TABLE _schema_hash (\n schema_hash TEXT\n , config_hash TEXT\n , version TEXT\n , PRIMARY KEY (schema_hash, config_hash, version)\n )\n \"\"\"\n )\n conn.execute(\n \"INSERT INTO _schema_hash (schema_hash, config_hash, version) VALUES (?, ?, ?)\",\n (schema_hash, config_hash, VERSION),\n )" }, { "identifier": "update_cache", "path": "rose/cache.py", "snippet": "def update_cache(\n c: Config,\n force: bool = False,\n # For testing.\n force_multiprocessing: bool = False,\n) -> None:\n \"\"\"\n Update the read cache to match the data for all releases in the music source directory. Delete\n any cached releases that are no longer present on disk.\n \"\"\"\n update_cache_for_releases(c, None, force, force_multiprocessing=force_multiprocessing)\n update_cache_evict_nonexistent_releases(c)\n update_cache_for_collages(c, None, force)\n update_cache_evict_nonexistent_collages(c)\n update_cache_for_playlists(c, None, force)\n update_cache_evict_nonexistent_playlists(c)" }, { "identifier": "update_cache_evict_nonexistent_releases", "path": "rose/cache.py", "snippet": "def update_cache_evict_nonexistent_releases(c: Config) -> None:\n logger.debug(\"Evicting cached releases that are not on disk\")\n dirs = [Path(d.path).resolve() for d in os.scandir(c.music_source_dir) if d.is_dir()]\n with connect(c) as conn:\n cursor = conn.execute(\n f\"\"\"\n DELETE FROM releases\n WHERE source_path NOT IN ({\",\".join([\"?\"] * len(dirs))})\n RETURNING source_path\n \"\"\",\n [str(d) for d in dirs],\n )\n for row in cursor:\n logger.info(f\"Evicted missing release {row['source_path']} from cache\")" }, { "identifier": "update_cache_for_releases", "path": "rose/cache.py", "snippet": "def update_cache_for_releases(\n c: Config,\n # Leave as None to update all releases.\n release_dirs: list[Path] | None = None,\n force: bool = False,\n # For testing.\n force_multiprocessing: bool = False,\n) -> None:\n \"\"\"\n Update the read cache to match the data for any passed-in releases. If a directory lacks a\n .rose.{uuid}.toml datafile, create the datafile for the release and set it to the initial state.\n\n This is a hot path and is thus performance-optimized. The bottleneck is disk accesses, so we\n structure this function in order to minimize them. We solely read files that have changed since\n last run and batch writes together. We trade higher memory for reduced disk accesses.\n Concretely, we:\n\n 1. Execute one big SQL query at the start to fetch the relevant previous caches.\n 2. Skip reading a file's data if the mtime has not changed since the previous cache update.\n 3. Batch SQLite write operations to the end of this function, and only execute a SQLite upsert\n if the read data differs from the previous caches.\n\n We also shard the directories across multiple processes and execute them simultaneously.\n \"\"\"\n release_dirs = release_dirs or [\n Path(d.path) for d in os.scandir(c.music_source_dir) if d.is_dir()\n ]\n release_dirs = [\n d\n for d in release_dirs\n if d.name != \"!collages\"\n and d.name != \"!playlists\"\n and d.name not in c.ignore_release_directories\n ]\n if not release_dirs:\n logger.debug(\"No-Op: No whitelisted releases passed into update_cache_for_releases\")\n return\n logger.debug(f\"Refreshing the read cache for {len(release_dirs)} releases\")\n if len(release_dirs) < 10:\n logger.debug(f\"Refreshing cached data for {', '.join([r.name for r in release_dirs])}\")\n\n # If the number of releases changed is less than 50; do not bother with all that multiprocessing\n # gunk: instead, directly call the executor.\n #\n # This has an added benefit of not spawning processes from the virtual filesystem and watchdog\n # processes, as those processes always update the cache for one release at a time and are\n # multithreaded. Starting other processes from threads is bad!\n if not force_multiprocessing and len(release_dirs) < 50:\n logger.debug(\n f\"Running cache update executor in same process because {len(release_dirs)=} < 50\"\n )\n _update_cache_for_releases_executor(c, release_dirs, force)\n return\n\n # Batch size defaults to equal split across all processes. However, if the number of directories\n # is small, we shrink the # of processes to save on overhead.\n num_proc = c.max_proc\n if len(release_dirs) < c.max_proc * 50:\n num_proc = max(1, math.ceil(len(release_dirs) // 50))\n batch_size = len(release_dirs) // num_proc + 1\n\n manager = multiprocessing.Manager()\n # Have each process propagate the collages and playlists it wants to update back upwards. We\n # will dispatch the force updater only once in the main process, instead of many times in each\n # process.\n collages_to_force_update = manager.list()\n playlists_to_force_update = manager.list()\n\n errors: list[BaseException] = []\n\n logger.debug(\"Creating multiprocessing pool to parallelize cache executors.\")\n with multiprocessing.Pool(processes=c.max_proc) as pool:\n # At 0, no batch. At 1, 1 batch. At 49, 1 batch. At 50, 1 batch. At 51, 2 batches.\n for i in range(0, len(release_dirs), batch_size):\n logger.debug(\n f\"Spawning release cache update process for releases [{i}, {i+batch_size})\"\n )\n pool.apply_async(\n _update_cache_for_releases_executor,\n (\n c,\n release_dirs[i : i + batch_size],\n force,\n collages_to_force_update,\n playlists_to_force_update,\n ),\n error_callback=lambda e: errors.append(e),\n )\n pool.close()\n pool.join()\n\n if errors:\n raise ExceptionGroup(\"Exception occurred in cache update subprocesses\", errors) # type: ignore\n\n if collages_to_force_update:\n update_cache_for_collages(c, uniq(list(collages_to_force_update)), force=True)\n if playlists_to_force_update:\n update_cache_for_playlists(c, uniq(list(playlists_to_force_update)), force=True)" }, { "identifier": "VERSION", "path": "rose/common.py", "snippet": "VERSION = fp.read().strip()" }, { "identifier": "Artist", "path": "rose/common.py", "snippet": "class Artist:\n name: str\n alias: bool = False\n\n def __hash__(self) -> int:\n return hash((self.name, self.alias))" }, { "identifier": "ArtistMapping", "path": "rose/common.py", "snippet": "class ArtistMapping:\n main: list[Artist] = dataclasses.field(default_factory=list)\n guest: list[Artist] = dataclasses.field(default_factory=list)\n remixer: list[Artist] = dataclasses.field(default_factory=list)\n producer: list[Artist] = dataclasses.field(default_factory=list)\n composer: list[Artist] = dataclasses.field(default_factory=list)\n djmixer: list[Artist] = dataclasses.field(default_factory=list)\n\n @property\n def all(self) -> list[Artist]:\n return uniq(\n self.main + self.guest + self.remixer + self.producer + self.composer + self.djmixer\n )\n\n def dump(self) -> dict[str, Any]:\n return dataclasses.asdict(self)\n\n def items(self) -> Iterator[tuple[str, list[Artist]]]:\n yield \"main\", self.main\n yield \"guest\", self.guest\n yield \"remixer\", self.remixer\n yield \"producer\", self.producer\n yield \"composer\", self.composer\n yield \"djmixer\", self.djmixer" }, { "identifier": "Config", "path": "rose/config.py", "snippet": "class Config:\n music_source_dir: Path\n fuse_mount_dir: Path\n cache_dir: Path\n # Maximum parallel processes for cache updates. Defaults to nproc/2.\n max_proc: int\n ignore_release_directories: list[str]\n\n # A map from parent artist -> subartists.\n artist_aliases_map: dict[str, list[str]]\n # A map from subartist -> parent artists.\n artist_aliases_parents_map: dict[str, list[str]]\n\n fuse_artists_whitelist: list[str] | None\n fuse_genres_whitelist: list[str] | None\n fuse_labels_whitelist: list[str] | None\n fuse_artists_blacklist: list[str] | None\n fuse_genres_blacklist: list[str] | None\n fuse_labels_blacklist: list[str] | None\n\n cover_art_stems: list[str]\n valid_art_exts: list[str]\n\n rename_source_files: bool\n path_templates: PathTemplateConfig\n\n stored_metadata_rules: list[MetadataRule]\n\n @classmethod\n def parse(cls, config_path_override: Path | None = None) -> Config:\n # As we parse, delete consumed values from the data dictionary. If any are left over at the\n # end of the config, warn that unknown config keys were found.\n cfgpath = config_path_override or CONFIG_PATH\n cfgtext = \"\"\n try:\n with cfgpath.open(\"r\") as fp:\n cfgtext = fp.read()\n data = tomllib.loads(cfgtext)\n except FileNotFoundError as e:\n raise ConfigNotFoundError(f\"Configuration file not found ({cfgpath})\") from e\n except tomllib.TOMLDecodeError as e:\n raise ConfigDecodeError(\n f\"Failed to decode configuration file: invalid TOML: {e}\"\n ) from e\n\n try:\n music_source_dir = Path(data[\"music_source_dir\"]).expanduser()\n del data[\"music_source_dir\"]\n except KeyError as e:\n raise MissingConfigKeyError(\n f\"Missing key music_source_dir in configuration file ({cfgpath})\"\n ) from e\n except (ValueError, TypeError) as e:\n raise InvalidConfigValueError(\n f\"Invalid value for music_source_dir in configuration file ({cfgpath}): must be a path\"\n ) from e\n\n try:\n fuse_mount_dir = Path(data[\"fuse_mount_dir\"]).expanduser()\n del data[\"fuse_mount_dir\"]\n except KeyError as e:\n raise MissingConfigKeyError(\n f\"Missing key fuse_mount_dir in configuration file ({cfgpath})\"\n ) from e\n except (ValueError, TypeError) as e:\n raise InvalidConfigValueError(\n f\"Invalid value for fuse_mount_dir in configuration file ({cfgpath}): must be a path\"\n ) from e\n\n try:\n cache_dir = Path(data[\"cache_dir\"]).expanduser()\n del data[\"cache_dir\"]\n except KeyError:\n cache_dir = XDG_CACHE_ROSE\n except (TypeError, ValueError) as e:\n raise InvalidConfigValueError(\n f\"Invalid value for cache_dir in configuration file ({cfgpath}): must be a path\"\n ) from e\n cache_dir.mkdir(parents=True, exist_ok=True)\n\n try:\n max_proc = int(data[\"max_proc\"])\n del data[\"max_proc\"]\n if max_proc <= 0:\n raise ValueError(f\"must be a positive integer: got {max_proc}\")\n except KeyError:\n max_proc = max(1, multiprocessing.cpu_count() // 2)\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for max_proc in configuration file ({cfgpath}): must be a positive integer\"\n ) from e\n\n artist_aliases_map: dict[str, list[str]] = defaultdict(list)\n artist_aliases_parents_map: dict[str, list[str]] = defaultdict(list)\n try:\n for entry in data.get(\"artist_aliases\", []):\n if not isinstance(entry[\"artist\"], str):\n raise ValueError(f\"Artists must be of type str: got {type(entry['artist'])}\")\n artist_aliases_map[entry[\"artist\"]] = entry[\"aliases\"]\n if not isinstance(entry[\"aliases\"], list):\n raise ValueError(\n f\"Aliases must be of type list[str]: got {type(entry['aliases'])}\"\n )\n for s in entry[\"aliases\"]:\n if not isinstance(s, str):\n raise ValueError(f\"Each alias must be of type str: got {type(s)}\")\n artist_aliases_parents_map[s].append(entry[\"artist\"])\n with contextlib.suppress(KeyError):\n del data[\"artist_aliases\"]\n except (ValueError, TypeError, KeyError) as e:\n raise InvalidConfigValueError(\n f\"Invalid value for artist_aliases in configuration file ({cfgpath}): must be a list of {{ artist = str, aliases = list[str] }} records\"\n ) from e\n\n try:\n fuse_artists_whitelist = data[\"fuse_artists_whitelist\"]\n del data[\"fuse_artists_whitelist\"]\n if not isinstance(fuse_artists_whitelist, list):\n raise ValueError(f\"Must be a list[str]: got {type(fuse_artists_whitelist)}\")\n for s in fuse_artists_whitelist:\n if not isinstance(s, str):\n raise ValueError(f\"Each artist must be of type str: got {type(s)}\")\n except KeyError:\n fuse_artists_whitelist = None\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for fuse_artists_whitelist in configuration file ({cfgpath}): {e}\"\n ) from e\n\n try:\n fuse_genres_whitelist = data[\"fuse_genres_whitelist\"]\n del data[\"fuse_genres_whitelist\"]\n if not isinstance(fuse_genres_whitelist, list):\n raise ValueError(f\"Must be a list[str]: got {type(fuse_genres_whitelist)}\")\n for s in fuse_genres_whitelist:\n if not isinstance(s, str):\n raise ValueError(f\"Each genre must be of type str: got {type(s)}\")\n except KeyError:\n fuse_genres_whitelist = None\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for fuse_genres_whitelist in configuration file ({cfgpath}): {e}\"\n ) from e\n\n try:\n fuse_labels_whitelist = data[\"fuse_labels_whitelist\"]\n del data[\"fuse_labels_whitelist\"]\n if not isinstance(fuse_labels_whitelist, list):\n raise ValueError(f\"Must be a list[str]: got {type(fuse_labels_whitelist)}\")\n for s in fuse_labels_whitelist:\n if not isinstance(s, str):\n raise ValueError(f\"Each label must be of type str: got {type(s)}\")\n except KeyError:\n fuse_labels_whitelist = None\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for fuse_labels_whitelist in configuration file ({cfgpath}): {e}\"\n ) from e\n\n try:\n fuse_artists_blacklist = data[\"fuse_artists_blacklist\"]\n del data[\"fuse_artists_blacklist\"]\n if not isinstance(fuse_artists_blacklist, list):\n raise ValueError(f\"Must be a list[str]: got {type(fuse_artists_blacklist)}\")\n for s in fuse_artists_blacklist:\n if not isinstance(s, str):\n raise ValueError(f\"Each artist must be of type str: got {type(s)}\")\n except KeyError:\n fuse_artists_blacklist = None\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for fuse_artists_blacklist in configuration file ({cfgpath}): {e}\"\n ) from e\n\n try:\n fuse_genres_blacklist = data[\"fuse_genres_blacklist\"]\n del data[\"fuse_genres_blacklist\"]\n if not isinstance(fuse_genres_blacklist, list):\n raise ValueError(f\"Must be a list[str]: got {type(fuse_genres_blacklist)}\")\n for s in fuse_genres_blacklist:\n if not isinstance(s, str):\n raise ValueError(f\"Each genre must be of type str: got {type(s)}\")\n except KeyError:\n fuse_genres_blacklist = None\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for fuse_genres_blacklist in configuration file ({cfgpath}): {e}\"\n ) from e\n\n try:\n fuse_labels_blacklist = data[\"fuse_labels_blacklist\"]\n del data[\"fuse_labels_blacklist\"]\n if not isinstance(fuse_labels_blacklist, list):\n raise ValueError(f\"Must be a list[str]: got {type(fuse_labels_blacklist)}\")\n for s in fuse_labels_blacklist:\n if not isinstance(s, str):\n raise ValueError(f\"Each label must be of type str: got {type(s)}\")\n except KeyError:\n fuse_labels_blacklist = None\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for fuse_labels_blacklist in configuration file ({cfgpath}): {e}\"\n ) from e\n\n if fuse_artists_whitelist and fuse_artists_blacklist:\n raise InvalidConfigValueError(\n f\"Cannot specify both fuse_artists_whitelist and fuse_artists_blacklist in configuration file ({cfgpath}): must specify only one or the other\"\n )\n if fuse_genres_whitelist and fuse_genres_blacklist:\n raise InvalidConfigValueError(\n f\"Cannot specify both fuse_genres_whitelist and fuse_genres_blacklist in configuration file ({cfgpath}): must specify only one or the other\"\n )\n if fuse_labels_whitelist and fuse_labels_blacklist:\n raise InvalidConfigValueError(\n f\"Cannot specify both fuse_labels_whitelist and fuse_labels_blacklist in configuration file ({cfgpath}): must specify only one or the other\"\n )\n\n try:\n cover_art_stems = data[\"cover_art_stems\"]\n del data[\"cover_art_stems\"]\n if not isinstance(cover_art_stems, list):\n raise ValueError(f\"Must be a list[str]: got {type(cover_art_stems)}\")\n for s in cover_art_stems:\n if not isinstance(s, str):\n raise ValueError(f\"Each cover art stem must be of type str: got {type(s)}\")\n except KeyError:\n cover_art_stems = [\"folder\", \"cover\", \"art\", \"front\"]\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for cover_art_stems in configuration file ({cfgpath}): {e}\"\n ) from e\n\n try:\n valid_art_exts = data[\"valid_art_exts\"]\n del data[\"valid_art_exts\"]\n if not isinstance(valid_art_exts, list):\n raise ValueError(f\"Must be a list[str]: got {type(valid_art_exts)}\")\n for s in valid_art_exts:\n if not isinstance(s, str):\n raise ValueError(f\"Each art extension must be of type str: got {type(s)}\")\n except KeyError:\n valid_art_exts = [\"jpg\", \"jpeg\", \"png\"]\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for valid_art_exts in configuration file ({cfgpath}): {e}\"\n ) from e\n\n cover_art_stems = [x.lower() for x in cover_art_stems]\n valid_art_exts = [x.lower() for x in valid_art_exts]\n\n try:\n rename_source_files = data[\"rename_source_files\"]\n del data[\"rename_source_files\"]\n if not isinstance(rename_source_files, bool):\n raise ValueError(f\"Must be a bool: got {type(rename_source_files)}\")\n except KeyError:\n rename_source_files = False\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for rename_source_files in configuration file ({cfgpath}): {e}\"\n ) from e\n\n try:\n ignore_release_directories = data[\"ignore_release_directories\"]\n del data[\"ignore_release_directories\"]\n if not isinstance(ignore_release_directories, list):\n raise ValueError(f\"Must be a list[str]: got {type(ignore_release_directories)}\")\n for s in ignore_release_directories:\n if not isinstance(s, str):\n raise ValueError(f\"Each release directory must be of type str: got {type(s)}\")\n except KeyError:\n ignore_release_directories = []\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for ignore_release_directories in configuration file ({cfgpath}): {e}\"\n ) from e\n\n stored_metadata_rules: list[MetadataRule] = []\n for d in data.get(\"stored_metadata_rules\", []):\n if not isinstance(d, dict):\n raise InvalidConfigValueError(\n f\"Invalid value in stored_metadata_rules in configuration file ({cfgpath}): list values must be a dict: got {type(d)}\"\n )\n\n try:\n matcher = d[\"matcher\"]\n except KeyError as e:\n raise InvalidConfigValueError(\n f\"Missing key `matcher` in stored_metadata_rules in configuration file ({cfgpath}): rule {d}\"\n ) from e\n if not isinstance(matcher, str):\n raise InvalidConfigValueError(\n f\"Invalid value for `matcher` in stored_metadata_rules in configuration file ({cfgpath}): rule {d}: must be a string\"\n )\n\n try:\n actions = d[\"actions\"]\n except KeyError as e:\n raise InvalidConfigValueError(\n f\"Missing key `actions` in stored_metadata_rules in configuration file ({cfgpath}): rule {d}\"\n ) from e\n if not isinstance(actions, list):\n raise InvalidConfigValueError(\n f\"Invalid value for `actions` in stored_metadata_rules in configuration file ({cfgpath}): rule {d}: must be a list of strings\"\n )\n for action in actions:\n if not isinstance(action, str):\n raise InvalidConfigValueError(\n f\"Invalid value for `actions` in stored_metadata_rules in configuration file ({cfgpath}): rule {d}: must be a list of strings: got {type(action)}\"\n )\n\n try:\n stored_metadata_rules.append(MetadataRule.parse(matcher, actions))\n except RuleSyntaxError as e:\n raise InvalidConfigValueError(\n f\"Failed to parse stored_metadata_rules in configuration file ({cfgpath}): rule {d}: {e}\"\n ) from e\n if \"stored_metadata_rules\" in data:\n del data[\"stored_metadata_rules\"]\n\n # Get the potential default template before evaluating the rest.\n default_templates = deepcopy(DEFAULT_TEMPLATE_PAIR)\n with contextlib.suppress(KeyError):\n default_templates.release = PathTemplate(data[\"path_templates\"][\"default\"][\"release\"])\n del data[\"path_templates\"][\"default\"][\"release\"]\n with contextlib.suppress(KeyError):\n default_templates.track = PathTemplate(data[\"path_templates\"][\"default\"][\"track\"])\n del data[\"path_templates\"][\"default\"][\"track\"]\n with contextlib.suppress(KeyError):\n if not data[\"path_templates\"][\"default\"]:\n del data[\"path_templates\"][\"default\"]\n\n path_templates = PathTemplateConfig.with_defaults(default_templates)\n if tmpl_config := data.get(\"path_templates\", None):\n for key in [\n \"source\",\n \"all_releases\",\n \"new_releases\",\n \"recently_added_releases\",\n \"artists\",\n \"genres\",\n \"labels\",\n \"collages\",\n ]:\n with contextlib.suppress(KeyError):\n getattr(path_templates, key).release = PathTemplate(tmpl_config[key][\"release\"])\n del tmpl_config[key][\"release\"]\n with contextlib.suppress(KeyError):\n getattr(path_templates, key).track = PathTemplate(tmpl_config[key][\"track\"])\n del tmpl_config[key][\"track\"]\n with contextlib.suppress(KeyError):\n if not tmpl_config[key]:\n del tmpl_config[key]\n\n with contextlib.suppress(KeyError):\n path_templates.playlists = PathTemplate(tmpl_config[\"playlists\"])\n del tmpl_config[\"playlists\"]\n with contextlib.suppress(KeyError):\n if not data[\"path_templates\"]:\n del data[\"path_templates\"]\n\n try:\n path_templates.parse()\n except InvalidPathTemplateError as e:\n raise InvalidConfigValueError(\n f\"Invalid path template in configuration file ({cfgpath}) for template {e.key}: {e}\"\n ) from e\n\n if data:\n unrecognized_accessors: list[str] = []\n # Do a DFS over the data keys to assemble the map of unknown keys. State is a tuple of\n # (\"accessor\", node).\n dfs_state: deque[tuple[str, dict[str, Any]]] = deque([(\"\", data)])\n while dfs_state:\n accessor, node = dfs_state.pop()\n if isinstance(node, dict):\n for k, v in node.items():\n child_accessor = k if not accessor else f\"{accessor}.{k}\"\n dfs_state.append((child_accessor, v))\n continue\n unrecognized_accessors.append(accessor)\n logger.warning(\n f\"Unrecognized options found in configuration file: {', '.join(unrecognized_accessors)}\"\n )\n\n return Config(\n music_source_dir=music_source_dir,\n fuse_mount_dir=fuse_mount_dir,\n cache_dir=cache_dir,\n max_proc=max_proc,\n artist_aliases_map=artist_aliases_map,\n artist_aliases_parents_map=artist_aliases_parents_map,\n fuse_artists_whitelist=fuse_artists_whitelist,\n fuse_genres_whitelist=fuse_genres_whitelist,\n fuse_labels_whitelist=fuse_labels_whitelist,\n fuse_artists_blacklist=fuse_artists_blacklist,\n fuse_genres_blacklist=fuse_genres_blacklist,\n fuse_labels_blacklist=fuse_labels_blacklist,\n cover_art_stems=cover_art_stems,\n valid_art_exts=valid_art_exts,\n path_templates=path_templates,\n rename_source_files=rename_source_files,\n ignore_release_directories=ignore_release_directories,\n stored_metadata_rules=stored_metadata_rules,\n )\n\n @functools.cached_property\n def valid_cover_arts(self) -> list[str]:\n return [s + \".\" + e for s in self.cover_art_stems for e in self.valid_art_exts]\n\n @functools.cached_property\n def cache_database_path(self) -> Path:\n return self.cache_dir / \"cache.sqlite3\"\n\n @functools.cached_property\n def watchdog_pid_path(self) -> Path:\n return self.cache_dir / \"watchdog.pid\"\n\n @functools.cached_property\n def sanitized_artist_aliases_map(self) -> dict[str, list[str]]:\n return {sanitize_dirname(k, False): v for k, v in self.artist_aliases_map.items()}\n\n @functools.cached_property\n def sanitized_artist_aliases_parents_map(self) -> dict[str, list[str]]:\n return {sanitize_dirname(k, False): v for k, v in self.artist_aliases_parents_map.items()}" } ]
import dataclasses import hashlib import shutil import time import pytest import tomllib from pathlib import Path from conftest import TEST_COLLAGE_1, TEST_PLAYLIST_1, TEST_RELEASE_1, TEST_RELEASE_2, TEST_RELEASE_3 from rose.audiotags import AudioTags from rose.cache import ( CACHE_SCHEMA_PATH, STORED_DATA_FILE_REGEX, CachedCollage, CachedPlaylist, CachedRelease, CachedTrack, _unpack, artist_exists, connect, genre_exists, get_collage, get_playlist, get_release, get_release_logtext, get_track, get_track_logtext, get_tracks_associated_with_release, get_tracks_associated_with_releases, label_exists, list_artists, list_collages, list_genres, list_labels, list_playlists, list_releases, list_tracks, lock, maybe_invalidate_cache_database, update_cache, update_cache_evict_nonexistent_releases, update_cache_for_releases, ) from rose.common import VERSION, Artist, ArtistMapping from rose.config import Config
18,339
assert af.release_id is not None af = AudioTags.from_file(release_dir / "02.m4a") assert af.id is not None assert af.release_id is not None def test_update_cache_releases_already_fully_cached(config: Config) -> None: """Test that a fully cached release No Ops when updated again.""" release_dir = config.music_source_dir / TEST_RELEASE_1.name shutil.copytree(TEST_RELEASE_1, release_dir) update_cache_for_releases(config, [release_dir]) update_cache_for_releases(config, [release_dir]) # Assert that the release metadata was read correctly. with connect(config) as conn: cursor = conn.execute( "SELECT id, source_path, title, releasetype, year, new FROM releases", ) row = cursor.fetchone() assert row["source_path"] == str(release_dir) assert row["title"] == "I Love Blackpink" assert row["releasetype"] == "album" assert row["year"] == 1990 assert row["new"] def test_update_cache_releases_disk_update_to_previously_cached(config: Config) -> None: """Test that a cached release is updated after a track updates.""" release_dir = config.music_source_dir / TEST_RELEASE_1.name shutil.copytree(TEST_RELEASE_1, release_dir) update_cache_for_releases(config, [release_dir]) # I'm too lazy to mutagen update the files, so instead we're going to update the database. And # then touch a file to signify that "we modified it." with connect(config) as conn: conn.execute("UPDATE releases SET title = 'An Uncool Album'") (release_dir / "01.m4a").touch() update_cache_for_releases(config, [release_dir]) # Assert that the release metadata was re-read and updated correctly. with connect(config) as conn: cursor = conn.execute( "SELECT id, source_path, title, releasetype, year, new FROM releases", ) row = cursor.fetchone() assert row["source_path"] == str(release_dir) assert row["title"] == "I Love Blackpink" assert row["releasetype"] == "album" assert row["year"] == 1990 assert row["new"] def test_update_cache_releases_disk_update_to_datafile(config: Config) -> None: """Test that a cached release is updated after a datafile updates.""" release_dir = config.music_source_dir / TEST_RELEASE_1.name shutil.copytree(TEST_RELEASE_1, release_dir) update_cache_for_releases(config, [release_dir]) with connect(config) as conn: conn.execute("UPDATE releases SET datafile_mtime = '0' AND new = false") update_cache_for_releases(config, [release_dir]) # Assert that the release metadata was re-read and updated correctly. with connect(config) as conn: cursor = conn.execute("SELECT new, added_at FROM releases") row = cursor.fetchone() assert row["new"] assert row["added_at"] def test_update_cache_releases_disk_upgrade_old_datafile(config: Config) -> None: """Test that a legacy invalid datafile is upgraded on index.""" release_dir = config.music_source_dir / TEST_RELEASE_1.name shutil.copytree(TEST_RELEASE_1, release_dir) datafile = release_dir / ".rose.lalala.toml" datafile.touch() update_cache_for_releases(config, [release_dir]) # Assert that the release metadata was re-read and updated correctly. with connect(config) as conn: cursor = conn.execute("SELECT id, new, added_at FROM releases") row = cursor.fetchone() assert row["id"] == "lalala" assert row["new"] assert row["added_at"] with datafile.open("r") as fp: data = fp.read() assert "new = true" in data assert "added_at = " in data def test_update_cache_releases_source_path_renamed(config: Config) -> None: """Test that a cached release is updated after a directory rename.""" release_dir = config.music_source_dir / TEST_RELEASE_1.name shutil.copytree(TEST_RELEASE_1, release_dir) update_cache_for_releases(config, [release_dir]) moved_release_dir = config.music_source_dir / "moved lol" release_dir.rename(moved_release_dir) update_cache_for_releases(config, [moved_release_dir]) # Assert that the release metadata was re-read and updated correctly. with connect(config) as conn: cursor = conn.execute( "SELECT id, source_path, title, releasetype, year, new FROM releases", ) row = cursor.fetchone() assert row["source_path"] == str(moved_release_dir) assert row["title"] == "I Love Blackpink" assert row["releasetype"] == "album" assert row["year"] == 1990 assert row["new"] def test_update_cache_releases_delete_nonexistent(config: Config) -> None: """Test that deleted releases that are no longer on disk are cleared from cache.""" with connect(config) as conn: conn.execute( """ INSERT INTO releases (id, source_path, added_at, datafile_mtime, title, releasetype, disctotal, metahash) VALUES ('aaaaaa', '0000-01-01T00:00:00+00:00', '999', 'nonexistent', 'aa', 'unknown', false, '0') """ )
def test_schema(config: Config) -> None: """Test that the schema successfully bootstraps.""" with CACHE_SCHEMA_PATH.open("rb") as fp: schema_hash = hashlib.sha256(fp.read()).hexdigest() maybe_invalidate_cache_database(config) with connect(config) as conn: cursor = conn.execute("SELECT schema_hash, config_hash, version FROM _schema_hash") row = cursor.fetchone() assert row["schema_hash"] == schema_hash assert row["config_hash"] is not None assert row["version"] == VERSION def test_migration(config: Config) -> None: """Test that "migrating" the database correctly migrates it.""" config.cache_database_path.unlink() with connect(config) as conn: conn.execute( """ CREATE TABLE _schema_hash ( schema_hash TEXT , config_hash TEXT , version TEXT , PRIMARY KEY (schema_hash, config_hash, version) ) """ ) conn.execute( """ INSERT INTO _schema_hash (schema_hash, config_hash, version) VALUES ('haha', 'lala', 'blabla') """, ) with CACHE_SCHEMA_PATH.open("rb") as fp: latest_schema_hash = hashlib.sha256(fp.read()).hexdigest() maybe_invalidate_cache_database(config) with connect(config) as conn: cursor = conn.execute("SELECT schema_hash, config_hash, version FROM _schema_hash") row = cursor.fetchone() assert row["schema_hash"] == latest_schema_hash assert row["config_hash"] is not None assert row["version"] == VERSION cursor = conn.execute("SELECT COUNT(*) FROM _schema_hash") assert cursor.fetchone()[0] == 1 def test_locks(config: Config) -> None: """Test that taking locks works. The times are a bit loose b/c GH Actions is slow.""" lock_name = "lol" # Test that the locking and timeout work. start = time.time() with lock(config, lock_name, timeout=0.2): lock1_acq = time.time() with lock(config, lock_name, timeout=0.2): lock2_acq = time.time() # Assert that we had to wait ~0.1sec to get the second lock. assert lock1_acq - start < 0.08 assert lock2_acq - lock1_acq > 0.17 # Test that releasing a lock actually works. start = time.time() with lock(config, lock_name, timeout=0.2): lock1_acq = time.time() with lock(config, lock_name, timeout=0.2): lock2_acq = time.time() # Assert that we had to wait negligible time to get the second lock. assert lock1_acq - start < 0.08 assert lock2_acq - lock1_acq < 0.08 def test_update_cache_all(config: Config) -> None: """Test that the update all function works.""" shutil.copytree(TEST_RELEASE_1, config.music_source_dir / TEST_RELEASE_1.name) shutil.copytree(TEST_RELEASE_2, config.music_source_dir / TEST_RELEASE_2.name) # Test that we prune deleted releases too. with connect(config) as conn: conn.execute( """ INSERT INTO releases (id, source_path, added_at, datafile_mtime, title, releasetype, disctotal, metahash) VALUES ('aaaaaa', '0000-01-01T00:00:00+00:00', '999', 'nonexistent', 'aa', 'unknown', false, '0') """ ) update_cache(config) with connect(config) as conn: cursor = conn.execute("SELECT COUNT(*) FROM releases") assert cursor.fetchone()[0] == 2 cursor = conn.execute("SELECT COUNT(*) FROM tracks") assert cursor.fetchone()[0] == 4 def test_update_cache_multiprocessing(config: Config) -> None: """Test that the update all function works.""" shutil.copytree(TEST_RELEASE_1, config.music_source_dir / TEST_RELEASE_1.name) shutil.copytree(TEST_RELEASE_2, config.music_source_dir / TEST_RELEASE_2.name) update_cache_for_releases(config, force_multiprocessing=True) with connect(config) as conn: cursor = conn.execute("SELECT COUNT(*) FROM releases") assert cursor.fetchone()[0] == 2 cursor = conn.execute("SELECT COUNT(*) FROM tracks") assert cursor.fetchone()[0] == 4 def test_update_cache_releases(config: Config) -> None: release_dir = config.music_source_dir / TEST_RELEASE_1.name shutil.copytree(TEST_RELEASE_1, release_dir) update_cache_for_releases(config, [release_dir]) # Check that the release directory was given a UUID. release_id: str | None = None for f in release_dir.iterdir(): if m := STORED_DATA_FILE_REGEX.match(f.name): release_id = m[1] assert release_id is not None # Assert that the release metadata was read correctly. with connect(config) as conn: cursor = conn.execute( """ SELECT id, source_path, title, releasetype, year, new FROM releases WHERE id = ? """, (release_id,), ) row = cursor.fetchone() assert row["source_path"] == str(release_dir) assert row["title"] == "I Love Blackpink" assert row["releasetype"] == "album" assert row["year"] == 1990 assert row["new"] cursor = conn.execute( "SELECT genre FROM releases_genres WHERE release_id = ?", (release_id,), ) genres = {r["genre"] for r in cursor.fetchall()} assert genres == {"K-Pop", "Pop"} cursor = conn.execute( "SELECT label FROM releases_labels WHERE release_id = ?", (release_id,), ) labels = {r["label"] for r in cursor.fetchall()} assert labels == {"A Cool Label"} cursor = conn.execute( "SELECT artist, role FROM releases_artists WHERE release_id = ?", (release_id,), ) artists = {(r["artist"], r["role"]) for r in cursor.fetchall()} assert artists == { ("BLACKPINK", "main"), } for f in release_dir.iterdir(): if f.suffix != ".m4a": continue # Assert that the track metadata was read correctly. cursor = conn.execute( """ SELECT id, source_path, title, release_id, tracknumber, discnumber, duration_seconds FROM tracks WHERE source_path = ? """, (str(f),), ) row = cursor.fetchone() track_id = row["id"] assert row["title"].startswith("Track") assert row["release_id"] == release_id assert row["tracknumber"] != "" assert row["discnumber"] == "1" assert row["duration_seconds"] == 2 cursor = conn.execute( "SELECT artist, role FROM tracks_artists WHERE track_id = ?", (track_id,), ) artists = {(r["artist"], r["role"]) for r in cursor.fetchall()} assert artists == { ("BLACKPINK", "main"), } def test_update_cache_releases_uncached_with_existing_id(config: Config) -> None: """Test that IDs in filenames are read and preserved.""" release_dir = config.music_source_dir / TEST_RELEASE_2.name shutil.copytree(TEST_RELEASE_2, release_dir) update_cache_for_releases(config, [release_dir]) # Check that the release directory was given a UUID. release_id: str | None = None for f in release_dir.iterdir(): if m := STORED_DATA_FILE_REGEX.match(f.name): release_id = m[1] assert release_id == "ilovecarly" # Hardcoded ID for testing. def test_update_cache_releases_preserves_track_ids_across_rebuilds(config: Config) -> None: """Test that track IDs are preserved across cache rebuilds.""" release_dir = config.music_source_dir / TEST_RELEASE_3.name shutil.copytree(TEST_RELEASE_3, release_dir) update_cache_for_releases(config, [release_dir]) with connect(config) as conn: cursor = conn.execute("SELECT id FROM tracks") first_track_ids = {r["id"] for r in cursor} # Nuke the database. config.cache_database_path.unlink() maybe_invalidate_cache_database(config) # Repeat cache population. update_cache_for_releases(config, [release_dir]) with connect(config) as conn: cursor = conn.execute("SELECT id FROM tracks") second_track_ids = {r["id"] for r in cursor} # Assert IDs are equivalent. assert first_track_ids == second_track_ids def test_update_cache_releases_writes_ids_to_tags(config: Config) -> None: """Test that track IDs and release IDs are written to files.""" release_dir = config.music_source_dir / TEST_RELEASE_3.name shutil.copytree(TEST_RELEASE_3, release_dir) af = AudioTags.from_file(release_dir / "01.m4a") assert af.id is None assert af.release_id is None af = AudioTags.from_file(release_dir / "02.m4a") assert af.id is None assert af.release_id is None update_cache_for_releases(config, [release_dir]) af = AudioTags.from_file(release_dir / "01.m4a") assert af.id is not None assert af.release_id is not None af = AudioTags.from_file(release_dir / "02.m4a") assert af.id is not None assert af.release_id is not None def test_update_cache_releases_already_fully_cached(config: Config) -> None: """Test that a fully cached release No Ops when updated again.""" release_dir = config.music_source_dir / TEST_RELEASE_1.name shutil.copytree(TEST_RELEASE_1, release_dir) update_cache_for_releases(config, [release_dir]) update_cache_for_releases(config, [release_dir]) # Assert that the release metadata was read correctly. with connect(config) as conn: cursor = conn.execute( "SELECT id, source_path, title, releasetype, year, new FROM releases", ) row = cursor.fetchone() assert row["source_path"] == str(release_dir) assert row["title"] == "I Love Blackpink" assert row["releasetype"] == "album" assert row["year"] == 1990 assert row["new"] def test_update_cache_releases_disk_update_to_previously_cached(config: Config) -> None: """Test that a cached release is updated after a track updates.""" release_dir = config.music_source_dir / TEST_RELEASE_1.name shutil.copytree(TEST_RELEASE_1, release_dir) update_cache_for_releases(config, [release_dir]) # I'm too lazy to mutagen update the files, so instead we're going to update the database. And # then touch a file to signify that "we modified it." with connect(config) as conn: conn.execute("UPDATE releases SET title = 'An Uncool Album'") (release_dir / "01.m4a").touch() update_cache_for_releases(config, [release_dir]) # Assert that the release metadata was re-read and updated correctly. with connect(config) as conn: cursor = conn.execute( "SELECT id, source_path, title, releasetype, year, new FROM releases", ) row = cursor.fetchone() assert row["source_path"] == str(release_dir) assert row["title"] == "I Love Blackpink" assert row["releasetype"] == "album" assert row["year"] == 1990 assert row["new"] def test_update_cache_releases_disk_update_to_datafile(config: Config) -> None: """Test that a cached release is updated after a datafile updates.""" release_dir = config.music_source_dir / TEST_RELEASE_1.name shutil.copytree(TEST_RELEASE_1, release_dir) update_cache_for_releases(config, [release_dir]) with connect(config) as conn: conn.execute("UPDATE releases SET datafile_mtime = '0' AND new = false") update_cache_for_releases(config, [release_dir]) # Assert that the release metadata was re-read and updated correctly. with connect(config) as conn: cursor = conn.execute("SELECT new, added_at FROM releases") row = cursor.fetchone() assert row["new"] assert row["added_at"] def test_update_cache_releases_disk_upgrade_old_datafile(config: Config) -> None: """Test that a legacy invalid datafile is upgraded on index.""" release_dir = config.music_source_dir / TEST_RELEASE_1.name shutil.copytree(TEST_RELEASE_1, release_dir) datafile = release_dir / ".rose.lalala.toml" datafile.touch() update_cache_for_releases(config, [release_dir]) # Assert that the release metadata was re-read and updated correctly. with connect(config) as conn: cursor = conn.execute("SELECT id, new, added_at FROM releases") row = cursor.fetchone() assert row["id"] == "lalala" assert row["new"] assert row["added_at"] with datafile.open("r") as fp: data = fp.read() assert "new = true" in data assert "added_at = " in data def test_update_cache_releases_source_path_renamed(config: Config) -> None: """Test that a cached release is updated after a directory rename.""" release_dir = config.music_source_dir / TEST_RELEASE_1.name shutil.copytree(TEST_RELEASE_1, release_dir) update_cache_for_releases(config, [release_dir]) moved_release_dir = config.music_source_dir / "moved lol" release_dir.rename(moved_release_dir) update_cache_for_releases(config, [moved_release_dir]) # Assert that the release metadata was re-read and updated correctly. with connect(config) as conn: cursor = conn.execute( "SELECT id, source_path, title, releasetype, year, new FROM releases", ) row = cursor.fetchone() assert row["source_path"] == str(moved_release_dir) assert row["title"] == "I Love Blackpink" assert row["releasetype"] == "album" assert row["year"] == 1990 assert row["new"] def test_update_cache_releases_delete_nonexistent(config: Config) -> None: """Test that deleted releases that are no longer on disk are cleared from cache.""" with connect(config) as conn: conn.execute( """ INSERT INTO releases (id, source_path, added_at, datafile_mtime, title, releasetype, disctotal, metahash) VALUES ('aaaaaa', '0000-01-01T00:00:00+00:00', '999', 'nonexistent', 'aa', 'unknown', false, '0') """ )
update_cache_evict_nonexistent_releases(config)
35
2023-10-09 14:42:23+00:00
24k
zhaoyizhou1123/mbrcsl
examples/pointmaze/run_combo_maze.py
[ { "identifier": "MLP", "path": "offlinerlkit/nets/mlp.py", "snippet": "class MLP(nn.Module):\n def __init__(\n self,\n input_dim: int,\n hidden_dims: Union[List[int], Tuple[int]],\n output_dim: Optional[int] = None,\n activation: nn.Module = nn.ReLU,\n dropout_rate: Optional[float] = None,\n init_last: bool = False\n ) -> None:\n super().__init__()\n hidden_dims = [input_dim] + list(hidden_dims)\n model = []\n for in_dim, out_dim in zip(hidden_dims[:-1], hidden_dims[1:]):\n model += [nn.Linear(in_dim, out_dim), activation()]\n if dropout_rate is not None:\n model += [nn.Dropout(p=dropout_rate)]\n\n self.output_dim = hidden_dims[-1]\n if output_dim is not None:\n last_layer = nn.Linear(hidden_dims[-1], output_dim)\n if init_last:\n nn.init.xavier_uniform_(last_layer.weight, gain=1e-2)\n nn.init.constant_(last_layer.bias, 0.0)\n model += [last_layer]\n self.output_dim = output_dim\n self.model = nn.Sequential(*model)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return self.model(x)" }, { "identifier": "ActorProb", "path": "offlinerlkit/modules/actor_module.py", "snippet": "class ActorProb(nn.Module):\n def __init__(\n self,\n backbone: nn.Module,\n dist_net: nn.Module,\n device: str = \"cpu\"\n ) -> None:\n super().__init__()\n\n self.device = torch.device(device)\n self.backbone = backbone.to(device)\n self.dist_net = dist_net.to(device)\n\n def forward(self, obs: Union[np.ndarray, torch.Tensor]) -> torch.distributions.Normal:\n obs = torch.as_tensor(obs, device=self.device, dtype=torch.float32)\n logits = self.backbone(obs)\n dist = self.dist_net(logits)\n return dist" }, { "identifier": "Critic", "path": "offlinerlkit/modules/critic_module.py", "snippet": "class Critic(nn.Module):\n def __init__(self, backbone: nn.Module, device: str = \"cpu\") -> None:\n super().__init__()\n\n self.device = torch.device(device)\n self.backbone = backbone.to(device)\n latent_dim = getattr(backbone, \"output_dim\")\n self.last = nn.Linear(latent_dim, 1).to(device)\n\n def forward(\n self,\n obs: Union[np.ndarray, torch.Tensor],\n actions: Optional[Union[np.ndarray, torch.Tensor]] = None\n ) -> torch.Tensor:\n obs = torch.as_tensor(obs, device=self.device, dtype=torch.float32)\n if actions is not None:\n actions = torch.as_tensor(actions, device=self.device, dtype=torch.float32).flatten(1)\n obs = torch.cat([obs, actions], dim=1)\n logits = self.backbone(obs)\n values = self.last(logits)\n return values" }, { "identifier": "TanhDiagGaussian", "path": "offlinerlkit/modules/dist_module.py", "snippet": "class TanhDiagGaussian(DiagGaussian):\n def __init__(\n self,\n latent_dim,\n output_dim,\n unbounded=False,\n conditioned_sigma=False,\n max_mu=1.0,\n sigma_min=-5.0,\n sigma_max=2.0\n ):\n super().__init__(\n latent_dim=latent_dim,\n output_dim=output_dim,\n unbounded=unbounded,\n conditioned_sigma=conditioned_sigma,\n max_mu=max_mu,\n sigma_min=sigma_min,\n sigma_max=sigma_max\n )\n\n def forward(self, logits):\n mu = self.mu(logits)\n if not self._unbounded:\n mu = self._max * torch.tanh(mu)\n if self._c_sigma:\n sigma = torch.clamp(self.sigma(logits), min=self._sigma_min, max=self._sigma_max).exp()\n else:\n shape = [1] * len(mu.shape)\n shape[1] = -1\n sigma = (self.sigma_param.view(shape) + torch.zeros_like(mu)).exp()\n return TanhNormalWrapper(mu, sigma)" }, { "identifier": "EnsembleDynamicsModel", "path": "offlinerlkit/modules/dynamics_module.py", "snippet": "class EnsembleDynamicsModel(nn.Module):\n def __init__(\n self,\n obs_dim: int,\n action_dim: int,\n hidden_dims: Union[List[int], Tuple[int]],\n num_ensemble: int = 7,\n num_elites: int = 5,\n activation: nn.Module = Swish,\n weight_decays: Optional[Union[List[float], Tuple[float]]] = None,\n with_reward: bool = True,\n device: str = \"cpu\"\n ) -> None:\n super().__init__()\n\n self.num_ensemble = num_ensemble\n self.num_elites = num_elites\n self._with_reward = with_reward\n self.device = torch.device(device)\n\n self.activation = activation()\n\n assert len(weight_decays) == (len(hidden_dims) + 1)\n\n module_list = []\n hidden_dims = [obs_dim+action_dim] + list(hidden_dims)\n if weight_decays is None:\n weight_decays = [0.0] * (len(hidden_dims) + 1)\n for in_dim, out_dim, weight_decay in zip(hidden_dims[:-1], hidden_dims[1:], weight_decays[:-1]):\n module_list.append(EnsembleLinear(in_dim, out_dim, num_ensemble, weight_decay))\n self.backbones = nn.ModuleList(module_list)\n\n self.output_layer = EnsembleLinear(\n hidden_dims[-1],\n 2 * (obs_dim + self._with_reward),\n num_ensemble,\n weight_decays[-1]\n )\n\n self.register_parameter(\n \"max_logvar\",\n nn.Parameter(torch.ones(obs_dim + self._with_reward) * 0.5, requires_grad=True)\n )\n self.register_parameter(\n \"min_logvar\",\n nn.Parameter(torch.ones(obs_dim + self._with_reward) * -10, requires_grad=True)\n )\n\n self.register_parameter(\n \"elites\",\n nn.Parameter(torch.tensor(list(range(0, self.num_elites))), requires_grad=False)\n )\n\n self.to(self.device)\n\n def forward(self, obs_action: np.ndarray) -> Tuple[torch.Tensor, torch.Tensor]:\n obs_action = torch.as_tensor(obs_action, dtype=torch.float32).to(self.device)\n output = obs_action\n for layer in self.backbones:\n output = self.activation(layer(output))\n mean, logvar = torch.chunk(self.output_layer(output), 2, dim=-1)\n logvar = soft_clamp(logvar, self.min_logvar, self.max_logvar)\n return mean, logvar\n\n def load_save(self) -> None:\n for layer in self.backbones:\n layer.load_save()\n self.output_layer.load_save()\n\n def update_save(self, indexes: List[int]) -> None:\n for layer in self.backbones:\n layer.update_save(indexes)\n self.output_layer.update_save(indexes)\n \n def get_decay_loss(self) -> torch.Tensor:\n decay_loss = 0\n for layer in self.backbones:\n decay_loss += layer.get_decay_loss()\n decay_loss += self.output_layer.get_decay_loss()\n return decay_loss\n\n def set_elites(self, indexes: List[int]) -> None:\n assert len(indexes) <= self.num_ensemble and max(indexes) < self.num_ensemble\n self.register_parameter('elites', nn.Parameter(torch.tensor(indexes), requires_grad=False))\n \n def random_elite_idxs(self, batch_size: int) -> np.ndarray:\n idxs = np.random.choice(self.elites.data.cpu().numpy(), size=batch_size)\n return idxs" }, { "identifier": "EnsembleDynamics", "path": "offlinerlkit/dynamics/ensemble_dynamics.py", "snippet": "class EnsembleDynamics(BaseDynamics):\n def __init__(\n self,\n model: nn.Module,\n optim: torch.optim.Optimizer,\n scaler: StandardScaler,\n terminal_fn: Callable[[np.ndarray, np.ndarray, np.ndarray], np.ndarray],\n penalty_coef: float = 0.0,\n uncertainty_mode: str = \"aleatoric\"\n ) -> None:\n super().__init__(model, optim)\n self.scaler = scaler\n self.terminal_fn = terminal_fn\n self._penalty_coef = penalty_coef\n self._uncertainty_mode = uncertainty_mode\n\n @ torch.no_grad()\n def step(\n self,\n obs: np.ndarray,\n action: np.ndarray\n ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, Dict]:\n '''\n Return:\n reward (B,1) (if obs has batch)\n terminal (B,1)\n '''\n \"imagine single forward step\"\n obs_act = np.concatenate([obs, action], axis=-1)\n obs_act = self.scaler.transform(obs_act)\n mean, logvar = self.model(obs_act)\n mean = mean.cpu().numpy()\n logvar = logvar.cpu().numpy()\n mean[..., :-1] += obs # We estimated delta_obs\n std = np.sqrt(np.exp(logvar))\n\n ensemble_samples = (mean + np.random.normal(size=mean.shape) * std).astype(np.float32)\n\n # choose one model from ensemble\n num_models, batch_size, _ = ensemble_samples.shape\n model_idxs = self.model.random_elite_idxs(batch_size)\n samples = ensemble_samples[model_idxs, np.arange(batch_size)]\n \n next_obs = samples[..., :-1]\n reward = samples[..., -1:]\n terminal = self.terminal_fn(obs, action, next_obs)\n info = {}\n info[\"raw_reward\"] = reward\n\n if self._penalty_coef:\n if self._uncertainty_mode == \"aleatoric\":\n penalty = np.amax(np.linalg.norm(std, axis=2), axis=0)\n elif self._uncertainty_mode == \"pairwise-diff\":\n next_obses_mean = mean[..., :-1]\n next_obs_mean = np.mean(next_obses_mean, axis=0)\n diff = next_obses_mean - next_obs_mean\n penalty = np.amax(np.linalg.norm(diff, axis=2), axis=0)\n elif self._uncertainty_mode == \"ensemble_std\":\n next_obses_mean = mean[..., :-1]\n penalty = np.sqrt(next_obses_mean.var(0).mean(1))\n else:\n raise ValueError\n penalty = np.expand_dims(penalty, 1).astype(np.float32)\n assert penalty.shape == reward.shape\n reward = reward - self._penalty_coef * penalty\n info[\"penalty\"] = penalty\n \n return next_obs, reward, terminal, info\n \n @ torch.no_grad()\n def sample_next_obss(\n self,\n obs: torch.Tensor,\n action: torch.Tensor,\n num_samples: int\n ) -> torch.Tensor:\n obs_act = torch.cat([obs, action], dim=-1)\n obs_act = self.scaler.transform_tensor(obs_act)\n mean, logvar = self.model(obs_act)\n mean[..., :-1] += obs\n std = torch.sqrt(torch.exp(logvar))\n\n mean = mean[self.model.elites.data.cpu().numpy()]\n std = std[self.model.elites.data.cpu().numpy()]\n\n samples = torch.stack([mean + torch.randn_like(std) * std for i in range(num_samples)], 0)\n next_obss = samples[..., :-1]\n return next_obss\n\n def format_samples_for_training(self, data: Dict) -> Tuple[np.ndarray, np.ndarray]:\n obss = data[\"observations\"]\n actions = data[\"actions\"]\n next_obss = data[\"next_observations\"]\n rewards = data[\"rewards\"]\n rewards = rewards.reshape(rewards.shape[0], -1)\n delta_obss = next_obss - obss\n inputs = np.concatenate((obss, actions), axis=-1)\n targets = np.concatenate((delta_obss, rewards), axis=-1)\n return inputs, targets\n\n def train(\n self,\n data: Dict,\n logger: Logger,\n max_epochs: Optional[float] = None,\n max_epochs_since_update: int = 5,\n batch_size: int = 256,\n holdout_ratio: float = 0.2,\n logvar_loss_coef: float = 0.01\n ) -> None:\n inputs, targets = self.format_samples_for_training(data)\n data_size = inputs.shape[0]\n holdout_size = min(int(data_size * holdout_ratio), 1000)\n train_size = data_size - holdout_size\n train_splits, holdout_splits = torch.utils.data.random_split(range(data_size), (train_size, holdout_size))\n train_inputs, train_targets = inputs[train_splits.indices], targets[train_splits.indices]\n holdout_inputs, holdout_targets = inputs[holdout_splits.indices], targets[holdout_splits.indices]\n\n self.scaler.fit(train_inputs)\n train_inputs = self.scaler.transform(train_inputs)\n holdout_inputs = self.scaler.transform(holdout_inputs)\n holdout_losses = [1e10 for i in range(self.model.num_ensemble)]\n\n data_idxes = np.random.randint(train_size, size=[self.model.num_ensemble, train_size])\n def shuffle_rows(arr):\n idxes = np.argsort(np.random.uniform(size=arr.shape), axis=-1)\n return arr[np.arange(arr.shape[0])[:, None], idxes]\n\n epoch = 0\n cnt = 0\n logger.log(\"Training dynamics:\")\n while True:\n epoch += 1\n train_loss = self.learn(train_inputs[data_idxes], train_targets[data_idxes], batch_size, logvar_loss_coef)\n new_holdout_losses = self.validate(holdout_inputs, holdout_targets)\n holdout_loss = (np.sort(new_holdout_losses)[:self.model.num_elites]).mean()\n logger.logkv(\"loss/dynamics_train_loss\", train_loss)\n logger.logkv(\"loss/dynamics_holdout_loss\", holdout_loss)\n logger.set_timestep(epoch)\n logger.dumpkvs(exclude=[\"policy_training_progress\"])\n\n # shuffle data for each base learner\n data_idxes = shuffle_rows(data_idxes)\n\n indexes = []\n for i, new_loss, old_loss in zip(range(len(holdout_losses)), new_holdout_losses, holdout_losses):\n improvement = (old_loss - new_loss) / old_loss\n if improvement > 0.01:\n indexes.append(i)\n holdout_losses[i] = new_loss\n \n if len(indexes) > 0:\n self.model.update_save(indexes)\n cnt = 0\n else:\n cnt += 1\n \n if (cnt >= max_epochs_since_update) or (max_epochs and (epoch >= max_epochs)):\n break\n\n indexes = self.select_elites(holdout_losses)\n self.model.set_elites(indexes)\n self.model.load_save()\n self.save(logger.model_dir)\n self.model.eval()\n logger.log(\"elites:{} , holdout loss: {}\".format(indexes, (np.sort(holdout_losses)[:self.model.num_elites]).mean()))\n \n def learn(\n self,\n inputs: np.ndarray,\n targets: np.ndarray,\n batch_size: int = 256,\n logvar_loss_coef: float = 0.01\n ) -> float:\n self.model.train()\n train_size = inputs.shape[1]\n losses = []\n\n for batch_num in range(int(np.ceil(train_size / batch_size))):\n inputs_batch = inputs[:, batch_num * batch_size:(batch_num + 1) * batch_size]\n targets_batch = targets[:, batch_num * batch_size:(batch_num + 1) * batch_size]\n targets_batch = torch.as_tensor(targets_batch).to(self.model.device)\n \n mean, logvar = self.model(inputs_batch)\n inv_var = torch.exp(-logvar)\n # Average over batch and dim, sum over ensembles.\n mse_loss_inv = (torch.pow(mean - targets_batch, 2) * inv_var).mean(dim=(1, 2)) # MLE for Gaussian\n var_loss = logvar.mean(dim=(1, 2))\n loss = mse_loss_inv.sum() + var_loss.sum()\n loss = loss + self.model.get_decay_loss()\n loss = loss + logvar_loss_coef * self.model.max_logvar.sum() - logvar_loss_coef * self.model.min_logvar.sum()\n\n self.optim.zero_grad()\n loss.backward()\n self.optim.step()\n\n losses.append(loss.item())\n return np.mean(losses)\n \n @ torch.no_grad()\n def validate(self, inputs: np.ndarray, targets: np.ndarray) -> List[float]:\n self.model.eval()\n targets = torch.as_tensor(targets).to(self.model.device)\n mean, _ = self.model(inputs)\n loss = ((mean - targets) ** 2).mean(dim=(1, 2))\n val_loss = list(loss.cpu().numpy())\n return val_loss\n \n def select_elites(self, metrics: List) -> List[int]:\n pairs = [(metric, index) for metric, index in zip(metrics, range(len(metrics)))]\n pairs = sorted(pairs, key=lambda x: x[0])\n elites = [pairs[i][1] for i in range(self.model.num_elites)]\n return elites\n\n def save(self, save_path: str) -> None:\n torch.save(self.model.state_dict(), os.path.join(save_path, \"dynamics.pth\"))\n self.scaler.save_scaler(save_path)\n \n def load(self, load_path: str) -> None:\n self.model.load_state_dict(torch.load(os.path.join(load_path, \"dynamics.pth\"), map_location=self.model.device))\n self.scaler.load_scaler(load_path)" }, { "identifier": "StandardScaler", "path": "offlinerlkit/utils/scaler.py", "snippet": "class StandardScaler(object):\n def __init__(self, mu=None, std=None):\n self.mu = mu\n self.std = std\n\n def fit(self, data):\n \"\"\"Runs two ops, one for assigning the mean of the data to the internal mean, and\n another for assigning the standard deviation of the data to the internal standard deviation.\n This function must be called within a 'with <session>.as_default()' block.\n\n Arguments:\n data (np.ndarray): A numpy array containing the input\n\n Returns: None.\n \"\"\"\n self.mu = np.mean(data, axis=0, keepdims=True)\n self.std = np.std(data, axis=0, keepdims=True)\n self.std[self.std < 1e-12] = 1.0\n\n def transform(self, data):\n \"\"\"Transforms the input matrix data using the parameters of this scaler.\n\n Arguments:\n data (np.array): A numpy array containing the points to be transformed.\n\n Returns: (np.array) The transformed dataset.\n \"\"\"\n return (data - self.mu) / self.std\n\n def inverse_transform(self, data):\n \"\"\"Undoes the transformation performed by this scaler.\n\n Arguments:\n data (np.array): A numpy array containing the points to be transformed.\n\n Returns: (np.array) The transformed dataset.\n \"\"\"\n return self.std * data + self.mu\n \n def save_scaler(self, save_path):\n mu_path = path.join(save_path, \"mu.npy\")\n std_path = path.join(save_path, \"std.npy\")\n np.save(mu_path, self.mu)\n np.save(std_path, self.std)\n \n def load_scaler(self, load_path):\n mu_path = path.join(load_path, \"mu.npy\")\n std_path = path.join(load_path, \"std.npy\")\n self.mu = np.load(mu_path)\n self.std = np.load(std_path)\n\n def transform_tensor(self, data: torch.Tensor):\n device = data.device\n data = self.transform(data.cpu().numpy())\n data = torch.tensor(data, device=device)\n return data" }, { "identifier": "termination_fn_default", "path": "offlinerlkit/utils/termination_fns.py", "snippet": "def termination_fn_default(obs, act, next_obs):\n '''\n Return np.ndarray (obs.shape[0], 1)\n '''\n done = np.array([False] * obs.shape[0])\n done = done[:, None]\n return done" }, { "identifier": "ReplayBuffer", "path": "offlinerlkit/buffer/buffer.py", "snippet": "class ReplayBuffer:\n def __init__(\n self,\n buffer_size: int,\n obs_shape: Tuple,\n obs_dtype: np.dtype,\n action_dim: int,\n action_dtype: np.dtype,\n device: str = \"cpu\"\n ) -> None:\n self._max_size = buffer_size\n self.obs_shape = obs_shape\n self.obs_dtype = obs_dtype\n self.action_dim = action_dim\n self.action_dtype = action_dtype\n\n self._ptr = 0\n self._size = 0\n\n self.observations = np.zeros((self._max_size,) + self.obs_shape, dtype=obs_dtype)\n self.next_observations = np.zeros((self._max_size,) + self.obs_shape, dtype=obs_dtype)\n self.actions = np.zeros((self._max_size, self.action_dim), dtype=action_dtype)\n self.rewards = np.zeros((self._max_size, 1), dtype=np.float32)\n self.terminals = np.zeros((self._max_size, 1), dtype=np.float32)\n\n self.device = torch.device(device)\n\n def add(\n self,\n obs: np.ndarray,\n next_obs: np.ndarray,\n action: np.ndarray,\n reward: np.ndarray,\n terminal: np.ndarray\n ) -> None:\n # Copy to avoid modification by reference\n self.observations[self._ptr] = np.array(obs).copy()\n self.next_observations[self._ptr] = np.array(next_obs).copy()\n self.actions[self._ptr] = np.array(action).copy()\n self.rewards[self._ptr] = np.array(reward).copy()\n self.terminals[self._ptr] = np.array(terminal).copy()\n\n self._ptr = (self._ptr + 1) % self._max_size\n self._size = min(self._size + 1, self._max_size)\n \n def add_batch(\n self,\n obss: np.ndarray,\n next_obss: np.ndarray,\n actions: np.ndarray,\n rewards: np.ndarray,\n terminals: np.ndarray\n ) -> None:\n batch_size = len(obss)\n indexes = np.arange(self._ptr, self._ptr + batch_size) % self._max_size\n\n self.observations[indexes] = np.array(obss).copy()\n self.next_observations[indexes] = np.array(next_obss).copy()\n self.actions[indexes] = np.array(actions).copy()\n self.rewards[indexes] = np.array(rewards).copy()\n self.terminals[indexes] = np.array(terminals).copy()\n\n self._ptr = (self._ptr + batch_size) % self._max_size\n self._size = min(self._size + batch_size, self._max_size)\n \n def load_dataset(self, dataset: Dict[str, np.ndarray]) -> None:\n observations = np.array(dataset[\"observations\"], dtype=self.obs_dtype)\n next_observations = np.array(dataset[\"next_observations\"], dtype=self.obs_dtype)\n actions = np.array(dataset[\"actions\"], dtype=self.action_dtype)\n rewards = np.array(dataset[\"rewards\"], dtype=np.float32).reshape(-1, 1)\n terminals = np.array(dataset[\"terminals\"], dtype=np.float32).reshape(-1, 1)\n\n self.observations = observations\n self.next_observations = next_observations\n self.actions = actions\n self.rewards = rewards\n self.terminals = terminals\n\n self._ptr = len(observations)\n self._size = len(observations)\n \n def normalize_obs(self, eps: float = 1e-3) -> Tuple[np.ndarray, np.ndarray]:\n mean = self.observations.mean(0, keepdims=True)\n std = self.observations.std(0, keepdims=True) + eps\n self.observations = (self.observations - mean) / std\n self.next_observations = (self.next_observations - mean) / std\n obs_mean, obs_std = mean, std\n return obs_mean, obs_std\n\n def sample(self, batch_size: int) -> Dict[str, torch.Tensor]:\n\n batch_indexes = np.random.randint(0, self._size, size=batch_size)\n \n return {\n \"observations\": torch.tensor(self.observations[batch_indexes]).to(self.device),\n \"actions\": torch.tensor(self.actions[batch_indexes]).to(self.device),\n \"next_observations\": torch.tensor(self.next_observations[batch_indexes]).to(self.device),\n \"terminals\": torch.tensor(self.terminals[batch_indexes]).to(self.device),\n \"rewards\": torch.tensor(self.rewards[batch_indexes]).to(self.device)\n }\n \n def sample_all(self) -> Dict[str, np.ndarray]:\n return {\n \"observations\": self.observations[:self._size].copy(),\n \"actions\": self.actions[:self._size].copy(),\n \"next_observations\": self.next_observations[:self._size].copy(),\n \"terminals\": self.terminals[:self._size].copy(),\n \"rewards\": self.rewards[:self._size].copy()\n }" }, { "identifier": "Logger", "path": "offlinerlkit/utils/logger.py", "snippet": "class Logger(object):\n def __init__(self, dir: str, ouput_config: Dict) -> None:\n self._dir = dir\n self._init_dirs()\n self._init_ouput_handlers(ouput_config)\n self._name2val = defaultdict(float)\n self._name2cnt = defaultdict(int)\n self._level = INFO\n self._timestep = 0\n \n def _init_dirs(self) -> None:\n self._record_dir = os.path.join(self._dir, \"record\")\n self._checkpoint_dir = os.path.join(self._dir, \"checkpoint\")\n self._model_dir = os.path.join(self._dir, \"model\")\n self._result_dir = os.path.join(self._dir, \"result\")\n os.mkdir(self._record_dir)\n os.mkdir(self._checkpoint_dir)\n os.mkdir(self._model_dir)\n os.mkdir(self._result_dir)\n \n def _init_ouput_handlers(self, output_config: Dict) -> None:\n self._output_handlers = []\n for file_name, fmt in output_config.items():\n try:\n self._output_handlers.append(HANDLER[fmt](os.path.join(self._record_dir, file_name)))\n except KeyError:\n warnings.warn(\"Invalid output type, Valid types: stdout, csv, tensorboard\", DeprecationWarning)\n # default output to console\n self._output_handlers.append(StandardOutputHandler(sys.stdout))\n \n def log_hyperparameters(self, hyper_param: Dict) -> None:\n json_output_handler = JSONOutputHandler(os.path.join(self._record_dir, \"hyper_param\"))\n json_output_handler.writekvs(hyper_param)\n json_output_handler.close()\n for handler in self._output_handlers:\n if isinstance(handler, TensorBoardOutputHandler):\n handler.add_hyper_params_to_tb(hyper_param)\n\n def logkv(self, key: Any, val: Any) -> None:\n \"\"\"\n Log a value of some diagnostic\n Call this once for each diagnostic quantity, each iteration\n If called many times, last value will be used.\n \"\"\"\n self._name2val[key] = val\n\n def logkv_mean(self, key: Any, val: Number) -> None:\n \"\"\"\n The same as logkv(), but if called many times, values averaged.\n \"\"\"\n oldval, cnt = self._name2val[key], self._name2cnt[key]\n self._name2val[key] = oldval*cnt/(cnt+1) + val/(cnt+1)\n self._name2cnt[key] = cnt + 1\n\n def dumpkvs(self, exclude:Optional[Union[str, Tuple[str, ...]]]=None) -> None:\n # log timestep\n self.logkv(DEFAULT_X_NAME, self._timestep)\n for handler in self._output_handlers:\n if isinstance(handler, KVWriter):\n if exclude is not None and handler.handler_name in exclude:\n continue\n handler.writekvs(self._name2val)\n self._name2val.clear()\n self._name2cnt.clear()\n\n def log(self, s: str, level=INFO) -> None:\n for handler in self._output_handlers:\n if isinstance(handler, StandardOutputHandler):\n handler.writestr(s)\n \n def set_timestep(self, timestep: int) -> None:\n self._timestep = timestep\n for handler in self._output_handlers:\n if isinstance(handler, TensorBoardOutputHandler):\n handler.set_step(timestep)\n\n def set_level(self, level) -> None:\n self._level = level\n\n @property\n def record_dir(self) -> str:\n return self._record_dir\n \n @property\n def checkpoint_dir(self) -> str:\n return self._checkpoint_dir\n\n @property\n def model_dir(self) -> str:\n return self._model_dir\n \n @property\n def result_dir(self) -> str:\n return self._result_dir\n \n def close(self) -> None:\n for handler in self._output_handlers:\n handler.close()" }, { "identifier": "make_log_dirs", "path": "offlinerlkit/utils/logger.py", "snippet": "def make_log_dirs(\n task_name: str,\n algo_name: str,\n exp_name: str,\n args: Dict,\n part: Optional[str] = None,\n record_params: Optional[List]=None\n) -> str:\n if record_params is not None:\n for param_name in record_params:\n algo_name += f\"&{param_name}={args[param_name]}\"\n\n if part is not None:\n log_dirs = os.path.join(ROOT_DIR, task_name, algo_name, exp_name, part)\n else:\n log_dirs = os.path.join(ROOT_DIR, task_name, algo_name, exp_name)\n os.makedirs(log_dirs)\n return log_dirs" }, { "identifier": "MBPolicyTrainer", "path": "offlinerlkit/policy_trainer/mb_policy_trainer.py", "snippet": "class MBPolicyTrainer:\n def __init__(\n self,\n policy: BasePolicy,\n eval_env: Union[gym.Env, gymnasium.Env],\n real_buffer: ReplayBuffer,\n fake_buffer: ReplayBuffer,\n logger: Logger,\n rollout_setting: Tuple[int, int, int],\n epoch: int = 1000,\n step_per_epoch: int = 1000,\n batch_size: int = 256,\n real_ratio: float = 0.05,\n eval_episodes: int = 10,\n lr_scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None,\n dynamics_update_freq: int = 0,\n horizon: Optional[int] = None,\n has_terminal = False,\n binary_ret = False\n ) -> None:\n self.policy = policy\n self.eval_env = eval_env\n self.horizon = horizon\n self.real_buffer = real_buffer\n self.fake_buffer = fake_buffer\n self.logger = logger\n\n self._rollout_freq, self._rollout_batch_size, \\\n self._rollout_length = rollout_setting\n self._dynamics_update_freq = dynamics_update_freq\n\n self._epoch = epoch\n self._step_per_epoch = step_per_epoch\n self._batch_size = batch_size\n self._real_ratio = real_ratio\n self._eval_episodes = eval_episodes\n self.lr_scheduler = lr_scheduler\n\n self.is_gymnasium_env = hasattr(self.eval_env, \"get_true_observation\")\n assert (not self.is_gymnasium_env) or (self.horizon is not None), \"Horizon must be specified for Gymnasium env\"\n self.has_terminal = has_terminal\n self.binary_ret = binary_ret\n\n def train(self, last_eval = False) -> Dict[str, float]:\n start_time = time.time()\n\n num_timesteps = 0\n last_10_performance = deque(maxlen=10)\n # train loop\n for e in range(1, self._epoch + 1):\n\n self.policy.train()\n\n pbar = tqdm(range(self._step_per_epoch), desc=f\"Epoch #{e}/{self._epoch}\")\n for it in pbar:\n if num_timesteps % self._rollout_freq == 0: # rollout periodically\n init_obss = self.real_buffer.sample(self._rollout_batch_size)[\"observations\"].cpu().numpy()\n rollout_transitions, rollout_info = self.policy.rollout(init_obss, self._rollout_length)\n self.fake_buffer.add_batch(**rollout_transitions)\n self.logger.log(\n \"num rollout transitions: {}, reward mean: {:.4f}\".\\\n format(rollout_info[\"num_transitions\"], rollout_info[\"reward_mean\"])\n )\n for _key, _value in rollout_info.items():\n self.logger.logkv_mean(\"rollout_info/\"+_key, _value)\n\n # Sample from both real (offline data) and fake (rollout data) according to real_ratio\n real_sample_size = int(self._batch_size * self._real_ratio)\n fake_sample_size = self._batch_size - real_sample_size\n real_batch = self.real_buffer.sample(batch_size=real_sample_size)\n fake_batch = self.fake_buffer.sample(batch_size=fake_sample_size)\n batch = {\"real\": real_batch, \"fake\": fake_batch}\n loss = self.policy.learn(batch)\n pbar.set_postfix(**loss)\n\n for k, v in loss.items():\n self.logger.logkv_mean(k, v)\n \n # update the dynamics if necessary\n if 0 < self._dynamics_update_freq and (num_timesteps+1)%self._dynamics_update_freq == 0:\n dynamics_update_info = self.policy.update_dynamics(self.real_buffer)\n for k, v in dynamics_update_info.items():\n self.logger.logkv_mean(k, v)\n \n num_timesteps += 1\n\n if self.lr_scheduler is not None:\n self.lr_scheduler.step()\n \n if last_eval and e < self._epoch: # When last_eval is True, only evaluate on last epoch\n pass\n else:\n # evaluate current policy\n eval_info = self._evaluate()\n ep_reward_mean, ep_reward_std = np.mean(eval_info[\"eval/episode_reward\"]), np.std(eval_info[\"eval/episode_reward\"])\n ep_length_mean, ep_length_std = np.mean(eval_info[\"eval/episode_length\"]), np.std(eval_info[\"eval/episode_length\"])\n\n if not hasattr(self.eval_env, \"get_normalized_score\"): # gymnasium_env does not have normalized score\n last_10_performance.append(ep_reward_mean)\n self.logger.logkv(\"eval/episode_reward\", ep_reward_mean)\n self.logger.logkv(\"eval/episode_reward_std\", ep_reward_std) \n else: \n norm_ep_rew_mean = self.eval_env.get_normalized_score(ep_reward_mean) * 100\n norm_ep_rew_std = self.eval_env.get_normalized_score(ep_reward_std) * 100\n last_10_performance.append(norm_ep_rew_mean)\n self.logger.logkv(\"eval/normalized_episode_reward\", norm_ep_rew_mean)\n self.logger.logkv(\"eval/normalized_episode_reward_std\", norm_ep_rew_std)\n self.logger.logkv(\"eval/episode_length\", ep_length_mean)\n self.logger.logkv(\"eval/episode_length_std\", ep_length_std)\n self.logger.set_timestep(num_timesteps)\n self.logger.dumpkvs(exclude=[\"dynamics_training_progress\"])\n \n # save checkpoint\n torch.save(self.policy.state_dict(), os.path.join(self.logger.checkpoint_dir, \"policy.pth\"))\n\n self.logger.log(\"total time: {:.2f}s\".format(time.time() - start_time))\n torch.save(self.policy.state_dict(), os.path.join(self.logger.model_dir, \"policy.pth\"))\n self.policy.dynamics.save(self.logger.model_dir)\n self.logger.close()\n \n return {\"last_10_performance\": np.mean(last_10_performance)}\n\n def _evaluate(self) -> Dict[str, List[float]]:\n is_gymnasium_env = self.is_gymnasium_env\n \n self.policy.eval()\n if is_gymnasium_env:\n obs, _ = self.eval_env.reset()\n obs = self.eval_env.get_true_observation(obs)\n else:\n obs = self.eval_env.reset()\n \n\n eval_ep_info_buffer = []\n num_episodes = 0\n episode_reward, episode_length = 0, 0\n\n if not self.has_terminal: # Finite horizon, terminal is unimportant\n while num_episodes < self._eval_episodes:\n for timestep in range(self.horizon): # One epoch\n # print(f\"Timestep {timestep}, obs {obs}\")\n action = self.policy.select_action(obs.reshape(1, -1), deterministic=True)\n if hasattr(self.eval_env, \"get_true_observation\"): # gymnasium env \n next_obs, reward, terminal, _, _ = self.eval_env.step(action.flatten())\n else:\n next_obs, reward, terminal, _ = self.eval_env.step(action.flatten())\n if is_gymnasium_env:\n next_obs = self.eval_env.get_true_observation(next_obs)\n episode_reward += reward\n episode_length += 1\n\n obs = next_obs\n\n if self.binary_ret:\n episode_reward = 1 if episode_reward >= 1 else 0\n eval_ep_info_buffer.append(\n {\"episode_reward\": episode_reward, \"episode_length\": episode_length}\n )\n num_episodes +=1\n episode_reward, episode_length = 0, 0\n if is_gymnasium_env:\n obs, _ = self.eval_env.reset()\n obs = self.eval_env.get_true_observation(obs)\n else:\n obs = self.eval_env.reset()\n else:\n while num_episodes < self._eval_episodes:\n action = self.policy.select_action(obs.reshape(1, -1), deterministic=True)\n if hasattr(self.eval_env, \"get_true_observation\"): # gymnasium env \n next_obs, reward, terminal, _, _ = self.eval_env.step(action.flatten())\n else:\n next_obs, reward, terminal, _ = self.eval_env.step(action.flatten())\n if is_gymnasium_env:\n next_obs = self.eval_env.get_true_observation(next_obs)\n episode_reward += reward\n episode_length += 1\n\n obs = next_obs\n\n if terminal: # Episode finishes\n if self.binary_ret:\n episode_reward = 1 if episode_reward >= 1 else 0\n eval_ep_info_buffer.append(\n {\"episode_reward\": episode_reward, \"episode_length\": episode_length}\n )\n num_episodes +=1\n episode_reward, episode_length = 0, 0\n if is_gymnasium_env:\n obs, _ = self.eval_env.reset()\n obs = self.eval_env.get_true_observation(obs)\n else:\n obs = self.eval_env.reset()\n \n return {\n \"eval/episode_reward\": [ep_info[\"episode_reward\"] for ep_info in eval_ep_info_buffer],\n \"eval/episode_length\": [ep_info[\"episode_length\"] for ep_info in eval_ep_info_buffer]\n }" }, { "identifier": "COMBOPolicy", "path": "offlinerlkit/policy/model_based/combo.py", "snippet": "class COMBOPolicy(CQLPolicy):\n \"\"\"\n Conservative Offline Model-Based Policy Optimization <Ref: https://arxiv.org/abs/2102.08363>\n \"\"\"\n\n def __init__(\n self,\n dynamics: BaseDynamics,\n actor: nn.Module,\n critic1: nn.Module,\n critic2: nn.Module,\n actor_optim: torch.optim.Optimizer,\n critic1_optim: torch.optim.Optimizer,\n critic2_optim: torch.optim.Optimizer,\n action_space: gym.spaces.Space,\n tau: float = 0.005,\n gamma: float = 0.99,\n alpha: Union[float, Tuple[float, torch.Tensor, torch.optim.Optimizer]] = 0.2,\n cql_weight: float = 1.0,\n temperature: float = 1.0,\n max_q_backup: bool = False,\n deterministic_backup: bool = True,\n with_lagrange: bool = True,\n lagrange_threshold: float = 10.0,\n cql_alpha_lr: float = 1e-4,\n num_repeart_actions:int = 10,\n uniform_rollout: bool = False,\n rho_s: str = \"mix\"\n ) -> None:\n super().__init__(\n actor,\n critic1,\n critic2,\n actor_optim,\n critic1_optim,\n critic2_optim,\n action_space,\n tau=tau,\n gamma=gamma,\n alpha=alpha,\n cql_weight=cql_weight,\n temperature=temperature,\n max_q_backup=max_q_backup,\n deterministic_backup=deterministic_backup,\n with_lagrange=with_lagrange,\n lagrange_threshold=lagrange_threshold,\n cql_alpha_lr=cql_alpha_lr,\n num_repeart_actions=num_repeart_actions\n )\n\n self.dynamics = dynamics\n self._uniform_rollout = uniform_rollout\n self._rho_s = rho_s\n\n def rollout(\n self,\n init_obss: np.ndarray,\n rollout_length: int\n ) -> Tuple[Dict[str, np.ndarray], Dict]:\n\n num_transitions = 0\n rewards_arr = np.array([])\n rollout_transitions = defaultdict(list)\n\n # rollout\n observations = init_obss\n for _ in range(rollout_length):\n if self._uniform_rollout:\n actions = np.random.uniform(\n self.action_space.low[0],\n self.action_space.high[0],\n size=(len(observations), self.action_space.shape[0])\n )\n else:\n actions = self.select_action(observations)\n next_observations, rewards, terminals, info = self.dynamics.step(observations, actions)\n rollout_transitions[\"obss\"].append(observations)\n rollout_transitions[\"next_obss\"].append(next_observations)\n rollout_transitions[\"actions\"].append(actions)\n rollout_transitions[\"rewards\"].append(rewards)\n rollout_transitions[\"terminals\"].append(terminals)\n\n num_transitions += len(observations)\n rewards_arr = np.append(rewards_arr, rewards.flatten())\n\n nonterm_mask = (~terminals).flatten()\n if nonterm_mask.sum() == 0:\n break\n\n observations = next_observations[nonterm_mask]\n \n for k, v in rollout_transitions.items():\n rollout_transitions[k] = np.concatenate(v, axis=0)\n\n return rollout_transitions, \\\n {\"num_transitions\": num_transitions, \"reward_mean\": rewards_arr.mean()}\n \n def learn(self, batch: Dict) -> Dict[str, float]:\n real_batch, fake_batch = batch[\"real\"], batch[\"fake\"]\n # Mix data from real (offline) and fake (rollout)\n mix_batch = {k: torch.cat([real_batch[k], fake_batch[k]], 0) for k in real_batch.keys()}\n\n obss, actions, next_obss, rewards, terminals = mix_batch[\"observations\"], mix_batch[\"actions\"], \\\n mix_batch[\"next_observations\"], mix_batch[\"rewards\"], mix_batch[\"terminals\"]\n batch_size = obss.shape[0]\n \n # update actor\n a, log_probs = self.actforward(obss)\n q1a, q2a = self.critic1(obss, a), self.critic2(obss, a)\n actor_loss = (self._alpha * log_probs - torch.min(q1a, q2a)).mean()\n self.actor_optim.zero_grad()\n actor_loss.backward()\n self.actor_optim.step()\n\n if self._is_auto_alpha:\n log_probs = log_probs.detach() + self._target_entropy\n alpha_loss = -(self._log_alpha * log_probs).mean()\n self.alpha_optim.zero_grad()\n alpha_loss.backward()\n self.alpha_optim.step()\n self._alpha = self._log_alpha.detach().exp()\n \n # compute td error\n if self._max_q_backup:\n with torch.no_grad():\n tmp_next_obss = next_obss.unsqueeze(1) \\\n .repeat(1, self._num_repeat_actions, 1) \\\n .view(batch_size * self._num_repeat_actions, next_obss.shape[-1])\n tmp_next_actions, _ = self.actforward(tmp_next_obss)\n tmp_next_q1 = self.critic1_old(tmp_next_obss, tmp_next_actions) \\\n .view(batch_size, self._num_repeat_actions, 1) \\\n .max(1)[0].view(-1, 1)\n tmp_next_q2 = self.critic2_old(tmp_next_obss, tmp_next_actions) \\\n .view(batch_size, self._num_repeat_actions, 1) \\\n .max(1)[0].view(-1, 1)\n next_q = torch.min(tmp_next_q1, tmp_next_q2)\n else:\n with torch.no_grad():\n next_actions, next_log_probs = self.actforward(next_obss)\n next_q = torch.min(\n self.critic1_old(next_obss, next_actions),\n self.critic2_old(next_obss, next_actions)\n )\n if not self._deterministic_backup:\n next_q -= self._alpha * next_log_probs\n\n target_q = rewards + self._gamma * (1 - terminals) * next_q\n q1, q2 = self.critic1(obss, actions), self.critic2(obss, actions)\n critic1_loss = ((q1 - target_q).pow(2)).mean()\n critic2_loss = ((q2 - target_q).pow(2)).mean()\n\n # compute conservative loss\n if self._rho_s == \"model\":\n obss, actions, next_obss = fake_batch[\"observations\"], \\\n fake_batch[\"actions\"], fake_batch[\"next_observations\"]\n \n batch_size = len(obss)\n random_actions = torch.FloatTensor(\n batch_size * self._num_repeat_actions, actions.shape[-1]\n ).uniform_(self.action_space.low[0], self.action_space.high[0]).to(self.actor.device)\n # tmp_obss & tmp_next_obss: (batch_size * num_repeat, obs_dim)\n tmp_obss = obss.unsqueeze(1) \\\n .repeat(1, self._num_repeat_actions, 1) \\\n .view(batch_size * self._num_repeat_actions, obss.shape[-1])\n tmp_next_obss = next_obss.unsqueeze(1) \\\n .repeat(1, self._num_repeat_actions, 1) \\\n .view(batch_size * self._num_repeat_actions, obss.shape[-1])\n \n obs_pi_value1, obs_pi_value2 = self.calc_pi_values(tmp_obss, tmp_obss)\n next_obs_pi_value1, next_obs_pi_value2 = self.calc_pi_values(tmp_next_obss, tmp_obss)\n random_value1, random_value2 = self.calc_random_values(tmp_obss, random_actions)\n\n for value in [\n obs_pi_value1, obs_pi_value2, next_obs_pi_value1, next_obs_pi_value2,\n random_value1, random_value2\n ]:\n value.reshape(batch_size, self._num_repeat_actions, 1)\n \n # cat_q shape: (batch_size, 3 * num_repeat, 1)\n cat_q1 = torch.cat([obs_pi_value1, next_obs_pi_value1, random_value1], 1)\n cat_q2 = torch.cat([obs_pi_value2, next_obs_pi_value2, random_value2], 1)\n # Samples from the original dataset\n real_obss, real_actions = real_batch['observations'], real_batch['actions']\n q1, q2 = self.critic1(real_obss, real_actions), self.critic2(real_obss, real_actions)\n\n conservative_loss1 = \\\n torch.logsumexp(cat_q1 / self._temperature, dim=1).mean() * self._cql_weight * self._temperature - \\\n q1.mean() * self._cql_weight\n conservative_loss2 = \\\n torch.logsumexp(cat_q2 / self._temperature, dim=1).mean() * self._cql_weight * self._temperature - \\\n q2.mean() * self._cql_weight\n \n if self._with_lagrange:\n cql_alpha = torch.clamp(self.cql_log_alpha.exp(), 0.0, 1e6)\n conservative_loss1 = cql_alpha * (conservative_loss1 - self._lagrange_threshold)\n conservative_loss2 = cql_alpha * (conservative_loss2 - self._lagrange_threshold)\n\n self.cql_alpha_optim.zero_grad()\n cql_alpha_loss = -(conservative_loss1 + conservative_loss2) * 0.5\n cql_alpha_loss.backward(retain_graph=True)\n self.cql_alpha_optim.step()\n \n critic1_loss = critic1_loss + conservative_loss1\n critic2_loss = critic2_loss + conservative_loss2\n\n # update critic\n self.critic1_optim.zero_grad()\n critic1_loss.backward(retain_graph=True)\n self.critic1_optim.step()\n\n self.critic2_optim.zero_grad()\n critic2_loss.backward()\n self.critic2_optim.step()\n\n self._sync_weight()\n\n result = {\n \"loss/actor\": actor_loss.item(),\n \"loss/critic1\": critic1_loss.item(),\n \"loss/critic2\": critic2_loss.item()\n }\n\n if self._is_auto_alpha:\n result[\"loss/alpha\"] = alpha_loss.item()\n result[\"alpha\"] = self._alpha.item()\n if self._with_lagrange:\n result[\"loss/cql_alpha\"] = cql_alpha_loss.item()\n result[\"cql_alpha\"] = cql_alpha.item()\n \n return result" }, { "identifier": "none_or_str", "path": "offlinerlkit/utils/none_or_str.py", "snippet": "def none_or_str(value):\n if value == 'None':\n return None\n return value" }, { "identifier": "create_env_dataset", "path": "envs/pointmaze/create_maze_dataset.py", "snippet": "def create_env_dataset(args):\n '''\n Create env and dataset (if not created)\n '''\n maze_config = json.load(open(args.maze_config_file, 'r'))\n maze = maze_config[\"maze\"]\n map = maze['map'] \n\n start = maze['start']\n goal = maze['goal']\n\n sample_args = maze_config[\"sample_args\"]\n\n print(f\"Create point maze\")\n point_maze = PointMaze(data_path = os.path.join(args.data_dir, args.data_file), \n horizon = args.horizon,\n maze_map = map,\n start = np.array(start),\n goal = np.array(goal),\n sample_args = sample_args,\n debug=False,\n render=False) \n env = point_maze.env_cls()\n trajs = point_maze.dataset[0]\n return env, trajs" }, { "identifier": "get_pointmaze_dataset", "path": "envs/pointmaze/utils/trajectory.py", "snippet": "def get_pointmaze_dataset(\n trajs: List,\n sample_ratio: float = 1.) -> Tuple[Dict, np.ndarray, float]:\n '''\n Return:\n dataset: Dict. key 'rtgs' is set to zero, it will not be used in training\n init_obss\n max offline return\n '''\n num_trajs = int(len(trajs) * sample_ratio)\n idxs = np.random.choice(len(trajs), size=(num_trajs), replace = False)\n valid_trajs = [trajs[i] for i in list(idxs)]\n\n obss = [traj.observations[0:-1] for traj in valid_trajs]\n next_obss = [traj.observations[1:] for traj in valid_trajs]\n acts = [traj.actions[0:-1] for traj in valid_trajs]\n rs = [traj.rewards[0:-1] for traj in valid_trajs]\n init_obss = [traj.observations[0:1] for traj in valid_trajs] # initial observations\n\n obss = np.concatenate(obss, axis=0)\n next_obss = np.concatenate(next_obss, axis=0)\n acts = np.concatenate(acts, axis=0)\n rs = np.concatenate(rs, axis=0)\n terminals = np.array([False]).repeat(obss.shape[0])\n weights = np.ones_like(rs).astype(np.float32)\n init_obss = np.concatenate(init_obss, axis=0)\n\n rets = [sum(traj.rewards) for traj in valid_trajs]\n rtgs = np.zeros_like(rs) \n\n dataset = {\n \"observations\": obss,\n \"next_observations\": next_obss,\n \"actions\": acts,\n \"rewards\": rs,\n \"rtgs\": rtgs,\n \"terminals\": terminals,\n \"weights\": weights}\n\n return dataset, init_obss, max(rets)" }, { "identifier": "PointMazeObsWrapper", "path": "envs/pointmaze/utils/maze_utils.py", "snippet": "class PointMazeObsWrapper(Wrapper):\n def __init__(self, env):\n super().__init__(env)\n self.observation_space = env.observation_space['observation']\n\n def observation(self, obs: Dict[str, np.ndarray]) -> np.ndarray:\n return obs['observation']\n \n def step(self, action):\n '''\n use truncated signal as terminal\n '''\n next_obs, reward, _, truncated, info = self.env.step(action)\n next_obs = self.observation(next_obs)\n return next_obs, reward, truncated, info\n\n def reset(self, seed=None):\n obs, _ = self.env.reset(seed=seed)\n return self.observation(obs)" } ]
import argparse import random import datetime import numpy as np import torch from offlinerlkit.nets import MLP from offlinerlkit.modules import ActorProb, Critic, TanhDiagGaussian, EnsembleDynamicsModel from offlinerlkit.dynamics import EnsembleDynamics from offlinerlkit.utils.scaler import StandardScaler from offlinerlkit.utils.termination_fns import termination_fn_default from offlinerlkit.buffer import ReplayBuffer from offlinerlkit.utils.logger import Logger, make_log_dirs from offlinerlkit.policy_trainer import MBPolicyTrainer from offlinerlkit.policy import COMBOPolicy from offlinerlkit.utils.none_or_str import none_or_str from envs.pointmaze.create_maze_dataset import create_env_dataset from envs.pointmaze.utils.trajectory import get_pointmaze_dataset from envs.pointmaze.utils.maze_utils import PointMazeObsWrapper
14,991
env.reset(seed=args.seed) # create policy model actor_backbone = MLP(input_dim=np.prod(args.obs_shape), hidden_dims=args.hidden_dims) critic1_backbone = MLP(input_dim=np.prod(args.obs_shape) + args.action_dim, hidden_dims=args.hidden_dims) critic2_backbone = MLP(input_dim=np.prod(args.obs_shape) + args.action_dim, hidden_dims=args.hidden_dims) dist = TanhDiagGaussian( latent_dim=getattr(actor_backbone, "output_dim"), output_dim=args.action_dim, unbounded=True, conditioned_sigma=True ) actor = ActorProb(actor_backbone, dist, args.device) critic1 = Critic(critic1_backbone, args.device) critic2 = Critic(critic2_backbone, args.device) actor_optim = torch.optim.Adam(actor.parameters(), lr=args.actor_lr) critic1_optim = torch.optim.Adam(critic1.parameters(), lr=args.critic_lr) critic2_optim = torch.optim.Adam(critic2.parameters(), lr=args.critic_lr) lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(actor_optim, args.epoch) if args.auto_alpha: target_entropy = args.target_entropy if args.target_entropy \ else -np.prod(env.action_space.shape) args.target_entropy = target_entropy log_alpha = torch.zeros(1, requires_grad=True, device=args.device) alpha_optim = torch.optim.Adam([log_alpha], lr=args.alpha_lr) alpha = (target_entropy, log_alpha, alpha_optim) else: alpha = args.alpha # create dynamics load_dynamics_model = True if args.load_dynamics_path else False dynamics_model = EnsembleDynamicsModel( obs_dim=np.prod(args.obs_shape), action_dim=args.action_dim, hidden_dims=args.dynamics_hidden_dims, num_ensemble=args.n_ensemble, num_elites=args.n_elites, weight_decays=args.dynamics_weight_decay, device=args.device ) dynamics_optim = torch.optim.Adam( dynamics_model.parameters(), lr=args.dynamics_lr ) scaler = StandardScaler() termination_fn = termination_fn_default dynamics = EnsembleDynamics( dynamics_model, dynamics_optim, scaler, termination_fn ) if args.load_dynamics_path: print(f"Load dynamics from {args.load_dynamics_path}") dynamics.load(args.load_dynamics_path) # create policy policy = COMBOPolicy( dynamics, actor, critic1, critic2, actor_optim, critic1_optim, critic2_optim, action_space=env.action_space, tau=args.tau, gamma=args.gamma, alpha=alpha, cql_weight=args.cql_weight, temperature=args.temperature, max_q_backup=args.max_q_backup, deterministic_backup=args.deterministic_backup, with_lagrange=args.with_lagrange, lagrange_threshold=args.lagrange_threshold, cql_alpha_lr=args.cql_alpha_lr, num_repeart_actions=args.num_repeat_actions, uniform_rollout=args.uniform_rollout, rho_s=args.rho_s ) # create buffer real_buffer = ReplayBuffer( buffer_size=len(dataset["observations"]), obs_shape=args.obs_shape, obs_dtype=np.float32, action_dim=args.action_dim, action_dtype=np.float32, device=args.device ) real_buffer.load_dataset(dataset) fake_buffer = ReplayBuffer( buffer_size=args.rollout_batch_size*args.rollout_length*args.model_retain_epochs, obs_shape=args.obs_shape, obs_dtype=np.float32, action_dim=args.action_dim, action_dtype=np.float32, device=args.device ) # log timestamp = datetime.datetime.now().strftime("%y-%m%d-%H%M%S") exp_name = f"timestamp_{timestamp}&{args.seed}" log_dirs = make_log_dirs(args.task, args.algo_name, exp_name, vars(args)) # key: output file name, value: output handler type output_config = { "consoleout_backup": "stdout", "policy_training_progress": "csv", "dynamics_training_progress": "csv", "tb": "tensorboard" } logger = Logger(log_dirs, output_config) logger.log_hyperparameters(vars(args)) # create policy trainer
def get_args(): parser = argparse.ArgumentParser() parser.add_argument("--algo_name", type=str, default="combo") parser.add_argument("--task", type=str, default="pointmaze") # Self-constructed environment parser.add_argument("--last_eval", action="store_true") # env config (general) parser.add_argument('--data_dir', type=str, required=True) parser.add_argument('--horizon', type=int, default=200, help="max path length for pickplace") # env config (pointmaze) parser.add_argument('--maze_config_file', type=str, default='envs/pointmaze/config/maze_default.json') parser.add_argument('--data_file', type=str, default='pointmaze.dat') parser.add_argument("--seed", type=int, default=0) parser.add_argument("--actor-lr", type=float, default=1e-4) parser.add_argument("--critic-lr", type=float, default=3e-4) parser.add_argument("--hidden-dims", type=int, nargs='*', default=[256, 256, 256]) parser.add_argument("--gamma", type=float, default=0.99) parser.add_argument("--tau", type=float, default=0.005) parser.add_argument("--alpha", type=float, default=0.2) parser.add_argument("--auto-alpha", default=True) parser.add_argument("--target-entropy", type=int, default=None) parser.add_argument("--alpha-lr", type=float, default=1e-4) parser.add_argument("--cql-weight", type=float, default=1.0) parser.add_argument("--temperature", type=float, default=1.0) parser.add_argument("--max-q-backup", type=bool, default=False) parser.add_argument("--deterministic-backup", type=bool, default=True) parser.add_argument("--with-lagrange", type=bool, default=False) parser.add_argument("--lagrange-threshold", type=float, default=10.0) parser.add_argument("--cql-alpha-lr", type=float, default=3e-4) parser.add_argument("--num-repeat-actions", type=int, default=10) parser.add_argument("--uniform-rollout", type=bool, default=False) parser.add_argument("--rho-s", type=str, default="mix", choices=["model", "mix"]) parser.add_argument("--dynamics-lr", type=float, default=1e-3) parser.add_argument("--dynamics-hidden-dims", type=int, nargs='*', default=[200, 200, 200, 200]) parser.add_argument("--dynamics-weight-decay", type=float, nargs='*', default=[2.5e-5, 5e-5, 7.5e-5, 7.5e-5, 1e-4]) parser.add_argument("--n-ensemble", type=int, default=7) parser.add_argument("--n-elites", type=int, default=5) parser.add_argument("--rollout-freq", type=int, default=1000) parser.add_argument("--rollout-batch-size", type=int, default=50000) parser.add_argument("--rollout-length", type=int, default=5) parser.add_argument("--model-retain-epochs", type=int, default=5) parser.add_argument("--real-ratio", type=float, default=0.5) parser.add_argument("--load-dynamics-path", type=none_or_str, default=None) parser.add_argument("--epoch", type=int, default=100) parser.add_argument("--step-per-epoch", type=int, default=1000) parser.add_argument("--eval_episodes", type=int, default=10) parser.add_argument("--batch-size", type=int, default=256) parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu") return parser.parse_args() def train(args=get_args()): # seed random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) torch.backends.cudnn.deterministic = True # create env and dataset if args.task == 'pointmaze': env, trajs = create_env_dataset(args) env = PointMazeObsWrapper(env) obs_space = env.observation_space args.obs_shape = obs_space.shape args.obs_dim = np.prod(args.obs_shape) args.action_shape = env.action_space.shape args.action_dim = np.prod(args.action_shape) dataset, _, _ = get_pointmaze_dataset(trajs) else: raise NotImplementedError env.reset(seed=args.seed) # create policy model actor_backbone = MLP(input_dim=np.prod(args.obs_shape), hidden_dims=args.hidden_dims) critic1_backbone = MLP(input_dim=np.prod(args.obs_shape) + args.action_dim, hidden_dims=args.hidden_dims) critic2_backbone = MLP(input_dim=np.prod(args.obs_shape) + args.action_dim, hidden_dims=args.hidden_dims) dist = TanhDiagGaussian( latent_dim=getattr(actor_backbone, "output_dim"), output_dim=args.action_dim, unbounded=True, conditioned_sigma=True ) actor = ActorProb(actor_backbone, dist, args.device) critic1 = Critic(critic1_backbone, args.device) critic2 = Critic(critic2_backbone, args.device) actor_optim = torch.optim.Adam(actor.parameters(), lr=args.actor_lr) critic1_optim = torch.optim.Adam(critic1.parameters(), lr=args.critic_lr) critic2_optim = torch.optim.Adam(critic2.parameters(), lr=args.critic_lr) lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(actor_optim, args.epoch) if args.auto_alpha: target_entropy = args.target_entropy if args.target_entropy \ else -np.prod(env.action_space.shape) args.target_entropy = target_entropy log_alpha = torch.zeros(1, requires_grad=True, device=args.device) alpha_optim = torch.optim.Adam([log_alpha], lr=args.alpha_lr) alpha = (target_entropy, log_alpha, alpha_optim) else: alpha = args.alpha # create dynamics load_dynamics_model = True if args.load_dynamics_path else False dynamics_model = EnsembleDynamicsModel( obs_dim=np.prod(args.obs_shape), action_dim=args.action_dim, hidden_dims=args.dynamics_hidden_dims, num_ensemble=args.n_ensemble, num_elites=args.n_elites, weight_decays=args.dynamics_weight_decay, device=args.device ) dynamics_optim = torch.optim.Adam( dynamics_model.parameters(), lr=args.dynamics_lr ) scaler = StandardScaler() termination_fn = termination_fn_default dynamics = EnsembleDynamics( dynamics_model, dynamics_optim, scaler, termination_fn ) if args.load_dynamics_path: print(f"Load dynamics from {args.load_dynamics_path}") dynamics.load(args.load_dynamics_path) # create policy policy = COMBOPolicy( dynamics, actor, critic1, critic2, actor_optim, critic1_optim, critic2_optim, action_space=env.action_space, tau=args.tau, gamma=args.gamma, alpha=alpha, cql_weight=args.cql_weight, temperature=args.temperature, max_q_backup=args.max_q_backup, deterministic_backup=args.deterministic_backup, with_lagrange=args.with_lagrange, lagrange_threshold=args.lagrange_threshold, cql_alpha_lr=args.cql_alpha_lr, num_repeart_actions=args.num_repeat_actions, uniform_rollout=args.uniform_rollout, rho_s=args.rho_s ) # create buffer real_buffer = ReplayBuffer( buffer_size=len(dataset["observations"]), obs_shape=args.obs_shape, obs_dtype=np.float32, action_dim=args.action_dim, action_dtype=np.float32, device=args.device ) real_buffer.load_dataset(dataset) fake_buffer = ReplayBuffer( buffer_size=args.rollout_batch_size*args.rollout_length*args.model_retain_epochs, obs_shape=args.obs_shape, obs_dtype=np.float32, action_dim=args.action_dim, action_dtype=np.float32, device=args.device ) # log timestamp = datetime.datetime.now().strftime("%y-%m%d-%H%M%S") exp_name = f"timestamp_{timestamp}&{args.seed}" log_dirs = make_log_dirs(args.task, args.algo_name, exp_name, vars(args)) # key: output file name, value: output handler type output_config = { "consoleout_backup": "stdout", "policy_training_progress": "csv", "dynamics_training_progress": "csv", "tb": "tensorboard" } logger = Logger(log_dirs, output_config) logger.log_hyperparameters(vars(args)) # create policy trainer
policy_trainer = MBPolicyTrainer(
11
2023-10-11 08:36:06+00:00
24k
lmb-freiburg/ldce
scripts/ldce.py
[ { "identifier": "disabled_train", "path": "sampling_helpers.py", "snippet": "def disabled_train(self, mode=True):\n \"\"\"Overwrite model.train with this function to make sure train/eval mode\n does not change anymore.\"\"\"\n return self" }, { "identifier": "get_model", "path": "sampling_helpers.py", "snippet": "def get_model(cfg_path=\"configs/latent-diffusion/cin256-v2.yaml\", ckpt_path=\"models/ldm/cin256-v2/model.ckpt\"):\n config = OmegaConf.load(cfg_path)\n model = load_model_from_config(config, ckpt_path)\n return model" }, { "identifier": "_unmap_img", "path": "sampling_helpers.py", "snippet": "def _unmap_img(x, from_image_net_dist=False):\n \"\"\"\n from 0 to 1 to -1 to 1\n \"\"\"\n\n return 2. * x - 1" }, { "identifier": "generate_samples", "path": "sampling_helpers.py", "snippet": "def generate_samples(\n model, \n sampler, \n target_y, \n ddim_steps, \n scale, \n init_image=None, \n t_enc=None,\n init_latent=None, \n ccdddim=False, \n ddim_eta=0., \n latent_t_0=True, \n prompts: list = None,\n seed: int = 0\n):\n torch.cuda.empty_cache()\n \n all_samples = []\n all_probs = []\n all_videos = []\n all_masks = []\n all_cgs = []\n\n with torch.no_grad():\n with model.ema_scope():\n tic = time.time()\n print(f\"rendering target classes '{target_y}' in {len(sampler.ddim_timesteps)} or {ddim_steps} steps and using s={scale:.2f}.\")\n batch_size = target_y.shape[0]\n if \"class_label\" == model.cond_stage_key: # class-conditional\n uc = model.get_learned_conditioning({model.cond_stage_key: torch.tensor(batch_size * [1000]).to(model.device)})\n c = model.get_learned_conditioning({model.cond_stage_key: target_y.to(model.device)})\n elif \"txt\" == model.cond_stage_key: # text-conditional\n uc = model.get_learned_conditioning(batch_size * [\"\"])\n if prompts is None:\n raise ValueError(\"Prompts are not defined!\")\n c = model.get_learned_conditioning(prompts)\n else:\n raise NotImplementedError\n \n if init_latent is not None:\n if seed!=-1:\n noises_per_batch = []\n for b in range(batch_size):\n torch.manual_seed(seed)\n np.random.seed(seed)\n random.seed(seed)\n torch.cuda.manual_seed_all(seed)\n noises_per_batch.append(torch.randn_like(init_latent[b]))\n noise = torch.stack(noises_per_batch, dim=0)\n else:\n noise = None\n z_enc = sampler.stochastic_encode(init_latent, torch.tensor([t_enc] * (batch_size)).to(\n init_latent.device), noise=noise) if not latent_t_0 else init_latent\n\n if seed!=-1:\n torch.manual_seed(seed)\n np.random.seed(seed)\n random.seed(seed)\n torch.cuda.manual_seed_all(seed)\n\n # decode it\n if ccdddim:\n out = sampler.decode(\n z_enc, \n c, \n t_enc, \n unconditional_guidance_scale=scale,\n unconditional_conditioning=uc, \n y=target_y.to(model.device), \n latent_t_0=latent_t_0,\n )\n samples = out[\"x_dec\"]\n prob = out[\"prob\"]\n vid = out[\"video\"]\n mask = out[\"mask\"]\n cg = out[\"concensus_regions\"]\n\n else:\n samples = sampler.decode(z_enc, c, t_enc, unconditional_guidance_scale=scale,\n unconditional_conditioning=uc)\n\n x_samples = model.decode_first_stage(samples)\n x_samples_ddim = torch.clamp((x_samples + 1.0) / 2.0, min=0.0, max=1.0)\n cat_samples = x_samples_ddim #torch.cat([init_image[:1], x_samples_ddim], dim=0)\n else:\n\n samples_ddim, _ = sampler.sample(S=ddim_steps,\n conditioning=c,\n batch_size=batch_size,\n shape=[3, 64, 64],\n verbose=False,\n unconditional_guidance_scale=scale,\n unconditional_conditioning=uc,\n eta=ddim_eta)\n\n x_samples_ddim = model.decode_first_stage(samples_ddim)\n x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0,\n min=0.0, max=1.0)\n cat_samples = x_samples_ddim\n\n all_samples.append(cat_samples)\n all_probs.append(prob) if ccdddim and prob is not None else None\n all_videos.append(vid) if ccdddim and vid is not None else None\n all_masks.append(mask) if ccdddim and mask is not None else None\n all_cgs.append(cg) if ccdddim and cg is not None else None\n tac = time.time()\n\n out = {}\n out[\"samples\"] = all_samples\n out[\"probs\"] = all_probs if len(all_probs) > 0 else None\n out[\"videos\"] = all_videos if len(all_videos) > 0 else None\n out[\"masks\"] = all_masks if len(all_masks) > 0 else None\n out[\"cgs\"] = all_cgs if len(all_cgs) > 0 else None\n \n return out" }, { "identifier": "load_model_hf", "path": "sampling_helpers.py", "snippet": "def load_model_hf(repo_id, filename, dir, ckpt_config_filename, device='cpu'):\n cache_config_file = hf_hub_download(repo_id=repo_id, filename=ckpt_config_filename)\n\n args = SLConfig.fromfile(cache_config_file)\n args.device = device\n model = build_model(args)\n\n cache_file = hf_hub_download(repo_id=repo_id, filename=filename, cache_dir=dir)\n checkpoint = torch.load(cache_file, map_location='cpu')\n log = model.load_state_dict(clean_state_dict(checkpoint['model']), strict=False)\n print(\"Model loaded from {} \\n => {}\".format(cache_file, log))\n _ = model.eval()\n return model.to(device)" }, { "identifier": "CCMDDIMSampler", "path": "ldm/models/diffusion/cc_ddim.py", "snippet": "class CCMDDIMSampler(object):\n def __init__(self, model, classifier, model_type=\"latent\", schedule=\"linear\", guidance=\"free\", lp_custom=False,\n deg_cone_projection=10., denoise_dist_input=True, classifier_lambda=1, dist_lambda=0.15,\n enforce_same_norms=True, seg_model=None, detect_model=None, masked_guidance=False,\n backprop_diffusion=True, log_backprop_gradients: bool = False, mask_alpha = 5., cone_projection_type= 'default', self_recurrence=0, classifier_wrapper: bool = True, record_intermediate_results:bool=False, verbose:bool=True,**kwargs):\n\n super().__init__()\n self.model_type = model_type\n self.lp_custom = lp_custom\n self.images = []\n self.probs = []\n self.classifier_lambda = classifier_lambda\n self.model = model\n self.ddpm_num_timesteps = model.num_timesteps\n self.schedule = schedule\n self.classifier = classifier\n self.guidance = guidance\n self.backprop_diffusion = backprop_diffusion\n self.log_backprop_gradients = log_backprop_gradients\n # self.projected_counterfactuals = projected_counterfactuals\n self.deg_cone_projection = deg_cone_projection\n self.cone_projection_type = cone_projection_type\n self.denoise_dist_input = denoise_dist_input\n self.dist_lambda = dist_lambda\n self.enforce_same_norms = enforce_same_norms\n self.seg_model = seg_model\n self.masked_guidance = masked_guidance\n self.mask_alpha = mask_alpha\n self.self_recurrence = self_recurrence\n self.classifier_wrapper = classifier_wrapper\n self.record_intermediate_results = record_intermediate_results\n self.verbose = verbose\n\n self.init_images = None\n self.init_labels = None \n self.mask = None\n self.concensus_regions = []\n \n self.detect_model = detect_model\n self.classification_criterion = torch.nn.CrossEntropyLoss()\n self.binary_classification_criterion = torch.nn.BCEWithLogitsLoss()\n \n self.dino_pipeline = False\n if isinstance(self.lp_custom, str) and \"dino_\" in self.lp_custom:\n self.distance_criterion = DinoLoss(dino=torch.hub.load('facebookresearch/dino:main', 'dino_vitb16').eval(), loss_identifier=self.lp_custom.split(\"_\")[-1])\n self.dino_init_features = None\n self.dino_pipeline = True\n elif isinstance(self.lp_custom, int):\n if self.lp_custom == 1:\n self.distance_criterion = torch.nn.L1Loss(reduction='sum')\n elif self.lp_custom == 2:\n self.distance_criterion = torch.nn.MSELoss(reduction='sum')\n else:\n raise NotImplementedError\n else:\n raise NotImplementedError\n\n def get_classifier_dist(self, x, t=None):\n \"\"\"\n Create a distribution over the classifier output space\n Args:\n x: input image for which to create the distribution over the classifier output space range [-1, 1]\n\n Returns:\n dist: torch distribution over the classifier output space\n\n \"\"\"\n x = tf.center_crop(x, 224)\n x = normalize(_map_img(x))\n logit = self.classifier(x) # (TODO) add option for t here\n dist = torchd.independent.Independent(OneHotDist(logit, validate_args = False), 0) # 0 here is the batch dimension, so event_shape is (num_classes, )\n return dist\n\n def get_classifier_logits(self, x, t=None):\n \"\"\"\n Returns classifier logits\n Args:\n x: input image for which to create the prediction\n\n Returns:\n logits: logits of output layer of target model\n\n \"\"\"\n x = _map_img(x)\n if not self.classifier_wrapper: # only works for ImageNet!\n x = tf.center_crop(x, 224)\n x = normalize(x)\n return self.classifier(x)\n\n def get_dino_features(self, x, device):\n x = normalize(_map_img(tf.center_crop(x, output_size=224)))\n return self.distance_criterion.dino(x.to(device))\n\n def get_mask_clip_seg(self):\n \"\"\"\n this function returns a negative mask given by a segmentation model for the region of interest\n values are higher outside the region of interest\n \"\"\"\n if self.mask is not None:\n return self.mask\n\n prompts = []\n\n for l in self.init_labels:\n prompts.append(re.sub(r'\\b(\\w)', lambda m: m.group(1).upper(), i2h[l]))\n\n with torch.no_grad():\n img_to_seg = F.interpolate(normalize(self.init_images), size=(352, 352), mode='bilinear',\n align_corners=False).to(self.init_images.device)\n preds = self.seg_model(img_to_seg, prompts)[0]\n preds = F.interpolate(preds, size=self.init_images.shape[-2:], mode='bilinear', align_corners=False)\n preds = torch.sigmoid(preds) # torch.softmax(preds.view(preds.shape[0], -1), dim=1).view(*preds.shape)\n # penalty = 1-preds\n preds = (preds - preds.min()) / (preds.max() - preds.min())\n preds = torch.sigmoid(self.mask_alpha*2*(preds-0.5))\n self.mask = preds.to(self.init_images.device)\n return self.mask\n\n def get_mask(self):\n \"\"\"\n this function returns a negative mask given by a segmentation model for the region of interest\n values are higher outside the region of interest\n \"\"\"\n\n if self.mask is not None:\n return self.mask\n\n with torch.no_grad():\n print(\"input range\", self.init_images.min(), self.init_images.max())\n image_int8 = (self.init_images[0].permute(1, 2, 0).cpu().numpy() * 255.).astype(np.uint8)\n # detected_boxes = detect(image, text_prompt=i2h[label], model=groundingdino_model, image_source=image_image)\n detected_boxes = detect(normalize(self.init_images[0]).squeeze(),\n text_prompt=i2h[self.init_labels[0]].split(',')[0],\n model=self.detect_model) # , image_source=image_int8)\n segmented_frame_masks = segment(image_int8, self.seg_model, boxes=detected_boxes)\n preds = torch.any(segmented_frame_masks, dim=0)\n preds = preds.unsqueeze(0).repeat(self.init_images.shape[0], *(1,) * len(preds.shape))\n # print(\"preds range after first seg \", preds.min(), preds.max())\n self.mask = preds.to(self.init_images.device)\n\n return self.mask\n\n def get_output(self, x, t, c, index, unconditional_conditioning, use_original_steps=True, quantize_denoised=True,\n return_decoded=False, return_pred_latent_x0=False):\n b, device = x.shape[0], x.device\n x_in = torch.cat([x] * 2)\n t_in = torch.cat([t] * 2)\n c_in = torch.cat([unconditional_conditioning, c])\n with torch.enable_grad() if self.backprop_diffusion else torch.no_grad():\n e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)\n\n if return_decoded:\n # getting the original denoised image\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index], device=device)\n # current prediction for x_0\n # get the original image with range [0, 1] if it is in latent space\n pred_latent_x0 = (x - sqrt_one_minus_at * e_t_uncond) / a_t.sqrt() # e_t - > e_t_uncond\n if quantize_denoised:\n pred_latent_x0, _, *_ = self.model.first_stage_model.quantize(pred_latent_x0)\n\n pred_x0 = self.model.differentiable_decode_first_stage(\n pred_latent_x0) # if self.model_type == \"latent\" else pred_latent_x0\n # pred_x0 = torch.clamp((pred_x0 + 1.0) / 2.0, min=0.0, max=1.0)\n \n if return_pred_latent_x0:\n return e_t_uncond, e_t, pred_x0, pred_latent_x0\n else:\n return e_t_uncond, e_t, pred_x0\n else:\n return e_t_uncond, e_t\n\n def conditional_score(self, x, t, c, index, use_original_steps, quantize_denoised, unconditional_guidance_scale=1.,\n unconditional_conditioning=None, y=None):\n \"\"\"\n\n Args:\n x: input image\n t: time step\n c: conditioning\n index: index for the schedule\n use_original_steps: whether to use the original steps\n quantize_denoised: whether to quantize the denoised image\n unconditional_guidance_scale: scale for the unconditional guidance\n unconditional_conditioning: unconditional conditioning\n y: target class\n\n\n Returns:\n e_t: score after conditioning\n\n \"\"\"\n b, *_, device = *x.shape, x.device\n x = x.detach() # .requires_grad_()\n # x.requires_grad = True\n prob_best_class = None\n mask_guidance = None\n\n ## check if gradient tracking is on for x\n if unconditional_conditioning is None or unconditional_guidance_scale == 1.:\n e_t = self.model.apply_model(x, t, c)\n return e_t\n\n # print(\"check gradient tracking onf e \", e_t.requires_grad)\n if self.guidance == \"free\":\n e_t_uncond, e_t, pred_x0 = self.get_output(x, t, c, index, unconditional_conditioning, use_original_steps,\n quantize_denoised, return_decoded=True)\n\n e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)\n\n return e_t\n\n # print(\"check gradient tracking onf e \", e_t.requires_grad)\n score_out = torch.zeros_like(x)\n\n with torch.enable_grad():\n x_noise = x.detach().requires_grad_()\n ret_vals = self.get_output(x_noise, t, c, index, unconditional_conditioning,\n use_original_steps, quantize_denoised=quantize_denoised,\n return_decoded=True, return_pred_latent_x0=self.log_backprop_gradients)\n if self.log_backprop_gradients:\n e_t_uncond, e_t, pred_x0, pred_latent_x0 = ret_vals\n else:\n e_t_uncond, e_t, pred_x0 = ret_vals\n\n with torch.no_grad():\n if isinstance(self.lp_custom, str) and \"dino_\" in self.lp_custom: # retain_graph causes cuda oom issues for dino distance regularizer...\n with torch.enable_grad():\n pred_x0_0to1 = torch.clamp(_map_img(pred_x0), min=0.0, max=1.0)\n lp_dist = self.distance_criterion(pred_x0_0to1, self.dino_init_features.to(x.device).detach())\n lp_grad = torch.autograd.grad(lp_dist.mean(), x_noise, retain_graph=False)[0]\n elif self.lp_custom:\n with torch.enable_grad():\n pred_x0_0to1 = torch.clamp(_map_img(pred_x0), min=0.0, max=1.0)\n lp_dist = self.distance_criterion(pred_x0_0to1, self.init_images.to(x.device))\n lp_grad = torch.autograd.grad(lp_dist.mean(), x_noise, retain_graph=True)[0]\n \n if self.classifier_lambda != 0:\n with torch.enable_grad():\n if isinstance(self.lp_custom, str) and \"dino_\" in self.lp_custom:\n x_noise = x.detach().requires_grad_()\n ret_vals = self.get_output(x_noise, t, c, index, unconditional_conditioning,\n use_original_steps, quantize_denoised=quantize_denoised,\n return_decoded=True, return_pred_latent_x0=self.log_backprop_gradients)\n if self.log_backprop_gradients:\n e_t_uncond, e_t, pred_x0, pred_latent_x0 = ret_vals\n else:\n e_t_uncond, e_t, pred_x0 = ret_vals\n pred_logits = self.get_classifier_logits(pred_x0)\n if len(pred_logits.shape) == 2: # multi-class\n log_probs = torch.nn.functional.log_softmax(pred_logits, dim=-1)\n log_probs = log_probs[range(log_probs.size(0)), y.view(-1)]\n prob_best_class = torch.exp(log_probs).detach()\n else: # binary\n loss = self.binary_classification_criterion(pred_logits, y)\n loss *= -1 # minimize this\n log_probs = loss\n prob_best_class = pred_logits.sigmoid().detach()\n\n if self.log_backprop_gradients: pred_latent_x0.retain_grad()\n\n if self.dino_pipeline:\n grad_classifier = torch.autograd.grad(log_probs.sum(), x_noise, retain_graph=False)[0]\n else:\n grad_classifier = torch.autograd.grad(log_probs.sum(), x_noise, retain_graph=True)[0]\n # grad_classifier = torch.autograd.grad(log_probs.sum(), x_noise, retain_graph=True)[0]\n # grad_classifier2 = torch.autograd.grad(log_probs[0].sum(), x_noise, retain_graph=False)[0]\n\n if self.log_backprop_gradients:\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n a_t_sqrt = a_t.sqrt()\n sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index], device=device)\n grad_pred_latent_x0 = pred_latent_x0.grad.data\n grad_unet_wrt_zt = (grad_classifier*a_t_sqrt/grad_pred_latent_x0 - 1)*(-1/sqrt_one_minus_at)\n\n cossim = torch.nn.CosineSimilarity()\n cossim_wpre = cossim(grad_classifier.view(2, -1), grad_pred_latent_x0.view(2, -1))\n \n print(torch.norm(grad_classifier, dim=(2,3)), torch.norm(grad_pred_latent_x0, dim=(2,3)), torch.norm(grad_unet_wrt_zt, dim=(2,3)))\n print(cossim_wpre)\n\n # assert e_t_uncond.requires_grad == True and e_t.requires_grad == True, \"e_t_uncond and e_t should require gradients\"\n\n # if self.guidance == \"projected\":\n implicit_classifier_score = (e_t - e_t_uncond) # .detach()\n # check gradient tracking on implicit_classifier_score\n assert implicit_classifier_score.requires_grad == False, \"implicit_classifier_score requires grad\"\n\n if self.lp_custom or self.classifier_lambda != 0:\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n\n if self.classifier_lambda != 0:\n classifier_score = -1 * grad_classifier * (1 - a_t).sqrt()\n assert classifier_score.requires_grad == False, \"classifier_score requires grad\"\n # project the gradient of the classifier on the implicit classifier\n\n\n projection_fn = cone_project if self.cone_projection_type == \"default\" else cone_project_chuncked\n projection_fn = cone_project_chuncked_zero if \"zero\" in self.cone_projection_type else projection_fn\n \n \n proj_out = projection_fn(implicit_classifier_score.view(x.shape[0], -1),\n classifier_score.view(x.shape[0], -1),\n self.deg_cone_projection,\n orig_shp=implicit_classifier_score.shape) \\\n if self.guidance == \"projected\" else classifier_score\n \n classifier_score = proj_out if self.cone_projection_type == \"default\" else proj_out[0].view_as(classifier_score)\n concensus_region = proj_out[1].unsqueeze(1) if self.cone_projection_type == \"binning\" else None\n #print(classifier_score.shape, concensus_region.shape)\n if self.enforce_same_norms:\n score_, norm_ = _renormalize_gradient(classifier_score,\n implicit_classifier_score) # e_t_uncond (AWAREE!!)\n classifier_score = self.classifier_lambda * score_\n\n else:\n classifier_score *= self.classifier_lambda\n\n score_out += classifier_score\n\n # distance gradients\n if self.lp_custom:\n\n lp_score = -1 * lp_grad * (1 - a_t).sqrt()\n\n if self.enforce_same_norms:\n score_, norm_ = _renormalize_gradient(lp_score,\n implicit_classifier_score)\n lp_score = self.dist_lambda * score_\n\n else:\n\n lp_score *= self.dist_lambda\n\n score_out -= lp_score\n\n e_t = e_t_uncond + unconditional_guidance_scale * score_out # (1 - a_t).sqrt() * grad_out\n\n \n if self.record_intermediate_results:\n # adding images to create a gif\n pred_x0_copy = pred_x0.clone().detach()\n img = torch.clamp(_map_img(pred_x0_copy), min=0.0, max=1.0)\n #img = torch.permute(img, (1, 2, 0, 3)).reshape((img.shape[1], img.shape[2], -1))\n\n self.images.append(img.detach().cpu())\n if self.classifier_lambda != 0 and self.cone_projection_type == \"binning\":\n self.concensus_regions.append(concensus_region.detach().cpu())\n \n if prob_best_class is not None:\n self.probs.append(prob_best_class.detach().cpu())\n\n return e_t\n\n def register_buffer(self, name, attr):\n if type(attr) == torch.Tensor:\n #pass\n # TODO: this is a hack to make it work on CPU\n if attr.device != torch.device(\"cuda\"):\n attr = attr.to(torch.device(\"cuda\"))\n setattr(self, name, attr)\n\n def make_schedule(self, ddim_num_steps, ddim_discretize=\"uniform\", ddim_eta=0., verbose=True):\n self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,\n num_ddpm_timesteps=self.ddpm_num_timesteps, verbose=verbose)\n #print(\"DDIM timesteps: \", self.ddim_timesteps, \"with length: \", len(self.ddim_timesteps))\n #print all input parameters\n #print(\"DDIM parameters: \", self.ddim_timesteps, ddim_discretize, ddim_eta)\n alphas_cumprod = self.model.alphas_cumprod\n assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'\n to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)\n\n self.register_buffer('betas', to_torch(self.model.betas))\n self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))\n self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))\n\n # calculations for diffusion q(x_t | x_{t-1}) and others\n self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))\n self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))\n self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))\n\n # ddim sampling parameters\n ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),\n ddim_timesteps=self.ddim_timesteps,\n eta=ddim_eta, verbose=verbose)\n self.register_buffer('ddim_sigmas', ddim_sigmas)\n self.register_buffer('ddim_alphas', ddim_alphas)\n self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)\n self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))\n sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(\n (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (\n 1 - self.alphas_cumprod / self.alphas_cumprod_prev))\n self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)\n\n @torch.no_grad()\n def sample(self,\n S,\n batch_size,\n shape,\n conditioning=None,\n callback=None,\n normals_sequence=None,\n img_callback=None,\n quantize_x0=False,\n eta=0.,\n mask=None,\n x0=None,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n verbose=True,\n x_T=None,\n log_every_t=100,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None,\n # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...\n **kwargs\n ):\n if conditioning is not None:\n if isinstance(conditioning, dict):\n cbs = conditioning[list(conditioning.keys())[0]].shape[0]\n if cbs != batch_size:\n print(f\"Warning: Got {cbs} conditionings but batch-size is {batch_size}\")\n else:\n if conditioning.shape[0] != batch_size:\n print(f\"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}\")\n\n self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)\n # sampling\n C, H, W = shape\n size = (batch_size, C, H, W)\n print(f'Data shape for DDIM sampling is {size}, eta {eta}')\n\n samples, intermediates = self.ddim_sampling(conditioning, size,\n callback=callback,\n img_callback=img_callback,\n quantize_denoised=quantize_x0,\n mask=mask, x0=x0,\n ddim_use_original_steps=False,\n noise_dropout=noise_dropout,\n temperature=temperature,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n x_T=x_T,\n log_every_t=log_every_t,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n )\n return samples, intermediates\n\n @torch.no_grad()\n def ddim_sampling(self, cond, shape,\n x_T=None, ddim_use_original_steps=False,\n callback=None, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, img_callback=None, log_every_t=100,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None, ):\n\n device = self.model.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n if timesteps is None:\n timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps\n elif timesteps is not None and not ddim_use_original_steps:\n subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1\n timesteps = self.ddim_timesteps[:subset_end]\n\n intermediates = {'x_inter': [img], 'pred_x0': [img]}\n time_range = reversed(range(0, timesteps)) if ddim_use_original_steps else np.flip(timesteps)\n total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]\n print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)\n\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((b,), step, device=device, dtype=torch.long)\n\n if mask is not None:\n assert x0 is not None\n img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?\n img = img_orig * mask + (1. - mask) * img\n\n outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,\n quantize_denoised=quantize_denoised, temperature=temperature,\n noise_dropout=noise_dropout, score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning)\n img, pred_x0 = outs\n if callback: callback(i)\n if img_callback: img_callback(pred_x0, i)\n\n if index % log_every_t == 0 or index == total_steps - 1:\n intermediates['x_inter'].append(img)\n intermediates['pred_x0'].append(pred_x0)\n\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None, y=None):\n b, *_, device = *x.shape, x.device\n\n e_t = self.conditional_score(x=x, c=c, t=t, index=index, use_original_steps=use_original_steps,\n quantize_denoised=quantize_denoised,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning, y=y)\n\n if score_corrector is not None:\n assert self.model.parameterization == \"eps\"\n e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)\n\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n # select parameters corresponding to the currently considered timestep\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)\n sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index], device=device)\n\n # current prediction for x_0\n pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n if quantize_denoised:\n pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n # direction pointing to x_t\n dir_xt = (1. - a_prev - sigma_t ** 2).sqrt() * e_t\n noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n return x_prev, pred_x0\n\n @torch.no_grad()\n def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):\n # fast, but does not allow for exact reconstruction\n # t serves as an index to gather the correct alphas\n if use_original_steps:\n sqrt_alphas_cumprod = self.sqrt_alphas_cumprod\n sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod\n else:\n sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas).to(x0.device)\n sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas.to(x0.device)\n\n if noise is None:\n noise = torch.randn_like(x0)\n return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +\n extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)\n\n @torch.no_grad()\n def decode(self, x_latent, cond, t_start, y=None, unconditional_guidance_scale=1.0, unconditional_conditioning=None,\n use_original_steps=False, latent_t_0=False):\n\n timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps\n timesteps = timesteps[:t_start]\n\n time_range = np.flip(timesteps)\n total_steps = timesteps.shape[0]\n print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n if self.masked_guidance:\n print(\"### Getting the mask ###\")\n mask = self.get_mask()\n mask = F.interpolate(mask.to(torch.uint8), size=x_latent.shape[-2:])\n # mask = self.get_mask()\n # mask = F.interpolate(mask, size=x_latent.shape[-2:], mode='bilinear', align_corners=True)\n # mask = (mask - mask.min()) / (mask.max() - mask.min())\n # mask[mask < 0.5] = 0.\n # mask[mask >= 0.5] = 1.\n\n if self.verbose:\n iterator = tqdm(time_range, desc='Decoding image', total=total_steps)\n else:\n iterator = range(time_range)\n\n # if latent_t_0:\n # x_orig = x_latent\n # x_dec = self.stochastic_encode(x_latent.clone(),\n # torch.tensor([t_start] * (x_latent.shape[0])).to(x_latent.device))\n # else:\n x_dec = x_latent if not latent_t_0 else self.stochastic_encode(x_latent.clone(), torch.tensor([t_start] * (x_latent.shape[0])).to(x_latent.device))\n for i, step in enumerate(iterator):\n tic = time.time()\n index = total_steps - i - 1\n ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)\n\n if self.masked_guidance and latent_t_0:\n #print(\"blending with original image\")\n img_orig = self.model.q_sample(x_latent.clone(), ts)\n x_dec = img_orig * (1. - mask) + (mask) * x_dec\n\n x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning, y=y)\n x_dec = x_dec.detach()\n for j in range(self.self_recurrence):\n print(\"self recurrence\")\n x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps, unconditional_guidance_scale = 1)\n\n #workaround for long running time\n elapsed_time = time.time() - tic\n if elapsed_time > 6:\n print(f\"Iteration time {elapsed_time} exceeded limit 6 secs, terminating program...\")\n print(\"x_dec device: \", x_dec.device)\n sys.exit(1) # Terminate the program with exit code 1 (indicating an error) \n \n out = {}\n out['x_dec'] = x_dec\n out['video'] = torch.stack(self.images, dim=1) if len(self.images) != 0 else None\n out[\"mask\"] = self.mask.to(torch.float32) if self.mask is not None else None\n # print(f\"Video shape: {out['video'].shape}\")\n #out['prob'] = self.probs[-1].item() if len(self.probs) != 0 else None\n out['prob'] = self.probs[-1].detach().cpu().numpy() if len(self.probs) != 0 else None\n out['concensus_regions'] = torch.stack(self.concensus_regions, dim=1) if len(self.concensus_regions) != 0 else None\n #print(out['concensus_regions'].shape, (out[\"concensus_regions\"]>200).to(torch.float32).mean())\n self.images = []\n self.probs = []\n \n self.concensus_regions = []\n self.mask = None\n\n return out" }, { "identifier": "name_map", "path": "data/imagenet_classnames.py", "snippet": "" }, { "identifier": "DecisionDensenetModel", "path": "utils/DecisionDensenetModel.py", "snippet": "class DecisionDensenetModel(nn.Module):\n\n def __init__(self, num_classes=40, pretrained=False, query_label=-1):\n super().__init__()\n self.feat_extract = DenseNet121(pretrained=pretrained)\n self.classifier = nn.Linear(self.feat_extract.output_size, num_classes)\n self.query_label = query_label\n\n def forward(self, x, before_sigmoid=True):\n\n x = self.feat_extract(x)\n x = self.classifier(x)\n if not before_sigmoid:\n x = torch.sigmoid(x)\n return x[:, self.query_label]" }, { "identifier": "Normalizer", "path": "utils/preprocessor.py", "snippet": "class Normalizer(torch.nn.Module):\n '''\n normalizing module. Useful for computing the gradient\n to a x image (x in [0, 1]) when using a classifier with\n different normalization inputs (i.e. f((x - mu) / sigma))\n '''\n def __init__(self, classifier,\n mu=[0.485, 0.456, 0.406],\n sigma=[0.229, 0.224, 0.225]):\n super().__init__()\n self.classifier = classifier\n self.register_buffer('mu', torch.tensor(mu).view(1, -1, 1, 1))\n self.register_buffer('sigma', torch.tensor(sigma).view(1, -1, 1, 1))\n\n def forward(self, x):\n x = (x - self.mu) / self.sigma\n return self.classifier(x)" }, { "identifier": "CropAndNormalizer", "path": "utils/preprocessor.py", "snippet": "class CropAndNormalizer(torch.nn.Module):\n def __init__(self, classifier, crop_size: int=224, mu=[0.485, 0.456, 0.406], sigma=[0.229, 0.224, 0.225]) -> None:\n super().__init__()\n self.classifier = classifier\n self.crop_size = crop_size\n self.center_crop = torchvision.transforms.CenterCrop(crop_size)\n self.register_buffer('mu', torch.tensor(mu).view(1, -1, 1, 1))\n self.register_buffer('sigma', torch.tensor(sigma).view(1, -1, 1, 1))\n\n def forward(self, x):\n # assumes x in [0, 1]!\n # x = F.center_crop(x, self.crop_size)\n x = self.center_crop(x)\n x = (x - self.mu) / self.sigma\n return self.classifier(x)" }, { "identifier": "ResizeAndNormalizer", "path": "utils/preprocessor.py", "snippet": "class ResizeAndNormalizer(torch.nn.Module):\n def __init__(self, classifier, resolution: tuple=(224, 224), mu=[0.485, 0.456, 0.406], sigma=[0.229, 0.224, 0.225]) -> None:\n super().__init__()\n self.classifier = classifier\n self.resolution = resolution\n self.resize = torchvision.transforms.Resize(resolution)\n self.register_buffer('mu', torch.tensor(mu).view(1, -1, 1, 1))\n self.register_buffer('sigma', torch.tensor(sigma).view(1, -1, 1, 1))\n\n def forward(self, x):\n # assumes x in [0, 1]!\n x = self.resize(x)\n x = (x - self.mu) / self.sigma\n return self.classifier(x)" }, { "identifier": "GenericPreprocessing", "path": "utils/preprocessor.py", "snippet": "class GenericPreprocessing(torch.nn.Module):\n def __init__(self, classifier, preprocessor) -> None:\n super().__init__()\n self.classifier = classifier\n self.preprocessor = preprocessor\n\n def forward(self, x):\n # assumes x in [0, 1]!\n x = self.preprocessor(x)\n return self.classifier(x)" }, { "identifier": "Crop", "path": "utils/preprocessor.py", "snippet": "class Crop(torch.nn.Module):\n def __init__(self, classifier, crop_size: int=224) -> None:\n super().__init__()\n self.classifier = classifier\n self.crop_size = crop_size\n self.center_crop = torchvision.transforms.CenterCrop(crop_size)\n\n def forward(self, x):\n # assumes x in [0, 1]!\n x = self.center_crop(x)\n return self.classifier(x)" }, { "identifier": "VisionLanguageWrapper", "path": "utils/vision_language_wrapper.py", "snippet": "class VisionLanguageWrapper(nn.Module):\n def __init__(self, model, tokenizer, prompts) -> None:\n super().__init__()\n self.model = model\n self.tokenizer = tokenizer\n self.prompts = prompts\n\n device = next(self.model.parameters()).device\n\n text = tokenizer(prompts)\n with torch.no_grad():\n self.text_features = model.encode_text(text.to(device))\n self.text_features = self.text_features / self.text_features.norm(dim=-1, keepdim=True)\n\n def forward(self, x):\n image_features = self.model.encode_image(x)\n image_features = image_features / image_features.norm(dim=-1, keepdim=True)\n logits = 100.0 * image_features @ self.text_features.T\n return logits" }, { "identifier": "MadryNet", "path": "utils/madry_net.py", "snippet": "def MadryNet(ckpt, device):\n norm = \"l2\"\n model = load_model(\n modelname=\"Engstrom2019Robustness\", norm=norm, device=device\n )\n state_dict = torch.load(ckpt, map_location=\"cpu\")\n model.model.load_state_dict(state_dict, strict=True)\n return model" }, { "identifier": "LinearClassifier", "path": "utils/dino_linear.py", "snippet": "class LinearClassifier(nn.Module):\n \"\"\"Linear layer to train on top of frozen features\"\"\"\n def __init__(self, dim, num_labels=1000):\n super(LinearClassifier, self).__init__()\n self.num_labels = num_labels\n self.linear = nn.Linear(dim, num_labels)\n self.linear.weight.data.normal_(mean=0.0, std=0.01)\n self.linear.bias.data.zero_()\n\n def forward(self, x):\n # flatten\n x = x.view(x.size(0), -1)\n\n # linear layer\n return self.linear(x)" }, { "identifier": "DINOLinear", "path": "utils/dino_linear.py", "snippet": "class DINOLinear(nn.Module):\n def __init__(self, dino, linear_classifier) -> None:\n super().__init__()\n self.dino = dino\n self.linear = linear_classifier\n \n def forward(self, x):\n x = self.dino(x)\n return self.linear(x)" } ]
import argparse import os import psutil import yaml import copy import random import matplotlib.pyplot as plt import numpy as np import pathlib import torch import hydra import wandb import torchvision import json import sys import regex as re import open_clip from contextlib import nullcontext from torch import autocast from omegaconf import OmegaConf, open_dict from hydra.utils import instantiate from omegaconf import DictConfig, OmegaConf from torchvision import transforms, datasets from torchvision.utils import save_image from sampling_helpers import disabled_train, get_model, _unmap_img, generate_samples from sampling_helpers import load_model_hf from ldm import * from ldm.models.diffusion.cc_ddim import CCMDDIMSampler from data.imagenet_classnames import name_map, openai_imagenet_classes from utils.DecisionDensenetModel import DecisionDensenetModel from utils.preprocessor import Normalizer, CropAndNormalizer, ResizeAndNormalizer, GenericPreprocessing, Crop from utils.vision_language_wrapper import VisionLanguageWrapper from utils.madry_net import MadryNet from utils.dino_linear import LinearClassifier, DINOLinear
14,962
elif "Flowers102" in cfg.data._target_: with open("data/flowers_idx_to_label.json", "r") as f: flowers_idx_to_classname = json.load(f) flowers_idx_to_classname = {int(k)-1: v for k, v in flowers_idx_to_classname.items()} i2h = flowers_idx_to_classname elif "OxfordIIIPets" in cfg.data._target_: with open("data/pets_idx_to_label.json", "r") as f: pets_idx_to_classname = json.load(f) i2h = {int(k): v for k, v in pets_idx_to_classname.items()} else: raise NotImplementedError if "ImageNet" in cfg.data._target_: with open('data/synset_closest_idx.yaml', 'r') as file: synset_closest_idx = yaml.safe_load(file) elif "Flowers102" in cfg.data._target_: with open("data/flowers_closest_indices.json") as file: closest_indices = json.load(file) closest_indices = {int(k):v for k,v in closest_indices.items()} elif "OxfordIIIPets" in cfg.data._target_: with open("data/pets_closest_indices.json") as file: closest_indices = json.load(file) closest_indices = {int(k):v for k,v in closest_indices.items()} if not cfg.resume: torch.save({"last_data_idx": -1}, checkpoint_path) seed = cfg.seed if "seed" in cfg else 0 set_seed(seed=seed) for i, batch in enumerate(data_loader): if "fixed_seed" in cfg: set_seed(seed=cfg.get("seed", 0)) if cfg.fixed_seed else None seed = seed if cfg.fixed_seed else -1 if "return_tgt_cls" in cfg.data and cfg.data.return_tgt_cls: image, label, tgt_classes, unique_data_idx = batch tgt_classes = tgt_classes.to(device) #squeeze() else: image, label, unique_data_idx = batch if "ImageNet" in cfg.data._target_: tgt_classes = torch.tensor([random.choice(synset_closest_idx[l.item()]) for l in label]).to(device) elif "CelebAHQDataset" in cfg.data._target_: tgt_classes = (1 - label).type(torch.float32) elif "Flowers102" in cfg.data._target_ or "OxfordIIIPets" in cfg.data._target_: tgt_classes = torch.tensor([closest_indices[unique_data_idx[l].item()*cfg.data.num_shards + cfg.data.shard][0] for l in range(label.shape[0])]).to(device) else: raise NotImplementedError image = image.to(device) #squeeze() label = label.to(device) #.item() #squeeze() #tgt_classes = torch.tensor([random.choice(synset_closest_idx[l.item()]) for l in label]).to(device) #tgt_classes = synset_closest_idx[label] #tgt_classes = torch.tensor([random.choice(synset_closest_idx[l.item()]) for l in label]).to(device) #shuffle tgt_classes #random.shuffle(tgt_classes) #get classifcation prediction with torch.inference_mode(): #with precision_scope(): if "classifier_wrapper" in cfg.classifier_model and cfg.classifier_model.classifier_wrapper: logits = classifier_model(image) else: logits = sampler.get_classifier_logits(_unmap_img(image)) #converting to -1, 1 # TODO: handle binary vs multi-class if "ImageNet" in cfg.data._target_ or "OxfordIIIPets" in cfg.data._target_ or "Flowers102" in cfg.data._target_: # multi-class in_class_pred = logits.argmax(dim=1) in_confid = logits.softmax(dim=1).max(dim=1).values in_confid_tgt = logits.softmax(dim=1)[torch.arange(batch_size), tgt_classes] else: # binary in_class_pred = (logits >= 0).type(torch.int8) in_confid = torch.where(logits >= 0, logits.sigmoid(), 1 - logits.sigmoid()) in_confid_tgt = torch.where(tgt_classes.to(device) == 0, 1 - logits.sigmoid(), logits.sigmoid()) print("in class_pred: ", in_class_pred, in_confid) for j, l in enumerate(label): print(f"converting {i} from : {i2h[l.item()]} to: {i2h[int(tgt_classes[j].item())]}") init_image = image.clone() #image.repeat(n_samples_per_class, 1, 1, 1).to(device) sampler.init_images = init_image.to(device) sampler.init_labels = label # n_samples_per_class * [label] if isinstance(cfg.sampler.lp_custom, str) and "dino_" in cfg.sampler.lp_custom: if device != next(sampler.distance_criterion.dino.parameters()).device: sampler.distance_criterion.dino = sampler.distance_criterion.dino.to(device) sampler.dino_init_features = sampler.get_dino_features(sampler.init_images, device=device).clone() #mapped_image = _unmap_img(init_image) init_latent = model.get_first_stage_encoding( model.encode_first_stage(_unmap_img(init_image))) # move to latent space if "txt" == model.cond_stage_key: # text-conditional if "ImageNet" in cfg.data._target_: prompts = [f"a photo of a {openai_imagenet_classes[idx.item()]}." for idx in tgt_classes] elif "CelebAHQDataset" in cfg.data._target_: # query label 31 (smile): label=0 <-> no smile and label=1 <-> smile # query label 39 (age): label=0 <-> old and label=1 <-> young assert cfg.data.query_label in [31, 39] prompts = [] for target in tgt_classes: if cfg.data.query_label == 31 and target == 0: attr = "non-smiling" elif cfg.data.query_label == 31 and target == 1: attr = "smiling" elif cfg.data.query_label == 39 and target == 0: attr = "old" elif cfg.data.query_label == 39 and target == 1: attr = "young" else: raise NotImplementedError prompts.append(f"a photo of a {attr} person") elif "OxfordIIIPets" in cfg.data._target_: # prompts following https://github.com/openai/CLIP/blob/main/data/prompts.md prompts = [f"a photo of a {i2h[idx.item()]}, a type of pet." for idx in tgt_classes] elif "Flowers102" in cfg.data._target_: # prompts following https://github.com/openai/CLIP/blob/main/data/prompts.md prompts = [f"a photo of a {i2h[idx.item()]}, a type of flower." for idx in tgt_classes] else: raise NotImplementedError else: prompts = None
torch.backends.cuda.matmul.allow_tf32 = True # torch.backends.cudnn.benchmark = True try: except: print("Install OpenClip via: pip install open_clip_torch") def set_seed(seed: int = 0): torch.manual_seed(seed) np.random.seed(seed) random.seed(seed) torch.cuda.manual_seed_all(seed) def blockPrint(): sys.stdout = open(os.devnull, 'w') def get_classifier(cfg, device): if "ImageNet" in cfg.data._target_: classifier_name = cfg.classifier_model.name if classifier_name == "robust_resnet50": classifier_model = MadryNet(cfg.classifier_model.ckpt, device) if "classifier_wrapper" in cfg.classifier_model and cfg.classifier_model.classifier_wrapper: classifier_model = Crop(classifier_model) else: classifier_model = getattr(torchvision.models, classifier_name)(pretrained=True) if "classifier_wrapper" in cfg.classifier_model and cfg.classifier_model.classifier_wrapper: classifier_model = CropAndNormalizer(classifier_model) elif "CelebAHQDataset" in cfg.data._target_: assert cfg.data.query_label in [20, 31, 39], 'Query label MUST be 20 (Gender), 31 (Smile), or 39 (Age) for CelebAHQ' ql = 0 if cfg.data.query_label in [31, 39]: ql = 1 if cfg.data.query_label == 31 else 2 classifier_model = DecisionDensenetModel(3, pretrained=False, query_label=ql) classifier_model.load_state_dict(torch.load(cfg.classifier_model.classifier_path, map_location='cpu')['model_state_dict']) if cfg.classifier_model.classifier_wrapper: classifier_model = Normalizer( classifier_model, [0.5] * 3, [0.5] * 3 ) elif "Flowers102" in cfg.data._target_: # fine-tuned Dino ViT B/8: https://arxiv.org/pdf/2104.14294.pdf dino = torch.hub.load('facebookresearch/dino:main', 'dino_vits8').to(device).eval() dim = dino.embed_dim linear_classifier = LinearClassifier(dim*cfg.classifier_model.n_last_blocks, 102) linear_classifier.load_state_dict(torch.load(cfg.classifier_model.classifier_path, map_location="cpu"), strict=True) linear_classifier = linear_classifier.eval().to(device) classifier_model = DINOLinear(dino, linear_classifier) transforms_list = [transforms.CenterCrop(224), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))] classifier_model = GenericPreprocessing(classifier_model, transforms.Compose(transforms_list)) elif "OxfordIIIPets" in cfg.data._target_: # zero-shot OpenClip: https://arxiv.org/pdf/2212.07143.pdf model, _, preprocess = open_clip.create_model_and_transforms('ViT-B-32', pretrained='laion2b_s34b_b79k') model = model.to(device).eval() tokenizer = open_clip.get_tokenizer('ViT-B-32') # prompts following https://github.com/openai/CLIP/blob/main/data/prompts.md with open("data/pets_idx_to_label.json", "r") as f: pets_idx_to_classname = json.load(f) prompts = [f"a photo of a {label}, a type of pet." for label in pets_idx_to_classname.values()] classifier_model = VisionLanguageWrapper(model, tokenizer, prompts) # try running optimization on 224x224 pixel image # transforms_list = [preprocess.transforms[0], preprocess.transforms[1], preprocess.transforms[4]] if cfg.classifier_model.classifier_wrapper: transforms_list = [preprocess.transforms[1], preprocess.transforms[4]] # CenterCrop(224, 224), Normalize classifier_model = GenericPreprocessing(classifier_model, transforms.Compose(transforms_list)) else: raise NotImplementedError return classifier_model def get_dataset(cfg, last_data_idx: int = 0): if "ImageNet" in cfg.data._target_: out_size = 256 transform_list = [ transforms.Resize((out_size, out_size)), transforms.ToTensor() ] transform = transforms.Compose(transform_list) dataset = instantiate(cfg.data, start_sample=cfg.data.start_sample, end_sample=cfg.data.end_sample, transform=transform, restart_idx=last_data_idx) elif "CelebAHQDataset" in cfg.data._target_: dataset = instantiate( cfg.data, image_size=256, data_dir=cfg.data.data_dir, random_crop=False, random_flip=False, partition='test', query_label=cfg.data.query_label, normalize=False, shard=cfg.data.shard, num_shards=cfg.data.num_shards, restart_idx=last_data_idx ) elif "Flowers102" in cfg.data._target_: transform = transforms.Compose([ transforms.Resize((256, 256)), transforms.ToTensor(), ]) dataset = instantiate( cfg.data, shard=cfg.data.shard, num_shards=cfg.data.num_shards, transform=transform, restart_idx=last_data_idx ) elif "OxfordIIIPets" in cfg.data._target_: # try running on 224x224 img def _convert_to_rgb(image): return image.convert('RGB') out_size = 256 transform_list = [ transforms.Resize((out_size, out_size)), # transforms.CenterCrop(out_size), _convert_to_rgb, transforms.ToTensor(), ] transform = transforms.Compose(transform_list) dataset = instantiate( cfg.data, shard=cfg.data.shard, num_shards=cfg.data.num_shards, transform=transform, restart_idx=last_data_idx ) else: raise NotImplementedError return dataset @hydra.main(version_base=None, config_path="../configs/ldce", config_name="v1") def main(cfg : DictConfig) -> None: if "verbose" not in cfg: with open_dict(cfg): cfg.verbose = True if "record_intermediate_results" not in cfg: with open_dict(cfg): cfg.record_intermediate_results = True if "verbose" in cfg and not cfg.verbose: blockPrint() os.makedirs(cfg.output_dir, exist_ok=True) os.chmod(cfg.output_dir, 0o777) if "ImageNet" in cfg.data._target_: out_dir = os.path.join(cfg.output_dir, f"bucket_{cfg.data.start_sample}_{cfg.data.end_sample}") else: out_dir = os.path.join(cfg.output_dir, f"bucket_{cfg.data.shard}_{cfg.data.num_shards}") os.makedirs(out_dir, exist_ok=True) os.chmod(out_dir, 0o777) checkpoint_path = os.path.join(out_dir, "last_saved_id.pth") config = {} if "ImageNet" in cfg.data._target_: run_id = f"{cfg.data.start_sample}_{cfg.data.end_sample}" else: run_id = f"{cfg.data.shard}_{cfg.data.num_shards}" if cfg.resume: print("run ID to resume: ", run_id) else: print("starting new run", run_id) config.update(OmegaConf.to_container(cfg, resolve=True)) print("current run id: ", run_id) last_data_idx = 0 if cfg.resume: # or os.path.isfile(checkpoint_path): resume only if asked to, allow restarts print(f"resuming from {checkpoint_path}") #check if checkpoint exists if not os.path.exists(checkpoint_path): print("checkpoint does not exist! starting from 0 ...") else: checkpoint = torch.load(checkpoint_path)# torch.load(restored_file.name) last_data_idx = checkpoint["last_data_idx"] + 1 if "last_data_idx" in checkpoint else 0 print(f"resuming from batch {last_data_idx}") device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # device = torch.device("cpu") # there seems to be a CUDA/autograd instability in gradient computation print(f"using device: {device}") model = get_model(cfg_path=cfg.diffusion_model.cfg_path, ckpt_path = cfg.diffusion_model.ckpt_path).to(device).eval() classifier_model = get_classifier(cfg, device) classifier_model.to(device).eval() classifier_model.train = disabled_train ddim_steps = cfg.ddim_steps ddim_eta = cfg.ddim_eta scale = cfg.scale #for unconditional guidance strength = cfg.strength #for unconditional guidance sampler = CCMDDIMSampler(model, classifier_model, seg_model= None, classifier_wrapper="classifier_wrapper" in cfg.classifier_model and cfg.classifier_model.classifier_wrapper, record_intermediate_results=cfg.record_intermediate_results, verbose=cfg.verbose, **cfg.sampler) sampler.make_schedule(ddim_num_steps=ddim_steps, ddim_eta=ddim_eta, verbose=False) assert 0. <= strength <= 1., 'can only work with strength in [0.0, 1.0]' t_enc = int(strength * len(sampler.ddim_timesteps)) assert len(sampler.ddim_timesteps) == ddim_steps, "ddim_steps should be equal to len(sampler.ddim_timesteps)" n_samples_per_class = cfg.n_samples_per_class batch_size = cfg.data.batch_size shuffle = cfg.get("shuffle", False) #save config to the output directory #check if the config file already exists else create a config file config_path = os.path.join(out_dir, "config.yaml") if os.path.exists(config_path): print("config file already exists! skipping ...") else: with open(os.path.join(out_dir, "config.yaml"), 'w') as f: print("saving config to ", os.path.join(out_dir, "config.yaml ...")) yaml.dump(config, f) os.chmod(os.path.join(out_dir, "config.yaml"), 0o555) #data_path = cfg.data_path dataset = get_dataset(cfg, last_data_idx=last_data_idx) print("dataset length: ", len(dataset)) data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=1) if "ImageNet" in cfg.data._target_: i2h = name_map elif "CelebAHQDataset" in cfg.data._target_: # query label 31 (smile): label=0 <-> no smile and label=1 <-> smile # query label 39 (age): label=0 <-> old and label=1 <-> young assert cfg.data.query_label in [31, 39] if 31 == cfg.data.query_label: i2h = ["no smile", "smile"] elif 39 == cfg.data.query_label: i2h = ["old", "young"] else: raise NotImplementedError elif "Flowers102" in cfg.data._target_: with open("data/flowers_idx_to_label.json", "r") as f: flowers_idx_to_classname = json.load(f) flowers_idx_to_classname = {int(k)-1: v for k, v in flowers_idx_to_classname.items()} i2h = flowers_idx_to_classname elif "OxfordIIIPets" in cfg.data._target_: with open("data/pets_idx_to_label.json", "r") as f: pets_idx_to_classname = json.load(f) i2h = {int(k): v for k, v in pets_idx_to_classname.items()} else: raise NotImplementedError if "ImageNet" in cfg.data._target_: with open('data/synset_closest_idx.yaml', 'r') as file: synset_closest_idx = yaml.safe_load(file) elif "Flowers102" in cfg.data._target_: with open("data/flowers_closest_indices.json") as file: closest_indices = json.load(file) closest_indices = {int(k):v for k,v in closest_indices.items()} elif "OxfordIIIPets" in cfg.data._target_: with open("data/pets_closest_indices.json") as file: closest_indices = json.load(file) closest_indices = {int(k):v for k,v in closest_indices.items()} if not cfg.resume: torch.save({"last_data_idx": -1}, checkpoint_path) seed = cfg.seed if "seed" in cfg else 0 set_seed(seed=seed) for i, batch in enumerate(data_loader): if "fixed_seed" in cfg: set_seed(seed=cfg.get("seed", 0)) if cfg.fixed_seed else None seed = seed if cfg.fixed_seed else -1 if "return_tgt_cls" in cfg.data and cfg.data.return_tgt_cls: image, label, tgt_classes, unique_data_idx = batch tgt_classes = tgt_classes.to(device) #squeeze() else: image, label, unique_data_idx = batch if "ImageNet" in cfg.data._target_: tgt_classes = torch.tensor([random.choice(synset_closest_idx[l.item()]) for l in label]).to(device) elif "CelebAHQDataset" in cfg.data._target_: tgt_classes = (1 - label).type(torch.float32) elif "Flowers102" in cfg.data._target_ or "OxfordIIIPets" in cfg.data._target_: tgt_classes = torch.tensor([closest_indices[unique_data_idx[l].item()*cfg.data.num_shards + cfg.data.shard][0] for l in range(label.shape[0])]).to(device) else: raise NotImplementedError image = image.to(device) #squeeze() label = label.to(device) #.item() #squeeze() #tgt_classes = torch.tensor([random.choice(synset_closest_idx[l.item()]) for l in label]).to(device) #tgt_classes = synset_closest_idx[label] #tgt_classes = torch.tensor([random.choice(synset_closest_idx[l.item()]) for l in label]).to(device) #shuffle tgt_classes #random.shuffle(tgt_classes) #get classifcation prediction with torch.inference_mode(): #with precision_scope(): if "classifier_wrapper" in cfg.classifier_model and cfg.classifier_model.classifier_wrapper: logits = classifier_model(image) else: logits = sampler.get_classifier_logits(_unmap_img(image)) #converting to -1, 1 # TODO: handle binary vs multi-class if "ImageNet" in cfg.data._target_ or "OxfordIIIPets" in cfg.data._target_ or "Flowers102" in cfg.data._target_: # multi-class in_class_pred = logits.argmax(dim=1) in_confid = logits.softmax(dim=1).max(dim=1).values in_confid_tgt = logits.softmax(dim=1)[torch.arange(batch_size), tgt_classes] else: # binary in_class_pred = (logits >= 0).type(torch.int8) in_confid = torch.where(logits >= 0, logits.sigmoid(), 1 - logits.sigmoid()) in_confid_tgt = torch.where(tgt_classes.to(device) == 0, 1 - logits.sigmoid(), logits.sigmoid()) print("in class_pred: ", in_class_pred, in_confid) for j, l in enumerate(label): print(f"converting {i} from : {i2h[l.item()]} to: {i2h[int(tgt_classes[j].item())]}") init_image = image.clone() #image.repeat(n_samples_per_class, 1, 1, 1).to(device) sampler.init_images = init_image.to(device) sampler.init_labels = label # n_samples_per_class * [label] if isinstance(cfg.sampler.lp_custom, str) and "dino_" in cfg.sampler.lp_custom: if device != next(sampler.distance_criterion.dino.parameters()).device: sampler.distance_criterion.dino = sampler.distance_criterion.dino.to(device) sampler.dino_init_features = sampler.get_dino_features(sampler.init_images, device=device).clone() #mapped_image = _unmap_img(init_image) init_latent = model.get_first_stage_encoding( model.encode_first_stage(_unmap_img(init_image))) # move to latent space if "txt" == model.cond_stage_key: # text-conditional if "ImageNet" in cfg.data._target_: prompts = [f"a photo of a {openai_imagenet_classes[idx.item()]}." for idx in tgt_classes] elif "CelebAHQDataset" in cfg.data._target_: # query label 31 (smile): label=0 <-> no smile and label=1 <-> smile # query label 39 (age): label=0 <-> old and label=1 <-> young assert cfg.data.query_label in [31, 39] prompts = [] for target in tgt_classes: if cfg.data.query_label == 31 and target == 0: attr = "non-smiling" elif cfg.data.query_label == 31 and target == 1: attr = "smiling" elif cfg.data.query_label == 39 and target == 0: attr = "old" elif cfg.data.query_label == 39 and target == 1: attr = "young" else: raise NotImplementedError prompts.append(f"a photo of a {attr} person") elif "OxfordIIIPets" in cfg.data._target_: # prompts following https://github.com/openai/CLIP/blob/main/data/prompts.md prompts = [f"a photo of a {i2h[idx.item()]}, a type of pet." for idx in tgt_classes] elif "Flowers102" in cfg.data._target_: # prompts following https://github.com/openai/CLIP/blob/main/data/prompts.md prompts = [f"a photo of a {i2h[idx.item()]}, a type of flower." for idx in tgt_classes] else: raise NotImplementedError else: prompts = None
out = generate_samples(
3
2023-10-10 09:40:10+00:00
24k
spla-tam/SplaTAM
scripts/post_splatam_opt.py
[ { "identifier": "AzureKinectDataset", "path": "datasets/gradslam_datasets/azure.py", "snippet": "class AzureKinectDataset(GradSLAMDataset):\n def __init__(\n self,\n config_dict,\n basedir,\n sequence,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 480,\n desired_width: Optional[int] = 640,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n self.pose_path = None\n\n # # check if a file named 'poses_global_dvo.txt' exists in the basedir / sequence folder\n # if os.path.isfile(os.path.join(basedir, sequence, \"poses_global_dvo.txt\")):\n # self.pose_path = os.path.join(basedir, sequence, \"poses_global_dvo.txt\")\n\n if \"odomfile\" in kwargs.keys():\n self.pose_path = os.path.join(self.input_folder, kwargs[\"odomfile\"])\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n )\n\n def get_filepaths(self):\n color_paths = natsorted(glob.glob(f\"{self.input_folder}/color/*.jpg\"))\n depth_paths = natsorted(glob.glob(f\"{self.input_folder}/depth/*.png\"))\n embedding_paths = None\n if self.load_embeddings:\n embedding_paths = natsorted(glob.glob(f\"{self.input_folder}/{self.embedding_dir}/*.pt\"))\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n if self.pose_path is None:\n print(\"WARNING: Dataset does not contain poses. Returning identity transform.\")\n return [torch.eye(4).float() for _ in range(self.num_imgs)]\n else:\n # Determine whether the posefile ends in \".log\"\n # a .log file has the following format for each frame\n # frame_idx frame_idx+1\n # row 1 of 4x4 transform\n # row 2 of 4x4 transform\n # row 3 of 4x4 transform\n # row 4 of 4x4 transform\n # [repeat for all frames]\n #\n # on the other hand, the \"poses_o3d.txt\" or \"poses_dvo.txt\" files have the format\n # 16 entries of 4x4 transform\n # [repeat for all frames]\n if self.pose_path.endswith(\".log\"):\n # print(\"Loading poses from .log format\")\n poses = []\n lines = None\n with open(self.pose_path, \"r\") as f:\n lines = f.readlines()\n if len(lines) % 5 != 0:\n raise ValueError(\n \"Incorrect file format for .log odom file \" \"Number of non-empty lines must be a multiple of 5\"\n )\n num_lines = len(lines) // 5\n for i in range(0, num_lines):\n _curpose = []\n _curpose.append(list(map(float, lines[5 * i + 1].split())))\n _curpose.append(list(map(float, lines[5 * i + 2].split())))\n _curpose.append(list(map(float, lines[5 * i + 3].split())))\n _curpose.append(list(map(float, lines[5 * i + 4].split())))\n _curpose = np.array(_curpose).reshape(4, 4)\n poses.append(torch.from_numpy(_curpose))\n else:\n poses = []\n lines = None\n with open(self.pose_path, \"r\") as f:\n lines = f.readlines()\n for line in lines:\n if len(line.split()) == 0:\n continue\n c2w = np.array(list(map(float, line.split()))).reshape(4, 4)\n poses.append(torch.from_numpy(c2w))\n return poses\n\n def read_embedding_from_file(self, embedding_file_path):\n embedding = torch.load(embedding_file_path)\n return embedding # .permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "load_dataset_config", "path": "datasets/gradslam_datasets/dataconfig.py", "snippet": "def load_dataset_config(path, default_path=None):\n \"\"\"\n Loads config file.\n\n Args:\n path (str): path to config file.\n default_path (str, optional): whether to use default path. Defaults to None.\n\n Returns:\n cfg (dict): config dict.\n\n \"\"\"\n # load configuration from file itself\n with open(path, \"r\") as f:\n cfg_special = yaml.full_load(f)\n\n # check if we should inherit from a config\n inherit_from = cfg_special.get(\"inherit_from\")\n\n # if yes, load this config first as default\n # if no, use the default_path\n if inherit_from is not None:\n cfg = load_dataset_config(inherit_from, default_path)\n elif default_path is not None:\n with open(default_path, \"r\") as f:\n cfg = yaml.full_load(f)\n else:\n cfg = dict()\n\n # include main configuration\n update_recursive(cfg, cfg_special)\n\n return cfg" }, { "identifier": "ICLDataset", "path": "datasets/gradslam_datasets/icl.py", "snippet": "class ICLDataset(GradSLAMDataset):\n def __init__(\n self,\n config_dict: Dict,\n basedir: Union[Path, str],\n sequence: Union[Path, str],\n stride: Optional[int] = 1,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 480,\n desired_width: Optional[int] = 640,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[Union[Path, str]] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n embedding_file_extension: Optional[str] = \"pt\",\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n # Attempt to find pose file (*.gt.sim)\n self.pose_path = glob.glob(os.path.join(self.input_folder, \"*.gt.sim\"))\n if self.pose_path == 0:\n raise ValueError(\"Need pose file ending in extension `*.gt.sim`\")\n self.pose_path = self.pose_path[0]\n self.embedding_file_extension = embedding_file_extension\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n )\n\n def get_filepaths(self):\n color_paths = natsorted(glob.glob(f\"{self.input_folder}/rgb/*.png\"))\n depth_paths = natsorted(glob.glob(f\"{self.input_folder}/depth/*.png\"))\n embedding_paths = None\n if self.load_embeddings:\n embedding_paths = natsorted(\n glob.glob(f\"{self.input_folder}/{self.embedding_dir}/*.{self.embedding_file_extension}\")\n )\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n poses = []\n\n lines = []\n with open(self.pose_path, \"r\") as f:\n lines = f.readlines()\n\n _posearr = []\n for line in lines:\n line = line.strip().split()\n if len(line) == 0:\n continue\n _npvec = np.asarray([float(line[0]), float(line[1]), float(line[2]), float(line[3])])\n _posearr.append(_npvec)\n _posearr = np.stack(_posearr)\n\n for pose_line_idx in range(0, _posearr.shape[0], 3):\n _curpose = np.zeros((4, 4))\n _curpose[3, 3] = 3\n _curpose[0] = _posearr[pose_line_idx]\n _curpose[1] = _posearr[pose_line_idx + 1]\n _curpose[2] = _posearr[pose_line_idx + 2]\n poses.append(torch.from_numpy(_curpose).float())\n\n return poses\n\n def read_embedding_from_file(self, embedding_file_path):\n embedding = torch.load(embedding_file_path)\n return embedding.permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "ReplicaDataset", "path": "datasets/gradslam_datasets/replica.py", "snippet": "class ReplicaDataset(GradSLAMDataset):\n def __init__(\n self,\n config_dict,\n basedir,\n sequence,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 480,\n desired_width: Optional[int] = 640,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n self.pose_path = os.path.join(self.input_folder, \"traj.txt\")\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n )\n\n def get_filepaths(self):\n color_paths = natsorted(glob.glob(f\"{self.input_folder}/results/frame*.jpg\"))\n depth_paths = natsorted(glob.glob(f\"{self.input_folder}/results/depth*.png\"))\n embedding_paths = None\n if self.load_embeddings:\n embedding_paths = natsorted(glob.glob(f\"{self.input_folder}/{self.embedding_dir}/*.pt\"))\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n poses = []\n with open(self.pose_path, \"r\") as f:\n lines = f.readlines()\n for i in range(self.num_imgs):\n line = lines[i]\n c2w = np.array(list(map(float, line.split()))).reshape(4, 4)\n # c2w[:3, 1] *= -1\n # c2w[:3, 2] *= -1\n c2w = torch.from_numpy(c2w).float()\n poses.append(c2w)\n return poses\n\n def read_embedding_from_file(self, embedding_file_path):\n embedding = torch.load(embedding_file_path)\n return embedding.permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "ScannetDataset", "path": "datasets/gradslam_datasets/scannet.py", "snippet": "class ScannetDataset(GradSLAMDataset):\n def __init__(\n self,\n config_dict,\n basedir,\n sequence,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 968,\n desired_width: Optional[int] = 1296,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n self.pose_path = None\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n )\n\n def get_filepaths(self):\n color_paths = natsorted(glob.glob(f\"{self.input_folder}/color/*.jpg\"))\n depth_paths = natsorted(glob.glob(f\"{self.input_folder}/depth/*.png\"))\n embedding_paths = None\n if self.load_embeddings:\n embedding_paths = natsorted(glob.glob(f\"{self.input_folder}/{self.embedding_dir}/*.pt\"))\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n poses = []\n posefiles = natsorted(glob.glob(f\"{self.input_folder}/pose/*.txt\"))\n for posefile in posefiles:\n _pose = torch.from_numpy(np.loadtxt(posefile))\n poses.append(_pose)\n return poses\n\n def read_embedding_from_file(self, embedding_file_path):\n print(embedding_file_path)\n embedding = torch.load(embedding_file_path, map_location=\"cpu\")\n return embedding.permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "Ai2thorDataset", "path": "datasets/gradslam_datasets/ai2thor.py", "snippet": "class Ai2thorDataset(GradSLAMDataset):\n def __init__(\n self,\n config_dict,\n basedir,\n sequence,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 968,\n desired_width: Optional[int] = 1296,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n )\n\n def get_filepaths(self):\n color_paths = natsorted(glob.glob(f\"{self.input_folder}/color/*.png\"))\n depth_paths = natsorted(glob.glob(f\"{self.input_folder}/depth/*.png\"))\n embedding_paths = None\n if self.load_embeddings:\n if self.embedding_dir == \"embed_semseg\":\n # embed_semseg is stored as uint16 pngs\n embedding_paths = natsorted(glob.glob(f\"{self.input_folder}/{self.embedding_dir}/*.png\"))\n else:\n embedding_paths = natsorted(glob.glob(f\"{self.input_folder}/{self.embedding_dir}/*.pt\"))\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n poses = []\n posefiles = natsorted(glob.glob(f\"{self.input_folder}/pose/*.txt\"))\n for posefile in posefiles:\n _pose = torch.from_numpy(np.loadtxt(posefile))\n poses.append(_pose)\n return poses\n\n def read_embedding_from_file(self, embedding_file_path):\n if self.embedding_dir == \"embed_semseg\":\n embedding = imageio.imread(embedding_file_path) # (H, W)\n embedding = cv2.resize(\n embedding, (self.desired_width, self.desired_height), interpolation=cv2.INTER_NEAREST\n )\n embedding = torch.from_numpy(embedding).long() # (H, W)\n embedding = F.one_hot(embedding, num_classes=self.embedding_dim) # (H, W, C)\n embedding = embedding.half() # (H, W, C)\n embedding = embedding.permute(2, 0, 1) # (C, H, W)\n embedding = embedding.unsqueeze(0) # (1, C, H, W)\n else:\n embedding = torch.load(embedding_file_path, map_location=\"cpu\")\n return embedding.permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "RealsenseDataset", "path": "datasets/gradslam_datasets/realsense.py", "snippet": "class RealsenseDataset(GradSLAMDataset):\n \"\"\"\n Dataset class to process depth images captured by realsense camera on the tabletop manipulator\n \"\"\"\n\n def __init__(\n self,\n config_dict,\n basedir,\n sequence,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 480,\n desired_width: Optional[int] = 640,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n # only poses/images/depth corresponding to the realsense_camera_order are read/used\n self.pose_path = os.path.join(self.input_folder, \"poses\")\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n )\n\n def get_filepaths(self):\n color_paths = natsorted(glob.glob(os.path.join(self.input_folder, \"rgb\", \"*.jpg\")))\n depth_paths = natsorted(glob.glob(os.path.join(self.input_folder, \"depth\", \"*.png\")))\n embedding_paths = None\n if self.load_embeddings:\n embedding_paths = natsorted(glob.glob(f\"{self.input_folder}/{self.embedding_dir}/*.pt\"))\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n posefiles = natsorted(glob.glob(os.path.join(self.pose_path, \"*.npy\")))\n poses = []\n P = torch.tensor([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]).float()\n for posefile in posefiles:\n c2w = torch.from_numpy(np.load(posefile)).float()\n _R = c2w[:3, :3]\n _t = c2w[:3, 3]\n _pose = P @ c2w @ P.T\n poses.append(_pose)\n return poses\n\n def read_embedding_from_file(self, embedding_file_path):\n embedding = torch.load(embedding_file_path)\n return embedding.permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "Record3DDataset", "path": "datasets/gradslam_datasets/record3d.py", "snippet": "class Record3DDataset(GradSLAMDataset):\n \"\"\"\n Dataset class to read in saved files from the structure created by our\n `save_record3d_stream.py` script\n \"\"\"\n\n def __init__(\n self,\n config_dict,\n basedir,\n sequence,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 480,\n desired_width: Optional[int] = 640,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n self.pose_path = os.path.join(self.input_folder, \"poses\")\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n )\n\n def get_filepaths(self):\n color_paths = natsorted(glob.glob(os.path.join(self.input_folder, \"rgb\", \"*.png\")))\n depth_paths = natsorted(glob.glob(os.path.join(self.input_folder, \"depth\", \"*.png\")))\n embedding_paths = None\n if self.load_embeddings:\n embedding_paths = natsorted(glob.glob(f\"{self.input_folder}/{self.embedding_dir}/*.pt\"))\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n posefiles = natsorted(glob.glob(os.path.join(self.pose_path, \"*.npy\")))\n poses = []\n P = torch.tensor([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]).float()\n for posefile in posefiles:\n c2w = torch.from_numpy(np.load(posefile)).float()\n _R = c2w[:3, :3]\n _t = c2w[:3, 3]\n _pose = P @ c2w @ P.T\n poses.append(_pose)\n return poses\n\n def read_embedding_from_file(self, embedding_file_path):\n embedding = torch.load(embedding_file_path)\n return embedding.permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "TUMDataset", "path": "datasets/gradslam_datasets/tum.py", "snippet": "class TUMDataset(GradSLAMDataset):\n def __init__(\n self,\n config_dict,\n basedir,\n sequence,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 480,\n desired_width: Optional[int] = 640,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n self.pose_path = None\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n )\n\n def parse_list(self, filepath, skiprows=0):\n \"\"\" read list data \"\"\"\n data = np.loadtxt(filepath, delimiter=' ',\n dtype=np.unicode_, skiprows=skiprows)\n return data\n\n def associate_frames(self, tstamp_image, tstamp_depth, tstamp_pose, max_dt=0.08):\n \"\"\" pair images, depths, and poses \"\"\"\n associations = []\n for i, t in enumerate(tstamp_image):\n if tstamp_pose is None:\n j = np.argmin(np.abs(tstamp_depth - t))\n if (np.abs(tstamp_depth[j] - t) < max_dt):\n associations.append((i, j))\n\n else:\n j = np.argmin(np.abs(tstamp_depth - t))\n k = np.argmin(np.abs(tstamp_pose - t))\n\n if (np.abs(tstamp_depth[j] - t) < max_dt) and \\\n (np.abs(tstamp_pose[k] - t) < max_dt):\n associations.append((i, j, k))\n\n return associations\n\n def pose_matrix_from_quaternion(self, pvec):\n \"\"\" convert 4x4 pose matrix to (t, q) \"\"\"\n from scipy.spatial.transform import Rotation\n\n pose = np.eye(4)\n pose[:3, :3] = Rotation.from_quat(pvec[3:]).as_matrix()\n pose[:3, 3] = pvec[:3]\n return pose\n\n def get_filepaths(self):\n\n frame_rate = 32\n \"\"\" read video data in tum-rgbd format \"\"\"\n if os.path.isfile(os.path.join(self.input_folder, 'groundtruth.txt')):\n pose_list = os.path.join(self.input_folder, 'groundtruth.txt')\n elif os.path.isfile(os.path.join(self.input_folder, 'pose.txt')):\n pose_list = os.path.join(self.input_folder, 'pose.txt')\n\n image_list = os.path.join(self.input_folder, 'rgb.txt')\n depth_list = os.path.join(self.input_folder, 'depth.txt')\n\n image_data = self.parse_list(image_list)\n depth_data = self.parse_list(depth_list)\n pose_data = self.parse_list(pose_list, skiprows=1)\n pose_vecs = pose_data[:, 1:].astype(np.float64)\n\n tstamp_image = image_data[:, 0].astype(np.float64)\n tstamp_depth = depth_data[:, 0].astype(np.float64)\n tstamp_pose = pose_data[:, 0].astype(np.float64)\n associations = self.associate_frames(\n tstamp_image, tstamp_depth, tstamp_pose)\n\n indicies = [0]\n for i in range(1, len(associations)):\n t0 = tstamp_image[associations[indicies[-1]][0]]\n t1 = tstamp_image[associations[i][0]]\n if t1 - t0 > 1.0 / frame_rate:\n indicies += [i]\n\n color_paths, depth_paths = [], []\n for ix in indicies:\n (i, j, k) = associations[ix]\n color_paths += [os.path.join(self.input_folder, image_data[i, 1])]\n depth_paths += [os.path.join(self.input_folder, depth_data[j, 1])]\n\n embedding_paths = None\n\n return color_paths, depth_paths, embedding_paths\n \n def load_poses(self):\n \n frame_rate = 32\n \"\"\" read video data in tum-rgbd format \"\"\"\n if os.path.isfile(os.path.join(self.input_folder, 'groundtruth.txt')):\n pose_list = os.path.join(self.input_folder, 'groundtruth.txt')\n elif os.path.isfile(os.path.join(self.input_folder, 'pose.txt')):\n pose_list = os.path.join(self.input_folder, 'pose.txt')\n\n image_list = os.path.join(self.input_folder, 'rgb.txt')\n depth_list = os.path.join(self.input_folder, 'depth.txt')\n\n image_data = self.parse_list(image_list)\n depth_data = self.parse_list(depth_list)\n pose_data = self.parse_list(pose_list, skiprows=1)\n pose_vecs = pose_data[:, 1:].astype(np.float64)\n\n tstamp_image = image_data[:, 0].astype(np.float64)\n tstamp_depth = depth_data[:, 0].astype(np.float64)\n tstamp_pose = pose_data[:, 0].astype(np.float64)\n associations = self.associate_frames(\n tstamp_image, tstamp_depth, tstamp_pose)\n\n indicies = [0]\n for i in range(1, len(associations)):\n t0 = tstamp_image[associations[indicies[-1]][0]]\n t1 = tstamp_image[associations[i][0]]\n if t1 - t0 > 1.0 / frame_rate:\n indicies += [i]\n\n color_paths, poses, depth_paths, intrinsics = [], [], [], []\n inv_pose = None\n for ix in indicies:\n (i, j, k) = associations[ix]\n color_paths += [os.path.join(self.input_folder, image_data[i, 1])]\n depth_paths += [os.path.join(self.input_folder, depth_data[j, 1])]\n c2w = self.pose_matrix_from_quaternion(pose_vecs[k])\n c2w = torch.from_numpy(c2w).float()\n poses += [c2w]\n\n return poses\n \n def read_embedding_from_file(self, embedding_file_path):\n embedding = torch.load(embedding_file_path, map_location=\"cpu\")\n return embedding.permute(0, 2, 3, 1)" }, { "identifier": "ScannetPPDataset", "path": "datasets/gradslam_datasets/scannetpp.py", "snippet": "class ScannetPPDataset(GradSLAMDataset):\n def __init__(\n self,\n basedir,\n sequence,\n ignore_bad: Optional[bool] = False,\n use_train_split: Optional[bool] = True,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 1168,\n desired_width: Optional[int] = 1752,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n config_dict = {}\n config_dict[\"dataset_name\"] = \"scannetpp\"\n self.pose_path = None\n self.ignore_bad = ignore_bad\n self.use_train_split = use_train_split\n\n # Load Train & Test Split\n self.train_test_split = json.load(open(f\"{self.input_folder}/dslr/train_test_lists.json\", \"r\"))\n if self.use_train_split:\n self.image_names = self.train_test_split[\"train\"]\n else:\n self.image_names = self.train_test_split[\"test\"]\n self.train_image_names = self.train_test_split[\"train\"]\n \n # Load NeRFStudio format camera & poses data\n self.cams_metadata = self.load_cams_metadata()\n if self.use_train_split:\n self.frames_metadata = self.cams_metadata[\"frames\"]\n self.filepath_index_mapping = create_filepath_index_mapping(self.frames_metadata)\n else:\n self.frames_metadata = self.cams_metadata[\"test_frames\"]\n self.train_frames_metadata = self.cams_metadata[\"frames\"]\n self.filepath_index_mapping = create_filepath_index_mapping(self.frames_metadata)\n self.train_filepath_index_mapping = create_filepath_index_mapping(self.train_frames_metadata) \n\n # Init Intrinsics\n config_dict[\"camera_params\"] = {}\n config_dict[\"camera_params\"][\"png_depth_scale\"] = 1000.0 # Depth is in mm\n config_dict[\"camera_params\"][\"image_height\"] = self.cams_metadata[\"h\"]\n config_dict[\"camera_params\"][\"image_width\"] = self.cams_metadata[\"w\"]\n config_dict[\"camera_params\"][\"fx\"] = self.cams_metadata[\"fl_x\"]\n config_dict[\"camera_params\"][\"fy\"] = self.cams_metadata[\"fl_y\"]\n config_dict[\"camera_params\"][\"cx\"] = self.cams_metadata[\"cx\"]\n config_dict[\"camera_params\"][\"cy\"] = self.cams_metadata[\"cy\"]\n\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n ) \n\n def load_cams_metadata(self):\n cams_metadata_path = f\"{self.input_folder}/dslr/nerfstudio/transforms_undistorted.json\"\n cams_metadata = json.load(open(cams_metadata_path, \"r\"))\n return cams_metadata\n \n def get_filepaths(self):\n base_path = f\"{self.input_folder}/dslr\"\n color_paths = []\n depth_paths = []\n self.tmp_poses = []\n P = torch.tensor(\n [\n [1, 0, 0, 0],\n [0, -1, 0, 0],\n [0, 0, -1, 0],\n [0, 0, 0, 1]\n ]\n ).float()\n if not self.use_train_split:\n self.first_train_image_name = self.train_image_names[0]\n self.first_train_image_index = self.train_filepath_index_mapping.get(self.first_train_image_name)\n self.first_train_frame_metadata = self.train_frames_metadata[self.first_train_image_index]\n # Get path of undistorted image and depth\n color_path = f\"{base_path}/undistorted_images/{self.first_train_image_name}\"\n depth_path = f\"{base_path}/undistorted_depths/{self.first_train_image_name.replace('.JPG', '.png')}\"\n color_paths.append(color_path)\n depth_paths.append(depth_path)\n # Get pose of first train frame in GradSLAM format\n c2w = torch.from_numpy(np.array(self.first_train_frame_metadata[\"transform_matrix\"])).float()\n _pose = P @ c2w @ P.T\n self.tmp_poses.append(_pose)\n for image_name in self.image_names:\n # Search for image name in frames_metadata\n frame_metadata = self.frames_metadata[self.filepath_index_mapping.get(image_name)]\n # Check if frame is blurry and if it needs to be ignored\n if self.ignore_bad and frame_metadata['is_bad']:\n continue\n # Get path of undistorted image and depth\n color_path = f\"{base_path}/undistorted_images/{image_name}\"\n depth_path = f\"{base_path}/undistorted_depths/{image_name.replace('.JPG', '.png')}\"\n color_paths.append(color_path)\n depth_paths.append(depth_path)\n # Get pose of undistorted image in GradSLAM format\n c2w = torch.from_numpy(np.array(frame_metadata[\"transform_matrix\"])).float()\n _pose = P @ c2w @ P.T\n self.tmp_poses.append(_pose)\n embedding_paths = None\n if self.load_embeddings:\n embedding_paths = natsorted(glob.glob(f\"{base_path}/{self.embedding_dir}/*.pt\"))\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n return self.tmp_poses\n\n def read_embedding_from_file(self, embedding_file_path):\n print(embedding_file_path)\n embedding = torch.load(embedding_file_path, map_location=\"cpu\")\n return embedding.permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "NeRFCaptureDataset", "path": "datasets/gradslam_datasets/nerfcapture.py", "snippet": "class NeRFCaptureDataset(GradSLAMDataset):\n def __init__(\n self,\n basedir,\n sequence,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 1440,\n desired_width: Optional[int] = 1920,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n config_dict = {}\n config_dict[\"dataset_name\"] = \"nerfcapture\"\n self.pose_path = None\n \n # Load NeRFStudio format camera & poses data\n self.cams_metadata = self.load_cams_metadata()\n self.frames_metadata = self.cams_metadata[\"frames\"]\n self.filepath_index_mapping = create_filepath_index_mapping(self.frames_metadata)\n\n # Load RGB & Depth filepaths\n self.image_names = natsorted(os.listdir(f\"{self.input_folder}/rgb\"))\n self.image_names = [f'rgb/{image_name}' for image_name in self.image_names]\n\n # Init Intrinsics\n config_dict[\"camera_params\"] = {}\n config_dict[\"camera_params\"][\"png_depth_scale\"] = 6553.5 # Depth is in mm\n config_dict[\"camera_params\"][\"image_height\"] = self.cams_metadata[\"h\"]\n config_dict[\"camera_params\"][\"image_width\"] = self.cams_metadata[\"w\"]\n config_dict[\"camera_params\"][\"fx\"] = self.cams_metadata[\"fl_x\"]\n config_dict[\"camera_params\"][\"fy\"] = self.cams_metadata[\"fl_y\"]\n config_dict[\"camera_params\"][\"cx\"] = self.cams_metadata[\"cx\"]\n config_dict[\"camera_params\"][\"cy\"] = self.cams_metadata[\"cy\"]\n\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n ) \n\n def load_cams_metadata(self):\n cams_metadata_path = f\"{self.input_folder}/transforms.json\"\n cams_metadata = json.load(open(cams_metadata_path, \"r\"))\n return cams_metadata\n \n def get_filepaths(self):\n base_path = f\"{self.input_folder}\"\n color_paths = []\n depth_paths = []\n self.tmp_poses = []\n P = torch.tensor(\n [\n [1, 0, 0, 0],\n [0, -1, 0, 0],\n [0, 0, -1, 0],\n [0, 0, 0, 1]\n ]\n ).float()\n for image_name in self.image_names:\n # Search for image name in frames_metadata\n frame_metadata = self.frames_metadata[self.filepath_index_mapping.get(image_name)]\n # Get path of image and depth\n color_path = f\"{base_path}/{image_name}\"\n depth_path = f\"{base_path}/{image_name.replace('rgb', 'depth')}\"\n color_paths.append(color_path)\n depth_paths.append(depth_path)\n # Get pose of image in GradSLAM format\n c2w = torch.from_numpy(np.array(frame_metadata[\"transform_matrix\"])).float()\n _pose = P @ c2w @ P.T\n self.tmp_poses.append(_pose)\n embedding_paths = None\n if self.load_embeddings:\n embedding_paths = natsorted(glob.glob(f\"{base_path}/{self.embedding_dir}/*.pt\"))\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n return self.tmp_poses\n\n def read_embedding_from_file(self, embedding_file_path):\n print(embedding_file_path)\n embedding = torch.load(embedding_file_path, map_location=\"cpu\")\n return embedding.permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "seed_everything", "path": "utils/common_utils.py", "snippet": "def seed_everything(seed=42):\n \"\"\"\n Set the `seed` value for torch and numpy seeds. Also turns on\n deterministic execution for cudnn.\n \n Parameters:\n - seed: A hashable seed value\n \"\"\"\n random.seed(seed)\n os.environ[\"PYTHONHASHSEED\"] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n print(f\"Seed set to: {seed} (type: {type(seed)})\")" }, { "identifier": "save_seq_params", "path": "utils/common_utils.py", "snippet": "def save_seq_params(all_params, output_dir):\n params_to_save = {}\n for frame_idx, params in enumerate(all_params):\n params_to_save[f\"frame_{frame_idx}\"] = params2cpu(params)\n # Save the Parameters containing the Sequence of Gaussians\n os.makedirs(output_dir, exist_ok=True)\n print(f\"Saving parameters to: {output_dir}\")\n save_path = os.path.join(output_dir, \"params.npz\")\n np.savez(save_path, **params_to_save)" }, { "identifier": "save_params", "path": "utils/common_utils.py", "snippet": "def save_params(output_params, output_dir):\n # Convert to CPU Numpy Arrays\n to_save = params2cpu(output_params)\n # Save the Parameters containing the Gaussian Trajectories\n os.makedirs(output_dir, exist_ok=True)\n print(f\"Saving parameters to: {output_dir}\")\n save_path = os.path.join(output_dir, \"params.npz\")\n np.savez(save_path, **to_save)" }, { "identifier": "save_params_ckpt", "path": "utils/common_utils.py", "snippet": "def save_params_ckpt(output_params, output_dir, time_idx):\n # Convert to CPU Numpy Arrays\n to_save = params2cpu(output_params)\n # Save the Parameters containing the Gaussian Trajectories\n os.makedirs(output_dir, exist_ok=True)\n print(f\"Saving parameters to: {output_dir}\")\n save_path = os.path.join(output_dir, \"params\"+str(time_idx)+\".npz\")\n np.savez(save_path, **to_save)" }, { "identifier": "save_seq_params_ckpt", "path": "utils/common_utils.py", "snippet": "def save_seq_params_ckpt(all_params, output_dir,time_idx):\n params_to_save = {}\n for frame_idx, params in enumerate(all_params):\n params_to_save[f\"frame_{frame_idx}\"] = params2cpu(params)\n # Save the Parameters containing the Sequence of Gaussians\n os.makedirs(output_dir, exist_ok=True)\n print(f\"Saving parameters to: {output_dir}\")\n save_path = os.path.join(output_dir, \"params\"+str(time_idx)+\".npz\")\n np.savez(save_path, **params_to_save)" }, { "identifier": "setup_camera", "path": "utils/recon_helpers.py", "snippet": "def setup_camera(w, h, k, w2c, near=0.01, far=100):\n fx, fy, cx, cy = k[0][0], k[1][1], k[0][2], k[1][2]\n w2c = torch.tensor(w2c).cuda().float()\n cam_center = torch.inverse(w2c)[:3, 3]\n w2c = w2c.unsqueeze(0).transpose(1, 2)\n opengl_proj = torch.tensor([[2 * fx / w, 0.0, -(w - 2 * cx) / w, 0.0],\n [0.0, 2 * fy / h, -(h - 2 * cy) / h, 0.0],\n [0.0, 0.0, far / (far - near), -(far * near) / (far - near)],\n [0.0, 0.0, 1.0, 0.0]]).cuda().float().unsqueeze(0).transpose(1, 2)\n full_proj = w2c.bmm(opengl_proj)\n cam = Camera(\n image_height=h,\n image_width=w,\n tanfovx=w / (2 * fx),\n tanfovy=h / (2 * fy),\n bg=torch.tensor([0, 0, 0], dtype=torch.float32, device=\"cuda\"),\n scale_modifier=1.0,\n viewmatrix=w2c,\n projmatrix=full_proj,\n sh_degree=0,\n campos=cam_center,\n prefiltered=False\n )\n return cam" }, { "identifier": "params2rendervar", "path": "utils/gs_helpers.py", "snippet": "def params2rendervar(params):\n rendervar = {\n 'means3D': params['means3D'],\n 'colors_precomp': params['rgb_colors'],\n 'rotations': F.normalize(params['unnorm_rotations']),\n 'opacities': torch.sigmoid(params['logit_opacities']),\n 'scales': torch.exp(torch.tile(params['log_scales'], (1, 3))),\n 'means2D': torch.zeros_like(params['means3D'], requires_grad=True, device=\"cuda\") + 0\n }\n return rendervar" }, { "identifier": "params2depthplussilhouette", "path": "utils/gs_helpers.py", "snippet": "def params2depthplussilhouette(params, w2c):\n rendervar = {\n 'means3D': params['means3D'],\n 'colors_precomp': get_depth_and_silhouette(params['means3D'], w2c),\n 'rotations': F.normalize(params['unnorm_rotations']),\n 'opacities': torch.sigmoid(params['logit_opacities']),\n 'scales': torch.exp(torch.tile(params['log_scales'], (1, 3))),\n 'means2D': torch.zeros_like(params['means3D'], requires_grad=True, device=\"cuda\") + 0\n }\n return rendervar" }, { "identifier": "transformed_params2depthplussilhouette", "path": "utils/gs_helpers.py", "snippet": "def transformed_params2depthplussilhouette(params, w2c, transformed_pts):\n rendervar = {\n 'means3D': transformed_pts,\n 'colors_precomp': get_depth_and_silhouette(transformed_pts, w2c),\n 'rotations': F.normalize(params['unnorm_rotations']),\n 'opacities': torch.sigmoid(params['logit_opacities']),\n 'scales': torch.exp(torch.tile(params['log_scales'], (1, 3))),\n 'means2D': torch.zeros_like(params['means3D'], requires_grad=True, device=\"cuda\") + 0\n }\n return rendervar" }, { "identifier": "transform_to_frame", "path": "utils/gs_helpers.py", "snippet": "def transform_to_frame(params, time_idx, gaussians_grad, camera_grad):\n \"\"\"\n Function to transform Isotropic Gaussians from world frame to camera frame.\n \n Args:\n params: dict of parameters\n time_idx: time index to transform to\n gaussians_grad: enable gradients for Gaussians\n camera_grad: enable gradients for camera pose\n \n Returns:\n transformed_pts: Transformed Centers of Gaussians\n \"\"\"\n # Get Frame Camera Pose\n if camera_grad:\n cam_rot = F.normalize(params['cam_unnorm_rots'][..., time_idx])\n cam_tran = params['cam_trans'][..., time_idx]\n else:\n cam_rot = F.normalize(params['cam_unnorm_rots'][..., time_idx].detach())\n cam_tran = params['cam_trans'][..., time_idx].detach()\n rel_w2c = torch.eye(4).cuda().float()\n rel_w2c[:3, :3] = build_rotation(cam_rot)\n rel_w2c[:3, 3] = cam_tran\n\n # Get Centers and norm Rots of Gaussians in World Frame\n if gaussians_grad:\n pts = params['means3D']\n else:\n pts = params['means3D'].detach()\n \n # Transform Centers and Unnorm Rots of Gaussians to Camera Frame\n pts_ones = torch.ones(pts.shape[0], 1).cuda().float()\n pts4 = torch.cat((pts, pts_ones), dim=1)\n transformed_pts = (rel_w2c @ pts4.T).T[:, :3]\n\n return transformed_pts" }, { "identifier": "report_progress", "path": "utils/gs_helpers.py", "snippet": "def report_progress(params, data, i, progress_bar, iter_time_idx, sil_thres, every_i=1, qual_every_i=1, \n tracking=False, mapping=False, wandb_run=None, wandb_step=None, wandb_save_qual=False, online_time_idx=None):\n if i % every_i == 0 or i == 1:\n if wandb_run is not None:\n if tracking:\n stage = \"Tracking\"\n elif mapping:\n stage = \"Mapping\"\n else:\n stage = \"Current Frame Optimization\"\n\n # Initialize Render Variables\n rendervar = params2rendervar(params)\n depth_sil_rendervar = params2depthplussilhouette(params, data['w2c'])\n\n # Initialize Render Variables\n depth_sil, _, _, = Renderer(raster_settings=data['cam'])(**depth_sil_rendervar)\n rastered_depth = depth_sil[0, :, :].unsqueeze(0)\n valid_depth_mask = (data['depth'] > 0)\n silhouette = depth_sil[1, :, :]\n presence_sil_mask = (silhouette > sil_thres)\n\n im, _, _, = Renderer(raster_settings=data['cam'])(**rendervar)\n if tracking:\n psnr = calc_psnr(im * presence_sil_mask, data['im'] * presence_sil_mask).mean()\n else:\n psnr = calc_psnr(im, data['im']).mean()\n\n if tracking:\n diff_depth_rmse = torch.sqrt((((rastered_depth - data['depth']) * presence_sil_mask) ** 2))\n diff_depth_rmse = diff_depth_rmse * valid_depth_mask\n rmse = diff_depth_rmse.sum() / valid_depth_mask.sum()\n else:\n diff_depth_rmse = torch.sqrt(((rastered_depth - data['depth']) ** 2))\n diff_depth_rmse = diff_depth_rmse * valid_depth_mask\n rmse = diff_depth_rmse.sum() / valid_depth_mask.sum()\n\n if not mapping:\n progress_bar.set_postfix({f\"Time-Step: {iter_time_idx} | Frame {data['id']} | PSNR: {psnr:.{7}} | RMSE\": f\"{rmse:.{7}}\"})\n progress_bar.update(every_i)\n else:\n progress_bar.set_postfix({f\"Time-Step: {online_time_idx} | Frame {data['id']} | PSNR: {psnr:.{7}} | RMSE\": f\"{rmse:.{7}}\"})\n progress_bar.update(every_i)\n \n if wandb_run is not None:\n wandb_run.log({f\"{stage} PSNR\": psnr, f\"{stage} RMSE\": rmse}, step=wandb_step)\n \n if wandb_save_qual and (i % qual_every_i == 0 or i == 1):\n # Silhouette Mask\n presence_sil_mask = presence_sil_mask.detach().cpu().numpy()\n\n # Log plot to wandb\n if not mapping:\n fig_title = f\"Time-Step: {iter_time_idx} | Iter: {i} | Frame: {data['id']}\"\n else:\n fig_title = f\"Time-Step: {online_time_idx} | Iter: {i} | Frame: {data['id']}\"\n plot_rgbd_silhouette(data['im'], data['depth'], im, rastered_depth, presence_sil_mask, diff_depth_rmse,\n psnr, rmse, fig_title, wandb_run=wandb_run, wandb_step=wandb_step, \n wandb_title=f\"{stage} Qual Viz\")" }, { "identifier": "eval", "path": "utils/gs_helpers.py", "snippet": "def eval(dataset, final_params, num_frames, eval_dir, sil_thres, mapping_iters, add_new_gaussians, wandb_run=None, wandb_save_qual=False):\n print(\"Evaluating Final Parameters ...\")\n psnr_list = []\n rmse_list = []\n lpips_list = []\n ssim_list = []\n plot_dir = os.path.join(eval_dir, \"plots\")\n os.makedirs(plot_dir, exist_ok=True)\n\n gt_w2c_list = []\n for time_idx in tqdm(range(num_frames)):\n # Get RGB-D Data & Camera Parameters\n color, depth, intrinsics, pose = dataset[time_idx]\n gt_w2c = torch.linalg.inv(pose)\n gt_w2c_list.append(gt_w2c)\n intrinsics = intrinsics[:3, :3]\n\n # Process RGB-D Data\n color = color.permute(2, 0, 1) / 255 # (H, W, C) -> (C, H, W)\n depth = depth.permute(2, 0, 1) # (H, W, C) -> (C, H, W)\n\n # Process Camera Parameters\n w2c = torch.linalg.inv(pose)\n if time_idx == 0:\n first_frame_w2c = w2c\n # Setup Camera\n cam = setup_camera(color.shape[2], color.shape[1], intrinsics.cpu().numpy(), w2c.detach().cpu().numpy())\n \n # Define current frame data\n curr_data = {'cam': cam, 'im': color, 'depth': depth, 'id': time_idx, 'intrinsics': intrinsics, 'w2c': w2c}\n\n # Initialize Render Variables\n rendervar = params2rendervar(final_params)\n depth_sil_rendervar = params2depthplussilhouette(final_params, w2c)\n\n # Render Depth & Silhouette\n depth_sil, _, _, = Renderer(raster_settings=curr_data['cam'])(**depth_sil_rendervar)\n rastered_depth = depth_sil[0, :, :].unsqueeze(0)\n valid_depth_mask = (curr_data['depth'] > 0)\n silhouette = depth_sil[1, :, :]\n presence_sil_mask = (silhouette > sil_thres)\n \n # Render RGB and Calculate PSNR\n im, radius, _, = Renderer(raster_settings=curr_data['cam'])(**rendervar)\n if mapping_iters==0 and not add_new_gaussians:\n weighted_im = im * presence_sil_mask\n weighted_gt_im = curr_data['im'] * presence_sil_mask\n psnr = calc_psnr(weighted_im, weighted_gt_im).mean()\n ssim = ms_ssim(weighted_im.unsqueeze(0).cpu(), weighted_gt_im.unsqueeze(0).cpu(), \n data_range=1.0, size_average=True)\n lpips_score = loss_fn_alex(torch.clamp(weighted_im.unsqueeze(0), 0.0, 1.0),\n torch.clamp(weighted_gt_im.unsqueeze(0), 0.0, 1.0)).item()\n else:\n psnr = calc_psnr(im, curr_data['im']).mean()\n ssim = ms_ssim(im.unsqueeze(0).cpu(), curr_data['im'].unsqueeze(0).cpu(), \n data_range=1.0, size_average=True)\n lpips_score = loss_fn_alex(torch.clamp(im.unsqueeze(0), 0.0, 1.0),\n torch.clamp(curr_data['im'].unsqueeze(0), 0.0, 1.0)).item()\n\n psnr_list.append(psnr.cpu().numpy())\n ssim_list.append(ssim.cpu().numpy())\n lpips_list.append(lpips_score)\n\n # Compute Depth RMSE\n if mapping_iters==0 and not add_new_gaussians:\n diff_depth_rmse = torch.sqrt((((rastered_depth - curr_data['depth']) * presence_sil_mask) ** 2))\n diff_depth_rmse = diff_depth_rmse * valid_depth_mask\n rmse = diff_depth_rmse.sum() / valid_depth_mask.sum()\n else:\n diff_depth_rmse = torch.sqrt(((rastered_depth - curr_data['depth']) ** 2))\n diff_depth_rmse = diff_depth_rmse * valid_depth_mask\n rmse = diff_depth_rmse.sum() / valid_depth_mask.sum()\n rmse_list.append(rmse.cpu().numpy())\n\n # Plot the Ground Truth and Rasterized RGB & Depth, along with Silhouette\n fig_title = \"Time Step: {}\".format(time_idx)\n plot_name = \"%04d\" % time_idx\n presence_sil_mask = presence_sil_mask.detach().cpu().numpy()\n if wandb_run is None:\n plot_rgbd_silhouette(color, depth, im, rastered_depth, presence_sil_mask, diff_depth_rmse,\n psnr, rmse, fig_title, plot_dir, \n plot_name=plot_name, save_plot=True)\n elif wandb_save_qual:\n plot_rgbd_silhouette(color, depth, im, rastered_depth, presence_sil_mask, diff_depth_rmse,\n psnr, rmse, fig_title, plot_dir, \n plot_name=plot_name, save_plot=True,\n wandb_run=wandb_run, wandb_step=None, \n wandb_title=\"Eval Qual Viz\")\n\n # Compute Average Metrics\n psnr_list = np.array(psnr_list)\n rmse_list = np.array(rmse_list)\n ssim_list = np.array(ssim_list)\n lpips_list = np.array(lpips_list)\n avg_psnr = psnr_list.mean()\n avg_rmse = rmse_list.mean()\n avg_ssim = ssim_list.mean()\n avg_lpips = lpips_list.mean()\n print(\"Average PSNR: {:.2f}\".format(avg_psnr))\n print(\"Average Depth RMSE: {:.2f}\".format(avg_rmse))\n print(\"Average MS-SSIM: {:.2f}\".format(avg_ssim))\n print(\"Average LPIPS: {:.2f}\".format(avg_lpips))\n\n if wandb_run is not None:\n wandb_run.log({\"Average PSNR\": avg_psnr, \"Average Depth RMSE\": avg_rmse, \"Average MS-SSIM\": avg_ssim, \"Average LPIPS\": avg_lpips})\n\n # # Save metric lists as text files\n # np.savetxt(os.path.join(eval_dir, \"psnr.txt\"), psnr_list)\n # np.savetxt(os.path.join(eval_dir, \"rmse.txt\"), rmse_list)\n # np.savetxt(os.path.join(eval_dir, \"ssim.txt\"), ssim_list)\n # np.savetxt(os.path.join(eval_dir, \"lpips.txt\"), lpips_list)\n\n # # Plot PSNR & RMSE as line plots\n # fig, axs = plt.subplots(1, 2, figsize=(12, 4))\n # axs[0].plot(np.arange(num_frames), psnr_list)\n # axs[0].set_title(\"RGB PSNR\")\n # axs[0].set_xlabel(\"Time Step\")\n # axs[0].set_ylabel(\"PSNR\")\n # axs[1].plot(np.arange(num_frames), rmse_list)\n # axs[1].set_title(\"Depth RMSE\")\n # axs[1].set_xlabel(\"Time Step\")\n # axs[1].set_ylabel(\"RMSE\")\n # fig.suptitle(\"Average PSNR: {:.2f}, Average Depth RMSE: {:.2f}\".format(avg_psnr, avg_rmse), y=1.05, fontsize=16)\n # plt.savefig(os.path.join(eval_dir, \"metrics.png\"), bbox_inches='tight')\n # if wandb_run is not None:\n # wandb_run.log({\"Eval Metrics\": fig})\n # plt.close()" }, { "identifier": "l1_loss_v1", "path": "utils/gs_helpers.py", "snippet": "def l1_loss_v1(x, y):\n return torch.abs((x - y)).mean()" }, { "identifier": "matrix_to_quaternion", "path": "utils/gs_helpers.py", "snippet": "def matrix_to_quaternion(matrix: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert rotations given as rotation matrices to quaternions.\n\n Args:\n matrix: Rotation matrices as tensor of shape (..., 3, 3).\n\n Returns:\n quaternions with real part first, as tensor of shape (..., 4).\n Source: https://pytorch3d.readthedocs.io/en/latest/_modules/pytorch3d/transforms/rotation_conversions.html#matrix_to_quaternion\n \"\"\"\n if matrix.size(-1) != 3 or matrix.size(-2) != 3:\n raise ValueError(f\"Invalid rotation matrix shape {matrix.shape}.\")\n\n batch_dim = matrix.shape[:-2]\n m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.unbind(\n matrix.reshape(batch_dim + (9,)), dim=-1\n )\n\n q_abs = _sqrt_positive_part(\n torch.stack(\n [\n 1.0 + m00 + m11 + m22,\n 1.0 + m00 - m11 - m22,\n 1.0 - m00 + m11 - m22,\n 1.0 - m00 - m11 + m22,\n ],\n dim=-1,\n )\n )\n\n # we produce the desired quaternion multiplied by each of r, i, j, k\n quat_by_rijk = torch.stack(\n [\n # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and\n # `int`.\n torch.stack([q_abs[..., 0] ** 2, m21 - m12, m02 - m20, m10 - m01], dim=-1),\n # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and\n # `int`.\n torch.stack([m21 - m12, q_abs[..., 1] ** 2, m10 + m01, m02 + m20], dim=-1),\n # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and\n # `int`.\n torch.stack([m02 - m20, m10 + m01, q_abs[..., 2] ** 2, m12 + m21], dim=-1),\n # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and\n # `int`.\n torch.stack([m10 - m01, m20 + m02, m21 + m12, q_abs[..., 3] ** 2], dim=-1),\n ],\n dim=-2,\n )\n\n # We floor here at 0.1 but the exact level is not important; if q_abs is small,\n # the candidate won't be picked.\n flr = torch.tensor(0.1).to(dtype=q_abs.dtype, device=q_abs.device)\n quat_candidates = quat_by_rijk / (2.0 * q_abs[..., None].max(flr))\n\n # if not for numerical problems, quat_candidates[i] should be same (up to a sign),\n # forall i; we pick the best-conditioned one (with the largest denominator)\n\n return quat_candidates[\n F.one_hot(q_abs.argmax(dim=-1), num_classes=4) > 0.5, :\n ].reshape(batch_dim + (4,))" }, { "identifier": "calc_ssim", "path": "utils/gs_external.py", "snippet": "def calc_ssim(img1, img2, window_size=11, size_average=True):\n channel = img1.size(-3)\n window = create_window(window_size, channel)\n\n if img1.is_cuda:\n window = window.cuda(img1.get_device())\n window = window.type_as(img1)\n\n return _ssim(img1, img2, window, window_size, channel, size_average)" }, { "identifier": "build_rotation", "path": "utils/gs_external.py", "snippet": "def build_rotation(q):\n norm = torch.sqrt(q[:, 0] * q[:, 0] + q[:, 1] * q[:, 1] + q[:, 2] * q[:, 2] + q[:, 3] * q[:, 3])\n q = q / norm[:, None]\n rot = torch.zeros((q.size(0), 3, 3), device='cuda')\n r = q[:, 0]\n x = q[:, 1]\n y = q[:, 2]\n z = q[:, 3]\n rot[:, 0, 0] = 1 - 2 * (y * y + z * z)\n rot[:, 0, 1] = 2 * (x * y - r * z)\n rot[:, 0, 2] = 2 * (x * z + r * y)\n rot[:, 1, 0] = 2 * (x * y + r * z)\n rot[:, 1, 1] = 1 - 2 * (x * x + z * z)\n rot[:, 1, 2] = 2 * (y * z - r * x)\n rot[:, 2, 0] = 2 * (x * z - r * y)\n rot[:, 2, 1] = 2 * (y * z + r * x)\n rot[:, 2, 2] = 1 - 2 * (x * x + y * y)\n return rot" }, { "identifier": "densify", "path": "utils/gs_external.py", "snippet": "def densify(params, variables, optimizer, iter, densify_dict):\n if iter <= densify_dict['stop_after']:\n variables = accumulate_mean2d_gradient(variables)\n grad_thresh = densify_dict['grad_thresh']\n if (iter >= densify_dict['start_after']) and (iter % densify_dict['densify_every'] == 0):\n grads = variables['means2D_gradient_accum'] / variables['denom']\n grads[grads.isnan()] = 0.0\n to_clone = torch.logical_and(grads >= grad_thresh, (\n torch.max(torch.exp(params['log_scales']), dim=1).values <= 0.01 * variables['scene_radius']))\n new_params = {k: v[to_clone] for k, v in params.items() if k not in ['cam_unnorm_rots', 'cam_trans']}\n\n new_timestep_vars = torch.zeros(new_params['means3D'].shape[0], device=\"cuda\")\n new_timestep_vars = variables['timestep'][to_clone] \n variables['timestep'] = torch.cat((variables['timestep'], new_timestep_vars), dim=0)\n params = cat_params_to_optimizer(new_params, params, optimizer)\n num_pts = params['means3D'].shape[0]\n\n padded_grad = torch.zeros(num_pts, device=\"cuda\")\n padded_grad[:grads.shape[0]] = grads\n to_split = torch.logical_and(padded_grad >= grad_thresh,\n torch.max(torch.exp(params['log_scales']), dim=1).values > 0.01 * variables[\n 'scene_radius'])\n n = densify_dict['num_to_split_into'] # number to split into\n new_params = {k: v[to_split].repeat(n, 1) for k, v in params.items() if k not in ['cam_unnorm_rots', 'cam_trans']}\n #track new variables for new formed points\n new_timestep_vars = torch.zeros(new_params['means3D'].shape[0], device=\"cuda\")\n new_timestep_vars = variables['timestep'][to_split].repeat(n)\n variables['timestep'] = torch.cat((variables['timestep'], new_timestep_vars), dim=0)\n\n stds = torch.exp(params['log_scales'])[to_split].repeat(n, 3)\n means = torch.zeros((stds.size(0), 3), device=\"cuda\")\n samples = torch.normal(mean=means, std=stds)\n rots = build_rotation(params['unnorm_rotations'][to_split]).repeat(n, 1, 1)\n new_params['means3D'] += torch.bmm(rots, samples.unsqueeze(-1)).squeeze(-1)\n new_params['log_scales'] = torch.log(torch.exp(new_params['log_scales']) / (0.8 * n))\n params = cat_params_to_optimizer(new_params, params, optimizer)\n num_pts = params['means3D'].shape[0]\n \n variables['means2D_gradient_accum'] = torch.zeros(num_pts, device=\"cuda\")\n variables['denom'] = torch.zeros(num_pts, device=\"cuda\")\n variables['max_2D_radius'] = torch.zeros(num_pts, device=\"cuda\")\n\n to_remove = torch.cat((to_split, torch.zeros(n * to_split.sum(), dtype=torch.bool, device=\"cuda\")))\n params, variables = remove_points(to_remove, params, variables, optimizer)\n\n if iter == densify_dict['stop_after']:\n remove_threshold = densify_dict['final_removal_opacity_threshold']\n else:\n remove_threshold = densify_dict['removal_opacity_threshold']\n to_remove = (torch.sigmoid(params['logit_opacities']) < remove_threshold).squeeze()\n if iter >= densify_dict['remove_big_after']:\n big_points_ws = torch.exp(params['log_scales']).max(dim=1).values > 0.1 * variables['scene_radius']\n to_remove = torch.logical_or(to_remove, big_points_ws)\n params, variables = remove_points(to_remove, params, variables, optimizer)\n\n torch.cuda.empty_cache()\n\n # Reset Opacities for all Gaussians (This is not desired for mapping on only current frame)\n if iter > 0 and iter % densify_dict['reset_opacities_every'] == 0 and densify_dict['reset_opacities']:\n new_params = {'logit_opacities': inverse_sigmoid(torch.ones_like(params['logit_opacities']) * 0.01)}\n params = update_params_and_optimizer(new_params, params, optimizer)\n\n return params, variables" }, { "identifier": "get_expon_lr_func", "path": "utils/gs_external.py", "snippet": "def get_expon_lr_func(\n lr_init, lr_final, lr_delay_steps=0, lr_delay_mult=1.0, max_steps=1000000\n):\n \"\"\"\n Copied from Plenoxels\n\n Continuous learning rate decay function. Adapted from JaxNeRF\n The returned rate is lr_init when step=0 and lr_final when step=max_steps, and\n is log-linearly interpolated elsewhere (equivalent to exponential decay).\n If lr_delay_steps>0 then the learning rate will be scaled by some smooth\n function of lr_delay_mult, such that the initial learning rate is\n lr_init*lr_delay_mult at the beginning of optimization but will be eased back\n to the normal learning rate when steps>lr_delay_steps.\n :param conf: config subtree 'lr' or similar\n :param max_steps: int, the number of steps during optimization.\n :return HoF which takes step as input\n \"\"\"\n\n def helper(step):\n if step < 0 or (lr_init == 0.0 and lr_final == 0.0):\n # Disable this parameter\n return 0.0\n if lr_delay_steps > 0:\n # A kind of reverse cosine decay.\n delay_rate = lr_delay_mult + (1 - lr_delay_mult) * np.sin(\n 0.5 * np.pi * np.clip(step / lr_delay_steps, 0, 1)\n )\n else:\n delay_rate = 1.0\n t = np.clip(step / max_steps, 0, 1)\n log_lerp = np.exp(np.log(lr_init) * (1 - t) + np.log(lr_final) * t)\n return delay_rate * log_lerp\n\n return helper" }, { "identifier": "update_learning_rate", "path": "utils/gs_external.py", "snippet": "def update_learning_rate(optimizer, means3D_scheduler, iteration):\n ''' Learning rate scheduling per step '''\n for param_group in optimizer.param_groups:\n if param_group[\"name\"] == \"means3D\":\n lr = means3D_scheduler(iteration)\n param_group['lr'] = lr\n return lr" } ]
import argparse import os import random import sys import shutil import cv2 import numpy as np import torch import wandb from importlib.machinery import SourceFileLoader from tqdm import tqdm from datasets.gradslam_datasets import ( load_dataset_config, ICLDataset, ReplicaDataset, AzureKinectDataset, ScannetDataset, Ai2thorDataset, Record3DDataset, RealsenseDataset, TUMDataset, ScannetPPDataset, NeRFCaptureDataset ) from utils.common_utils import seed_everything, save_seq_params, save_params, save_params_ckpt, save_seq_params_ckpt from utils.recon_helpers import setup_camera from utils.gs_helpers import ( params2rendervar, params2depthplussilhouette, transformed_params2depthplussilhouette, transform_to_frame, report_progress, eval, l1_loss_v1, matrix_to_quaternion ) from utils.gs_external import ( calc_ssim, build_rotation, densify, get_expon_lr_func, update_learning_rate ) from diff_gaussian_rasterization import GaussianRasterizer as Renderer
18,414
elif config_dict["dataset_name"].lower() in ["record3d"]: return Record3DDataset(config_dict, basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["realsense"]: return RealsenseDataset(config_dict, basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["tum"]: return TUMDataset(config_dict, basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["scannetpp"]: return ScannetPPDataset(basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["nerfcapture"]: return NeRFCaptureDataset(basedir, sequence, **kwargs) else: raise ValueError(f"Unknown dataset name {config_dict['dataset_name']}") def get_pointcloud(color, depth, intrinsics, w2c, transform_pts=True, mask=None, compute_mean_sq_dist=False, mean_sq_dist_method="projective"): width, height = color.shape[2], color.shape[1] CX = intrinsics[0][2] CY = intrinsics[1][2] FX = intrinsics[0][0] FY = intrinsics[1][1] # Compute indices of pixels x_grid, y_grid = torch.meshgrid(torch.arange(width).cuda().float(), torch.arange(height).cuda().float(), indexing='xy') xx = (x_grid - CX)/FX yy = (y_grid - CY)/FY xx = xx.reshape(-1) yy = yy.reshape(-1) depth_z = depth[0].reshape(-1) # Initialize point cloud pts_cam = torch.stack((xx * depth_z, yy * depth_z, depth_z), dim=-1) if transform_pts: pix_ones = torch.ones(height * width, 1).cuda().float() pts4 = torch.cat((pts_cam, pix_ones), dim=1) c2w = torch.inverse(w2c) pts = (c2w @ pts4.T).T[:, :3] else: pts = pts_cam # Compute mean squared distance for initializing the scale of the Gaussians if compute_mean_sq_dist: if mean_sq_dist_method == "projective": # Projective Geometry (this is fast, farther -> larger radius) scale_gaussian = depth_z / ((FX + FY)/2) mean3_sq_dist = scale_gaussian**2 else: raise ValueError(f"Unknown mean_sq_dist_method: {mean_sq_dist_method}") # Colorize point cloud cols = torch.permute(color, (1, 2, 0)).reshape(-1, 3) # (C, H, W) -> (H, W, C) -> (H * W, C) point_cld = torch.cat((pts, cols), -1) # Select points based on mask if mask is not None: point_cld = point_cld[mask] if compute_mean_sq_dist: mean3_sq_dist = mean3_sq_dist[mask] if compute_mean_sq_dist: return point_cld, mean3_sq_dist else: return point_cld def initialize_params(init_pt_cld, num_frames, mean3_sq_dist): num_pts = init_pt_cld.shape[0] means3D = init_pt_cld[:, :3] # [num_gaussians, 3] unnorm_rots = np.tile([1, 0, 0, 0], (num_pts, 1)) # [num_gaussians, 3] logit_opacities = torch.zeros((num_pts, 1), dtype=torch.float, device="cuda") params = { 'means3D': means3D, 'rgb_colors': init_pt_cld[:, 3:6], 'unnorm_rotations': unnorm_rots, 'logit_opacities': logit_opacities, 'log_scales': torch.tile(torch.log(torch.sqrt(mean3_sq_dist))[..., None], (1, 1)), } # Initialize a single gaussian trajectory to model the camera poses relative to the first frame cam_rots = np.tile([1, 0, 0, 0], (1, 1)) cam_rots = np.tile(cam_rots[:, :, None], (1, 1, num_frames)) params['cam_unnorm_rots'] = cam_rots params['cam_trans'] = np.zeros((1, 3, num_frames)) for k, v in params.items(): # Check if value is already a torch tensor if not isinstance(v, torch.Tensor): params[k] = torch.nn.Parameter(torch.tensor(v).cuda().float().contiguous().requires_grad_(True)) else: params[k] = torch.nn.Parameter(v.cuda().float().contiguous().requires_grad_(True)) variables = {'max_2D_radius': torch.zeros(params['means3D'].shape[0]).cuda().float(), 'means2D_gradient_accum': torch.zeros(params['means3D'].shape[0]).cuda().float(), 'denom': torch.zeros(params['means3D'].shape[0]).cuda().float()} return params, variables def initialize_optimizer(params, lrs_dict): lrs = lrs_dict param_groups = [{'params': [v], 'name': k, 'lr': lrs[k]} for k, v in params.items()] return torch.optim.Adam(param_groups, lr=0.0, eps=1e-15) def initialize_first_timestep_from_ckpt(ckpt_path,dataset, num_frames, lrs_dict, mean_sq_dist_method): # Get RGB-D Data & Camera Parameters color, depth, intrinsics, pose = dataset[0] # Process RGB-D Data color = color.permute(2, 0, 1) / 255 # (H, W, C) -> (C, H, W) depth = depth.permute(2, 0, 1) # (H, W, C) -> (C, H, W) # Process Camera Parameters intrinsics = intrinsics[:3, :3] w2c = torch.linalg.inv(pose) # Setup Camera
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, _BASE_DIR) print("System Paths:") for p in sys.path: print(p) def get_dataset(config_dict, basedir, sequence, **kwargs): if config_dict["dataset_name"].lower() in ["icl"]: return ICLDataset(config_dict, basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["replica"]: return ReplicaDataset(config_dict, basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["azure", "azurekinect"]: return AzureKinectDataset(config_dict, basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["scannet"]: return ScannetDataset(config_dict, basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["ai2thor"]: return Ai2thorDataset(config_dict, basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["record3d"]: return Record3DDataset(config_dict, basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["realsense"]: return RealsenseDataset(config_dict, basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["tum"]: return TUMDataset(config_dict, basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["scannetpp"]: return ScannetPPDataset(basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["nerfcapture"]: return NeRFCaptureDataset(basedir, sequence, **kwargs) else: raise ValueError(f"Unknown dataset name {config_dict['dataset_name']}") def get_pointcloud(color, depth, intrinsics, w2c, transform_pts=True, mask=None, compute_mean_sq_dist=False, mean_sq_dist_method="projective"): width, height = color.shape[2], color.shape[1] CX = intrinsics[0][2] CY = intrinsics[1][2] FX = intrinsics[0][0] FY = intrinsics[1][1] # Compute indices of pixels x_grid, y_grid = torch.meshgrid(torch.arange(width).cuda().float(), torch.arange(height).cuda().float(), indexing='xy') xx = (x_grid - CX)/FX yy = (y_grid - CY)/FY xx = xx.reshape(-1) yy = yy.reshape(-1) depth_z = depth[0].reshape(-1) # Initialize point cloud pts_cam = torch.stack((xx * depth_z, yy * depth_z, depth_z), dim=-1) if transform_pts: pix_ones = torch.ones(height * width, 1).cuda().float() pts4 = torch.cat((pts_cam, pix_ones), dim=1) c2w = torch.inverse(w2c) pts = (c2w @ pts4.T).T[:, :3] else: pts = pts_cam # Compute mean squared distance for initializing the scale of the Gaussians if compute_mean_sq_dist: if mean_sq_dist_method == "projective": # Projective Geometry (this is fast, farther -> larger radius) scale_gaussian = depth_z / ((FX + FY)/2) mean3_sq_dist = scale_gaussian**2 else: raise ValueError(f"Unknown mean_sq_dist_method: {mean_sq_dist_method}") # Colorize point cloud cols = torch.permute(color, (1, 2, 0)).reshape(-1, 3) # (C, H, W) -> (H, W, C) -> (H * W, C) point_cld = torch.cat((pts, cols), -1) # Select points based on mask if mask is not None: point_cld = point_cld[mask] if compute_mean_sq_dist: mean3_sq_dist = mean3_sq_dist[mask] if compute_mean_sq_dist: return point_cld, mean3_sq_dist else: return point_cld def initialize_params(init_pt_cld, num_frames, mean3_sq_dist): num_pts = init_pt_cld.shape[0] means3D = init_pt_cld[:, :3] # [num_gaussians, 3] unnorm_rots = np.tile([1, 0, 0, 0], (num_pts, 1)) # [num_gaussians, 3] logit_opacities = torch.zeros((num_pts, 1), dtype=torch.float, device="cuda") params = { 'means3D': means3D, 'rgb_colors': init_pt_cld[:, 3:6], 'unnorm_rotations': unnorm_rots, 'logit_opacities': logit_opacities, 'log_scales': torch.tile(torch.log(torch.sqrt(mean3_sq_dist))[..., None], (1, 1)), } # Initialize a single gaussian trajectory to model the camera poses relative to the first frame cam_rots = np.tile([1, 0, 0, 0], (1, 1)) cam_rots = np.tile(cam_rots[:, :, None], (1, 1, num_frames)) params['cam_unnorm_rots'] = cam_rots params['cam_trans'] = np.zeros((1, 3, num_frames)) for k, v in params.items(): # Check if value is already a torch tensor if not isinstance(v, torch.Tensor): params[k] = torch.nn.Parameter(torch.tensor(v).cuda().float().contiguous().requires_grad_(True)) else: params[k] = torch.nn.Parameter(v.cuda().float().contiguous().requires_grad_(True)) variables = {'max_2D_radius': torch.zeros(params['means3D'].shape[0]).cuda().float(), 'means2D_gradient_accum': torch.zeros(params['means3D'].shape[0]).cuda().float(), 'denom': torch.zeros(params['means3D'].shape[0]).cuda().float()} return params, variables def initialize_optimizer(params, lrs_dict): lrs = lrs_dict param_groups = [{'params': [v], 'name': k, 'lr': lrs[k]} for k, v in params.items()] return torch.optim.Adam(param_groups, lr=0.0, eps=1e-15) def initialize_first_timestep_from_ckpt(ckpt_path,dataset, num_frames, lrs_dict, mean_sq_dist_method): # Get RGB-D Data & Camera Parameters color, depth, intrinsics, pose = dataset[0] # Process RGB-D Data color = color.permute(2, 0, 1) / 255 # (H, W, C) -> (C, H, W) depth = depth.permute(2, 0, 1) # (H, W, C) -> (C, H, W) # Process Camera Parameters intrinsics = intrinsics[:3, :3] w2c = torch.linalg.inv(pose) # Setup Camera
cam = setup_camera(color.shape[2], color.shape[1], intrinsics.cpu().numpy(), w2c.detach().cpu().numpy())
16
2023-11-30 20:26:47+00:00
24k
zhyever/PatchFusion
zoedepth/trainers/zoedepth_custom_trainer.py
[ { "identifier": "SILogLoss", "path": "zoedepth/trainers/loss_sample.py", "snippet": "class SILogLoss(nn.Module):\n \"\"\"SILog loss (pixel-wise)\"\"\"\n def __init__(self, beta=0.15):\n super(SILogLoss, self).__init__()\n self.name = 'SILog'\n self.beta = beta\n\n def forward(self, input, target, mask=None):\n input = extract_key(input, KEY_OUTPUT)\n \n if mask is not None:\n input_filtered = input[mask]\n target_filtered = target[mask]\n\n with amp.autocast(enabled=False): # amp causes NaNs in this loss function\n alpha = 1e-7\n g = torch.log(input_filtered + alpha) - torch.log(target_filtered + alpha)\n Dg = torch.var(g) + self.beta * torch.pow(torch.mean(g), 2)\n loss = 10 * torch.sqrt(Dg)\n\n if torch.isnan(loss):\n print(\"Nan SILog loss\")\n print(\"input:\", input.shape)\n print(\"target:\", target.shape)\n print(\"G\", torch.sum(torch.isnan(g)))\n print(\"Input min max\", torch.min(input), torch.max(input))\n print(\"Target min max\", torch.min(target), torch.max(target))\n print(\"Dg\", torch.isnan(Dg))\n print(\"loss\", torch.isnan(loss))\n\n return loss" }, { "identifier": "DistributionLoss", "path": "zoedepth/trainers/loss_sample.py", "snippet": "class DistributionLoss(nn.Module):\n def __init__(self, max_depth):\n super(DistributionLoss, self).__init__()\n self.name = 'DistributionLoss'\n self.max_depth = max_depth\n\n def forward(self, input, target, mask=None, dist='biLaplacian'):\n \n \n mu0 = input['mu0']\n mu1 = input['mu1']\n sigma0 = input['sigma0']\n sigma1 = input['sigma1']\n pi0 = input['pi0']\n pi1 = input['pi1']\n \n pred_mask = (pi0 / sigma0 > pi1 / sigma1).float()\n pred_depth = (mu0 * pred_mask + mu1 * (1. - pred_mask))\n pred_metric_depth = (1 - pred_depth) * self.max_depth\n\n\n if mask is not None:\n mu0 = mu0[mask]\n mu1 = mu1[mask]\n sigma0 = sigma0[mask]\n sigma1 = sigma1[mask]\n pi0 = pi0[mask]\n pi1 = pi1[mask]\n\n # real_input = real_depth[mask]\n \n real_input = mu0\n pred_metric_depth = pred_metric_depth[mask]\n record_target = target[mask]\n\n\n target_filtered = 1 - target[mask] / self.max_depth\n bi_loss = bimodal_loss(mu0, mu1, sigma0, sigma1, pi0, pi1, target_filtered, dist=dist).mean()\n # print(bi_loss) \n\n alpha = 1e-7\n beta = 0.15\n g = torch.log(real_input + alpha) - torch.log(record_target + alpha)\n Dg = torch.var(g) + beta * torch.pow(torch.mean(g), 2)\n sig_loss = 10 * torch.sqrt(Dg)\n # print(sig_loss)\n \n return bi_loss, sig_loss" }, { "identifier": "SILogLoss", "path": "zoedepth/trainers/loss.py", "snippet": "class SILogLoss(nn.Module):\n \"\"\"SILog loss (pixel-wise)\"\"\"\n def __init__(self, beta=0.15):\n super(SILogLoss, self).__init__()\n self.name = 'SILog'\n self.beta = beta\n\n def forward(self, input, target, mask=None, interpolate=True, return_interpolated=False):\n hack_input = input\n\n input = extract_key(input, KEY_OUTPUT)\n if input.shape[-1] != target.shape[-1] and interpolate:\n input = nn.functional.interpolate(\n input, target.shape[-2:], mode='bilinear', align_corners=True)\n intr_input = input\n else:\n intr_input = input\n\n if target.ndim == 3:\n target = target.unsqueeze(1)\n\n if mask is not None:\n if mask.ndim == 3:\n mask = mask.unsqueeze(1)\n\n input = input[mask]\n target = target[mask]\n\n with amp.autocast(enabled=False): # amp causes NaNs in this loss function\n alpha = 1e-7\n g = torch.log(input + alpha) - torch.log(target + alpha)\n\n # n, c, h, w = g.shape\n # norm = 1/(h*w)\n # Dg = norm * torch.sum(g**2) - (0.85/(norm**2)) * (torch.sum(g))**2\n\n Dg = torch.var(g) + self.beta * torch.pow(torch.mean(g), 2)\n\n loss = 10 * torch.sqrt(Dg)\n\n if torch.isnan(loss):\n if input.numel() == 0:\n loss = torch.mean(hack_input) * 0\n if not return_interpolated:\n return loss\n return loss, intr_input\n \n print(\"Nan SILog loss\")\n print(\"input:\", input.shape)\n print(\"target:\", target.shape)\n print(\"G\", torch.sum(torch.isnan(g)))\n print(\"Input min max\", torch.min(input), torch.max(input))\n print(\"Target min max\", torch.min(target), torch.max(target))\n print(\"Dg\", torch.isnan(Dg))\n print(\"loss\", torch.isnan(loss))\n\n if not return_interpolated:\n return loss\n\n return loss, intr_input" }, { "identifier": "BudgetConstraint", "path": "zoedepth/trainers/loss.py", "snippet": "class BudgetConstraint(nn.Module):\n \"\"\"\n Given budget constraint to reduce expected inference FLOPs in the Dynamic Network.\n \"\"\"\n def __init__(self, loss_mu, flops_all, warm_up=True):\n super().__init__()\n self.loss_mu = loss_mu\n self.flops_all = flops_all\n self.warm_up = warm_up\n\n def forward(self, flops_expt, warm_up_rate=1.0):\n if self.warm_up:\n warm_up_rate = min(1.0, warm_up_rate)\n else:\n warm_up_rate = 1.0\n losses = warm_up_rate * ((flops_expt / self.flops_all - self.loss_mu)**2)\n return losses" }, { "identifier": "HistogramMatchingLoss", "path": "zoedepth/trainers/loss.py", "snippet": "class HistogramMatchingLoss(nn.Module):\n def __init__(self, min_depth, max_depth, bins=512):\n super(HistogramMatchingLoss, self).__init__()\n self.name = 'HistogramMatchingLoss'\n self.min_depth = min_depth\n self.max_depth = max_depth\n self.bins = bins\n\n def forward(self, input, target, mask, interpolate=True):\n if input.shape[-1] != mask.shape[-1] and interpolate:\n input = nn.functional.interpolate(\n input, mask.shape[-2:], mode='bilinear', align_corners=True)\n \n if target.shape[-1] != mask.shape[-1] and interpolate:\n target = nn.functional.interpolate(\n target, mask.shape[-2:], mode='bilinear', align_corners=True)\n\n input[~mask] = 0\n target[~mask] = 0\n\n\n pred_hist = torch.histc(input, bins=self.bins, min=self.min_depth, max=self.max_depth)\n gt_hist = torch.histc(target, bins=self.bins, min=self.min_depth, max=self.max_depth)\n\n pred_hist /= pred_hist.sum(dim=0, keepdim=True)\n gt_hist /= gt_hist.sum(dim=0, keepdim=True)\n\n # print(pred_hist.shape)\n # print(pred_hist)\n # _pred_hist = pred_hist.detach().cpu().numpy()\n # _gt_hist = gt_hist.detach().cpu().numpy()\n # plt.subplot(2, 1, 1)\n # plt.bar(range(len(_pred_hist)), _pred_hist)\n # plt.subplot(2, 1, 2)\n # plt.bar(range(len(_gt_hist)), _gt_hist)\n # plt.savefig('./debug_scale.png')\n\n # Compute cumulative histograms (CDF)\n cdf_pred = torch.cumsum(pred_hist, dim=0)\n cdf_gt = torch.cumsum(gt_hist, dim=0)\n\n # Compute Earth Mover's Distance (EMD) between the CDFs\n loss = torch.mean(torch.abs(cdf_pred - cdf_gt))\n # loss = torch.mean(torch.sqrt((pred_hist - gt_hist)**2))\n # loss = F.kl_div(torch.log(pred_hist + 1e-10), gt_hist, reduction='mean')\n \n return loss" }, { "identifier": "SSIM", "path": "zoedepth/trainers/loss.py", "snippet": "class SSIM(torch.nn.Module):\n def __init__(self, window_size = 11, size_average = True):\n super(SSIM, self).__init__()\n self.window_size = window_size\n self.size_average = size_average\n self.channel = 1\n self.window = create_window(window_size, self.channel)\n\n def forward(self, img1, img2, mask, interpolate=True):\n if img1.shape[-1] != mask.shape[-1] and interpolate:\n img1 = nn.functional.interpolate(\n img1, mask.shape[-2:], mode='bilinear', align_corners=True)\n \n if img2.shape[-1] != mask.shape[-1] and interpolate:\n img2 = nn.functional.interpolate(\n img2, mask.shape[-2:], mode='bilinear', align_corners=True)\n\n img1[~mask] = 0\n img2[~mask] = 0\n\n (_, channel, _, _) = img1.size()\n\n if channel == self.channel and self.window.data.type() == img1.data.type():\n window = self.window\n else:\n window = create_window(self.window_size, channel)\n \n if img1.is_cuda:\n window = window.cuda(img1.get_device())\n window = window.type_as(img1)\n \n self.window = window\n self.channel = channel\n\n\n loss = _ssim(img1, img2, window, self.window_size, channel, self.size_average)\n return loss" }, { "identifier": "ConsistencyLoss", "path": "zoedepth/trainers/loss.py", "snippet": "class ConsistencyLoss(nn.Module):\n def __init__(self, target, focus_flatten=False, wp=1) -> None:\n super().__init__()\n self.name = 'Consistency'\n self.target = target\n self.mode = 'no-resize'\n # self.mode = 'resize'\n self.focus_flatten = focus_flatten\n self.wp = wp\n\n def gradient_y(self, img):\n # gy = torch.cat([F.conv2d(img[:, i, :, :].unsqueeze(0), torch.Tensor([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]).view((1, 1, 3, 3)).to(img.device), padding=1) for i in range(img.shape[1])], 1)\n gy = F.conv2d(img, torch.Tensor([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]).view((1, 1, 3, 3)).to(img.device), padding=1)\n return gy\n\n def gradient_x(self, img):\n # gx = torch.cat([F.conv2d(img[:, i, :, :].unsqueeze(0), torch.Tensor([[1, 0, -1], [2, 0, -2], [1, 0, -1]]).view((1, 1, 3, 3)).to(img.device), padding=1) for i in range(img.shape[1])], 1)\n gx = F.conv2d(img, torch.Tensor([[1, 0, -1], [2, 0, -2], [1, 0, -1]]).view((1, 1, 3, 3)).to(img.device), padding=1)\n return gx\n\n def forward(self, depth_preds, shifts, mask, temp_features, pred_f=None):\n\n common_area_1_list = []\n common_area_2_list = []\n\n if self.focus_flatten:\n # only consider flatten place\n grad = kornia.filters.spatial_gradient(pred_f.detach())\n grad_x, grad_y = grad[:, :, 0, :, :], grad[:, :, 1, :, :]\n grad = torch.sqrt(grad_x ** 2 + grad_y ** 2)\n grad_ext = grad > 0.05 # over 5cm\n grad_ext = grad_ext.float()\n grad_blur = kornia.filters.gaussian_blur2d(grad_ext, (11, 11), (3, 3))\n grad_ext = grad_blur > 0 # over 5cm\n grad_ext = grad_blur == 0 \n mask = torch.logical_and(mask, grad_ext)\n\n\n if self.target == \"mix\":\n ## for feature\n bs, c, h, w = depth_preds.shape\n split_depth = torch.split(depth_preds, bs//2, dim=0)\n split_mask = torch.split(F.interpolate(mask.float(), (384, 512)).bool(), bs//2, dim=0)\n\n feat_ori_list = []\n feat_shift_list = []\n multi_level_mask = []\n\n for idx, feature in enumerate(temp_features): # multi-level\n split_feat = torch.split(feature, bs//2, dim=0)\n\n _, _, h, w = split_feat[0].shape\n feat_ori_list.append(split_feat[0])\n feat_shift_list.append(split_feat[1])\n\n mask_ori_cur_scale = F.interpolate(split_mask[0].float(), (h, w)).bool()\n multi_level_mask.append(mask_ori_cur_scale)\n\n for idx_out, (feat_ori_cur_level, feat_shift_cur_level, mask_ori_cur_level) in enumerate(zip(feat_ori_list, feat_shift_list, multi_level_mask)): # iter multi-scale\n scale_factor = 2 ** (5 - idx_out)\n _, _, cur_scale_h, cur_scale_w = feat_ori_cur_level.shape\n scale_factor = int(384 / cur_scale_h)\n\n for idx_in, (feat_ori, feat_shift, mask_ori, shift_bs) in enumerate(zip(feat_ori_cur_level, feat_shift_cur_level, mask_ori_cur_level, shifts)): # iter bs (paired feat)\n c, _, _ = feat_ori.shape\n mask_ori = mask_ori.repeat(c, 1, 1)\n shift_h, shift_w = int(shift_bs[0] * (384/540) / scale_factor), int(shift_bs[1]* (512/960) / scale_factor)\n\n if shift_h >= 0 and shift_w >= 0:\n common_area_1 = feat_ori[:, shift_h:, shift_w:]\n common_area_2 = feat_shift[:, :-shift_h, :-shift_w]\n mask_common = mask_ori[:, shift_h:, shift_w:] \n elif shift_h >= 0 and shift_w <= 0:\n common_area_1 = feat_ori[:, shift_h:, :-abs(shift_w)]\n common_area_2 = feat_shift[:, :-shift_h, abs(shift_w):]\n mask_common = mask_ori[:, shift_h:, :-abs(shift_w)]\n elif shift_h <= 0 and shift_w <= 0:\n common_area_1 = feat_ori[:, :-abs(shift_h), :-abs(shift_w)]\n common_area_2 = feat_shift[:, abs(shift_h):, abs(shift_w):]\n mask_common = mask_ori[:, :-abs(shift_h), :-abs(shift_w)]\n elif shift_h <= 0 and shift_w >= 0:\n common_area_1 = feat_ori[:, :-abs(shift_h):, shift_w:]\n common_area_2 = feat_shift[:, abs(shift_h):, :-shift_w]\n mask_common = mask_ori[:, :-abs(shift_h):, shift_w:]\n else:\n print(\"can you really reach here?\")\n\n common_area_masked_1 = common_area_1[mask_common].flatten()\n common_area_masked_2 = common_area_2[mask_common].flatten()\n common_area_1_list.append(common_area_masked_1)\n common_area_2_list.append(common_area_masked_2)\n\n common_area_1 = torch.cat(common_area_1_list)\n common_area_2 = torch.cat(common_area_2_list)\n if common_area_1.numel() == 0 or common_area_2.numel() == 0:\n consistency_loss = torch.Tensor([0]).squeeze()\n else:\n consistency_loss = F.mse_loss(common_area_1, common_area_2)\n consistency_loss_feat = consistency_loss\n\n \n common_area_1_list = []\n common_area_2_list = []\n\n ## for pred\n bs, c, h, w = depth_preds.shape\n split_depth = torch.split(depth_preds, bs//2, dim=0)\n split_mask = torch.split(mask, bs//2, dim=0)\n \n for shift, depth_ori, depth_shift, mask_ori, mask_shift in zip(shifts, split_depth[0], split_depth[1], split_mask[0], split_mask[1]):\n shift_h, shift_w = shift[0], shift[1]\n if shift_h >= 0 and shift_w >= 0:\n common_area_1 = depth_ori[:, shift_h:, shift_w:]\n common_area_2 = depth_shift[:, :-shift_h, :-shift_w]\n mask_common = mask_ori[:, shift_h:, shift_w:]\n # mask_debug = mask_shift[:, :-shift_h, :-shift_w]\n elif shift_h >= 0 and shift_w <= 0:\n common_area_1 = depth_ori[:, shift_h:, :-abs(shift_w)]\n common_area_2 = depth_shift[:, :-shift_h, abs(shift_w):]\n mask_common = mask_ori[:, shift_h:, :-abs(shift_w)]\n # mask_debug = mask_shift[:, :-shift_h, abs(shift_w):]\n elif shift_h <= 0 and shift_w <= 0:\n common_area_1 = depth_ori[:, :-abs(shift_h), :-abs(shift_w)]\n common_area_2 = depth_shift[:, abs(shift_h):, abs(shift_w):]\n mask_common = mask_ori[:, :-abs(shift_h), :-abs(shift_w)]\n # mask_debug = mask_shift[:, abs(shift_h):, abs(shift_w):]\n elif shift_h <= 0 and shift_w >= 0:\n common_area_1 = depth_ori[:, :-abs(shift_h):, shift_w:]\n common_area_2 = depth_shift[:, abs(shift_h):, :-shift_w]\n mask_common = mask_ori[:, :-abs(shift_h):, shift_w:]\n # mask_debug = mask_shift[:, abs(shift_h):, :-shift_w]\n else:\n print(\"can you really reach here?\")\n \n common_area_1 = common_area_1[mask_common].flatten()\n common_area_2 = common_area_2[mask_common].flatten()\n common_area_1_list.append(common_area_1)\n common_area_2_list.append(common_area_2)\n\n common_area_1 = torch.cat(common_area_1_list)\n common_area_2 = torch.cat(common_area_2_list)\n if common_area_1.numel() == 0 or common_area_2.numel() == 0:\n consistency_loss = torch.Tensor([0]).squeeze()\n else:\n # pred_hist = torch.histc(common_area_1, bins=512, min=0, max=80)\n # gt_hist = torch.histc(common_area_2, bins=512, min=0, max=80)\n\n # pred_hist /= pred_hist.sum(dim=0, keepdim=True)\n # gt_hist /= gt_hist.sum(dim=0, keepdim=True)\n\n # # Compute cumulative histograms (CDF)\n # cdf_pred = torch.cumsum(pred_hist, dim=0)\n # cdf_gt = torch.cumsum(gt_hist, dim=0)\n\n # # Compute Earth Mover's Distance (EMD) between the CDFs\n # consistency_loss = torch.mean(torch.abs(cdf_pred - cdf_gt))\n consistency_loss = F.mse_loss(common_area_1, common_area_2) \n consistency_loss_pred = consistency_loss\n\n consistency_loss = consistency_loss_pred * self.wp + consistency_loss_feat\n return consistency_loss\n \n elif 'feat' in self.target:\n if self.mode == 'resize':\n bs, c, h, w = depth_preds.shape\n split_depth = torch.split(depth_preds, bs//2, dim=0)\n split_mask = torch.split(mask, bs//2, dim=0)\n \n feat_ori_list = []\n feat_shift_list = []\n\n for idx, feature in enumerate(temp_features): # multi-level\n if idx < 4:\n continue\n \n split_feat = torch.split(feature, bs//2, dim=0)\n f = F.interpolate(split_feat[0], (h, w), mode='bilinear', align_corners=True)\n feat_ori_list.append(f)\n f = F.interpolate(split_feat[1], (h, w), mode='bilinear', align_corners=True)\n feat_shift_list.append(f)\n\n\n for idx_out, (feat_ori_cur_level, feat_shift_cur_level) in enumerate(zip(feat_ori_list, feat_shift_list)): # iter multi-scale\n scale_factor = 2 ** (5 - idx_out)\n\n for idx_in, (feat_ori, feat_shift, mask_ori, shift_bs) in enumerate(zip(feat_ori_cur_level, feat_shift_cur_level, split_mask[0], shifts)): # iter bs (paired feat)\n c, h, w = feat_ori.shape\n mask_ori = mask_ori.repeat(c, 1, 1)\n shift_h, shift_w = shift_bs[0], shift_bs[1]\n\n if shift_h >= 0 and shift_w >= 0:\n common_area_1 = feat_ori[:, shift_h:, shift_w:]\n common_area_2 = feat_shift[:, :-shift_h, :-shift_w]\n mask_common = mask_ori[:, shift_h:, shift_w:] \n elif shift_h >= 0 and shift_w <= 0:\n common_area_1 = feat_ori[:, shift_h:, :-abs(shift_w)]\n common_area_2 = feat_shift[:, :-shift_h, abs(shift_w):]\n mask_common = mask_ori[:, shift_h:, :-abs(shift_w)]\n elif shift_h <= 0 and shift_w <= 0:\n common_area_1 = feat_ori[:, :-abs(shift_h), :-abs(shift_w)]\n common_area_2 = feat_shift[:, abs(shift_h):, abs(shift_w):]\n mask_common = mask_ori[:, :-abs(shift_h), :-abs(shift_w)]\n elif shift_h <= 0 and shift_w >= 0:\n common_area_1 = feat_ori[:, :-abs(shift_h):, shift_w:]\n common_area_2 = feat_shift[:, abs(shift_h):, :-shift_w]\n mask_common = mask_ori[:, :-abs(shift_h):, shift_w:]\n else:\n print(\"can you really reach here?\")\n\n common_area_masked_1 = common_area_1[mask_common].flatten()\n common_area_masked_2 = common_area_2[mask_common].flatten()\n # common_area_masked_1 = common_area_1.flatten()\n # common_area_masked_2 = common_area_2.flatten()\n common_area_1_list.append(common_area_masked_1)\n common_area_2_list.append(common_area_masked_2)\n\n common_area_1 = torch.cat(common_area_1_list)\n common_area_2 = torch.cat(common_area_2_list)\n if common_area_1.numel() == 0 or common_area_2.numel() == 0:\n consistency_loss = torch.Tensor([0]).squeeze()\n else:\n consistency_loss = F.mse_loss(common_area_1, common_area_2)\n\n return consistency_loss\n \n\n else:\n bs, c, h, w = depth_preds.shape\n split_depth = torch.split(depth_preds, bs//2, dim=0)\n mask = F.interpolate(mask.float(), (384, 512)).bool() # back to 384, 512\n split_mask = torch.split(mask, bs//2, dim=0)\n\n feat_ori_list = []\n feat_shift_list = []\n multi_level_mask = []\n\n for idx, feature in enumerate(temp_features): # multi-level\n split_feat = torch.split(feature, bs//2, dim=0)\n\n _, _, h, w = split_feat[0].shape\n feat_ori_list.append(split_feat[0])\n feat_shift_list.append(split_feat[1])\n\n mask_ori_cur_scale = F.interpolate(split_mask[0].float(), (h, w)).bool()\n multi_level_mask.append(mask_ori_cur_scale)\n\n for idx_out, (feat_ori_cur_level, feat_shift_cur_level, mask_ori_cur_level) in enumerate(zip(feat_ori_list, feat_shift_list, multi_level_mask)): # iter multi-scale\n scale_factor = 2 ** (5 - idx_out)\n _, _, cur_scale_h, cur_scale_w = feat_ori_cur_level.shape\n scale_factor = int(384 / cur_scale_h)\n\n for idx_in, (feat_ori, feat_shift, mask_ori, shift_bs) in enumerate(zip(feat_ori_cur_level, feat_shift_cur_level, mask_ori_cur_level, shifts)): # iter bs (paired feat)\n c, _, _ = feat_ori.shape\n mask_ori = mask_ori.repeat(c, 1, 1)\n shift_h, shift_w = int(shift_bs[0] * (384/540) / scale_factor), int(shift_bs[1]* (512/960) / scale_factor)\n\n if shift_h >= 0 and shift_w >= 0:\n common_area_1 = feat_ori[:, shift_h:, shift_w:]\n common_area_2 = feat_shift[:, :-shift_h, :-shift_w]\n mask_common = mask_ori[:, shift_h:, shift_w:] \n elif shift_h >= 0 and shift_w <= 0:\n common_area_1 = feat_ori[:, shift_h:, :-abs(shift_w)]\n common_area_2 = feat_shift[:, :-shift_h, abs(shift_w):]\n mask_common = mask_ori[:, shift_h:, :-abs(shift_w)]\n elif shift_h <= 0 and shift_w <= 0:\n common_area_1 = feat_ori[:, :-abs(shift_h), :-abs(shift_w)]\n common_area_2 = feat_shift[:, abs(shift_h):, abs(shift_w):]\n mask_common = mask_ori[:, :-abs(shift_h), :-abs(shift_w)]\n elif shift_h <= 0 and shift_w >= 0:\n common_area_1 = feat_ori[:, :-abs(shift_h):, shift_w:]\n common_area_2 = feat_shift[:, abs(shift_h):, :-shift_w]\n mask_common = mask_ori[:, :-abs(shift_h):, shift_w:]\n else:\n print(\"can you really reach here?\")\n\n common_area_masked_1 = common_area_1[mask_common].flatten()\n common_area_masked_2 = common_area_2[mask_common].flatten()\n common_area_1_list.append(common_area_masked_1)\n common_area_2_list.append(common_area_masked_2)\n\n common_area_1 = torch.cat(common_area_1_list)\n common_area_2 = torch.cat(common_area_2_list)\n if common_area_1.numel() == 0 or common_area_2.numel() == 0:\n consistency_loss = torch.Tensor([0]).squeeze()\n else:\n consistency_loss = F.mse_loss(common_area_1, common_area_2)\n return consistency_loss\n \n elif self.target == 'pred':\n bs, c, h, w = depth_preds.shape\n split_depth = torch.split(depth_preds, bs//2, dim=0)\n split_mask = torch.split(mask, bs//2, dim=0)\n \n for shift, depth_ori, depth_shift, mask_ori, mask_shift in zip(shifts, split_depth[0], split_depth[1], split_mask[0], split_mask[1]):\n shift_h, shift_w = shift[0], shift[1]\n if shift_h >= 0 and shift_w >= 0:\n common_area_1 = depth_ori[:, shift_h:, shift_w:]\n common_area_2 = depth_shift[:, :-shift_h, :-shift_w]\n mask_common = mask_ori[:, shift_h:, shift_w:]\n # mask_debug = mask_shift[:, :-shift_h, :-shift_w]\n elif shift_h >= 0 and shift_w <= 0:\n common_area_1 = depth_ori[:, shift_h:, :-abs(shift_w)]\n common_area_2 = depth_shift[:, :-shift_h, abs(shift_w):]\n mask_common = mask_ori[:, shift_h:, :-abs(shift_w)]\n # mask_debug = mask_shift[:, :-shift_h, abs(shift_w):]\n elif shift_h <= 0 and shift_w <= 0:\n common_area_1 = depth_ori[:, :-abs(shift_h), :-abs(shift_w)]\n common_area_2 = depth_shift[:, abs(shift_h):, abs(shift_w):]\n mask_common = mask_ori[:, :-abs(shift_h), :-abs(shift_w)]\n # mask_debug = mask_shift[:, abs(shift_h):, abs(shift_w):]\n elif shift_h <= 0 and shift_w >= 0:\n common_area_1 = depth_ori[:, :-abs(shift_h):, shift_w:]\n common_area_2 = depth_shift[:, abs(shift_h):, :-shift_w]\n mask_common = mask_ori[:, :-abs(shift_h):, shift_w:]\n # mask_debug = mask_shift[:, abs(shift_h):, :-shift_w]\n else:\n print(\"can you really reach here?\")\n \n common_area_1 = common_area_1[mask_common].flatten()\n common_area_2 = common_area_2[mask_common].flatten()\n common_area_1_list.append(common_area_1)\n common_area_2_list.append(common_area_2)\n\n common_area_1 = torch.cat(common_area_1_list)\n common_area_2 = torch.cat(common_area_2_list)\n if common_area_1.numel() == 0 or common_area_2.numel() == 0:\n consistency_loss = torch.Tensor([0]).squeeze()\n else:\n # pred_hist = torch.histc(common_area_1, bins=512, min=0, max=80)\n # gt_hist = torch.histc(common_area_2, bins=512, min=0, max=80)\n\n # pred_hist /= pred_hist.sum(dim=0, keepdim=True)\n # gt_hist /= gt_hist.sum(dim=0, keepdim=True)\n\n # # Compute cumulative histograms (CDF)\n # cdf_pred = torch.cumsum(pred_hist, dim=0)\n # cdf_gt = torch.cumsum(gt_hist, dim=0)\n\n # # Compute Earth Mover's Distance (EMD) between the CDFs\n # consistency_loss = torch.mean(torch.abs(cdf_pred - cdf_gt))\n consistency_loss = F.mse_loss(common_area_1, common_area_2)\n \n return consistency_loss\n \n else:\n raise NotImplementedError" }, { "identifier": "DATASETS_CONFIG", "path": "zoedepth/utils/config.py", "snippet": "DATASETS_CONFIG = {\n \"kitti\": {\n \"dataset\": \"kitti\",\n \"min_depth\": 0.001,\n \"max_depth\": 80,\n \"data_path\": os.path.join(HOME_DIR, \"shortcuts/datasets/kitti/raw\"),\n \"gt_path\": os.path.join(HOME_DIR, \"shortcuts/datasets/kitti/gts\"),\n \"filenames_file\": \"./train_test_inputs/kitti_eigen_train_files_with_gt.txt\",\n \"input_height\": 352,\n \"input_width\": 1216, # 704\n \"data_path_eval\": os.path.join(HOME_DIR, \"shortcuts/datasets/kitti/raw\"),\n \"gt_path_eval\": os.path.join(HOME_DIR, \"shortcuts/datasets/kitti/gts\"),\n \"filenames_file_eval\": \"./train_test_inputs/kitti_eigen_test_files_with_gt.txt\",\n\n \"min_depth_eval\": 1e-3,\n \"max_depth_eval\": 80,\n\n \"do_random_rotate\": True,\n \"degree\": 1.0,\n \"do_kb_crop\": True,\n \"garg_crop\": True,\n \"eigen_crop\": False,\n \"use_right\": False\n },\n \"kitti_test\": {\n \"dataset\": \"kitti\",\n \"min_depth\": 0.001,\n \"max_depth\": 80,\n \"data_path\": os.path.join(HOME_DIR, \"shortcuts/datasets/kitti/raw\"),\n \"gt_path\": os.path.join(HOME_DIR, \"shortcuts/datasets/kitti/gts\"),\n \"filenames_file\": \"./train_test_inputs/kitti_eigen_train_files_with_gt.txt\",\n \"input_height\": 352,\n \"input_width\": 1216,\n \"data_path_eval\": os.path.join(HOME_DIR, \"shortcuts/datasets/kitti/raw\"),\n \"gt_path_eval\": os.path.join(HOME_DIR, \"shortcuts/datasets/kitti/gts\"),\n \"filenames_file_eval\": \"./train_test_inputs/kitti_eigen_test_files_with_gt.txt\",\n\n \"min_depth_eval\": 1e-3,\n \"max_depth_eval\": 80,\n\n \"do_random_rotate\": False,\n \"degree\": 1.0,\n \"do_kb_crop\": True,\n \"garg_crop\": True,\n \"eigen_crop\": False,\n \"use_right\": False\n },\n \"nyu\": {\n \"dataset\": \"nyu\",\n \"avoid_boundary\": False,\n \"min_depth\": 1e-3, # originally 0.1\n \"max_depth\": 10,\n \"data_path\": os.path.join(\"/ibex/ai/home/liz0l/codes/datasets/nyu/data_folder\"),\n \"gt_path\": os.path.join(\"/ibex/ai/home/liz0l/codes/datasets/nyu/data_folder\"),\n \"filenames_file\": \"/ibex/ai/home/liz0l/codes/datasets/nyu/data_folder/nyu_train.txt\",\n \"input_height\": 480,\n \"input_width\": 640,\n \"data_path_eval\": os.path.join(\"/ibex/ai/home/liz0l/codes/datasets/nyu/data_folder\"),\n \"gt_path_eval\": os.path.join(\"/ibex/ai/home/liz0l/codes/datasets/nyu/data_folder\"),\n \"filenames_file_eval\": \"/ibex/ai/home/liz0l/codes/datasets/nyu/data_folder/nyu_test.txt\",\n \"min_depth_eval\": 1e-3,\n \"max_depth_eval\": 10,\n \"min_depth_diff\": -10,\n \"max_depth_diff\": 10,\n\n \"do_random_rotate\": True,\n \"degree\": 1.0,\n \"do_kb_crop\": False,\n \"garg_crop\": False,\n \"eigen_crop\": False,\n },\n \"u4k\": {\n \"dataset\": \"u4k\",\n \"min_depth\": 1e-3, # originally 0.1\n \"max_depth\": 80,\n \"data_path\": os.path.join(\"/ibex/ai/home/liz0l/codes/datasets/u4k\"),\n \"filenames_train\": \"/ibex/ai/home/liz0l/codes/datasets/u4k/splits/train.txt\",\n \"input_height\": 480, # ? will not be used (random crop)\n \"input_width\": 640, # ? will not be used (random crop)\n \"filenames_val\": \"/ibex/ai/home/liz0l/codes/datasets/u4k/splits/val.txt\",\n # \"filenames_val\": \"/ibex/ai/home/liz0l/codes/datasets/u4k/splits/test.txt\",\n \"filenames_test\": \"/ibex/ai/home/liz0l/codes/datasets/u4k/splits/test.txt\",\n \"min_depth_eval\": 1e-3,\n \"max_depth_eval\": 80,\n \"min_depth_diff\": -10,\n \"max_depth_diff\": 10,\n\n \"do_random_rotate\": True,\n \"degree\": 1.0,\n \"do_kb_crop\": False,\n \"garg_crop\": False,\n \"eigen_crop\": False,\n \n \"num_sample_inout\": 50000,\n # \"num_sample_inout\": 40000,\n \"sampling_strategy\": 'random',\n # \"sampling_strategy\": 'dda',\n \"dilation_factor\": 10,\n\n \"use_rgb\": False,\n \"do_normalize\": True, # do normalize in dataloader\n \"do_input_resize\": True\n },\n \"mid\": {\n \"dataset\": \"mid\",\n \"min_depth\": 1e-3, # originally 0.1\n \"max_depth\": 10,\n \"data_path\": os.path.join(\"/ibex/ai/home/liz0l/codes/datasets/middlebury\"),\n \"filenames_train\": \"/ibex/ai/home/liz0l/codes/datasets/middlebury/splits/train.txt\",\n \"input_height\": 480, # ? will not be used (random crop)\n \"input_width\": 640, # ? will not be used (random crop)\n \"filenames_val\": \"/ibex/ai/home/liz0l/codes/datasets/middlebury/splits/val.txt\",\n \"filenames_test\": \"/ibex/ai/home/liz0l/codes/datasets/middlebury/splits/test.txt\",\n \"min_depth_eval\": 1e-3,\n \"max_depth_eval\": 10,\n \"min_depth_diff\": -10,\n \"max_depth_diff\": 10,\n\n \"do_random_rotate\": True,\n \"degree\": 1.0,\n \"do_kb_crop\": False,\n \"garg_crop\": False,\n \"eigen_crop\": False,\n \n \"num_sample_inout\": 50000,\n # \"num_sample_inout\": 40000,\n \"sampling_strategy\": 'random',\n # \"sampling_strategy\": 'dda',\n \"dilation_factor\": 10,\n\n \"use_rgb\": False,\n \"do_normalize\": True, # do normalize in dataloader\n \"do_input_resize\": True\n },\n \"gta\": {\n \"dataset\": \"gta\",\n \"min_depth\": 1e-3, # originally 0.1\n \"max_depth\": 80,\n \"data_path\": os.path.join(\"/ibex/ai/home/liz0l/codes/datasets/gta/GTAV_1080\"),\n \"filenames_train\": \"/ibex/ai/home/liz0l/codes/datasets/gta/GTAV_1080/train.txt\",\n \"input_height\": 480, # ? will not be used (random crop)\n \"input_width\": 640, # ? will not be used (random crop)\n \"filenames_val\": \"/ibex/ai/home/liz0l/codes/datasets/gta/GTAV_1080/val.txt\",\n # \"filenames_val\": \"/ibex/ai/home/liz0l/codes/datasets/u4k/splits/test.txt\",\n \"filenames_test\": \"/ibex/ai/home/liz0l/codes/datasets/gta/GTAV_1080/test.txt\",\n \"min_depth_eval\": 1e-3,\n \"max_depth_eval\": 80,\n \"min_depth_diff\": -10,\n \"max_depth_diff\": 10,\n\n \"do_random_rotate\": True,\n \"degree\": 1.0,\n \"do_kb_crop\": False,\n \"garg_crop\": False,\n \"eigen_crop\": False,\n \n \"num_sample_inout\": 50000,\n # \"num_sample_inout\": 40000,\n \"sampling_strategy\": 'random',\n # \"sampling_strategy\": 'dda',\n \"dilation_factor\": 10,\n\n \"use_rgb\": False,\n \"do_normalize\": True, # do normalize in dataloader\n \"do_input_resize\": True\n },\n \"ibims\": {\n \"dataset\": \"ibims\",\n \"ibims_root\": os.path.join(HOME_DIR, \"shortcuts/datasets/ibims/ibims1_core_raw/\"),\n \"eigen_crop\": True,\n \"garg_crop\": False,\n \"do_kb_crop\": False,\n \"min_depth_eval\": 0,\n \"max_depth_eval\": 10,\n \"min_depth\": 1e-3,\n \"max_depth\": 10\n },\n \"sunrgbd\": {\n \"dataset\": \"sunrgbd\",\n \"sunrgbd_root\": os.path.join(HOME_DIR, \"shortcuts/datasets/SUNRGBD/test/\"),\n \"eigen_crop\": True,\n \"garg_crop\": False,\n \"do_kb_crop\": False,\n \"min_depth_eval\": 0,\n \"max_depth_eval\": 8,\n \"min_depth\": 1e-3,\n \"max_depth\": 10\n },\n \"diml_indoor\": {\n \"dataset\": \"diml_indoor\",\n \"diml_indoor_root\": os.path.join(HOME_DIR, \"shortcuts/datasets/diml_indoor_test/\"),\n \"eigen_crop\": True,\n \"garg_crop\": False,\n \"do_kb_crop\": False,\n \"min_depth_eval\": 0,\n \"max_depth_eval\": 10,\n \"min_depth\": 1e-3,\n \"max_depth\": 10\n },\n \"diml_outdoor\": {\n \"dataset\": \"diml_outdoor\",\n \"diml_outdoor_root\": os.path.join(HOME_DIR, \"shortcuts/datasets/diml_outdoor_test/\"),\n \"eigen_crop\": False,\n \"garg_crop\": True,\n \"do_kb_crop\": False,\n \"min_depth_eval\": 2,\n \"max_depth_eval\": 80,\n \"min_depth\": 1e-3,\n \"max_depth\": 80\n },\n \"diode_indoor\": {\n \"dataset\": \"diode_indoor\",\n \"diode_indoor_root\": os.path.join(HOME_DIR, \"shortcuts/datasets/diode_indoor/\"),\n \"eigen_crop\": True,\n \"garg_crop\": False,\n \"do_kb_crop\": False,\n \"min_depth_eval\": 1e-3,\n \"max_depth_eval\": 10,\n \"min_depth\": 1e-3,\n \"max_depth\": 10\n },\n \"diode_outdoor\": {\n \"dataset\": \"diode_outdoor\",\n \"diode_outdoor_root\": os.path.join(HOME_DIR, \"shortcuts/datasets/diode_outdoor/\"),\n \"eigen_crop\": False,\n \"garg_crop\": True,\n \"do_kb_crop\": False,\n \"min_depth_eval\": 1e-3,\n \"max_depth_eval\": 80,\n \"min_depth\": 1e-3,\n \"max_depth\": 80\n },\n \"hypersim_test\": {\n \"dataset\": \"hypersim_test\",\n \"hypersim_test_root\": os.path.join(HOME_DIR, \"shortcuts/datasets/hypersim_test/\"),\n \"eigen_crop\": True,\n \"garg_crop\": False,\n \"do_kb_crop\": False,\n \"min_depth_eval\": 1e-3,\n \"max_depth_eval\": 80,\n \"min_depth\": 1e-3,\n \"max_depth\": 10\n },\n \"vkitti\": {\n \"dataset\": \"vkitti\",\n \"vkitti_root\": os.path.join(HOME_DIR, \"shortcuts/datasets/vkitti_test/\"),\n \"eigen_crop\": False,\n \"garg_crop\": True,\n \"do_kb_crop\": True,\n \"min_depth_eval\": 1e-3,\n \"max_depth_eval\": 80,\n \"min_depth\": 1e-3,\n \"max_depth\": 80\n },\n \"vkitti2\": {\n \"dataset\": \"vkitti2\",\n \"vkitti2_root\": os.path.join(HOME_DIR, \"shortcuts/datasets/vkitti2/\"),\n \"eigen_crop\": False,\n \"garg_crop\": True,\n \"do_kb_crop\": True,\n \"min_depth_eval\": 1e-3,\n \"max_depth_eval\": 80,\n \"min_depth\": 1e-3,\n \"max_depth\": 80,\n },\n \"ddad\": {\n \"dataset\": \"ddad\",\n \"ddad_root\": os.path.join(HOME_DIR, \"shortcuts/datasets/ddad/ddad_val/\"),\n \"eigen_crop\": False,\n \"garg_crop\": True,\n \"do_kb_crop\": True,\n \"min_depth_eval\": 1e-3,\n \"max_depth_eval\": 80,\n \"min_depth\": 1e-3,\n \"max_depth\": 80,\n },\n}" }, { "identifier": "compute_metrics", "path": "zoedepth/utils/misc.py", "snippet": "def compute_metrics(gt, pred, interpolate=True, garg_crop=False, eigen_crop=True, dataset='nyu', min_depth_eval=0.1, max_depth_eval=10, disp_gt_edges=None, pred_depths=None, **kwargs):\n \"\"\"Compute metrics of predicted depth maps. Applies cropping and masking as necessary or specified via arguments. Refer to compute_errors for more details on metrics.\n \"\"\"\n if 'config' in kwargs:\n config = kwargs['config']\n garg_crop = config.garg_crop\n eigen_crop = config.eigen_crop\n min_depth_eval = config.min_depth_eval\n max_depth_eval = config.max_depth_eval\n\n if gt.shape[-2:] != pred.shape[-2:] and interpolate:\n pred = nn.functional.interpolate(\n pred.unsqueeze(dim=0).unsqueeze(dim=0), gt.shape[-2:], mode='bilinear', align_corners=True).squeeze()\n\n pred = pred.squeeze().cpu().numpy()\n pred[pred < min_depth_eval] = min_depth_eval\n pred[pred > max_depth_eval] = max_depth_eval\n pred[np.isinf(pred)] = max_depth_eval\n pred[np.isnan(pred)] = min_depth_eval\n\n gt_depth = gt.squeeze().cpu().numpy()\n valid_mask = np.logical_and(\n gt_depth > min_depth_eval, gt_depth < max_depth_eval)\n\n eval_mask = np.ones(valid_mask.shape)\n if garg_crop or eigen_crop:\n gt_height, gt_width = gt_depth.shape\n eval_mask = np.zeros(valid_mask.shape)\n\n if garg_crop:\n eval_mask[int(0.40810811 * gt_height):int(0.99189189 * gt_height),\n int(0.03594771 * gt_width):int(0.96405229 * gt_width)] = 1\n\n elif eigen_crop:\n # print(\"-\"*10, \" EIGEN CROP \", \"-\"*10)\n if dataset == 'kitti':\n eval_mask[int(0.3324324 * gt_height):int(0.91351351 * gt_height),\n int(0.0359477 * gt_width):int(0.96405229 * gt_width)] = 1\n else:\n # assert gt_depth.shape == (480, 640), \"Error: Eigen crop is currently only valid for (480, 640) images\"\n eval_mask[45:471, 41:601] = 1\n else:\n eval_mask = np.ones(valid_mask.shape)\n valid_mask = np.logical_and(valid_mask, eval_mask)\n\n # if dataset == 'nyu':\n # # pred = scale_shift_linear(torch.tensor(pred_depths), torch.tensor(pred), torch.tensor(valid_mask), fuse=False).numpy()\n # pred = scale_shift_linear(torch.tensor(gt), torch.tensor(pred), torch.tensor(valid_mask), fuse=False).numpy()\n \n metrics = compute_errors(gt_depth[valid_mask], pred[valid_mask])\n\n mask = valid_mask.squeeze() # squeeze\n gt = gt_depth\n pred = pred\n see_depth = 0\n if disp_gt_edges is None:\n print(\"Maybe we need edge maps from origin disp!\")\n edges = get_boundaries(gt, th=0.08, dilation=0)\n else:\n edges = disp_gt_edges\n \n mask = np.logical_and(mask, edges)\n import matplotlib.pyplot as plt\n if mask.sum() > 0:\n see_depth = soft_edge_error(pred, gt)[mask].mean()\n metrics['see'] = see_depth\n \n return metrics" }, { "identifier": "get_black_border", "path": "zoedepth/data/preprocess.py", "snippet": "def get_black_border(rgb_image, **kwargs) -> CropParams:\n \"\"\"Crops the black border of the RGB.\n\n Args:\n rgb: RGB image, shape (H, W, 3).\n\n Returns:\n Crop parameters.\n \"\"\"\n\n return get_border_params(rgb_image, value=0, **kwargs)" }, { "identifier": "BaseTrainer", "path": "zoedepth/trainers/base_trainer.py", "snippet": "def is_rank_zero(args):\n def __init__(self, config, model, train_loader, test_loader=None, device=None):\n def resize_to_target(self, prediction, target):\n def load_ckpt(self, checkpoint_dir=\"./checkpoints\", ckpt_type=\"best\"):\n def init_optimizer(self):\n def init_scheduler(self):\n def train_on_batch(self, batch, train_step):\n def validate_on_batch(self, batch, val_step):\n def raise_if_nan(self, losses):\n def iters_per_epoch(self):\n def total_iters(self):\n def should_early_stop(self):\n def train(self):\n def stringify_losses(L): return \"; \".join(map(\n def validate(self):\n def save_checkpoint(self, filename):\n def log_images(self, rgb: Dict[str, list] = {}, depth: Dict[str, list] = {}, scalar_field: Dict[str, list] = {}, prefix=\"\", scalar_cmap=\"turbo_r\", min_depth=None, max_depth=None):\n def log_line_plot(self, data):\n def log_bar_plot(self, title, labels, values):\nclass BaseTrainer:" }, { "identifier": "generatemask", "path": "zoedepth/utils/misc.py", "snippet": "def generatemask(size, k_size=-1, sigma=-1, h_factor=0.03, w_factor=0.02):\n # Generates a Guassian mask\n mask = np.zeros(size, dtype=np.float32)\n if sigma == -1:\n sigma = int(size[0]/16)\n if k_size == -1:\n k_size = int(2 * np.ceil(2 * int(size[0]/16)) + 1)\n # mask[int(0.02*size[0]):size[0] - int(0.02*size[0]), int(0.015*size[1]): size[1] - int(0.015*size[1])] = 1\n mask[int(h_factor*size[0]):size[0] - int(h_factor*size[0]), int(w_factor*size[1]): size[1] - int(w_factor*size[1])] = 1\n mask = cv2.GaussianBlur(mask, (int(k_size), int(k_size)), sigma)\n mask = (mask - mask.min()) / (mask.max() - mask.min())\n mask = mask.astype(np.float32)\n return mask" } ]
import os import torch import torch.cuda.amp as amp import torch.nn as nn import numpy as np import wandb import uuid import torch.distributed as dist import copy import torch.optim as optim import matplotlib.pyplot as plt from zoedepth.trainers.loss_sample import SILogLoss, DistributionLoss from zoedepth.trainers.loss import SILogLoss as DenseSILogLoss from zoedepth.trainers.loss import BudgetConstraint, HistogramMatchingLoss, SSIM, ConsistencyLoss from zoedepth.utils.config import DATASETS_CONFIG from zoedepth.utils.misc import compute_metrics from zoedepth.data.preprocess import get_black_border from .base_trainer import BaseTrainer, is_rank_zero, colors, flatten from torchvision import transforms from PIL import Image from tqdm import tqdm from datetime import datetime as dt from zoedepth.utils.misc import generatemask
15,603
# For now, this may be a bit slow due to converting to numpy and back # We assume no normalization is done on the input image # get the black border assert x.shape[0] == 1, "Only batch size 1 is supported for now" x_pil = transforms.ToPILImage()(x[0].cpu()) x_np = np.array(x_pil, dtype=np.uint8) black_border_params = get_black_border(x_np) top, bottom, left, right = black_border_params.top, black_border_params.bottom, black_border_params.left, black_border_params.right x_np_cropped = x_np[top:bottom, left:right, :] x_cropped = transforms.ToTensor()(Image.fromarray(x_np_cropped)) # run inference on the cropped image pred_depths_cropped = self.eval_infer(x_cropped.unsqueeze(0).to(self.device)) # resize the prediction to x_np_cropped's size pred_depths_cropped = nn.functional.interpolate( pred_depths_cropped, size=(x_np_cropped.shape[0], x_np_cropped.shape[1]), mode="bilinear", align_corners=False) # pad the prediction back to the original size pred_depths = torch.zeros((1, 1, x_np.shape[0], x_np.shape[1]), device=pred_depths_cropped.device, dtype=pred_depths_cropped.dtype) pred_depths[:, :, top:bottom, left:right] = pred_depths_cropped return pred_depths def validate_on_batch(self, batch, val_step): images = batch['image'].to(self.device) depths_gt = batch['depth'].to(self.device) dataset = batch['dataset'][0] image_raw = batch['image_raw'].to(self.device) mask = batch["mask"].to(self.device) disp_gt_edges = batch['disp_gt_edges'].squeeze().numpy() bboxs = batch.get("bbox", None) if bboxs is not None: bboxs = bboxs.to(self.device) bbox_raw = batch.get("bbox_raw", None) if bbox_raw is not None: bbox_raw = bbox_raw.to(self.device) crop_area = batch.get("crop_area", None) if crop_area is not None: crop_area = crop_area.to(self.device) if 'has_valid_depth' in batch: if not batch['has_valid_depth']: return None, None depths_gt = depths_gt.squeeze().unsqueeze(0).unsqueeze(0) mask = mask.squeeze().unsqueeze(0).unsqueeze(0) # if dataset == 'nyu': # pred_depths = self.crop_aware_infer(images, image_raw) # else: # pred_depths = self.eval_infer(images, image_raw, bboxs, crop_area, dataset, bbox_raw) pred_depths = self.eval_infer(images, image_raw, bboxs, crop_area, dataset, bbox_raw) pred_depths = pred_depths.squeeze().unsqueeze(0).unsqueeze(0) # print(pred_depths.shape) # torch.Size([1, 1, 2160, 3840]) # print(depths_gt.shape) # torch.Size([1, 1, 2160, 3840]) with amp.autocast(enabled=self.config.use_amp): if self.sampled_training: l_depth = self.silog_loss( pred_depths, depths_gt, mask=mask.to(torch.bool)) else: l_depth = self.dense_silog_loss( pred_depths, depths_gt, mask=mask.to(torch.bool), interpolate=True) metrics = compute_metrics(depths_gt, pred_depths, disp_gt_edges=disp_gt_edges, **self.config) losses = {f"{self.silog_loss.name}": l_depth.item()} if self.should_log and self.config.get("debug", False): print(metrics) if val_step in [21, 27] and self.should_log: if self.config.get("debug", False): pass else: if self.sec_stage: log_rgb = image_raw else: log_rgb = images scale_pred = nn.functional.interpolate( pred_depths[0:1], depths_gt.shape[-2:], mode='bilinear', align_corners=True)[0] depths_gt[torch.logical_not(mask)] = DATASETS_CONFIG[dataset]['max_depth'] self.log_images(rgb={"Input": log_rgb[0]}, depth={"GT": depths_gt[0], "PredictedMono": scale_pred}, prefix="Test", min_depth=DATASETS_CONFIG[dataset]['min_depth'], max_depth=DATASETS_CONFIG[dataset]['max_depth']) return metrics, losses def train(self): print(f"Training {self.config.name}") if self.config.uid is None: self.config.uid = str(uuid.uuid4()).split('-')[-1] run_id = f"{dt.now().strftime('%d-%h_%H-%M')}-{self.config.uid}" self.config.run_id = run_id self.config.experiment_id = f"{self.config.wandb_start}_{self.config.name}{self.config.version_name}_{run_id}" self.should_write = ((not self.config.distributed) or self.config.rank == 0) self.should_log = self.should_write # and logging if self.should_log: if self.config.get("debug", False): pass else: tags = self.config.tags.split( ',') if self.config.tags != '' else None wandb.init(project=self.config.project, name=self.config.experiment_id, config=flatten(self.config), dir=self.config.root, tags=tags, notes=self.config.notes, settings=wandb.Settings(start_method="fork")) self.model.train() self.step = 0 best_loss = np.inf validate_every = int(self.config.validate_every * self.iters_per_epoch) if self.config.prefetch: for i, batch in tqdm(enumerate(self.train_loader), desc=f"Prefetching...",
# MIT License # Copyright (c) 2022 Intelligent Systems Lab Org # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # File author: Zhenyu Li # This file is partly inspired from ZoeDepth (https://github.com/isl-org/ZoeDepth/blob/main/zoedepth/trainers/zoedepth_trainer.py); author: Shariq Farooq Bhat class Trainer(BaseTrainer): def __init__(self, config, model, train_loader, test_loader=None, device=None): self.addf = config.get("addf", False) self.lazy_epoch = -1 self.boostingdepth = config.get("boostingdepth", False) super().__init__(config, model, train_loader, test_loader=test_loader, device=device) self.device = device self.silog_loss = SILogLoss(beta=config.get("beta", 0.15)) self.dense_silog_loss = DenseSILogLoss(beta=config.get("beta", 0.15)) print("sigloss's beta is set to {}".format(config.get("beta", 0.15))) self.scaler = amp.GradScaler(enabled=self.config.use_amp) self.distribution_loss = DistributionLoss(max_depth=self.config.max_depth) self.sampled_training = config.get("sampled_training", False) self.sec_stage = config.get("sec_stage", False) self.multi_consistency = config.get("multi_consistency", False) self.use_blur = config.get("use_blur", False) self.dynamic = config.get("dynamic", False) if self.dynamic: self.dynamic_unupdate_rate = config.get("dynamic_unupdate_rate", 0.0) self.budget_loss = BudgetConstraint(loss_mu=0.0, flops_all=21552.5684, warm_up=True) self.use_scale_loss = config.get("use_scale_loss", False) if self.use_scale_loss: if config.get("scale_type", "ssim"): self.scale_loss = SSIM(window_size=config.get("window_size", int(11))) else: self.scale_loss = HistogramMatchingLoss(min_depth=self.config.min_depth, max_depth=self.config.max_depth) self.scale_target = config.get("scale_target", None) self.consistency_training = config.get("consistency_training", False) if self.consistency_training: self.consistency_target = config.get("consistency_target", None) self.consistency_loss = ConsistencyLoss(self.consistency_target, config.get("focus_flatten", False), config.get("w_p", 1.0)) print("current weight for consistency loss is {}. focus_flatten is {}. w_p is {}".format(self.config.w_consistency, config.get("focus_flatten", False), config.get("w_p", 1.0))) def train_on_batch(self, batch, train_step, step_rate): """ Expects a batch of images and depth as input batch["image"].shape : batch_size, c, h, w batch["depth"].shape : batch_size, 1, h, w """ images, depths_gt = batch['image'].to(self.device), batch['depth'].to(self.device) image_raw = batch.get("image_raw", None) if image_raw is not None: image_raw = image_raw.to(self.device) sample_points = None if self.sampled_training: sample_points = batch['sample_points'].to(self.device) bbox = batch.get("bbox", None) if bbox is not None: bbox = bbox.to(self.device) bbox_raw = batch.get("bbox_raw", None) if bbox_raw is not None: bbox_raw = bbox_raw.to(self.device) depth_raw = batch.get("depth_raw", None) if depth_raw is not None: depth_raw = depth_raw.to(self.device) crop_area = batch.get("crop_area", None) if crop_area is not None: crop_area = crop_area.to(self.device) shift = batch.get("shift", None) if shift is not None: shift = shift.to(self.device) dataset = batch['dataset'][0] b, c, h, w = images.size() mask = batch["mask"].to(self.device).to(torch.bool) sample_mask = batch.get("sample_mask", None) if sample_mask is not None: sample_mask = sample_mask.to(self.device).to(torch.bool) mask_raw = batch.get("mask_raw", None) if mask_raw is not None: mask_raw = mask_raw.to(self.device).to(torch.bool) losses = {} with amp.autocast(enabled=self.config.use_amp): if self.sampled_training: output = self.model(images, sample_points, mode='train', image_raw=image_raw, bbox=bbox, depth_raw=depth_raw, crop_area=crop_area, shift=shift, bbox_raw=bbox_raw) else: output = self.model(images, None, mode='train', image_raw=image_raw, bbox=bbox, depth_raw=depth_raw, crop_area=crop_area, shift=shift, bbox_raw=bbox_raw) if self.boostingdepth: if self.lazy_epoch < self.epoch: output.update_learning_rate() self.lazy_epoch = self.epoch input_dict = dict() input_dict['data_gtfake'] = depths_gt output.set_input_train_gt(input_dict) output.optimize_parameters() pred_depths = output.fake_B pred = output.fake_B # print(torch.min(pred), torch.max(pred)) losses = output.get_current_losses() else: pred_depths = output['metric_depth'] if self.sampled_training: sampled_depth_gt = sample_points[:, :, -1].float().unsqueeze(dim=-1) sampled_depth_gt = sampled_depth_gt.permute(0, 2, 1) if self.config.get("representation", "") == 'biLaplacian': # only for sampled training for now l_dist, l_si = self.distribution_loss(output, sampled_depth_gt, mask=sample_mask) loss = self.config.w_dist * l_dist + self.config.w_si * l_si losses['distribution_loss'] = l_dist losses['sigloss'] = l_si if self.multi_consistency: coarse, fine = output['coarse_depth_pred'], output['fine_depth_pred'] l_si_f = self.dense_silog_loss( fine, depths_gt, mask=mask, interpolate=True, return_interpolated=False) l_si_c = self.dense_silog_loss( coarse, depth_raw, mask=mask_raw, interpolate=True, return_interpolated=False) losses['sigloss_f'] = l_si_f losses['l_si_c'] = l_si_c loss += self.config.w_si * (l_si_f + l_si_c) else: if self.sampled_training: l_si = self.silog_loss( pred_depths, sampled_depth_gt, mask=sample_mask) loss = self.config.w_si * l_si losses[self.silog_loss.name] = l_si if self.multi_consistency: coarse, fine = output['coarse_depth_pred'], output['fine_depth_pred'] l_si_f = self.dense_silog_loss( fine, depths_gt, mask=mask, interpolate=True, return_interpolated=False) l_si_c = self.dense_silog_loss( coarse, depth_raw, mask=mask_raw, interpolate=True, return_interpolated=False) losses['sigloss_f'] = l_si_f losses['l_si_c'] = l_si_c loss += self.config.w_si * (l_si_f + l_si_c) else: if self.multi_consistency: #### here here here pred_depths, coarse, fine = output['metric_depth'], output['coarse_depth_pred'], output['fine_depth_pred'] if self.consistency_training: depths_gt = torch.split(depths_gt, 1, dim=1) depths_gt = torch.cat(depths_gt, dim=0) mask = torch.split(mask, 1, dim=-1) mask = torch.cat(mask, dim=0).permute(0, 3, 1, 2) mask_raw = torch.cat([mask_raw, mask_raw], dim=0) depth_raw = torch.cat([depth_raw, depth_raw], dim=0) temp_features = output.get('temp_features', None) l_si_1, pred = self.dense_silog_loss( pred_depths, depths_gt, mask=mask, interpolate=True, return_interpolated=True) l_si_f, pred_f = self.dense_silog_loss( fine, depths_gt, mask=mask, interpolate=True, return_interpolated=True) l_si_c = self.dense_silog_loss( coarse, depth_raw, mask=mask_raw, interpolate=True, return_interpolated=False) losses[self.silog_loss.name] = l_si_1 losses['sigloss_f'] = l_si_f losses['l_si_c'] = l_si_c # loss = l_si_1 + l_si_f + l_si_c loss = l_si_1 if self.consistency_training: try: # depths_gt? pred_f? l_consistency = self.consistency_loss(pred, shift, mask, temp_features, pred_f=depths_gt) # use the resized pred except RuntimeError as e: print(e) print("some runtime error here! Hack with 0") l_consistency = torch.Tensor([0]).squeeze() losses[self.consistency_loss.name] = l_consistency loss += l_consistency * self.config.w_consistency else: l_si, pred = self.dense_silog_loss( pred_depths, depths_gt, mask=mask, interpolate=True, return_interpolated=True) loss = self.config.w_si * l_si losses[self.silog_loss.name] = l_si if self.dynamic: if step_rate > self.dynamic_unupdate_rate: warm_up_rate = min(1.0, (step_rate - self.dynamic_unupdate_rate) / 0.02) flop_cost = self.budget_loss(output['all_cell_flops'], warm_up_rate=warm_up_rate) loss += self.config.w_flop * flop_cost losses['flop_loss'] = flop_cost else: flop_cost = self.budget_loss(output['all_cell_flops'], warm_up_rate=1) loss += 0 * flop_cost losses['flop_loss'] = flop_cost if self.use_scale_loss: if self.scale_target == 'coarse': h_loss = self.scale_loss(pred_depths, output['coarse_depth_pred_roi'], mask, interpolate=True) else: h_loss = self.scale_loss(pred_depths, depths_gt, mask, interpolate=True) loss += self.config.w_scale * h_loss losses['scale_loss'] = h_loss # self.scaler.scale(loss).backward() # if self.config.clip_grad > 0: # self.scaler.unscale_(self.optimizer) # nn.utils.clip_grad_norm_( # self.model.parameters(), self.config.clip_grad) # self.scaler.step(self.optimizer) # self.scaler.update() # self.optimizer.zero_grad() self.scaler.scale(loss).backward() if self.config.clip_grad > 0: self.scaler.unscale_(self.optimizer) nn.utils.clip_grad_norm_( self.model.parameters(), self.config.clip_grad) self.scaler.step(self.optimizer) self.scaler.update() self.optimizer.zero_grad() if self.should_log and (self.step % int(self.config.log_images_every * self.iters_per_epoch)) == 0: if self.config.get("debug", False): pred = nn.functional.interpolate( pred[0:1], depths_gt.shape[-2:], mode='bilinear', align_corners=True)[0] plt.imshow(pred.squeeze().detach().cpu().numpy()) plt.savefig('debug.png') pass else: pred = nn.functional.interpolate( pred[0:1], depths_gt.shape[-2:], mode='bilinear', align_corners=True)[0] depths_gt[torch.logical_not(mask)] = DATASETS_CONFIG[dataset]['max_depth'] if self.consistency_training: split_images = torch.split(images, 3, dim=1) images = torch.cat(split_images, dim=0) self.log_images(rgb={"Input": images[0, ...]}, depth={"GT": depths_gt[0], "PredictedMono": pred}, prefix="Train", min_depth=DATASETS_CONFIG[dataset]['min_depth'], max_depth=DATASETS_CONFIG[dataset]['max_depth']) return losses @torch.no_grad() def eval_infer(self, x, image_raw, bboxs=None, crop_area=None, dataset='u4k', bbox_raw=None): m = self.model.module if self.config.multigpu else self.model if dataset == 'u4k': base_h = 540 base_w = 960 elif dataset == 'gta': base_h = 270 base_w = 480 elif dataset == 'nyu': base_h = 120 * 2 base_w = 160 * 2 else: raise NotImplementedError if dataset == 'nyu': if self.sec_stage: images_crops = torch.split(x, 3, dim=1) bboxs_list = torch.split(bboxs, 1, dim=1) crop_areas = torch.split(crop_area, 1, dim=1) pred_depth_crops = [] for i, (img, bbox, crop_area) in enumerate(zip(images_crops, bboxs_list, crop_areas)): with amp.autocast(enabled=self.config.use_amp): if i == 0: out_dict = m(img, mode='eval', image_raw=image_raw, bbox=bbox[0], crop_area=crop_area, bbox_raw=bbox_raw[:, i, :] if bbox_raw is not None else None) # whole_depth_pred = out_dict['coarse_depth_pred'] pred_depth_crop = out_dict['metric_depth'] else: pred_depth_crop = m(img, mode='eval', image_raw=image_raw, bbox=bbox[0], crop_area=crop_area, bbox_raw=bbox_raw[:, i, :] if bbox_raw is not None else None)['metric_depth'] pred_depth_crop = nn.functional.interpolate( pred_depth_crop, (base_h, base_w), mode='bilinear', align_corners=True) pred_depth_crops.append(pred_depth_crop) x_start, y_start = [0, base_h], [0, base_w] pred_depth = torch.zeros((base_h*2, base_w*2)).cuda() inner_idx = 0 for ii, x in enumerate(x_start): for jj, y in enumerate(y_start): if self.use_blur: pred_depth[x: x+base_h, y: y+base_w] = pred_depth_crops[inner_idx].squeeze() # do not care about boundry during validation else: pred_depth[x: x+base_h, y: y+base_w] = pred_depth_crops[inner_idx].squeeze() inner_idx += 1 pred_depth = pred_depth.squeeze(dim=0) else: with amp.autocast(enabled=self.config.use_amp): pred_depth = m(x, mode='eval', image_raw=image_raw)['metric_depth'] else: if self.sec_stage: images_crops = torch.split(x, 3, dim=1) bboxs_list = torch.split(bboxs, 1, dim=1) crop_areas = torch.split(crop_area, 1, dim=1) pred_depth_crops = [] for i, (img, bbox, crop_area) in enumerate(zip(images_crops, bboxs_list, crop_areas)): with amp.autocast(enabled=self.config.use_amp): if i == 0: out_dict = m(img, mode='eval', image_raw=image_raw, bbox=bbox[0], crop_area=crop_area, bbox_raw=bbox_raw[:, i, :] if bbox_raw is not None else None) # whole_depth_pred = out_dict['coarse_depth_pred'] pred_depth_crop = out_dict['metric_depth'] else: pred_depth_crop = m(img, mode='eval', image_raw=image_raw, bbox=bbox[0], crop_area=crop_area, bbox_raw=bbox_raw[:, i, :] if bbox_raw is not None else None)['metric_depth'] pred_depth_crop = nn.functional.interpolate( pred_depth_crop, (base_h, base_w), mode='bilinear', align_corners=True) pred_depth_crops.append(pred_depth_crop) x_start, y_start = [0, base_h], [0, base_w] pred_depth = torch.zeros((base_h*2, base_w*2)).cuda() inner_idx = 0 for ii, x in enumerate(x_start): for jj, y in enumerate(y_start): if self.use_blur: pred_depth[x: x+base_h, y: y+base_w] = pred_depth_crops[inner_idx].squeeze() # do not care about boundry during validation else: pred_depth[x: x+base_h, y: y+base_w] = pred_depth_crops[inner_idx].squeeze() inner_idx += 1 pred_depth = pred_depth.squeeze(dim=0) else: with amp.autocast(enabled=self.config.use_amp): pred_depth = m(x, mode='eval', image_raw=image_raw)['metric_depth'] return pred_depth @torch.no_grad() def crop_aware_infer(self, x, image_raw): # if we are not avoiding the black border, we can just use the normal inference if not self.config.get("avoid_boundary", False): return self.eval_infer(x) # otherwise, we need to crop the image to avoid the black border # For now, this may be a bit slow due to converting to numpy and back # We assume no normalization is done on the input image # get the black border assert x.shape[0] == 1, "Only batch size 1 is supported for now" x_pil = transforms.ToPILImage()(x[0].cpu()) x_np = np.array(x_pil, dtype=np.uint8) black_border_params = get_black_border(x_np) top, bottom, left, right = black_border_params.top, black_border_params.bottom, black_border_params.left, black_border_params.right x_np_cropped = x_np[top:bottom, left:right, :] x_cropped = transforms.ToTensor()(Image.fromarray(x_np_cropped)) # run inference on the cropped image pred_depths_cropped = self.eval_infer(x_cropped.unsqueeze(0).to(self.device)) # resize the prediction to x_np_cropped's size pred_depths_cropped = nn.functional.interpolate( pred_depths_cropped, size=(x_np_cropped.shape[0], x_np_cropped.shape[1]), mode="bilinear", align_corners=False) # pad the prediction back to the original size pred_depths = torch.zeros((1, 1, x_np.shape[0], x_np.shape[1]), device=pred_depths_cropped.device, dtype=pred_depths_cropped.dtype) pred_depths[:, :, top:bottom, left:right] = pred_depths_cropped return pred_depths def validate_on_batch(self, batch, val_step): images = batch['image'].to(self.device) depths_gt = batch['depth'].to(self.device) dataset = batch['dataset'][0] image_raw = batch['image_raw'].to(self.device) mask = batch["mask"].to(self.device) disp_gt_edges = batch['disp_gt_edges'].squeeze().numpy() bboxs = batch.get("bbox", None) if bboxs is not None: bboxs = bboxs.to(self.device) bbox_raw = batch.get("bbox_raw", None) if bbox_raw is not None: bbox_raw = bbox_raw.to(self.device) crop_area = batch.get("crop_area", None) if crop_area is not None: crop_area = crop_area.to(self.device) if 'has_valid_depth' in batch: if not batch['has_valid_depth']: return None, None depths_gt = depths_gt.squeeze().unsqueeze(0).unsqueeze(0) mask = mask.squeeze().unsqueeze(0).unsqueeze(0) # if dataset == 'nyu': # pred_depths = self.crop_aware_infer(images, image_raw) # else: # pred_depths = self.eval_infer(images, image_raw, bboxs, crop_area, dataset, bbox_raw) pred_depths = self.eval_infer(images, image_raw, bboxs, crop_area, dataset, bbox_raw) pred_depths = pred_depths.squeeze().unsqueeze(0).unsqueeze(0) # print(pred_depths.shape) # torch.Size([1, 1, 2160, 3840]) # print(depths_gt.shape) # torch.Size([1, 1, 2160, 3840]) with amp.autocast(enabled=self.config.use_amp): if self.sampled_training: l_depth = self.silog_loss( pred_depths, depths_gt, mask=mask.to(torch.bool)) else: l_depth = self.dense_silog_loss( pred_depths, depths_gt, mask=mask.to(torch.bool), interpolate=True) metrics = compute_metrics(depths_gt, pred_depths, disp_gt_edges=disp_gt_edges, **self.config) losses = {f"{self.silog_loss.name}": l_depth.item()} if self.should_log and self.config.get("debug", False): print(metrics) if val_step in [21, 27] and self.should_log: if self.config.get("debug", False): pass else: if self.sec_stage: log_rgb = image_raw else: log_rgb = images scale_pred = nn.functional.interpolate( pred_depths[0:1], depths_gt.shape[-2:], mode='bilinear', align_corners=True)[0] depths_gt[torch.logical_not(mask)] = DATASETS_CONFIG[dataset]['max_depth'] self.log_images(rgb={"Input": log_rgb[0]}, depth={"GT": depths_gt[0], "PredictedMono": scale_pred}, prefix="Test", min_depth=DATASETS_CONFIG[dataset]['min_depth'], max_depth=DATASETS_CONFIG[dataset]['max_depth']) return metrics, losses def train(self): print(f"Training {self.config.name}") if self.config.uid is None: self.config.uid = str(uuid.uuid4()).split('-')[-1] run_id = f"{dt.now().strftime('%d-%h_%H-%M')}-{self.config.uid}" self.config.run_id = run_id self.config.experiment_id = f"{self.config.wandb_start}_{self.config.name}{self.config.version_name}_{run_id}" self.should_write = ((not self.config.distributed) or self.config.rank == 0) self.should_log = self.should_write # and logging if self.should_log: if self.config.get("debug", False): pass else: tags = self.config.tags.split( ',') if self.config.tags != '' else None wandb.init(project=self.config.project, name=self.config.experiment_id, config=flatten(self.config), dir=self.config.root, tags=tags, notes=self.config.notes, settings=wandb.Settings(start_method="fork")) self.model.train() self.step = 0 best_loss = np.inf validate_every = int(self.config.validate_every * self.iters_per_epoch) if self.config.prefetch: for i, batch in tqdm(enumerate(self.train_loader), desc=f"Prefetching...",
total=self.iters_per_epoch) if is_rank_zero(self.config) else enumerate(self.train_loader):
10
2023-12-04 08:43:15+00:00
24k
alvinliu0/HumanGaussian
threestudio/models/geometry/tetrahedra_sdf_grid.py
[ { "identifier": "BaseExplicitGeometry", "path": "threestudio/models/geometry/base.py", "snippet": "class BaseExplicitGeometry(BaseGeometry):\n @dataclass\n class Config(BaseGeometry.Config):\n radius: float = 1.0\n\n cfg: Config\n\n def configure(self) -> None:\n self.bbox: Float[Tensor, \"2 3\"]\n self.register_buffer(\n \"bbox\",\n torch.as_tensor(\n [\n [-self.cfg.radius, -self.cfg.radius, -self.cfg.radius],\n [self.cfg.radius, self.cfg.radius, self.cfg.radius],\n ],\n dtype=torch.float32,\n ),\n )" }, { "identifier": "BaseGeometry", "path": "threestudio/models/geometry/base.py", "snippet": "class BaseGeometry(BaseModule):\n @dataclass\n class Config(BaseModule.Config):\n pass\n\n cfg: Config\n\n @staticmethod\n def create_from(\n other: \"BaseGeometry\", cfg: Optional[Union[dict, DictConfig]] = None, **kwargs\n ) -> \"BaseGeometry\":\n raise TypeError(\n f\"Cannot create {BaseGeometry.__name__} from {other.__class__.__name__}\"\n )\n\n def export(self, *args, **kwargs) -> Dict[str, Any]:\n return {}" }, { "identifier": "contract_to_unisphere", "path": "threestudio/models/geometry/base.py", "snippet": "def contract_to_unisphere(\n x: Float[Tensor, \"... 3\"], bbox: Float[Tensor, \"2 3\"], unbounded: bool = False\n) -> Float[Tensor, \"... 3\"]:\n if unbounded:\n x = scale_tensor(x, bbox, (0, 1))\n x = x * 2 - 1 # aabb is at [-1, 1]\n mag = x.norm(dim=-1, keepdim=True)\n mask = mag.squeeze(-1) > 1\n x[mask] = (2 - 1 / mag[mask]) * (x[mask] / mag[mask])\n x = x / 4 + 0.5 # [-inf, inf] is at [0, 1]\n else:\n x = scale_tensor(x, bbox, (0, 1))\n return x" }, { "identifier": "ImplicitSDF", "path": "threestudio/models/geometry/implicit_sdf.py", "snippet": "class ImplicitSDF(BaseImplicitGeometry):\n @dataclass\n class Config(BaseImplicitGeometry.Config):\n n_input_dims: int = 3\n n_feature_dims: int = 3\n pos_encoding_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"HashGrid\",\n \"n_levels\": 16,\n \"n_features_per_level\": 2,\n \"log2_hashmap_size\": 19,\n \"base_resolution\": 16,\n \"per_level_scale\": 1.447269237440378,\n }\n )\n mlp_network_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"VanillaMLP\",\n \"activation\": \"ReLU\",\n \"output_activation\": \"none\",\n \"n_neurons\": 64,\n \"n_hidden_layers\": 1,\n }\n )\n normal_type: Optional[\n str\n ] = \"finite_difference\" # in ['pred', 'finite_difference', 'finite_difference_laplacian']\n finite_difference_normal_eps: Union[\n float, str\n ] = 0.01 # in [float, \"progressive\"]\n shape_init: Optional[str] = None\n shape_init_params: Optional[Any] = None\n shape_init_mesh_up: str = \"+z\"\n shape_init_mesh_front: str = \"+x\"\n force_shape_init: bool = False\n sdf_bias: Union[float, str] = 0.0\n sdf_bias_params: Optional[Any] = None\n\n # no need to removal outlier for SDF\n isosurface_remove_outliers: bool = False\n\n cfg: Config\n\n def configure(self) -> None:\n super().configure()\n self.encoding = get_encoding(\n self.cfg.n_input_dims, self.cfg.pos_encoding_config\n )\n self.sdf_network = get_mlp(\n self.encoding.n_output_dims, 1, self.cfg.mlp_network_config\n )\n\n if self.cfg.n_feature_dims > 0:\n self.feature_network = get_mlp(\n self.encoding.n_output_dims,\n self.cfg.n_feature_dims,\n self.cfg.mlp_network_config,\n )\n\n if self.cfg.normal_type == \"pred\":\n self.normal_network = get_mlp(\n self.encoding.n_output_dims, 3, self.cfg.mlp_network_config\n )\n if self.cfg.isosurface_deformable_grid:\n assert (\n self.cfg.isosurface_method == \"mt\"\n ), \"isosurface_deformable_grid only works with mt\"\n self.deformation_network = get_mlp(\n self.encoding.n_output_dims, 3, self.cfg.mlp_network_config\n )\n\n self.finite_difference_normal_eps: Optional[float] = None\n\n def initialize_shape(self) -> None:\n if self.cfg.shape_init is None and not self.cfg.force_shape_init:\n return\n\n # do not initialize shape if weights are provided\n if self.cfg.weights is not None and not self.cfg.force_shape_init:\n return\n\n if self.cfg.sdf_bias != 0.0:\n threestudio.warn(\n \"shape_init and sdf_bias are both specified, which may lead to unexpected results.\"\n )\n\n get_gt_sdf: Callable[[Float[Tensor, \"N 3\"]], Float[Tensor, \"N 1\"]]\n assert isinstance(self.cfg.shape_init, str)\n if self.cfg.shape_init == \"ellipsoid\":\n assert (\n isinstance(self.cfg.shape_init_params, Sized)\n and len(self.cfg.shape_init_params) == 3\n )\n size = torch.as_tensor(self.cfg.shape_init_params).to(self.device)\n\n def func(points_rand: Float[Tensor, \"N 3\"]) -> Float[Tensor, \"N 1\"]:\n return ((points_rand / size) ** 2).sum(\n dim=-1, keepdim=True\n ).sqrt() - 1.0 # pseudo signed distance of an ellipsoid\n\n get_gt_sdf = func\n elif self.cfg.shape_init == \"sphere\":\n assert isinstance(self.cfg.shape_init_params, float)\n radius = self.cfg.shape_init_params\n\n def func(points_rand: Float[Tensor, \"N 3\"]) -> Float[Tensor, \"N 1\"]:\n return (points_rand**2).sum(dim=-1, keepdim=True).sqrt() - radius\n\n get_gt_sdf = func\n elif self.cfg.shape_init.startswith(\"mesh:\"):\n assert isinstance(self.cfg.shape_init_params, float)\n mesh_path = self.cfg.shape_init[5:]\n if not os.path.exists(mesh_path):\n raise ValueError(f\"Mesh file {mesh_path} does not exist.\")\n\n import trimesh\n\n scene = trimesh.load(mesh_path)\n if isinstance(scene, trimesh.Trimesh):\n mesh = scene\n elif isinstance(scene, trimesh.scene.Scene):\n mesh = trimesh.Trimesh()\n for obj in scene.geometry.values():\n mesh = trimesh.util.concatenate([mesh, obj])\n else:\n raise ValueError(f\"Unknown mesh type at {mesh_path}.\")\n\n # move to center\n centroid = mesh.vertices.mean(0)\n mesh.vertices = mesh.vertices - centroid\n\n # align to up-z and front-x\n dirs = [\"+x\", \"+y\", \"+z\", \"-x\", \"-y\", \"-z\"]\n dir2vec = {\n \"+x\": np.array([1, 0, 0]),\n \"+y\": np.array([0, 1, 0]),\n \"+z\": np.array([0, 0, 1]),\n \"-x\": np.array([-1, 0, 0]),\n \"-y\": np.array([0, -1, 0]),\n \"-z\": np.array([0, 0, -1]),\n }\n if (\n self.cfg.shape_init_mesh_up not in dirs\n or self.cfg.shape_init_mesh_front not in dirs\n ):\n raise ValueError(\n f\"shape_init_mesh_up and shape_init_mesh_front must be one of {dirs}.\"\n )\n if self.cfg.shape_init_mesh_up[1] == self.cfg.shape_init_mesh_front[1]:\n raise ValueError(\n \"shape_init_mesh_up and shape_init_mesh_front must be orthogonal.\"\n )\n z_, x_ = (\n dir2vec[self.cfg.shape_init_mesh_up],\n dir2vec[self.cfg.shape_init_mesh_front],\n )\n y_ = np.cross(z_, x_)\n std2mesh = np.stack([x_, y_, z_], axis=0).T\n mesh2std = np.linalg.inv(std2mesh)\n\n # scaling\n scale = np.abs(mesh.vertices).max()\n mesh.vertices = mesh.vertices / scale * self.cfg.shape_init_params\n mesh.vertices = np.dot(mesh2std, mesh.vertices.T).T\n\n from pysdf import SDF\n\n sdf = SDF(mesh.vertices, mesh.faces)\n\n def func(points_rand: Float[Tensor, \"N 3\"]) -> Float[Tensor, \"N 1\"]:\n # add a negative signed here\n # as in pysdf the inside of the shape has positive signed distance\n return torch.from_numpy(-sdf(points_rand.cpu().numpy())).to(\n points_rand\n )[..., None]\n\n get_gt_sdf = func\n\n else:\n raise ValueError(\n f\"Unknown shape initialization type: {self.cfg.shape_init}\"\n )\n\n # Initialize SDF to a given shape when no weights are provided or force_shape_init is True\n optim = torch.optim.Adam(self.parameters(), lr=1e-3)\n from tqdm import tqdm\n\n for _ in tqdm(\n range(1000),\n desc=f\"Initializing SDF to a(n) {self.cfg.shape_init}:\",\n disable=get_rank() != 0,\n ):\n points_rand = (\n torch.rand((10000, 3), dtype=torch.float32).to(self.device) * 2.0 - 1.0\n )\n sdf_gt = get_gt_sdf(points_rand)\n sdf_pred = self.forward_sdf(points_rand)\n loss = F.mse_loss(sdf_pred, sdf_gt)\n optim.zero_grad()\n loss.backward()\n optim.step()\n\n # explicit broadcast to ensure param consistency across ranks\n for param in self.parameters():\n broadcast(param, src=0)\n\n def get_shifted_sdf(\n self, points: Float[Tensor, \"*N Di\"], sdf: Float[Tensor, \"*N 1\"]\n ) -> Float[Tensor, \"*N 1\"]:\n sdf_bias: Union[float, Float[Tensor, \"*N 1\"]]\n if self.cfg.sdf_bias == \"ellipsoid\":\n assert (\n isinstance(self.cfg.sdf_bias_params, Sized)\n and len(self.cfg.sdf_bias_params) == 3\n )\n size = torch.as_tensor(self.cfg.sdf_bias_params).to(points)\n sdf_bias = ((points / size) ** 2).sum(\n dim=-1, keepdim=True\n ).sqrt() - 1.0 # pseudo signed distance of an ellipsoid\n elif self.cfg.sdf_bias == \"sphere\":\n assert isinstance(self.cfg.sdf_bias_params, float)\n radius = self.cfg.sdf_bias_params\n sdf_bias = (points**2).sum(dim=-1, keepdim=True).sqrt() - radius\n elif isinstance(self.cfg.sdf_bias, float):\n sdf_bias = self.cfg.sdf_bias\n else:\n raise ValueError(f\"Unknown sdf bias {self.cfg.sdf_bias}\")\n return sdf + sdf_bias\n\n def forward(\n self, points: Float[Tensor, \"*N Di\"], output_normal: bool = False\n ) -> Dict[str, Float[Tensor, \"...\"]]:\n grad_enabled = torch.is_grad_enabled()\n\n if output_normal and self.cfg.normal_type == \"analytic\":\n torch.set_grad_enabled(True)\n points.requires_grad_(True)\n\n points_unscaled = points # points in the original scale\n points = contract_to_unisphere(\n points, self.bbox, self.unbounded\n ) # points normalized to (0, 1)\n\n enc = self.encoding(points.view(-1, self.cfg.n_input_dims))\n sdf = self.sdf_network(enc).view(*points.shape[:-1], 1)\n sdf = self.get_shifted_sdf(points_unscaled, sdf)\n output = {\"sdf\": sdf}\n\n if self.cfg.n_feature_dims > 0:\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n output.update({\"features\": features})\n\n if output_normal:\n if (\n self.cfg.normal_type == \"finite_difference\"\n or self.cfg.normal_type == \"finite_difference_laplacian\"\n ):\n assert self.finite_difference_normal_eps is not None\n eps: float = self.finite_difference_normal_eps\n if self.cfg.normal_type == \"finite_difference_laplacian\":\n offsets: Float[Tensor, \"6 3\"] = torch.as_tensor(\n [\n [eps, 0.0, 0.0],\n [-eps, 0.0, 0.0],\n [0.0, eps, 0.0],\n [0.0, -eps, 0.0],\n [0.0, 0.0, eps],\n [0.0, 0.0, -eps],\n ]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 6 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n sdf_offset: Float[Tensor, \"... 6 1\"] = self.forward_sdf(\n points_offset\n )\n sdf_grad = (\n 0.5\n * (sdf_offset[..., 0::2, 0] - sdf_offset[..., 1::2, 0])\n / eps\n )\n else:\n offsets: Float[Tensor, \"3 3\"] = torch.as_tensor(\n [[eps, 0.0, 0.0], [0.0, eps, 0.0], [0.0, 0.0, eps]]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 3 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n sdf_offset: Float[Tensor, \"... 3 1\"] = self.forward_sdf(\n points_offset\n )\n sdf_grad = (sdf_offset[..., 0::1, 0] - sdf) / eps\n normal = F.normalize(sdf_grad, dim=-1)\n elif self.cfg.normal_type == \"pred\":\n normal = self.normal_network(enc).view(*points.shape[:-1], 3)\n normal = F.normalize(normal, dim=-1)\n sdf_grad = normal\n elif self.cfg.normal_type == \"analytic\":\n sdf_grad = -torch.autograd.grad(\n sdf,\n points_unscaled,\n grad_outputs=torch.ones_like(sdf),\n create_graph=True,\n )[0]\n normal = F.normalize(sdf_grad, dim=-1)\n if not grad_enabled:\n sdf_grad = sdf_grad.detach()\n normal = normal.detach()\n else:\n raise AttributeError(f\"Unknown normal type {self.cfg.normal_type}\")\n output.update(\n {\"normal\": normal, \"shading_normal\": normal, \"sdf_grad\": sdf_grad}\n )\n return output\n\n def forward_sdf(self, points: Float[Tensor, \"*N Di\"]) -> Float[Tensor, \"*N 1\"]:\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n\n sdf = self.sdf_network(\n self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n ).reshape(*points.shape[:-1], 1)\n sdf = self.get_shifted_sdf(points_unscaled, sdf)\n return sdf\n\n def forward_field(\n self, points: Float[Tensor, \"*N Di\"]\n ) -> Tuple[Float[Tensor, \"*N 1\"], Optional[Float[Tensor, \"*N 3\"]]]:\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n sdf = self.sdf_network(enc).reshape(*points.shape[:-1], 1)\n sdf = self.get_shifted_sdf(points_unscaled, sdf)\n deformation: Optional[Float[Tensor, \"*N 3\"]] = None\n if self.cfg.isosurface_deformable_grid:\n deformation = self.deformation_network(enc).reshape(*points.shape[:-1], 3)\n return sdf, deformation\n\n def forward_level(\n self, field: Float[Tensor, \"*N 1\"], threshold: float\n ) -> Float[Tensor, \"*N 1\"]:\n return field - threshold\n\n def export(self, points: Float[Tensor, \"*N Di\"], **kwargs) -> Dict[str, Any]:\n out: Dict[str, Any] = {}\n if self.cfg.n_feature_dims == 0:\n return out\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n out.update(\n {\n \"features\": features,\n }\n )\n return out\n\n def update_step(self, epoch: int, global_step: int, on_load_weights: bool = False):\n if (\n self.cfg.normal_type == \"finite_difference\"\n or self.cfg.normal_type == \"finite_difference_laplacian\"\n ):\n if isinstance(self.cfg.finite_difference_normal_eps, float):\n self.finite_difference_normal_eps = (\n self.cfg.finite_difference_normal_eps\n )\n elif self.cfg.finite_difference_normal_eps == \"progressive\":\n # progressive finite difference eps from Neuralangelo\n # https://arxiv.org/abs/2306.03092\n hg_conf: Any = self.cfg.pos_encoding_config\n assert (\n hg_conf.otype == \"ProgressiveBandHashGrid\"\n ), \"finite_difference_normal_eps=progressive only works with ProgressiveBandHashGrid\"\n current_level = min(\n hg_conf.start_level\n + max(global_step - hg_conf.start_step, 0) // hg_conf.update_steps,\n hg_conf.n_levels,\n )\n grid_res = hg_conf.base_resolution * hg_conf.per_level_scale ** (\n current_level - 1\n )\n grid_size = 2 * self.cfg.radius / grid_res\n if grid_size != self.finite_difference_normal_eps:\n threestudio.info(\n f\"Update finite_difference_normal_eps to {grid_size}\"\n )\n self.finite_difference_normal_eps = grid_size\n else:\n raise ValueError(\n f\"Unknown finite_difference_normal_eps={self.cfg.finite_difference_normal_eps}\"\n )" }, { "identifier": "ImplicitVolume", "path": "threestudio/models/geometry/implicit_volume.py", "snippet": "class ImplicitVolume(BaseImplicitGeometry):\n @dataclass\n class Config(BaseImplicitGeometry.Config):\n n_input_dims: int = 3\n n_feature_dims: int = 3\n density_activation: Optional[str] = \"softplus\"\n density_bias: Union[float, str] = \"blob_magic3d\"\n density_blob_scale: float = 10.0\n density_blob_std: float = 0.5\n pos_encoding_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"HashGrid\",\n \"n_levels\": 16,\n \"n_features_per_level\": 2,\n \"log2_hashmap_size\": 19,\n \"base_resolution\": 16,\n \"per_level_scale\": 1.447269237440378,\n }\n )\n mlp_network_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"VanillaMLP\",\n \"activation\": \"ReLU\",\n \"output_activation\": \"none\",\n \"n_neurons\": 64,\n \"n_hidden_layers\": 1,\n }\n )\n normal_type: Optional[\n str\n ] = \"finite_difference\" # in ['pred', 'finite_difference', 'finite_difference_laplacian']\n finite_difference_normal_eps: float = 0.01\n\n # automatically determine the threshold\n isosurface_threshold: Union[float, str] = 25.0\n\n cfg: Config\n\n def configure(self) -> None:\n super().configure()\n self.encoding = get_encoding(\n self.cfg.n_input_dims, self.cfg.pos_encoding_config\n )\n self.density_network = get_mlp(\n self.encoding.n_output_dims, 1, self.cfg.mlp_network_config\n )\n if self.cfg.n_feature_dims > 0:\n self.feature_network = get_mlp(\n self.encoding.n_output_dims,\n self.cfg.n_feature_dims,\n self.cfg.mlp_network_config,\n )\n if self.cfg.normal_type == \"pred\":\n self.normal_network = get_mlp(\n self.encoding.n_output_dims, 3, self.cfg.mlp_network_config\n )\n\n def get_activated_density(\n self, points: Float[Tensor, \"*N Di\"], density: Float[Tensor, \"*N 1\"]\n ) -> Tuple[Float[Tensor, \"*N 1\"], Float[Tensor, \"*N 1\"]]:\n density_bias: Union[float, Float[Tensor, \"*N 1\"]]\n if self.cfg.density_bias == \"blob_dreamfusion\":\n # pre-activation density bias\n density_bias = (\n self.cfg.density_blob_scale\n * torch.exp(\n -0.5 * (points**2).sum(dim=-1) / self.cfg.density_blob_std**2\n )[..., None]\n )\n elif self.cfg.density_bias == \"blob_magic3d\":\n # pre-activation density bias\n density_bias = (\n self.cfg.density_blob_scale\n * (\n 1\n - torch.sqrt((points**2).sum(dim=-1)) / self.cfg.density_blob_std\n )[..., None]\n )\n elif isinstance(self.cfg.density_bias, float):\n density_bias = self.cfg.density_bias\n else:\n raise ValueError(f\"Unknown density bias {self.cfg.density_bias}\")\n raw_density: Float[Tensor, \"*N 1\"] = density + density_bias\n density = get_activation(self.cfg.density_activation)(raw_density)\n return raw_density, density\n\n def forward(\n self, points: Float[Tensor, \"*N Di\"], output_normal: bool = False\n ) -> Dict[str, Float[Tensor, \"...\"]]:\n grad_enabled = torch.is_grad_enabled()\n\n if output_normal and self.cfg.normal_type == \"analytic\":\n torch.set_grad_enabled(True)\n points.requires_grad_(True)\n\n points_unscaled = points # points in the original scale\n points = contract_to_unisphere(\n points, self.bbox, self.unbounded\n ) # points normalized to (0, 1)\n\n enc = self.encoding(points.view(-1, self.cfg.n_input_dims))\n density = self.density_network(enc).view(*points.shape[:-1], 1)\n raw_density, density = self.get_activated_density(points_unscaled, density)\n\n output = {\n \"density\": density,\n }\n\n if self.cfg.n_feature_dims > 0:\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n output.update({\"features\": features})\n\n if output_normal:\n if (\n self.cfg.normal_type == \"finite_difference\"\n or self.cfg.normal_type == \"finite_difference_laplacian\"\n ):\n # TODO: use raw density\n eps = self.cfg.finite_difference_normal_eps\n if self.cfg.normal_type == \"finite_difference_laplacian\":\n offsets: Float[Tensor, \"6 3\"] = torch.as_tensor(\n [\n [eps, 0.0, 0.0],\n [-eps, 0.0, 0.0],\n [0.0, eps, 0.0],\n [0.0, -eps, 0.0],\n [0.0, 0.0, eps],\n [0.0, 0.0, -eps],\n ]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 6 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n density_offset: Float[Tensor, \"... 6 1\"] = self.forward_density(\n points_offset\n )\n normal = (\n -0.5\n * (density_offset[..., 0::2, 0] - density_offset[..., 1::2, 0])\n / eps\n )\n else:\n offsets: Float[Tensor, \"3 3\"] = torch.as_tensor(\n [[eps, 0.0, 0.0], [0.0, eps, 0.0], [0.0, 0.0, eps]]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 3 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n density_offset: Float[Tensor, \"... 3 1\"] = self.forward_density(\n points_offset\n )\n normal = -(density_offset[..., 0::1, 0] - density) / eps\n normal = F.normalize(normal, dim=-1)\n elif self.cfg.normal_type == \"pred\":\n normal = self.normal_network(enc).view(*points.shape[:-1], 3)\n normal = F.normalize(normal, dim=-1)\n elif self.cfg.normal_type == \"analytic\":\n normal = -torch.autograd.grad(\n density,\n points_unscaled,\n grad_outputs=torch.ones_like(density),\n create_graph=True,\n )[0]\n normal = F.normalize(normal, dim=-1)\n if not grad_enabled:\n normal = normal.detach()\n else:\n raise AttributeError(f\"Unknown normal type {self.cfg.normal_type}\")\n output.update({\"normal\": normal, \"shading_normal\": normal})\n\n torch.set_grad_enabled(grad_enabled)\n return output\n\n def forward_density(self, points: Float[Tensor, \"*N Di\"]) -> Float[Tensor, \"*N 1\"]:\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n\n density = self.density_network(\n self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n ).reshape(*points.shape[:-1], 1)\n\n _, density = self.get_activated_density(points_unscaled, density)\n return density\n\n def forward_field(\n self, points: Float[Tensor, \"*N Di\"]\n ) -> Tuple[Float[Tensor, \"*N 1\"], Optional[Float[Tensor, \"*N 3\"]]]:\n if self.cfg.isosurface_deformable_grid:\n threestudio.warn(\n f\"{self.__class__.__name__} does not support isosurface_deformable_grid. Ignoring.\"\n )\n density = self.forward_density(points)\n return density, None\n\n def forward_level(\n self, field: Float[Tensor, \"*N 1\"], threshold: float\n ) -> Float[Tensor, \"*N 1\"]:\n return -(field - threshold)\n\n def export(self, points: Float[Tensor, \"*N Di\"], **kwargs) -> Dict[str, Any]:\n out: Dict[str, Any] = {}\n if self.cfg.n_feature_dims == 0:\n return out\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n out.update(\n {\n \"features\": features,\n }\n )\n return out\n\n @staticmethod\n @torch.no_grad()\n def create_from(\n other: BaseGeometry,\n cfg: Optional[Union[dict, DictConfig]] = None,\n copy_net: bool = True,\n **kwargs,\n ) -> \"ImplicitVolume\":\n if isinstance(other, ImplicitVolume):\n instance = ImplicitVolume(cfg, **kwargs)\n instance.encoding.load_state_dict(other.encoding.state_dict())\n instance.density_network.load_state_dict(other.density_network.state_dict())\n if copy_net:\n if (\n instance.cfg.n_feature_dims > 0\n and other.cfg.n_feature_dims == instance.cfg.n_feature_dims\n ):\n instance.feature_network.load_state_dict(\n other.feature_network.state_dict()\n )\n if (\n instance.cfg.normal_type == \"pred\"\n and other.cfg.normal_type == \"pred\"\n ):\n instance.normal_network.load_state_dict(\n other.normal_network.state_dict()\n )\n return instance\n else:\n raise TypeError(\n f\"Cannot create {ImplicitVolume.__name__} from {other.__class__.__name__}\"\n )" }, { "identifier": "MarchingTetrahedraHelper", "path": "threestudio/models/isosurface.py", "snippet": "class MarchingTetrahedraHelper(IsosurfaceHelper):\n def __init__(self, resolution: int, tets_path: str):\n super().__init__()\n self.resolution = resolution\n self.tets_path = tets_path\n\n self.triangle_table: Float[Tensor, \"...\"]\n self.register_buffer(\n \"triangle_table\",\n torch.as_tensor(\n [\n [-1, -1, -1, -1, -1, -1],\n [1, 0, 2, -1, -1, -1],\n [4, 0, 3, -1, -1, -1],\n [1, 4, 2, 1, 3, 4],\n [3, 1, 5, -1, -1, -1],\n [2, 3, 0, 2, 5, 3],\n [1, 4, 0, 1, 5, 4],\n [4, 2, 5, -1, -1, -1],\n [4, 5, 2, -1, -1, -1],\n [4, 1, 0, 4, 5, 1],\n [3, 2, 0, 3, 5, 2],\n [1, 3, 5, -1, -1, -1],\n [4, 1, 2, 4, 3, 1],\n [3, 0, 4, -1, -1, -1],\n [2, 0, 1, -1, -1, -1],\n [-1, -1, -1, -1, -1, -1],\n ],\n dtype=torch.long,\n ),\n persistent=False,\n )\n self.num_triangles_table: Integer[Tensor, \"...\"]\n self.register_buffer(\n \"num_triangles_table\",\n torch.as_tensor(\n [0, 1, 1, 2, 1, 2, 2, 1, 1, 2, 2, 1, 2, 1, 1, 0], dtype=torch.long\n ),\n persistent=False,\n )\n self.base_tet_edges: Integer[Tensor, \"...\"]\n self.register_buffer(\n \"base_tet_edges\",\n torch.as_tensor([0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3], dtype=torch.long),\n persistent=False,\n )\n\n tets = np.load(self.tets_path)\n self._grid_vertices: Float[Tensor, \"...\"]\n self.register_buffer(\n \"_grid_vertices\",\n torch.from_numpy(tets[\"vertices\"]).float(),\n persistent=False,\n )\n self.indices: Integer[Tensor, \"...\"]\n self.register_buffer(\n \"indices\", torch.from_numpy(tets[\"indices\"]).long(), persistent=False\n )\n\n self._all_edges: Optional[Integer[Tensor, \"Ne 2\"]] = None\n\n def normalize_grid_deformation(\n self, grid_vertex_offsets: Float[Tensor, \"Nv 3\"]\n ) -> Float[Tensor, \"Nv 3\"]:\n return (\n (self.points_range[1] - self.points_range[0])\n / (self.resolution) # half tet size is approximately 1 / self.resolution\n * torch.tanh(grid_vertex_offsets)\n ) # FIXME: hard-coded activation\n\n @property\n def grid_vertices(self) -> Float[Tensor, \"Nv 3\"]:\n return self._grid_vertices\n\n @property\n def all_edges(self) -> Integer[Tensor, \"Ne 2\"]:\n if self._all_edges is None:\n # compute edges on GPU, or it would be VERY SLOW (basically due to the unique operation)\n edges = torch.tensor(\n [0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3],\n dtype=torch.long,\n device=self.indices.device,\n )\n _all_edges = self.indices[:, edges].reshape(-1, 2)\n _all_edges_sorted = torch.sort(_all_edges, dim=1)[0]\n _all_edges = torch.unique(_all_edges_sorted, dim=0)\n self._all_edges = _all_edges\n return self._all_edges\n\n def sort_edges(self, edges_ex2):\n with torch.no_grad():\n order = (edges_ex2[:, 0] > edges_ex2[:, 1]).long()\n order = order.unsqueeze(dim=1)\n\n a = torch.gather(input=edges_ex2, index=order, dim=1)\n b = torch.gather(input=edges_ex2, index=1 - order, dim=1)\n\n return torch.stack([a, b], -1)\n\n def _forward(self, pos_nx3, sdf_n, tet_fx4):\n with torch.no_grad():\n occ_n = sdf_n > 0\n occ_fx4 = occ_n[tet_fx4.reshape(-1)].reshape(-1, 4)\n occ_sum = torch.sum(occ_fx4, -1)\n valid_tets = (occ_sum > 0) & (occ_sum < 4)\n occ_sum = occ_sum[valid_tets]\n\n # find all vertices\n all_edges = tet_fx4[valid_tets][:, self.base_tet_edges].reshape(-1, 2)\n all_edges = self.sort_edges(all_edges)\n unique_edges, idx_map = torch.unique(all_edges, dim=0, return_inverse=True)\n\n unique_edges = unique_edges.long()\n mask_edges = occ_n[unique_edges.reshape(-1)].reshape(-1, 2).sum(-1) == 1\n mapping = (\n torch.ones(\n (unique_edges.shape[0]), dtype=torch.long, device=pos_nx3.device\n )\n * -1\n )\n mapping[mask_edges] = torch.arange(\n mask_edges.sum(), dtype=torch.long, device=pos_nx3.device\n )\n idx_map = mapping[idx_map] # map edges to verts\n\n interp_v = unique_edges[mask_edges]\n edges_to_interp = pos_nx3[interp_v.reshape(-1)].reshape(-1, 2, 3)\n edges_to_interp_sdf = sdf_n[interp_v.reshape(-1)].reshape(-1, 2, 1)\n edges_to_interp_sdf[:, -1] *= -1\n\n denominator = edges_to_interp_sdf.sum(1, keepdim=True)\n\n edges_to_interp_sdf = torch.flip(edges_to_interp_sdf, [1]) / denominator\n verts = (edges_to_interp * edges_to_interp_sdf).sum(1)\n\n idx_map = idx_map.reshape(-1, 6)\n\n v_id = torch.pow(2, torch.arange(4, dtype=torch.long, device=pos_nx3.device))\n tetindex = (occ_fx4[valid_tets] * v_id.unsqueeze(0)).sum(-1)\n num_triangles = self.num_triangles_table[tetindex]\n\n # Generate triangle indices\n faces = torch.cat(\n (\n torch.gather(\n input=idx_map[num_triangles == 1],\n dim=1,\n index=self.triangle_table[tetindex[num_triangles == 1]][:, :3],\n ).reshape(-1, 3),\n torch.gather(\n input=idx_map[num_triangles == 2],\n dim=1,\n index=self.triangle_table[tetindex[num_triangles == 2]][:, :6],\n ).reshape(-1, 3),\n ),\n dim=0,\n )\n\n return verts, faces\n\n def forward(\n self,\n level: Float[Tensor, \"N3 1\"],\n deformation: Optional[Float[Tensor, \"N3 3\"]] = None,\n ) -> Mesh:\n if deformation is not None:\n grid_vertices = self.grid_vertices + self.normalize_grid_deformation(\n deformation\n )\n else:\n grid_vertices = self.grid_vertices\n\n v_pos, t_pos_idx = self._forward(grid_vertices, level, self.indices)\n\n mesh = Mesh(\n v_pos=v_pos,\n t_pos_idx=t_pos_idx,\n # extras\n grid_vertices=grid_vertices,\n tet_edges=self.all_edges,\n grid_level=level,\n grid_deformation=deformation,\n )\n\n return mesh" }, { "identifier": "Mesh", "path": "threestudio/models/mesh.py", "snippet": "class Mesh:\n def __init__(\n self, v_pos: Float[Tensor, \"Nv 3\"], t_pos_idx: Integer[Tensor, \"Nf 3\"], **kwargs\n ) -> None:\n self.v_pos: Float[Tensor, \"Nv 3\"] = v_pos\n self.t_pos_idx: Integer[Tensor, \"Nf 3\"] = t_pos_idx\n self._v_nrm: Optional[Float[Tensor, \"Nv 3\"]] = None\n self._v_tng: Optional[Float[Tensor, \"Nv 3\"]] = None\n self._v_tex: Optional[Float[Tensor, \"Nt 3\"]] = None\n self._t_tex_idx: Optional[Float[Tensor, \"Nf 3\"]] = None\n self._v_rgb: Optional[Float[Tensor, \"Nv 3\"]] = None\n self._edges: Optional[Integer[Tensor, \"Ne 2\"]] = None\n self.extras: Dict[str, Any] = {}\n for k, v in kwargs.items():\n self.add_extra(k, v)\n\n def add_extra(self, k, v) -> None:\n self.extras[k] = v\n\n def remove_outlier(self, outlier_n_faces_threshold: Union[int, float]) -> Mesh:\n if self.requires_grad:\n threestudio.debug(\"Mesh is differentiable, not removing outliers\")\n return self\n\n # use trimesh to first split the mesh into connected components\n # then remove the components with less than n_face_threshold faces\n import trimesh\n\n # construct a trimesh object\n mesh = trimesh.Trimesh(\n vertices=self.v_pos.detach().cpu().numpy(),\n faces=self.t_pos_idx.detach().cpu().numpy(),\n )\n\n # split the mesh into connected components\n components = mesh.split(only_watertight=False)\n # log the number of faces in each component\n threestudio.debug(\n \"Mesh has {} components, with faces: {}\".format(\n len(components), [c.faces.shape[0] for c in components]\n )\n )\n\n n_faces_threshold: int\n if isinstance(outlier_n_faces_threshold, float):\n # set the threshold to the number of faces in the largest component multiplied by outlier_n_faces_threshold\n n_faces_threshold = int(\n max([c.faces.shape[0] for c in components]) * outlier_n_faces_threshold\n )\n else:\n # set the threshold directly to outlier_n_faces_threshold\n n_faces_threshold = outlier_n_faces_threshold\n\n # log the threshold\n threestudio.debug(\n \"Removing components with less than {} faces\".format(n_faces_threshold)\n )\n\n # remove the components with less than n_face_threshold faces\n components = [c for c in components if c.faces.shape[0] >= n_faces_threshold]\n\n # log the number of faces in each component after removing outliers\n threestudio.debug(\n \"Mesh has {} components after removing outliers, with faces: {}\".format(\n len(components), [c.faces.shape[0] for c in components]\n )\n )\n # merge the components\n mesh = trimesh.util.concatenate(components)\n\n # convert back to our mesh format\n v_pos = torch.from_numpy(mesh.vertices).to(self.v_pos)\n t_pos_idx = torch.from_numpy(mesh.faces).to(self.t_pos_idx)\n\n clean_mesh = Mesh(v_pos, t_pos_idx)\n # keep the extras unchanged\n\n if len(self.extras) > 0:\n clean_mesh.extras = self.extras\n threestudio.debug(\n f\"The following extra attributes are inherited from the original mesh unchanged: {list(self.extras.keys())}\"\n )\n return clean_mesh\n\n @property\n def requires_grad(self):\n return self.v_pos.requires_grad\n\n @property\n def v_nrm(self):\n if self._v_nrm is None:\n self._v_nrm = self._compute_vertex_normal()\n return self._v_nrm\n\n @property\n def v_tng(self):\n if self._v_tng is None:\n self._v_tng = self._compute_vertex_tangent()\n return self._v_tng\n\n @property\n def v_tex(self):\n if self._v_tex is None:\n self._v_tex, self._t_tex_idx = self._unwrap_uv()\n return self._v_tex\n\n @property\n def t_tex_idx(self):\n if self._t_tex_idx is None:\n self._v_tex, self._t_tex_idx = self._unwrap_uv()\n return self._t_tex_idx\n\n @property\n def v_rgb(self):\n return self._v_rgb\n\n @property\n def edges(self):\n if self._edges is None:\n self._edges = self._compute_edges()\n return self._edges\n\n def _compute_vertex_normal(self):\n i0 = self.t_pos_idx[:, 0]\n i1 = self.t_pos_idx[:, 1]\n i2 = self.t_pos_idx[:, 2]\n\n v0 = self.v_pos[i0, :]\n v1 = self.v_pos[i1, :]\n v2 = self.v_pos[i2, :]\n\n face_normals = torch.cross(v1 - v0, v2 - v0)\n\n # Splat face normals to vertices\n v_nrm = torch.zeros_like(self.v_pos)\n v_nrm.scatter_add_(0, i0[:, None].repeat(1, 3), face_normals)\n v_nrm.scatter_add_(0, i1[:, None].repeat(1, 3), face_normals)\n v_nrm.scatter_add_(0, i2[:, None].repeat(1, 3), face_normals)\n\n # Normalize, replace zero (degenerated) normals with some default value\n v_nrm = torch.where(\n dot(v_nrm, v_nrm) > 1e-20, v_nrm, torch.as_tensor([0.0, 0.0, 1.0]).to(v_nrm)\n )\n v_nrm = F.normalize(v_nrm, dim=1)\n\n if torch.is_anomaly_enabled():\n assert torch.all(torch.isfinite(v_nrm))\n\n return v_nrm\n\n def _compute_vertex_tangent(self):\n vn_idx = [None] * 3\n pos = [None] * 3\n tex = [None] * 3\n for i in range(0, 3):\n pos[i] = self.v_pos[self.t_pos_idx[:, i]]\n tex[i] = self.v_tex[self.t_tex_idx[:, i]]\n # t_nrm_idx is always the same as t_pos_idx\n vn_idx[i] = self.t_pos_idx[:, i]\n\n tangents = torch.zeros_like(self.v_nrm)\n tansum = torch.zeros_like(self.v_nrm)\n\n # Compute tangent space for each triangle\n uve1 = tex[1] - tex[0]\n uve2 = tex[2] - tex[0]\n pe1 = pos[1] - pos[0]\n pe2 = pos[2] - pos[0]\n\n nom = pe1 * uve2[..., 1:2] - pe2 * uve1[..., 1:2]\n denom = uve1[..., 0:1] * uve2[..., 1:2] - uve1[..., 1:2] * uve2[..., 0:1]\n\n # Avoid division by zero for degenerated texture coordinates\n tang = nom / torch.where(\n denom > 0.0, torch.clamp(denom, min=1e-6), torch.clamp(denom, max=-1e-6)\n )\n\n # Update all 3 vertices\n for i in range(0, 3):\n idx = vn_idx[i][:, None].repeat(1, 3)\n tangents.scatter_add_(0, idx, tang) # tangents[n_i] = tangents[n_i] + tang\n tansum.scatter_add_(\n 0, idx, torch.ones_like(tang)\n ) # tansum[n_i] = tansum[n_i] + 1\n tangents = tangents / tansum\n\n # Normalize and make sure tangent is perpendicular to normal\n tangents = F.normalize(tangents, dim=1)\n tangents = F.normalize(tangents - dot(tangents, self.v_nrm) * self.v_nrm)\n\n if torch.is_anomaly_enabled():\n assert torch.all(torch.isfinite(tangents))\n\n return tangents\n\n def _unwrap_uv(\n self, xatlas_chart_options: dict = {}, xatlas_pack_options: dict = {}\n ):\n threestudio.info(\"Using xatlas to perform UV unwrapping, may take a while ...\")\n\n import xatlas\n\n atlas = xatlas.Atlas()\n atlas.add_mesh(\n self.v_pos.detach().cpu().numpy(),\n self.t_pos_idx.cpu().numpy(),\n )\n co = xatlas.ChartOptions()\n po = xatlas.PackOptions()\n for k, v in xatlas_chart_options.items():\n setattr(co, k, v)\n for k, v in xatlas_pack_options.items():\n setattr(po, k, v)\n atlas.generate(co, po)\n vmapping, indices, uvs = atlas.get_mesh(0)\n vmapping = (\n torch.from_numpy(\n vmapping.astype(np.uint64, casting=\"same_kind\").view(np.int64)\n )\n .to(self.v_pos.device)\n .long()\n )\n uvs = torch.from_numpy(uvs).to(self.v_pos.device).float()\n indices = (\n torch.from_numpy(\n indices.astype(np.uint64, casting=\"same_kind\").view(np.int64)\n )\n .to(self.v_pos.device)\n .long()\n )\n return uvs, indices\n\n def unwrap_uv(\n self, xatlas_chart_options: dict = {}, xatlas_pack_options: dict = {}\n ):\n self._v_tex, self._t_tex_idx = self._unwrap_uv(\n xatlas_chart_options, xatlas_pack_options\n )\n\n def set_vertex_color(self, v_rgb):\n assert v_rgb.shape[0] == self.v_pos.shape[0]\n self._v_rgb = v_rgb\n\n def _compute_edges(self):\n # Compute edges\n edges = torch.cat(\n [\n self.t_pos_idx[:, [0, 1]],\n self.t_pos_idx[:, [1, 2]],\n self.t_pos_idx[:, [2, 0]],\n ],\n dim=0,\n )\n edges = edges.sort()[0]\n edges = torch.unique(edges, dim=0)\n return edges\n\n def normal_consistency(self) -> Float[Tensor, \"\"]:\n edge_nrm: Float[Tensor, \"Ne 2 3\"] = self.v_nrm[self.edges]\n nc = (\n 1.0 - torch.cosine_similarity(edge_nrm[:, 0], edge_nrm[:, 1], dim=-1)\n ).mean()\n return nc\n\n def _laplacian_uniform(self):\n # from stable-dreamfusion\n # https://github.com/ashawkey/stable-dreamfusion/blob/8fb3613e9e4cd1ded1066b46e80ca801dfb9fd06/nerf/renderer.py#L224\n verts, faces = self.v_pos, self.t_pos_idx\n\n V = verts.shape[0]\n F = faces.shape[0]\n\n # Neighbor indices\n ii = faces[:, [1, 2, 0]].flatten()\n jj = faces[:, [2, 0, 1]].flatten()\n adj = torch.stack([torch.cat([ii, jj]), torch.cat([jj, ii])], dim=0).unique(\n dim=1\n )\n adj_values = torch.ones(adj.shape[1]).to(verts)\n\n # Diagonal indices\n diag_idx = adj[0]\n\n # Build the sparse matrix\n idx = torch.cat((adj, torch.stack((diag_idx, diag_idx), dim=0)), dim=1)\n values = torch.cat((-adj_values, adj_values))\n\n # The coalesce operation sums the duplicate indices, resulting in the\n # correct diagonal\n return torch.sparse_coo_tensor(idx, values, (V, V)).coalesce()\n\n def laplacian(self) -> Float[Tensor, \"\"]:\n with torch.no_grad():\n L = self._laplacian_uniform()\n loss = L.mm(self.v_pos)\n loss = loss.norm(dim=1)\n loss = loss.mean()\n return loss" }, { "identifier": "get_encoding", "path": "threestudio/models/networks.py", "snippet": "def get_encoding(n_input_dims: int, config) -> nn.Module:\n # input suppose to be range [0, 1]\n encoding: nn.Module\n if config.otype == \"ProgressiveBandFrequency\":\n encoding = ProgressiveBandFrequency(n_input_dims, config_to_primitive(config))\n elif config.otype == \"ProgressiveBandHashGrid\":\n encoding = ProgressiveBandHashGrid(n_input_dims, config_to_primitive(config))\n else:\n encoding = TCNNEncoding(n_input_dims, config_to_primitive(config))\n encoding = CompositeEncoding(\n encoding,\n include_xyz=config.get(\"include_xyz\", False),\n xyz_scale=2.0,\n xyz_offset=-1.0,\n ) # FIXME: hard coded\n return encoding" }, { "identifier": "get_mlp", "path": "threestudio/models/networks.py", "snippet": "def get_mlp(n_input_dims, n_output_dims, config) -> nn.Module:\n network: nn.Module\n if config.otype == \"VanillaMLP\":\n network = VanillaMLP(n_input_dims, n_output_dims, config_to_primitive(config))\n elif config.otype == \"SphereInitVanillaMLP\":\n network = SphereInitVanillaMLP(\n n_input_dims, n_output_dims, config_to_primitive(config)\n )\n else:\n assert (\n config.get(\"sphere_init\", False) is False\n ), \"sphere_init=True only supported by VanillaMLP\"\n network = TCNNNetwork(n_input_dims, n_output_dims, config_to_primitive(config))\n return network" }, { "identifier": "broadcast", "path": "threestudio/utils/misc.py", "snippet": "def broadcast(tensor, src=0):\n if not _distributed_available():\n return tensor\n else:\n torch.distributed.broadcast(tensor, src=src)\n return tensor" }, { "identifier": "scale_tensor", "path": "threestudio/utils/ops.py", "snippet": "def scale_tensor(\n dat: Num[Tensor, \"... D\"], inp_scale: ValidScale, tgt_scale: ValidScale\n):\n if inp_scale is None:\n inp_scale = (0, 1)\n if tgt_scale is None:\n tgt_scale = (0, 1)\n if isinstance(tgt_scale, Tensor):\n assert dat.shape[-1] == tgt_scale.shape[-1]\n dat = (dat - inp_scale[0]) / (inp_scale[1] - inp_scale[0])\n dat = dat * (tgt_scale[1] - tgt_scale[0]) + tgt_scale[0]\n return dat" } ]
import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import threestudio import trimesh from dataclasses import dataclass, field from threestudio.models.geometry.base import ( BaseExplicitGeometry, BaseGeometry, contract_to_unisphere, ) from threestudio.models.geometry.implicit_sdf import ImplicitSDF from threestudio.models.geometry.implicit_volume import ImplicitVolume from threestudio.models.isosurface import MarchingTetrahedraHelper from threestudio.models.mesh import Mesh from threestudio.models.networks import get_encoding, get_mlp from threestudio.utils.misc import broadcast from threestudio.utils.ops import scale_tensor from threestudio.utils.typing import * from pysdf import SDF
14,711
self.deformation = None if not self.cfg.geometry_only: self.encoding = get_encoding( self.cfg.n_input_dims, self.cfg.pos_encoding_config ) self.feature_network = get_mlp( self.encoding.n_output_dims, self.cfg.n_feature_dims, self.cfg.mlp_network_config, ) self.mesh: Optional[Mesh] = None def initialize_shape(self) -> None: if self.cfg.shape_init is None and not self.cfg.force_shape_init: return # do not initialize shape if weights are provided if self.cfg.weights is not None and not self.cfg.force_shape_init: return get_gt_sdf: Callable[[Float[Tensor, "N 3"]], Float[Tensor, "N 1"]] assert isinstance(self.cfg.shape_init, str) if self.cfg.shape_init == "ellipsoid": assert ( isinstance(self.cfg.shape_init_params, Sized) and len(self.cfg.shape_init_params) == 3 ) size = torch.as_tensor(self.cfg.shape_init_params).to(self.device) def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]: return ((points_rand / size) ** 2).sum( dim=-1, keepdim=True ).sqrt() - 1.0 # pseudo signed distance of an ellipsoid get_gt_sdf = func elif self.cfg.shape_init == "sphere": assert isinstance(self.cfg.shape_init_params, float) radius = self.cfg.shape_init_params def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]: return (points_rand**2).sum(dim=-1, keepdim=True).sqrt() - radius get_gt_sdf = func elif self.cfg.shape_init.startswith("mesh:"): assert isinstance(self.cfg.shape_init_params, float) mesh_path = self.cfg.shape_init[5:] if not os.path.exists(mesh_path): raise ValueError(f"Mesh file {mesh_path} does not exist.") mesh = trimesh.load(mesh_path) # move to center centroid = mesh.vertices.mean(0) mesh.vertices = mesh.vertices - centroid # align to up-z and front-x dirs = ["+x", "+y", "+z", "-x", "-y", "-z"] dir2vec = { "+x": np.array([1, 0, 0]), "+y": np.array([0, 1, 0]), "+z": np.array([0, 0, 1]), "-x": np.array([-1, 0, 0]), "-y": np.array([0, -1, 0]), "-z": np.array([0, 0, -1]), } if ( self.cfg.shape_init_mesh_up not in dirs or self.cfg.shape_init_mesh_front not in dirs ): raise ValueError( f"shape_init_mesh_up and shape_init_mesh_front must be one of {dirs}." ) if self.cfg.shape_init_mesh_up[1] == self.cfg.shape_init_mesh_front[1]: raise ValueError( "shape_init_mesh_up and shape_init_mesh_front must be orthogonal." ) z_, x_ = ( dir2vec[self.cfg.shape_init_mesh_up], dir2vec[self.cfg.shape_init_mesh_front], ) y_ = np.cross(z_, x_) std2mesh = np.stack([x_, y_, z_], axis=0).T mesh2std = np.linalg.inv(std2mesh) # scaling scale = np.abs(mesh.vertices).max() mesh.vertices = mesh.vertices / scale * self.cfg.shape_init_params mesh.vertices = np.dot(mesh2std, mesh.vertices.T).T sdf = SDF(mesh.vertices, mesh.faces) def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]: # add a negative signed here # as in pysdf the inside of the shape has positive signed distance return torch.from_numpy(-sdf(points_rand.cpu().numpy())).to( points_rand )[..., None] get_gt_sdf = func else: raise ValueError( f"Unknown shape initialization type: {self.cfg.shape_init}" ) sdf_gt = get_gt_sdf( scale_tensor( self.isosurface_helper.grid_vertices, self.isosurface_helper.points_range, self.isosurface_bbox, ) ) self.sdf.data = sdf_gt # explicit broadcast to ensure param consistency across ranks for param in self.parameters():
@threestudio.register("tetrahedra-sdf-grid") class TetrahedraSDFGrid(BaseExplicitGeometry): @dataclass class Config(BaseExplicitGeometry.Config): isosurface_resolution: int = 128 isosurface_deformable_grid: bool = True isosurface_remove_outliers: bool = False isosurface_outlier_n_faces_threshold: Union[int, float] = 0.01 n_input_dims: int = 3 n_feature_dims: int = 3 pos_encoding_config: dict = field( default_factory=lambda: { "otype": "HashGrid", "n_levels": 16, "n_features_per_level": 2, "log2_hashmap_size": 19, "base_resolution": 16, "per_level_scale": 1.447269237440378, } ) mlp_network_config: dict = field( default_factory=lambda: { "otype": "VanillaMLP", "activation": "ReLU", "output_activation": "none", "n_neurons": 64, "n_hidden_layers": 1, } ) shape_init: Optional[str] = None shape_init_params: Optional[Any] = None shape_init_mesh_up: str = "+z" shape_init_mesh_front: str = "+x" force_shape_init: bool = False geometry_only: bool = False fix_geometry: bool = False cfg: Config def configure(self) -> None: super().configure() # this should be saved to state_dict, register as buffer self.isosurface_bbox: Float[Tensor, "2 3"] self.register_buffer("isosurface_bbox", self.bbox.clone()) self.isosurface_helper = MarchingTetrahedraHelper( self.cfg.isosurface_resolution, f"load/tets/{self.cfg.isosurface_resolution}_tets.npz", ) self.sdf: Float[Tensor, "Nv 1"] self.deformation: Optional[Float[Tensor, "Nv 3"]] if not self.cfg.fix_geometry: self.register_parameter( "sdf", nn.Parameter( torch.zeros( (self.isosurface_helper.grid_vertices.shape[0], 1), dtype=torch.float32, ) ), ) if self.cfg.isosurface_deformable_grid: self.register_parameter( "deformation", nn.Parameter( torch.zeros_like(self.isosurface_helper.grid_vertices) ), ) else: self.deformation = None else: self.register_buffer( "sdf", torch.zeros( (self.isosurface_helper.grid_vertices.shape[0], 1), dtype=torch.float32, ), ) if self.cfg.isosurface_deformable_grid: self.register_buffer( "deformation", torch.zeros_like(self.isosurface_helper.grid_vertices), ) else: self.deformation = None if not self.cfg.geometry_only: self.encoding = get_encoding( self.cfg.n_input_dims, self.cfg.pos_encoding_config ) self.feature_network = get_mlp( self.encoding.n_output_dims, self.cfg.n_feature_dims, self.cfg.mlp_network_config, ) self.mesh: Optional[Mesh] = None def initialize_shape(self) -> None: if self.cfg.shape_init is None and not self.cfg.force_shape_init: return # do not initialize shape if weights are provided if self.cfg.weights is not None and not self.cfg.force_shape_init: return get_gt_sdf: Callable[[Float[Tensor, "N 3"]], Float[Tensor, "N 1"]] assert isinstance(self.cfg.shape_init, str) if self.cfg.shape_init == "ellipsoid": assert ( isinstance(self.cfg.shape_init_params, Sized) and len(self.cfg.shape_init_params) == 3 ) size = torch.as_tensor(self.cfg.shape_init_params).to(self.device) def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]: return ((points_rand / size) ** 2).sum( dim=-1, keepdim=True ).sqrt() - 1.0 # pseudo signed distance of an ellipsoid get_gt_sdf = func elif self.cfg.shape_init == "sphere": assert isinstance(self.cfg.shape_init_params, float) radius = self.cfg.shape_init_params def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]: return (points_rand**2).sum(dim=-1, keepdim=True).sqrt() - radius get_gt_sdf = func elif self.cfg.shape_init.startswith("mesh:"): assert isinstance(self.cfg.shape_init_params, float) mesh_path = self.cfg.shape_init[5:] if not os.path.exists(mesh_path): raise ValueError(f"Mesh file {mesh_path} does not exist.") mesh = trimesh.load(mesh_path) # move to center centroid = mesh.vertices.mean(0) mesh.vertices = mesh.vertices - centroid # align to up-z and front-x dirs = ["+x", "+y", "+z", "-x", "-y", "-z"] dir2vec = { "+x": np.array([1, 0, 0]), "+y": np.array([0, 1, 0]), "+z": np.array([0, 0, 1]), "-x": np.array([-1, 0, 0]), "-y": np.array([0, -1, 0]), "-z": np.array([0, 0, -1]), } if ( self.cfg.shape_init_mesh_up not in dirs or self.cfg.shape_init_mesh_front not in dirs ): raise ValueError( f"shape_init_mesh_up and shape_init_mesh_front must be one of {dirs}." ) if self.cfg.shape_init_mesh_up[1] == self.cfg.shape_init_mesh_front[1]: raise ValueError( "shape_init_mesh_up and shape_init_mesh_front must be orthogonal." ) z_, x_ = ( dir2vec[self.cfg.shape_init_mesh_up], dir2vec[self.cfg.shape_init_mesh_front], ) y_ = np.cross(z_, x_) std2mesh = np.stack([x_, y_, z_], axis=0).T mesh2std = np.linalg.inv(std2mesh) # scaling scale = np.abs(mesh.vertices).max() mesh.vertices = mesh.vertices / scale * self.cfg.shape_init_params mesh.vertices = np.dot(mesh2std, mesh.vertices.T).T sdf = SDF(mesh.vertices, mesh.faces) def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]: # add a negative signed here # as in pysdf the inside of the shape has positive signed distance return torch.from_numpy(-sdf(points_rand.cpu().numpy())).to( points_rand )[..., None] get_gt_sdf = func else: raise ValueError( f"Unknown shape initialization type: {self.cfg.shape_init}" ) sdf_gt = get_gt_sdf( scale_tensor( self.isosurface_helper.grid_vertices, self.isosurface_helper.points_range, self.isosurface_bbox, ) ) self.sdf.data = sdf_gt # explicit broadcast to ensure param consistency across ranks for param in self.parameters():
broadcast(param, src=0)
9
2023-11-27 02:39:39+00:00
24k
EricGuo5513/momask-codes
gen_t2m.py
[ { "identifier": "MaskTransformer", "path": "models/mask_transformer/transformer.py", "snippet": "class MaskTransformer(nn.Module):\n def __init__(self, code_dim, cond_mode, latent_dim=256, ff_size=1024, num_layers=8,\n num_heads=4, dropout=0.1, clip_dim=512, cond_drop_prob=0.1,\n clip_version=None, opt=None, **kargs):\n super(MaskTransformer, self).__init__()\n print(f'latent_dim: {latent_dim}, ff_size: {ff_size}, nlayers: {num_layers}, nheads: {num_heads}, dropout: {dropout}')\n\n self.code_dim = code_dim\n self.latent_dim = latent_dim\n self.clip_dim = clip_dim\n self.dropout = dropout\n self.opt = opt\n\n self.cond_mode = cond_mode\n self.cond_drop_prob = cond_drop_prob\n\n if self.cond_mode == 'action':\n assert 'num_actions' in kargs\n self.num_actions = kargs.get('num_actions', 1)\n\n '''\n Preparing Networks\n '''\n self.input_process = InputProcess(self.code_dim, self.latent_dim)\n self.position_enc = PositionalEncoding(self.latent_dim, self.dropout)\n\n seqTransEncoderLayer = nn.TransformerEncoderLayer(d_model=self.latent_dim,\n nhead=num_heads,\n dim_feedforward=ff_size,\n dropout=dropout,\n activation='gelu')\n\n self.seqTransEncoder = nn.TransformerEncoder(seqTransEncoderLayer,\n num_layers=num_layers)\n\n self.encode_action = partial(F.one_hot, num_classes=self.num_actions)\n\n # if self.cond_mode != 'no_cond':\n if self.cond_mode == 'text':\n self.cond_emb = nn.Linear(self.clip_dim, self.latent_dim)\n elif self.cond_mode == 'action':\n self.cond_emb = nn.Linear(self.num_actions, self.latent_dim)\n elif self.cond_mode == 'uncond':\n self.cond_emb = nn.Identity()\n else:\n raise KeyError(\"Unsupported condition mode!!!\")\n\n\n _num_tokens = opt.num_tokens + 2 # two dummy tokens, one for masking, one for padding\n self.mask_id = opt.num_tokens\n self.pad_id = opt.num_tokens + 1\n\n self.output_process = OutputProcess_Bert(out_feats=opt.num_tokens, latent_dim=latent_dim)\n\n self.token_emb = nn.Embedding(_num_tokens, self.code_dim)\n\n self.apply(self.__init_weights)\n\n '''\n Preparing frozen weights\n '''\n\n if self.cond_mode == 'text':\n print('Loading CLIP...')\n self.clip_version = clip_version\n self.clip_model = self.load_and_freeze_clip(clip_version)\n\n self.noise_schedule = cosine_schedule\n\n def load_and_freeze_token_emb(self, codebook):\n '''\n :param codebook: (c, d)\n :return:\n '''\n assert self.training, 'Only necessary in training mode'\n c, d = codebook.shape\n self.token_emb.weight = nn.Parameter(torch.cat([codebook, torch.zeros(size=(2, d), device=codebook.device)], dim=0)) #add two dummy tokens, 0 vectors\n self.token_emb.requires_grad_(False)\n # self.token_emb.weight.requires_grad = False\n # self.token_emb_ready = True\n print(\"Token embedding initialized!\")\n\n def __init_weights(self, module):\n if isinstance(module, (nn.Linear, nn.Embedding)):\n module.weight.data.normal_(mean=0.0, std=0.02)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n\n def parameters_wo_clip(self):\n return [p for name, p in self.named_parameters() if not name.startswith('clip_model.')]\n\n def load_and_freeze_clip(self, clip_version):\n clip_model, clip_preprocess = clip.load(clip_version, device='cpu',\n jit=False) # Must set jit=False for training\n # Cannot run on cpu\n clip.model.convert_weights(\n clip_model) # Actually this line is unnecessary since clip by default already on float16\n # Date 0707: It's necessary, only unecessary when load directly to gpu. Disable if need to run on cpu\n\n # Freeze CLIP weights\n clip_model.eval()\n for p in clip_model.parameters():\n p.requires_grad = False\n\n return clip_model\n\n def encode_text(self, raw_text):\n device = next(self.parameters()).device\n text = clip.tokenize(raw_text, truncate=True).to(device)\n feat_clip_text = self.clip_model.encode_text(text).float()\n return feat_clip_text\n\n def mask_cond(self, cond, force_mask=False):\n bs, d = cond.shape\n if force_mask:\n return torch.zeros_like(cond)\n elif self.training and self.cond_drop_prob > 0.:\n mask = torch.bernoulli(torch.ones(bs, device=cond.device) * self.cond_drop_prob).view(bs, 1)\n return cond * (1. - mask)\n else:\n return cond\n\n def trans_forward(self, motion_ids, cond, padding_mask, force_mask=False):\n '''\n :param motion_ids: (b, seqlen)\n :padding_mask: (b, seqlen), all pad positions are TRUE else FALSE\n :param cond: (b, embed_dim) for text, (b, num_actions) for action\n :param force_mask: boolean\n :return:\n -logits: (b, num_token, seqlen)\n '''\n\n cond = self.mask_cond(cond, force_mask=force_mask)\n\n # print(motion_ids.shape)\n x = self.token_emb(motion_ids)\n # print(x.shape)\n # (b, seqlen, d) -> (seqlen, b, latent_dim)\n x = self.input_process(x)\n\n cond = self.cond_emb(cond).unsqueeze(0) #(1, b, latent_dim)\n\n x = self.position_enc(x)\n xseq = torch.cat([cond, x], dim=0) #(seqlen+1, b, latent_dim)\n\n padding_mask = torch.cat([torch.zeros_like(padding_mask[:, 0:1]), padding_mask], dim=1) #(b, seqlen+1)\n # print(xseq.shape, padding_mask.shape)\n\n # print(padding_mask.shape, xseq.shape)\n\n output = self.seqTransEncoder(xseq, src_key_padding_mask=padding_mask)[1:] #(seqlen, b, e)\n logits = self.output_process(output) #(seqlen, b, e) -> (b, ntoken, seqlen)\n return logits\n\n def forward(self, ids, y, m_lens):\n '''\n :param ids: (b, n)\n :param y: raw text for cond_mode=text, (b, ) for cond_mode=action\n :m_lens: (b,)\n :return:\n '''\n\n bs, ntokens = ids.shape\n device = ids.device\n\n # Positions that are PADDED are ALL FALSE\n non_pad_mask = lengths_to_mask(m_lens, ntokens) #(b, n)\n ids = torch.where(non_pad_mask, ids, self.pad_id)\n\n force_mask = False\n if self.cond_mode == 'text':\n with torch.no_grad():\n cond_vector = self.encode_text(y)\n elif self.cond_mode == 'action':\n cond_vector = self.enc_action(y).to(device).float()\n elif self.cond_mode == 'uncond':\n cond_vector = torch.zeros(bs, self.latent_dim).float().to(device)\n force_mask = True\n else:\n raise NotImplementedError(\"Unsupported condition mode!!!\")\n\n\n '''\n Prepare mask\n '''\n rand_time = uniform((bs,), device=device)\n rand_mask_probs = self.noise_schedule(rand_time)\n num_token_masked = (ntokens * rand_mask_probs).round().clamp(min=1)\n\n batch_randperm = torch.rand((bs, ntokens), device=device).argsort(dim=-1)\n # Positions to be MASKED are ALL TRUE\n mask = batch_randperm < num_token_masked.unsqueeze(-1)\n\n # Positions to be MASKED must also be NON-PADDED\n mask &= non_pad_mask\n\n # Note this is our training target, not input\n labels = torch.where(mask, ids, self.mask_id)\n\n x_ids = ids.clone()\n\n # Further Apply Bert Masking Scheme\n # Step 1: 10% replace with an incorrect token\n mask_rid = get_mask_subset_prob(mask, 0.1)\n rand_id = torch.randint_like(x_ids, high=self.opt.num_tokens)\n x_ids = torch.where(mask_rid, rand_id, x_ids)\n # Step 2: 90% x 10% replace with correct token, and 90% x 88% replace with mask token\n mask_mid = get_mask_subset_prob(mask & ~mask_rid, 0.88)\n\n # mask_mid = mask\n\n x_ids = torch.where(mask_mid, self.mask_id, x_ids)\n\n logits = self.trans_forward(x_ids, cond_vector, ~non_pad_mask, force_mask)\n ce_loss, pred_id, acc = cal_performance(logits, labels, ignore_index=self.mask_id)\n\n return ce_loss, pred_id, acc\n\n def forward_with_cond_scale(self,\n motion_ids,\n cond_vector,\n padding_mask,\n cond_scale=3,\n force_mask=False):\n # bs = motion_ids.shape[0]\n # if cond_scale == 1:\n if force_mask:\n return self.trans_forward(motion_ids, cond_vector, padding_mask, force_mask=True)\n\n logits = self.trans_forward(motion_ids, cond_vector, padding_mask)\n if cond_scale == 1:\n return logits\n\n aux_logits = self.trans_forward(motion_ids, cond_vector, padding_mask, force_mask=True)\n\n scaled_logits = aux_logits + (logits - aux_logits) * cond_scale\n return scaled_logits\n\n @torch.no_grad()\n @eval_decorator\n def generate(self,\n conds,\n m_lens,\n timesteps: int,\n cond_scale: int,\n temperature=1,\n topk_filter_thres=0.9,\n gsample=False,\n force_mask=False\n ):\n # print(self.opt.num_quantizers)\n # assert len(timesteps) >= len(cond_scales) == self.opt.num_quantizers\n\n device = next(self.parameters()).device\n seq_len = max(m_lens)\n batch_size = len(m_lens)\n\n if self.cond_mode == 'text':\n with torch.no_grad():\n cond_vector = self.encode_text(conds)\n elif self.cond_mode == 'action':\n cond_vector = self.enc_action(conds).to(device)\n elif self.cond_mode == 'uncond':\n cond_vector = torch.zeros(batch_size, self.latent_dim).float().to(device)\n else:\n raise NotImplementedError(\"Unsupported condition mode!!!\")\n\n padding_mask = ~lengths_to_mask(m_lens, seq_len)\n # print(padding_mask.shape, )\n\n # Start from all tokens being masked\n ids = torch.where(padding_mask, self.pad_id, self.mask_id)\n scores = torch.where(padding_mask, 1e5, 0.)\n starting_temperature = temperature\n\n for timestep, steps_until_x0 in zip(torch.linspace(0, 1, timesteps, device=device), reversed(range(timesteps))):\n # 0 < timestep < 1\n rand_mask_prob = self.noise_schedule(timestep) # Tensor\n\n '''\n Maskout, and cope with variable length\n '''\n # fix: the ratio regarding lengths, instead of seq_len\n num_token_masked = torch.round(rand_mask_prob * m_lens).clamp(min=1) # (b, )\n\n # select num_token_masked tokens with lowest scores to be masked\n sorted_indices = scores.argsort(\n dim=1) # (b, k), sorted_indices[i, j] = the index of j-th lowest element in scores on dim=1\n ranks = sorted_indices.argsort(dim=1) # (b, k), rank[i, j] = the rank (0: lowest) of scores[i, j] on dim=1\n is_mask = (ranks < num_token_masked.unsqueeze(-1))\n ids = torch.where(is_mask, self.mask_id, ids)\n\n '''\n Preparing input\n '''\n # (b, num_token, seqlen)\n logits = self.forward_with_cond_scale(ids, cond_vector=cond_vector,\n padding_mask=padding_mask,\n cond_scale=cond_scale,\n force_mask=force_mask)\n\n logits = logits.permute(0, 2, 1) # (b, seqlen, ntoken)\n # print(logits.shape, self.opt.num_tokens)\n # clean low prob token\n filtered_logits = top_k(logits, topk_filter_thres, dim=-1)\n\n '''\n Update ids\n '''\n # if force_mask:\n temperature = starting_temperature\n # else:\n # temperature = starting_temperature * (steps_until_x0 / timesteps)\n # temperature = max(temperature, 1e-4)\n # print(filtered_logits.shape)\n # temperature is annealed, gradually reducing temperature as well as randomness\n if gsample: # use gumbel_softmax sampling\n # print(\"1111\")\n pred_ids = gumbel_sample(filtered_logits, temperature=temperature, dim=-1) # (b, seqlen)\n else: # use multinomial sampling\n # print(\"2222\")\n probs = F.softmax(filtered_logits, dim=-1) # (b, seqlen, ntoken)\n # print(temperature, starting_temperature, steps_until_x0, timesteps)\n # print(probs / temperature)\n pred_ids = Categorical(probs / temperature).sample() # (b, seqlen)\n\n # print(pred_ids.max(), pred_ids.min())\n # if pred_ids.\n ids = torch.where(is_mask, pred_ids, ids)\n\n '''\n Updating scores\n '''\n probs_without_temperature = logits.softmax(dim=-1) # (b, seqlen, ntoken)\n scores = probs_without_temperature.gather(2, pred_ids.unsqueeze(dim=-1)) # (b, seqlen, 1)\n scores = scores.squeeze(-1) # (b, seqlen)\n\n # We do not want to re-mask the previously kept tokens, or pad tokens\n scores = scores.masked_fill(~is_mask, 1e5)\n\n ids = torch.where(padding_mask, -1, ids)\n # print(\"Final\", ids.max(), ids.min())\n return ids\n\n\n @torch.no_grad()\n @eval_decorator\n def edit(self,\n conds,\n tokens,\n m_lens,\n timesteps: int,\n cond_scale: int,\n temperature=1,\n topk_filter_thres=0.9,\n gsample=False,\n force_mask=False,\n edit_mask=None,\n padding_mask=None,\n ):\n\n assert edit_mask.shape == tokens.shape if edit_mask is not None else True\n device = next(self.parameters()).device\n seq_len = tokens.shape[1]\n\n if self.cond_mode == 'text':\n with torch.no_grad():\n cond_vector = self.encode_text(conds)\n elif self.cond_mode == 'action':\n cond_vector = self.enc_action(conds).to(device)\n elif self.cond_mode == 'uncond':\n cond_vector = torch.zeros(1, self.latent_dim).float().to(device)\n else:\n raise NotImplementedError(\"Unsupported condition mode!!!\")\n\n if padding_mask == None:\n padding_mask = ~lengths_to_mask(m_lens, seq_len)\n\n # Start from all tokens being masked\n if edit_mask == None:\n mask_free = True\n ids = torch.where(padding_mask, self.pad_id, tokens)\n edit_mask = torch.ones_like(padding_mask)\n edit_mask = edit_mask & ~padding_mask\n edit_len = edit_mask.sum(dim=-1)\n scores = torch.where(edit_mask, 0., 1e5)\n else:\n mask_free = False\n edit_mask = edit_mask & ~padding_mask\n edit_len = edit_mask.sum(dim=-1)\n ids = torch.where(edit_mask, self.mask_id, tokens)\n scores = torch.where(edit_mask, 0., 1e5)\n starting_temperature = temperature\n\n for timestep, steps_until_x0 in zip(torch.linspace(0, 1, timesteps, device=device), reversed(range(timesteps))):\n # 0 < timestep < 1\n rand_mask_prob = 0.16 if mask_free else self.noise_schedule(timestep) # Tensor\n\n '''\n Maskout, and cope with variable length\n '''\n # fix: the ratio regarding lengths, instead of seq_len\n num_token_masked = torch.round(rand_mask_prob * edit_len).clamp(min=1) # (b, )\n\n # select num_token_masked tokens with lowest scores to be masked\n sorted_indices = scores.argsort(\n dim=1) # (b, k), sorted_indices[i, j] = the index of j-th lowest element in scores on dim=1\n ranks = sorted_indices.argsort(dim=1) # (b, k), rank[i, j] = the rank (0: lowest) of scores[i, j] on dim=1\n is_mask = (ranks < num_token_masked.unsqueeze(-1))\n # is_mask = (torch.rand_like(scores) < 0.8) * ~padding_mask if mask_free else is_mask\n ids = torch.where(is_mask, self.mask_id, ids)\n\n '''\n Preparing input\n '''\n # (b, num_token, seqlen)\n logits = self.forward_with_cond_scale(ids, cond_vector=cond_vector,\n padding_mask=padding_mask,\n cond_scale=cond_scale,\n force_mask=force_mask)\n\n logits = logits.permute(0, 2, 1) # (b, seqlen, ntoken)\n # print(logits.shape, self.opt.num_tokens)\n # clean low prob token\n filtered_logits = top_k(logits, topk_filter_thres, dim=-1)\n\n '''\n Update ids\n '''\n # if force_mask:\n temperature = starting_temperature\n # else:\n # temperature = starting_temperature * (steps_until_x0 / timesteps)\n # temperature = max(temperature, 1e-4)\n # print(filtered_logits.shape)\n # temperature is annealed, gradually reducing temperature as well as randomness\n if gsample: # use gumbel_softmax sampling\n # print(\"1111\")\n pred_ids = gumbel_sample(filtered_logits, temperature=temperature, dim=-1) # (b, seqlen)\n else: # use multinomial sampling\n # print(\"2222\")\n probs = F.softmax(filtered_logits, dim=-1) # (b, seqlen, ntoken)\n # print(temperature, starting_temperature, steps_until_x0, timesteps)\n # print(probs / temperature)\n pred_ids = Categorical(probs / temperature).sample() # (b, seqlen)\n\n # print(pred_ids.max(), pred_ids.min())\n # if pred_ids.\n ids = torch.where(is_mask, pred_ids, ids)\n\n '''\n Updating scores\n '''\n probs_without_temperature = logits.softmax(dim=-1) # (b, seqlen, ntoken)\n scores = probs_without_temperature.gather(2, pred_ids.unsqueeze(dim=-1)) # (b, seqlen, 1)\n scores = scores.squeeze(-1) # (b, seqlen)\n\n # We do not want to re-mask the previously kept tokens, or pad tokens\n scores = scores.masked_fill(~edit_mask, 1e5) if mask_free else scores.masked_fill(~is_mask, 1e5)\n\n ids = torch.where(padding_mask, -1, ids)\n # print(\"Final\", ids.max(), ids.min())\n return ids\n\n @torch.no_grad()\n @eval_decorator\n def edit_beta(self,\n conds,\n conds_og,\n tokens,\n m_lens,\n cond_scale: int,\n force_mask=False,\n ):\n\n device = next(self.parameters()).device\n seq_len = tokens.shape[1]\n\n if self.cond_mode == 'text':\n with torch.no_grad():\n cond_vector = self.encode_text(conds)\n if conds_og is not None:\n cond_vector_og = self.encode_text(conds_og)\n else:\n cond_vector_og = None\n elif self.cond_mode == 'action':\n cond_vector = self.enc_action(conds).to(device)\n if conds_og is not None:\n cond_vector_og = self.enc_action(conds_og).to(device)\n else:\n cond_vector_og = None\n else:\n raise NotImplementedError(\"Unsupported condition mode!!!\")\n\n padding_mask = ~lengths_to_mask(m_lens, seq_len)\n\n # Start from all tokens being masked\n ids = torch.where(padding_mask, self.pad_id, tokens) # Do not mask anything\n\n '''\n Preparing input\n '''\n # (b, num_token, seqlen)\n logits = self.forward_with_cond_scale(ids,\n cond_vector=cond_vector,\n cond_vector_neg=cond_vector_og,\n padding_mask=padding_mask,\n cond_scale=cond_scale,\n force_mask=force_mask)\n\n logits = logits.permute(0, 2, 1) # (b, seqlen, ntoken)\n\n '''\n Updating scores\n '''\n probs_without_temperature = logits.softmax(dim=-1) # (b, seqlen, ntoken)\n tokens[tokens == -1] = 0 # just to get through an error when index = -1 using gather\n og_tokens_scores = probs_without_temperature.gather(2, tokens.unsqueeze(dim=-1)) # (b, seqlen, 1)\n og_tokens_scores = og_tokens_scores.squeeze(-1) # (b, seqlen)\n\n return og_tokens_scores" }, { "identifier": "ResidualTransformer", "path": "models/mask_transformer/transformer.py", "snippet": "class ResidualTransformer(nn.Module):\n def __init__(self, code_dim, cond_mode, latent_dim=256, ff_size=1024, num_layers=8, cond_drop_prob=0.1,\n num_heads=4, dropout=0.1, clip_dim=512, shared_codebook=False, share_weight=False,\n clip_version=None, opt=None, **kargs):\n super(ResidualTransformer, self).__init__()\n print(f'latent_dim: {latent_dim}, ff_size: {ff_size}, nlayers: {num_layers}, nheads: {num_heads}, dropout: {dropout}')\n\n # assert shared_codebook == True, \"Only support shared codebook right now!\"\n\n self.code_dim = code_dim\n self.latent_dim = latent_dim\n self.clip_dim = clip_dim\n self.dropout = dropout\n self.opt = opt\n\n self.cond_mode = cond_mode\n # self.cond_drop_prob = cond_drop_prob\n\n if self.cond_mode == 'action':\n assert 'num_actions' in kargs\n self.num_actions = kargs.get('num_actions', 1)\n self.cond_drop_prob = cond_drop_prob\n\n '''\n Preparing Networks\n '''\n self.input_process = InputProcess(self.code_dim, self.latent_dim)\n self.position_enc = PositionalEncoding(self.latent_dim, self.dropout)\n\n seqTransEncoderLayer = nn.TransformerEncoderLayer(d_model=self.latent_dim,\n nhead=num_heads,\n dim_feedforward=ff_size,\n dropout=dropout,\n activation='gelu')\n\n self.seqTransEncoder = nn.TransformerEncoder(seqTransEncoderLayer,\n num_layers=num_layers)\n\n self.encode_quant = partial(F.one_hot, num_classes=self.opt.num_quantizers)\n self.encode_action = partial(F.one_hot, num_classes=self.num_actions)\n\n self.quant_emb = nn.Linear(self.opt.num_quantizers, self.latent_dim)\n # if self.cond_mode != 'no_cond':\n if self.cond_mode == 'text':\n self.cond_emb = nn.Linear(self.clip_dim, self.latent_dim)\n elif self.cond_mode == 'action':\n self.cond_emb = nn.Linear(self.num_actions, self.latent_dim)\n else:\n raise KeyError(\"Unsupported condition mode!!!\")\n\n\n _num_tokens = opt.num_tokens + 1 # one dummy tokens for padding\n self.pad_id = opt.num_tokens\n\n # self.output_process = OutputProcess_Bert(out_feats=opt.num_tokens, latent_dim=latent_dim)\n self.output_process = OutputProcess(out_feats=code_dim, latent_dim=latent_dim)\n\n if shared_codebook:\n token_embed = nn.Parameter(torch.normal(mean=0, std=0.02, size=(_num_tokens, code_dim)))\n self.token_embed_weight = token_embed.expand(opt.num_quantizers-1, _num_tokens, code_dim)\n if share_weight:\n self.output_proj_weight = self.token_embed_weight\n self.output_proj_bias = None\n else:\n output_proj = nn.Parameter(torch.normal(mean=0, std=0.02, size=(_num_tokens, code_dim)))\n output_bias = nn.Parameter(torch.zeros(size=(_num_tokens,)))\n # self.output_proj_bias = 0\n self.output_proj_weight = output_proj.expand(opt.num_quantizers-1, _num_tokens, code_dim)\n self.output_proj_bias = output_bias.expand(opt.num_quantizers-1, _num_tokens)\n\n else:\n if share_weight:\n self.embed_proj_shared_weight = nn.Parameter(torch.normal(mean=0, std=0.02, size=(opt.num_quantizers - 2, _num_tokens, code_dim)))\n self.token_embed_weight_ = nn.Parameter(torch.normal(mean=0, std=0.02, size=(1, _num_tokens, code_dim)))\n self.output_proj_weight_ = nn.Parameter(torch.normal(mean=0, std=0.02, size=(1, _num_tokens, code_dim)))\n self.output_proj_bias = None\n self.registered = False\n else:\n output_proj_weight = torch.normal(mean=0, std=0.02,\n size=(opt.num_quantizers - 1, _num_tokens, code_dim))\n\n self.output_proj_weight = nn.Parameter(output_proj_weight)\n self.output_proj_bias = nn.Parameter(torch.zeros(size=(opt.num_quantizers, _num_tokens)))\n token_embed_weight = torch.normal(mean=0, std=0.02,\n size=(opt.num_quantizers - 1, _num_tokens, code_dim))\n self.token_embed_weight = nn.Parameter(token_embed_weight)\n\n self.apply(self.__init_weights)\n self.shared_codebook = shared_codebook\n self.share_weight = share_weight\n\n if self.cond_mode == 'text':\n print('Loading CLIP...')\n self.clip_version = clip_version\n self.clip_model = self.load_and_freeze_clip(clip_version)\n\n # def\n\n def mask_cond(self, cond, force_mask=False):\n bs, d = cond.shape\n if force_mask:\n return torch.zeros_like(cond)\n elif self.training and self.cond_drop_prob > 0.:\n mask = torch.bernoulli(torch.ones(bs, device=cond.device) * self.cond_drop_prob).view(bs, 1)\n return cond * (1. - mask)\n else:\n return cond\n\n def __init_weights(self, module):\n if isinstance(module, (nn.Linear, nn.Embedding)):\n module.weight.data.normal_(mean=0.0, std=0.02)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n\n def parameters_wo_clip(self):\n return [p for name, p in self.named_parameters() if not name.startswith('clip_model.')]\n\n def load_and_freeze_clip(self, clip_version):\n clip_model, clip_preprocess = clip.load(clip_version, device='cpu',\n jit=False) # Must set jit=False for training\n # Cannot run on cpu\n clip.model.convert_weights(\n clip_model) # Actually this line is unnecessary since clip by default already on float16\n # Date 0707: It's necessary, only unecessary when load directly to gpu. Disable if need to run on cpu\n\n # Freeze CLIP weights\n clip_model.eval()\n for p in clip_model.parameters():\n p.requires_grad = False\n\n return clip_model\n\n def encode_text(self, raw_text):\n device = next(self.parameters()).device\n text = clip.tokenize(raw_text, truncate=True).to(device)\n feat_clip_text = self.clip_model.encode_text(text).float()\n return feat_clip_text\n\n\n def q_schedule(self, bs, low, high):\n noise = uniform((bs,), device=self.opt.device)\n schedule = 1 - cosine_schedule(noise)\n return torch.round(schedule * (high - low)) + low\n\n def process_embed_proj_weight(self):\n if self.share_weight and (not self.shared_codebook):\n # if not self.registered:\n self.output_proj_weight = torch.cat([self.embed_proj_shared_weight, self.output_proj_weight_], dim=0)\n self.token_embed_weight = torch.cat([self.token_embed_weight_, self.embed_proj_shared_weight], dim=0)\n # self.registered = True\n\n def output_project(self, logits, qids):\n '''\n :logits: (bs, code_dim, seqlen)\n :qids: (bs)\n\n :return:\n -logits (bs, ntoken, seqlen)\n '''\n # (num_qlayers-1, num_token, code_dim) -> (bs, ntoken, code_dim)\n output_proj_weight = self.output_proj_weight[qids]\n # (num_qlayers, ntoken) -> (bs, ntoken)\n output_proj_bias = None if self.output_proj_bias is None else self.output_proj_bias[qids]\n\n output = torch.einsum('bnc, bcs->bns', output_proj_weight, logits)\n if output_proj_bias is not None:\n output += output + output_proj_bias.unsqueeze(-1)\n return output\n\n\n\n def trans_forward(self, motion_codes, qids, cond, padding_mask, force_mask=False):\n '''\n :param motion_codes: (b, seqlen, d)\n :padding_mask: (b, seqlen), all pad positions are TRUE else FALSE\n :param qids: (b), quantizer layer ids\n :param cond: (b, embed_dim) for text, (b, num_actions) for action\n :return:\n -logits: (b, num_token, seqlen)\n '''\n cond = self.mask_cond(cond, force_mask=force_mask)\n\n # (b, seqlen, d) -> (seqlen, b, latent_dim)\n x = self.input_process(motion_codes)\n\n # (b, num_quantizer)\n q_onehot = self.encode_quant(qids).float().to(x.device)\n\n q_emb = self.quant_emb(q_onehot).unsqueeze(0) # (1, b, latent_dim)\n cond = self.cond_emb(cond).unsqueeze(0) # (1, b, latent_dim)\n\n x = self.position_enc(x)\n xseq = torch.cat([cond, q_emb, x], dim=0) # (seqlen+2, b, latent_dim)\n\n padding_mask = torch.cat([torch.zeros_like(padding_mask[:, 0:2]), padding_mask], dim=1) # (b, seqlen+2)\n output = self.seqTransEncoder(xseq, src_key_padding_mask=padding_mask)[2:] # (seqlen, b, e)\n logits = self.output_process(output)\n return logits\n\n def forward_with_cond_scale(self,\n motion_codes,\n q_id,\n cond_vector,\n padding_mask,\n cond_scale=3,\n force_mask=False):\n bs = motion_codes.shape[0]\n # if cond_scale == 1:\n qids = torch.full((bs,), q_id, dtype=torch.long, device=motion_codes.device)\n if force_mask:\n logits = self.trans_forward(motion_codes, qids, cond_vector, padding_mask, force_mask=True)\n logits = self.output_project(logits, qids-1)\n return logits\n\n logits = self.trans_forward(motion_codes, qids, cond_vector, padding_mask)\n logits = self.output_project(logits, qids-1)\n if cond_scale == 1:\n return logits\n\n aux_logits = self.trans_forward(motion_codes, qids, cond_vector, padding_mask, force_mask=True)\n aux_logits = self.output_project(aux_logits, qids-1)\n\n scaled_logits = aux_logits + (logits - aux_logits) * cond_scale\n return scaled_logits\n\n def forward(self, all_indices, y, m_lens):\n '''\n :param all_indices: (b, n, q)\n :param y: raw text for cond_mode=text, (b, ) for cond_mode=action\n :m_lens: (b,)\n :return:\n '''\n\n self.process_embed_proj_weight()\n\n bs, ntokens, num_quant_layers = all_indices.shape\n device = all_indices.device\n\n # Positions that are PADDED are ALL FALSE\n non_pad_mask = lengths_to_mask(m_lens, ntokens) # (b, n)\n\n q_non_pad_mask = repeat(non_pad_mask, 'b n -> b n q', q=num_quant_layers)\n all_indices = torch.where(q_non_pad_mask, all_indices, self.pad_id) #(b, n, q)\n\n # randomly sample quantization layers to work on, [1, num_q)\n active_q_layers = q_schedule(bs, low=1, high=num_quant_layers, device=device)\n\n # print(self.token_embed_weight.shape, all_indices.shape)\n token_embed = repeat(self.token_embed_weight, 'q c d-> b c d q', b=bs)\n gather_indices = repeat(all_indices[..., :-1], 'b n q -> b n d q', d=token_embed.shape[2])\n # print(token_embed.shape, gather_indices.shape)\n all_codes = token_embed.gather(1, gather_indices) # (b, n, d, q-1)\n\n cumsum_codes = torch.cumsum(all_codes, dim=-1) #(b, n, d, q-1)\n\n active_indices = all_indices[torch.arange(bs), :, active_q_layers] # (b, n)\n history_sum = cumsum_codes[torch.arange(bs), :, :, active_q_layers - 1]\n\n force_mask = False\n if self.cond_mode == 'text':\n with torch.no_grad():\n cond_vector = self.encode_text(y)\n elif self.cond_mode == 'action':\n cond_vector = self.enc_action(y).to(device).float()\n elif self.cond_mode == 'uncond':\n cond_vector = torch.zeros(bs, self.latent_dim).float().to(device)\n force_mask = True\n else:\n raise NotImplementedError(\"Unsupported condition mode!!!\")\n\n logits = self.trans_forward(history_sum, active_q_layers, cond_vector, ~non_pad_mask, force_mask)\n logits = self.output_project(logits, active_q_layers-1)\n ce_loss, pred_id, acc = cal_performance(logits, active_indices, ignore_index=self.pad_id)\n\n return ce_loss, pred_id, acc\n\n @torch.no_grad()\n @eval_decorator\n def generate(self,\n motion_ids,\n conds,\n m_lens,\n temperature=1,\n topk_filter_thres=0.9,\n cond_scale=2,\n num_res_layers=-1, # If it's -1, use all.\n ):\n\n # print(self.opt.num_quantizers)\n # assert len(timesteps) >= len(cond_scales) == self.opt.num_quantizers\n self.process_embed_proj_weight()\n\n device = next(self.parameters()).device\n seq_len = motion_ids.shape[1]\n batch_size = len(conds)\n\n if self.cond_mode == 'text':\n with torch.no_grad():\n cond_vector = self.encode_text(conds)\n elif self.cond_mode == 'action':\n cond_vector = self.enc_action(conds).to(device)\n elif self.cond_mode == 'uncond':\n cond_vector = torch.zeros(batch_size, self.latent_dim).float().to(device)\n else:\n raise NotImplementedError(\"Unsupported condition mode!!!\")\n\n # token_embed = repeat(self.token_embed_weight, 'c d -> b c d', b=batch_size)\n # gathered_ids = repeat(motion_ids, 'b n -> b n d', d=token_embed.shape[-1])\n # history_sum = token_embed.gather(1, gathered_ids)\n\n # print(pa, seq_len)\n padding_mask = ~lengths_to_mask(m_lens, seq_len)\n # print(padding_mask.shape, motion_ids.shape)\n motion_ids = torch.where(padding_mask, self.pad_id, motion_ids)\n all_indices = [motion_ids]\n history_sum = 0\n num_quant_layers = self.opt.num_quantizers if num_res_layers==-1 else num_res_layers+1\n\n for i in range(1, num_quant_layers):\n # print(f\"--> Working on {i}-th quantizer\")\n # Start from all tokens being masked\n # qids = torch.full((batch_size,), i, dtype=torch.long, device=motion_ids.device)\n token_embed = self.token_embed_weight[i-1]\n token_embed = repeat(token_embed, 'c d -> b c d', b=batch_size)\n gathered_ids = repeat(motion_ids, 'b n -> b n d', d=token_embed.shape[-1])\n history_sum += token_embed.gather(1, gathered_ids)\n\n logits = self.forward_with_cond_scale(history_sum, i, cond_vector, padding_mask, cond_scale=cond_scale)\n # logits = self.trans_forward(history_sum, qids, cond_vector, padding_mask)\n\n logits = logits.permute(0, 2, 1) # (b, seqlen, ntoken)\n # clean low prob token\n filtered_logits = top_k(logits, topk_filter_thres, dim=-1)\n\n pred_ids = gumbel_sample(filtered_logits, temperature=temperature, dim=-1) # (b, seqlen)\n\n # probs = F.softmax(filtered_logits, dim=-1) # (b, seqlen, ntoken)\n # # print(temperature, starting_temperature, steps_until_x0, timesteps)\n # # print(probs / temperature)\n # pred_ids = Categorical(probs / temperature).sample() # (b, seqlen)\n\n ids = torch.where(padding_mask, self.pad_id, pred_ids)\n\n motion_ids = ids\n all_indices.append(ids)\n\n all_indices = torch.stack(all_indices, dim=-1)\n # padding_mask = repeat(padding_mask, 'b n -> b n q', q=all_indices.shape[-1])\n # all_indices = torch.where(padding_mask, -1, all_indices)\n all_indices = torch.where(all_indices==self.pad_id, -1, all_indices)\n # all_indices = all_indices.masked_fill()\n return all_indices\n\n @torch.no_grad()\n @eval_decorator\n def edit(self,\n motion_ids,\n conds,\n m_lens,\n temperature=1,\n topk_filter_thres=0.9,\n cond_scale=2\n ):\n\n # print(self.opt.num_quantizers)\n # assert len(timesteps) >= len(cond_scales) == self.opt.num_quantizers\n self.process_embed_proj_weight()\n\n device = next(self.parameters()).device\n seq_len = motion_ids.shape[1]\n batch_size = len(conds)\n\n if self.cond_mode == 'text':\n with torch.no_grad():\n cond_vector = self.encode_text(conds)\n elif self.cond_mode == 'action':\n cond_vector = self.enc_action(conds).to(device)\n elif self.cond_mode == 'uncond':\n cond_vector = torch.zeros(batch_size, self.latent_dim).float().to(device)\n else:\n raise NotImplementedError(\"Unsupported condition mode!!!\")\n\n # token_embed = repeat(self.token_embed_weight, 'c d -> b c d', b=batch_size)\n # gathered_ids = repeat(motion_ids, 'b n -> b n d', d=token_embed.shape[-1])\n # history_sum = token_embed.gather(1, gathered_ids)\n\n # print(pa, seq_len)\n padding_mask = ~lengths_to_mask(m_lens, seq_len)\n # print(padding_mask.shape, motion_ids.shape)\n motion_ids = torch.where(padding_mask, self.pad_id, motion_ids)\n all_indices = [motion_ids]\n history_sum = 0\n\n for i in range(1, self.opt.num_quantizers):\n # print(f\"--> Working on {i}-th quantizer\")\n # Start from all tokens being masked\n # qids = torch.full((batch_size,), i, dtype=torch.long, device=motion_ids.device)\n token_embed = self.token_embed_weight[i-1]\n token_embed = repeat(token_embed, 'c d -> b c d', b=batch_size)\n gathered_ids = repeat(motion_ids, 'b n -> b n d', d=token_embed.shape[-1])\n history_sum += token_embed.gather(1, gathered_ids)\n\n logits = self.forward_with_cond_scale(history_sum, i, cond_vector, padding_mask, cond_scale=cond_scale)\n # logits = self.trans_forward(history_sum, qids, cond_vector, padding_mask)\n\n logits = logits.permute(0, 2, 1) # (b, seqlen, ntoken)\n # clean low prob token\n filtered_logits = top_k(logits, topk_filter_thres, dim=-1)\n\n pred_ids = gumbel_sample(filtered_logits, temperature=temperature, dim=-1) # (b, seqlen)\n\n # probs = F.softmax(filtered_logits, dim=-1) # (b, seqlen, ntoken)\n # # print(temperature, starting_temperature, steps_until_x0, timesteps)\n # # print(probs / temperature)\n # pred_ids = Categorical(probs / temperature).sample() # (b, seqlen)\n\n ids = torch.where(padding_mask, self.pad_id, pred_ids)\n\n motion_ids = ids\n all_indices.append(ids)\n\n all_indices = torch.stack(all_indices, dim=-1)\n # padding_mask = repeat(padding_mask, 'b n -> b n q', q=all_indices.shape[-1])\n # all_indices = torch.where(padding_mask, -1, all_indices)\n all_indices = torch.where(all_indices==self.pad_id, -1, all_indices)\n # all_indices = all_indices.masked_fill()\n return all_indices" }, { "identifier": "RVQVAE", "path": "models/vq/model.py", "snippet": "class RVQVAE(nn.Module):\n def __init__(self,\n args,\n input_width=263,\n nb_code=1024,\n code_dim=512,\n output_emb_width=512,\n down_t=3,\n stride_t=2,\n width=512,\n depth=3,\n dilation_growth_rate=3,\n activation='relu',\n norm=None):\n\n super().__init__()\n assert output_emb_width == code_dim\n self.code_dim = code_dim\n self.num_code = nb_code\n # self.quant = args.quantizer\n self.encoder = Encoder(input_width, output_emb_width, down_t, stride_t, width, depth,\n dilation_growth_rate, activation=activation, norm=norm)\n self.decoder = Decoder(input_width, output_emb_width, down_t, stride_t, width, depth,\n dilation_growth_rate, activation=activation, norm=norm)\n rvqvae_config = {\n 'num_quantizers': args.num_quantizers,\n 'shared_codebook': args.shared_codebook,\n 'quantize_dropout_prob': args.quantize_dropout_prob,\n 'quantize_dropout_cutoff_index': 0,\n 'nb_code': nb_code,\n 'code_dim':code_dim, \n 'args': args,\n }\n self.quantizer = ResidualVQ(**rvqvae_config)\n\n def preprocess(self, x):\n # (bs, T, Jx3) -> (bs, Jx3, T)\n x = x.permute(0, 2, 1).float()\n return x\n\n def postprocess(self, x):\n # (bs, Jx3, T) -> (bs, T, Jx3)\n x = x.permute(0, 2, 1)\n return x\n\n def encode(self, x):\n N, T, _ = x.shape\n x_in = self.preprocess(x)\n x_encoder = self.encoder(x_in)\n # print(x_encoder.shape)\n code_idx, all_codes = self.quantizer.quantize(x_encoder, return_latent=True)\n # print(code_idx.shape)\n # code_idx = code_idx.view(N, -1)\n # (N, T, Q)\n # print()\n return code_idx, all_codes\n\n def forward(self, x):\n x_in = self.preprocess(x)\n # Encode\n x_encoder = self.encoder(x_in)\n\n ## quantization\n # x_quantized, code_idx, commit_loss, perplexity = self.quantizer(x_encoder, sample_codebook_temp=0.5,\n # force_dropout_index=0) #TODO hardcode\n x_quantized, code_idx, commit_loss, perplexity = self.quantizer(x_encoder, sample_codebook_temp=0.5)\n\n # print(code_idx[0, :, 1])\n ## decoder\n x_out = self.decoder(x_quantized)\n # x_out = self.postprocess(x_decoder)\n return x_out, commit_loss, perplexity\n\n def forward_decoder(self, x):\n x_d = self.quantizer.get_codes_from_indices(x)\n # x_d = x_d.view(1, -1, self.code_dim).permute(0, 2, 1).contiguous()\n x = x_d.sum(dim=0).permute(0, 2, 1)\n\n # decoder\n x_out = self.decoder(x)\n # x_out = self.postprocess(x_decoder)\n return x_out" }, { "identifier": "LengthEstimator", "path": "models/vq/model.py", "snippet": "class LengthEstimator(nn.Module):\n def __init__(self, input_size, output_size):\n super(LengthEstimator, self).__init__()\n nd = 512\n self.output = nn.Sequential(\n nn.Linear(input_size, nd),\n nn.LayerNorm(nd),\n nn.LeakyReLU(0.2, inplace=True),\n\n nn.Dropout(0.2),\n nn.Linear(nd, nd // 2),\n nn.LayerNorm(nd // 2),\n nn.LeakyReLU(0.2, inplace=True),\n\n nn.Dropout(0.2),\n nn.Linear(nd // 2, nd // 4),\n nn.LayerNorm(nd // 4),\n nn.LeakyReLU(0.2, inplace=True),\n\n nn.Linear(nd // 4, output_size)\n )\n\n self.output.apply(self.__init_weights)\n\n def __init_weights(self, module):\n if isinstance(module, (nn.Linear, nn.Embedding)):\n module.weight.data.normal_(mean=0.0, std=0.02)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n\n def forward(self, text_emb):\n return self.output(text_emb)" }, { "identifier": "EvalT2MOptions", "path": "options/eval_option.py", "snippet": "class EvalT2MOptions(BaseOptions):\n def initialize(self):\n BaseOptions.initialize(self)\n self.parser.add_argument('--which_epoch', type=str, default=\"latest\", help='Checkpoint you want to use, {latest, net_best_fid, etc}')\n self.parser.add_argument('--batch_size', type=int, default=32, help='Batch size')\n\n self.parser.add_argument('--ext', type=str, default='text2motion', help='Extension of the result file or folder')\n self.parser.add_argument(\"--num_batch\", default=2, type=int,\n help=\"Number of batch for generation\")\n self.parser.add_argument(\"--repeat_times\", default=1, type=int,\n help=\"Number of repetitions, per sample text prompt\")\n self.parser.add_argument(\"--cond_scale\", default=4, type=float,\n help=\"For classifier-free sampling - specifies the s parameter, as defined in the paper.\")\n self.parser.add_argument(\"--temperature\", default=1., type=float,\n help=\"Sampling Temperature.\")\n self.parser.add_argument(\"--topkr\", default=0.9, type=float,\n help=\"Filter out percentil low prop entries.\")\n self.parser.add_argument(\"--time_steps\", default=18, type=int,\n help=\"Mask Generate steps.\")\n self.parser.add_argument(\"--seed\", default=10107, type=int)\n\n self.parser.add_argument('--gumbel_sample', action=\"store_true\", help='True: gumbel sampling, False: categorical sampling.')\n self.parser.add_argument('--use_res_model', action=\"store_true\", help='Whether to use residual transformer.')\n # self.parser.add_argument('--est_length', action=\"store_true\", help='Training iterations')\n\n self.parser.add_argument('--res_name', type=str, default='tres_nlayer8_ld384_ff1024_rvq6ns_cdp0.2_sw', help='Model name of residual transformer')\n self.parser.add_argument('--text_path', type=str, default=\"\", help='Text prompt file')\n\n\n self.parser.add_argument('-msec', '--mask_edit_section', nargs='*', type=str, help='Indicate sections for editing, use comma to separate the start and end of a section'\n 'type int will specify the token frame, type float will specify the ratio of seq_len')\n self.parser.add_argument('--text_prompt', default='', type=str, help=\"A text prompt to be generated. If empty, will take text prompts from dataset.\")\n self.parser.add_argument('--source_motion', default='example_data/000612.npy', type=str, help=\"Source motion path for editing. (new_joint_vecs format .npy file)\")\n self.parser.add_argument(\"--motion_length\", default=0, type=int,\n help=\"Motion length for generation, only applicable with single text prompt.\")\n self.is_train = False" }, { "identifier": "get_opt", "path": "utils/get_opt.py", "snippet": "def get_opt(opt_path, device, **kwargs):\n opt = Namespace()\n opt_dict = vars(opt)\n\n skip = ('-------------- End ----------------',\n '------------ Options -------------',\n '\\n')\n print('Reading', opt_path)\n with open(opt_path, 'r') as f:\n for line in f:\n if line.strip() not in skip:\n # print(line.strip())\n key, value = line.strip('\\n').split(': ')\n if value in ('True', 'False'):\n opt_dict[key] = (value == 'True')\n # print(key, value)\n elif is_float(value):\n opt_dict[key] = float(value)\n elif is_number(value):\n opt_dict[key] = int(value)\n else:\n opt_dict[key] = str(value)\n\n # print(opt)\n opt_dict['which_epoch'] = 'finest'\n opt.save_root = pjoin(opt.checkpoints_dir, opt.dataset_name, opt.name)\n opt.model_dir = pjoin(opt.save_root, 'model')\n opt.meta_dir = pjoin(opt.save_root, 'meta')\n\n if opt.dataset_name == 't2m':\n opt.data_root = './dataset/HumanML3D/'\n opt.motion_dir = pjoin(opt.data_root, 'new_joint_vecs')\n opt.text_dir = pjoin(opt.data_root, 'texts')\n opt.joints_num = 22\n opt.dim_pose = 263\n opt.max_motion_length = 196\n opt.max_motion_frame = 196\n opt.max_motion_token = 55\n elif opt.dataset_name == 'kit':\n opt.data_root = './dataset/KIT-ML/'\n opt.motion_dir = pjoin(opt.data_root, 'new_joint_vecs')\n opt.text_dir = pjoin(opt.data_root, 'texts')\n opt.joints_num = 21\n opt.dim_pose = 251\n opt.max_motion_length = 196\n opt.max_motion_frame = 196\n opt.max_motion_token = 55\n else:\n raise KeyError('Dataset not recognized')\n if not hasattr(opt, 'unit_length'):\n opt.unit_length = 4\n opt.dim_word = 300\n opt.num_classes = 200 // opt.unit_length\n opt.dim_pos_ohot = len(POS_enumerator)\n opt.is_train = False\n opt.is_continue = False\n opt.device = device\n\n opt_dict.update(kwargs) # Overwrite with kwargs params\n\n return opt" }, { "identifier": "fixseed", "path": "utils/fixseed.py", "snippet": "def fixseed(seed):\n torch.backends.cudnn.benchmark = False\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)" }, { "identifier": "Joint2BVHConvertor", "path": "visualization/joints2bvh.py", "snippet": "class Joint2BVHConvertor:\n def __init__(self):\n self.template = BVH.load('./visualization/data/template.bvh', need_quater=True)\n self.re_order = [0, 1, 4, 7, 10, 2, 5, 8, 11, 3, 6, 9, 12, 15, 13, 16, 18, 20, 14, 17, 19, 21]\n\n self.re_order_inv = [0, 1, 5, 9, 2, 6, 10, 3, 7, 11, 4, 8, 12, 14, 18, 13, 15, 19, 16, 20, 17, 21]\n self.end_points = [4, 8, 13, 17, 21]\n\n self.template_offset = self.template.offsets.copy()\n self.parents = [-1, 0, 1, 2, 3, 0, 5, 6, 7, 0, 9, 10, 11, 12, 11, 14, 15, 16, 11, 18, 19, 20]\n\n def convert(self, positions, filename, iterations=10, foot_ik=True):\n '''\n Convert the SMPL joint positions to Mocap BVH\n :param positions: (N, 22, 3)\n :param filename: Save path for resulting BVH\n :param iterations: iterations for optimizing rotations, 10 is usually enough\n :param foot_ik: whether to enfore foot inverse kinematics, removing foot slide issue.\n :return:\n '''\n positions = positions[:, self.re_order]\n new_anim = self.template.copy()\n new_anim.rotations = Quaternions.id(positions.shape[:-1])\n new_anim.positions = new_anim.positions[0:1].repeat(positions.shape[0], axis=-0)\n new_anim.positions[:, 0] = positions[:, 0]\n\n if foot_ik:\n positions = remove_fs(positions, None, fid_l=(3, 4), fid_r=(7, 8), interp_length=5,\n force_on_floor=True)\n ik_solver = BasicInverseKinematics(new_anim, positions, iterations=iterations, silent=True)\n new_anim = ik_solver()\n\n # BVH.save(filename, new_anim, names=new_anim.names, frametime=1 / 20, order='zyx', quater=True)\n glb = Animation.positions_global(new_anim)[:, self.re_order_inv]\n if filename is not None:\n BVH.save(filename, new_anim, names=new_anim.names, frametime=1 / 20, order='zyx', quater=True)\n return new_anim, glb\n\n def convert_sgd(self, positions, filename, iterations=100, foot_ik=True):\n '''\n Convert the SMPL joint positions to Mocap BVH\n\n :param positions: (N, 22, 3)\n :param filename: Save path for resulting BVH\n :param iterations: iterations for optimizing rotations, 10 is usually enough\n :param foot_ik: whether to enfore foot inverse kinematics, removing foot slide issue.\n :return:\n '''\n\n ## Positional Foot locking ##\n glb = positions[:, self.re_order]\n\n if foot_ik:\n glb = remove_fs(glb, None, fid_l=(3, 4), fid_r=(7, 8), interp_length=2,\n force_on_floor=True)\n\n ## Fit BVH ##\n new_anim = self.template.copy()\n new_anim.rotations = Quaternions.id(glb.shape[:-1])\n new_anim.positions = new_anim.positions[0:1].repeat(glb.shape[0], axis=-0)\n new_anim.positions[:, 0] = glb[:, 0]\n anim = new_anim.copy()\n\n rot = torch.tensor(anim.rotations.qs, dtype=torch.float)\n pos = torch.tensor(anim.positions[:, 0, :], dtype=torch.float)\n offset = torch.tensor(anim.offsets, dtype=torch.float)\n\n glb = torch.tensor(glb, dtype=torch.float)\n ik_solver = InverseKinematics(rot, pos, offset, anim.parents, glb)\n print('Fixing foot contact using IK...')\n for i in tqdm(range(iterations)):\n mse = ik_solver.step()\n # print(i, mse)\n\n rotations = ik_solver.rotations.detach().cpu()\n norm = torch.norm(rotations, dim=-1, keepdim=True)\n rotations /= norm\n\n anim.rotations = Quaternions(rotations.numpy())\n anim.rotations[:, self.end_points] = Quaternions.id((anim.rotations.shape[0], len(self.end_points)))\n anim.positions[:, 0, :] = ik_solver.position.detach().cpu().numpy()\n if filename is not None:\n BVH.save(filename, anim, names=new_anim.names, frametime=1 / 20, order='zyx', quater=True)\n # BVH.save(filename[:-3] + 'bvh', anim, names=new_anim.names, frametime=1 / 20, order='zyx', quater=True)\n glb = Animation.positions_global(anim)[:, self.re_order_inv]\n return anim, glb" }, { "identifier": "recover_from_ric", "path": "utils/motion_process.py", "snippet": "def recover_from_ric(data, joints_num):\n r_rot_quat, r_pos = recover_root_rot_pos(data)\n positions = data[..., 4:(joints_num - 1) * 3 + 4]\n positions = positions.view(positions.shape[:-1] + (-1, 3))\n\n '''Add Y-axis rotation to local joints'''\n positions = qrot(qinv(r_rot_quat[..., None, :]).expand(positions.shape[:-1] + (4,)), positions)\n\n '''Add root XZ to joints'''\n positions[..., 0] += r_pos[..., 0:1]\n positions[..., 2] += r_pos[..., 2:3]\n\n '''Concate root and joints'''\n positions = torch.cat([r_pos.unsqueeze(-2), positions], dim=-2)\n\n return positions" }, { "identifier": "plot_3d_motion", "path": "utils/plot_script.py", "snippet": "def plot_3d_motion(save_path, kinematic_tree, joints, title, figsize=(10, 10), fps=120, radius=4):\n matplotlib.use('Agg')\n\n title_sp = title.split(' ')\n if len(title_sp) > 20:\n title = '\\n'.join([' '.join(title_sp[:10]), ' '.join(title_sp[10:20]), ' '.join(title_sp[20:])])\n elif len(title_sp) > 10:\n title = '\\n'.join([' '.join(title_sp[:10]), ' '.join(title_sp[10:])])\n\n def init():\n ax.set_xlim3d([-radius / 2, radius / 2])\n ax.set_ylim3d([0, radius])\n ax.set_zlim3d([0, radius])\n # print(title)\n fig.suptitle(title, fontsize=20)\n ax.grid(b=False)\n\n def plot_xzPlane(minx, maxx, miny, minz, maxz):\n ## Plot a plane XZ\n verts = [\n [minx, miny, minz],\n [minx, miny, maxz],\n [maxx, miny, maxz],\n [maxx, miny, minz]\n ]\n xz_plane = Poly3DCollection([verts])\n xz_plane.set_facecolor((0.5, 0.5, 0.5, 0.5))\n ax.add_collection3d(xz_plane)\n\n # return ax\n\n # (seq_len, joints_num, 3)\n data = joints.copy().reshape(len(joints), -1, 3)\n fig = plt.figure(figsize=figsize)\n ax = p3.Axes3D(fig)\n init()\n MINS = data.min(axis=0).min(axis=0)\n MAXS = data.max(axis=0).max(axis=0)\n colors = ['red', 'blue', 'black', 'red', 'blue',\n 'darkblue', 'darkblue', 'darkblue', 'darkblue', 'darkblue',\n 'darkred', 'darkred', 'darkred', 'darkred', 'darkred']\n frame_number = data.shape[0]\n # print(data.shape)\n\n height_offset = MINS[1]\n data[:, :, 1] -= height_offset\n trajec = data[:, 0, [0, 2]]\n\n data[..., 0] -= data[:, 0:1, 0]\n data[..., 2] -= data[:, 0:1, 2]\n\n # print(trajec.shape)\n\n def update(index):\n # print(index)\n ax.lines = []\n ax.collections = []\n ax.view_init(elev=120, azim=-90)\n ax.dist = 7.5\n # ax =\n plot_xzPlane(MINS[0] - trajec[index, 0], MAXS[0] - trajec[index, 0], 0, MINS[2] - trajec[index, 1],\n MAXS[2] - trajec[index, 1])\n # ax.scatter(data[index, :22, 0], data[index, :22, 1], data[index, :22, 2], color='black', s=3)\n\n if index > 1:\n ax.plot3D(trajec[:index, 0] - trajec[index, 0], np.zeros_like(trajec[:index, 0]),\n trajec[:index, 1] - trajec[index, 1], linewidth=1.0,\n color='blue')\n # ax = plot_xzPlane(ax, MINS[0], MAXS[0], 0, MINS[2], MAXS[2])\n\n for i, (chain, color) in enumerate(zip(kinematic_tree, colors)):\n # print(color)\n if i < 5:\n linewidth = 4.0\n else:\n linewidth = 2.0\n ax.plot3D(data[index, chain, 0], data[index, chain, 1], data[index, chain, 2], linewidth=linewidth,\n color=color)\n # print(trajec[:index, 0].shape)\n\n plt.axis('off')\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n ax.set_zticklabels([])\n\n ani = FuncAnimation(fig, update, frames=frame_number, interval=1000 / fps, repeat=False)\n\n # writer = FFMpegFileWriter(fps=fps)\n ani.save(save_path, fps=fps)\n plt.close()" }, { "identifier": "t2m_kinematic_chain", "path": "utils/paramUtil.py", "snippet": "" } ]
import os import torch import torch.nn.functional as F import numpy as np from os.path import join as pjoin from models.mask_transformer.transformer import MaskTransformer, ResidualTransformer from models.vq.model import RVQVAE, LengthEstimator from options.eval_option import EvalT2MOptions from utils.get_opt import get_opt from utils.fixseed import fixseed from visualization.joints2bvh import Joint2BVHConvertor from torch.distributions.categorical import Categorical from utils.motion_process import recover_from_ric from utils.plot_script import plot_3d_motion from utils.paramUtil import t2m_kinematic_chain
17,884
################################# ######Loading R-Transformer###### ################################# res_opt_path = pjoin(opt.checkpoints_dir, opt.dataset_name, opt.res_name, 'opt.txt') res_opt = get_opt(res_opt_path, device=opt.device) res_model = load_res_model(res_opt, vq_opt, opt) assert res_opt.vq_name == model_opt.vq_name ################################# ######Loading M-Transformer###### ################################# t2m_transformer = load_trans_model(model_opt, opt, 'latest.tar') ################################## #####Loading Length Predictor##### ################################## length_estimator = load_len_estimator(model_opt) t2m_transformer.eval() vq_model.eval() res_model.eval() length_estimator.eval() res_model.to(opt.device) t2m_transformer.to(opt.device) vq_model.to(opt.device) length_estimator.to(opt.device) ##### ---- Dataloader ---- ##### opt.nb_joints = 21 if opt.dataset_name == 'kit' else 22 mean = np.load(pjoin(opt.checkpoints_dir, opt.dataset_name, model_opt.vq_name, 'meta', 'mean.npy')) std = np.load(pjoin(opt.checkpoints_dir, opt.dataset_name, model_opt.vq_name, 'meta', 'std.npy')) def inv_transform(data): return data * std + mean prompt_list = [] length_list = [] est_length = False if opt.text_prompt != "": prompt_list.append(opt.text_prompt) if opt.motion_length == 0: est_length = True else: length_list.append(opt.motion_length) elif opt.text_path != "": with open(opt.text_path, 'r') as f: lines = f.readlines() for line in lines: infos = line.split('#') prompt_list.append(infos[0]) if len(infos) == 1 or (not infos[1].isdigit()): est_length = True length_list = [] else: length_list.append(int(infos[-1])) else: raise "A text prompt, or a file a text prompts are required!!!" # print('loading checkpoint {}'.format(file)) if est_length: print("Since no motion length are specified, we will use estimated motion lengthes!!") text_embedding = t2m_transformer.encode_text(prompt_list) pred_dis = length_estimator(text_embedding) probs = F.softmax(pred_dis, dim=-1) # (b, ntoken) token_lens = Categorical(probs).sample() # (b, seqlen) # lengths = torch.multinomial() else: token_lens = torch.LongTensor(length_list) // 4 token_lens = token_lens.to(opt.device).long() m_length = token_lens * 4 captions = prompt_list sample = 0 kinematic_chain = t2m_kinematic_chain converter = Joint2BVHConvertor() for r in range(opt.repeat_times): print("-->Repeat %d"%r) with torch.no_grad(): mids = t2m_transformer.generate(captions, token_lens, timesteps=opt.time_steps, cond_scale=opt.cond_scale, temperature=opt.temperature, topk_filter_thres=opt.topkr, gsample=opt.gumbel_sample) # print(mids) # print(mids.shape) mids = res_model.generate(mids, captions, token_lens, temperature=1, cond_scale=5) pred_motions = vq_model.forward_decoder(mids) pred_motions = pred_motions.detach().cpu().numpy() data = inv_transform(pred_motions) for k, (caption, joint_data) in enumerate(zip(captions, data)): print("---->Sample %d: %s %d"%(k, caption, m_length[k])) animation_path = pjoin(animation_dir, str(k)) joint_path = pjoin(joints_dir, str(k)) os.makedirs(animation_path, exist_ok=True) os.makedirs(joint_path, exist_ok=True) joint_data = joint_data[:m_length[k]] joint = recover_from_ric(torch.from_numpy(joint_data).float(), 22).numpy() bvh_path = pjoin(animation_path, "sample%d_repeat%d_len%d_ik.bvh"%(k, r, m_length[k])) _, ik_joint = converter.convert(joint, filename=bvh_path, iterations=100) bvh_path = pjoin(animation_path, "sample%d_repeat%d_len%d.bvh" % (k, r, m_length[k])) _, joint = converter.convert(joint, filename=bvh_path, iterations=100, foot_ik=False) save_path = pjoin(animation_path, "sample%d_repeat%d_len%d.mp4"%(k, r, m_length[k])) ik_save_path = pjoin(animation_path, "sample%d_repeat%d_len%d_ik.mp4"%(k, r, m_length[k]))
clip_version = 'ViT-B/32' def load_vq_model(vq_opt): # opt_path = pjoin(opt.checkpoints_dir, opt.dataset_name, opt.vq_name, 'opt.txt') vq_model = RVQVAE(vq_opt, vq_opt.dim_pose, vq_opt.nb_code, vq_opt.code_dim, vq_opt.output_emb_width, vq_opt.down_t, vq_opt.stride_t, vq_opt.width, vq_opt.depth, vq_opt.dilation_growth_rate, vq_opt.vq_act, vq_opt.vq_norm) ckpt = torch.load(pjoin(vq_opt.checkpoints_dir, vq_opt.dataset_name, vq_opt.name, 'model', 'net_best_fid.tar'), map_location='cpu') model_key = 'vq_model' if 'vq_model' in ckpt else 'net' vq_model.load_state_dict(ckpt[model_key]) print(f'Loading VQ Model {vq_opt.name} Completed!') return vq_model, vq_opt def load_trans_model(model_opt, opt, which_model): t2m_transformer = MaskTransformer(code_dim=model_opt.code_dim, cond_mode='text', latent_dim=model_opt.latent_dim, ff_size=model_opt.ff_size, num_layers=model_opt.n_layers, num_heads=model_opt.n_heads, dropout=model_opt.dropout, clip_dim=512, cond_drop_prob=model_opt.cond_drop_prob, clip_version=clip_version, opt=model_opt) ckpt = torch.load(pjoin(model_opt.checkpoints_dir, model_opt.dataset_name, model_opt.name, 'model', which_model), map_location='cpu') model_key = 't2m_transformer' if 't2m_transformer' in ckpt else 'trans' # print(ckpt.keys()) missing_keys, unexpected_keys = t2m_transformer.load_state_dict(ckpt[model_key], strict=False) assert len(unexpected_keys) == 0 assert all([k.startswith('clip_model.') for k in missing_keys]) print(f'Loading Transformer {opt.name} from epoch {ckpt["ep"]}!') return t2m_transformer def load_res_model(res_opt, vq_opt, opt): res_opt.num_quantizers = vq_opt.num_quantizers res_opt.num_tokens = vq_opt.nb_code res_transformer = ResidualTransformer(code_dim=vq_opt.code_dim, cond_mode='text', latent_dim=res_opt.latent_dim, ff_size=res_opt.ff_size, num_layers=res_opt.n_layers, num_heads=res_opt.n_heads, dropout=res_opt.dropout, clip_dim=512, shared_codebook=vq_opt.shared_codebook, cond_drop_prob=res_opt.cond_drop_prob, # codebook=vq_model.quantizer.codebooks[0] if opt.fix_token_emb else None, share_weight=res_opt.share_weight, clip_version=clip_version, opt=res_opt) ckpt = torch.load(pjoin(res_opt.checkpoints_dir, res_opt.dataset_name, res_opt.name, 'model', 'net_best_fid.tar'), map_location=opt.device) missing_keys, unexpected_keys = res_transformer.load_state_dict(ckpt['res_transformer'], strict=False) assert len(unexpected_keys) == 0 assert all([k.startswith('clip_model.') for k in missing_keys]) print(f'Loading Residual Transformer {res_opt.name} from epoch {ckpt["ep"]}!') return res_transformer def load_len_estimator(opt): model = LengthEstimator(512, 50) ckpt = torch.load(pjoin(opt.checkpoints_dir, opt.dataset_name, 'length_estimator', 'model', 'finest.tar'), map_location=opt.device) model.load_state_dict(ckpt['estimator']) print(f'Loading Length Estimator from epoch {ckpt["epoch"]}!') return model if __name__ == '__main__': parser = EvalT2MOptions() opt = parser.parse() fixseed(opt.seed) opt.device = torch.device("cpu" if opt.gpu_id == -1 else "cuda:" + str(opt.gpu_id)) torch.autograd.set_detect_anomaly(True) dim_pose = 251 if opt.dataset_name == 'kit' else 263 # out_dir = pjoin(opt.check) root_dir = pjoin(opt.checkpoints_dir, opt.dataset_name, opt.name) model_dir = pjoin(root_dir, 'model') result_dir = pjoin('./generation', opt.ext) joints_dir = pjoin(result_dir, 'joints') animation_dir = pjoin(result_dir, 'animations') os.makedirs(joints_dir, exist_ok=True) os.makedirs(animation_dir,exist_ok=True) model_opt_path = pjoin(root_dir, 'opt.txt') model_opt = get_opt(model_opt_path, device=opt.device) ####################### ######Loading RVQ###### ####################### vq_opt_path = pjoin(opt.checkpoints_dir, opt.dataset_name, model_opt.vq_name, 'opt.txt') vq_opt = get_opt(vq_opt_path, device=opt.device) vq_opt.dim_pose = dim_pose vq_model, vq_opt = load_vq_model(vq_opt) model_opt.num_tokens = vq_opt.nb_code model_opt.num_quantizers = vq_opt.num_quantizers model_opt.code_dim = vq_opt.code_dim ################################# ######Loading R-Transformer###### ################################# res_opt_path = pjoin(opt.checkpoints_dir, opt.dataset_name, opt.res_name, 'opt.txt') res_opt = get_opt(res_opt_path, device=opt.device) res_model = load_res_model(res_opt, vq_opt, opt) assert res_opt.vq_name == model_opt.vq_name ################################# ######Loading M-Transformer###### ################################# t2m_transformer = load_trans_model(model_opt, opt, 'latest.tar') ################################## #####Loading Length Predictor##### ################################## length_estimator = load_len_estimator(model_opt) t2m_transformer.eval() vq_model.eval() res_model.eval() length_estimator.eval() res_model.to(opt.device) t2m_transformer.to(opt.device) vq_model.to(opt.device) length_estimator.to(opt.device) ##### ---- Dataloader ---- ##### opt.nb_joints = 21 if opt.dataset_name == 'kit' else 22 mean = np.load(pjoin(opt.checkpoints_dir, opt.dataset_name, model_opt.vq_name, 'meta', 'mean.npy')) std = np.load(pjoin(opt.checkpoints_dir, opt.dataset_name, model_opt.vq_name, 'meta', 'std.npy')) def inv_transform(data): return data * std + mean prompt_list = [] length_list = [] est_length = False if opt.text_prompt != "": prompt_list.append(opt.text_prompt) if opt.motion_length == 0: est_length = True else: length_list.append(opt.motion_length) elif opt.text_path != "": with open(opt.text_path, 'r') as f: lines = f.readlines() for line in lines: infos = line.split('#') prompt_list.append(infos[0]) if len(infos) == 1 or (not infos[1].isdigit()): est_length = True length_list = [] else: length_list.append(int(infos[-1])) else: raise "A text prompt, or a file a text prompts are required!!!" # print('loading checkpoint {}'.format(file)) if est_length: print("Since no motion length are specified, we will use estimated motion lengthes!!") text_embedding = t2m_transformer.encode_text(prompt_list) pred_dis = length_estimator(text_embedding) probs = F.softmax(pred_dis, dim=-1) # (b, ntoken) token_lens = Categorical(probs).sample() # (b, seqlen) # lengths = torch.multinomial() else: token_lens = torch.LongTensor(length_list) // 4 token_lens = token_lens.to(opt.device).long() m_length = token_lens * 4 captions = prompt_list sample = 0 kinematic_chain = t2m_kinematic_chain converter = Joint2BVHConvertor() for r in range(opt.repeat_times): print("-->Repeat %d"%r) with torch.no_grad(): mids = t2m_transformer.generate(captions, token_lens, timesteps=opt.time_steps, cond_scale=opt.cond_scale, temperature=opt.temperature, topk_filter_thres=opt.topkr, gsample=opt.gumbel_sample) # print(mids) # print(mids.shape) mids = res_model.generate(mids, captions, token_lens, temperature=1, cond_scale=5) pred_motions = vq_model.forward_decoder(mids) pred_motions = pred_motions.detach().cpu().numpy() data = inv_transform(pred_motions) for k, (caption, joint_data) in enumerate(zip(captions, data)): print("---->Sample %d: %s %d"%(k, caption, m_length[k])) animation_path = pjoin(animation_dir, str(k)) joint_path = pjoin(joints_dir, str(k)) os.makedirs(animation_path, exist_ok=True) os.makedirs(joint_path, exist_ok=True) joint_data = joint_data[:m_length[k]] joint = recover_from_ric(torch.from_numpy(joint_data).float(), 22).numpy() bvh_path = pjoin(animation_path, "sample%d_repeat%d_len%d_ik.bvh"%(k, r, m_length[k])) _, ik_joint = converter.convert(joint, filename=bvh_path, iterations=100) bvh_path = pjoin(animation_path, "sample%d_repeat%d_len%d.bvh" % (k, r, m_length[k])) _, joint = converter.convert(joint, filename=bvh_path, iterations=100, foot_ik=False) save_path = pjoin(animation_path, "sample%d_repeat%d_len%d.mp4"%(k, r, m_length[k])) ik_save_path = pjoin(animation_path, "sample%d_repeat%d_len%d_ik.mp4"%(k, r, m_length[k]))
plot_3d_motion(ik_save_path, kinematic_chain, ik_joint, title=caption, fps=20)
9
2023-11-29 19:21:27+00:00
24k
dvlab-research/LLMGA
llmga/serve/gradio_web_server.py
[ { "identifier": "default_conversation", "path": "llmga/llava/conversation.py", "snippet": "class SeparatorStyle(Enum):\nclass Conversation:\n SINGLE = auto()\n TWO = auto()\n MPT = auto()\n PLAIN = auto()\n LLAMA_2 = auto()\n W, H = image.size\n H, W = longest_edge, shortest_edge\n H, W = shortest_edge, longest_edge\n W, H = image.size\n H, W = longest_edge, shortest_edge\n H, W = shortest_edge, longest_edge\n def get_prompt(self):\n def append_message(self, role, message):\n def get_images(self, return_pil=False):\n def expand2square(pil_img, background_color=(122, 116, 104)):\n def to_gradio_chatbot(self):\n def copy(self):\n def dict(self):" }, { "identifier": "LOGDIR", "path": "llmga/llava/constants.py", "snippet": "LOGDIR = \".\"" }, { "identifier": "build_logger", "path": "llmga/llava/utils.py", "snippet": "def build_logger(logger_name, logger_filename):\n def __init__(self, logger, log_level=logging.INFO):\n def __getattr__(self, attr):\n def write(self, buf):\n def flush(self):\ndef disable_torch_init():\ndef violates_moderation(text):\ndef pretty_print_semaphore(semaphore):\nclass StreamToLogger(object):" }, { "identifier": "IMAGE_TOKEN_INDEX", "path": "llmga/llava/constants.py", "snippet": "IMAGE_TOKEN_INDEX = -200" }, { "identifier": "DEFAULT_IMAGE_TOKEN", "path": "llmga/llava/constants.py", "snippet": "DEFAULT_IMAGE_TOKEN = \"<image>\"" }, { "identifier": "DEFAULT_IM_START_TOKEN", "path": "llmga/llava/constants.py", "snippet": "DEFAULT_IM_START_TOKEN = \"<im_start>\"" }, { "identifier": "DEFAULT_IM_END_TOKEN", "path": "llmga/llava/constants.py", "snippet": "DEFAULT_IM_END_TOKEN = \"<im_end>\"" }, { "identifier": "conv_templates", "path": "llmga/llava/conversation.py", "snippet": "class SeparatorStyle(Enum):\nclass Conversation:\n SINGLE = auto()\n TWO = auto()\n MPT = auto()\n PLAIN = auto()\n LLAMA_2 = auto()\n W, H = image.size\n H, W = longest_edge, shortest_edge\n H, W = shortest_edge, longest_edge\n W, H = image.size\n H, W = longest_edge, shortest_edge\n H, W = shortest_edge, longest_edge\n def get_prompt(self):\n def append_message(self, role, message):\n def get_images(self, return_pil=False):\n def expand2square(pil_img, background_color=(122, 116, 104)):\n def to_gradio_chatbot(self):\n def copy(self):\n def dict(self):" }, { "identifier": "load_pretrained_model", "path": "llmga/llava/model/builder.py", "snippet": "def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map=\"auto\"):\n kwargs = {\"device_map\": device_map}\n\n if load_8bit:\n kwargs['load_in_8bit'] = True\n elif load_4bit:\n kwargs['load_in_4bit'] = True\n kwargs['quantization_config'] = BitsAndBytesConfig(\n load_in_4bit=True,\n bnb_4bit_compute_dtype=torch.float16,\n bnb_4bit_use_double_quant=True,\n bnb_4bit_quant_type='nf4'\n )\n else:\n kwargs['torch_dtype'] = torch.float16\n\n if 'llmga' in model_name.lower():\n # Load LLaVA model\n if 'lora' in model_name.lower() and model_base is not None:\n lora_cfg_pretrained = AutoConfig.from_pretrained(model_path)\n tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)\n print('Loading LLMGA from base model...')\n model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, **kwargs)\n token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features\n if model.lm_head.weight.shape[0] != token_num:\n model.lm_head.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))\n model.model.embed_tokens.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))\n\n print('Loading additional LLMGA weights...')\n if os.path.exists(os.path.join(model_path, 'non_lora_trainables.bin')):\n non_lora_trainables = torch.load(os.path.join(model_path, 'non_lora_trainables.bin'), map_location='cpu')\n else:\n # this is probably from HF Hub\n from huggingface_hub import hf_hub_download\n def load_from_hf(repo_id, filename, subfolder=None):\n cache_file = hf_hub_download(\n repo_id=repo_id,\n filename=filename,\n subfolder=subfolder)\n return torch.load(cache_file, map_location='cpu')\n non_lora_trainables = load_from_hf(model_path, 'non_lora_trainables.bin')\n non_lora_trainables = {(k[11:] if k.startswith('base_model.') else k): v for k, v in non_lora_trainables.items()}\n if any(k.startswith('model.model.') for k in non_lora_trainables):\n non_lora_trainables = {(k[6:] if k.startswith('model.') else k): v for k, v in non_lora_trainables.items()}\n model.load_state_dict(non_lora_trainables, strict=False)\n\n from peft import PeftModel\n print('Loading LoRA weights...')\n model = PeftModel.from_pretrained(model, model_path)\n print('Merging LoRA weights...')\n model = model.merge_and_unload()\n print('Model is loaded...')\n elif model_base is not None:\n # this may be mm projector only\n print('Loading LLMGA from base model...')\n if 'mpt' in model_name.lower():\n if not os.path.isfile(os.path.join(model_path, 'configuration_mpt.py')):\n shutil.copyfile(os.path.join(model_base, 'configuration_mpt.py'), os.path.join(model_path, 'configuration_mpt.py'))\n tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=True)\n cfg_pretrained = AutoConfig.from_pretrained(model_path, trust_remote_code=True)\n model = LlavaMPTForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs)\n else:\n tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)\n cfg_pretrained = AutoConfig.from_pretrained(model_path)\n model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs)\n\n mm_projector_weights = torch.load(os.path.join(model_path, 'mm_projector.bin'), map_location='cpu')\n mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()}\n model.load_state_dict(mm_projector_weights, strict=False)\n else:\n if 'mpt' in model_name.lower():\n tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)\n model = LlavaMPTForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)\n else:\n tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)\n model = LlavaLlamaForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)\n else:\n # Load language model\n if model_base is not None:\n # PEFT model\n from peft import PeftModel\n tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)\n model = AutoModelForCausalLM.from_pretrained(model_base, torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map=\"auto\")\n print(f\"Loading LoRA weights from {model_path}\")\n model = PeftModel.from_pretrained(model, model_path)\n print(f\"Merging weights\")\n model = model.merge_and_unload()\n print('Convert to FP16...')\n model.to(torch.float16)\n else:\n use_fast = False\n if 'mpt' in model_name.lower():\n tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)\n model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, trust_remote_code=True, **kwargs)\n else:\n tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)\n model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)\n\n image_processor = None\n\n if 'llmga' in model_name.lower():\n mm_use_im_start_end = getattr(model.config, \"mm_use_im_start_end\", False)\n mm_use_im_patch_token = getattr(model.config, \"mm_use_im_patch_token\", True)\n if mm_use_im_patch_token:\n tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)\n if mm_use_im_start_end:\n tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)\n model.resize_token_embeddings(len(tokenizer))\n\n vision_tower = model.get_vision_tower()\n if not vision_tower.is_loaded:\n vision_tower.load_model()\n vision_tower.to(device='cuda', dtype=torch.float16)\n image_processor = vision_tower.image_processor\n\n if hasattr(model.config, \"max_sequence_length\"):\n context_len = model.config.max_sequence_length\n else:\n context_len = 2048\n\n return tokenizer, model, image_processor, context_len" }, { "identifier": "disable_torch_init", "path": "llmga/llava/utils.py", "snippet": "def disable_torch_init():\n \"\"\"\n Disable the redundant torch default initialization to accelerate model creation.\n \"\"\"\n import torch\n setattr(torch.nn.Linear, \"reset_parameters\", lambda self: None)\n setattr(torch.nn.LayerNorm, \"reset_parameters\", lambda self: None)" }, { "identifier": "tokenizer_image_token", "path": "llmga/llava/mm_utils.py", "snippet": "def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None):\n prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split('<image>')]\n def insert_separator(X, sep):\n return [ele for sublist in zip(X, [sep]*len(X)) for ele in sublist][:-1]\n\n input_ids = []\n offset = 0\n if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:\n offset = 1\n input_ids.append(prompt_chunks[0][0])\n\n for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):\n input_ids.extend(x[offset:])\n\n if return_tensors is not None:\n if return_tensors == 'pt':\n return torch.tensor(input_ids, dtype=torch.long)\n raise ValueError(f'Unsupported tensor type: {return_tensors}')\n return input_ids" }, { "identifier": "get_model_name_from_path", "path": "llmga/llava/mm_utils.py", "snippet": "def get_model_name_from_path(model_path):\n model_path = model_path.strip(\"/\")\n model_paths = model_path.split(\"/\")\n if model_paths[-1].startswith('checkpoint-'):\n return model_paths[-2] + \"_\" + model_paths[-1]\n else:\n return model_paths[-1]" }, { "identifier": "KeywordsStoppingCriteria", "path": "llmga/llava/mm_utils.py", "snippet": "class KeywordsStoppingCriteria(StoppingCriteria):\n def __init__(self, keywords, tokenizer, input_ids):\n self.keywords = keywords\n self.keyword_ids = []\n for keyword in keywords:\n cur_keyword_ids = tokenizer(keyword).input_ids\n if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:\n cur_keyword_ids = cur_keyword_ids[1:]\n self.keyword_ids.append(torch.tensor(cur_keyword_ids))\n self.tokenizer = tokenizer\n self.start_len = input_ids.shape[1]\n\n def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:\n assert output_ids.shape[0] == 1, \"Only support batch size 1 (yet)\" # TODO\n offset = min(output_ids.shape[1] - self.start_len, 3)\n self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]\n for keyword_id in self.keyword_ids:\n if output_ids[0, -keyword_id.shape[0]:] == keyword_id:\n return True\n outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]\n for keyword in self.keywords:\n if keyword in outputs:\n return True\n return False" }, { "identifier": "StableDiffusionXLPipeline", "path": "llmga/diffusers/pipeline_stable_diffusion_xl_lpw.py", "snippet": "class StableDiffusionXLPipeline(\n DiffusionPipeline, FromSingleFileMixin, StableDiffusionXLLoraLoaderMixin, TextualInversionLoaderMixin\n):\n r\"\"\"\n Pipeline for text-to-image generation using Stable Diffusion XL.\n\n This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the\n library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)\n\n In addition the pipeline inherits the following loading methods:\n - *LoRA*: [`loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`]\n - *Ckpt*: [`loaders.FromSingleFileMixin.from_single_file`]\n\n as well as the following saving methods:\n - *LoRA*: [`loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`]\n\n Args:\n vae ([`AutoencoderKL`]):\n Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.\n text_encoder ([`CLIPTextModel`]):\n Frozen text-encoder. Stable Diffusion XL uses the text portion of\n [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically\n the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.\n text_encoder_2 ([` CLIPTextModelWithProjection`]):\n Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of\n [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),\n specifically the\n [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)\n variant.\n tokenizer (`CLIPTokenizer`):\n Tokenizer of class\n [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).\n tokenizer_2 (`CLIPTokenizer`):\n Second Tokenizer of class\n [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).\n unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.\n scheduler ([`SchedulerMixin`]):\n A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of\n [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].\n force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `\"True\"`):\n Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of\n `stabilityai/stable-diffusion-xl-base-1-0`.\n add_watermarker (`bool`, *optional*):\n Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to\n watermark output images. If not defined, it will default to True if the package is installed, otherwise no\n watermarker will be used.\n \"\"\"\n model_cpu_offload_seq = \"text_encoder->text_encoder_2->unet->vae\"\n\n def __init__(\n self,\n vae: AutoencoderKL,\n text_encoder: CLIPTextModel,\n text_encoder_2: CLIPTextModelWithProjection,\n tokenizer: CLIPTokenizer,\n tokenizer_2: CLIPTokenizer,\n unet: UNet2DConditionModel,\n scheduler: KarrasDiffusionSchedulers,\n force_zeros_for_empty_prompt: bool = True,\n add_watermarker: Optional[bool] = None,\n ):\n super().__init__()\n\n self.register_modules(\n vae=vae,\n text_encoder=text_encoder,\n text_encoder_2=text_encoder_2,\n tokenizer=tokenizer,\n tokenizer_2=tokenizer_2,\n unet=unet,\n scheduler=scheduler,\n )\n self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)\n self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)\n self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)\n self.default_sample_size = self.unet.config.sample_size\n\n add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()\n\n if add_watermarker:\n self.watermark = StableDiffusionXLWatermarker()\n else:\n self.watermark = None\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing\n def enable_vae_slicing(self):\n r\"\"\"\n Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to\n compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.\n \"\"\"\n self.vae.enable_slicing()\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing\n def disable_vae_slicing(self):\n r\"\"\"\n Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to\n computing decoding in one step.\n \"\"\"\n self.vae.disable_slicing()\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling\n def enable_vae_tiling(self):\n r\"\"\"\n Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to\n compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow\n processing larger images.\n \"\"\"\n self.vae.enable_tiling()\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling\n def disable_vae_tiling(self):\n r\"\"\"\n Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to\n computing decoding in one step.\n \"\"\"\n self.vae.disable_tiling()\n\n def encode_prompt(\n self,\n prompt: str,\n prompt_2: Optional[str] = None,\n device: Optional[torch.device] = None,\n num_images_per_prompt: int = 1,\n do_classifier_free_guidance: bool = True,\n negative_prompt: Optional[str] = None,\n negative_prompt_2: Optional[str] = None,\n prompt_embeds: Optional[torch.FloatTensor] = None,\n negative_prompt_embeds: Optional[torch.FloatTensor] = None,\n pooled_prompt_embeds: Optional[torch.FloatTensor] = None,\n negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,\n lora_scale: Optional[float] = None,\n clip_skip: Optional[int] = None,\n ):\n r\"\"\"\n Encodes the prompt into text encoder hidden states.\n\n Args:\n prompt (`str` or `List[str]`, *optional*):\n prompt to be encoded\n prompt_2 (`str` or `List[str]`, *optional*):\n The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is\n used in both text-encoders\n device: (`torch.device`):\n torch device\n num_images_per_prompt (`int`):\n number of images that should be generated per prompt\n do_classifier_free_guidance (`bool`):\n whether to use classifier free guidance or not\n negative_prompt (`str` or `List[str]`, *optional*):\n The prompt or prompts not to guide the image generation. If not defined, one has to pass\n `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is\n less than `1`).\n negative_prompt_2 (`str` or `List[str]`, *optional*):\n The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and\n `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders\n prompt_embeds (`torch.FloatTensor`, *optional*):\n Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not\n provided, text embeddings will be generated from `prompt` input argument.\n negative_prompt_embeds (`torch.FloatTensor`, *optional*):\n Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt\n weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input\n argument.\n pooled_prompt_embeds (`torch.FloatTensor`, *optional*):\n Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.\n If not provided, pooled text embeddings will be generated from `prompt` input argument.\n negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):\n Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt\n weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`\n input argument.\n lora_scale (`float`, *optional*):\n A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.\n clip_skip (`int`, *optional*):\n Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that\n the output of the pre-final layer will be used for computing the prompt embeddings.\n \"\"\"\n device = device or self._execution_device\n\n # set lora scale so that monkey patched LoRA\n # function of text encoder can correctly access it\n if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):\n self._lora_scale = lora_scale\n\n # dynamically adjust the LoRA scale\n if not USE_PEFT_BACKEND:\n adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)\n adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)\n else:\n scale_lora_layers(self.text_encoder, lora_scale)\n scale_lora_layers(self.text_encoder_2, lora_scale)\n\n prompt = [prompt] if isinstance(prompt, str) else prompt\n\n if prompt is not None:\n batch_size = len(prompt)\n else:\n batch_size = prompt_embeds.shape[0]\n\n # Define tokenizers and text encoders\n tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]\n text_encoders = (\n [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]\n )\n\n if prompt_embeds is None:\n prompt_2 = prompt_2 or prompt\n prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2\n\n # textual inversion: procecss multi-vector tokens if necessary\n prompt_embeds_list = []\n prompts = [prompt, prompt_2]\n fg=0\n for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):\n if isinstance(self, TextualInversionLoaderMixin):\n prompt = self.maybe_convert_prompt(prompt, tokenizer)\n\n text_input_ids = get_text_index(tokenizer,prompt)\n\n \n untruncated_ids = tokenizer(prompt, padding=\"longest\", return_tensors=\"pt\").input_ids\n\n if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(\n text_input_ids, untruncated_ids\n ):\n removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])\n logger.warning(\n \"The following part of your input was truncated because CLIP can only handle sequences up to\"\n f\" {tokenizer.model_max_length} tokens: {removed_text}\"\n )\n\n if fg==0:\n text_embeddings, hidden_states = get_unweighted_text_embeddings_SDXL1(text_encoder,text_input_ids.to(device),chunk_length=tokenizer.model_max_length,clip_skip=clip_skip)\n fg=1\n else:\n text_embeddings, hidden_states = get_unweighted_text_embeddings_SDXL2(text_encoder,text_input_ids.to(device),chunk_length=tokenizer.model_max_length,clip_skip=clip_skip)\n\n\n # We are only ALWAYS interested in the pooled output of the final text encoder\n pooled_prompt_embeds = text_embeddings\n\n\n prompt_embeds_list.append(hidden_states)\n\n prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)\n\n # get unconditional embeddings for classifier free guidance\n zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt\n if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:\n negative_prompt_embeds = torch.zeros_like(prompt_embeds)\n negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)\n elif do_classifier_free_guidance and negative_prompt_embeds is None:\n negative_prompt = negative_prompt or \"\"\n negative_prompt_2 = negative_prompt_2 or negative_prompt\n\n # normalize str to list\n negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt\n negative_prompt_2 = (\n batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2\n )\n\n uncond_tokens: List[str]\n if prompt is not None and type(prompt) is not type(negative_prompt):\n raise TypeError(\n f\"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=\"\n f\" {type(prompt)}.\"\n )\n elif batch_size != len(negative_prompt):\n raise ValueError(\n f\"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:\"\n f\" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches\"\n \" the batch size of `prompt`.\"\n )\n else:\n uncond_tokens = [negative_prompt, negative_prompt_2]\n\n negative_prompt_embeds_list = []\n fg=1\n for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):\n if isinstance(self, TextualInversionLoaderMixin):\n negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)\n\n max_length = prompt_embeds.shape[1]\n\n uncond_input = get_text_index(tokenizer,negative_prompt)\n\n if fg==0:\n negative_pooled_prompt_embeds, negative_prompt_embeds = get_unweighted_text_embeddings_SDXL1(text_encoder,uncond_input.to(device),chunk_length=tokenizer.model_max_length,clip_skip=clip_skip)\n fg=1\n else:\n negative_pooled_prompt_embeds, negative_prompt_embeds = get_unweighted_text_embeddings_SDXL2(text_encoder,uncond_input.to(device),chunk_length=tokenizer.model_max_length,clip_skip=clip_skip)\n\n negative_prompt_embeds_list.append(negative_prompt_embeds)\n\n negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)\n\n prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)\n bs_embed, seq_len, _ = prompt_embeds.shape\n # duplicate text embeddings for each generation per prompt, using mps friendly method\n prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)\n prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)\n\n if do_classifier_free_guidance:\n # duplicate unconditional embeddings for each generation per prompt, using mps friendly method\n seq_len = negative_prompt_embeds.shape[1]\n negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)\n negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)\n negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)\n\n pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(\n bs_embed * num_images_per_prompt, -1\n )\n if do_classifier_free_guidance:\n negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(\n bs_embed * num_images_per_prompt, -1\n )\n\n if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:\n # Retrieve the original scale by scaling back the LoRA layers\n unscale_lora_layers(self.text_encoder)\n unscale_lora_layers(self.text_encoder_2)\n\n return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs\n def prepare_extra_step_kwargs(self, generator, eta):\n # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature\n # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.\n # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502\n # and should be between [0, 1]\n\n accepts_eta = \"eta\" in set(inspect.signature(self.scheduler.step).parameters.keys())\n extra_step_kwargs = {}\n if accepts_eta:\n extra_step_kwargs[\"eta\"] = eta\n\n # check if the scheduler accepts generator\n accepts_generator = \"generator\" in set(inspect.signature(self.scheduler.step).parameters.keys())\n if accepts_generator:\n extra_step_kwargs[\"generator\"] = generator\n return extra_step_kwargs\n\n def check_inputs(\n self,\n prompt,\n prompt_2,\n height,\n width,\n callback_steps,\n negative_prompt=None,\n negative_prompt_2=None,\n prompt_embeds=None,\n negative_prompt_embeds=None,\n pooled_prompt_embeds=None,\n negative_pooled_prompt_embeds=None,\n ):\n if height % 8 != 0 or width % 8 != 0:\n raise ValueError(f\"`height` and `width` have to be divisible by 8 but are {height} and {width}.\")\n\n if (callback_steps is None) or (\n callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)\n ):\n raise ValueError(\n f\"`callback_steps` has to be a positive integer but is {callback_steps} of type\"\n f\" {type(callback_steps)}.\"\n )\n\n if prompt is not None and prompt_embeds is not None:\n raise ValueError(\n f\"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to\"\n \" only forward one of the two.\"\n )\n elif prompt_2 is not None and prompt_embeds is not None:\n raise ValueError(\n f\"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to\"\n \" only forward one of the two.\"\n )\n elif prompt is None and prompt_embeds is None:\n raise ValueError(\n \"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined.\"\n )\n elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):\n raise ValueError(f\"`prompt` has to be of type `str` or `list` but is {type(prompt)}\")\n elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):\n raise ValueError(f\"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}\")\n\n if negative_prompt is not None and negative_prompt_embeds is not None:\n raise ValueError(\n f\"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:\"\n f\" {negative_prompt_embeds}. Please make sure to only forward one of the two.\"\n )\n elif negative_prompt_2 is not None and negative_prompt_embeds is not None:\n raise ValueError(\n f\"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:\"\n f\" {negative_prompt_embeds}. Please make sure to only forward one of the two.\"\n )\n\n if prompt_embeds is not None and negative_prompt_embeds is not None:\n if prompt_embeds.shape != negative_prompt_embeds.shape:\n raise ValueError(\n \"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but\"\n f\" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`\"\n f\" {negative_prompt_embeds.shape}.\"\n )\n\n if prompt_embeds is not None and pooled_prompt_embeds is None:\n raise ValueError(\n \"If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`.\"\n )\n\n if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:\n raise ValueError(\n \"If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`.\"\n )\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents\n def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):\n shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)\n if isinstance(generator, list) and len(generator) != batch_size:\n raise ValueError(\n f\"You have passed a list of generators of length {len(generator)}, but requested an effective batch\"\n f\" size of {batch_size}. Make sure the batch size matches the length of the generators.\"\n )\n\n if latents is None:\n latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)\n else:\n latents = latents.to(device)\n\n # scale the initial noise by the standard deviation required by the scheduler\n latents = latents * self.scheduler.init_noise_sigma\n return latents\n\n def _get_add_time_ids(self, original_size, crops_coords_top_left, target_size, dtype):\n add_time_ids = list(original_size + crops_coords_top_left + target_size)\n\n passed_add_embed_dim = (\n self.unet.config.addition_time_embed_dim * len(add_time_ids) + self.text_encoder_2.config.projection_dim\n )\n expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features\n\n if expected_add_embed_dim != passed_add_embed_dim:\n raise ValueError(\n f\"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`.\"\n )\n\n add_time_ids = torch.tensor([add_time_ids], dtype=dtype)\n return add_time_ids\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae\n def upcast_vae(self):\n dtype = self.vae.dtype\n self.vae.to(dtype=torch.float32)\n use_torch_2_0_or_xformers = isinstance(\n self.vae.decoder.mid_block.attentions[0].processor,\n (\n AttnProcessor2_0,\n XFormersAttnProcessor,\n LoRAXFormersAttnProcessor,\n LoRAAttnProcessor2_0,\n ),\n )\n # if xformers or torch_2_0 is used attention block does not need\n # to be in float32 which can save lots of memory\n if use_torch_2_0_or_xformers:\n self.vae.post_quant_conv.to(dtype)\n self.vae.decoder.conv_in.to(dtype)\n self.vae.decoder.mid_block.to(dtype)\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_freeu\n def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):\n r\"\"\"Enables the FreeU mechanism as in https://arxiv.org/abs/2309.11497.\n\n The suffixes after the scaling factors represent the stages where they are being applied.\n\n Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of the values\n that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.\n\n Args:\n s1 (`float`):\n Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to\n mitigate \"oversmoothing effect\" in the enhanced denoising process.\n s2 (`float`):\n Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to\n mitigate \"oversmoothing effect\" in the enhanced denoising process.\n b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.\n b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.\n \"\"\"\n if not hasattr(self, \"unet\"):\n raise ValueError(\"The pipeline must have `unet` for using FreeU.\")\n self.unet.enable_freeu(s1=s1, s2=s2, b1=b1, b2=b2)\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_freeu\n def disable_freeu(self):\n \"\"\"Disables the FreeU mechanism if enabled.\"\"\"\n self.unet.disable_freeu()\n\n @torch.no_grad()\n @replace_example_docstring(EXAMPLE_DOC_STRING)\n def __call__(\n self,\n prompt: Union[str, List[str]] = None,\n prompt_2: Optional[Union[str, List[str]]] = None,\n height: Optional[int] = None,\n width: Optional[int] = None,\n num_inference_steps: int = 50,\n denoising_end: Optional[float] = None,\n guidance_scale: float = 5.0,\n negative_prompt: Optional[Union[str, List[str]]] = None,\n negative_prompt_2: Optional[Union[str, List[str]]] = None,\n num_images_per_prompt: Optional[int] = 1,\n eta: float = 0.0,\n generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,\n latents: Optional[torch.FloatTensor] = None,\n prompt_embeds: Optional[torch.FloatTensor] = None,\n negative_prompt_embeds: Optional[torch.FloatTensor] = None,\n pooled_prompt_embeds: Optional[torch.FloatTensor] = None,\n negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,\n output_type: Optional[str] = \"pil\",\n return_dict: bool = True,\n callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,\n callback_steps: int = 1,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n guidance_rescale: float = 0.0,\n original_size: Optional[Tuple[int, int]] = None,\n crops_coords_top_left: Tuple[int, int] = (0, 0),\n target_size: Optional[Tuple[int, int]] = None,\n negative_original_size: Optional[Tuple[int, int]] = None,\n negative_crops_coords_top_left: Tuple[int, int] = (0, 0),\n negative_target_size: Optional[Tuple[int, int]] = None,\n clip_skip: Optional[int] = None,\n ):\n r\"\"\"\n Function invoked when calling the pipeline for generation.\n\n Args:\n prompt (`str` or `List[str]`, *optional*):\n The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.\n instead.\n prompt_2 (`str` or `List[str]`, *optional*):\n The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is\n used in both text-encoders\n height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):\n The height in pixels of the generated image. This is set to 1024 by default for the best results.\n Anything below 512 pixels won't work well for\n [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)\n and checkpoints that are not specifically fine-tuned on low resolutions.\n width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):\n The width in pixels of the generated image. This is set to 1024 by default for the best results.\n Anything below 512 pixels won't work well for\n [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)\n and checkpoints that are not specifically fine-tuned on low resolutions.\n num_inference_steps (`int`, *optional*, defaults to 50):\n The number of denoising steps. More denoising steps usually lead to a higher quality image at the\n expense of slower inference.\n denoising_end (`float`, *optional*):\n When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be\n completed before it is intentionally prematurely terminated. As a result, the returned sample will\n still retain a substantial amount of noise as determined by the discrete timesteps selected by the\n scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a\n \"Mixture of Denoisers\" multi-pipeline setup, as elaborated in [**Refining the Image\n Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)\n guidance_scale (`float`, *optional*, defaults to 5.0):\n Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).\n `guidance_scale` is defined as `w` of equation 2. of [Imagen\n Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >\n 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,\n usually at the expense of lower image quality.\n negative_prompt (`str` or `List[str]`, *optional*):\n The prompt or prompts not to guide the image generation. If not defined, one has to pass\n `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is\n less than `1`).\n negative_prompt_2 (`str` or `List[str]`, *optional*):\n The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and\n `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders\n num_images_per_prompt (`int`, *optional*, defaults to 1):\n The number of images to generate per prompt.\n eta (`float`, *optional*, defaults to 0.0):\n Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to\n [`schedulers.DDIMScheduler`], will be ignored for others.\n generator (`torch.Generator` or `List[torch.Generator]`, *optional*):\n One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)\n to make generation deterministic.\n latents (`torch.FloatTensor`, *optional*):\n Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image\n generation. Can be used to tweak the same generation with different prompts. If not provided, a latents\n tensor will ge generated by sampling using the supplied random `generator`.\n prompt_embeds (`torch.FloatTensor`, *optional*):\n Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not\n provided, text embeddings will be generated from `prompt` input argument.\n negative_prompt_embeds (`torch.FloatTensor`, *optional*):\n Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt\n weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input\n argument.\n pooled_prompt_embeds (`torch.FloatTensor`, *optional*):\n Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.\n If not provided, pooled text embeddings will be generated from `prompt` input argument.\n negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):\n Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt\n weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`\n input argument.\n output_type (`str`, *optional*, defaults to `\"pil\"`):\n The output format of the generate image. Choose between\n [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.\n return_dict (`bool`, *optional*, defaults to `True`):\n Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead\n of a plain tuple.\n callback (`Callable`, *optional*):\n A function that will be called every `callback_steps` steps during inference. The function will be\n called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.\n callback_steps (`int`, *optional*, defaults to 1):\n The frequency at which the `callback` function will be called. If not specified, the callback will be\n called at every step.\n cross_attention_kwargs (`dict`, *optional*):\n A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under\n `self.processor` in\n [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).\n guidance_rescale (`float`, *optional*, defaults to 0.0):\n Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are\n Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of\n [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).\n Guidance rescale factor should fix overexposure when using zero terminal SNR.\n original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):\n If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.\n `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as\n explained in section 2.2 of\n [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).\n crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):\n `crops_coords_top_left` can be used to generate an image that appears to be \"cropped\" from the position\n `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting\n `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of\n [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).\n target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):\n For most cases, `target_size` should be set to the desired height and width of the generated image. If\n not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in\n section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).\n negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):\n To negatively condition the generation process based on a specific image resolution. Part of SDXL's\n micro-conditioning as explained in section 2.2 of\n [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more\n information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.\n negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):\n To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's\n micro-conditioning as explained in section 2.2 of\n [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more\n information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.\n negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):\n To negatively condition the generation process based on a target image resolution. It should be as same\n as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of\n [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more\n information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.\n\n Examples:\n\n Returns:\n [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:\n [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a\n `tuple`. When returning a tuple, the first element is a list with the generated images.\n \"\"\"\n # 0. Default height and width to unet\n height = height or self.default_sample_size * self.vae_scale_factor\n width = width or self.default_sample_size * self.vae_scale_factor\n\n original_size = original_size or (height, width)\n target_size = target_size or (height, width)\n\n # 1. Check inputs. Raise error if not correct\n self.check_inputs(\n prompt,\n prompt_2,\n height,\n width,\n callback_steps,\n negative_prompt,\n negative_prompt_2,\n prompt_embeds,\n negative_prompt_embeds,\n pooled_prompt_embeds,\n negative_pooled_prompt_embeds,\n )\n\n # 2. Define call parameters\n if prompt is not None and isinstance(prompt, str):\n batch_size = 1\n elif prompt is not None and isinstance(prompt, list):\n batch_size = len(prompt)\n else:\n batch_size = prompt_embeds.shape[0]\n\n device = self._execution_device\n\n # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)\n # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`\n # corresponds to doing no classifier free guidance.\n do_classifier_free_guidance = guidance_scale > 1.0\n\n # 3. Encode input prompt\n lora_scale = cross_attention_kwargs.get(\"scale\", None) if cross_attention_kwargs is not None else None\n\n (\n prompt_embeds,\n negative_prompt_embeds,\n pooled_prompt_embeds,\n negative_pooled_prompt_embeds,\n ) = self.encode_prompt(\n prompt=prompt,\n prompt_2=prompt_2,\n device=device,\n num_images_per_prompt=num_images_per_prompt,\n do_classifier_free_guidance=do_classifier_free_guidance,\n negative_prompt=negative_prompt,\n negative_prompt_2=negative_prompt_2,\n prompt_embeds=prompt_embeds,\n negative_prompt_embeds=negative_prompt_embeds,\n pooled_prompt_embeds=pooled_prompt_embeds,\n negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,\n lora_scale=lora_scale,\n clip_skip=clip_skip,\n )\n\n # 4. Prepare timesteps\n self.scheduler.set_timesteps(num_inference_steps, device=device)\n\n timesteps = self.scheduler.timesteps\n\n # 5. Prepare latent variables\n num_channels_latents = self.unet.config.in_channels\n latents = self.prepare_latents(\n batch_size * num_images_per_prompt,\n num_channels_latents,\n height,\n width,\n prompt_embeds.dtype,\n device,\n generator,\n latents,\n )\n\n # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline\n extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)\n\n # 7. Prepare added time ids & embeddings\n add_text_embeds = pooled_prompt_embeds\n add_time_ids = self._get_add_time_ids(\n original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype\n )\n if negative_original_size is not None and negative_target_size is not None:\n negative_add_time_ids = self._get_add_time_ids(\n negative_original_size,\n negative_crops_coords_top_left,\n negative_target_size,\n dtype=prompt_embeds.dtype,\n )\n else:\n negative_add_time_ids = add_time_ids\n\n if do_classifier_free_guidance:\n prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)\n add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)\n add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)\n\n prompt_embeds = prompt_embeds.to(device)\n add_text_embeds = add_text_embeds.to(device)\n add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)\n\n # 8. Denoising loop\n num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)\n\n # 8.1 Apply denoising_end\n if denoising_end is not None and isinstance(denoising_end, float) and denoising_end > 0 and denoising_end < 1:\n discrete_timestep_cutoff = int(\n round(\n self.scheduler.config.num_train_timesteps\n - (denoising_end * self.scheduler.config.num_train_timesteps)\n )\n )\n num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))\n timesteps = timesteps[:num_inference_steps]\n\n with self.progress_bar(total=num_inference_steps) as progress_bar:\n for i, t in enumerate(timesteps):\n # expand the latents if we are doing classifier free guidance\n latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents\n\n latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)\n\n # predict the noise residual\n added_cond_kwargs = {\"text_embeds\": add_text_embeds, \"time_ids\": add_time_ids}\n noise_pred = self.unet(\n latent_model_input,\n t,\n encoder_hidden_states=prompt_embeds,\n cross_attention_kwargs=cross_attention_kwargs,\n added_cond_kwargs=added_cond_kwargs,\n return_dict=False,\n )[0]\n\n # perform guidance\n if do_classifier_free_guidance:\n noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)\n noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)\n\n if do_classifier_free_guidance and guidance_rescale > 0.0:\n # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf\n noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)\n\n # compute the previous noisy sample x_t -> x_t-1\n latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]\n\n # call the callback, if provided\n if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):\n progress_bar.update()\n if callback is not None and i % callback_steps == 0:\n step_idx = i // getattr(self.scheduler, \"order\", 1)\n callback(step_idx, t, latents)\n\n if XLA_AVAILABLE:\n xm.mark_step()\n\n if not output_type == \"latent\":\n # make sure the VAE is in float32 mode, as it overflows in float16\n needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast\n\n if needs_upcasting:\n self.upcast_vae()\n latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)\n\n image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]\n\n # cast back to fp16 if needed\n if needs_upcasting:\n self.vae.to(dtype=torch.float16)\n else:\n image = latents\n\n if not output_type == \"latent\":\n # apply watermark if available\n if self.watermark is not None:\n image = self.watermark.apply_watermark(image)\n\n image = self.image_processor.postprocess(image, output_type=output_type)\n\n # Offload all models\n self.maybe_free_model_hooks()\n\n if not return_dict:\n return (image,)\n\n return StableDiffusionXLPipelineOutput(images=image)" } ]
import argparse import datetime import json import os import time import gradio as gr import requests import hashlib import torch import copy from llmga.llava.conversation import (default_conversation, conv_templates, SeparatorStyle) from llmga.llava.constants import LOGDIR from llmga.llava.utils import (build_logger, server_error_msg, violates_moderation, moderation_msg) from llmga.llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN from llmga.llava.conversation import conv_templates, SeparatorStyle from llmga.llava.model.builder import load_pretrained_model from llmga.llava.utils import disable_torch_init from llmga.llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria from llmga.diffusers.pipeline_stable_diffusion_xl_lpw import StableDiffusionXLPipeline from diffusers import DiffusionPipeline
15,597
disable_btn = gr.Button.update(interactive=False) get_window_url_params = """ function() { const params = new URLSearchParams(window.location.search); url_params = Object.fromEntries(params); console.log(url_params); return url_params; } """ def load_demo(url_params, request: gr.Request): dropdown_update = gr.Dropdown.update(visible=True) if "model" in url_params: model = url_params["model"] if model in models: dropdown_update = gr.Dropdown.update( value=model, visible=True) state = default_conversation.copy() return state, dropdown_update def load_demo_refresh_model_list(request: gr.Request): state = default_conversation.copy() dropdown_update = gr.Dropdown.update( choices=models, value=models[0] if len(models) > 0 else "" ) return state, dropdown_update def regenerate(state, image_process_mode, request: gr.Request): # logger.info(f"regenerate. ip: {request.client.host}") state.messages[-1][-1] = None prev_human_msg = state.messages[-2] if type(prev_human_msg[1]) in (tuple, list): prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode) state.skip_next = False return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 3 def clear_history(request: gr.Request): # logger.info(f"clear_history. ip: {request.client.host}") state = default_conversation.copy() return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 3 def add_text(state, text, image, image_process_mode, request: gr.Request): # logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}") if len(text) <= 0 and image is None: state.skip_next = True return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 3 if args.moderate: flagged = violates_moderation(text) if flagged: state.skip_next = True return (state, state.to_gradio_chatbot(), moderation_msg, None) + ( no_change_btn,) * 3 text = text[:1536] # Hard cut-off if image is not None: text = text[:1200] # Hard cut-off for images if '<image>' not in text: # text = '<Image><image></Image>' + text if model.config.mm_use_im_start_end: text = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + text else: text = DEFAULT_IMAGE_TOKEN + '\n' + text text = (text, image, image_process_mode) if len(state.get_images(return_pil=True)) > 0: state = default_conversation.copy() state.append_message(state.roles[0], text) state.append_message(state.roles[1], None) state.skip_next = False tp=state.to_gradio_chatbot() for tpp in tp: if tpp[-1] is None: continue tpp[-1] = tpp[-1].replace("\n\n","\n") if "<gen_image>" in tpp[-1] and "</gen_image>" in tpp[-1]: tpp[-1]="The generation is finished: \n\n" + tpp[-1] return (state, tp, "", None) + (disable_btn,) * 3 def http_bot(state, model_selector, temperature, top_p, max_new_tokens, request: gr.Request): # logger.info(f"http_bot. ip: {request.client.host}") start_tstamp = time.time() model_name = model_selector if state.skip_next: # This generate call is skipped due to invalid inputs yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5 return if len(state.messages) == state.offset + 2: # First round of conversation template_name = "llava_llama_2" new_state = conv_templates[template_name].copy() new_state.append_message(new_state.roles[0], state.messages[-2][1]) new_state.append_message(new_state.roles[1], None) state = new_state prompt = state.get_prompt() images = state.get_images(return_pil=True) image_tensors =[image_processor.preprocess(image, return_tensors='pt')['pixel_values'].half().cuda() for image in images] if len(image_tensors)==0: image_tensor=None elif len(image_tensors)==1: image_tensor=image_tensors[0] else: image_tensor=image_tensors
headers = {"User-Agent": "LLMGA Client"} no_change_btn = gr.Button.update() enable_btn = gr.Button.update(interactive=True) disable_btn = gr.Button.update(interactive=False) get_window_url_params = """ function() { const params = new URLSearchParams(window.location.search); url_params = Object.fromEntries(params); console.log(url_params); return url_params; } """ def load_demo(url_params, request: gr.Request): dropdown_update = gr.Dropdown.update(visible=True) if "model" in url_params: model = url_params["model"] if model in models: dropdown_update = gr.Dropdown.update( value=model, visible=True) state = default_conversation.copy() return state, dropdown_update def load_demo_refresh_model_list(request: gr.Request): state = default_conversation.copy() dropdown_update = gr.Dropdown.update( choices=models, value=models[0] if len(models) > 0 else "" ) return state, dropdown_update def regenerate(state, image_process_mode, request: gr.Request): # logger.info(f"regenerate. ip: {request.client.host}") state.messages[-1][-1] = None prev_human_msg = state.messages[-2] if type(prev_human_msg[1]) in (tuple, list): prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode) state.skip_next = False return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 3 def clear_history(request: gr.Request): # logger.info(f"clear_history. ip: {request.client.host}") state = default_conversation.copy() return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 3 def add_text(state, text, image, image_process_mode, request: gr.Request): # logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}") if len(text) <= 0 and image is None: state.skip_next = True return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 3 if args.moderate: flagged = violates_moderation(text) if flagged: state.skip_next = True return (state, state.to_gradio_chatbot(), moderation_msg, None) + ( no_change_btn,) * 3 text = text[:1536] # Hard cut-off if image is not None: text = text[:1200] # Hard cut-off for images if '<image>' not in text: # text = '<Image><image></Image>' + text if model.config.mm_use_im_start_end: text = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + text else: text = DEFAULT_IMAGE_TOKEN + '\n' + text text = (text, image, image_process_mode) if len(state.get_images(return_pil=True)) > 0: state = default_conversation.copy() state.append_message(state.roles[0], text) state.append_message(state.roles[1], None) state.skip_next = False tp=state.to_gradio_chatbot() for tpp in tp: if tpp[-1] is None: continue tpp[-1] = tpp[-1].replace("\n\n","\n") if "<gen_image>" in tpp[-1] and "</gen_image>" in tpp[-1]: tpp[-1]="The generation is finished: \n\n" + tpp[-1] return (state, tp, "", None) + (disable_btn,) * 3 def http_bot(state, model_selector, temperature, top_p, max_new_tokens, request: gr.Request): # logger.info(f"http_bot. ip: {request.client.host}") start_tstamp = time.time() model_name = model_selector if state.skip_next: # This generate call is skipped due to invalid inputs yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5 return if len(state.messages) == state.offset + 2: # First round of conversation template_name = "llava_llama_2" new_state = conv_templates[template_name].copy() new_state.append_message(new_state.roles[0], state.messages[-2][1]) new_state.append_message(new_state.roles[1], None) state = new_state prompt = state.get_prompt() images = state.get_images(return_pil=True) image_tensors =[image_processor.preprocess(image, return_tensors='pt')['pixel_values'].half().cuda() for image in images] if len(image_tensors)==0: image_tensor=None elif len(image_tensors)==1: image_tensor=image_tensors[0] else: image_tensor=image_tensors
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
10
2023-11-27 18:46:55+00:00
24k
JiahuiLei/GART
solver.py
[ { "identifier": "prepare_real_seq", "path": "lib_data/get_data.py", "snippet": "def prepare_real_seq(\n seq_name,\n dataset_mode,\n split=\"train\",\n image_zoom_ratio=0.5,\n balance=False,\n ins_avt_wild_start_end_skip=None,\n):\n logging.info(\"Prepare real seq: {}\".format(seq_name))\n # * Get dataset\n if dataset_mode == \"ubcfashion\":\n dataset = UBCFasionDataset(\n data_root=\"./data/ubcfashion/\",\n video_list=[seq_name],\n image_zoom_ratio=image_zoom_ratio,\n start_end_skip=ins_avt_wild_start_end_skip,\n )\n elif dataset_mode == \"people_snapshot\":\n dataset = InstantAvatarDataset(\n noisy_flag=False,\n data_root=\"./data/people_snapshot/\",\n video_name=seq_name,\n split=split,\n image_zoom_ratio=image_zoom_ratio,\n )\n print(\"Load Instant Avatar processed PeopleSnapshot\")\n elif dataset_mode == \"zju\":\n dataset = ZJUDataset(\n data_root=\"./data/zju_mocap\",\n video_name=seq_name,\n split=split,\n image_zoom_ratio=image_zoom_ratio,\n )\n elif dataset_mode == \"instant_avatar_wild\":\n # assert image_zoom_ratio == 1.0, \"Check! in the wild data should use 1.0\"\n if image_zoom_ratio != 1.0:\n logging.warning(\n f\"Check! in the wild data should use 1.0, but got {image_zoom_ratio}\"\n )\n dataset = InstantAvatarWildDataset(\n data_root=\"./data/insav_wild\",\n video_name=seq_name,\n split=split,\n image_zoom_ratio=image_zoom_ratio,\n start_end_skip=ins_avt_wild_start_end_skip,\n )\n elif dataset_mode == \"dog_demo\":\n dataset = DogDemoDataset(data_root=\"./data/dog_data_official/\", video_name=seq_name)\n else:\n raise NotImplementedError(\"Unknown mode: {}\".format(dataset_mode))\n\n # prepare an optimizable data provider\n optimizable_data_provider = RealDataOptimizablePoseProviderPose(\n dataset,\n balance=balance,\n )\n return optimizable_data_provider, dataset" }, { "identifier": "DatabasePoseProvider", "path": "lib_data/data_provider.py", "snippet": "class DatabasePoseProvider(nn.Module):\n def __init__(\n self,\n pose_dirs: list,\n da_pose_prob=0.1,\n da_range=[0.0, np.pi / 4],\n device=torch.device(\"cuda\"),\n ) -> None:\n super().__init__()\n self.device = device\n self.base_R = matrix_to_axis_angle(\n torch.as_tensor(euler2mat(np.pi / 2.0, 0, np.pi / 2.0, \"sxyz\"))[None]\n )[0]\n self.base_R = self.base_R.float().to(self.device)\n\n self.da_pose_prob = da_pose_prob\n self.da_range = da_range\n\n self.data = []\n\n # cache the poses\n for d in pose_dirs:\n print(f\"Caching {d} ...\")\n for subject in tqdm(os.listdir(d)):\n sub_dir = os.path.join(d, subject)\n if not os.path.isdir(sub_dir):\n continue\n npz_files = [f for f in os.listdir(sub_dir) if f.endswith(\".npz\")]\n npz_files.sort()\n for fn in npz_files:\n try:\n npz_fn = os.path.join(sub_dir, fn)\n pose_data = np.load(npz_fn)\n amass_len = pose_data[\"poses\"].shape[0]\n smplx_to_smpl = list(range(66)) + [72, 73, 74, 117, 118, 119]\n poses = pose_data[\"poses\"][:, smplx_to_smpl].reshape(\n amass_len, 24, 3\n )\n self.data.append(poses.astype(np.float16))\n except:\n # print(f\"Error in {npz_fn}, skip!\")\n pass\n self.data = np.concatenate(self.data, axis=0)\n print(\n f\"Database has poses {len(self.data)} with DA-pose prob {self.da_pose_prob} and range {self.da_range}\"\n )\n return\n\n def forward(self, N: int):\n pose, trans = self.sample_pose(N)\n return pose, trans\n\n def sample_pose(self, N: int):\n # da pose\n pose_list = []\n for i in range(N):\n seed = np.random.rand()\n if seed > self.da_pose_prob:\n # from database\n idx = np.random.randint(len(self.data))\n pose = torch.from_numpy(self.data[idx]).float().to(self.device)\n else:\n # da pose\n pose = torch.zeros(24, 3).to(self.device)\n da_theta = float(np.random.uniform(*self.da_range))\n pose[1, -1] = da_theta\n pose[2, -1] = -da_theta\n pose[0] = self.base_R\n pose_list.append(pose)\n pose = torch.stack(pose_list, dim=0)\n trans = torch.zeros(N, 3).to(self.device)\n return pose, trans" }, { "identifier": "get_template", "path": "lib_gart/templates.py", "snippet": "def get_template(\n mode, init_beta, cano_pose_type, voxel_deformer_res, template_model_path=None\n):\n if mode == \"human\":\n template = SMPLTemplate(\n smpl_model_path=template_model_path,\n init_beta=init_beta,\n cano_pose_type=cano_pose_type,\n voxel_deformer_res=voxel_deformer_res,\n )\n elif mode == \"dog\":\n template = SMALTemplate(\n init_beta=init_beta,\n cano_pose_type=cano_pose_type,\n voxel_deformer_res=voxel_deformer_res,\n )\n else:\n raise ValueError(f\"Unknown mode {mode}\")\n return template" }, { "identifier": "GaussianTemplateModel", "path": "lib_gart/model.py", "snippet": "class GaussianTemplateModel(nn.Module):\n def __init__(\n self,\n template,\n add_bones: AdditionalBones,\n ##################################\n # attr config\n w_correction_flag=True,\n # w_rest_dim=0, # additional skinnign weight\n f_localcode_dim=0,\n max_sph_order=0,\n w_memory_type=\"point\",\n ##################################\n max_scale=0.1, # use sigmoid activation, can't be too large\n min_scale=0.0,\n # geo init\n init_mode=\"on_mesh\",\n opacity_init_value=0.9, # the init value of opacity\n # on mesh init params\n onmesh_init_subdivide_num=0,\n onmesh_init_scale_factor=1.0,\n onmesh_init_thickness_factor=0.5,\n # near mesh init params\n scale_init_value=0.01, # the init value of scale\n nearmesh_init_num=10000,\n nearmesh_init_std=0.1,\n ##################################\n ) -> None:\n super().__init__()\n\n self.template = template\n self.num_bones = template.voxel_deformer.num_bones\n self.add_bones = add_bones\n self.num_add_bones = add_bones.num_bones\n\n self.max_scale = max_scale\n self.min_scale = min_scale\n self._init_act(self.max_scale, self.min_scale)\n self.opacity_init_logit = self.o_inv_act(opacity_init_value)\n\n # * init geometry\n if init_mode == \"on_mesh\":\n x, q, s, o = get_on_mesh_init_geo_values(\n template,\n on_mesh_subdivide=onmesh_init_subdivide_num,\n scale_init_factor=onmesh_init_scale_factor,\n thickness_init_factor=onmesh_init_thickness_factor,\n max_scale=max_scale,\n min_scale=min_scale,\n s_inv_act=self.s_inv_act,\n opacity_init_logit=self.opacity_init_logit,\n )\n elif init_mode == \"near_mesh\":\n self.scale_init_logit = self.s_inv_act(scale_init_value)\n x, q, s, o = get_near_mesh_init_geo_values(\n template,\n scale_base_logit=self.scale_init_logit,\n opacity_base_logit=self.opacity_init_logit,\n random_init_num=nearmesh_init_num,\n random_init_std=nearmesh_init_std,\n )\n elif init_mode == \"in_mesh\":\n self.scale_init_logit = self.s_inv_act(scale_init_value)\n x, q, s, o = get_inside_mesh_init_geo_values(\n template,\n scale_base_logit=self.scale_init_logit,\n opacity_base_logit=self.opacity_init_logit,\n random_init_num=nearmesh_init_num,\n )\n else:\n raise NotImplementedError(f\"Unknown init_mode {init_mode}\")\n self._xyz = nn.Parameter(x)\n self._rotation = nn.Parameter(q)\n self._scaling = nn.Parameter(s)\n self._opacity = nn.Parameter(o)\n\n # * init attributes\n self.w_memory_type = w_memory_type\n assert self.w_memory_type in [\"point\", \"voxel\"], f\"Unknown {w_memory_type}\"\n\n self.max_sph_order = max_sph_order\n self.w_dc_dim = self.template.dim if w_correction_flag else 0\n self.w_rest_dim = self.add_bones.num_bones\n self.f_localcode_dim = f_localcode_dim\n\n sph_rest_dim = 3 * (sph_order2nfeat(self.max_sph_order) - 1)\n self._features_dc = nn.Parameter(torch.zeros_like(self._xyz))\n self._features_rest = nn.Parameter(torch.zeros(self.N, sph_rest_dim))\n\n # * Different implementation of smoothness\n if self.w_memory_type == \"point\":\n self._w_correction_dc = nn.Parameter(torch.zeros(self.N, self.w_dc_dim))\n self._w_correction_rest = nn.Parameter(\n torch.ones(self.N, self.w_rest_dim) * 1e-4\n )\n elif self.w_memory_type == \"voxel\":\n self._w_correction_dc = nn.Parameter(torch.zeros(self.N, 0))\n self._w_correction_rest = nn.Parameter(torch.zeros(self.N, 0))\n if self.w_dc_dim > 0:\n self.template.voxel_deformer.enable_voxel_correction()\n if self.w_rest_dim > 0:\n self.template.voxel_deformer.enable_additional_correction(\n self.w_rest_dim\n )\n elif self.w_memory_type == \"hash\":\n raise NotImplementedError(\"TODO\")\n else:\n raise NotImplementedError(f\"Unknown {w_memory_type}\")\n\n self._features_localcode = nn.Parameter(\n torch.zeros(self.N, self.f_localcode_dim)\n )\n\n assert self.f_localcode_dim == 0, \"TODO, add local mlp ablation\"\n\n # * States\n # warning, our code use N, instead of (N,1) as in GS code\n self.register_buffer(\"xyz_gradient_accum\", torch.zeros(self.N).float())\n self.register_buffer(\"xyz_gradient_denom\", torch.zeros(self.N).long())\n self.register_buffer(\"max_radii2D\", torch.zeros(self.N).float())\n\n self.op_update_exclude = [\"add_bones\"]\n if self.w_memory_type != \"point\":\n self.op_update_exclude.extend([\"w_dc_vox\", \"w_rest_vox\"])\n # self.summary()\n return\n\n def summary(self):\n # logging.info number of parameters per pytorch sub module\n msg = \"\"\n for name, param in self.named_parameters():\n if name.startswith(\"add_bones\"):\n continue # compact print\n msg = msg + f\"[{name}:{param.numel()/1e3:.1f}K] \" \n # logging.info(f\"{name}, {param.numel()/1e6:.3f}M\")\n logging.info(msg)\n return\n\n def _init_act(self, max_s_value, min_s_value):\n def s_act(x):\n if isinstance(x, float):\n x = torch.tensor(x).squeeze()\n return min_s_value + torch.sigmoid(x) * (max_s_value - min_s_value)\n\n def s_inv_act(x):\n if isinstance(x, float):\n x = torch.tensor(x).squeeze()\n y = (x - min_s_value) / (max_s_value - min_s_value) + 1e-5\n y = torch.logit(y)\n assert not torch.isnan(\n y\n ).any(), f\"{x.min()}, {x.max()}, {y.min()}, {y.max()}\"\n return y\n\n def o_act(x):\n if isinstance(x, float):\n x = torch.tensor(x).squeeze()\n return torch.sigmoid(x)\n\n def o_inv_act(x):\n if isinstance(x, float):\n x = torch.tensor(x).squeeze()\n return torch.logit(x)\n\n self.s_act = s_act\n self.s_inv_act = s_inv_act\n self.o_act = o_act\n self.o_inv_act = o_inv_act\n\n return\n\n @property\n def N(self):\n return len(self._xyz)\n\n @property\n def get_x(self):\n return self._xyz\n\n @property\n def get_R(self):\n return quaternion_to_matrix(self._rotation)\n\n @property\n def get_o(self):\n return self.o_act(self._opacity)\n\n @property\n def get_s(self):\n return self.s_act(self._scaling)\n\n @property\n def get_c(self):\n return torch.cat([self._features_dc, self._features_rest], dim=-1)\n\n def cache_for_fast(self):\n _cached_W, _ = self.template.forward(None, self._xyz)\n self._cached_W = _cached_W.detach().clone()\n return\n\n def forward(\n self, theta, trans, additional_dict={}, active_sph_order=None, fast=False\n ):\n # * fast will use the cached per point attr, no query anymore\n # TODO: the additional dict contain info to do flexible skinning: it can contain the As directly for optimization, or it can contain t index to query some buffers to provide As, or it can contain t along with the input theta to query some MLP;\n\n # TODO: if use vol memory, every forward update self.xxx, and remove them from parameters, pretend that the attributes are per point, but actually they are queried every forward\n\n # theta: B,24,3; trans: B,3\n B = len(theta)\n if active_sph_order is None:\n active_sph_order = self.max_sph_order\n else:\n assert (\n active_sph_order <= self.max_sph_order\n ), \"active_sph_order should be smaller\"\n sph_dim = 3 * sph_order2nfeat(active_sph_order)\n\n xyz = self.get_x\n mu_can = xyz\n frame_can = self.get_R\n s = self.get_s\n o = self.get_o\n sph = self.get_c[:, :sph_dim]\n\n mu_can = mu_can[None].expand(B, -1, -1)\n frame_can = frame_can[None].expand(B, -1, -1, -1)\n\n if fast:\n # only forward skeleton, no query voxel\n _, A = self.template.forward(theta, None)\n W = self._cached_W[None].expand(B, -1, -1)\n else:\n W, A = self.template.forward(theta, mu_can)\n if self._w_correction_dc.shape[-1] > 0:\n W = W + self._w_correction_dc[None]\n T = torch.einsum(\"bnj, bjrc -> bnrc\", W[..., : self.num_bones], A)\n\n # * additional correction here\n if \"pose\" not in additional_dict.keys():\n # maybe later we want to viz the different pose effect in cano\n additional_dict[\"pose\"] = theta.reshape(B, -1)[:, 3:]\n add_A = self.add_bones(**additional_dict)\n if add_A is not None:\n if theta.ndim == 2:\n global_axis_angle = theta[:, :3]\n else:\n global_axis_angle = theta[:, 0]\n global_orient_action = self.template.get_rot_action(global_axis_angle) # B,4,4\n add_A = torch.einsum(\"bij, bnjk -> bnik\", global_orient_action, add_A)\n\n if self.w_memory_type == \"point\":\n assert self._w_correction_rest.shape[-1] > 0\n add_W = self._w_correction_rest[None].expand(B, -1, -1)\n elif self.w_memory_type == \"voxel\":\n add_W = W[..., self.num_bones :]\n\n add_T = torch.einsum(\"bnj, bjrc -> bnrc\", add_W, add_A)\n T = T + add_T # Linear\n additional_dict[\"As\"] = add_A\n\n R, t = T[:, :, :3, :3], T[:, :, :3, 3] # B,N,3,3; B,N,3\n\n mu = torch.einsum(\"bnij,bnj->bni\", R, mu_can) + t # B,N,3\n frame = torch.einsum(\"bnij,bnjk->bnik\", R, frame_can) # B,N,3,3\n\n s = s[None].expand(B, -1, -1) # B,N,1\n o = o[None].expand(B, -1, -1) # B,N,1\n sph = sph[:, :sph_dim][None].expand(B, -1, -1) # B,N,C\n\n mu = mu + trans[:, None, :]\n\n return mu, frame, s, o, sph, additional_dict\n\n def compute_reg(self, K):\n # !can cancel the knn, but the w reg is critical\n if K > 0:\n xyz = self._xyz\n # todo: this can be cached and updated every several steps!!\n dist_sq, nn_ind, _ = knn_points(xyz[None], xyz[None], K=K, return_nn=False)\n nn_ind = nn_ind.squeeze(0)\n # reg the std inside knn\n q = self._rotation[nn_ind, :] # N,K,4\n s = self.get_s[nn_ind, :] # N,K,3\n o = self.get_o[nn_ind, :] # N,K,1\n q_std = q.std(dim=1).mean()\n s_std = s.std(dim=1).mean()\n o_std = o.std(dim=1).mean()\n\n cd = self._features_dc[nn_ind, :] # N,K,3\n ch = self._features_rest[nn_ind, :] # N,K,C\n cd_std = cd.std(dim=1).mean()\n ch_std = ch.std(dim=1).mean()\n if ch.shape[-1] == 0:\n ch_std = torch.zeros_like(ch_std)\n\n w = self._w_correction_dc[nn_ind, :] # N,K,3\n w_rest = self._w_correction_rest[nn_ind, :] # N,K,C\n f = self._features_localcode[nn_ind, :] # N,K,C\n w_std = w.std(dim=1).mean()\n w_rest_std = w_rest.std(dim=1).mean()\n f_std = f.std(dim=1).mean()\n if w.shape[-1] == 0:\n w_std = torch.zeros_like(cd_std)\n if w_rest.shape[-1] == 0:\n w_rest_std = torch.zeros_like(cd_std)\n if f.shape[-1] == 0:\n f_std = torch.zeros_like(cd_std)\n else:\n dummy = torch.zeros(1).to(self._xyz).squeeze()\n q_std, s_std, o_std = dummy, dummy, dummy\n cd_std, ch_std = dummy, dummy\n w_std, w_rest_std, f_std = dummy, dummy, dummy\n dist_sq = dummy\n\n w_norm = self._w_correction_dc.norm(dim=-1).mean() # N\n w_rest_norm = self._w_correction_rest.norm(dim=-1).mean() # N\n\n if self.w_memory_type == \"voxel\":\n # update the w related std and norm\n w_std = self.template.voxel_deformer.get_tv(\"dc\")\n w_rest_std = self.template.voxel_deformer.get_tv(\"rest\")\n w_norm = self.template.voxel_deformer.get_mag(\"dc\")\n w_rest_norm = self.template.voxel_deformer.get_mag(\"rest\")\n\n max_s_square = torch.mean((self.get_s.max(dim=1).values) ** 2)\n\n return (\n q_std,\n s_std,\n o_std,\n cd_std,\n ch_std,\n w_std,\n w_rest_std,\n f_std,\n w_norm,\n w_rest_norm,\n dist_sq.mean(),\n max_s_square,\n )\n\n def get_optimizable_list(\n self,\n lr_p=0.00016,\n lr_q=0.001,\n lr_s=0.005,\n lr_o=0.05,\n lr_sph=0.0025,\n lr_sph_rest=None,\n lr_w=0.001,\n lr_w_rest=0.001,\n lr_f=0.0001,\n ):\n lr_sph_rest = lr_sph / 20 if lr_sph_rest is None else lr_sph_rest\n l = [\n {\"params\": [self._xyz], \"lr\": lr_p, \"name\": \"xyz\"},\n {\"params\": [self._opacity], \"lr\": lr_o, \"name\": \"opacity\"},\n {\"params\": [self._scaling], \"lr\": lr_s, \"name\": \"scaling\"},\n {\"params\": [self._rotation], \"lr\": lr_q, \"name\": \"rotation\"},\n {\"params\": [self._features_dc], \"lr\": lr_sph, \"name\": \"f_dc\"},\n {\"params\": [self._features_rest], \"lr\": lr_sph_rest, \"name\": \"f_rest\"},\n {\"params\": [self._w_correction_dc], \"lr\": lr_w, \"name\": \"w_dc\"},\n {\"params\": [self._w_correction_rest], \"lr\": lr_w_rest, \"name\": \"w_rest\"},\n {\"params\": [self._features_localcode], \"lr\": lr_f, \"name\": \"f_localcode\"},\n ]\n if self.w_memory_type == \"voxel\":\n if self.w_dc_dim > 0:\n l.append(\n {\n \"params\": [self.template.voxel_deformer.voxel_w_correction],\n \"lr\": lr_w,\n \"name\": \"w_dc_vox\",\n }\n )\n if self.w_rest_dim > 0:\n l.append(\n {\n \"params\": [self.template.voxel_deformer.additional_correction],\n \"lr\": lr_w_rest,\n \"name\": \"w_rest_vox\",\n }\n )\n return l\n\n # * Gaussian Control\n def record_xyz_grad_radii(self, viewspace_point_tensor, radii, update_filter):\n # Record the gradient norm, invariant across different poses\n assert len(viewspace_point_tensor) == self.N\n self.xyz_gradient_accum[update_filter] += torch.norm(\n viewspace_point_tensor.grad[update_filter, :2], dim=-1, keepdim=False\n )\n self.xyz_gradient_denom[update_filter] += 1\n self.max_radii2D[update_filter] = torch.max(\n self.max_radii2D[update_filter], radii[update_filter]\n )\n return\n\n def _densification_postprocess(\n self,\n optimizer,\n new_xyz,\n new_r,\n new_s,\n new_o,\n new_sph_dc,\n new_sph_rest,\n new_w_dc,\n new_w_rest,\n new_localcode,\n ):\n d = {\n \"xyz\": new_xyz,\n \"f_dc\": new_sph_dc,\n \"f_rest\": new_sph_rest,\n \"opacity\": new_o,\n \"scaling\": new_s,\n \"rotation\": new_r,\n \"w_dc\": new_w_dc,\n \"w_rest\": new_w_rest,\n \"f_localcode\": new_localcode,\n }\n d = {k: v for k, v in d.items() if v is not None}\n\n # First cat to optimizer and then return to self\n optimizable_tensors = cat_tensors_to_optimizer(optimizer, d)\n\n self._xyz = optimizable_tensors[\"xyz\"]\n self._opacity = optimizable_tensors[\"opacity\"]\n self._scaling = optimizable_tensors[\"scaling\"]\n self._rotation = optimizable_tensors[\"rotation\"]\n self._features_dc = optimizable_tensors[\"f_dc\"]\n self._features_rest = optimizable_tensors[\"f_rest\"]\n self._w_correction_dc = optimizable_tensors[\"w_dc\"]\n self._w_correction_rest = optimizable_tensors[\"w_rest\"]\n self._features_localcode = optimizable_tensors[\"f_localcode\"]\n\n self.xyz_gradient_accum = torch.zeros(self._xyz.shape[0], device=\"cuda\")\n self.xyz_gradient_denom = torch.zeros(self._xyz.shape[0], device=\"cuda\")\n self.max_radii2D = torch.cat(\n [self.max_radii2D, torch.zeros_like(new_xyz[:, 0])], dim=0\n )\n return\n\n def _densify_and_clone(self, optimizer, grad_norm, grad_threshold, scale_th):\n # Extract points that satisfy the gradient condition\n # padding for enabling both call of clone and split\n padded_grad = torch.zeros((self.N), device=\"cuda\")\n padded_grad[: grad_norm.shape[0]] = grad_norm.squeeze()\n selected_pts_mask = torch.where(padded_grad >= grad_threshold, True, False)\n selected_pts_mask = torch.logical_and(\n selected_pts_mask,\n torch.max(self.get_s, dim=1).values <= scale_th,\n )\n if selected_pts_mask.sum() == 0:\n return 0\n\n new_xyz = self._xyz[selected_pts_mask]\n new_rotation = self._rotation[selected_pts_mask]\n new_scaling = self._scaling[selected_pts_mask]\n new_opacities = self._opacity[selected_pts_mask]\n new_features_dc = self._features_dc[selected_pts_mask]\n new_features_rest = self._features_rest[selected_pts_mask]\n new_w_dc = self._w_correction_dc[selected_pts_mask]\n new_w_rest = self._w_correction_rest[selected_pts_mask]\n new_localcode = self._features_localcode[selected_pts_mask]\n\n self._densification_postprocess(\n optimizer,\n new_xyz=new_xyz,\n new_r=new_rotation,\n new_s=new_scaling,\n new_o=new_opacities,\n new_sph_dc=new_features_dc,\n new_sph_rest=new_features_rest,\n new_w_dc=new_w_dc,\n new_w_rest=new_w_rest,\n new_localcode=new_localcode,\n )\n\n return len(new_xyz)\n\n def _densify_and_split(\n self,\n optimizer,\n grad_norm,\n grad_threshold,\n scale_th,\n N=2,\n ):\n # Extract points that satisfy the gradient condition\n _scaling = self.get_s\n # padding for enabling both call of clone and split\n padded_grad = torch.zeros((self.N), device=\"cuda\")\n padded_grad[: grad_norm.shape[0]] = grad_norm.squeeze()\n selected_pts_mask = torch.where(padded_grad >= grad_threshold, True, False)\n selected_pts_mask = torch.logical_and(\n selected_pts_mask,\n torch.max(_scaling, dim=1).values > scale_th,\n )\n if selected_pts_mask.sum() == 0:\n return 0\n\n stds = _scaling[selected_pts_mask].repeat(N, 1)\n means = torch.zeros((stds.size(0), 3), device=\"cuda\")\n samples = torch.normal(mean=means, std=stds)\n rots = quaternion_to_matrix(self._rotation[selected_pts_mask]).repeat(N, 1, 1)\n new_xyz = torch.bmm(rots, samples.unsqueeze(-1)).squeeze(-1) + self._xyz[\n selected_pts_mask\n ].repeat(N, 1)\n new_scaling = _scaling[selected_pts_mask].repeat(N, 1) / (0.8 * N)\n new_scaling = torch.clamp(new_scaling, max=self.max_scale, min=self.min_scale)\n new_scaling = self.s_inv_act(new_scaling)\n new_rotation = self._rotation[selected_pts_mask].repeat(N, 1)\n new_features_dc = self._features_dc[selected_pts_mask].repeat(N, 1)\n new_features_rest = self._features_rest[selected_pts_mask].repeat(N, 1)\n new_opacities = self._opacity[selected_pts_mask].repeat(N, 1)\n new_w_dc = self._w_correction_dc[selected_pts_mask].repeat(N, 1)\n new_w_rest = self._w_correction_rest[selected_pts_mask].repeat(N, 1)\n new_localcode = self._features_localcode[selected_pts_mask].repeat(N, 1)\n\n self._densification_postprocess(\n optimizer,\n new_xyz=new_xyz,\n new_r=new_rotation,\n new_s=new_scaling,\n new_o=new_opacities,\n new_sph_dc=new_features_dc,\n new_sph_rest=new_features_rest,\n new_w_dc=new_w_dc,\n new_w_rest=new_w_rest,\n new_localcode=new_localcode,\n )\n\n prune_filter = torch.cat(\n (\n selected_pts_mask,\n torch.zeros(N * selected_pts_mask.sum(), device=\"cuda\", dtype=bool),\n )\n )\n self._prune_points(optimizer, prune_filter)\n return len(new_xyz)\n\n def densify(self, optimizer, max_grad, percent_dense, extent, verbose=True):\n grads = self.xyz_gradient_accum / self.xyz_gradient_denom\n grads[grads.isnan()] = 0.0\n\n # n_clone = self._densify_and_clone(optimizer, grads, max_grad)\n n_clone = self._densify_and_clone(\n optimizer, grads, max_grad, percent_dense * extent\n )\n n_split = self._densify_and_split(\n optimizer, grads, max_grad, percent_dense * extent, N=2\n )\n\n if verbose:\n logging.info(f\"Densify: Clone[+] {n_clone}, Split[+] {n_split}\")\n # logging.info(f\"Densify: Clone[+] {n_clone}\")\n # torch.cuda.empty_cache()\n return\n\n def random_grow(self, optimizer, num_factor=0.05, std=0.1, init_opa_value=0.1):\n # * New operation, randomly add largely disturbed points to the geometry\n ind = torch.randperm(self.N)[: int(self.N * num_factor)]\n selected_pts_mask = torch.zeros(self.N, dtype=bool, device=\"cuda\")\n selected_pts_mask[ind] = True\n\n new_xyz = self._xyz[selected_pts_mask]\n noise = torch.randn_like(new_xyz) * std\n new_xyz = new_xyz + noise\n new_features_dc = self._features_dc[selected_pts_mask]\n new_features_rest = self._features_rest[selected_pts_mask]\n\n new_opacities = torch.ones_like(self._opacity[selected_pts_mask])\n new_opacities = new_opacities * self.o_inv_act(init_opa_value)\n\n new_scaling = self._scaling[selected_pts_mask]\n new_rotation = self._rotation[selected_pts_mask]\n\n new_w_dc = self._w_correction_dc[selected_pts_mask]\n new_w_rest = self._w_correction_rest[selected_pts_mask]\n new_localcode = self._features_localcode[selected_pts_mask]\n\n self._densification_postprocess(\n optimizer,\n new_xyz=new_xyz,\n new_r=new_rotation,\n new_s=new_scaling,\n new_o=new_opacities,\n new_sph_dc=new_features_dc,\n new_sph_rest=new_features_rest,\n new_w_dc=new_w_dc,\n new_w_rest=new_w_rest,\n new_localcode=new_localcode,\n )\n logging.info(f\"Random grow: {len(new_xyz)}\")\n return len(new_xyz)\n\n def prune_points(self, optimizer, min_opacity, max_screen_size, verbose=True):\n opacity = self.o_act(self._opacity)\n prune_mask = (opacity < min_opacity).squeeze()\n if max_screen_size: # if a point is too large\n big_points_vs = self.max_radii2D > max_screen_size\n prune_mask = torch.logical_or(prune_mask, big_points_vs)\n # * reset the maxRadii\n self.max_radii2D = torch.zeros_like(self.max_radii2D)\n self._prune_points(optimizer, prune_mask)\n if verbose:\n logging.info(f\"Prune: {prune_mask.sum()}\")\n\n def _prune_points(self, optimizer, mask):\n valid_points_mask = ~mask\n optimizable_tensors = prune_optimizer(\n optimizer,\n valid_points_mask,\n exclude_names=self.op_update_exclude,\n )\n\n self._xyz = optimizable_tensors[\"xyz\"]\n if getattr(self, \"color_memory\", None) is None:\n self._features_dc = optimizable_tensors[\"f_dc\"]\n self._features_rest = optimizable_tensors[\"f_rest\"]\n self._opacity = optimizable_tensors[\"opacity\"]\n self._scaling = optimizable_tensors[\"scaling\"]\n self._rotation = optimizable_tensors[\"rotation\"]\n self._w_correction_dc = optimizable_tensors[\"w_dc\"]\n self._w_correction_rest = optimizable_tensors[\"w_rest\"]\n self._features_localcode = optimizable_tensors[\"f_localcode\"]\n\n self.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask]\n self.xyz_gradient_denom = self.xyz_gradient_denom[valid_points_mask]\n self.max_radii2D = self.max_radii2D[valid_points_mask]\n # torch.cuda.empty_cache()\n return\n\n @torch.no_grad()\n def regaussian(self, optimizer, max_scale=0.03):\n # raise NotImplementedError(\"TODO, like split\")\n # * New operation, manually split the large gaussians with smaller ones to approximate\n # * Now, try bi-split\n\n # Extract points that satisfy the gradient condition\n _scaling = self.get_s\n selected_pts_mask = torch.max(_scaling, dim=1).values > max_scale\n\n step = 0\n before_num = self.N\n while selected_pts_mask.any():\n # This can be done more than 3 times, becuase there may be huge gaussians, which should be devided several times\n fg_xyz = self._xyz[selected_pts_mask]\n fg_scale = _scaling[selected_pts_mask]\n fg_frame = quaternion_to_matrix(self._rotation[selected_pts_mask])\n # each column is the direction of axis in global frame\n axis_ind = torch.argmax(fg_scale, dim=1)\n axis_scale = fg_scale.max(dim=1).values\n # select column\n axis_dir = torch.gather(\n fg_frame, dim=2, index=axis_ind[:, None, None].expand(-1, 3, -1)\n ).squeeze(\n -1\n ) # N,3\n new_x1 = fg_xyz + axis_dir.squeeze() * axis_scale[:, None] / 2.0\n new_x2 = fg_xyz - axis_dir.squeeze() * axis_scale[:, None] / 2.0\n # Repeat will change [1,2,3...] to [1,2,3..., 1,2,3...]\n new_xyz = torch.cat([new_x1, new_x2], dim=0).reshape(-1, 3)\n new_scaling = _scaling[selected_pts_mask]\n new_scaling = torch.scatter(\n new_scaling,\n dim=1,\n index=axis_ind[:, None],\n src=axis_scale[:, None] / 2.0,\n ).repeat(2, 1)\n new_scaling = torch.clamp(\n new_scaling, max=self.max_scale, min=self.min_scale\n )\n new_scaling = self.s_inv_act(new_scaling)\n new_rotation = self._rotation[selected_pts_mask].repeat(2, 1)\n new_features_dc = self._features_dc[selected_pts_mask].repeat(2, 1)\n new_features_rest = self._features_rest[selected_pts_mask].repeat(2, 1)\n new_opacities = self._opacity[selected_pts_mask].repeat(2, 1)\n new_w_dc = self._w_correction_dc[selected_pts_mask].repeat(2, 1)\n new_w_rest = self._w_correction_rest[selected_pts_mask].repeat(2, 1)\n new_localcode = self._features_localcode[selected_pts_mask].repeat(2, 1)\n\n self._densification_postprocess(\n optimizer,\n new_xyz=new_xyz.float(),\n new_r=new_rotation.float(),\n new_s=new_scaling.float(),\n new_o=new_opacities.float(),\n new_sph_dc=new_features_dc.float(),\n new_sph_rest=new_features_rest.float(),\n new_w_dc=new_w_dc.float(),\n new_w_rest=new_w_rest.float(),\n new_localcode=new_localcode.float(),\n )\n\n prune_filter = torch.cat(\n (\n selected_pts_mask,\n torch.zeros(2 * selected_pts_mask.sum(), device=\"cuda\", dtype=bool),\n )\n )\n self._prune_points(optimizer, prune_filter)\n\n step += 1\n logging.info(\n f\"Regaussian-[{step}], {selected_pts_mask.sum()} ({selected_pts_mask.float().mean()*100}% pts-scale>{max_scale})\"\n )\n\n _scaling = self.get_s\n selected_pts_mask = torch.max(_scaling, dim=1).values > max_scale\n logging.info(f\"Re-gaussian: {before_num} -> {self.N}\")\n return\n\n def reset_opacity(self, optimizer, value=0.01, verbose=True):\n opacities_new = self.o_inv_act(\n torch.min(self.o_act(self._opacity), torch.ones_like(self._opacity) * value)\n )\n optimizable_tensors = replace_tensor_to_optimizer(\n optimizer, opacities_new, \"opacity\"\n )\n if verbose:\n logging.info(f\"Reset opacity to {value}\")\n self._opacity = optimizable_tensors[\"opacity\"]\n\n def load(self, ckpt):\n # because N changed, have to re-init the buffers\n self._xyz = nn.Parameter(torch.as_tensor(ckpt[\"_xyz\"], dtype=torch.float32))\n\n self._features_dc = nn.Parameter(\n torch.as_tensor(ckpt[\"_features_dc\"], dtype=torch.float32)\n )\n self._features_rest = nn.Parameter(\n torch.as_tensor(ckpt[\"_features_rest\"], dtype=torch.float32)\n )\n self._opacity = nn.Parameter(\n torch.as_tensor(ckpt[\"_opacity\"], dtype=torch.float32)\n )\n self._scaling = nn.Parameter(\n torch.as_tensor(ckpt[\"_scaling\"], dtype=torch.float32)\n )\n self._rotation = nn.Parameter(\n torch.as_tensor(ckpt[\"_rotation\"], dtype=torch.float32)\n )\n self._w_correction_dc = nn.Parameter(\n torch.as_tensor(ckpt[\"_w_correction_dc\"], dtype=torch.float32)\n )\n self._w_correction_rest = nn.Parameter(\n torch.as_tensor(ckpt[\"_w_correction_rest\"], dtype=torch.float32)\n )\n self._features_localcode = nn.Parameter(\n torch.as_tensor(ckpt[\"_features_localcode\"], dtype=torch.float32)\n )\n self.xyz_gradient_accum = torch.as_tensor(\n ckpt[\"xyz_gradient_accum\"], dtype=torch.float32\n )\n self.xyz_gradient_denom = torch.as_tensor(\n ckpt[\"xyz_gradient_denom\"], dtype=torch.int64\n )\n self.max_radii2D = torch.as_tensor(ckpt[\"max_radii2D\"], dtype=torch.float32)\n\n # * add bones may have different total_t\n if \"add_bones.dt_list\" in ckpt.keys():\n self.add_bones.total_t = ckpt[\"add_bones.dt_list\"].shape[0]\n self.add_bones.dt_list = nn.Parameter(\n torch.as_tensor(ckpt[\"add_bones.dt_list\"], dtype=torch.float32)\n )\n self.add_bones.dr_list = nn.Parameter(\n torch.as_tensor(ckpt[\"add_bones.dr_list\"], dtype=torch.float32)\n )\n # load others\n self.load_state_dict(ckpt, strict=True)\n # this is critical, reinit the funcs\n self._init_act(self.max_scale, self.min_scale)\n return" }, { "identifier": "AdditionalBones", "path": "lib_gart/model.py", "snippet": "class AdditionalBones(nn.Module):\n def __init__(\n self, # additional bones\n num_bones: int = 0,\n total_t: int = 0, # any usage of time should use this!\n mode=\"pose-mlp\",\n # pose-mlp\n pose_dim=23 * 3,\n mlp_hidden_dims=[256, 256, 256, 256],\n mlp_act=nn.LeakyReLU,\n # pose+t-mlp\n ):\n super().__init__()\n self.num_bones = num_bones\n if self.num_bones == 0:\n return\n self.mode = mode\n assert self.mode in [\"pose-mlp\", \"pose+t-mlp\", \"delta-list\", \"list\"]\n self.total_t = total_t\n\n if self.mode == \"pose-mlp\":\n self.pose_dim = pose_dim\n self.mlp_layers = nn.ModuleList()\n c_in = self.pose_dim\n for c_out in mlp_hidden_dims:\n self.mlp_layers.append(nn.Sequential(nn.Linear(c_in, c_out), mlp_act()))\n c_in = c_out\n self.mlp_output_head = nn.Linear(c_in, 7 * self.num_bones, bias=False)\n with torch.no_grad():\n self.mlp_output_head.weight.data = (\n torch.randn_like(self.mlp_output_head.weight.data) * 1e-3\n )\n elif self.mode == \"delta-list\":\n self.dr_list = nn.Parameter(torch.zeros(self.total_t, num_bones, 3))\n self.dt_list = nn.Parameter(torch.zeros(self.total_t, num_bones, 3))\n else:\n raise NotImplementedError()\n\n return\n\n def forward(self, pose=None, t=None, As=None):\n if self.num_bones == 0:\n # * No additional bones\n return None\n if As is not None:\n # * Directly return if As already provided\n return As\n if self.mode == \"pose-mlp\":\n assert pose is not None\n assert pose.ndim == 2 and pose.shape[1] == self.pose_dim\n B = len(pose)\n x = pose\n for layer in self.mlp_layers:\n x = layer(x)\n x = self.mlp_output_head(x).reshape(B, -1, 7)\n q, t = x[:, :, :4], x[:, :, 4:]\n q[..., 0] = q[..., 0] + 1.0\n q = F.normalize(q, dim=-1)\n R = quaternion_to_matrix(q)\n Rt = torch.cat([R, t[:, :, :, None]], dim=-1)\n bottom = torch.zeros_like(Rt[:, :, 0:1])\n bottom[:, :, :, -1] = 1.0\n As = torch.cat([Rt, bottom], dim=2)\n return As\n elif self.mode == \"delta-list\":\n As = self._roll_out_continuous_T()\n if t is None:\n B = len(pose)\n # # ! If no time is set, now return eye(4)\n # ret = (\n # torch.eye(4)\n # .to(As.device)[None, None]\n # .repeat(B, self.num_bones, 1, 1)\n # )\n # ! If no time is set, now return first frame\n ret = As[0][None].repeat(B, 1, 1, 1)\n else:\n if isinstance(t, int):\n t = torch.tensor([t]).to(As.device)\n ret = As[t]\n return ret\n else:\n raise NotImplementedError()\n\n return # As in canonical frame\n\n def _roll_out_continuous_T(self):\n # ! this assumes continuous frames, single frame!\n R = axis_angle_to_matrix(self.dr_list)\n dT = (\n torch.eye(4).to(R.device)[None, None].repeat(self.total_t, R.shape[1], 1, 1)\n )\n dT[:, :, :3, :3] = dT[:, :, :3, :3] * 0 + R\n dT[:, :, :3, 3] = dT[:, :, :3, 3] * 0 + self.dt_list\n T = [dT[0]]\n for i in range(1, self.total_t):\n T.append(torch.einsum(\"nij, njk->nik\", T[-1], dT[i]))\n T = torch.stack(T, dim=0)\n return T" }, { "identifier": "render_cam_pcl", "path": "lib_render/gauspl_renderer.py", "snippet": "def render_cam_pcl(\n xyz,\n frame,\n scale,\n opacity,\n color_feat,\n H,\n W,\n CAM_K,\n verbose=False,\n active_sph_order=0,\n bg_color=[1.0, 1.0, 1.0],\n):\n # ! Camera is at origin, every input is in camera coordinate space\n\n S = torch.zeros_like(frame)\n S[:, 0, 0] = scale[:, 0]\n S[:, 1, 1] = scale[:, 1]\n S[:, 2, 2] = scale[:, 2]\n actual_covariance = frame @ (S**2) @ frame.permute(0, 2, 1)\n\n # Create zero tensor. We will use it to make pytorch return gradients of the 2D (screen-space) means\n device = xyz.device\n screenspace_points = (\n torch.zeros_like(xyz, dtype=xyz.dtype, requires_grad=True, device=xyz.device) + 0\n )\n # screenspace_points.retain_grad()\n try:\n screenspace_points.retain_grad()\n except:\n pass\n\n # * Specially handle the non-centered camera, using first padding and finally crop\n if abs(H // 2 - CAM_K[1, 2]) > 1.0 or abs(W // 2 - CAM_K[0, 2]) > 1.0:\n center_handling_flag = True\n left_w, right_w = CAM_K[0, 2], W - CAM_K[0, 2]\n top_h, bottom_h = CAM_K[1, 2], H - CAM_K[1, 2]\n new_W = int(2 * max(left_w, right_w))\n new_H = int(2 * max(top_h, bottom_h))\n else:\n center_handling_flag = False\n new_W, new_H = W, H\n\n # Set up rasterization configuration\n FoVx = focal2fov(CAM_K[0, 0], new_W)\n FoVy = focal2fov(CAM_K[1, 1], new_H)\n tanfovx = math.tan(FoVx * 0.5)\n tanfovy = math.tan(FoVy * 0.5)\n\n # TODO: Check dynamic gaussian repos and original gaussian repo, they use projection matrix to handle non-centered K, not using this stupid padding like me\n viewmatrix = torch.from_numpy(getWorld2View2(np.eye(3), np.zeros(3)).transpose(0, 1)).to(device)\n projection_matrix = (\n getProjectionMatrix(znear=0.01, zfar=1.0, fovX=FoVx, fovY=FoVy).transpose(0, 1).to(device)\n )\n full_proj_transform = (viewmatrix.unsqueeze(0).bmm(projection_matrix.unsqueeze(0))).squeeze(0)\n camera_center = viewmatrix.inverse()[3, :3]\n\n raster_settings = GaussianRasterizationSettings(\n image_height=new_H,\n image_width=new_W,\n tanfovx=tanfovx,\n tanfovy=tanfovy,\n bg=torch.tensor(bg_color, dtype=torch.float32, device=device),\n scale_modifier=1.0,\n viewmatrix=viewmatrix,\n projmatrix=full_proj_transform,\n sh_degree=0, # ! use pre-compute color!\n campos=camera_center,\n prefiltered=False,\n debug=False,\n )\n rasterizer = GaussianRasterizer(raster_settings=raster_settings)\n\n means3D = xyz\n means2D = screenspace_points\n # opacity = torch.ones_like(means3D[:, 0]) * sigma\n\n # If precomputed 3d covariance is provided, use it. If not, then it will be computed from\n # scaling / rotation by the rasterizer.\n scales = None\n rotations = None\n # JH\n cov3D_precomp = strip_lowerdiag(actual_covariance)\n\n # If precomputed colors are provided, use them. Otherwise, if it is desired to precompute colors\n # from SHs in Python, do it. If not, then SH -> RGB conversion will be done by rasterizer.\n # xyz are in camera frame, so the dir in camera frame is just their normalized direction\n dir_cam = F.normalize(xyz, dim=-1)\n # P_w = Frame @ P_local\n dir_local = torch.einsum(\"nji,nj->ni\", frame, dir_cam) # note the transpose\n dir_local = F.normalize(\n dir_local, dim=-1\n ) # If frame is not SO(3) but Affinity, have to normalize\n N = len(color_feat)\n shs_view = color_feat.reshape(N, -1, 3) # N, Deg, Channels\n sh2rgb = eval_sh(active_sph_order, shs_view.permute(0, 2, 1), dir_local)\n colors_precomp = torch.clamp_min(sh2rgb + 0.5, 0.0)\n # colors_precomp = color_feat\n\n # Rasterize visible Gaussians to image, obtain their radii (on screen).\n\n start_time = time.time()\n ret = rasterizer(\n means3D=means3D.float(),\n means2D=means2D.float(),\n shs=None,\n colors_precomp=colors_precomp.float(),\n opacities=opacity.float(),\n scales=scales,\n rotations=rotations,\n cov3D_precomp=cov3D_precomp.float(),\n )\n if len(ret) == 2:\n rendered_image, radii = ret\n depth, alpha = None, None\n elif len(ret) == 4:\n rendered_image, radii, depth, alpha = ret\n else:\n raise ValueError(f\"Unexpected return value from rasterizer with len={len(ret)}\")\n if verbose:\n print(\n f\"render time: {(time.time() - start_time)*1000:.3f}ms\",\n )\n ret = {\n \"rgb\": rendered_image,\n \"dep\": depth,\n \"alpha\": alpha,\n \"viewspace_points\": screenspace_points,\n \"visibility_filter\": radii > 0,\n \"radii\": radii,\n }\n if center_handling_flag:\n for k in [\"rgb\", \"dep\", \"alpha\"]:\n if ret[k] is None:\n continue\n if left_w > right_w:\n ret[k] = ret[k][:, :, :W]\n else:\n ret[k] = ret[k][:, :, -W:]\n if top_h > bottom_h:\n ret[k] = ret[k][:, :H, :]\n else:\n ret[k] = ret[k][:, -H:, :]\n return ret" }, { "identifier": "transform_mu_frame", "path": "lib_gart/model_utils.py", "snippet": "def transform_mu_frame(mu, frame, T):\n if len(mu) != len(T):\n assert len(mu) == 1 and len(frame) == 1\n mu = mu.expand(len(T), -1, -1)\n frame = frame.expand(len(T), -1, -1, -1)\n R, t = T[:, :3, :3], T[:, :3, 3]\n new_frame = torch.einsum(\"bij, bnjk->bnik\", R, frame)\n new_mu = torch.einsum(\"bij, bnj->bni\", R, mu) + t[:, None]\n return new_mu, new_frame" }, { "identifier": "viz_render", "path": "utils/viz.py", "snippet": "def viz_render(gt_rgb, gt_mask, pred_pkg, save_path=None):\n pred_rgb = pred_pkg[\"rgb\"].permute(1, 2, 0)\n pred_mask = pred_pkg[\"alpha\"].squeeze(0)\n pred_depth = pred_pkg[\"dep\"].squeeze(0)\n fig = plt.figure(figsize=(20, 5))\n plt.subplot(1, 5, 1)\n plt.imshow(torch.clamp(gt_rgb, 0.0, 1.0).detach().cpu().numpy())\n plt.title(\"GT\"), plt.axis(\"off\")\n plt.subplot(1, 5, 2)\n plt.imshow(torch.clamp(pred_rgb, 0.0, 1.0).detach().cpu().numpy())\n plt.title(\"Pred view\"), plt.axis(\"off\")\n plt.subplot(1, 5, 3)\n error = torch.clamp(abs(pred_rgb - gt_rgb), 0.0, 1.0).detach().cpu().numpy().max(axis=-1)\n cmap = plt.imshow(error)\n plt.title(\"Render Error (max in rgb)\"), plt.axis(\"off\")\n plt.colorbar(cmap, shrink=0.8)\n\n plt.subplot(1, 5, 4)\n error = torch.clamp(pred_mask - gt_mask, -1.0, 1.0).detach().cpu().numpy()\n cmap = plt.imshow(error)\n plt.title(\"(Pr - GT) Mask Error\"), plt.axis(\"off\")\n plt.colorbar(cmap, shrink=0.8)\n \n plt.subplot(1, 5, 5)\n depth = pred_depth.detach().cpu().numpy()\n cmap = plt.imshow(depth)\n plt.title(\"Pred Depth\"), plt.axis(\"off\")\n plt.colorbar(cmap, shrink=0.8)\n\n plt.tight_layout()\n fig.canvas.draw()\n fig_np = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)\n fig_np = fig_np.reshape(fig.canvas.get_width_height()[::-1] + (3,))\n if save_path is not None:\n plt.savefig(save_path)\n plt.close(fig)\n return fig_np" }, { "identifier": "sample_camera", "path": "lib_guidance/camera_sampling.py", "snippet": "def sample_camera(\n global_step=1,\n n_view=4,\n real_batch_size=1,\n random_azimuth_range=[-180.0, 180.0],\n random_elevation_range=[0.0, 30.0],\n eval_elevation_deg=15,\n camera_distance_range=[0.8, 1.0], # relative\n fovy_range=[15, 60],\n zoom_range=[1.0, 1.0],\n progressive_until=0,\n relative_radius=True,\n):\n # camera_perturb = 0.0\n # center_perturb = 0.0\n # up_perturb: 0.0\n\n # ! from uncond.py\n # ThreeStudio has progressive increase of camera poses, from eval to random\n r = min(1.0, global_step / (progressive_until + 1))\n elevation_range = [\n (1 - r) * eval_elevation_deg + r * random_elevation_range[0],\n (1 - r) * eval_elevation_deg + r * random_elevation_range[1],\n ]\n azimuth_range = [\n (1 - r) * 0.0 + r * random_azimuth_range[0],\n (1 - r) * 0.0 + r * random_azimuth_range[1],\n ]\n\n # sample elevation angles\n if random.random() < 0.5:\n # sample elevation angles uniformly with a probability 0.5 (biased towards poles)\n elevation_deg = (\n torch.rand(real_batch_size) * (elevation_range[1] - elevation_range[0])\n + elevation_range[0]\n ).repeat_interleave(n_view, dim=0)\n elevation = elevation_deg * math.pi / 180\n else:\n # otherwise sample uniformly on sphere\n elevation_range_percent = [\n (elevation_range[0] + 90.0) / 180.0,\n (elevation_range[1] + 90.0) / 180.0,\n ]\n # inverse transform sampling\n elevation = torch.asin(\n 2\n * (\n torch.rand(real_batch_size)\n * (elevation_range_percent[1] - elevation_range_percent[0])\n + elevation_range_percent[0]\n )\n - 1.0\n ).repeat_interleave(n_view, dim=0)\n elevation_deg = elevation / math.pi * 180.0\n\n # sample azimuth angles from a uniform distribution bounded by azimuth_range\n # ensures sampled azimuth angles in a batch cover the whole range\n azimuth_deg = (\n torch.rand(real_batch_size).reshape(-1, 1) + torch.arange(n_view).reshape(1, -1)\n ).reshape(-1) / n_view * (azimuth_range[1] - azimuth_range[0]) + azimuth_range[0]\n azimuth = azimuth_deg * math.pi / 180\n\n ######## Different from original ########\n # sample fovs from a uniform distribution bounded by fov_range\n fovy_deg = (\n torch.rand(real_batch_size) * (fovy_range[1] - fovy_range[0]) + fovy_range[0]\n ).repeat_interleave(n_view, dim=0)\n fovy = fovy_deg * math.pi / 180\n\n # sample distances from a uniform distribution bounded by distance_range\n camera_distances = (\n torch.rand(real_batch_size) * (camera_distance_range[1] - camera_distance_range[0])\n + camera_distance_range[0]\n ).repeat_interleave(n_view, dim=0)\n if relative_radius:\n scale = 1 / torch.tan(0.5 * fovy)\n camera_distances = scale * camera_distances\n\n # zoom in by decreasing fov after camera distance is fixed\n zoom = (\n torch.rand(real_batch_size) * (zoom_range[1] - zoom_range[0]) + zoom_range[0]\n ).repeat_interleave(n_view, dim=0)\n fovy = fovy * zoom\n fovy_deg = fovy_deg * zoom\n ###########################################\n\n # convert spherical coordinates to cartesian coordinates\n # right hand coordinate system, x back, y right, z up\n # elevation in (-90, 90), azimuth from +x to +y in (-180, 180)\n camera_positions = torch.stack(\n [\n camera_distances * torch.cos(elevation) * torch.cos(azimuth),\n camera_distances * torch.cos(elevation) * torch.sin(azimuth),\n camera_distances * torch.sin(elevation),\n ],\n dim=-1,\n )\n\n azimuth, elevation\n # build opencv camera\n z = -torch.stack(\n [\n torch.cos(elevation) * torch.cos(azimuth),\n torch.cos(elevation) * torch.sin(azimuth),\n torch.sin(elevation),\n ],\n -1,\n ) # nview, 3\n # up is 0,0,1\n x = torch.cross(z, torch.tensor([0.0, 0.0, 1.0], device=z.device).repeat(n_view, 1), -1)\n y = torch.cross(z, x, -1)\n\n R_wc = torch.stack([x, y, z], dim=2) # nview, 3, 3, col is basis\n t_wc = camera_positions\n\n T_wc = torch.eye(4, device=R_wc.device).repeat(n_view, 1, 1)\n T_wc[:, :3, :3] = R_wc\n T_wc[:, :3, 3] = t_wc\n\n return T_wc, fovy_deg # B,4,4, B" }, { "identifier": "fov2K", "path": "lib_guidance/camera_sampling.py", "snippet": "def fov2K(fov=90, H=256, W=256):\n if isinstance(fov, torch.Tensor):\n f = H / (2 * torch.tan(fov / 2 * np.pi / 180))\n K = torch.eye(3).repeat(fov.shape[0], 1, 1).to(fov)\n K[:, 0, 0], K[:, 0, 2] = f, W / 2.0\n K[:, 1, 1], K[:, 1, 2] = f, H / 2.0\n return K.clone()\n else:\n f = H / (2 * np.tan(fov / 2 * np.pi / 180))\n K = np.eye(3)\n K[0, 0], K[0, 2] = f, W / 2.0\n K[1, 1], K[1, 2] = f, H / 2.0\n return K.copy()" }, { "identifier": "opencv2blender", "path": "lib_guidance/camera_sampling.py", "snippet": "def opencv2blender(T):\n ret = T.clone()\n # y,z are negative\n ret[:, :, 1] *= -1\n ret[:, :, 2] *= -1\n return ret" }, { "identifier": "viz_spinning", "path": "viz_utils.py", "snippet": "@torch.no_grad()\ndef viz_spinning(\n model,\n pose,\n trans,\n H,\n W,\n K,\n save_path,\n time_index=None,\n n_spinning=10,\n model_mask=None,\n active_sph_order=0,\n bg_color=[1.0, 1.0, 1.0],\n):\n device = pose.device\n mu, fr, s, o, sph, additional_ret = model(\n pose, trans, {\"t\": time_index}, active_sph_order=active_sph_order\n )\n if model_mask is not None:\n assert len(model_mask) == mu.shape[1]\n mu = mu[:, model_mask.bool()]\n fr = fr[:, model_mask.bool()]\n s = s[:, model_mask.bool()]\n o = o[:, model_mask.bool()]\n sph = sph[:, model_mask.bool()]\n\n viz_frames = []\n for vid in range(n_spinning):\n spin_R = (\n torch.from_numpy(euler2mat(0, 2 * np.pi * vid / n_spinning, 0, \"sxyz\"))\n .to(device)\n .float()\n )\n spin_t = mu.mean(1)[0]\n spin_t = (torch.eye(3).to(device) - spin_R) @ spin_t[:, None]\n spin_T = torch.eye(4).to(device)\n spin_T[:3, :3] = spin_R\n spin_T[:3, 3] = spin_t.squeeze(-1)\n viz_mu, viz_fr = transform_mu_frame(mu, fr, spin_T[None])\n\n render_pkg = render_cam_pcl(\n viz_mu[0],\n viz_fr[0],\n s[0],\n o[0],\n sph[0],\n H,\n W,\n K,\n False,\n active_sph_order,\n bg_color=bg_color,\n )\n viz_frame = (\n torch.clamp(render_pkg[\"rgb\"], 0.0, 1.0)\n .permute(1, 2, 0)\n .detach()\n .cpu()\n .numpy()\n )\n viz_frame = (viz_frame * 255).astype(np.uint8)\n viz_frames.append(viz_frame)\n imageio.mimsave(save_path, viz_frames)\n return" }, { "identifier": "viz_human_all", "path": "viz_utils.py", "snippet": "@torch.no_grad()\ndef viz_human_all(\n solver,\n data_provider: RealDataOptimizablePoseProviderPose = None,\n ckpt_dir=None,\n training_skip=1,\n n_spinning=40,\n novel_pose_dir=\"novel_poses\",\n novel_skip=2,\n model=None,\n model_mask=None,\n viz_name=\"\",\n export_mesh_flag=False, # remove this from release version\n):\n if model is None:\n model = solver.load_saved_model(ckpt_dir)\n model.eval()\n\n viz_dir = osp.join(solver.log_dir, f\"{viz_name}_human_viz\")\n os.makedirs(viz_dir, exist_ok=True)\n\n active_sph_order = int(model.max_sph_order)\n\n if data_provider is not None:\n # if ckpt_dir is None:\n # ckpt_dir = solver.log_dir\n # pose_path = osp.join(ckpt_dir, \"pose.pth\")\n pose_base_list = data_provider.pose_base_list\n pose_rest_list = data_provider.pose_rest_list\n global_trans_list = data_provider.global_trans_list\n pose_list = torch.cat([pose_base_list, pose_rest_list], 1)\n pose_list, global_trans_list = pose_list.to(\n solver.device\n ), global_trans_list.to(solver.device)\n rgb_list = data_provider.rgb_list\n mask_list = data_provider.mask_list\n K_list = data_provider.K_list\n H, W = rgb_list.shape[1:3]\n else:\n H, W = 512, 512\n K_list = [torch.from_numpy(fov2K(45, H, W)).float().to(solver.device)]\n global_trans_list = torch.zeros(1, 3).to(solver.device)\n global_trans_list[0, -1] = 3.0\n\n # viz training\n if data_provider is not None:\n print(\"Viz training...\")\n viz_frames = []\n for t in range(len(pose_list)):\n if t % training_skip != 0:\n continue\n pose = pose_list[t][None]\n K = K_list[t]\n trans = global_trans_list[t][None]\n time_index = torch.Tensor([t]).long().to(solver.device)\n mu, fr, s, o, sph, _ = model(\n pose,\n trans,\n {\"t\": time_index}, # use time_index from training set\n active_sph_order=active_sph_order,\n )\n if model_mask is not None:\n assert len(model_mask) == mu.shape[1]\n mu = mu[:, model_mask.bool()]\n fr = fr[:, model_mask.bool()]\n s = s[:, model_mask.bool()]\n o = o[:, model_mask.bool()]\n sph = sph[:, model_mask.bool()]\n render_pkg = render_cam_pcl(\n mu[0],\n fr[0],\n s[0],\n o[0],\n sph[0],\n H,\n W,\n K,\n False,\n active_sph_order,\n bg_color=getattr(solver, \"DEFAULT_BG\", [1.0, 1.0, 1.0]),\n )\n viz_frame = viz_render(rgb_list[t], mask_list[t], render_pkg)\n viz_frames.append(viz_frame)\n imageio.mimsave(f\"{viz_dir}/training.gif\", viz_frames)\n\n # viz static spinning\n print(\"Viz spinning...\")\n can_pose = model.template.canonical_pose.detach()\n viz_base_R_opencv = np.asarray(euler2mat(np.pi, 0, 0, \"sxyz\"))\n viz_base_R_opencv = torch.from_numpy(viz_base_R_opencv).float()\n can_pose[0] = viz_base_R_opencv.to(can_pose.device)\n can_pose = matrix_to_axis_angle(can_pose)[None]\n dapose = torch.from_numpy(np.zeros((1, 24, 3))).float().to(solver.device)\n dapose[:, 1, -1] = np.pi / 4\n dapose[:, 2, -1] = -np.pi / 4\n dapose[:, 0] = matrix_to_axis_angle(solver.viz_base_R[None])[0]\n tpose = torch.from_numpy(np.zeros((1, 24, 3))).float().to(solver.device)\n tpose[:, 0] = matrix_to_axis_angle(solver.viz_base_R[None])[0]\n to_viz = {\"cano-pose\": can_pose, \"t-pose\": tpose, \"da-pose\": dapose}\n if data_provider is not None:\n to_viz[\"first-frame\"] = pose_list[0][None]\n\n for name, pose in to_viz.items():\n print(f\"Viz novel {name}...\")\n # if export_mesh_flag:\n # from lib_marchingcubes.gaumesh_utils import MeshExtractor\n # # also extract a mesh\n # mesh = solver.extract_mesh(model, pose)\n # mesh.export(f\"{viz_dir}/mc_{name}.obj\", \"obj\")\n\n # # for making figures, the rotation is in another way\n # viz_spinning_self_rotate(\n # model,\n # solver.viz_base_R.detach(),\n # pose,\n # global_trans_list[0][None],\n # H,\n # W,\n # K_list[0],\n # f\"{viz_dir}/{name}_selfrotate.gif\",\n # time_index=None, # if set to None and use t, the add_bone will hand this\n # n_spinning=n_spinning,\n # active_sph_order=model.max_sph_order,\n # )\n viz_spinning(\n model,\n pose,\n global_trans_list[0][None],\n H,\n W,\n K_list[0],\n f\"{viz_dir}/{name}.gif\",\n time_index=None, # if set to None and use t, the add_bone will hand this\n n_spinning=n_spinning,\n active_sph_order=model.max_sph_order,\n bg_color=getattr(solver, \"DEFAULT_BG\", [1.0, 1.0, 1.0]),\n )\n\n # viz novel pose dynamic spinning\n print(\"Viz novel seq...\")\n novel_pose_names = [\n f[:-4] for f in os.listdir(novel_pose_dir) if f.endswith(\".npy\")\n ]\n seq_viz_todo = {}\n for name in novel_pose_names:\n novel_pose_fn = osp.join(novel_pose_dir, f\"{name}.npy\")\n novel_poses = np.load(novel_pose_fn, allow_pickle=True)\n novel_poses = novel_poses[::novel_skip]\n N_frames = len(novel_poses)\n novel_poses = torch.from_numpy(novel_poses).float().to(solver.device)\n novel_poses = novel_poses.reshape(N_frames, 24, 3)\n\n seq_viz_todo[name] = (novel_poses, N_frames)\n if data_provider is not None:\n seq_viz_todo[\"training\"] = [pose_list, len(pose_list)]\n\n for name, (novel_poses, N_frames) in seq_viz_todo.items():\n base_R = solver.viz_base_R.detach().cpu().numpy()\n viz_frames = []\n K = K_list[0]\n for vid in range(N_frames):\n pose = novel_poses[vid][None]\n # pose = novel_poses[0][None] # debug\n rotation = euler2mat(2 * np.pi * vid / N_frames, 0.0, 0.0, \"syxz\")\n rotation = torch.from_numpy(rotation @ base_R).float().to(solver.device)\n pose[:, 0] = matrix_to_axis_angle(rotation[None])[0]\n trans = global_trans_list[0][None]\n mu, fr, s, o, sph, _ = model(\n pose,\n trans,\n # not pass in {}, so t is auto none\n additional_dict={},\n active_sph_order=active_sph_order,\n )\n if model_mask is not None:\n assert len(model_mask) == mu.shape[1]\n mu = mu[:, model_mask.bool()]\n fr = fr[:, model_mask.bool()]\n s = s[:, model_mask.bool()]\n o = o[:, model_mask.bool()]\n sph = sph[:, model_mask.bool()]\n render_pkg = render_cam_pcl(\n mu[0],\n fr[0],\n s[0],\n o[0],\n sph[0],\n H,\n W,\n K,\n False,\n active_sph_order,\n bg_color=getattr(solver, \"DEFAULT_BG\", [1.0, 1.0, 1.0]),\n # bg_color=[1.0, 1.0, 1.0], # ! use white bg for viz\n )\n viz_frame = (\n torch.clamp(render_pkg[\"rgb\"], 0.0, 1.0)\n .permute(1, 2, 0)\n .detach()\n .cpu()\n .numpy()\n )\n viz_frame = (viz_frame * 255).astype(np.uint8)\n viz_frames.append(viz_frame)\n imageio.mimsave(f\"{viz_dir}/novel_pose_{name}.gif\", viz_frames)\n return" }, { "identifier": "viz_dog_all", "path": "viz_utils.py", "snippet": "@torch.no_grad()\ndef viz_dog_all(solver, data_provider, model=None, ckpt_dir=None, viz_name=\"\"):\n if model is None:\n model = solver.load_saved_model(ckpt_dir)\n model.eval()\n viz_dir = osp.join(solver.log_dir, f\"{viz_name}_dog_viz\")\n os.makedirs(viz_dir, exist_ok=True)\n\n viz_pose = (\n torch.cat([data_provider.pose_base_list, data_provider.pose_rest_list], 1)\n .detach()\n .clone()\n )\n viz_pose = torch.mean(viz_pose, dim=0, keepdim=True) # use mean pose for viz \n limb = viz_pose[:, -7:] \n pose = viz_pose[:, :-7].reshape(-1, 35, 3)\n pose[:, :-3] = 0 # exclude ears and mouth poses\n\n viz_pose = torch.concat([pose.reshape(1, -1), limb], dim=1)\n viz_trans = torch.tensor([[0.0, -0.3, 25.0]], device=\"cuda:0\")\n\n viz_dog_spin(\n model.to(\"cuda\"),\n viz_pose,\n viz_trans,\n data_provider.H,\n data_provider.W,\n data_provider.K_list[0],\n save_path=osp.join(viz_dir, \"spin.gif\"),\n n_spinning=42,\n )\n\n viz_dog_spin2(\n model.to(\"cuda\"),\n viz_pose,\n viz_trans,\n data_provider.H,\n data_provider.W,\n data_provider.K_list[0],\n save_path=osp.join(viz_dir, \"spin2.gif\"),\n n_spinning=20,\n )\n\n ######################################################################\n # Dataset pose seq\n viz_pose = (\n torch.cat([data_provider.pose_base_list, data_provider.pose_rest_list], 1)\n .detach()\n .clone()\n )\n viz_pose = torch.mean(viz_pose, dim=0, keepdim=True)\n pose = viz_pose[:, :-7].reshape(-1, 35, 3)\n limb = viz_pose[:, -7:]\n\n # Animation\n aroot = osp.join(osp.dirname(__file__), \"novel_poses/husky\")\n window = list(range(350, 440)) # Run\n trans = torch.tensor([[0.3, -0.3, 25.0]], device=\"cuda:0\")\n files = [f\"{aroot}/{i:04d}.npz\" for i in window]\n pose_list = [dict(np.load(file))[\"pred_pose\"] for file in files]\n pose_list = np.concatenate(pose_list)\n animation = matrix_to_axis_angle(torch.from_numpy(pose_list)).to(solver.device)\n animation[:, [32, 33, 34]] = pose[:, [32, 33, 34]] \n\n viz_dog_animation(\n model.to(\"cuda\"),\n animation,\n limb,\n trans,\n data_provider.H,\n data_provider.W,\n data_provider.K_list[0],\n save_path=osp.join(viz_dir, \"animation.gif\"),\n fps=12,\n )\n return" }, { "identifier": "ssim", "path": "utils/ssim.py", "snippet": "def ssim(img1, img2, window_size=11, size_average=True):\n channel = img1.size(-3)\n window = create_window(window_size, channel)\n\n if img1.is_cuda:\n window = window.cuda(img1.get_device())\n window = window.type_as(img1)\n\n return _ssim(img1, img2, window, window_size, channel, size_average)" }, { "identifier": "test", "path": "test_utils/test_func.py", "snippet": "def test(\n solver,\n seq_name: str,\n tto_flag=True,\n tto_step=300,\n tto_decay=60,\n tto_decay_factor=0.5,\n pose_base_lr=3e-3,\n pose_rest_lr=3e-3,\n trans_lr=3e-3,\n dataset_mode=\"people_snapshot\",\n training_optimized_seq=None,\n):\n device = solver.device\n model = solver.load_saved_model()\n\n assert dataset_mode in [\n \"people_snapshot\",\n \"zju\",\n \"instant_avatar_wild\",\n \"dog_demo\",\n ], f\"Unknown dataset mode {dataset_mode}\"\n\n if dataset_mode == \"people_snapshot\":\n eval_mode = \"avatar\"\n bg = [1.0, 1.0, 1.0]\n test_dataset = InstantAvatarDataset(\n noisy_flag=False,\n data_root=\"./data/people_snapshot/\",\n video_name=seq_name,\n split=\"test\",\n image_zoom_ratio=0.5,\n )\n elif dataset_mode == \"zju\":\n eval_mode = \"nvr\"\n test_dataset = ZJUDataset(\n data_root=\"./data/zju_mocap\",\n video_name=seq_name,\n split=\"test\",\n image_zoom_ratio=0.5,\n )\n bg = [0.0, 0.0, 0.0] # zju use black background\n elif dataset_mode == \"instant_avatar_wild\":\n eval_mode = \"avatar\"\n test_dataset = InstantAvatarWildDataset(\n data_root=\"./data/insav_wild\",\n video_name=seq_name,\n split=\"test\",\n image_zoom_ratio=1.0,\n # ! warning, here follow the `ubc_hard.yaml` in InstAVT setting, use slicing\n start_end_skip=[2, 1000000000, 4],\n )\n bg = [1.0, 1.0, 1.0]\n\n test_len = len(test_dataset)\n assert (training_optimized_seq.total_t == test_len) or (\n training_optimized_seq.total_t == 1 + test_len\n ), \"Now UBC can only support the same length of training and testing or + 1\"\n test_dataset.smpl_params[\"body_pose\"] = (\n training_optimized_seq.pose_rest_list.reshape(-1, 69)[:test_len]\n .detach()\n .cpu()\n .numpy()\n )\n test_dataset.smpl_params[\"global_orient\"] = (\n training_optimized_seq.pose_base_list.reshape(-1, 3)[:test_len]\n .detach()\n .cpu()\n .numpy()\n )\n test_dataset.smpl_params[\"transl\"] = (\n training_optimized_seq.global_trans_list.reshape(-1, 3)[:test_len]\n .detach()\n .cpu()\n .numpy()\n )\n elif dataset_mode == \"dog_demo\":\n eval_mode = \"avatar_brightness\"\n bg = [1.0, 1.0, 1.0]\n test_dataset = DogDemoDataset(\n data_root=\"./data/dog_data_official/\", video_name=seq_name, test=True\n )\n else:\n raise NotImplementedError()\n\n evaluator = get_evaluator(eval_mode, device)\n\n _save_eval_maps(\n solver.log_dir,\n \"test\",\n model,\n solver,\n test_dataset,\n dataset_mode=dataset_mode,\n device=device,\n bg=bg,\n tto_flag=tto_flag,\n tto_step=tto_step,\n tto_decay=tto_decay,\n tto_decay_factor=tto_decay_factor,\n tto_evaluator=evaluator,\n pose_base_lr=pose_base_lr,\n pose_rest_lr=pose_rest_lr,\n trans_lr=trans_lr,\n )\n\n if tto_flag:\n _evaluate_dir(evaluator, solver.log_dir, \"test_tto\")\n else:\n _evaluate_dir(evaluator, solver.log_dir, \"test\")\n\n return" } ]
from matplotlib import pyplot as plt from pytorch3d.transforms import matrix_to_axis_angle from tqdm import tqdm from transforms3d.euler import euler2mat from omegaconf import OmegaConf from lib_data.get_data import prepare_real_seq from lib_data.data_provider import DatabasePoseProvider from lib_gart.templates import get_template from lib_gart.model import GaussianTemplateModel, AdditionalBones from lib_gart.optim_utils import * from lib_render.gauspl_renderer import render_cam_pcl from lib_gart.model_utils import transform_mu_frame from utils.misc import * from utils.viz import viz_render from pytorch3d.transforms import axis_angle_to_matrix, matrix_to_axis_angle from pytorch3d.ops import knn_points from lib_guidance.camera_sampling import sample_camera, fov2K, opencv2blender from viz_utils import viz_spinning, viz_human_all, viz_dog_all from utils.ssim import ssim from datetime import datetime from test_utils import test from lib_guidance.mvdream.mvdream_guidance import MVDream from utils.lpips import LPIPS import imageio import torch import numpy as np import os, os.path as osp, shutil, sys import time import logging import argparse
20,917
self.template_model_path = template_model_path self.device = device # * auto set attr cfg = OmegaConf.load(profile_fn) # assign the cfg to self attribute for k, v in cfg.items(): setattr(self, k, v) for k, v in kwargs.items(): setattr(self, k, v) # * explicitly set flags self.FAST_TRAINING = getattr(self, "FAST_TRAINING", False) self.LAMBDA_SSIM = getattr(self, "LAMBDA_SSIM", 0.0) self.LAMBDA_LPIPS = getattr(self, "LAMBDA_LPIPS", 0.0) if self.LAMBDA_LPIPS > 0: self.lpips = LPIPS(net="vgg").to(self.device) for param in self.lpips.parameters(): param.requires_grad = False if isinstance(self.RESET_OPACITY_STEPS, int): self.RESET_OPACITY_STEPS = [ i for i in range(1, self.TOTAL_steps) if i % self.RESET_OPACITY_STEPS == 0 ] if isinstance(self.REGAUSSIAN_STEPS, int): self.REGAUSSIAN_STEPS = [ i for i in range(1, self.TOTAL_steps) if i % self.REGAUSSIAN_STEPS == 0 ] # prepare base R if self.mode == "human": viz_base_R_opencv = np.asarray(euler2mat(np.pi, 0, 0, "sxyz")) else: viz_base_R_opencv = np.asarray(euler2mat(np.pi / 2.0, 0, np.pi, "rxyz")) viz_base_R_opencv = torch.from_numpy(viz_base_R_opencv).float() self.viz_base_R = viz_base_R_opencv.to(self.device) if self.mode == "human": self.reg_base_R_global = ( matrix_to_axis_angle( torch.as_tensor(euler2mat(np.pi / 2.0, 0, np.pi / 2.0, "sxyz"))[ None ] )[0] .float() .to(self.device) ) else: # TODO, for generation of dog pass self.writer = create_log( self.log_dir, name=osp.basename(self.profile_fn).split(".")[0], debug=False ) return def prepare_fake_data(self, mode, *args, **kwargs): if mode == "amass": # todo: change to amass provider = DatabasePoseProvider(*args, **kwargs, device=torch.device("cpu")) return provider return provider def prepare_real_seq( self, seq_name, dataset_mode, split, ins_avt_wild_start_end_skip=None, image_zoom_ratio=0.5, data_stay_gpu_flag=True, ): provider, dataset = prepare_real_seq( seq_name=seq_name, dataset_mode=dataset_mode, split=split, ins_avt_wild_start_end_skip=ins_avt_wild_start_end_skip, image_zoom_ratio=getattr( self, "IMAGE_ZOOM_RATIO", image_zoom_ratio ), # ! this overwrite the func arg balance=getattr(self, "VIEW_BALANCE_FLAG", False), ) provider.to(self.device) if getattr(self, "DATA_STAY_GPU_FLAG", data_stay_gpu_flag): provider.move_images_to_device(self.device) provider.viz_selection_prob( osp.join(self.log_dir, f"split_{split}_view_prob.png") ) return provider, dataset def load_saved_model(self, ckpt_path=None): if ckpt_path is None: ckpt_path = osp.join(self.log_dir, "model.pth") ret = self._get_model_optimizer(betas=None) model = ret[0] model.load(torch.load(ckpt_path)) model.to(self.device) model.eval() logging.info("After loading:") model.summary() return model def _get_model_optimizer(self, betas, add_bones_total_t=0): seed_everything(self.SEED) template = get_template( mode=self.mode, template_model_path=self.template_model_path, init_beta=betas, cano_pose_type=getattr(self, "CANO_POSE_TYPE", "t_pose"), voxel_deformer_res=getattr(self, "VOXEL_DEFORMER_RES", 64), )
# from lib_marchingcubes.gaumesh_utils import MeshExtractor try: # from lib_guidance.sd_utils import StableDiffusion except: logging.warning("No guidance module") class TGFitter: def __init__( self, log_dir, profile_fn, mode, template_model_path="data/smpl_model/SMPL_NEUTRAL.pkl", device=torch.device("cuda:0"), **kwargs, ) -> None: self.log_dir = log_dir os.makedirs(self.log_dir, exist_ok=True) self.profile_fn = profile_fn try: shutil.copy(profile_fn, osp.join(self.log_dir, osp.basename(profile_fn))) except: pass self.mode = mode assert self.mode in ["human", "dog"], "Only support human and dog for now" self.template_model_path = template_model_path self.device = device # * auto set attr cfg = OmegaConf.load(profile_fn) # assign the cfg to self attribute for k, v in cfg.items(): setattr(self, k, v) for k, v in kwargs.items(): setattr(self, k, v) # * explicitly set flags self.FAST_TRAINING = getattr(self, "FAST_TRAINING", False) self.LAMBDA_SSIM = getattr(self, "LAMBDA_SSIM", 0.0) self.LAMBDA_LPIPS = getattr(self, "LAMBDA_LPIPS", 0.0) if self.LAMBDA_LPIPS > 0: self.lpips = LPIPS(net="vgg").to(self.device) for param in self.lpips.parameters(): param.requires_grad = False if isinstance(self.RESET_OPACITY_STEPS, int): self.RESET_OPACITY_STEPS = [ i for i in range(1, self.TOTAL_steps) if i % self.RESET_OPACITY_STEPS == 0 ] if isinstance(self.REGAUSSIAN_STEPS, int): self.REGAUSSIAN_STEPS = [ i for i in range(1, self.TOTAL_steps) if i % self.REGAUSSIAN_STEPS == 0 ] # prepare base R if self.mode == "human": viz_base_R_opencv = np.asarray(euler2mat(np.pi, 0, 0, "sxyz")) else: viz_base_R_opencv = np.asarray(euler2mat(np.pi / 2.0, 0, np.pi, "rxyz")) viz_base_R_opencv = torch.from_numpy(viz_base_R_opencv).float() self.viz_base_R = viz_base_R_opencv.to(self.device) if self.mode == "human": self.reg_base_R_global = ( matrix_to_axis_angle( torch.as_tensor(euler2mat(np.pi / 2.0, 0, np.pi / 2.0, "sxyz"))[ None ] )[0] .float() .to(self.device) ) else: # TODO, for generation of dog pass self.writer = create_log( self.log_dir, name=osp.basename(self.profile_fn).split(".")[0], debug=False ) return def prepare_fake_data(self, mode, *args, **kwargs): if mode == "amass": # todo: change to amass provider = DatabasePoseProvider(*args, **kwargs, device=torch.device("cpu")) return provider return provider def prepare_real_seq( self, seq_name, dataset_mode, split, ins_avt_wild_start_end_skip=None, image_zoom_ratio=0.5, data_stay_gpu_flag=True, ): provider, dataset = prepare_real_seq( seq_name=seq_name, dataset_mode=dataset_mode, split=split, ins_avt_wild_start_end_skip=ins_avt_wild_start_end_skip, image_zoom_ratio=getattr( self, "IMAGE_ZOOM_RATIO", image_zoom_ratio ), # ! this overwrite the func arg balance=getattr(self, "VIEW_BALANCE_FLAG", False), ) provider.to(self.device) if getattr(self, "DATA_STAY_GPU_FLAG", data_stay_gpu_flag): provider.move_images_to_device(self.device) provider.viz_selection_prob( osp.join(self.log_dir, f"split_{split}_view_prob.png") ) return provider, dataset def load_saved_model(self, ckpt_path=None): if ckpt_path is None: ckpt_path = osp.join(self.log_dir, "model.pth") ret = self._get_model_optimizer(betas=None) model = ret[0] model.load(torch.load(ckpt_path)) model.to(self.device) model.eval() logging.info("After loading:") model.summary() return model def _get_model_optimizer(self, betas, add_bones_total_t=0): seed_everything(self.SEED) template = get_template( mode=self.mode, template_model_path=self.template_model_path, init_beta=betas, cano_pose_type=getattr(self, "CANO_POSE_TYPE", "t_pose"), voxel_deformer_res=getattr(self, "VOXEL_DEFORMER_RES", 64), )
add_bones = AdditionalBones(
4
2023-11-27 17:30:04+00:00
24k
skhu101/GauHuman
scene/dataset_readers.py
[ { "identifier": "read_extrinsics_text", "path": "scene/colmap_loader.py", "snippet": "def read_extrinsics_text(path):\n \"\"\"\n Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py\n \"\"\"\n images = {}\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n elems = line.split()\n image_id = int(elems[0])\n qvec = np.array(tuple(map(float, elems[1:5])))\n tvec = np.array(tuple(map(float, elems[5:8])))\n camera_id = int(elems[8])\n image_name = elems[9]\n elems = fid.readline().split()\n xys = np.column_stack([tuple(map(float, elems[0::3])),\n tuple(map(float, elems[1::3]))])\n point3D_ids = np.array(tuple(map(int, elems[2::3])))\n images[image_id] = Image(\n id=image_id, qvec=qvec, tvec=tvec,\n camera_id=camera_id, name=image_name,\n xys=xys, point3D_ids=point3D_ids)\n return images" }, { "identifier": "read_intrinsics_text", "path": "scene/colmap_loader.py", "snippet": "def read_intrinsics_text(path):\n \"\"\"\n Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py\n \"\"\"\n cameras = {}\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n elems = line.split()\n camera_id = int(elems[0])\n model = elems[1]\n assert model == \"PINHOLE\", \"While the loader support other types, the rest of the code assumes PINHOLE\"\n width = int(elems[2])\n height = int(elems[3])\n params = np.array(tuple(map(float, elems[4:])))\n cameras[camera_id] = Camera(id=camera_id, model=model,\n width=width, height=height,\n params=params)\n return cameras" }, { "identifier": "qvec2rotmat", "path": "scene/colmap_loader.py", "snippet": "def qvec2rotmat(qvec):\n return np.array([\n [1 - 2 * qvec[2]**2 - 2 * qvec[3]**2,\n 2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],\n 2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2]],\n [2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],\n 1 - 2 * qvec[1]**2 - 2 * qvec[3]**2,\n 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1]],\n [2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],\n 2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],\n 1 - 2 * qvec[1]**2 - 2 * qvec[2]**2]])" }, { "identifier": "read_extrinsics_binary", "path": "scene/colmap_loader.py", "snippet": "def read_extrinsics_binary(path_to_model_file):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadImagesBinary(const std::string& path)\n void Reconstruction::WriteImagesBinary(const std::string& path)\n \"\"\"\n images = {}\n with open(path_to_model_file, \"rb\") as fid:\n num_reg_images = read_next_bytes(fid, 8, \"Q\")[0]\n for _ in range(num_reg_images):\n binary_image_properties = read_next_bytes(\n fid, num_bytes=64, format_char_sequence=\"idddddddi\")\n image_id = binary_image_properties[0]\n qvec = np.array(binary_image_properties[1:5])\n tvec = np.array(binary_image_properties[5:8])\n camera_id = binary_image_properties[8]\n image_name = \"\"\n current_char = read_next_bytes(fid, 1, \"c\")[0]\n while current_char != b\"\\x00\": # look for the ASCII 0 entry\n image_name += current_char.decode(\"utf-8\")\n current_char = read_next_bytes(fid, 1, \"c\")[0]\n num_points2D = read_next_bytes(fid, num_bytes=8,\n format_char_sequence=\"Q\")[0]\n x_y_id_s = read_next_bytes(fid, num_bytes=24*num_points2D,\n format_char_sequence=\"ddq\"*num_points2D)\n xys = np.column_stack([tuple(map(float, x_y_id_s[0::3])),\n tuple(map(float, x_y_id_s[1::3]))])\n point3D_ids = np.array(tuple(map(int, x_y_id_s[2::3])))\n images[image_id] = Image(\n id=image_id, qvec=qvec, tvec=tvec,\n camera_id=camera_id, name=image_name,\n xys=xys, point3D_ids=point3D_ids)\n return images" }, { "identifier": "read_intrinsics_binary", "path": "scene/colmap_loader.py", "snippet": "def read_intrinsics_binary(path_to_model_file):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::WriteCamerasBinary(const std::string& path)\n void Reconstruction::ReadCamerasBinary(const std::string& path)\n \"\"\"\n cameras = {}\n with open(path_to_model_file, \"rb\") as fid:\n num_cameras = read_next_bytes(fid, 8, \"Q\")[0]\n for _ in range(num_cameras):\n camera_properties = read_next_bytes(\n fid, num_bytes=24, format_char_sequence=\"iiQQ\")\n camera_id = camera_properties[0]\n model_id = camera_properties[1]\n model_name = CAMERA_MODEL_IDS[camera_properties[1]].model_name\n width = camera_properties[2]\n height = camera_properties[3]\n num_params = CAMERA_MODEL_IDS[model_id].num_params\n params = read_next_bytes(fid, num_bytes=8*num_params,\n format_char_sequence=\"d\"*num_params)\n cameras[camera_id] = Camera(id=camera_id,\n model=model_name,\n width=width,\n height=height,\n params=np.array(params))\n assert len(cameras) == num_cameras\n return cameras" }, { "identifier": "read_points3D_binary", "path": "scene/colmap_loader.py", "snippet": "def read_points3D_binary(path_to_model_file):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadPoints3DBinary(const std::string& path)\n void Reconstruction::WritePoints3DBinary(const std::string& path)\n \"\"\"\n\n\n with open(path_to_model_file, \"rb\") as fid:\n num_points = read_next_bytes(fid, 8, \"Q\")[0]\n\n xyzs = np.empty((num_points, 3))\n rgbs = np.empty((num_points, 3))\n errors = np.empty((num_points, 1))\n\n for p_id in range(num_points):\n binary_point_line_properties = read_next_bytes(\n fid, num_bytes=43, format_char_sequence=\"QdddBBBd\")\n xyz = np.array(binary_point_line_properties[1:4])\n rgb = np.array(binary_point_line_properties[4:7])\n error = np.array(binary_point_line_properties[7])\n track_length = read_next_bytes(\n fid, num_bytes=8, format_char_sequence=\"Q\")[0]\n track_elems = read_next_bytes(\n fid, num_bytes=8*track_length,\n format_char_sequence=\"ii\"*track_length)\n xyzs[p_id] = xyz\n rgbs[p_id] = rgb\n errors[p_id] = error\n return xyzs, rgbs, errors" }, { "identifier": "read_points3D_text", "path": "scene/colmap_loader.py", "snippet": "def read_points3D_text(path):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadPoints3DText(const std::string& path)\n void Reconstruction::WritePoints3DText(const std::string& path)\n \"\"\"\n xyzs = None\n rgbs = None\n errors = None\n num_points = 0\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n num_points += 1\n\n\n xyzs = np.empty((num_points, 3))\n rgbs = np.empty((num_points, 3))\n errors = np.empty((num_points, 1))\n count = 0\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n elems = line.split()\n xyz = np.array(tuple(map(float, elems[1:4])))\n rgb = np.array(tuple(map(int, elems[4:7])))\n error = np.array(float(elems[7]))\n xyzs[count] = xyz\n rgbs[count] = rgb\n errors[count] = error\n count += 1\n\n return xyzs, rgbs, errors" }, { "identifier": "getWorld2View2", "path": "utils/graphics_utils.py", "snippet": "def getWorld2View2(R, t, translate=np.array([.0, .0, .0]), scale=1.0):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = R.transpose()\n Rt[:3, 3] = t\n Rt[3, 3] = 1.0\n\n C2W = np.linalg.inv(Rt)\n cam_center = C2W[:3, 3]\n cam_center = (cam_center + translate) * scale\n C2W[:3, 3] = cam_center\n Rt = np.linalg.inv(C2W)\n return np.float32(Rt)" }, { "identifier": "focal2fov", "path": "utils/graphics_utils.py", "snippet": "def focal2fov(focal, pixels):\n return 2*math.atan(pixels/(2*focal))" }, { "identifier": "fov2focal", "path": "utils/graphics_utils.py", "snippet": "def fov2focal(fov, pixels):\n return pixels / (2 * math.tan(fov / 2))" }, { "identifier": "SH2RGB", "path": "utils/sh_utils.py", "snippet": "def SH2RGB(sh):\n return sh * C0 + 0.5" }, { "identifier": "BasicPointCloud", "path": "scene/gaussian_model.py", "snippet": "class GaussianModel:\n def setup_functions(self):\n def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation, transform):\n def __init__(self, sh_degree : int, smpl_type : str, motion_offset_flag : bool, actor_gender: str):\n def capture(self):\n def restore(self, model_args, training_args):\n def get_scaling(self):\n def get_rotation(self):\n def get_xyz(self):\n def get_features(self):\n def get_opacity(self):\n def get_covariance(self, scaling_modifier = 1, transform=None):\n def oneupSHdegree(self):\n def create_from_pcd(self, pcd : BasicPointCloud, spatial_lr_scale : float):\n def training_setup(self, training_args):\n def update_learning_rate(self, iteration):\n def construct_list_of_attributes(self):\n def save_ply(self, path):\n def reset_opacity(self):\n def load_ply(self, path):\n def replace_tensor_to_optimizer(self, tensor, name):\n def _prune_optimizer(self, mask):\n def prune_points(self, mask):\n def cat_tensors_to_optimizer(self, tensors_dict):\n def densification_postfix(self, new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation):\n def densify_and_split(self, grads, grad_threshold, scene_extent, N=2):\n def densify_and_clone(self, grads, grad_threshold, scene_extent):\n def kl_densify_and_clone(self, grads, grad_threshold, scene_extent, kl_threshold=0.4):\n def kl_densify_and_split(self, grads, grad_threshold, scene_extent, kl_threshold=0.4, N=2):\n def kl_merge(self, grads, grad_threshold, scene_extent, kl_threshold=0.1):\n def densify_and_prune(self, max_grad, min_opacity, extent, max_screen_size, kl_threshold=0.4, t_vertices=None, iter=None):\n def kl_div(self, mu_0, rotation_0_q, scaling_0_diag, mu_1, rotation_1_q, scaling_1_diag):\n def add_densification_stats(self, viewspace_point_tensor, update_filter):\n def coarse_deform_c2source(self, query_pts, params, t_params, t_vertices, lbs_weights=None, correct_Rs=None, return_transl=False):\ndef read_pickle(pkl_path):\ndef SMPL_to_tensor(params, device):\ndef batch_rodrigues_torch(poses):\ndef get_rigid_transformation_torch(rot_mats, joints, parents):\ndef get_transform_params_torch(smpl, params, rot_mats=None, correct_Rs=None):\ndef batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32):\n L = build_scaling_rotation(scaling_modifier * scaling, rotation)\n L_0 = rotation_0 @ scaling_0\n A = torch.matmul(bweights, A.reshape(bs, joints_num, -1))\n A = torch.reshape(A, (bs, -1, 4, 4))\n A = torch.matmul(bweights, self.s_A.reshape(bs, joints_num, -1))\n A = torch.reshape(A, (bs, -1, 4, 4))\n K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1)\n K = K.reshape([batch_size, 3, 3])\n A = get_rigid_transformation_torch(rot_mats, joints, parents)\n R = params['R'] \n K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device)\n K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \\\n .view((batch_size, 3, 3))" }, { "identifier": "SMPL", "path": "smpl/smpl_numpy.py", "snippet": "class SMPL():\n def __init__(self, sex, model_dir):\n super(SMPL, self).__init__()\n\n model_paths = {\n 'male': os.path.join(model_dir, MALE_PATH),\n 'female': os.path.join(model_dir, FEMALE_PATH),\n # 'neutral': os.path.join(model_dir, NEUTRAL_PATH)\n 'neutral': os.path.join('assets/SMPL_NEUTRAL.pkl')\n }\n\n with open(model_paths[sex], 'rb') as f:\n smpl_model = pickle.load(f, encoding='latin1')\n self.J_regressor = np.array(smpl_model['J_regressor'].todense()) # (24, 6890)\n self.weights = smpl_model['weights'] # (6890, 24)\n self.posedirs = smpl_model['posedirs'] # (6890, 3, 207)\n self.v_template = smpl_model['v_template'] # (6890, 3)\n self.shapedirs = np.array(smpl_model['shapedirs']) # (6890, 3, 10)\n self.faces = smpl_model['f'].astype('int32') # (13776, 3)\n self.kintree_table = smpl_model['kintree_table'].astype('int64') # (2, 24)\n\n id_to_col = {self.kintree_table[1, i].item(): i for i in range(self.kintree_table.shape[1])}\n self.parent = np.array([id_to_col[self.kintree_table[0, it]] for it in range(1, self.kintree_table.shape[1])])\n\n self.pose_shape = [24, 3]\n self.beta_shape = [10]\n self.pose = np.zeros(self.pose_shape)\n self.beta = np.zeros(self.beta_shape)\n\n self.verts = None\n self.J = None\n self.R = None\n\n def __call__(self, pose, beta):\n\n v_template = self.v_template # (6890, 3)\n shapedirs = self.shapedirs.reshape(-1,10) # (6890*3, 10)\n beta = beta[:, None] # (10, 1)\n\n v_shaped = shapedirs.dot(beta).reshape(6890, 3) + v_template # (6890, 3)\n J = self.J_regressor.dot(v_shaped) # (24, 3)\n\n # input is a rotation matrix: (24,3,3)\n if pose.shape == (24, 3, 3):\n R = pose\n # input is a rotation axis-angle vector: (1, 72), (72, 1) or (72, )\n elif pose.shape == (1, 72) or pose.shape == (72, 1) or pose.shape == (72,):\n pose_vectors = pose.reshape(-1, 3) # (24, 3)\n R = np.array([rodrigues(pose_vectors[p_idx])[0] \n for p_idx in range(pose_vectors.shape[0])\n ], \n dtype='float32') # (24, 3, 3)\n else:\n raise ValueError(\"Unsupported Pose Inputs - the Pose Shape is {}\".format(pose.shape))\n\n Is = np.eye(3, dtype='float32')[None, :] # (1, 3, 3)\n lrotmin = (R[1:,:] - Is).reshape(-1, 1) # (23x3x3, 1)\n posedirs = self.posedirs.reshape(-1,207) # (6890x3, 207)\n v_posed = v_shaped + posedirs.dot(lrotmin).reshape(6890, 3) # (6890, 3)\n\n J_ = J.copy()\n J_[1:, :] = J[1:, :] - J[self.parent, :] # (24, 3)\n G_ = np.concatenate([R, J_[:, :, None]], axis=-1) # (24, 3, 4)\n pad_rows = np.array([[0, 0, 0, 1]], dtype='float32')\n pad_rows = np.repeat(pad_rows, 24, axis=0).reshape(-1, 1, 4)\n G_ = np.concatenate([G_, pad_rows], axis=1) # (24, 4, 4)\n\n G = [G_[0].copy()]\n for i in range(1, 24):\n G.append(G[self.parent[i-1]].dot(G_[i, :, :]))\n G = np.stack(G, axis=0) # (24, 4, 4)\n\n joints = G[:, :3, 3]\n rest_joints = np.concatenate([J, np.zeros((24, 1))], axis=-1)[:, :, None] # (24, 4, 1)\n zeros = np.zeros((24, 4, 3), dtype='float32') # (24, 4, 3)\n rest_joints_mtx = np.concatenate([zeros, rest_joints], axis=-1) # (24, 4, 4) \n # print(\"G1: \", G[0], \"rest_joints_mtx1: \", rest_joints_mtx[0])\n posed_joints_mtx = np.matmul(G, rest_joints_mtx)\n # print(\"rest_joints_mtx2: \", posed_joints_mtx[0])\n G = G - posed_joints_mtx\n # print(G[0]) \n rest_shape_h = np.concatenate([v_posed, np.ones(v_posed.shape[0])[:, None]], axis=-1) #(6890, 4)\n T = self.weights.dot(G.reshape(24, -1)).reshape(6890, 4, 4)\n v = np.matmul(T, rest_shape_h[:, :, None])[:, :3, 0]\n \n return v, joints" }, { "identifier": "SMPLX", "path": "smplx/body_models.py", "snippet": "class SMPLX(SMPLH):\n '''\n SMPL-X (SMPL eXpressive) is a unified body model, with shape parameters\n trained jointly for the face, hands and body.\n SMPL-X uses standard vertex based linear blend skinning with learned\n corrective blend shapes, has N=10475 vertices and K=54 joints,\n which includes joints for the neck, jaw, eyeballs and fingers.\n '''\n\n NUM_BODY_JOINTS = SMPLH.NUM_BODY_JOINTS\n NUM_HAND_JOINTS = 15\n NUM_FACE_JOINTS = 3\n NUM_JOINTS = NUM_BODY_JOINTS + 2 * NUM_HAND_JOINTS + NUM_FACE_JOINTS\n EXPRESSION_SPACE_DIM = 100\n NECK_IDX = 12\n\n def __init__(\n self, model_path: str,\n kid_template_path: str = '',\n num_expression_coeffs: int = 10,\n create_expression: bool = True,\n expression: Optional[Tensor] = None,\n create_jaw_pose: bool = True,\n jaw_pose: Optional[Tensor] = None,\n create_leye_pose: bool = True,\n leye_pose: Optional[Tensor] = None,\n create_reye_pose=True,\n reye_pose: Optional[Tensor] = None,\n use_face_contour: bool = False,\n batch_size: int = 1,\n gender: str = 'neutral',\n age: str = 'adult',\n dtype=torch.float32,\n ext: str = 'npz',\n **kwargs\n ) -> None:\n ''' SMPLX model constructor\n\n Parameters\n ----------\n model_path: str\n The path to the folder or to the file where the model\n parameters are stored\n num_expression_coeffs: int, optional\n Number of expression components to use\n (default = 10).\n create_expression: bool, optional\n Flag for creating a member variable for the expression space\n (default = True).\n expression: torch.tensor, optional, Bx10\n The default value for the expression member variable.\n (default = None)\n create_jaw_pose: bool, optional\n Flag for creating a member variable for the jaw pose.\n (default = False)\n jaw_pose: torch.tensor, optional, Bx3\n The default value for the jaw pose variable.\n (default = None)\n create_leye_pose: bool, optional\n Flag for creating a member variable for the left eye pose.\n (default = False)\n leye_pose: torch.tensor, optional, Bx10\n The default value for the left eye pose variable.\n (default = None)\n create_reye_pose: bool, optional\n Flag for creating a member variable for the right eye pose.\n (default = False)\n reye_pose: torch.tensor, optional, Bx10\n The default value for the right eye pose variable.\n (default = None)\n use_face_contour: bool, optional\n Whether to compute the keypoints that form the facial contour\n batch_size: int, optional\n The batch size used for creating the member variables\n gender: str, optional\n Which gender to load\n dtype: torch.dtype\n The data type for the created variables\n '''\n\n # Load the model\n if osp.isdir(model_path):\n model_fn = 'SMPLX_{}.{ext}'.format(gender.upper(), ext=ext)\n smplx_path = os.path.join(model_path, model_fn)\n else:\n smplx_path = model_path\n assert osp.exists(smplx_path), 'Path {} does not exist!'.format(\n smplx_path)\n\n if ext == 'pkl':\n with open(smplx_path, 'rb') as smplx_file:\n model_data = pickle.load(smplx_file, encoding='latin1')\n elif ext == 'npz':\n model_data = np.load(smplx_path, allow_pickle=True)\n else:\n raise ValueError('Unknown extension: {}'.format(ext))\n\n data_struct = Struct(**model_data)\n\n super(SMPLX, self).__init__(\n model_path=model_path,\n kid_template_path=kid_template_path,\n data_struct=data_struct,\n dtype=dtype,\n batch_size=batch_size,\n vertex_ids=VERTEX_IDS['smplx'],\n gender=gender, age=age, ext=ext,\n **kwargs)\n\n lmk_faces_idx = data_struct.lmk_faces_idx\n self.register_buffer('lmk_faces_idx',\n torch.tensor(lmk_faces_idx, dtype=torch.long))\n lmk_bary_coords = data_struct.lmk_bary_coords\n self.register_buffer('lmk_bary_coords',\n torch.tensor(lmk_bary_coords, dtype=dtype))\n\n self.use_face_contour = use_face_contour\n if self.use_face_contour:\n dynamic_lmk_faces_idx = data_struct.dynamic_lmk_faces_idx\n dynamic_lmk_faces_idx = torch.tensor(\n dynamic_lmk_faces_idx,\n dtype=torch.long)\n self.register_buffer('dynamic_lmk_faces_idx',\n dynamic_lmk_faces_idx)\n\n dynamic_lmk_bary_coords = data_struct.dynamic_lmk_bary_coords\n dynamic_lmk_bary_coords = torch.tensor(\n dynamic_lmk_bary_coords, dtype=dtype)\n self.register_buffer('dynamic_lmk_bary_coords',\n dynamic_lmk_bary_coords)\n\n neck_kin_chain = find_joint_kin_chain(self.NECK_IDX, self.parents)\n self.register_buffer(\n 'neck_kin_chain',\n torch.tensor(neck_kin_chain, dtype=torch.long))\n\n if create_jaw_pose:\n if jaw_pose is None:\n default_jaw_pose = torch.zeros([batch_size, 3], dtype=dtype)\n else:\n default_jaw_pose = torch.tensor(jaw_pose, dtype=dtype)\n jaw_pose_param = nn.Parameter(default_jaw_pose,\n requires_grad=True)\n self.register_parameter('jaw_pose', jaw_pose_param)\n\n if create_leye_pose:\n if leye_pose is None:\n default_leye_pose = torch.zeros([batch_size, 3], dtype=dtype)\n else:\n default_leye_pose = torch.tensor(leye_pose, dtype=dtype)\n leye_pose_param = nn.Parameter(default_leye_pose,\n requires_grad=True)\n self.register_parameter('leye_pose', leye_pose_param)\n\n if create_reye_pose:\n if reye_pose is None:\n default_reye_pose = torch.zeros([batch_size, 3], dtype=dtype)\n else:\n default_reye_pose = torch.tensor(reye_pose, dtype=dtype)\n reye_pose_param = nn.Parameter(default_reye_pose,\n requires_grad=True)\n self.register_parameter('reye_pose', reye_pose_param)\n\n shapedirs = data_struct.shapedirs\n if len(shapedirs.shape) < 3:\n shapedirs = shapedirs[:, :, None]\n if (shapedirs.shape[-1] < self.SHAPE_SPACE_DIM +\n self.EXPRESSION_SPACE_DIM):\n print(f'WARNING: You are using a {self.name()} model, with only'\n ' 10 shape and 10 expression coefficients.')\n expr_start_idx = 10\n expr_end_idx = 20\n num_expression_coeffs = min(num_expression_coeffs, 10)\n else:\n expr_start_idx = self.SHAPE_SPACE_DIM\n expr_end_idx = self.SHAPE_SPACE_DIM + num_expression_coeffs\n num_expression_coeffs = min(\n num_expression_coeffs, self.EXPRESSION_SPACE_DIM)\n\n self._num_expression_coeffs = num_expression_coeffs\n\n expr_dirs = shapedirs[:, :, expr_start_idx:expr_end_idx]\n self.register_buffer(\n 'expr_dirs', to_tensor(to_np(expr_dirs), dtype=dtype))\n\n if create_expression:\n if expression is None:\n default_expression = torch.zeros(\n [batch_size, self.num_expression_coeffs], dtype=dtype)\n else:\n default_expression = torch.tensor(expression, dtype=dtype)\n expression_param = nn.Parameter(default_expression,\n requires_grad=True)\n self.register_parameter('expression', expression_param)\n\n def name(self) -> str:\n return 'SMPL-X'\n\n @property\n def num_expression_coeffs(self):\n return self._num_expression_coeffs\n\n def create_mean_pose(self, data_struct, flat_hand_mean=False):\n # Create the array for the mean pose. If flat_hand is false, then use\n # the mean that is given by the data, rather than the flat open hand\n global_orient_mean = torch.zeros([3], dtype=self.dtype)\n body_pose_mean = torch.zeros([self.NUM_BODY_JOINTS * 3],\n dtype=self.dtype)\n jaw_pose_mean = torch.zeros([3], dtype=self.dtype)\n leye_pose_mean = torch.zeros([3], dtype=self.dtype)\n reye_pose_mean = torch.zeros([3], dtype=self.dtype)\n # pose_mean = np.concatenate([global_orient_mean, body_pose_mean, jaw_pose_mean, leye_pose_mean, reye_pose_mean, self.left_hand_mean, self.right_hand_mean], axis=0)\n pose_mean = torch.cat([global_orient_mean, body_pose_mean, jaw_pose_mean, leye_pose_mean, reye_pose_mean, self.left_hand_mean, self.right_hand_mean], 0)\n\n return pose_mean\n\n def extra_repr(self):\n msg = super(SMPLX, self).extra_repr()\n msg = [\n msg,\n f'Number of Expression Coefficients: {self.num_expression_coeffs}'\n ]\n return '\\n'.join(msg)\n\n def forward(\n self,\n betas: Optional[Tensor] = None,\n global_orient: Optional[Tensor] = None,\n body_pose: Optional[Tensor] = None,\n left_hand_pose: Optional[Tensor] = None,\n right_hand_pose: Optional[Tensor] = None,\n transl: Optional[Tensor] = None,\n expression: Optional[Tensor] = None,\n jaw_pose: Optional[Tensor] = None,\n leye_pose: Optional[Tensor] = None,\n reye_pose: Optional[Tensor] = None,\n return_verts: bool = True,\n return_full_pose: bool = False,\n pose2rot: bool = True,\n return_shaped: bool = True,\n **kwargs\n ) -> TensorOutput:\n '''\n Forward pass for the SMPLX model\n\n Parameters\n ----------\n global_orient: torch.tensor, optional, shape Bx3\n If given, ignore the member variable and use it as the global\n rotation of the body. Useful if someone wishes to predicts this\n with an external model. (default=None)\n betas: torch.tensor, optional, shape BxN_b\n If given, ignore the member variable `betas` and use it\n instead. For example, it can used if shape parameters\n `betas` are predicted from some external model.\n (default=None)\n expression: torch.tensor, optional, shape BxN_e\n If given, ignore the member variable `expression` and use it\n instead. For example, it can used if expression parameters\n `expression` are predicted from some external model.\n body_pose: torch.tensor, optional, shape Bx(J*3)\n If given, ignore the member variable `body_pose` and use it\n instead. For example, it can used if someone predicts the\n pose of the body joints are predicted from some external model.\n It should be a tensor that contains joint rotations in\n axis-angle format. (default=None)\n left_hand_pose: torch.tensor, optional, shape BxP\n If given, ignore the member variable `left_hand_pose` and\n use this instead. It should either contain PCA coefficients or\n joint rotations in axis-angle format.\n right_hand_pose: torch.tensor, optional, shape BxP\n If given, ignore the member variable `right_hand_pose` and\n use this instead. It should either contain PCA coefficients or\n joint rotations in axis-angle format.\n jaw_pose: torch.tensor, optional, shape Bx3\n If given, ignore the member variable `jaw_pose` and\n use this instead. It should either joint rotations in\n axis-angle format.\n transl: torch.tensor, optional, shape Bx3\n If given, ignore the member variable `transl` and use it\n instead. For example, it can used if the translation\n `transl` is predicted from some external model.\n (default=None)\n return_verts: bool, optional\n Return the vertices. (default=True)\n return_full_pose: bool, optional\n Returns the full axis-angle pose vector (default=False)\n\n Returns\n -------\n output: ModelOutput\n A named tuple of type `ModelOutput`\n '''\n\n # If no shape and pose parameters are passed along, then use the\n # ones from the module\n global_orient = (global_orient if global_orient is not None else\n self.global_orient)\n body_pose = body_pose if body_pose is not None else self.body_pose\n betas = betas if betas is not None else self.betas\n\n left_hand_pose = (left_hand_pose if left_hand_pose is not None else\n self.left_hand_pose)\n right_hand_pose = (right_hand_pose if right_hand_pose is not None else\n self.right_hand_pose)\n jaw_pose = jaw_pose if jaw_pose is not None else self.jaw_pose\n leye_pose = leye_pose if leye_pose is not None else self.leye_pose\n reye_pose = reye_pose if reye_pose is not None else self.reye_pose\n expression = expression if expression is not None else self.expression\n\n apply_trans = transl is not None or hasattr(self, 'transl')\n if transl is None:\n if hasattr(self, 'transl'):\n transl = self.transl\n\n if self.use_pca:\n left_hand_pose = torch.einsum(\n 'bi,ij->bj', [left_hand_pose, self.left_hand_components])\n right_hand_pose = torch.einsum(\n 'bi,ij->bj', [right_hand_pose, self.right_hand_components])\n\n full_pose = torch.cat([global_orient.reshape(-1, 1, 3),\n body_pose.reshape(-1, self.NUM_BODY_JOINTS, 3),\n jaw_pose.reshape(-1, 1, 3),\n leye_pose.reshape(-1, 1, 3),\n reye_pose.reshape(-1, 1, 3),\n left_hand_pose.reshape(-1, 15, 3),\n right_hand_pose.reshape(-1, 15, 3)],\n dim=1).reshape(-1, 165).to(self.pose_mean.device)\n\n # Add the mean pose of the model. Does not affect the body, only the\n # hands when flat_hand_mean == False\n full_pose += self.pose_mean\n\n batch_size = max(betas.shape[0], global_orient.shape[0],\n body_pose.shape[0])\n # Concatenate the shape and expression coefficients\n scale = int(batch_size / betas.shape[0])\n if scale > 1:\n betas = betas.expand(scale, -1)\n shape_components = torch.cat([betas, expression], dim=-1).to(self.pose_mean.device)\n\n shapedirs = torch.cat([self.shapedirs, self.expr_dirs], dim=-1)\n\n vertices, joints, A, T = lbs(shape_components, full_pose, self.v_template,\n shapedirs, self.posedirs,\n self.J_regressor, self.parents,\n self.lbs_weights, pose2rot=pose2rot,\n )\n\n lmk_faces_idx = self.lmk_faces_idx.unsqueeze(\n dim=0).expand(batch_size, -1).contiguous()\n lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).repeat(\n self.batch_size, 1, 1)\n if self.use_face_contour:\n lmk_idx_and_bcoords = find_dynamic_lmk_idx_and_bcoords(\n vertices, full_pose, self.dynamic_lmk_faces_idx,\n self.dynamic_lmk_bary_coords,\n self.neck_kin_chain,\n pose2rot=True,\n )\n dyn_lmk_faces_idx, dyn_lmk_bary_coords = lmk_idx_and_bcoords\n\n lmk_faces_idx = torch.cat([lmk_faces_idx,\n dyn_lmk_faces_idx], 1)\n lmk_bary_coords = torch.cat(\n [lmk_bary_coords.expand(batch_size, -1, -1),\n dyn_lmk_bary_coords], 1)\n\n landmarks = vertices2landmarks(vertices, self.faces_tensor,\n lmk_faces_idx,\n lmk_bary_coords)\n\n # import matplotlib.pyplot as plt\n # import numpy as np\n # xs = joints[0,:,0]\n # ys = joints[0,:,1]\n # plt.scatter(xs, ys)\n\n # # zip joins x and y coordinates in pairs\n # count = 0\n # for x,y in zip(xs, ys):\n\n # label = \"{:.2f}\".format(count)\n\n # plt.annotate(label, # this is the text\n # (x,y), # these are the coordinates to position the label\n # textcoords=\"offset points\", # how to position the text\n # xytext=(0,10), # distance from text to points (x,y)\n # ha='center') # horizontal alignment can be left, right or center\n # count += 1\n # plt.savefig(\"joints.png\")\n # import pdb; pdb.set_trace()\n\n # Add any extra joints that might be needed\n joints = self.vertex_joint_selector(vertices, joints)\n # Add the landmarks to the joints\n joints = torch.cat([joints, landmarks], dim=1)\n # Map the joints to the current dataset\n\n if self.joint_mapper is not None:\n joints = self.joint_mapper(joints=joints, vertices=vertices)\n\n if apply_trans:\n joints += transl.unsqueeze(dim=1)\n vertices += transl.unsqueeze(dim=1)\n # clone because we are modifying them in-place\n A = A.clone()\n A[..., :3, 3] += transl.unsqueeze(dim=1)\n T = T.clone()\n T[..., :3, 3] += transl.unsqueeze(dim=1)\n\n v_shaped = None\n if return_shaped:\n v_shaped = self.v_template + blend_shapes(betas, self.shapedirs)\n else:\n v_shaped = Tensor(0)\n\n output = TensorOutput(vertices=vertices if return_verts else None,\n joints=joints,\n betas=betas,\n expression=expression,\n global_orient=global_orient,\n body_pose=body_pose,\n left_hand_pose=left_hand_pose,\n right_hand_pose=right_hand_pose,\n jaw_pose=jaw_pose,\n v_shaped=v_shaped,\n full_pose=full_pose if return_full_pose else None,\n A=A,\n T=T,\n f=self.faces)\n return output" }, { "identifier": "SMCReader", "path": "data/dna_rendering/dna_rendering_sample_code/SMCReader.py", "snippet": "class SMCReader:\n\n def __init__(self, file_path):\n \"\"\"Read SenseMocapFile endswith \".smc\".\n\n Args:\n file_path (str):\n Path to an SMC file.\n body_model (nn.Module or dict):\n Only needed for SMPL transformation to device frame\n if nn.Module: a body_model instance\n if dict: a body_model config\n \"\"\"\n self.smc = h5py.File(file_path, 'r')\n self.__calibration_dict__ = None\n self.__kinect_calib_dict__ = None \n self.__available_keys__ = list(self.smc.keys())\n \n self.actor_info = None \n if hasattr(self.smc, 'attrs') and len(self.smc.attrs.keys()) > 0:\n self.actor_info = dict(\n id=self.smc.attrs['actor_id'],\n perf_id=self.smc.attrs['performance_id'],\n age=self.smc.attrs['age'],\n gender=self.smc.attrs['gender'],\n height=self.smc.attrs['height'],\n weight=self.smc.attrs['weight'],\n ethnicity=self.smc.attrs['ethnicity'],\n )\n\n self.Camera_5mp_info = None \n if 'Camera_5mp' in self.smc:\n self.Camera_5mp_info = dict(\n num_device=self.smc['Camera_5mp'].attrs['num_device'],\n num_frame=self.smc['Camera_5mp'].attrs['num_frame'],\n resolution=self.smc['Camera_5mp'].attrs['resolution'],\n )\n self.Camera_12mp_info = None \n if 'Camera_12mp' in self.smc:\n self.Camera_12mp_info = dict(\n num_device=self.smc['Camera_12mp'].attrs['num_device'],\n num_frame=self.smc['Camera_12mp'].attrs['num_frame'],\n resolution=self.smc['Camera_12mp'].attrs['resolution'],\n )\n self.Kinect_info = None\n if 'Kinect' in self.smc:\n self.Kinect_info=dict(\n num_device=self.smc['Kinect'].attrs['num_device'],\n num_frame=self.smc['Kinect'].attrs['num_frame'],\n resolution=self.smc['Kinect'].attrs['resolution'],\n )\n\n def get_available_keys(self):\n return self.__available_keys__ \n\n def get_actor_info(self):\n return self.actor_info\n \n def get_Camera_12mp_info(self):\n return self.Camera_12mp_info\n\n def get_Camera_5mp_info(self):\n return self.Camera_5mp_info\n \n def get_Kinect_info(self):\n return self.Kinect_info\n \n ### RGB Camera Calibration\n def get_Calibration_all(self):\n \"\"\"Get calibration matrix of all cameras and save it in self\n \n Args:\n None\n\n Returns:\n Dictionary of calibration matrixs of all matrixs.\n dict( \n Camera_Parameter: Camera_id : Matrix_type : value\n )\n Notice:\n Camera_id(str) in {'Camera_5mp': '0'~'47', 'Camera_12mp':'48'~'60'}\n Matrix_type in ['D', 'K', 'RT', 'Color_Calibration'] \n \"\"\" \n if not 'Camera_Parameter' in self.smc:\n print(\"=== no key: Camera_Parameter.\\nplease check available keys!\")\n return None \n\n if self.__calibration_dict__ is not None:\n return self.__calibration_dict__\n\n self.__calibration_dict__ = dict()\n for ci in self.smc['Camera_Parameter'].keys():\n self.__calibration_dict__.setdefault(ci,dict())\n for mt in ['D', 'K', 'RT', 'Color_Calibration'] :\n self.__calibration_dict__[ci][mt] = \\\n self.smc['Camera_Parameter'][ci][mt][()]\n return self.__calibration_dict__\n\n def get_Calibration(self, Camera_id):\n \"\"\"Get calibration matrixs of a certain camera by its type and id \n\n Args:\n Camera_id (int/str of a number):\n Camera_id(str) in {'Camera_5mp': '0'~'47', \n 'Camera_12mp':'48'~'60'}\n Returns:\n Dictionary of calibration matrixs.\n ['D', 'K', 'RT', 'Color_Calibration'] \n \"\"\"\n if not 'Camera_Parameter' in self.smc:\n print(\"=== no key: Camera_Parameter.\\nplease check available keys!\")\n return None \n\n rs = dict()\n for k in ['D', 'K', 'RT', 'Color_Calibration'] :\n rs[k] = self.smc['Camera_Parameter'][f'{int(Camera_id):02d}'][k][()]\n return rs\n\n ### Kinect Camera Calibration\n def get_Kinect_Calibration_all(self):\n \"\"\"Get calibration matrix of all kinect cameras and save it in self\n \n Args:\n None\n\n Returns:\n Dictionary of calibration matrixs of all matrixs.\n dict( \n Camera_group: Camera_id : Matrix_type : value\n )\n Notice:\n Camera_group(str) in ['Kinect']\n Camera_id(str) in {'Kinect': '0'~'7'}\n Matrix_type in ['D', 'K', 'RT'] \n \"\"\" \n if not 'Calibration' in self.smc:\n print(\"=== no key: Calibration.\\nplease check available keys!\")\n return None \n\n if self.__kinect_calib_dict__ is not None:\n return self.__kinect_calib_dict__\n\n self.__kinect_calib_dict__ = dict()\n for cg in ['Kinect']:\n self.__kinect_calib_dict__.setdefault(cg,dict())\n for ci in self.smc['Calibration'][cg].keys():\n self.__kinect_calib_dict__[cg].setdefault(ci,dict())\n for mt in ['D', 'K', 'RT'] :\n self.__kinect_calib_dict__[cg][ci][mt] = \\\n self.smc['Calibration'][cg][ci][mt][()]\n return self.__kinect_calib_dict__\n\n def get_kinect_Calibration(self, Camera_id):\n \"\"\"Get calibration matrixs of a certain kinect camera by its type and id \n\n Args:\n Camera_group (str):\n Camera_group in ['Kinect'].\n Camera_id (int/str of a number):\n CameraID(str) in {'Kinect': '0'~'7'}\n Returns:\n Dictionary of calibration matrixs.\n ['D', 'K', 'RT'] \n \"\"\" \n if not 'Calibration' in self.smc:\n print(\"=== no key: Calibration.\\nplease check available keys!\")\n return None \n\n Camera_id = f'{int(Camera_id):02d}'\n assert(Camera_id in self.smc['Calibration'][\"Kinect\"].keys())\n rs = dict()\n for k in ['D', 'K', 'RT']:\n rs[k] = self.smc['Calibration'][\"Kinect\"][Camera_id][k][()]\n return rs\n\n ### RGB image\n def __read_color_from_bytes__(self, color_array):\n \"\"\"Decode an RGB image from an encoded byte array.\"\"\"\n return cv2.imdecode(color_array, cv2.IMREAD_COLOR)\n\n def get_mask(self, Camera_id, Frame_id=None, disable_tqdm=True):\n \"\"\"Get mask from Camera_id, Frame_id\n\n Args:\n Camera_id (int/str of a number):\n Camera_id (str) in \n {'Camera_5mp': '0'~'47', \n 'Camera_12mp':'48'~'60',\n 'Kinect': '0'~'7'}\n Frame_id a.(int/str of a number): '0' ~ 'num_frame'\n b.list of numbers (int/str)\n c.None: get batch of all imgs in order of time sequence \n Returns:\n a single img :\n 'color': HWC in bgr (uint8)\n 'mask' : HW (uint8)\n 'depth': HW (uint16)\n \"\"\" \n if not 'Mask' in self.smc:\n print(\"=== no key: Mask.\\nplease check available keys!\")\n return None \n\n Camera_id = str(Camera_id)\n\n assert(isinstance(Frame_id,(list,int, str, type(None))))\n if isinstance(Frame_id, (str,int)):\n Frame_id = str(Frame_id)\n assert(Frame_id in self.smc['Mask'][Camera_id]['mask'].keys())\n img_byte = self.smc['Mask'][Camera_id]['mask'][Frame_id][()]\n img_color = self.__read_color_from_bytes__(img_byte)\n img_color = np.max(img_color,2)\n return img_color \n else:\n if Frame_id is None:\n Frame_id_list =sorted([int(l) for l in self.smc['Mask'][Camera_id]['mask'].keys()])\n elif isinstance(Frame_id, list):\n Frame_id_list = Frame_id\n rs = []\n for fi in tqdm.tqdm(Frame_id_list, disable=disable_tqdm):\n rs.append(self.get_mask(Camera_id,fi))\n return np.stack(rs,axis=0)\n\n def get_img(self, Camera_group, Camera_id, Image_type, Frame_id=None, disable_tqdm=True):\n \"\"\"Get image its Camera_group, Camera_id, Image_type and Frame_id\n\n Args:\n Camera_group (str):\n Camera_group in ['Camera_12mp', 'Camera_5mp','Kinect'].\n Camera_id (int/str of a number):\n CameraID (str) in \n {'Camera_5mp': '0'~'47', \n 'Camera_12mp':'48'~'60',\n 'Kinect': '0'~'7'}\n Image_type(str) in \n {'Camera_5mp': ['color'], \n 'Camera_12mp': ['color'],\n 'Kinect': ['depth', 'mask']}\n Frame_id a.(int/str of a number): '0' ~ 'num_frame'('149') \n b.list of numbers (int/str)\n c.None: get batch of all imgs in order of time sequence \n Returns:\n a single img :\n 'color': HWC in bgr (uint8)\n 'mask' : HW (uint8)\n 'depth': HW (uint16)\n \"\"\" \n if not Camera_group in self.smc:\n print(\"=== no key: %s.\\nplease check available keys!\" % Camera_group)\n return None\n\n assert(Camera_group in ['Camera_12mp', 'Camera_5mp','Kinect'])\n Camera_id = str(Camera_id)\n assert(Camera_id in self.smc[Camera_group].keys())\n assert(Image_type in self.smc[Camera_group][Camera_id].keys())\n assert(isinstance(Frame_id,(list,int, str, type(None))))\n if isinstance(Frame_id, (str,int)):\n Frame_id = str(Frame_id)\n assert(Frame_id in self.smc[Camera_group][Camera_id][Image_type].keys())\n if Image_type in ['color']:\n img_byte = self.smc[Camera_group][Camera_id][Image_type][Frame_id][()]\n img_color = self.__read_color_from_bytes__(img_byte)\n if Image_type == 'mask':\n img_byte = self.smc[Camera_group][Camera_id][Image_type][Frame_id][()]\n img_color = self.__read_color_from_bytes__(img_byte)\n img_color = np.max(img_color,2)\n if Image_type == 'depth':\n img_color = self.smc[Camera_group][Camera_id][Image_type][Frame_id][()]\n return img_color \n else:\n if Frame_id is None:\n Frame_id_list =sorted([int(l) for l in self.smc[Camera_group][Camera_id][Image_type].keys()])\n elif isinstance(Frame_id, list):\n Frame_id_list = Frame_id\n rs = []\n for fi in tqdm(Frame_id_list, disable=disable_tqdm):\n rs.append(self.get_img(Camera_group, Camera_id, Image_type,fi))\n return np.stack(rs,axis=0)\n \n ###Keypoints2d\n def get_Keypoints2d(self, Camera_id, Frame_id=None):\n \"\"\"Get keypoint2D by its Camera_group, Camera_id and Frame_id\n\n Args:\n Camera_id (int/str of a number):\n CameraID (str) in \n {'Camera_5mp': '0'~'47', \n 'Camera_12mp':'48'~'60',}\n Frame_id a.(int/str of a number): '0' ~ 'num_frame-1'('149') \n b.list of numbers (int/str)\n c.None: get batch of all imgs in order of time sequence \n Returns:\n a single img :\n 'color': HWC in bgr (uint8)\n 'mask' : HW (uint8)\n 'depth': HW (uint16)\n \"\"\" \n if not 'Keypoints_2D' in self.smc:\n print(\"=== no key: Keypoints_2D.\\nplease check available keys!\")\n return None \n\n Camera_id = f'{int(Camera_id):02d}'\n assert(isinstance(Frame_id,(list,int, str, type(None))))\n if isinstance(Frame_id, (str,int)):\n Frame_id = int(Frame_id)\n return self.smc['Keypoints_2D'][Camera_id][()][Frame_id,:]\n else:\n if Frame_id is None:\n return self.smc['Keypoints_2D'][Camera_id][()]\n elif isinstance(Frame_id, list):\n Frame_id_list = Frame_id\n rs = []\n for fi in tqdm.tqdm(Frame_id_list):\n rs.append(self.get_Keypoints2d(Camera_id,fi))\n return np.stack(rs,axis=0)\n\n ###Keypoints3d\n def get_Keypoints3d(self, Frame_id=None):\n \"\"\"Get keypoint3D Frame_id, TODO coordinate\n\n Args:\n Frame_id a.(int/str of a number): '0' ~ 'num_frame-1'('149') \n b.list of numbers (int/str)\n c.None: get batch of all imgs in order of time sequence \n Returns:\n Keypoints3d tensor: np.ndarray of shape ([N], ,3)\n \"\"\" \n if not 'Keypoints_3D' in self.smc:\n print(\"=== no key: Keypoints_3D.\\nplease check available keys!\")\n return None \n\n if isinstance(Frame_id, (str,int)):\n Frame_id = int(Frame_id)\n return self.smc['Keypoints_3D'][\"keypoints3d\"][Frame_id,:]\n else:\n if Frame_id is None:\n return self.smc['Keypoints_3D'][\"keypoints3d\"]\n elif isinstance(Frame_id, list):\n Frame_id_list = Frame_id\n rs = []\n for fi in tqdm.tqdm(Frame_id_list):\n rs.append(self.get_Keypoints3d(fi))\n return np.stack(rs,axis=0)\n\n ###SMPLx\n def get_SMPLx(self, Frame_id=None):\n \"\"\"Get SMPL (world coordinate) computed by mocap processing pipeline.\n\n Args:\n Frame_id (int, list or None, optional):\n int: frame id of one selected frame\n list: a list of frame id\n None: all frames will be returned\n Defaults to None.\n\n Returns:\n dict:\n 'global_orient': np.ndarray of shape (N, 3)\n 'body_pose': np.ndarray of shape (N, 21, 3)\n 'transl': np.ndarray of shape (N, 3)\n 'betas': np.ndarray of shape (1, 10)\n \"\"\"\n if not 'SMPLx' in self.smc:\n print(\"=== no key: SMPLx.\\nplease check available keys!\")\n return None \n\n t_frame = self.smc['SMPLx']['betas'][()].shape[0]\n if Frame_id is None:\n frame_list = range(t_frame)\n elif isinstance(Frame_id, list):\n frame_list = [int(fi) for fi in Frame_id]\n elif isinstance(Frame_id, (int,str)):\n Frame_id = int(Frame_id)\n assert Frame_id < t_frame,\\\n f'Invalid frame_index {Frame_id}'\n frame_list = Frame_id\n else:\n raise TypeError('frame_id should be int, list or None.')\n\n smpl_dict = {}\n for key in ['betas', 'expression', 'fullpose', 'transl']:\n smpl_dict[key] = self.smc['SMPLx'][key][()][frame_list, ...]\n smpl_dict['scale'] = self.smc['SMPLx']['scale'][()]\n\n return smpl_dict\n\n def release(self):\n self.smc = None \n self.__calibration_dict__ = None\n self.__kinect_calib_dict__ = None\n self.__available_keys__ = None\n self.actor_info = None \n self.Camera_5mp_info = None\n self.Camera_12mp_info = None \n self.Kinect_info = None" } ]
import os import sys import numpy as np import torch import json import imageio import cv2 import random from PIL import Image from typing import NamedTuple from scene.colmap_loader import read_extrinsics_text, read_intrinsics_text, qvec2rotmat, \ read_extrinsics_binary, read_intrinsics_binary, read_points3D_binary, read_points3D_text from utils.graphics_utils import getWorld2View2, focal2fov, fov2focal from pathlib import Path from plyfile import PlyData, PlyElement from utils.sh_utils import SH2RGB from scene.gaussian_model import BasicPointCloud from smpl.smpl_numpy import SMPL from smplx.body_models import SMPLX from data.dna_rendering.dna_rendering_sample_code.SMCReader import SMCReader
14,436
# # Copyright (C) 2023, Inria # GRAPHDECO research group, https://team.inria.fr/graphdeco # All rights reserved. # # This software is free for non-commercial, research and evaluation use # under the terms of the LICENSE.md file. # # For inquiries contact [email protected] # class CameraInfo(NamedTuple): uid: int pose_id: int R: np.array T: np.array K: np.array FovY: np.array FovX: np.array image: np.array image_path: str image_name: str bkgd_mask: np.array bound_mask: np.array width: int height: int smpl_param: dict world_vertex: np.array world_bound: np.array big_pose_smpl_param: dict big_pose_world_vertex: np.array big_pose_world_bound: np.array class SceneInfo(NamedTuple): point_cloud: BasicPointCloud train_cameras: list test_cameras: list nerf_normalization: dict ply_path: str def getNerfppNorm(cam_info): def get_center_and_diag(cam_centers): cam_centers = np.hstack(cam_centers) avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True) center = avg_cam_center dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True) diagonal = np.max(dist) return center.flatten(), diagonal cam_centers = [] for cam in cam_info: W2C = getWorld2View2(cam.R, cam.T) C2W = np.linalg.inv(W2C) cam_centers.append(C2W[:3, 3:4]) center, diagonal = get_center_and_diag(cam_centers) radius = diagonal * 1.1 translate = -center return {"translate": translate, "radius": radius} def readColmapCameras(cam_extrinsics, cam_intrinsics, images_folder): cam_infos = [] for idx, key in enumerate(cam_extrinsics): sys.stdout.write('\r') # the exact output you're looking for: sys.stdout.write("Reading camera {}/{}".format(idx+1, len(cam_extrinsics))) sys.stdout.flush() extr = cam_extrinsics[key] intr = cam_intrinsics[extr.camera_id] height = intr.height width = intr.width uid = intr.id R = np.transpose(qvec2rotmat(extr.qvec)) T = np.array(extr.tvec) if intr.model=="SIMPLE_PINHOLE": focal_length_x = intr.params[0]
# # Copyright (C) 2023, Inria # GRAPHDECO research group, https://team.inria.fr/graphdeco # All rights reserved. # # This software is free for non-commercial, research and evaluation use # under the terms of the LICENSE.md file. # # For inquiries contact [email protected] # class CameraInfo(NamedTuple): uid: int pose_id: int R: np.array T: np.array K: np.array FovY: np.array FovX: np.array image: np.array image_path: str image_name: str bkgd_mask: np.array bound_mask: np.array width: int height: int smpl_param: dict world_vertex: np.array world_bound: np.array big_pose_smpl_param: dict big_pose_world_vertex: np.array big_pose_world_bound: np.array class SceneInfo(NamedTuple): point_cloud: BasicPointCloud train_cameras: list test_cameras: list nerf_normalization: dict ply_path: str def getNerfppNorm(cam_info): def get_center_and_diag(cam_centers): cam_centers = np.hstack(cam_centers) avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True) center = avg_cam_center dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True) diagonal = np.max(dist) return center.flatten(), diagonal cam_centers = [] for cam in cam_info: W2C = getWorld2View2(cam.R, cam.T) C2W = np.linalg.inv(W2C) cam_centers.append(C2W[:3, 3:4]) center, diagonal = get_center_and_diag(cam_centers) radius = diagonal * 1.1 translate = -center return {"translate": translate, "radius": radius} def readColmapCameras(cam_extrinsics, cam_intrinsics, images_folder): cam_infos = [] for idx, key in enumerate(cam_extrinsics): sys.stdout.write('\r') # the exact output you're looking for: sys.stdout.write("Reading camera {}/{}".format(idx+1, len(cam_extrinsics))) sys.stdout.flush() extr = cam_extrinsics[key] intr = cam_intrinsics[extr.camera_id] height = intr.height width = intr.width uid = intr.id R = np.transpose(qvec2rotmat(extr.qvec)) T = np.array(extr.tvec) if intr.model=="SIMPLE_PINHOLE": focal_length_x = intr.params[0]
FovY = focal2fov(focal_length_x, height)
8
2023-11-29 07:10:39+00:00
24k
xmu-xiaoma666/X-Dreamer
train_x_dreamer.py
[ { "identifier": "DatasetMesh", "path": "dataset/dataset_mesh.py", "snippet": "class DatasetMesh(torch.utils.data.Dataset):\n\n\n def __init__(self, glctx, FLAGS, validate=False, gif=False):\n # Init \n self.glctx = glctx\n self.FLAGS = FLAGS\n self.validate = validate\n self.gif = gif\n self.aspect = FLAGS.train_res[1] / FLAGS.train_res[0]\n self.fovy_range_min = np.deg2rad(FLAGS.fovy_range[0])\n self.fovy_range_max = np.deg2rad(FLAGS.fovy_range[1])\n self.elevation_range_min= np.deg2rad(FLAGS.elevation_range[0])\n self.elevation_range_max= np.deg2rad(FLAGS.elevation_range[1])\n self.angle_front = np.deg2rad(FLAGS.front_threshold)\n \n\n def _gif_scene(self, itr):\n fovy = np.deg2rad(45)\n proj_mtx = util.perspective(fovy, self.FLAGS.display_res[1] / self.FLAGS.display_res[0], self.FLAGS.cam_near_far[0], self.FLAGS.cam_near_far[1])\n ang = (itr / 100) * np.pi * 2\n rotate_x = np.deg2rad(20)\n prompt_index = 0\n mv = util.translate(0, 0, -3) @ (util.rotate_x(-rotate_x) @ util.rotate_y(ang ))\n normal_rotate = util.rotate_y_1(0)\n mvp = proj_mtx @ mv\n campos = torch.linalg.inv(mv)[:3, 3]\n\n return mv[None, ...], mvp[None, ...], campos[None, ...], self.FLAGS.display_res, self.FLAGS.spp, normal_rotate[None,...], prompt_index, np.rad2deg(rotate_x), np.rad2deg(ang), torch.tensor([fovy])\n \n \n\n def _validate_scene(self, itr):\n fovy = np.deg2rad(45)\n proj_mtx = util.perspective(fovy, self.FLAGS.train_res[1] / self.FLAGS.train_res[0], self.FLAGS.cam_near_far[0], self.FLAGS.cam_near_far[1])\n ang = (itr / 4) * np.pi * 2\n rotate_x = np.random.uniform(-np.pi/4,np.pi/18)\n prompt_index = 0\n mv = util.translate(0, 0, -3) @ (util.rotate_x(rotate_x) @ util.rotate_y( ang ))\n normal_rotate = util.rotate_y_1(0)\n mvp = proj_mtx @ mv\n campos = torch.linalg.inv(mv)[:3, 3]\n return mv[None, ...], mvp[None, ...], campos[None, ...], self.FLAGS.display_res, self.FLAGS.spp, normal_rotate[None,...], prompt_index, np.rad2deg(rotate_x), np.rad2deg(ang), torch.tensor([fovy])\n\n def _train_scene(self, itr):\n fovy = np.random.uniform(self.fovy_range_min, self.fovy_range_max)\n proj_mtx = util.perspective(fovy, self.FLAGS.train_res[1] / self.FLAGS.train_res[0], self.FLAGS.cam_near_far[0], self.FLAGS.cam_near_far[1])\n if self.FLAGS.gpu_number == 8: # All the results in the paper were generated using 8 3090 GPUs. We cannot guarantee that fewer than 8 GPUs can achieve the same effect.\n if self.FLAGS.local_rank in [0,4]:\n rotate_y = np.random.uniform(np.deg2rad(-45), np.deg2rad(45))\n elif self.FLAGS.local_rank in [1,5]:\n rotate_y = np.random.uniform(np.deg2rad(45), np.deg2rad(135))\n elif self.FLAGS.local_rank in [2,6]:#back\n rotate_y = np.random.uniform( np.deg2rad(135), np.deg2rad(225))\n elif self.FLAGS.local_rank in [3,7]:\n rotate_y = np.random.uniform(np.deg2rad(-135), np.deg2rad(-45)) \n if rotate_y > np.pi:\n rotate_y = rotate_y - np.pi*2\n elif self.FLAGS.gpu_number == 4: #All the results in the paper were generated using 8 3090 GPUs. We cannot guarantee that fewer than 8 GPUs can achieve the same effect.\n if self.FLAGS.local_rank in [0]:\n rotate_y = np.random.uniform(np.deg2rad(-45), np.deg2rad(45))\n elif self.FLAGS.local_rank in [1]:\n rotate_y = np.random.uniform(np.deg2rad(45), np.deg2rad(135))\n elif self.FLAGS.local_rank in [2]:#back\n rotate_y = np.random.uniform( np.deg2rad(135), np.deg2rad(225))\n elif self.FLAGS.local_rank in [3]:\n rotate_y = np.random.uniform(np.deg2rad(-135), np.deg2rad(-45)) \n if rotate_y > np.pi:\n rotate_y = rotate_y - np.pi*2\n else:\n rotate_y = np.random.uniform(np.deg2rad(-180), np.deg2rad(180)) #All the results in the paper were generated using 8 3090 GPUs. We cannot guarantee that fewer than 8 GPUs can achieve the same effect.\n \n rotate_x = -np.random.uniform(self.elevation_range_min, self.elevation_range_max)\n # angle_front = np.deg2rad(45)\n prompt_index = get_view_direction(thetas= rotate_x, phis = rotate_y, front= self.angle_front)\n cam_radius = 3\n x = np.random.uniform(-self.FLAGS.camera_random_jitter, self.FLAGS.camera_random_jitter)\n y = np.random.uniform(-self.FLAGS.camera_random_jitter, self.FLAGS.camera_random_jitter)\n mv = util.translate(x, y, -cam_radius) @ (util.rotate_x(rotate_x) @ util.rotate_y(rotate_y))\n if ((itr+1)/self.FLAGS.batch) <=self.FLAGS.coarse_iter:\n rotate_y1 = np.random.uniform(0,np.pi*2) \n rotate_x1 = np.random.uniform(-np.pi,np.pi)\n normal_rotate = util.rotate_y_1(rotate_y1 )@ util.rotate_x_1(rotate_x1) \n else:\n normal_rotate = util.rotate_y_1(0)@util.rotate_x_1(0)\n mvp = proj_mtx @ mv\n campos = torch.linalg.inv(mv)[:3, 3]\n return mv[None, ...], mvp[None, ...], campos[None, ...], self.FLAGS.display_res, self.FLAGS.spp, normal_rotate[None,...], prompt_index, np.rad2deg(rotate_x), np.rad2deg(rotate_y), torch.tensor([fovy])\n\n def __len__(self):\n if self.gif == True:\n return 100\n else:\n return 4 if self.validate else (self.FLAGS.iter + 1) * self.FLAGS.batch\n\n def __getitem__(self, itr):\n if self.gif:\n mv, mvp, campos, iter_res, iter_spp, normal_rotate, prompt_index, elev, azim, fov = self._gif_scene(itr)\n elif self.validate:\n mv, mvp, campos, iter_res, iter_spp, normal_rotate, prompt_index, elev, azim, fov = self._validate_scene(itr)\n else:\n mv, mvp, campos, iter_res, iter_spp, normal_rotate, prompt_index, elev, azim, fov = self._train_scene(itr)\n\n return {\n 'mv' : mv,\n 'mvp' : mvp,\n 'campos' : campos,\n 'resolution' : iter_res,\n 'spp' : iter_spp,\n 'normal_rotate': normal_rotate,\n 'prompt_index' : prompt_index,\n 'elev': elev,\n 'azim': azim,\n 'fov': fov\n }\n def collate(self, batch):\n iter_res, iter_spp = batch[0]['resolution'], batch[0]['spp']\n return {\n 'mv' : torch.cat(list([item['mv'] for item in batch]), dim=0),\n 'mvp' : torch.cat(list([item['mvp'] for item in batch]), dim=0),\n 'campos' : torch.cat(list([item['campos'] for item in batch]), dim=0),\n 'resolution' : iter_res,\n 'spp' : iter_spp,\n 'normal_rotate' : torch.cat(list([item['normal_rotate'] for item in batch]), dim=0),\n # 'prompt_index' : torch.cat(list([item['prompt_index'] for item in batch]), dim=0),\n 'prompt_index' : np.array([item['prompt_index'] for item in batch], dtype=np.int32),\n 'elev' : np.array([item['elev'] for item in batch], dtype=np.float16),\n 'azim' : np.array([item['azim'] for item in batch], dtype=np.float16),\n 'fov' : torch.cat(list([item['fov'] for item in batch]), dim=0),\n }" }, { "identifier": "get_camera_params", "path": "dataset/dataset_mesh.py", "snippet": "def get_camera_params(resolution= 512, fov=45, elev_angle=-20, azim_angle=0):\n fovy = np.deg2rad(fov) \n elev = np.radians( elev_angle )\n azim = np.radians( azim_angle ) \n proj_mtx = util.perspective(fovy, resolution /resolution, 1, 50)\n mv = util.translate(0, 0, -3) @ (util.rotate_x(elev) @ util.rotate_y(azim))\n normal_rotate = util.rotate_y_1(-azim ) @ util.rotate_x_1(-elev) \n # nomral_rotate = util.rotate_y_1(0) @ util.rotate_x_1(0) \n mvp = proj_mtx @ mv\n campos = torch.linalg.inv(mv)[:3, 3]\n bkgs = torch.ones(1, resolution, resolution, 3, dtype=torch.float32, device='cuda')\n return {\n 'mvp' : mvp[None, ...].cuda(),\n 'mv' : mv[None, ...].cuda(),\n 'campos' : campos[None, ...].cuda(),\n 'resolution' : [resolution, resolution], \n 'spp' : 1,\n 'background' : bkgs,\n 'normal_rotate' : normal_rotate[None,...].cuda(),\n 'elev_angle' : torch.tensor(elev_angle).cuda(),\n 'azim_angle' : torch.tensor(azim_angle).cuda(),\n 'fov' : torch.tensor(fovy).cuda(),\n }" }, { "identifier": "DMTetGeometry", "path": "geometry/dmtet_x_dreamer.py", "snippet": "class DMTetGeometry(torch.nn.Module):\n def __init__(self, grid_res, scale, FLAGS):\n super(DMTetGeometry, self).__init__()\n\n self.FLAGS = FLAGS\n self.grid_res = grid_res\n self.marching_tets = DMTet()\n \n tets = np.load('data/tets/{}_tets.npz'.format(self.grid_res))\n self.verts = torch.tensor(tets['vertices'], dtype=torch.float32, device='cuda') * scale\n print(\"tet grid min/max\", torch.min(self.verts).item(), torch.max(self.verts).item())\n self.decoder = Decoder(multires=0 , AABB= self.getAABB(), mesh_scale= scale)\n self.indices = torch.tensor(tets['indices'], dtype=torch.long, device='cuda')\n self.generate_edges()\n self.pos_encoder = CameraEncoder().to(self.verts.device)\n\n def generate_edges(self):\n with torch.no_grad():\n edges = torch.tensor([0,1,0,2,0,3,1,2,1,3,2,3], dtype = torch.long, device = \"cuda\")\n all_edges = self.indices[:,edges].reshape(-1,2) \n all_edges_sorted = torch.sort(all_edges, dim=1)[0]\n self.all_edges = torch.unique(all_edges_sorted, dim=0)\n\n @torch.no_grad()\n def getAABB(self):\n return torch.min(self.verts, dim=0).values, torch.max(self.verts, dim=0).values\n\n def getMesh(self, material):\n pred= self.decoder(self.verts)\n \n self.sdf , self.deform = pred[:, 0], pred[:, 1:] \n v_deformed = self.verts + 1 / (self.grid_res ) * torch.tanh(self.deform)\n verts, faces = self.marching_tets(v_deformed, self.sdf, self.indices)\n \n imesh = mesh.Mesh(verts, faces, material=material)\n imesh = mesh.auto_normals(imesh)\n return imesh\n\n def render(self, glctx, target, lgt, opt_material, bsdf=None, if_normal=False, mode = 'geometry_modeling', if_flip_the_normal = False, if_use_bump = False):\n opt_mesh = self.getMesh(opt_material) \n return render.render_mesh(glctx, \n opt_mesh, \n target['mvp'], \n target['campos'], \n lgt, \n target['resolution'], \n spp=target['spp'], \n msaa= True,\n background= target['background'],\n bsdf= bsdf,\n if_normal= if_normal,\n normal_rotate= target['normal_rotate'],\n mode = mode,\n if_flip_the_normal = if_flip_the_normal,\n if_use_bump = if_use_bump\n )\n\n \n def tick(self, glctx, target, lgt, opt_material, iteration, if_normal, guidance, mode, if_flip_the_normal, if_use_bump):\n # ==============================================================================================\n # Render optimizable object with identical conditions\n # ==============================================================================================\n buffers= self.render(glctx, target, lgt, opt_material, if_normal= if_normal, mode = mode, if_flip_the_normal = if_flip_the_normal, if_use_bump = if_use_bump)\n if self.FLAGS.add_directional_text:\n text_embeddings = torch.cat([guidance.uncond_z[target['prompt_index']], guidance.text_z[target['prompt_index']]]) # [B*2, 77, 1024]\n indexs = torch.cat([guidance.uncond_index[target['prompt_index']], guidance.index[target['prompt_index']]]) # [B*2, 77, 1024]\n else:\n text_embeddings = torch.cat([guidance.uncond_z, guidance.text_z]) # [B * 2, 77, 1024]\n indexs = torch.cat([guidance.uncond_index, guidance.index]) # [B*2, 77, 1024]\n\n \n if iteration <=self.FLAGS.coarse_iter:\n t = torch.randint( guidance.min_step_early, guidance.max_step_early + 1, [self.FLAGS.batch], dtype=torch.long, device='cuda') # [B]\n pred_rgb_512 = buffers['shaded'][..., 0:4].permute(0, 3, 1, 2).contiguous() # [B, 4, 64, 64]\n latents = F.interpolate(pred_rgb_512, (64, 64), mode='bilinear', align_corners=False)\n mask = (buffers['shaded'][..., 3:4]).permute(0, 3, 1, 2).contiguous()\n mask2 = mask.squeeze()\n \n else:\n t = torch.randint(guidance.min_step_late, guidance.max_step_late + 1, [self.FLAGS.batch], dtype=torch.long, device='cuda')\n srgb = buffers['shaded'][...,0:3] #* buffers['shaded'][..., 3:4] # normal * mask\n # \n pred_rgb_512 = srgb.permute(0, 3, 1, 2).contiguous() # [B, 3, 512, 512]\n latents = guidance.encode_imgs(pred_rgb_512)\n mask = (buffers['shaded'][..., 3:4]).permute(0, 3, 1, 2).contiguous()\n mask2 = mask.squeeze()\n\n ### calculate camera pos feature\n came_pos = torch.cat([target['campos'],torch.from_numpy(target['elev']).unsqueeze(-1).cuda(),torch.from_numpy(target['azim']).cuda().unsqueeze(-1),target['fov'].unsqueeze(-1)],dim=-1)\n came_pos = torch.cat([came_pos,came_pos],dim=0) #bs*2, 5\n came_pos = normalize_camera(came_pos,self.FLAGS)\n came_posfeat = self.pos_encoder(came_pos)\n\n # add noise\n noise = torch.randn_like(latents)\n latents_noisy = guidance.scheduler.add_noise(latents, noise, t)\n # pred noise\n latent_model_input = torch.cat([latents_noisy] * 2)\n tt = torch.cat([t] * 2)\n noise_pred, attention_map = guidance.unet(latent_model_input, tt, encoder_hidden_states=text_embeddings, index=indexs, came_posfeat=came_posfeat)\n noise_pred = noise_pred.sample\n\n attention_map[0] = attention_map[0].reshape(self.FLAGS.batch*2, 64, 64).contiguous()\n attention_map[1] = attention_map[1].reshape(self.FLAGS.batch*2, 32, 32).contiguous()\n attention_map[2] = attention_map[2].reshape(self.FLAGS.batch*2, 16, 16).contiguous()\n attention_map[3] = attention_map[3].reshape(self.FLAGS.batch*2, 8 , 8 ).contiguous()\n attention_map[4] = attention_map[4].reshape(self.FLAGS.batch*2, 16, 16).contiguous()\n attention_map[5] = attention_map[5].reshape(self.FLAGS.batch*2, 32, 32).contiguous()\n attention_map[6] = attention_map[6].reshape(self.FLAGS.batch*2, 64, 64).contiguous()\n\n noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)\n noise_pred =noise_pred_uncond + guidance.guidance_weight * (noise_pred_text - noise_pred_uncond) # [B, 4, 64, 64]\n if iteration <= self.FLAGS.coarse_iter:\n w = (1 - guidance.alphas[t]) # [B]\n else:\n w = guidance.alphas[t] ** 0.5 * (1 - guidance.alphas[t])\n w = w[:, None, None, None] # [B, 1, 1, 1]\n grad = w * (noise_pred - noise ) #*w1\n grad = torch.nan_to_num(grad)\n \n sds_loss = SpecifyGradient.apply(latents, grad) \n img_loss = torch.tensor([0], dtype=torch.float32, device=\"cuda\")\n reg_loss = torch.tensor([0], dtype=torch.float32, device=\"cuda\")\n\n attention_loss = 0\n mask_sizes = [(64, 64), (32,32), (16,16), (8,8), (16,16), (32,32), (64,64)]\n for i in range(7):\n _, attention_map_text = attention_map[i].chunk(2)\n if(self.FLAGS.batch==1):\n mask2 = F.interpolate(mask2.unsqueeze(0).unsqueeze(0), mask_sizes[i], mode='bilinear').squeeze()\n else:\n mask2 = F.interpolate(mask2.unsqueeze(0), mask_sizes[i], mode='bilinear').squeeze()\n attention_map_text = (attention_map_text - attention_map_text.min())/(attention_map_text.max() - attention_map_text.min()+1e-6)\n attention_map_text = F.interpolate(attention_map_text.unsqueeze(0), size=mask_sizes[i], mode='bilinear', align_corners=False).squeeze()\n attention_loss = 0.1*F.l1_loss(mask2.float(), attention_map_text.float(), reduction=\"mean\") #0.1 1 10\n attention_loss = attention_loss/7\n \n return sds_loss, img_loss, reg_loss, attention_loss" }, { "identifier": "DLMesh", "path": "geometry/dlmesh_x_dreamer.py", "snippet": "class DLMesh(torch.nn.Module):\n def __init__(self, initial_guess, FLAGS):\n super(DLMesh, self).__init__()\n self.FLAGS = FLAGS\n self.initial_guess = initial_guess\n self.mesh = initial_guess.clone()\n self.pos_encoder = CameraEncoder().cuda()\n print(\"Base mesh has %d triangles and %d vertices.\" % (self.mesh.t_pos_idx.shape[0], self.mesh.v_pos.shape[0]))\n \n @torch.no_grad()\n def getAABB(self):\n return mesh.aabb(self.mesh)\n\n def getMesh(self, material):\n self.mesh.material = material\n\n imesh = mesh.Mesh(base=self.mesh)\n # Compute normals and tangent space\n imesh = mesh.auto_normals(imesh)\n imesh = mesh.compute_tangents(imesh)\n return imesh\n\n def render(self, glctx, target, lgt, opt_material, bsdf=None,if_normal=False, mode = 'appearance_modeling', if_flip_the_normal = False, if_use_bump = False):\n opt_mesh = self.getMesh(opt_material)\n return render.render_mesh(glctx, \n opt_mesh,\n target['mvp'],\n target['campos'],\n lgt,\n target['resolution'], \n spp=target['spp'], \n msaa=True,\n background= target['background'] ,\n bsdf= bsdf,\n if_normal=if_normal,\n normal_rotate=target['normal_rotate'], \n mode = mode,\n if_flip_the_normal = if_flip_the_normal,\n if_use_bump = if_use_bump\n )\n\n def tick(self, glctx, target, lgt, opt_material, iteration, if_normal, guidance, mode, if_flip_the_normal, if_use_bump):\n # ==============================================================================================\n # Render optimizable object with identical conditions\n # ==============================================================================================\n buffers= self.render(glctx, target, lgt, opt_material, if_normal = if_normal, mode = mode, if_flip_the_normal = if_flip_the_normal, if_use_bump = if_use_bump)\n if self.FLAGS.add_directional_text:\n text_embeddings = torch.cat([guidance.uncond_z[target['prompt_index']], guidance.text_z[target['prompt_index']]])\n indexs = torch.cat([guidance.uncond_index[target['prompt_index']], guidance.index[target['prompt_index']]]) # [B*2, 77, 1024]\n else:\n text_embeddings = torch.cat([guidance.uncond_z, guidance.text_z])\n indexs = torch.cat([guidance.uncond_index, guidance.index]) # [B*2, 77, 1024]\n\n\n if iteration <= self.FLAGS.coarse_iter:\n srgb = buffers['shaded'][...,0:3]\n srgb = util.rgb_to_srgb(srgb)\n mask = (buffers['shaded'][..., 3:4]).permute(0, 3, 1, 2).contiguous()\n mask2 = mask.squeeze()\n t = torch.randint( guidance.min_step_early, guidance.max_step_early+1, [self.FLAGS.batch], dtype=torch.long, device='cuda') # [B]\n else:\n srgb = buffers['shaded'][...,0:3]\n srgb = util.rgb_to_srgb(srgb)\n mask = (buffers['shaded'][..., 3:4]).permute(0, 3, 1, 2).contiguous()\n mask2 = mask.squeeze()\n t = torch.randint( guidance.min_step_late, guidance.max_step_late+1, [self.FLAGS.batch], dtype=torch.long, device='cuda') # [B]\n\n pred_rgb_512 = srgb.permute(0, 3, 1, 2).contiguous() # [1, 3, H, W]\n latents = guidance.encode_imgs(pred_rgb_512)\n \n ### calculate camera pos feature\n came_pos = torch.cat([target['campos'],torch.from_numpy(target['elev']).unsqueeze(-1).cuda(),torch.from_numpy(target['azim']).cuda().unsqueeze(-1),target['fov'].unsqueeze(-1)],dim=-1)\n came_pos = torch.cat([came_pos,came_pos],dim=0) #bs*2, 5\n came_pos = normalize_camera(came_pos,self.FLAGS)\n came_posfeat = self.pos_encoder(came_pos)\n\n\n # add noise\n noise = torch.randn_like(latents)\n latents_noisy = guidance.scheduler.add_noise(latents, noise, t)\n # pred noise\n latent_model_input = torch.cat([latents_noisy] * 2)\n tt = torch.cat([t] * 2)\n noise_pred, attention_map = guidance.unet(latent_model_input, tt, encoder_hidden_states= text_embeddings, index=indexs, came_posfeat=came_posfeat)#.sample######################\n noise_pred = noise_pred.sample\n\n attention_map[0] = attention_map[0].reshape(self.FLAGS.batch*2, 64, 64).contiguous()\n attention_map[1] = attention_map[1].reshape(self.FLAGS.batch*2, 32, 32).contiguous()\n attention_map[2] = attention_map[2].reshape(self.FLAGS.batch*2, 16, 16).contiguous()\n attention_map[3] = attention_map[3].reshape(self.FLAGS.batch*2, 8 , 8 ).contiguous()\n attention_map[4] = attention_map[4].reshape(self.FLAGS.batch*2, 16, 16).contiguous()\n attention_map[5] = attention_map[5].reshape(self.FLAGS.batch*2, 32, 32).contiguous()\n attention_map[6] = attention_map[6].reshape(self.FLAGS.batch*2, 64, 64).contiguous()\n\n noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)\n noise_pred = noise_pred_uncond + guidance.guidance_weight * (noise_pred_text - noise_pred_uncond)\n \n if guidance.sds_weight_strategy == 0:\n w = guidance.alphas[t] ** 0.5 * (1 - guidance.alphas[t])\n elif guidance.sds_weight_strategy == 1:\n w = 1 / (1 - guidance.alphas[t])\n elif guidance.sds_weight_strategy == 2:\n if iteration <= self.FLAGS.coarse_iter:\n w = guidance.alphas[t] ** 0.5 * (1 - guidance.alphas[t])\n else:\n w = 1 / (1 - guidance.alphas[t])\n w = w[:, None, None, None] # [B, 1, 1, 1]\n grad = w* (noise_pred -noise) \n grad = torch.nan_to_num(grad)\n sds_loss = SpecifyGradient.apply(latents, grad) \n img_loss = torch.tensor([0], dtype=torch.float32, device=\"cuda\")\n reg_loss = torch.tensor([0], dtype=torch.float32, device=\"cuda\")\n \n attention_loss = 0\n mask_sizes = [(64, 64), (32,32), (16,16), (8,8), (16,16), (32,32), (64,64)]\n for i in range(7):\n _, attention_map_text = attention_map[i].chunk(2)\n if(self.FLAGS.batch==1):\n mask2 = F.interpolate(mask2.unsqueeze(0).unsqueeze(0), mask_sizes[i], mode='bilinear').squeeze()\n else:\n mask2 = F.interpolate(mask2.unsqueeze(0), mask_sizes[i], mode='bilinear').squeeze()\n attention_map_text = (attention_map_text - attention_map_text.min())/(attention_map_text.max() - attention_map_text.min()+1e-6)\n attention_map_text = F.interpolate(attention_map_text.unsqueeze(0), size=mask2.shape, mode='bilinear', align_corners=False).squeeze()\n attention_loss = 0.1*F.l1_loss(mask2.float(), attention_map_text.float(), reduction=\"mean\") #0.1 1 10\n attention_loss = attention_loss/7\n \n return sds_loss, img_loss, reg_loss, attention_loss" }, { "identifier": "obj", "path": "render/obj.py", "snippet": "def _find_mat(materials, name):\ndef load_obj(filename, clear_ks=True, mtl_override=None):\ndef write_obj(folder, mesh, save_material=True):" }, { "identifier": "material", "path": "render/material.py", "snippet": "class Material(torch.nn.Module):\n def __init__(self, mat_dict):\n def __contains__(self, key):\n def __getitem__(self, key):\n def __setitem__(self, key, val):\n def __delitem__(self, key):\n def keys(self):\ndef load_mtl(fn, clear_ks=True):\ndef save_mtl(fn, material):\ndef _upscale_replicate(x, full_res):\ndef merge_materials(materials, texcoords, tfaces, mfaces):" }, { "identifier": "util", "path": "render/util.py", "snippet": "def dot(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:\ndef reflect(x: torch.Tensor, n: torch.Tensor) -> torch.Tensor:\ndef length(x: torch.Tensor, eps: float =1e-20) -> torch.Tensor:\ndef safe_normalize(x: torch.Tensor, eps: float =1e-20) -> torch.Tensor:\ndef to_hvec(x: torch.Tensor, w: float) -> torch.Tensor:\ndef _rgb_to_srgb(f: torch.Tensor) -> torch.Tensor:\ndef rgb_to_srgb(f: torch.Tensor) -> torch.Tensor:\ndef _srgb_to_rgb(f: torch.Tensor) -> torch.Tensor:\ndef srgb_to_rgb(f: torch.Tensor) -> torch.Tensor:\ndef reinhard(f: torch.Tensor) -> torch.Tensor:\ndef mse_to_psnr(mse):\ndef psnr_to_mse(psnr):\ndef get_miplevels(texture: np.ndarray) -> float:\ndef tex_2d(tex_map : torch.Tensor, coords : torch.Tensor, filter='nearest') -> torch.Tensor:\ndef cube_to_dir(s, x, y):\ndef latlong_to_cubemap(latlong_map, res):\ndef cubemap_to_latlong(cubemap, res):\ndef scale_img_hwc(x : torch.Tensor, size, mag='bilinear', min='area') -> torch.Tensor:\ndef scale_img_nhwc(x : torch.Tensor, size, mag='bilinear', min='area') -> torch.Tensor:\ndef avg_pool_nhwc(x : torch.Tensor, size) -> torch.Tensor:\ndef segment_sum(data: torch.Tensor, segment_ids: torch.Tensor) -> torch.Tensor:\ndef fovx_to_fovy(fovx, aspect):\ndef focal_length_to_fovy(focal_length, sensor_height):\ndef perspective(fovy=0.7854, aspect=1.0, n=0.1, f= 1000.0, device=None):\ndef perspective_offcenter(fovy, fraction, rx, ry, aspect=1.0, n=0.1, f=1000.0, device=None):\ndef translate(x, y, z, device=None):\ndef rotate_x(a, device=None):\ndef rotate_x_1(a, device=None):\ndef rotate_y(a, device=None):\ndef rotate_y_1(a, device=None):\ndef rotate_y_2(a, device=None):\ndef rotate_x_2(a, device=None):\ndef scale(s, device=None):\ndef lookAt(eye, at, up):\ndef random_rotation_translation(t, device=None):\ndef random_rotation(device=None):\ndef lines_focal(o, d):\ndef cosine_sample(N, size=None):\ndef bilinear_downsample(x : torch.tensor) -> torch.Tensor:\ndef bilinear_downsample(x : torch.tensor, spp) -> torch.Tensor:\ndef init_glfw():\ndef save_image(fn, x : np.ndarray):\ndef save_image_raw(fn, x : np.ndarray):\ndef load_image_raw(fn) -> np.ndarray:\ndef load_image(fn) -> np.ndarray:\ndef time_to_text(x):\ndef checkerboard(res, checker_size) -> np.ndarray:\ndef get_random_bg(h, w):\n R, L = aspect*y, -aspect*y\n T, B = y, -y\n I = torch.eye(3, dtype=o.dtype, device=o.device)\n S = torch.sum(d[..., None] @ torch.transpose(d[..., None], 1, 2) - I[None, ...], dim=0)\n C = torch.sum((d[..., None] @ torch.transpose(d[..., None], 1, 2) - I[None, ...]) @ o[..., None], dim=0).squeeze(1)\n N = N/torch.linalg.norm(N)" }, { "identifier": "mesh", "path": "render/mesh.py", "snippet": "class Mesh:\n def __init__(self, v_pos=None, t_pos_idx=None, v_nrm=None, t_nrm_idx=None, v_tex=None, t_tex_idx=None, v_tng=None, t_tng_idx=None, material=None, base=None):\n def copy_none(self, other):\n def clone(self):\ndef load_mesh(filename, mtl_override=None):\ndef aabb(mesh):\ndef compute_edges(attr_idx, return_inverse=False):\ndef compute_edge_to_face_mapping(attr_idx, return_inverse=False):\ndef unit_size(mesh):\ndef center_by_reference(base_mesh, ref_aabb, scale):\ndef auto_normals(imesh):\ndef compute_tangents(imesh):" }, { "identifier": "texture", "path": "render/texture.py", "snippet": "class texture2d_mip(torch.autograd.Function):\nclass Texture2D(torch.nn.Module):\n def forward(ctx, texture):\n def backward(ctx, dout):\n def __init__(self, init, min_max=None):\n def sample(self, texc, texc_deriv, filter_mode='linear-mipmap-linear'):\n def getRes(self):\n def getChannels(self):\n def getMips(self):\n def clamp_(self):\n def normalize_(self):\ndef create_trainable(init, res=None, auto_mipmaps=True, min_max=None):\ndef srgb_to_rgb(texture):\ndef rgb_to_srgb(texture):\ndef _load_mip2D(fn, lambda_fn=None, channels=None):\ndef load_texture2D(fn, lambda_fn=None, channels=None):\ndef _save_mip2D(fn, mip, mipidx, lambda_fn):\ndef save_texture2D(fn, tex, lambda_fn=None):" }, { "identifier": "mlptexture", "path": "render/mlptexture.py", "snippet": "class _MLP(torch.nn.Module):\nclass MLPTexture3D(torch.nn.Module):\n def __init__(self, cfg, loss_scale=1.0):\n def forward(self, x):\n def _init_weights(m):\n def __init__(self, AABB, channels = 3, internal_dims = 32, hidden = 1, min_max = None):\n def sample(self, texc):\n def clamp_(self):\n def cleanup(self):" }, { "identifier": "light", "path": "render/light.py", "snippet": "class cubemap_mip(torch.autograd.Function):\nclass EnvironmentLight(torch.nn.Module):\n def forward(ctx, cubemap):\n def backward(ctx, dout):\n def __init__(self, base):\n def xfm(self, mtx):\n def clone(self):\n def clamp_(self, min=None, max=None):\n def get_mip(self, roughness):\n def build_mips(self, cutoff=0.99):\n def regularizer(self):\n def shade(self, gb_pos, gb_normal, kd, ks, view_pos, specular=True):\ndef _load_env_hdr(fn, scale=1.0):\ndef load_env(fn, scale=1.0):\ndef save_env_map(fn, light):\ndef create_trainable_env_rnd(base_res, scale=0.5, bias=0.25):\n LIGHT_MIN_RES = 16\n MIN_ROUGHNESS = 0.08\n MAX_ROUGHNESS = 0.5" }, { "identifier": "render", "path": "render/render.py", "snippet": "def interpolate(attr, rast, attr_idx, rast_db=None):\ndef shade(\n gb_pos,\n gb_geometric_normal,\n gb_normal,\n gb_tangent,\n gb_texc,\n gb_texc_deriv,\n view_pos,\n lgt,\n material,\n bsdf,\n if_normal,\n normal_rotate,\n mode,\n if_flip_the_normal,\n if_use_bump\n ):\ndef render_layer(\n rast,\n rast_deriv,\n mesh,\n view_pos,\n lgt,\n resolution,\n spp,\n msaa,\n bsdf,\n if_normal,\n normal_rotate,\n mode,\n if_flip_the_normal,\n if_use_bump\n ):\ndef render_mesh(\n ctx,\n mesh,\n mtx_in,\n view_pos,\n lgt,\n resolution,\n spp = 1,\n num_layers = 1,\n msaa = False,\n background = None, \n bsdf = None,\n if_normal = False,\n normal_rotate = None,\n mode = 'geometry_modeling',\n if_flip_the_normal = False,\n if_use_bump = False\n ):\n def prepare_input_vector(x):\n def composite_buffer(key, layers, background, antialias):\ndef render_uv(ctx, mesh, resolution, mlp_texture):\ndef uv_padding(image, hole_mask, padding = 2, uv_padding_block = 4):\ndef render_uv1(ctx, mesh, resolution, mlp_texture, uv_padding_block):" }, { "identifier": "StableDiffusion", "path": "sd_cglora.py", "snippet": "class StableDiffusion(nn.Module):\n def __init__(self, \n device, \n mode='geometry', \n text= '', \n add_directional_text= False, \n batch = 1, \n guidance_weight = 100, \n sds_weight_strategy = 0,\n early_time_step_range = [0.02, 0.5],\n late_time_step_range = [0.02, 0.5]):\n super().__init__()\n\n self.device = device\n self.mode = mode\n self.text= text\n self.add_directional_text = add_directional_text\n self.batch = batch \n print(f'[INFO] loading stable diffusion...')\n model_key = \"stabilityai/stable-diffusion-2-1-base\"\n self.vae = AutoencoderKL.from_pretrained(model_key, subfolder=\"vae\",torch_dtype=torch.float16).to(self.device)\n self.tokenizer = CLIPTokenizer.from_pretrained(model_key, subfolder=\"tokenizer\",torch_dtype=torch.float16)\n self.text_encoder = CLIPTextModel.from_pretrained(model_key, subfolder=\"text_encoder\",torch_dtype=torch.float16).to(self.device)\n self.unet = UNet2DConditionModel.from_pretrained(model_key, subfolder=\"unet\",torch_dtype=torch.float16).to(self.device)\n if is_xformers_available():\n self.unet.enable_xformers_memory_efficient_attention()\n self.negative_text = ''\n if add_directional_text:\n self.text_z = []\n self.uncond_z = []\n self.index = []\n self.uncond_index = []\n for d in ['front', 'side', 'back', 'side']:\n text = f\"{self.text}, {d} view\"\n # text = f\"{d} view of {self.text}\"\n negative_text = f\"{self.negative_text}\"\n # if d == 'back': negative_text += \"face\"\n text_z, index = self.get_text_embeds([text], batch = 1)\n uncond_z, uncond_index =self.get_uncond_embeds([negative_text], batch = 1)\n self.text_z.append(text_z)\n self.uncond_z.append(uncond_z)\n self.index.append(index)\n self.uncond_index.append(uncond_index)\n self.text_z = torch.cat(self.text_z)\n self.uncond_z = torch.cat(self.uncond_z)\n self.index = torch.cat(self.index)\n self.uncond_index = torch.cat(self.uncond_index)\n else: \n self.text_z, self.index = self.get_text_embeds([self.text], batch = self.batch)\n self.uncond_z =self.get_uncond_embeds([self.negative_text], batch = self.batch)\n # del self.text_encoder\n self.scheduler = DPMSolverMultistepScheduler.from_pretrained(model_key, subfolder=\"scheduler\", torch_dtype=torch.float16)\n self.num_train_timesteps = self.scheduler.config.num_train_timesteps\n self.min_step_early = int(self.num_train_timesteps * early_time_step_range[0])\n self.max_step_early = int(self.num_train_timesteps * early_time_step_range[1])\n self.min_step_late = int(self.num_train_timesteps * late_time_step_range[0])\n self.max_step_late = int(self.num_train_timesteps * late_time_step_range[1])\n self.alphas = self.scheduler.alphas_cumprod.to(self.device) # for convenience\n self.guidance_weight = guidance_weight\n self.sds_weight_strategy = sds_weight_strategy\n print(f'[INFO] loaded stable diffusion!')\n\n for p in self.parameters():\n p.requires_grad_(False)\n self.unet_lora_params, self.names = inject_trainable_cglora(self.unet) # This will\n\n\n def get_text_embeds_global(self, prompt, batch=1):\n text_input = self.tokenizer(prompt, padding='max_length', max_length=self.tokenizer.model_max_length, truncation=True, return_tensors='pt')\n with torch.no_grad():\n text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0]\n if batch > 1:\n text_embeddings = text_embeddings.repeat(batch, 1, 1)\n \n global_embedding = text_embeddings[:,text_input['input_ids'].argmax(dim=-1),:].squeeze()\n \n return global_embedding\n\n\n def get_text_embeds(self, prompt, batch=1):\n text_input = self.tokenizer(prompt, padding='max_length', max_length=self.tokenizer.model_max_length, truncation=True, return_tensors='pt')\n with torch.no_grad():\n text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0]\n if batch > 1:\n text_embeddings = text_embeddings.repeat(batch, 1, 1)\n ###################################################################\n index = text_input['input_ids'].argmax(dim=-1)\n #global_embedding = text_embeddings[:, index, :].squeeze()\n ##################################################################\n \n return text_embeddings, index\n \n def get_uncond_embeds(self, negative_prompt, batch):\n uncond_input = self.tokenizer(negative_prompt, padding='max_length', max_length=self.tokenizer.model_max_length, return_tensors='pt')\n with torch.no_grad():\n uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]\n \n if batch > 1:\n uncond_embeddings = uncond_embeddings.repeat(batch, 1, 1)\n ###################################################################\n index = uncond_input['input_ids'].argmax(dim=-1)\n # global_embedding = uncond_embeddings[:, index, :].squeeze()\n ##################################################################\n return uncond_embeddings,index\n\n def encode_imgs(self, imgs):\n # imgs: [B, 3, H, W]\n if self.mode == 'appearance_modeling':\n \n imgs = 2 * imgs - 1\n\n posterior = self.vae.encode(imgs).latent_dist\n latents = posterior.sample() * 0.18215\n\n return latents" }, { "identifier": "util", "path": "render/util.py", "snippet": "def dot(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:\ndef reflect(x: torch.Tensor, n: torch.Tensor) -> torch.Tensor:\ndef length(x: torch.Tensor, eps: float =1e-20) -> torch.Tensor:\ndef safe_normalize(x: torch.Tensor, eps: float =1e-20) -> torch.Tensor:\ndef to_hvec(x: torch.Tensor, w: float) -> torch.Tensor:\ndef _rgb_to_srgb(f: torch.Tensor) -> torch.Tensor:\ndef rgb_to_srgb(f: torch.Tensor) -> torch.Tensor:\ndef _srgb_to_rgb(f: torch.Tensor) -> torch.Tensor:\ndef srgb_to_rgb(f: torch.Tensor) -> torch.Tensor:\ndef reinhard(f: torch.Tensor) -> torch.Tensor:\ndef mse_to_psnr(mse):\ndef psnr_to_mse(psnr):\ndef get_miplevels(texture: np.ndarray) -> float:\ndef tex_2d(tex_map : torch.Tensor, coords : torch.Tensor, filter='nearest') -> torch.Tensor:\ndef cube_to_dir(s, x, y):\ndef latlong_to_cubemap(latlong_map, res):\ndef cubemap_to_latlong(cubemap, res):\ndef scale_img_hwc(x : torch.Tensor, size, mag='bilinear', min='area') -> torch.Tensor:\ndef scale_img_nhwc(x : torch.Tensor, size, mag='bilinear', min='area') -> torch.Tensor:\ndef avg_pool_nhwc(x : torch.Tensor, size) -> torch.Tensor:\ndef segment_sum(data: torch.Tensor, segment_ids: torch.Tensor) -> torch.Tensor:\ndef fovx_to_fovy(fovx, aspect):\ndef focal_length_to_fovy(focal_length, sensor_height):\ndef perspective(fovy=0.7854, aspect=1.0, n=0.1, f= 1000.0, device=None):\ndef perspective_offcenter(fovy, fraction, rx, ry, aspect=1.0, n=0.1, f=1000.0, device=None):\ndef translate(x, y, z, device=None):\ndef rotate_x(a, device=None):\ndef rotate_x_1(a, device=None):\ndef rotate_y(a, device=None):\ndef rotate_y_1(a, device=None):\ndef rotate_y_2(a, device=None):\ndef rotate_x_2(a, device=None):\ndef scale(s, device=None):\ndef lookAt(eye, at, up):\ndef random_rotation_translation(t, device=None):\ndef random_rotation(device=None):\ndef lines_focal(o, d):\ndef cosine_sample(N, size=None):\ndef bilinear_downsample(x : torch.tensor) -> torch.Tensor:\ndef bilinear_downsample(x : torch.tensor, spp) -> torch.Tensor:\ndef init_glfw():\ndef save_image(fn, x : np.ndarray):\ndef save_image_raw(fn, x : np.ndarray):\ndef load_image_raw(fn) -> np.ndarray:\ndef load_image(fn) -> np.ndarray:\ndef time_to_text(x):\ndef checkerboard(res, checker_size) -> np.ndarray:\ndef get_random_bg(h, w):\n R, L = aspect*y, -aspect*y\n T, B = y, -y\n I = torch.eye(3, dtype=o.dtype, device=o.device)\n S = torch.sum(d[..., None] @ torch.transpose(d[..., None], 1, 2) - I[None, ...], dim=0)\n C = torch.sum((d[..., None] @ torch.transpose(d[..., None], 1, 2) - I[None, ...]) @ o[..., None], dim=0).squeeze(1)\n N = N/torch.linalg.norm(N)" }, { "identifier": "Video", "path": "render/video.py", "snippet": "class Video():\n def __init__(self, path, name='video_log.mp4', mode='I', fps=30, codec='libx264', bitrate='16M') -> None:\n \n if path[-1] != \"/\":\n path += \"/\"\n \n self.writer = imageio.get_writer(path+name, mode=mode, fps=fps, codec=codec, bitrate=bitrate)\n \n def ready_image(self, image, write_video=True):\n # assuming channels last - as renderer returns it\n if len(image.shape) == 4: \n image = image.squeeze(0)[..., :3].detach().cpu().numpy()\n else:\n image = image[..., :3].detach().cpu().numpy()\n\n image = np.clip(np.rint(image*255.0), 0, 255).astype(np.uint8)\n\n if write_video:\n self.writer.append_data(image)\n\n return image\n\n def close(self):\n self.writer.close()" } ]
import os import time import argparse import json import math import numpy as np import torch import nvdiffrast.torch as dr import itertools import xatlas import open3d as o3d import random import imageio import os.path as osp import pickle from dataset.dataset_mesh import DatasetMesh from dataset.dataset_mesh import get_camera_params from geometry.dmtet_x_dreamer import DMTetGeometry from geometry.dlmesh_x_dreamer import DLMesh from render import obj from render import material from render import util from render import mesh from render import texture from render import mlptexture from render import light from render import render from sd_cglora import StableDiffusion from tqdm import tqdm from render import util from render.video import Video
15,000
# Mix validation background target = prepare_batch(target, 'white') result_image, result_dict = validate_itr(glctx, target, geometry, opt_material, lgt, FLAGS, relight) for k in result_dict.keys(): np_img = result_dict[k].detach().cpu().numpy() if k == 'shaded': util.save_image(shaded_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) elif k == 'relight': util.save_image(relight_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) elif k == 'kd': util.save_image(kd_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) elif k == 'ks': util.save_image(ks_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) elif k == 'normal': util.save_image(normal_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) elif k == 'mask': util.save_image(mask_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) if 'shaded' in result_dict.keys(): save_gif(shaded_dir,30) if 'relight' in result_dict.keys(): save_gif(relight_dir,30) if 'kd' in result_dict.keys(): save_gif(kd_dir,30) if 'ks' in result_dict.keys(): save_gif(ks_dir,30) if 'normal' in result_dict.keys(): save_gif(normal_dir,30) return 0 ############################################################################### # Main shape fitter function / optimization loop ############################################################################### class Trainer(torch.nn.Module): def __init__(self, glctx, geometry, lgt, mat, optimize_geometry, optimize_light, FLAGS, guidance): super(Trainer, self).__init__() self.glctx = glctx self.geometry = geometry self.light = lgt self.material = mat self.optimize_geometry = optimize_geometry self.optimize_light = optimize_light self.FLAGS = FLAGS self.guidance = guidance self.if_flip_the_normal = FLAGS.if_flip_the_normal self.if_use_bump = FLAGS.if_use_bump if self.FLAGS.mode == 'appearance_modeling': if not self.optimize_light: with torch.no_grad(): self.light.build_mips() self.params = list(self.material.parameters()) self.params += list(self.geometry.pos_encoder.parameters()) self.params += list(self.light.parameters()) if optimize_light else [] self.geo_params = list(self.geometry.parameters()) if optimize_geometry else [] def forward(self, target, it, if_normal, if_pretrain, scene_and_vertices ): if self.FLAGS.mode == 'appearance_modeling': if self.optimize_light: self.light.build_mips() if self.FLAGS.camera_space_light: self.light.xfm(target['mv']) if if_pretrain: return self.geometry.decoder.pre_train_ellipsoid(it, scene_and_vertices) else: return self.geometry.tick(glctx, target, self.light, self.material, it , if_normal, self.guidance, self.FLAGS.mode, self.if_flip_the_normal, self.if_use_bump) def optimize_mesh( glctx, geometry, opt_material, lgt, dataset_train, dataset_validate, FLAGS, log_interval=10, optimize_light=True, optimize_geometry=True, guidance = None, scene_and_vertices = None, ): dataloader_train = torch.utils.data.DataLoader(dataset_train, batch_size=FLAGS.batch, collate_fn=dataset_train.collate, shuffle=False) dataloader_validate = torch.utils.data.DataLoader(dataset_validate, batch_size=1, collate_fn=dataset_train.collate) model = Trainer(glctx, geometry, lgt, opt_material, optimize_geometry, optimize_light, FLAGS, guidance) if optimize_geometry: optimizer_mesh = torch.optim.AdamW(model.geo_params, lr=0.001, betas=(0.9, 0.99), eps=1e-15) optimizer = torch.optim.AdamW(model.params, lr=0.01, betas=(0.9, 0.99), eps=1e-15) optimizer_lora = torch.optim.SGD(itertools.chain(*guidance.unet_lora_params), lr=1e-5) if FLAGS.multi_gpu: model = model.cuda() model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[FLAGS.local_rank], find_unused_parameters= True ) img_cnt = 0 img_loss_vec = [] reg_loss_vec = [] iter_dur_vec = [] def cycle(iterable): iterator = iter(iterable) while True: try: yield next(iterator) except StopIteration: iterator = iter(iterable) v_it = cycle(dataloader_validate) scaler = torch.cuda.amp.GradScaler(enabled=True) rot_ang = 0 if FLAGS.local_rank == 0:
############################################################################### # Mix background into a dataset image ############################################################################### @torch.no_grad() def prepare_batch(target, background= 'black'): target['mv'] = target['mv'].cuda() target['mvp'] = target['mvp'].cuda() target['campos'] = target['campos'].cuda() target['fov'] = target['fov'].cuda() target['normal_rotate'] = target['normal_rotate'].cuda() batch_size = target['mv'].shape[0] resolution = target['resolution'] if background == 'white': target['background']= torch.ones(batch_size, resolution[0], resolution[1], 3, dtype=torch.float32, device='cuda') if background == 'black': target['background'] = torch.zeros(batch_size, resolution[0], resolution[1], 3, dtype=torch.float32, device='cuda') return target ############################################################################### # UV - map geometry & convert to a mesh ############################################################################### @torch.no_grad() def xatlas_uvmap(glctx, geometry, mat, FLAGS): eval_mesh = geometry.getMesh(mat) # Create uvs with xatlas v_pos = eval_mesh.v_pos.detach().cpu().numpy() t_pos_idx = eval_mesh.t_pos_idx.detach().cpu().numpy() vmapping, indices, uvs = xatlas.parametrize(v_pos, t_pos_idx) # Convert to tensors indices_int64 = indices.astype(np.uint64, casting='same_kind').view(np.int64) uvs = torch.tensor(uvs, dtype=torch.float32, device='cuda') faces = torch.tensor(indices_int64, dtype=torch.int64, device='cuda') new_mesh = mesh.Mesh(v_tex=uvs, t_tex_idx=faces, base=eval_mesh) mask, kd, ks, normal = render.render_uv(glctx, new_mesh, FLAGS.texture_res, eval_mesh.material['kd_ks_normal']) if FLAGS.layers > 1: kd = torch.cat((kd, torch.rand_like(kd[...,0:1])), dim=-1) kd_min, kd_max = torch.tensor(FLAGS.kd_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.kd_max, dtype=torch.float32, device='cuda') ks_min, ks_max = torch.tensor(FLAGS.ks_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.ks_max, dtype=torch.float32, device='cuda') nrm_min, nrm_max = torch.tensor(FLAGS.nrm_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.nrm_max, dtype=torch.float32, device='cuda') new_mesh.material = material.Material({ 'bsdf' : mat['bsdf'], 'kd' : texture.Texture2D(kd, min_max=[kd_min, kd_max]), 'ks' : texture.Texture2D(ks, min_max=[ks_min, ks_max]), 'normal' : texture.Texture2D(normal, min_max=[nrm_min, nrm_max]) }) return new_mesh @torch.no_grad() def xatlas_uvmap1(glctx, geometry, mat, FLAGS): eval_mesh = geometry.getMesh(mat) new_mesh = mesh.Mesh( base=eval_mesh) mask, kd, ks, normal = render.render_uv1(glctx, new_mesh, FLAGS.texture_res, eval_mesh.material['kd_ks_normal'], FLAGS.uv_padding_block) if FLAGS.layers > 1: kd = torch.cat((kd, torch.rand_like(kd[...,0:1])), dim=-1) kd_min, kd_max = torch.tensor(FLAGS.kd_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.kd_max, dtype=torch.float32, device='cuda') ks_min, ks_max = torch.tensor(FLAGS.ks_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.ks_max, dtype=torch.float32, device='cuda') nrm_min, nrm_max = torch.tensor(FLAGS.nrm_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.nrm_max, dtype=torch.float32, device='cuda') new_mesh.material = material.Material({ 'bsdf' : mat['bsdf'], 'kd' : texture.Texture2D(kd, min_max=[kd_min, kd_max]), 'ks' : texture.Texture2D(ks, min_max=[ks_min, ks_max]), 'normal' : texture.Texture2D(normal, min_max=[nrm_min, nrm_max]) }) return new_mesh ############################################################################### # Utility functions for material ############################################################################### def get_normalize_mesh(pro_path): mesh = o3d.io.read_triangle_mesh(pro_path) vertices = np.asarray(mesh.vertices) shift = np.mean(vertices,axis=0) scale = np.max(np.linalg.norm(vertices-shift, ord=2, axis=1)) vertices = (vertices-shift) / scale mesh.vertices = o3d.cuda.pybind.utility.Vector3dVector(vertices) return mesh def initial_guness_material(geometry, mlp, FLAGS, init_mat=None): # ipdb.set_trace(()) kd_min, kd_max = torch.tensor(FLAGS.kd_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.kd_max, dtype=torch.float32, device='cuda') ks_min, ks_max = torch.tensor(FLAGS.ks_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.ks_max, dtype=torch.float32, device='cuda') nrm_min, nrm_max = torch.tensor(FLAGS.nrm_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.nrm_max, dtype=torch.float32, device='cuda') if mlp: mlp_min = torch.cat((kd_min[0:3], ks_min, nrm_min), dim=0) mlp_max = torch.cat((kd_max[0:3], ks_max, nrm_max), dim=0) mlp_map_opt = mlptexture.MLPTexture3D(geometry.getAABB(), channels=9, min_max=[mlp_min, mlp_max]) mat = material.Material({'kd_ks_normal' : mlp_map_opt}) else: # Setup Kd (albedo) and Ks (x, roughness, metalness) textures if FLAGS.random_textures or init_mat is None: num_channels = 4 if FLAGS.layers > 1 else 3 kd_init = torch.rand(size=FLAGS.texture_res + [num_channels], device='cuda') * (kd_max - kd_min)[None, None, 0:num_channels] + kd_min[None, None, 0:num_channels] kd_map_opt = texture.create_trainable(kd_init , FLAGS.texture_res, not FLAGS.custom_mip, [kd_min, kd_max]) ksR = np.random.uniform(size=FLAGS.texture_res + [1], low=0.0, high=0.01) ksG = np.random.uniform(size=FLAGS.texture_res + [1], low=ks_min[1].cpu(), high=ks_max[1].cpu()) ksB = np.random.uniform(size=FLAGS.texture_res + [1], low=ks_min[2].cpu(), high=ks_max[2].cpu()) ks_map_opt = texture.create_trainable(np.concatenate((ksR, ksG, ksB), axis=2), FLAGS.texture_res, not FLAGS.custom_mip, [ks_min, ks_max]) else: kd_map_opt = texture.create_trainable(init_mat['kd'], FLAGS.texture_res, not FLAGS.custom_mip, [kd_min, kd_max]) ks_map_opt = texture.create_trainable(init_mat['ks'], FLAGS.texture_res, not FLAGS.custom_mip, [ks_min, ks_max]) # Setup normal map if FLAGS.random_textures or init_mat is None or 'normal' not in init_mat: normal_map_opt = texture.create_trainable(np.array([0, 0, 1]), FLAGS.texture_res, not FLAGS.custom_mip, [nrm_min, nrm_max]) else: normal_map_opt = texture.create_trainable(init_mat['normal'], FLAGS.texture_res, not FLAGS.custom_mip, [nrm_min, nrm_max]) mat = material.Material({ 'kd' : kd_map_opt, 'ks' : ks_map_opt, 'normal' : normal_map_opt }) if init_mat is not None: mat['bsdf'] = init_mat['bsdf'] else: mat['bsdf'] = 'pbr' return mat ############################################################################### # Validation & testing ############################################################################### # @torch.no_grad() def validate_itr(glctx, target, geometry, opt_material, lgt, FLAGS, relight = None): result_dict = {} with torch.no_grad(): if FLAGS.mode == 'appearance_modeling': with torch.no_grad(): lgt.build_mips() if FLAGS.camera_space_light: lgt.xfm(target['mv']) if relight != None: relight.build_mips() buffers = geometry.render(glctx, target, lgt, opt_material, if_use_bump = FLAGS.if_use_bump) result_dict['shaded'] = buffers['shaded'][0, ..., 0:3] result_dict['shaded'] = util.rgb_to_srgb(result_dict['shaded']) if relight != None: result_dict['relight'] = geometry.render(glctx, target, relight, opt_material, if_use_bump = FLAGS.if_use_bump)['shaded'][0, ..., 0:3] result_dict['relight'] = util.rgb_to_srgb(result_dict['relight']) result_dict['mask'] = (buffers['shaded'][0, ..., 3:4]) result_image = result_dict['shaded'] if FLAGS.display is not None : # white_bg = torch.ones_like(target['background']) for layer in FLAGS.display: if 'latlong' in layer and layer['latlong']: if isinstance(lgt, light.EnvironmentLight): result_dict['light_image'] = util.cubemap_to_latlong(lgt.base, FLAGS.display_res) result_image = torch.cat([result_image, result_dict['light_image']], axis=1) elif 'bsdf' in layer: buffers = geometry.render(glctx, target, lgt, opt_material, bsdf=layer['bsdf'], if_use_bump = FLAGS.if_use_bump) if layer['bsdf'] == 'kd': result_dict[layer['bsdf']] = util.rgb_to_srgb(buffers['shaded'][0, ..., 0:3]) elif layer['bsdf'] == 'normal': result_dict[layer['bsdf']] = (buffers['shaded'][0, ..., 0:3] + 1) * 0.5 else: result_dict[layer['bsdf']] = buffers['shaded'][0, ..., 0:3] result_image = torch.cat([result_image, result_dict[layer['bsdf']]], axis=1) return result_image, result_dict def save_gif(dir,fps): imgpath = dir frames = [] for idx in sorted(os.listdir(imgpath)): img = osp.join(imgpath,idx) frames.append(imageio.imread(img)) imageio.mimsave(os.path.join(dir, 'eval.gif'),frames,'GIF',duration=1/fps,loop=0) @torch.no_grad() def validate(glctx, geometry, opt_material, lgt, dataset_validate, out_dir, FLAGS, relight= None): # ============================================================================================== # Validation loop # ============================================================================================== mse_values = [] psnr_values = [] dataloader_validate = torch.utils.data.DataLoader(dataset_validate, batch_size=1, collate_fn=dataset_validate.collate) os.makedirs(out_dir, exist_ok=True) shaded_dir = os.path.join(out_dir, "shaded") relight_dir = os.path.join(out_dir, "relight") kd_dir = os.path.join(out_dir, "kd") ks_dir = os.path.join(out_dir, "ks") normal_dir = os.path.join(out_dir, "normal") mask_dir = os.path.join(out_dir, "mask") os.makedirs(shaded_dir, exist_ok=True) os.makedirs(relight_dir, exist_ok=True) os.makedirs(kd_dir, exist_ok=True) os.makedirs(ks_dir, exist_ok=True) os.makedirs(normal_dir, exist_ok=True) os.makedirs(mask_dir, exist_ok=True) print("Running validation") dataloader_validate = tqdm(dataloader_validate) for it, target in enumerate(dataloader_validate): # Mix validation background target = prepare_batch(target, 'white') result_image, result_dict = validate_itr(glctx, target, geometry, opt_material, lgt, FLAGS, relight) for k in result_dict.keys(): np_img = result_dict[k].detach().cpu().numpy() if k == 'shaded': util.save_image(shaded_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) elif k == 'relight': util.save_image(relight_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) elif k == 'kd': util.save_image(kd_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) elif k == 'ks': util.save_image(ks_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) elif k == 'normal': util.save_image(normal_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) elif k == 'mask': util.save_image(mask_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) if 'shaded' in result_dict.keys(): save_gif(shaded_dir,30) if 'relight' in result_dict.keys(): save_gif(relight_dir,30) if 'kd' in result_dict.keys(): save_gif(kd_dir,30) if 'ks' in result_dict.keys(): save_gif(ks_dir,30) if 'normal' in result_dict.keys(): save_gif(normal_dir,30) return 0 ############################################################################### # Main shape fitter function / optimization loop ############################################################################### class Trainer(torch.nn.Module): def __init__(self, glctx, geometry, lgt, mat, optimize_geometry, optimize_light, FLAGS, guidance): super(Trainer, self).__init__() self.glctx = glctx self.geometry = geometry self.light = lgt self.material = mat self.optimize_geometry = optimize_geometry self.optimize_light = optimize_light self.FLAGS = FLAGS self.guidance = guidance self.if_flip_the_normal = FLAGS.if_flip_the_normal self.if_use_bump = FLAGS.if_use_bump if self.FLAGS.mode == 'appearance_modeling': if not self.optimize_light: with torch.no_grad(): self.light.build_mips() self.params = list(self.material.parameters()) self.params += list(self.geometry.pos_encoder.parameters()) self.params += list(self.light.parameters()) if optimize_light else [] self.geo_params = list(self.geometry.parameters()) if optimize_geometry else [] def forward(self, target, it, if_normal, if_pretrain, scene_and_vertices ): if self.FLAGS.mode == 'appearance_modeling': if self.optimize_light: self.light.build_mips() if self.FLAGS.camera_space_light: self.light.xfm(target['mv']) if if_pretrain: return self.geometry.decoder.pre_train_ellipsoid(it, scene_and_vertices) else: return self.geometry.tick(glctx, target, self.light, self.material, it , if_normal, self.guidance, self.FLAGS.mode, self.if_flip_the_normal, self.if_use_bump) def optimize_mesh( glctx, geometry, opt_material, lgt, dataset_train, dataset_validate, FLAGS, log_interval=10, optimize_light=True, optimize_geometry=True, guidance = None, scene_and_vertices = None, ): dataloader_train = torch.utils.data.DataLoader(dataset_train, batch_size=FLAGS.batch, collate_fn=dataset_train.collate, shuffle=False) dataloader_validate = torch.utils.data.DataLoader(dataset_validate, batch_size=1, collate_fn=dataset_train.collate) model = Trainer(glctx, geometry, lgt, opt_material, optimize_geometry, optimize_light, FLAGS, guidance) if optimize_geometry: optimizer_mesh = torch.optim.AdamW(model.geo_params, lr=0.001, betas=(0.9, 0.99), eps=1e-15) optimizer = torch.optim.AdamW(model.params, lr=0.01, betas=(0.9, 0.99), eps=1e-15) optimizer_lora = torch.optim.SGD(itertools.chain(*guidance.unet_lora_params), lr=1e-5) if FLAGS.multi_gpu: model = model.cuda() model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[FLAGS.local_rank], find_unused_parameters= True ) img_cnt = 0 img_loss_vec = [] reg_loss_vec = [] iter_dur_vec = [] def cycle(iterable): iterator = iter(iterable) while True: try: yield next(iterator) except StopIteration: iterator = iter(iterable) v_it = cycle(dataloader_validate) scaler = torch.cuda.amp.GradScaler(enabled=True) rot_ang = 0 if FLAGS.local_rank == 0:
video = Video(FLAGS.out_dir)
14
2023-11-27 13:44:01+00:00
24k
camenduru/magicanimate-hf
magicanimate/pipelines/pipeline_animation.py
[ { "identifier": "UNet3DConditionModel", "path": "magicanimate/models/unet_controlnet.py", "snippet": "class UNet3DConditionModel(ModelMixin, ConfigMixin):\n _supports_gradient_checkpointing = True\n\n @register_to_config\n def __init__(\n self,\n sample_size: Optional[int] = None,\n in_channels: int = 4,\n out_channels: int = 4,\n center_input_sample: bool = False,\n flip_sin_to_cos: bool = True,\n freq_shift: int = 0, \n down_block_types: Tuple[str] = (\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"DownBlock3D\",\n ),\n mid_block_type: str = \"UNetMidBlock3DCrossAttn\",\n up_block_types: Tuple[str] = (\n \"UpBlock3D\",\n \"CrossAttnUpBlock3D\",\n \"CrossAttnUpBlock3D\",\n \"CrossAttnUpBlock3D\"\n ),\n only_cross_attention: Union[bool, Tuple[bool]] = False,\n block_out_channels: Tuple[int] = (320, 640, 1280, 1280),\n layers_per_block: int = 2,\n downsample_padding: int = 1,\n mid_block_scale_factor: float = 1,\n act_fn: str = \"silu\",\n norm_num_groups: int = 32,\n norm_eps: float = 1e-5,\n cross_attention_dim: int = 1280,\n attention_head_dim: Union[int, Tuple[int]] = 8,\n dual_cross_attention: bool = False,\n use_linear_projection: bool = False,\n class_embed_type: Optional[str] = None,\n num_class_embeds: Optional[int] = None,\n upcast_attention: bool = False,\n resnet_time_scale_shift: str = \"default\",\n \n # Additional\n use_motion_module = False,\n motion_module_resolutions = ( 1,2,4,8 ),\n motion_module_mid_block = False,\n motion_module_decoder_only = False,\n motion_module_type = None,\n motion_module_kwargs = {},\n unet_use_cross_frame_attention = None,\n unet_use_temporal_attention = None,\n ):\n super().__init__()\n\n self.sample_size = sample_size\n time_embed_dim = block_out_channels[0] * 4\n\n # input\n self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1))\n\n # time\n self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)\n timestep_input_dim = block_out_channels[0]\n\n self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n\n # class embedding\n if class_embed_type is None and num_class_embeds is not None:\n self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)\n elif class_embed_type == \"timestep\":\n self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n elif class_embed_type == \"identity\":\n self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)\n else:\n self.class_embedding = None\n\n self.down_blocks = nn.ModuleList([])\n self.mid_block = None\n self.up_blocks = nn.ModuleList([])\n\n if isinstance(only_cross_attention, bool):\n only_cross_attention = [only_cross_attention] * len(down_block_types)\n\n if isinstance(attention_head_dim, int):\n attention_head_dim = (attention_head_dim,) * len(down_block_types)\n\n # down\n output_channel = block_out_channels[0]\n for i, down_block_type in enumerate(down_block_types):\n res = 2 ** i\n input_channel = output_channel\n output_channel = block_out_channels[i]\n is_final_block = i == len(block_out_channels) - 1\n\n down_block = get_down_block(\n down_block_type,\n num_layers=layers_per_block,\n in_channels=input_channel,\n out_channels=output_channel,\n temb_channels=time_embed_dim,\n add_downsample=not is_final_block,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[i],\n downsample_padding=downsample_padding,\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n\n unet_use_cross_frame_attention=unet_use_cross_frame_attention,\n unet_use_temporal_attention=unet_use_temporal_attention,\n \n use_motion_module=use_motion_module and (res in motion_module_resolutions) and (not motion_module_decoder_only),\n motion_module_type=motion_module_type,\n motion_module_kwargs=motion_module_kwargs,\n )\n self.down_blocks.append(down_block)\n\n # mid\n if mid_block_type == \"UNetMidBlock3DCrossAttn\":\n self.mid_block = UNetMidBlock3DCrossAttn(\n in_channels=block_out_channels[-1],\n temb_channels=time_embed_dim,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n output_scale_factor=mid_block_scale_factor,\n resnet_time_scale_shift=resnet_time_scale_shift,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[-1],\n resnet_groups=norm_num_groups,\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n upcast_attention=upcast_attention,\n\n unet_use_cross_frame_attention=unet_use_cross_frame_attention,\n unet_use_temporal_attention=unet_use_temporal_attention,\n \n use_motion_module=use_motion_module and motion_module_mid_block,\n motion_module_type=motion_module_type,\n motion_module_kwargs=motion_module_kwargs,\n )\n else:\n raise ValueError(f\"unknown mid_block_type : {mid_block_type}\")\n \n # count how many layers upsample the videos\n self.num_upsamplers = 0\n\n # up\n reversed_block_out_channels = list(reversed(block_out_channels))\n reversed_attention_head_dim = list(reversed(attention_head_dim))\n only_cross_attention = list(reversed(only_cross_attention))\n output_channel = reversed_block_out_channels[0]\n for i, up_block_type in enumerate(up_block_types):\n res = 2 ** (3 - i)\n is_final_block = i == len(block_out_channels) - 1\n\n prev_output_channel = output_channel\n output_channel = reversed_block_out_channels[i]\n input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]\n\n # add upsample block for all BUT final layer\n if not is_final_block:\n add_upsample = True\n self.num_upsamplers += 1\n else:\n add_upsample = False\n\n up_block = get_up_block(\n up_block_type,\n num_layers=layers_per_block + 1,\n in_channels=input_channel,\n out_channels=output_channel,\n prev_output_channel=prev_output_channel,\n temb_channels=time_embed_dim,\n add_upsample=add_upsample,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=reversed_attention_head_dim[i],\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n\n unet_use_cross_frame_attention=unet_use_cross_frame_attention,\n unet_use_temporal_attention=unet_use_temporal_attention,\n\n use_motion_module=use_motion_module and (res in motion_module_resolutions),\n motion_module_type=motion_module_type,\n motion_module_kwargs=motion_module_kwargs,\n )\n self.up_blocks.append(up_block)\n prev_output_channel = output_channel\n\n # out\n self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps)\n self.conv_act = nn.SiLU()\n self.conv_out = InflatedConv3d(block_out_channels[0], out_channels, kernel_size=3, padding=1)\n\n def set_attention_slice(self, slice_size):\n r\"\"\"\n Enable sliced attention computation.\n\n When this option is enabled, the attention module will split the input tensor in slices, to compute attention\n in several steps. This is useful to save some memory in exchange for a small speed decrease.\n\n Args:\n slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `\"auto\"`):\n When `\"auto\"`, halves the input to the attention heads, so attention will be computed in two steps. If\n `\"max\"`, maxium amount of memory will be saved by running only one slice at a time. If a number is\n provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`\n must be a multiple of `slice_size`.\n \"\"\"\n sliceable_head_dims = []\n\n def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):\n if hasattr(module, \"set_attention_slice\"):\n sliceable_head_dims.append(module.sliceable_head_dim)\n\n for child in module.children():\n fn_recursive_retrieve_slicable_dims(child)\n\n # retrieve number of attention layers\n for module in self.children():\n fn_recursive_retrieve_slicable_dims(module)\n\n num_slicable_layers = len(sliceable_head_dims)\n\n if slice_size == \"auto\":\n # half the attention head size is usually a good trade-off between\n # speed and memory\n slice_size = [dim // 2 for dim in sliceable_head_dims]\n elif slice_size == \"max\":\n # make smallest slice possible\n slice_size = num_slicable_layers * [1]\n\n slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size\n\n if len(slice_size) != len(sliceable_head_dims):\n raise ValueError(\n f\"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different\"\n f\" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}.\"\n )\n\n for i in range(len(slice_size)):\n size = slice_size[i]\n dim = sliceable_head_dims[i]\n if size is not None and size > dim:\n raise ValueError(f\"size {size} has to be smaller or equal to {dim}.\")\n\n # Recursively walk through all the children.\n # Any children which exposes the set_attention_slice method\n # gets the message\n def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):\n if hasattr(module, \"set_attention_slice\"):\n module.set_attention_slice(slice_size.pop())\n\n for child in module.children():\n fn_recursive_set_attention_slice(child, slice_size)\n\n reversed_slice_size = list(reversed(slice_size))\n for module in self.children():\n fn_recursive_set_attention_slice(module, reversed_slice_size)\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D)):\n module.gradient_checkpointing = value\n\n def forward(\n self,\n sample: torch.FloatTensor,\n timestep: Union[torch.Tensor, float, int],\n encoder_hidden_states: torch.Tensor,\n class_labels: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n # for controlnet\n down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,\n mid_block_additional_residual: Optional[torch.Tensor] = None,\n return_dict: bool = True,\n ) -> Union[UNet3DConditionOutput, Tuple]:\n r\"\"\"\n Args:\n sample (`torch.FloatTensor`): (batch, channel, height, width) noisy inputs tensor\n timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps\n encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states\n return_dict (`bool`, *optional*, defaults to `True`):\n Whether or not to return a [`models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain tuple.\n\n Returns:\n [`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:\n [`~models.unet_2d_condition.UNet2DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When\n returning a tuple, the first element is the sample tensor.\n \"\"\"\n # By default samples have to be AT least a multiple of the overall upsampling factor.\n # The overall upsampling factor is equal to 2 ** (# num of upsampling layears).\n # However, the upsampling interpolation output size can be forced to fit any upsampling size\n # on the fly if necessary.\n default_overall_up_factor = 2**self.num_upsamplers\n\n # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`\n forward_upsample_size = False\n upsample_size = None\n\n if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):\n logger.info(\"Forward upsample size to force interpolation output size.\")\n forward_upsample_size = True\n\n # prepare attention_mask\n if attention_mask is not None:\n attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0\n attention_mask = attention_mask.unsqueeze(1)\n\n # center input if necessary\n if self.config.center_input_sample:\n sample = 2 * sample - 1.0\n\n # time\n timesteps = timestep\n if not torch.is_tensor(timesteps):\n # This would be a good case for the `match` statement (Python 3.10+)\n is_mps = sample.device.type == \"mps\"\n if isinstance(timestep, float):\n dtype = torch.float32 if is_mps else torch.float64\n else:\n dtype = torch.int32 if is_mps else torch.int64\n timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)\n elif len(timesteps.shape) == 0:\n timesteps = timesteps[None].to(sample.device)\n\n # broadcast to batch dimension in a way that's compatible with ONNX/Core ML\n timesteps = timesteps.expand(sample.shape[0])\n\n t_emb = self.time_proj(timesteps)\n\n # timesteps does not contain any weights and will always return f32 tensors\n # but time_embedding might actually be running in fp16. so we need to cast here.\n # there might be better ways to encapsulate this.\n t_emb = t_emb.to(dtype=self.dtype)\n emb = self.time_embedding(t_emb)\n\n if self.class_embedding is not None:\n if class_labels is None:\n raise ValueError(\"class_labels should be provided when num_class_embeds > 0\")\n\n if self.config.class_embed_type == \"timestep\":\n class_labels = self.time_proj(class_labels)\n\n class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)\n emb = emb + class_emb\n\n # pre-process\n sample = self.conv_in(sample)\n\n # down\n is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None\n\n down_block_res_samples = (sample,)\n for downsample_block in self.down_blocks:\n if hasattr(downsample_block, \"has_cross_attention\") and downsample_block.has_cross_attention:\n sample, res_samples = downsample_block(\n hidden_states=sample,\n temb=emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n )\n else:\n sample, res_samples = downsample_block(hidden_states=sample, temb=emb, encoder_hidden_states=encoder_hidden_states)\n\n down_block_res_samples += res_samples\n\n if is_controlnet:\n new_down_block_res_samples = ()\n\n for down_block_res_sample, down_block_additional_residual in zip(\n down_block_res_samples, down_block_additional_residuals\n ):\n down_block_res_sample = down_block_res_sample + down_block_additional_residual\n new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)\n\n down_block_res_samples = new_down_block_res_samples\n\n # mid\n sample = self.mid_block(\n sample, emb, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask\n )\n\n if is_controlnet:\n sample = sample + mid_block_additional_residual\n\n # up\n for i, upsample_block in enumerate(self.up_blocks):\n is_final_block = i == len(self.up_blocks) - 1\n\n res_samples = down_block_res_samples[-len(upsample_block.resnets) :]\n down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]\n\n # if we have not reached the final block and need to forward the\n # upsample size, we do it here\n if not is_final_block and forward_upsample_size:\n upsample_size = down_block_res_samples[-1].shape[2:]\n\n if hasattr(upsample_block, \"has_cross_attention\") and upsample_block.has_cross_attention:\n sample = upsample_block(\n hidden_states=sample,\n temb=emb,\n res_hidden_states_tuple=res_samples,\n encoder_hidden_states=encoder_hidden_states,\n upsample_size=upsample_size,\n attention_mask=attention_mask,\n )\n else:\n sample = upsample_block(\n hidden_states=sample, temb=emb, res_hidden_states_tuple=res_samples, upsample_size=upsample_size, encoder_hidden_states=encoder_hidden_states,\n )\n\n # post-process\n sample = self.conv_norm_out(sample)\n sample = self.conv_act(sample)\n sample = self.conv_out(sample)\n\n if not return_dict:\n return (sample,)\n\n return UNet3DConditionOutput(sample=sample)\n\n @classmethod\n def from_pretrained_2d(cls, pretrained_model_path, subfolder=None, unet_additional_kwargs=None):\n if subfolder is not None:\n pretrained_model_path = os.path.join(pretrained_model_path, subfolder)\n print(f\"loaded temporal unet's pretrained weights from {pretrained_model_path} ...\")\n\n config_file = os.path.join(pretrained_model_path, 'config.json')\n if not os.path.isfile(config_file):\n raise RuntimeError(f\"{config_file} does not exist\")\n with open(config_file, \"r\") as f:\n config = json.load(f)\n config[\"_class_name\"] = cls.__name__\n config[\"down_block_types\"] = [\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"DownBlock3D\"\n ]\n config[\"up_block_types\"] = [\n \"UpBlock3D\",\n \"CrossAttnUpBlock3D\",\n \"CrossAttnUpBlock3D\",\n \"CrossAttnUpBlock3D\"\n ]\n # config[\"mid_block_type\"] = \"UNetMidBlock3DCrossAttn\"\n\n from diffusers.utils import WEIGHTS_NAME\n model = cls.from_config(config, **unet_additional_kwargs)\n model_file = os.path.join(pretrained_model_path, WEIGHTS_NAME)\n if not os.path.isfile(model_file):\n raise RuntimeError(f\"{model_file} does not exist\")\n state_dict = torch.load(model_file, map_location=\"cpu\")\n\n m, u = model.load_state_dict(state_dict, strict=False)\n print(f\"### missing keys: {len(m)}; \\n### unexpected keys: {len(u)};\")\n # print(f\"### missing keys:\\n{m}\\n### unexpected keys:\\n{u}\\n\")\n \n params = [p.numel() if \"temporal\" in n else 0 for n, p in model.named_parameters()]\n print(f\"### Temporal Module Parameters: {sum(params) / 1e6} M\")\n \n return model" }, { "identifier": "ControlNetModel", "path": "magicanimate/models/controlnet.py", "snippet": "class ControlNetModel(ModelMixin, ConfigMixin):\n _supports_gradient_checkpointing = True\n\n @register_to_config\n def __init__(\n self,\n in_channels: int = 4,\n flip_sin_to_cos: bool = True,\n freq_shift: int = 0,\n down_block_types: Tuple[str] = (\n \"CrossAttnDownBlock2D\",\n \"CrossAttnDownBlock2D\",\n \"CrossAttnDownBlock2D\",\n \"DownBlock2D\",\n ),\n only_cross_attention: Union[bool, Tuple[bool]] = False,\n block_out_channels: Tuple[int] = (320, 640, 1280, 1280),\n layers_per_block: int = 2,\n downsample_padding: int = 1,\n mid_block_scale_factor: float = 1,\n act_fn: str = \"silu\",\n norm_num_groups: Optional[int] = 32,\n norm_eps: float = 1e-5,\n cross_attention_dim: int = 1280,\n attention_head_dim: Union[int, Tuple[int]] = 8,\n use_linear_projection: bool = False,\n class_embed_type: Optional[str] = None,\n num_class_embeds: Optional[int] = None,\n upcast_attention: bool = False,\n resnet_time_scale_shift: str = \"default\",\n projection_class_embeddings_input_dim: Optional[int] = None,\n controlnet_conditioning_channel_order: str = \"rgb\",\n conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),\n ):\n super().__init__()\n\n # Check inputs\n if len(block_out_channels) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}.\"\n )\n\n if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}.\"\n )\n\n if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}.\"\n )\n\n # input\n conv_in_kernel = 3\n conv_in_padding = (conv_in_kernel - 1) // 2\n self.conv_in = nn.Conv2d(\n in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding\n )\n\n # time\n time_embed_dim = block_out_channels[0] * 4\n\n self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)\n timestep_input_dim = block_out_channels[0]\n\n self.time_embedding = TimestepEmbedding(\n timestep_input_dim,\n time_embed_dim,\n act_fn=act_fn,\n )\n\n # class embedding\n if class_embed_type is None and num_class_embeds is not None:\n self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)\n elif class_embed_type == \"timestep\":\n self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n elif class_embed_type == \"identity\":\n self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)\n elif class_embed_type == \"projection\":\n if projection_class_embeddings_input_dim is None:\n raise ValueError(\n \"`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set\"\n )\n # The projection `class_embed_type` is the same as the timestep `class_embed_type` except\n # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings\n # 2. it projects from an arbitrary input dimension.\n #\n # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.\n # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.\n # As a result, `TimestepEmbedding` can be passed arbitrary vectors.\n self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)\n else:\n self.class_embedding = None\n\n # control net conditioning embedding\n self.controlnet_cond_embedding = ControlNetConditioningEmbedding(\n conditioning_embedding_channels=block_out_channels[0],\n block_out_channels=conditioning_embedding_out_channels,\n )\n\n self.down_blocks = nn.ModuleList([])\n self.controlnet_down_blocks = nn.ModuleList([])\n\n if isinstance(only_cross_attention, bool):\n only_cross_attention = [only_cross_attention] * len(down_block_types)\n\n if isinstance(attention_head_dim, int):\n attention_head_dim = (attention_head_dim,) * len(down_block_types)\n\n # down\n output_channel = block_out_channels[0]\n\n controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n for i, down_block_type in enumerate(down_block_types):\n input_channel = output_channel\n output_channel = block_out_channels[i]\n is_final_block = i == len(block_out_channels) - 1\n\n down_block = get_down_block(\n down_block_type,\n num_layers=layers_per_block,\n in_channels=input_channel,\n out_channels=output_channel,\n temb_channels=time_embed_dim,\n add_downsample=not is_final_block,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n num_attention_heads=attention_head_dim[i],\n downsample_padding=downsample_padding,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n )\n self.down_blocks.append(down_block)\n\n for _ in range(layers_per_block):\n controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n if not is_final_block:\n controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n # mid\n mid_block_channel = block_out_channels[-1]\n\n controlnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_mid_block = controlnet_block\n\n self.mid_block = UNetMidBlock2DCrossAttn(\n in_channels=mid_block_channel,\n temb_channels=time_embed_dim,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n output_scale_factor=mid_block_scale_factor,\n resnet_time_scale_shift=resnet_time_scale_shift,\n cross_attention_dim=cross_attention_dim,\n num_attention_heads=attention_head_dim[-1],\n resnet_groups=norm_num_groups,\n use_linear_projection=use_linear_projection,\n upcast_attention=upcast_attention,\n )\n\n @classmethod\n def from_unet(\n cls,\n unet: UNet2DConditionModel,\n controlnet_conditioning_channel_order: str = \"rgb\",\n conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),\n load_weights_from_unet: bool = True,\n ):\n r\"\"\"\n Instantiate Controlnet class from UNet2DConditionModel.\n\n Parameters:\n unet (`UNet2DConditionModel`):\n UNet model which weights are copied to the ControlNet. Note that all configuration options are also\n copied where applicable.\n \"\"\"\n controlnet = cls(\n in_channels=unet.config.in_channels,\n flip_sin_to_cos=unet.config.flip_sin_to_cos,\n freq_shift=unet.config.freq_shift,\n down_block_types=unet.config.down_block_types,\n only_cross_attention=unet.config.only_cross_attention,\n block_out_channels=unet.config.block_out_channels,\n layers_per_block=unet.config.layers_per_block,\n downsample_padding=unet.config.downsample_padding,\n mid_block_scale_factor=unet.config.mid_block_scale_factor,\n act_fn=unet.config.act_fn,\n norm_num_groups=unet.config.norm_num_groups,\n norm_eps=unet.config.norm_eps,\n cross_attention_dim=unet.config.cross_attention_dim,\n attention_head_dim=unet.config.attention_head_dim,\n use_linear_projection=unet.config.use_linear_projection,\n class_embed_type=unet.config.class_embed_type,\n num_class_embeds=unet.config.num_class_embeds,\n upcast_attention=unet.config.upcast_attention,\n resnet_time_scale_shift=unet.config.resnet_time_scale_shift,\n projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,\n controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,\n conditioning_embedding_out_channels=conditioning_embedding_out_channels,\n )\n\n if load_weights_from_unet:\n controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())\n controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())\n controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())\n\n if controlnet.class_embedding:\n controlnet.class_embedding.load_state_dict(unet.class_embedding.state_dict())\n\n controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict())\n controlnet.mid_block.load_state_dict(unet.mid_block.state_dict())\n\n return controlnet\n\n # @property\n # # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors\n # def attn_processors(self) -> Dict[str, AttentionProcessor]:\n # r\"\"\"\n # Returns:\n # `dict` of attention processors: A dictionary containing all attention processors used in the model with\n # indexed by its weight name.\n # \"\"\"\n # # set recursively\n # processors = {}\n\n # def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):\n # if hasattr(module, \"set_processor\"):\n # processors[f\"{name}.processor\"] = module.processor\n\n # for sub_name, child in module.named_children():\n # fn_recursive_add_processors(f\"{name}.{sub_name}\", child, processors)\n\n # return processors\n\n # for name, module in self.named_children():\n # fn_recursive_add_processors(name, module, processors)\n\n # return processors\n\n # # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor\n # def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):\n # r\"\"\"\n # Parameters:\n # `processor (`dict` of `AttentionProcessor` or `AttentionProcessor`):\n # The instantiated processor class or a dictionary of processor classes that will be set as the processor\n # of **all** `Attention` layers.\n # In case `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainable attention processors.:\n\n # \"\"\"\n # count = len(self.attn_processors.keys())\n\n # if isinstance(processor, dict) and len(processor) != count:\n # raise ValueError(\n # f\"A dict of processors was passed, but the number of processors {len(processor)} does not match the\"\n # f\" number of attention layers: {count}. Please make sure to pass {count} processor classes.\"\n # )\n\n # def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):\n # if hasattr(module, \"set_processor\"):\n # if not isinstance(processor, dict):\n # module.set_processor(processor)\n # else:\n # module.set_processor(processor.pop(f\"{name}.processor\"))\n\n # for sub_name, child in module.named_children():\n # fn_recursive_attn_processor(f\"{name}.{sub_name}\", child, processor)\n\n # for name, module in self.named_children():\n # fn_recursive_attn_processor(name, module, processor)\n\n # # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor\n # def set_default_attn_processor(self):\n # \"\"\"\n # Disables custom attention processors and sets the default attention implementation.\n # \"\"\"\n # self.set_attn_processor(AttnProcessor())\n\n # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attention_slice\n def set_attention_slice(self, slice_size):\n r\"\"\"\n Enable sliced attention computation.\n\n When this option is enabled, the attention module will split the input tensor in slices, to compute attention\n in several steps. This is useful to save some memory in exchange for a small speed decrease.\n\n Args:\n slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `\"auto\"`):\n When `\"auto\"`, halves the input to the attention heads, so attention will be computed in two steps. If\n `\"max\"`, maximum amount of memory will be saved by running only one slice at a time. If a number is\n provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`\n must be a multiple of `slice_size`.\n \"\"\"\n sliceable_head_dims = []\n\n def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):\n if hasattr(module, \"set_attention_slice\"):\n sliceable_head_dims.append(module.sliceable_head_dim)\n\n for child in module.children():\n fn_recursive_retrieve_sliceable_dims(child)\n\n # retrieve number of attention layers\n for module in self.children():\n fn_recursive_retrieve_sliceable_dims(module)\n\n num_sliceable_layers = len(sliceable_head_dims)\n\n if slice_size == \"auto\":\n # half the attention head size is usually a good trade-off between\n # speed and memory\n slice_size = [dim // 2 for dim in sliceable_head_dims]\n elif slice_size == \"max\":\n # make smallest slice possible\n slice_size = num_sliceable_layers * [1]\n\n slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size\n\n if len(slice_size) != len(sliceable_head_dims):\n raise ValueError(\n f\"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different\"\n f\" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}.\"\n )\n\n for i in range(len(slice_size)):\n size = slice_size[i]\n dim = sliceable_head_dims[i]\n if size is not None and size > dim:\n raise ValueError(f\"size {size} has to be smaller or equal to {dim}.\")\n\n # Recursively walk through all the children.\n # Any children which exposes the set_attention_slice method\n # gets the message\n def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):\n if hasattr(module, \"set_attention_slice\"):\n module.set_attention_slice(slice_size.pop())\n\n for child in module.children():\n fn_recursive_set_attention_slice(child, slice_size)\n\n reversed_slice_size = list(reversed(slice_size))\n for module in self.children():\n fn_recursive_set_attention_slice(module, reversed_slice_size)\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):\n module.gradient_checkpointing = value\n\n def forward(\n self,\n sample: torch.FloatTensor,\n timestep: Union[torch.Tensor, float, int],\n encoder_hidden_states: torch.Tensor,\n controlnet_cond: torch.FloatTensor,\n conditioning_scale: float = 1.0,\n class_labels: Optional[torch.Tensor] = None,\n timestep_cond: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n return_dict: bool = True,\n ) -> Union[ControlNetOutput, Tuple]:\n # check channel order\n channel_order = self.config.controlnet_conditioning_channel_order\n\n if channel_order == \"rgb\":\n # in rgb order by default\n ...\n elif channel_order == \"bgr\":\n controlnet_cond = torch.flip(controlnet_cond, dims=[1])\n else:\n raise ValueError(f\"unknown `controlnet_conditioning_channel_order`: {channel_order}\")\n\n # prepare attention_mask\n if attention_mask is not None:\n attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0\n attention_mask = attention_mask.unsqueeze(1)\n\n # 1. time\n timesteps = timestep\n if not torch.is_tensor(timesteps):\n # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can\n # This would be a good case for the `match` statement (Python 3.10+)\n is_mps = sample.device.type == \"mps\"\n if isinstance(timestep, float):\n dtype = torch.float32 if is_mps else torch.float64\n else:\n dtype = torch.int32 if is_mps else torch.int64\n timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)\n elif len(timesteps.shape) == 0:\n timesteps = timesteps[None].to(sample.device)\n\n # broadcast to batch dimension in a way that's compatible with ONNX/Core ML\n timesteps = timesteps.expand(sample.shape[0])\n\n t_emb = self.time_proj(timesteps)\n\n # timesteps does not contain any weights and will always return f32 tensors\n # but time_embedding might actually be running in fp16. so we need to cast here.\n # there might be better ways to encapsulate this.\n t_emb = t_emb.to(dtype=self.dtype)\n\n emb = self.time_embedding(t_emb, timestep_cond)\n\n if self.class_embedding is not None:\n if class_labels is None:\n raise ValueError(\"class_labels should be provided when num_class_embeds > 0\")\n\n if self.config.class_embed_type == \"timestep\":\n class_labels = self.time_proj(class_labels)\n\n class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)\n emb = emb + class_emb\n\n # 2. pre-process\n sample = self.conv_in(sample)\n\n controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)\n\n sample += controlnet_cond\n\n # 3. down\n down_block_res_samples = (sample,)\n for downsample_block in self.down_blocks:\n if hasattr(downsample_block, \"has_cross_attention\") and downsample_block.has_cross_attention:\n sample, res_samples = downsample_block(\n hidden_states=sample,\n temb=emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n # cross_attention_kwargs=cross_attention_kwargs,\n )\n else:\n sample, res_samples = downsample_block(hidden_states=sample, temb=emb)\n\n down_block_res_samples += res_samples\n\n # 4. mid\n if self.mid_block is not None:\n sample = self.mid_block(\n sample,\n emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n # cross_attention_kwargs=cross_attention_kwargs,\n )\n\n # 5. Control net blocks\n\n controlnet_down_block_res_samples = ()\n\n for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):\n down_block_res_sample = controlnet_block(down_block_res_sample)\n controlnet_down_block_res_samples += (down_block_res_sample,)\n\n down_block_res_samples = controlnet_down_block_res_samples\n\n mid_block_res_sample = self.controlnet_mid_block(sample)\n\n # 6. scaling\n down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]\n mid_block_res_sample *= conditioning_scale\n\n if not return_dict:\n return (down_block_res_samples, mid_block_res_sample)\n\n return ControlNetOutput(\n down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample\n )" }, { "identifier": "ReferenceAttentionControl", "path": "magicanimate/models/mutual_self_attention.py", "snippet": "class ReferenceAttentionControl():\n \n def __init__(self, \n unet,\n mode=\"write\",\n do_classifier_free_guidance=False,\n attention_auto_machine_weight = float('inf'),\n gn_auto_machine_weight = 1.0,\n style_fidelity = 1.0,\n reference_attn=True,\n reference_adain=False,\n fusion_blocks=\"midup\",\n batch_size=1, \n ) -> None:\n # 10. Modify self attention and group norm\n self.unet = unet\n assert mode in [\"read\", \"write\"]\n assert fusion_blocks in [\"midup\", \"full\"]\n self.reference_attn = reference_attn\n self.reference_adain = reference_adain\n self.fusion_blocks = fusion_blocks\n self.register_reference_hooks(\n mode, \n do_classifier_free_guidance,\n attention_auto_machine_weight,\n gn_auto_machine_weight,\n style_fidelity,\n reference_attn,\n reference_adain,\n fusion_blocks,\n batch_size=batch_size, \n )\n\n def register_reference_hooks(\n self, \n mode, \n do_classifier_free_guidance,\n attention_auto_machine_weight,\n gn_auto_machine_weight,\n style_fidelity,\n reference_attn,\n reference_adain,\n dtype=torch.float16,\n batch_size=1, \n num_images_per_prompt=1, \n device=torch.device(\"cpu\"), \n fusion_blocks='midup',\n ):\n MODE = mode\n do_classifier_free_guidance = do_classifier_free_guidance\n attention_auto_machine_weight = attention_auto_machine_weight\n gn_auto_machine_weight = gn_auto_machine_weight\n style_fidelity = style_fidelity\n reference_attn = reference_attn\n reference_adain = reference_adain\n fusion_blocks = fusion_blocks\n num_images_per_prompt = num_images_per_prompt\n dtype=dtype\n if do_classifier_free_guidance:\n uc_mask = (\n torch.Tensor([1] * batch_size * num_images_per_prompt * 16 + [0] * batch_size * num_images_per_prompt * 16)\n .to(device)\n .bool()\n )\n else:\n uc_mask = (\n torch.Tensor([0] * batch_size * num_images_per_prompt * 2)\n .to(device)\n .bool()\n )\n \n def hacked_basic_transformer_inner_forward(\n self,\n hidden_states: torch.FloatTensor,\n attention_mask: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n timestep: Optional[torch.LongTensor] = None,\n cross_attention_kwargs: Dict[str, Any] = None,\n class_labels: Optional[torch.LongTensor] = None,\n video_length=None,\n ):\n if self.use_ada_layer_norm:\n norm_hidden_states = self.norm1(hidden_states, timestep)\n elif self.use_ada_layer_norm_zero:\n norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(\n hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype\n )\n else:\n norm_hidden_states = self.norm1(hidden_states)\n\n # 1. Self-Attention\n cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}\n if self.only_cross_attention:\n attn_output = self.attn1(\n norm_hidden_states,\n encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,\n attention_mask=attention_mask,\n **cross_attention_kwargs,\n )\n else:\n if MODE == \"write\":\n self.bank.append(norm_hidden_states.clone())\n attn_output = self.attn1(\n norm_hidden_states,\n encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,\n attention_mask=attention_mask,\n **cross_attention_kwargs,\n )\n if MODE == \"read\":\n self.bank = [rearrange(d.unsqueeze(1).repeat(1, video_length, 1, 1), \"b t l c -> (b t) l c\")[:hidden_states.shape[0]] for d in self.bank]\n hidden_states_uc = self.attn1(norm_hidden_states, \n encoder_hidden_states=torch.cat([norm_hidden_states] + self.bank, dim=1),\n attention_mask=attention_mask) + hidden_states\n hidden_states_c = hidden_states_uc.clone()\n _uc_mask = uc_mask.clone()\n if do_classifier_free_guidance:\n if hidden_states.shape[0] != _uc_mask.shape[0]:\n _uc_mask = (\n torch.Tensor([1] * (hidden_states.shape[0]//2) + [0] * (hidden_states.shape[0]//2))\n .to(device)\n .bool()\n )\n hidden_states_c[_uc_mask] = self.attn1(\n norm_hidden_states[_uc_mask],\n encoder_hidden_states=norm_hidden_states[_uc_mask],\n attention_mask=attention_mask,\n ) + hidden_states[_uc_mask]\n hidden_states = hidden_states_c.clone()\n \n self.bank.clear()\n if self.attn2 is not None:\n # Cross-Attention\n norm_hidden_states = (\n self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)\n )\n hidden_states = (\n self.attn2(\n norm_hidden_states, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask\n )\n + hidden_states\n )\n\n # Feed-forward\n hidden_states = self.ff(self.norm3(hidden_states)) + hidden_states\n\n # Temporal-Attention\n if self.unet_use_temporal_attention:\n d = hidden_states.shape[1]\n hidden_states = rearrange(hidden_states, \"(b f) d c -> (b d) f c\", f=video_length)\n norm_hidden_states = (\n self.norm_temp(hidden_states, timestep) if self.use_ada_layer_norm else self.norm_temp(hidden_states)\n )\n hidden_states = self.attn_temp(norm_hidden_states) + hidden_states\n hidden_states = rearrange(hidden_states, \"(b d) f c -> (b f) d c\", d=d)\n\n return hidden_states\n \n if self.use_ada_layer_norm_zero:\n attn_output = gate_msa.unsqueeze(1) * attn_output\n hidden_states = attn_output + hidden_states\n\n if self.attn2 is not None:\n norm_hidden_states = (\n self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)\n )\n\n # 2. Cross-Attention\n attn_output = self.attn2(\n norm_hidden_states,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=encoder_attention_mask,\n **cross_attention_kwargs,\n )\n hidden_states = attn_output + hidden_states\n\n # 3. Feed-forward\n norm_hidden_states = self.norm3(hidden_states)\n\n if self.use_ada_layer_norm_zero:\n norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]\n\n ff_output = self.ff(norm_hidden_states)\n\n if self.use_ada_layer_norm_zero:\n ff_output = gate_mlp.unsqueeze(1) * ff_output\n\n hidden_states = ff_output + hidden_states\n\n return hidden_states\n\n def hacked_mid_forward(self, *args, **kwargs):\n eps = 1e-6\n x = self.original_forward(*args, **kwargs)\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append(mean)\n self.var_bank.append(var)\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank) / float(len(self.mean_bank))\n var_acc = sum(self.var_bank) / float(len(self.var_bank))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n x_uc = (((x - mean) / std) * std_acc) + mean_acc\n x_c = x_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n x_c[uc_mask] = x[uc_mask]\n x = style_fidelity * x_c + (1.0 - style_fidelity) * x_uc\n self.mean_bank = []\n self.var_bank = []\n return x\n\n def hack_CrossAttnDownBlock2D_forward(\n self,\n hidden_states: torch.FloatTensor,\n temb: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n ):\n eps = 1e-6\n\n # TODO(Patrick, William) - attention mask is not used\n output_states = ()\n\n for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)):\n hidden_states = resnet(hidden_states, temb)\n hidden_states = attn(\n hidden_states,\n encoder_hidden_states=encoder_hidden_states,\n cross_attention_kwargs=cross_attention_kwargs,\n attention_mask=attention_mask,\n encoder_attention_mask=encoder_attention_mask,\n return_dict=False,\n )[0]\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append([mean])\n self.var_bank.append([var])\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))\n var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc\n hidden_states_c = hidden_states_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n hidden_states_c[uc_mask] = hidden_states[uc_mask].to(hidden_states_c.dtype)\n hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc\n\n output_states = output_states + (hidden_states,)\n\n if MODE == \"read\":\n self.mean_bank = []\n self.var_bank = []\n\n if self.downsamplers is not None:\n for downsampler in self.downsamplers:\n hidden_states = downsampler(hidden_states)\n\n output_states = output_states + (hidden_states,)\n\n return hidden_states, output_states\n\n def hacked_DownBlock2D_forward(self, hidden_states, temb=None):\n eps = 1e-6\n\n output_states = ()\n\n for i, resnet in enumerate(self.resnets):\n hidden_states = resnet(hidden_states, temb)\n\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append([mean])\n self.var_bank.append([var])\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))\n var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc\n hidden_states_c = hidden_states_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n hidden_states_c[uc_mask] = hidden_states[uc_mask].to(hidden_states_c.dtype)\n hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc\n\n output_states = output_states + (hidden_states,)\n\n if MODE == \"read\":\n self.mean_bank = []\n self.var_bank = []\n\n if self.downsamplers is not None:\n for downsampler in self.downsamplers:\n hidden_states = downsampler(hidden_states)\n\n output_states = output_states + (hidden_states,)\n\n return hidden_states, output_states\n\n def hacked_CrossAttnUpBlock2D_forward(\n self,\n hidden_states: torch.FloatTensor,\n res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],\n temb: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n upsample_size: Optional[int] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n ):\n eps = 1e-6\n # TODO(Patrick, William) - attention mask is not used\n for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)):\n # pop res hidden states\n res_hidden_states = res_hidden_states_tuple[-1]\n res_hidden_states_tuple = res_hidden_states_tuple[:-1]\n hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)\n hidden_states = resnet(hidden_states, temb)\n hidden_states = attn(\n hidden_states,\n encoder_hidden_states=encoder_hidden_states,\n cross_attention_kwargs=cross_attention_kwargs,\n attention_mask=attention_mask,\n encoder_attention_mask=encoder_attention_mask,\n return_dict=False,\n )[0]\n\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append([mean])\n self.var_bank.append([var])\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))\n var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc\n hidden_states_c = hidden_states_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n hidden_states_c[uc_mask] = hidden_states[uc_mask].to(hidden_states_c.dtype)\n hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc\n\n if MODE == \"read\":\n self.mean_bank = []\n self.var_bank = []\n\n if self.upsamplers is not None:\n for upsampler in self.upsamplers:\n hidden_states = upsampler(hidden_states, upsample_size)\n\n return hidden_states\n\n def hacked_UpBlock2D_forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None):\n eps = 1e-6\n for i, resnet in enumerate(self.resnets):\n # pop res hidden states\n res_hidden_states = res_hidden_states_tuple[-1]\n res_hidden_states_tuple = res_hidden_states_tuple[:-1]\n hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)\n hidden_states = resnet(hidden_states, temb)\n\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append([mean])\n self.var_bank.append([var])\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))\n var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc\n hidden_states_c = hidden_states_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n hidden_states_c[uc_mask] = hidden_states[uc_mask].to(hidden_states_c.dtype)\n hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc\n\n if MODE == \"read\":\n self.mean_bank = []\n self.var_bank = []\n\n if self.upsamplers is not None:\n for upsampler in self.upsamplers:\n hidden_states = upsampler(hidden_states, upsample_size)\n\n return hidden_states\n\n if self.reference_attn:\n if self.fusion_blocks == \"midup\":\n attn_modules = [module for module in (torch_dfs(self.unet.mid_block)+torch_dfs(self.unet.up_blocks)) if isinstance(module, BasicTransformerBlock) or isinstance(module, _BasicTransformerBlock)]\n elif self.fusion_blocks == \"full\":\n attn_modules = [module for module in torch_dfs(self.unet) if isinstance(module, BasicTransformerBlock) or isinstance(module, _BasicTransformerBlock)] \n attn_modules = sorted(attn_modules, key=lambda x: -x.norm1.normalized_shape[0])\n\n for i, module in enumerate(attn_modules):\n module._original_inner_forward = module.forward\n module.forward = hacked_basic_transformer_inner_forward.__get__(module, BasicTransformerBlock)\n module.bank = []\n module.attn_weight = float(i) / float(len(attn_modules))\n\n if self.reference_adain:\n gn_modules = [self.unet.mid_block]\n self.unet.mid_block.gn_weight = 0\n\n down_blocks = self.unet.down_blocks\n for w, module in enumerate(down_blocks):\n module.gn_weight = 1.0 - float(w) / float(len(down_blocks))\n gn_modules.append(module)\n\n up_blocks = self.unet.up_blocks\n for w, module in enumerate(up_blocks):\n module.gn_weight = float(w) / float(len(up_blocks))\n gn_modules.append(module)\n\n for i, module in enumerate(gn_modules):\n if getattr(module, \"original_forward\", None) is None:\n module.original_forward = module.forward\n if i == 0:\n # mid_block\n module.forward = hacked_mid_forward.__get__(module, torch.nn.Module)\n elif isinstance(module, CrossAttnDownBlock2D):\n module.forward = hack_CrossAttnDownBlock2D_forward.__get__(module, CrossAttnDownBlock2D)\n elif isinstance(module, DownBlock2D):\n module.forward = hacked_DownBlock2D_forward.__get__(module, DownBlock2D)\n elif isinstance(module, CrossAttnUpBlock2D):\n module.forward = hacked_CrossAttnUpBlock2D_forward.__get__(module, CrossAttnUpBlock2D)\n elif isinstance(module, UpBlock2D):\n module.forward = hacked_UpBlock2D_forward.__get__(module, UpBlock2D)\n module.mean_bank = []\n module.var_bank = []\n module.gn_weight *= 2\n \n def update(self, writer, dtype=torch.float16):\n if self.reference_attn:\n if self.fusion_blocks == \"midup\":\n reader_attn_modules = [module for module in (torch_dfs(self.unet.mid_block)+torch_dfs(self.unet.up_blocks)) if isinstance(module, _BasicTransformerBlock)]\n writer_attn_modules = [module for module in (torch_dfs(writer.unet.mid_block)+torch_dfs(writer.unet.up_blocks)) if isinstance(module, BasicTransformerBlock)]\n elif self.fusion_blocks == \"full\":\n reader_attn_modules = [module for module in torch_dfs(self.unet) if isinstance(module, _BasicTransformerBlock)]\n writer_attn_modules = [module for module in torch_dfs(writer.unet) if isinstance(module, BasicTransformerBlock)]\n reader_attn_modules = sorted(reader_attn_modules, key=lambda x: -x.norm1.normalized_shape[0]) \n writer_attn_modules = sorted(writer_attn_modules, key=lambda x: -x.norm1.normalized_shape[0])\n for r, w in zip(reader_attn_modules, writer_attn_modules):\n r.bank = [v.clone().to(dtype) for v in w.bank]\n # w.bank.clear()\n if self.reference_adain:\n reader_gn_modules = [self.unet.mid_block]\n \n down_blocks = self.unet.down_blocks\n for w, module in enumerate(down_blocks):\n reader_gn_modules.append(module)\n\n up_blocks = self.unet.up_blocks\n for w, module in enumerate(up_blocks):\n reader_gn_modules.append(module)\n \n writer_gn_modules = [writer.unet.mid_block]\n \n down_blocks = writer.unet.down_blocks\n for w, module in enumerate(down_blocks):\n writer_gn_modules.append(module)\n\n up_blocks = writer.unet.up_blocks\n for w, module in enumerate(up_blocks):\n writer_gn_modules.append(module)\n \n for r, w in zip(reader_gn_modules, writer_gn_modules):\n if len(w.mean_bank) > 0 and isinstance(w.mean_bank[0], list):\n r.mean_bank = [[v.clone().to(dtype) for v in vl] for vl in w.mean_bank]\n r.var_bank = [[v.clone().to(dtype) for v in vl] for vl in w.var_bank]\n else:\n r.mean_bank = [v.clone().to(dtype) for v in w.mean_bank]\n r.var_bank = [v.clone().to(dtype) for v in w.var_bank]\n \n def clear(self):\n if self.reference_attn:\n if self.fusion_blocks == \"midup\":\n reader_attn_modules = [module for module in (torch_dfs(self.unet.mid_block)+torch_dfs(self.unet.up_blocks)) if isinstance(module, BasicTransformerBlock) or isinstance(module, _BasicTransformerBlock)]\n elif self.fusion_blocks == \"full\":\n reader_attn_modules = [module for module in torch_dfs(self.unet) if isinstance(module, BasicTransformerBlock) or isinstance(module, _BasicTransformerBlock)]\n reader_attn_modules = sorted(reader_attn_modules, key=lambda x: -x.norm1.normalized_shape[0])\n for r in reader_attn_modules:\n r.bank.clear()\n if self.reference_adain:\n reader_gn_modules = [self.unet.mid_block]\n \n down_blocks = self.unet.down_blocks\n for w, module in enumerate(down_blocks):\n reader_gn_modules.append(module)\n\n up_blocks = self.unet.up_blocks\n for w, module in enumerate(up_blocks):\n reader_gn_modules.append(module)\n \n for r in reader_gn_modules:\n r.mean_bank.clear()\n r.var_bank.clear()" }, { "identifier": "get_context_scheduler", "path": "magicanimate/pipelines/context.py", "snippet": "def get_context_scheduler(name: str) -> Callable:\n if name == \"uniform\":\n return uniform\n else:\n raise ValueError(f\"Unknown context_overlap policy {name}\")" }, { "identifier": "get_total_steps", "path": "magicanimate/pipelines/context.py", "snippet": "def get_total_steps(\n scheduler,\n timesteps: List[int],\n num_steps: Optional[int] = None,\n num_frames: int = ...,\n context_size: Optional[int] = None,\n context_stride: int = 3,\n context_overlap: int = 4,\n closed_loop: bool = True,\n):\n return sum(\n len(\n list(\n scheduler(\n i,\n num_steps,\n num_frames,\n context_size,\n context_stride,\n context_overlap,\n )\n )\n )\n for i in range(len(timesteps))\n )" }, { "identifier": "get_tensor_interpolation_method", "path": "magicanimate/utils/util.py", "snippet": "def get_tensor_interpolation_method():\n return tensor_interpolation" } ]
import inspect, math import numpy as np import torch import torch.distributed as dist from typing import Callable, List, Optional, Union from dataclasses import dataclass from PIL import Image from tqdm import tqdm from diffusers.utils import is_accelerate_available from packaging import version from transformers import CLIPTextModel, CLIPTokenizer from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL from diffusers.pipeline_utils import DiffusionPipeline from diffusers.schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from diffusers.utils import deprecate, logging, BaseOutput from einops import rearrange from magicanimate.models.unet_controlnet import UNet3DConditionModel from magicanimate.models.controlnet import ControlNetModel from magicanimate.models.mutual_self_attention import ReferenceAttentionControl from magicanimate.pipelines.context import ( get_context_scheduler, get_total_steps ) from magicanimate.utils.util import get_tensor_interpolation_method from accelerate import cpu_offload
19,468
v1 = None for i0,i1 in zip( range( org_video_length ),range( org_video_length )[1:] ): v0 = latents[:,:,i0,:,:] v1 = latents[:,:,i1,:,:] new_latents[:,:,new_index,:,:] = v0 new_index += 1 for f in rate: v = get_tensor_interpolation_method()(v0.to(device=device),v1.to(device=device),f) new_latents[:,:,new_index,:,:] = v.to(latents.device) new_index += 1 new_latents[:,:,new_index,:,:] = v1 new_index += 1 return new_latents def select_controlnet_res_samples(self, controlnet_res_samples_cache_dict, context, do_classifier_free_guidance, b, f): _down_block_res_samples = [] _mid_block_res_sample = [] for i in np.concatenate(np.array(context)): _down_block_res_samples.append(controlnet_res_samples_cache_dict[i][0]) _mid_block_res_sample.append(controlnet_res_samples_cache_dict[i][1]) down_block_res_samples = [[] for _ in range(len(controlnet_res_samples_cache_dict[i][0]))] for res_t in _down_block_res_samples: for i, res in enumerate(res_t): down_block_res_samples[i].append(res) down_block_res_samples = [torch.cat(res) for res in down_block_res_samples] mid_block_res_sample = torch.cat(_mid_block_res_sample) # reshape controlnet output to match the unet3d inputs b = b // 2 if do_classifier_free_guidance else b _down_block_res_samples = [] for sample in down_block_res_samples: sample = rearrange(sample, '(b f) c h w -> b c f h w', b=b, f=f) if do_classifier_free_guidance: sample = sample.repeat(2, 1, 1, 1, 1) _down_block_res_samples.append(sample) down_block_res_samples = _down_block_res_samples mid_block_res_sample = rearrange(mid_block_res_sample, '(b f) c h w -> b c f h w', b=b, f=f) if do_classifier_free_guidance: mid_block_res_sample = mid_block_res_sample.repeat(2, 1, 1, 1, 1) return down_block_res_samples, mid_block_res_sample @torch.no_grad() def __call__( self, prompt: Union[str, List[str]], video_length: Optional[int], height: Optional[int] = None, width: Optional[int] = None, num_inference_steps: int = 50, guidance_scale: float = 7.5, negative_prompt: Optional[Union[str, List[str]]] = None, num_videos_per_prompt: Optional[int] = 1, eta: float = 0.0, generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, latents: Optional[torch.FloatTensor] = None, output_type: Optional[str] = "tensor", return_dict: bool = True, callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, callback_steps: Optional[int] = 1, controlnet_condition: list = None, controlnet_conditioning_scale: float = 1.0, context_frames: int = 16, context_stride: int = 1, context_overlap: int = 4, context_batch_size: int = 1, context_schedule: str = "uniform", init_latents: Optional[torch.FloatTensor] = None, num_actual_inference_steps: Optional[int] = None, appearance_encoder = None, reference_control_writer = None, reference_control_reader = None, source_image: str = None, decoder_consistency = None, **kwargs, ): """ New args: - controlnet_condition : condition map (e.g., depth, canny, keypoints) for controlnet - controlnet_conditioning_scale : conditioning scale for controlnet - init_latents : initial latents to begin with (used along with invert()) - num_actual_inference_steps : number of actual inference steps (while total steps is num_inference_steps) """ controlnet = self.controlnet # Default height and width to unet height = height or self.unet.config.sample_size * self.vae_scale_factor width = width or self.unet.config.sample_size * self.vae_scale_factor # Check inputs. Raise error if not correct self.check_inputs(prompt, height, width, callback_steps) # Define call parameters # batch_size = 1 if isinstance(prompt, str) else len(prompt) batch_size = 1 if latents is not None: batch_size = latents.shape[0] if isinstance(prompt, list): batch_size = len(prompt) device = self._execution_device # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. do_classifier_free_guidance = guidance_scale > 1.0 # Encode input prompt prompt = prompt if isinstance(prompt, list) else [prompt] * batch_size if negative_prompt is not None: negative_prompt = negative_prompt if isinstance(negative_prompt, list) else [negative_prompt] * batch_size text_embeddings = self._encode_prompt( prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt ) text_embeddings = torch.cat([text_embeddings] * context_batch_size)
# ************************************************************************* # This file may have been modified by Bytedance Inc. (“Bytedance Inc.'s Mo- # difications”). All Bytedance Inc.'s Modifications are Copyright (2023) B- # ytedance Inc.. # ************************************************************************* # Adapted from https://github.com/showlab/Tune-A-Video/blob/main/tuneavideo/pipelines/pipeline_tuneavideo.py # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ TODO: 1. support multi-controlnet 2. [DONE] support DDIM inversion 3. support Prompt-to-prompt """ logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class AnimationPipelineOutput(BaseOutput): videos: Union[torch.Tensor, np.ndarray] class AnimationPipeline(DiffusionPipeline): _optional_components = [] def __init__( self, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet3DConditionModel, controlnet: ControlNetModel, scheduler: Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ], ): super().__init__() if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1: deprecation_message = ( f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`" f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False) new_config = dict(scheduler.config) new_config["steps_offset"] = 1 scheduler._internal_dict = FrozenDict(new_config) if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True: deprecation_message = ( f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`." " `clip_sample` should be set to False in the configuration file. Please make sure to update the" " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in" " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very" " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file" ) deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False) new_config = dict(scheduler.config) new_config["clip_sample"] = False scheduler._internal_dict = FrozenDict(new_config) is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse( version.parse(unet.config._diffusers_version).base_version ) < version.parse("0.9.0.dev0") is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64 if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64: deprecation_message = ( "The configuration file of the unet has set the default `sample_size` to smaller than" " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the" " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-" " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5" " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the" " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`" " in the config might lead to incorrect results in future versions. If you have downloaded this" " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for" " the `unet/config.json` file" ) deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False) new_config = dict(unet.config) new_config["sample_size"] = 64 unet._internal_dict = FrozenDict(new_config) self.register_modules( vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet, controlnet=controlnet, scheduler=scheduler, ) self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) def enable_vae_slicing(self): self.vae.enable_slicing() def disable_vae_slicing(self): self.vae.disable_slicing() def enable_sequential_cpu_offload(self, gpu_id=0): if is_accelerate_available(): else: raise ImportError("Please install accelerate via `pip install accelerate`") device = torch.device(f"cuda:{gpu_id}") for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]: if cpu_offloaded_model is not None: cpu_offload(cpu_offloaded_model, device) @property def _execution_device(self): if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"): return self.device for module in self.unet.modules(): if ( hasattr(module, "_hf_hook") and hasattr(module._hf_hook, "execution_device") and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device) return self.device def _encode_prompt(self, prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt): batch_size = len(prompt) if isinstance(prompt, list) else 1 text_inputs = self.tokenizer( prompt, padding="max_length", max_length=self.tokenizer.model_max_length, truncation=True, return_tensors="pt", ) text_input_ids = text_inputs.input_ids untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids): removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]) logger.warning( "The following part of your input was truncated because CLIP can only handle sequences up to" f" {self.tokenizer.model_max_length} tokens: {removed_text}" ) if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: attention_mask = text_inputs.attention_mask.to(device) else: attention_mask = None text_embeddings = self.text_encoder( text_input_ids.to(device), attention_mask=attention_mask, ) text_embeddings = text_embeddings[0] # duplicate text embeddings for each generation per prompt, using mps friendly method bs_embed, seq_len, _ = text_embeddings.shape text_embeddings = text_embeddings.repeat(1, num_videos_per_prompt, 1) text_embeddings = text_embeddings.view(bs_embed * num_videos_per_prompt, seq_len, -1) # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: uncond_tokens: List[str] if negative_prompt is None: uncond_tokens = [""] * batch_size elif type(prompt) is not type(negative_prompt): raise TypeError( f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" f" {type(prompt)}." ) elif isinstance(negative_prompt, str): uncond_tokens = [negative_prompt] elif batch_size != len(negative_prompt): raise ValueError( f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" " the batch size of `prompt`." ) else: uncond_tokens = negative_prompt max_length = text_input_ids.shape[-1] uncond_input = self.tokenizer( uncond_tokens, padding="max_length", max_length=max_length, truncation=True, return_tensors="pt", ) if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: attention_mask = uncond_input.attention_mask.to(device) else: attention_mask = None uncond_embeddings = self.text_encoder( uncond_input.input_ids.to(device), attention_mask=attention_mask, ) uncond_embeddings = uncond_embeddings[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method seq_len = uncond_embeddings.shape[1] uncond_embeddings = uncond_embeddings.repeat(1, num_videos_per_prompt, 1) uncond_embeddings = uncond_embeddings.view(batch_size * num_videos_per_prompt, seq_len, -1) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes text_embeddings = torch.cat([uncond_embeddings, text_embeddings]) return text_embeddings def decode_latents(self, latents, rank, decoder_consistency=None): video_length = latents.shape[2] latents = 1 / 0.18215 * latents latents = rearrange(latents, "b c f h w -> (b f) c h w") # video = self.vae.decode(latents).sample video = [] for frame_idx in tqdm(range(latents.shape[0]), disable=(rank!=0)): if decoder_consistency is not None: video.append(decoder_consistency(latents[frame_idx:frame_idx+1])) else: video.append(self.vae.decode(latents[frame_idx:frame_idx+1]).sample) video = torch.cat(video) video = rearrange(video, "(b f) c h w -> b c f h w", f=video_length) video = (video / 2 + 0.5).clamp(0, 1) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16 video = video.cpu().float().numpy() return video def prepare_extra_step_kwargs(self, generator, eta): # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) extra_step_kwargs = {} if accepts_eta: extra_step_kwargs["eta"] = eta # check if the scheduler accepts generator accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) if accepts_generator: extra_step_kwargs["generator"] = generator return extra_step_kwargs def check_inputs(self, prompt, height, width, callback_steps): if not isinstance(prompt, str) and not isinstance(prompt, list): raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") if height % 8 != 0 or width % 8 != 0: raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") if (callback_steps is None) or ( callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0) ): raise ValueError( f"`callback_steps` has to be a positive integer but is {callback_steps} of type" f" {type(callback_steps)}." ) def prepare_latents(self, batch_size, num_channels_latents, video_length, height, width, dtype, device, generator, latents=None, clip_length=16): shape = (batch_size, num_channels_latents, clip_length, height // self.vae_scale_factor, width // self.vae_scale_factor) if isinstance(generator, list) and len(generator) != batch_size: raise ValueError( f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" f" size of {batch_size}. Make sure the batch size matches the length of the generators." ) if latents is None: rand_device = "cpu" if device.type == "mps" else device if isinstance(generator, list): latents = [ torch.randn(shape, generator=generator[i], device=rand_device, dtype=dtype) for i in range(batch_size) ] latents = torch.cat(latents, dim=0).to(device) else: latents = torch.randn(shape, generator=generator, device=rand_device, dtype=dtype).to(device) latents = latents.repeat(1, 1, video_length//clip_length, 1, 1) else: if latents.shape != shape: raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}") latents = latents.to(device) # scale the initial noise by the standard deviation required by the scheduler latents = latents * self.scheduler.init_noise_sigma return latents def prepare_condition(self, condition, num_videos_per_prompt, device, dtype, do_classifier_free_guidance): # prepare conditions for controlnet condition = torch.from_numpy(condition.copy()).to(device=device, dtype=dtype) / 255.0 condition = torch.stack([condition for _ in range(num_videos_per_prompt)], dim=0) condition = rearrange(condition, 'b f h w c -> (b f) c h w').clone() if do_classifier_free_guidance: condition = torch.cat([condition] * 2) return condition def next_step( self, model_output: torch.FloatTensor, timestep: int, x: torch.FloatTensor, eta=0., verbose=False ): """ Inverse sampling for DDIM Inversion """ if verbose: print("timestep: ", timestep) next_step = timestep timestep = min(timestep - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps, 999) alpha_prod_t = self.scheduler.alphas_cumprod[timestep] if timestep >= 0 else self.scheduler.final_alpha_cumprod alpha_prod_t_next = self.scheduler.alphas_cumprod[next_step] beta_prod_t = 1 - alpha_prod_t pred_x0 = (x - beta_prod_t**0.5 * model_output) / alpha_prod_t**0.5 pred_dir = (1 - alpha_prod_t_next)**0.5 * model_output x_next = alpha_prod_t_next**0.5 * pred_x0 + pred_dir return x_next, pred_x0 @torch.no_grad() def images2latents(self, images, dtype): """ Convert RGB image to VAE latents """ device = self._execution_device images = torch.from_numpy(images).float().to(dtype) / 127.5 - 1 images = rearrange(images, "f h w c -> f c h w").to(device) latents = [] for frame_idx in range(images.shape[0]): latents.append(self.vae.encode(images[frame_idx:frame_idx+1])['latent_dist'].mean * 0.18215) latents = torch.cat(latents) return latents @torch.no_grad() def invert( self, image: torch.Tensor, prompt, num_inference_steps=20, num_actual_inference_steps=10, eta=0.0, return_intermediates=False, **kwargs): """ Adapted from: https://github.com/Yujun-Shi/DragDiffusion/blob/main/drag_pipeline.py#L440 invert a real image into noise map with determinisc DDIM inversion """ device = self._execution_device batch_size = image.shape[0] if isinstance(prompt, list): if batch_size == 1: image = image.expand(len(prompt), -1, -1, -1) elif isinstance(prompt, str): if batch_size > 1: prompt = [prompt] * batch_size # text embeddings text_input = self.tokenizer( prompt, padding="max_length", max_length=77, return_tensors="pt" ) text_embeddings = self.text_encoder(text_input.input_ids.to(device))[0] print("input text embeddings :", text_embeddings.shape) # define initial latents latents = self.images2latents(image) print("latents shape: ", latents.shape) # interative sampling self.scheduler.set_timesteps(num_inference_steps) print("Valid timesteps: ", reversed(self.scheduler.timesteps)) latents_list = [latents] pred_x0_list = [latents] for i, t in enumerate(tqdm(reversed(self.scheduler.timesteps), desc="DDIM Inversion")): if num_actual_inference_steps is not None and i >= num_actual_inference_steps: continue model_inputs = latents # predict the noise # NOTE: the u-net here is UNet3D, therefore the model_inputs need to be of shape (b c f h w) model_inputs = rearrange(model_inputs, "f c h w -> 1 c f h w") noise_pred = self.unet(model_inputs, t, encoder_hidden_states=text_embeddings).sample noise_pred = rearrange(noise_pred, "b c f h w -> (b f) c h w") # compute the previous noise sample x_t-1 -> x_t latents, pred_x0 = self.next_step(noise_pred, t, latents) latents_list.append(latents) pred_x0_list.append(pred_x0) if return_intermediates: # return the intermediate laters during inversion return latents, latents_list return latents def interpolate_latents(self, latents: torch.Tensor, interpolation_factor:int, device ): if interpolation_factor < 2: return latents new_latents = torch.zeros( (latents.shape[0],latents.shape[1],((latents.shape[2]-1) * interpolation_factor)+1, latents.shape[3],latents.shape[4]), device=latents.device, dtype=latents.dtype, ) org_video_length = latents.shape[2] rate = [i/interpolation_factor for i in range(interpolation_factor)][1:] new_index = 0 v0 = None v1 = None for i0,i1 in zip( range( org_video_length ),range( org_video_length )[1:] ): v0 = latents[:,:,i0,:,:] v1 = latents[:,:,i1,:,:] new_latents[:,:,new_index,:,:] = v0 new_index += 1 for f in rate: v = get_tensor_interpolation_method()(v0.to(device=device),v1.to(device=device),f) new_latents[:,:,new_index,:,:] = v.to(latents.device) new_index += 1 new_latents[:,:,new_index,:,:] = v1 new_index += 1 return new_latents def select_controlnet_res_samples(self, controlnet_res_samples_cache_dict, context, do_classifier_free_guidance, b, f): _down_block_res_samples = [] _mid_block_res_sample = [] for i in np.concatenate(np.array(context)): _down_block_res_samples.append(controlnet_res_samples_cache_dict[i][0]) _mid_block_res_sample.append(controlnet_res_samples_cache_dict[i][1]) down_block_res_samples = [[] for _ in range(len(controlnet_res_samples_cache_dict[i][0]))] for res_t in _down_block_res_samples: for i, res in enumerate(res_t): down_block_res_samples[i].append(res) down_block_res_samples = [torch.cat(res) for res in down_block_res_samples] mid_block_res_sample = torch.cat(_mid_block_res_sample) # reshape controlnet output to match the unet3d inputs b = b // 2 if do_classifier_free_guidance else b _down_block_res_samples = [] for sample in down_block_res_samples: sample = rearrange(sample, '(b f) c h w -> b c f h w', b=b, f=f) if do_classifier_free_guidance: sample = sample.repeat(2, 1, 1, 1, 1) _down_block_res_samples.append(sample) down_block_res_samples = _down_block_res_samples mid_block_res_sample = rearrange(mid_block_res_sample, '(b f) c h w -> b c f h w', b=b, f=f) if do_classifier_free_guidance: mid_block_res_sample = mid_block_res_sample.repeat(2, 1, 1, 1, 1) return down_block_res_samples, mid_block_res_sample @torch.no_grad() def __call__( self, prompt: Union[str, List[str]], video_length: Optional[int], height: Optional[int] = None, width: Optional[int] = None, num_inference_steps: int = 50, guidance_scale: float = 7.5, negative_prompt: Optional[Union[str, List[str]]] = None, num_videos_per_prompt: Optional[int] = 1, eta: float = 0.0, generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, latents: Optional[torch.FloatTensor] = None, output_type: Optional[str] = "tensor", return_dict: bool = True, callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, callback_steps: Optional[int] = 1, controlnet_condition: list = None, controlnet_conditioning_scale: float = 1.0, context_frames: int = 16, context_stride: int = 1, context_overlap: int = 4, context_batch_size: int = 1, context_schedule: str = "uniform", init_latents: Optional[torch.FloatTensor] = None, num_actual_inference_steps: Optional[int] = None, appearance_encoder = None, reference_control_writer = None, reference_control_reader = None, source_image: str = None, decoder_consistency = None, **kwargs, ): """ New args: - controlnet_condition : condition map (e.g., depth, canny, keypoints) for controlnet - controlnet_conditioning_scale : conditioning scale for controlnet - init_latents : initial latents to begin with (used along with invert()) - num_actual_inference_steps : number of actual inference steps (while total steps is num_inference_steps) """ controlnet = self.controlnet # Default height and width to unet height = height or self.unet.config.sample_size * self.vae_scale_factor width = width or self.unet.config.sample_size * self.vae_scale_factor # Check inputs. Raise error if not correct self.check_inputs(prompt, height, width, callback_steps) # Define call parameters # batch_size = 1 if isinstance(prompt, str) else len(prompt) batch_size = 1 if latents is not None: batch_size = latents.shape[0] if isinstance(prompt, list): batch_size = len(prompt) device = self._execution_device # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. do_classifier_free_guidance = guidance_scale > 1.0 # Encode input prompt prompt = prompt if isinstance(prompt, list) else [prompt] * batch_size if negative_prompt is not None: negative_prompt = negative_prompt if isinstance(negative_prompt, list) else [negative_prompt] * batch_size text_embeddings = self._encode_prompt( prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt ) text_embeddings = torch.cat([text_embeddings] * context_batch_size)
reference_control_writer = ReferenceAttentionControl(appearance_encoder, do_classifier_free_guidance=True, mode='write', batch_size=context_batch_size)
2
2023-12-04 20:47:34+00:00
24k
metatube-community/metatube-plex-plugins
MetaTube.bundle/Contents/Libraries/Shared/urllib3/poolmanager.py
[ { "identifier": "HTTPHeaderDict", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/_collections.py", "snippet": "class HTTPHeaderDict(MutableMapping):\n \"\"\"\n :param headers:\n An iterable of field-value pairs. Must not contain multiple field names\n when compared case-insensitively.\n\n :param kwargs:\n Additional field-value pairs to pass in to ``dict.update``.\n\n A ``dict`` like container for storing HTTP Headers.\n\n Field names are stored and compared case-insensitively in compliance with\n RFC 7230. Iteration provides the first case-sensitive key seen for each\n case-insensitive pair.\n\n Using ``__setitem__`` syntax overwrites fields that compare equal\n case-insensitively in order to maintain ``dict``'s api. For fields that\n compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``\n in a loop.\n\n If multiple fields that are equal case-insensitively are passed to the\n constructor or ``.update``, the behavior is undefined and some will be\n lost.\n\n >>> headers = HTTPHeaderDict()\n >>> headers.add('Set-Cookie', 'foo=bar')\n >>> headers.add('set-cookie', 'baz=quxx')\n >>> headers['content-length'] = '7'\n >>> headers['SET-cookie']\n 'foo=bar, baz=quxx'\n >>> headers['Content-Length']\n '7'\n \"\"\"\n\n def __init__(self, headers=None, **kwargs):\n super(HTTPHeaderDict, self).__init__()\n self._container = OrderedDict()\n if headers is not None:\n if isinstance(headers, HTTPHeaderDict):\n self._copy_from(headers)\n else:\n self.extend(headers)\n if kwargs:\n self.extend(kwargs)\n\n def __setitem__(self, key, val):\n self._container[key.lower()] = [key, val]\n return self._container[key.lower()]\n\n def __getitem__(self, key):\n val = self._container[key.lower()]\n return \", \".join(val[1:])\n\n def __delitem__(self, key):\n del self._container[key.lower()]\n\n def __contains__(self, key):\n return key.lower() in self._container\n\n def __eq__(self, other):\n if not isinstance(other, Mapping) and not hasattr(other, \"keys\"):\n return False\n if not isinstance(other, type(self)):\n other = type(self)(other)\n return dict((k.lower(), v) for k, v in self.itermerged()) == dict(\n (k.lower(), v) for k, v in other.itermerged()\n )\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n if six.PY2: # Python 2\n iterkeys = MutableMapping.iterkeys\n itervalues = MutableMapping.itervalues\n\n __marker = object()\n\n def __len__(self):\n return len(self._container)\n\n def __iter__(self):\n # Only provide the originally cased names\n for vals in self._container.values():\n yield vals[0]\n\n def pop(self, key, default=__marker):\n \"\"\"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n If key is not found, d is returned if given, otherwise KeyError is raised.\n \"\"\"\n # Using the MutableMapping function directly fails due to the private marker.\n # Using ordinary dict.pop would expose the internal structures.\n # So let's reinvent the wheel.\n try:\n value = self[key]\n except KeyError:\n if default is self.__marker:\n raise\n return default\n else:\n del self[key]\n return value\n\n def discard(self, key):\n try:\n del self[key]\n except KeyError:\n pass\n\n def add(self, key, val):\n \"\"\"Adds a (name, value) pair, doesn't overwrite the value if it already\n exists.\n\n >>> headers = HTTPHeaderDict(foo='bar')\n >>> headers.add('Foo', 'baz')\n >>> headers['foo']\n 'bar, baz'\n \"\"\"\n key_lower = key.lower()\n new_vals = [key, val]\n # Keep the common case aka no item present as fast as possible\n vals = self._container.setdefault(key_lower, new_vals)\n if new_vals is not vals:\n vals.append(val)\n\n def extend(self, *args, **kwargs):\n \"\"\"Generic import function for any type of header-like object.\n Adapted version of MutableMapping.update in order to insert items\n with self.add instead of self.__setitem__\n \"\"\"\n if len(args) > 1:\n raise TypeError(\n \"extend() takes at most 1 positional \"\n \"arguments ({0} given)\".format(len(args))\n )\n other = args[0] if len(args) >= 1 else ()\n\n if isinstance(other, HTTPHeaderDict):\n for key, val in other.iteritems():\n self.add(key, val)\n elif isinstance(other, Mapping):\n for key in other:\n self.add(key, other[key])\n elif hasattr(other, \"keys\"):\n for key in other.keys():\n self.add(key, other[key])\n else:\n for key, value in other:\n self.add(key, value)\n\n for key, value in kwargs.items():\n self.add(key, value)\n\n def getlist(self, key, default=__marker):\n \"\"\"Returns a list of all the values for the named field. Returns an\n empty list if the key doesn't exist.\"\"\"\n try:\n vals = self._container[key.lower()]\n except KeyError:\n if default is self.__marker:\n return []\n return default\n else:\n return vals[1:]\n\n def _prepare_for_method_change(self):\n \"\"\"\n Remove content-specific header fields before changing the request\n method to GET or HEAD according to RFC 9110, Section 15.4.\n \"\"\"\n content_specific_headers = [\n \"Content-Encoding\",\n \"Content-Language\",\n \"Content-Location\",\n \"Content-Type\",\n \"Content-Length\",\n \"Digest\",\n \"Last-Modified\",\n ]\n for header in content_specific_headers:\n self.discard(header)\n return self\n\n # Backwards compatibility for httplib\n getheaders = getlist\n getallmatchingheaders = getlist\n iget = getlist\n\n # Backwards compatibility for http.cookiejar\n get_all = getlist\n\n def __repr__(self):\n return \"%s(%s)\" % (type(self).__name__, dict(self.itermerged()))\n\n def _copy_from(self, other):\n for key in other:\n val = other.getlist(key)\n if isinstance(val, list):\n # Don't need to convert tuples\n val = list(val)\n self._container[key.lower()] = [key] + val\n\n def copy(self):\n clone = type(self)()\n clone._copy_from(self)\n return clone\n\n def iteritems(self):\n \"\"\"Iterate over all header lines, including duplicate ones.\"\"\"\n for key in self:\n vals = self._container[key.lower()]\n for val in vals[1:]:\n yield vals[0], val\n\n def itermerged(self):\n \"\"\"Iterate over all headers, merging duplicate ones together.\"\"\"\n for key in self:\n val = self._container[key.lower()]\n yield val[0], \", \".join(val[1:])\n\n def items(self):\n return list(self.iteritems())\n\n @classmethod\n def from_httplib(cls, message): # Python 2\n \"\"\"Read headers from a Python 2 httplib message object.\"\"\"\n # python2.7 does not expose a proper API for exporting multiheaders\n # efficiently. This function re-reads raw lines from the message\n # object and extracts the multiheaders properly.\n obs_fold_continued_leaders = (\" \", \"\\t\")\n headers = []\n\n for line in message.headers:\n if line.startswith(obs_fold_continued_leaders):\n if not headers:\n # We received a header line that starts with OWS as described\n # in RFC-7230 S3.2.4. This indicates a multiline header, but\n # there exists no previous header to which we can attach it.\n raise InvalidHeader(\n \"Header continuation with no previous header: %s\" % line\n )\n else:\n key, value = headers[-1]\n headers[-1] = (key, value + \" \" + line.strip())\n continue\n\n key, value = line.split(\":\", 1)\n headers.append((key, value.strip()))\n\n return cls(headers)" }, { "identifier": "RecentlyUsedContainer", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/_collections.py", "snippet": "class RecentlyUsedContainer(MutableMapping):\n \"\"\"\n Provides a thread-safe dict-like container which maintains up to\n ``maxsize`` keys while throwing away the least-recently-used keys beyond\n ``maxsize``.\n\n :param maxsize:\n Maximum number of recent elements to retain.\n\n :param dispose_func:\n Every time an item is evicted from the container,\n ``dispose_func(value)`` is called. Callback which will get called\n \"\"\"\n\n ContainerCls = OrderedDict\n\n def __init__(self, maxsize=10, dispose_func=None):\n self._maxsize = maxsize\n self.dispose_func = dispose_func\n\n self._container = self.ContainerCls()\n self.lock = RLock()\n\n def __getitem__(self, key):\n # Re-insert the item, moving it to the end of the eviction line.\n with self.lock:\n item = self._container.pop(key)\n self._container[key] = item\n return item\n\n def __setitem__(self, key, value):\n evicted_value = _Null\n with self.lock:\n # Possibly evict the existing value of 'key'\n evicted_value = self._container.get(key, _Null)\n self._container[key] = value\n\n # If we didn't evict an existing value, we might have to evict the\n # least recently used item from the beginning of the container.\n if len(self._container) > self._maxsize:\n _key, evicted_value = self._container.popitem(last=False)\n\n if self.dispose_func and evicted_value is not _Null:\n self.dispose_func(evicted_value)\n\n def __delitem__(self, key):\n with self.lock:\n value = self._container.pop(key)\n\n if self.dispose_func:\n self.dispose_func(value)\n\n def __len__(self):\n with self.lock:\n return len(self._container)\n\n def __iter__(self):\n raise NotImplementedError(\n \"Iteration over this class is unlikely to be threadsafe.\"\n )\n\n def clear(self):\n with self.lock:\n # Copy pointers to all values, then wipe the mapping\n values = list(itervalues(self._container))\n self._container.clear()\n\n if self.dispose_func:\n for value in values:\n self.dispose_func(value)\n\n def keys(self):\n with self.lock:\n return list(iterkeys(self._container))" }, { "identifier": "HTTPConnectionPool", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/connectionpool.py", "snippet": "class ConnectionPool(object):\nclass HTTPConnectionPool(ConnectionPool, RequestMethods):\nclass HTTPSConnectionPool(HTTPConnectionPool):\n def __init__(self, host, port=None):\n def __str__(self):\n def __enter__(self):\n def __exit__(self, exc_type, exc_val, exc_tb):\n def close(self):\n def __init__(\n self,\n host,\n port=None,\n strict=False,\n timeout=Timeout.DEFAULT_TIMEOUT,\n maxsize=1,\n block=False,\n headers=None,\n retries=None,\n _proxy=None,\n _proxy_headers=None,\n _proxy_config=None,\n **conn_kw\n ):\n def _new_conn(self):\n def _get_conn(self, timeout=None):\n def _put_conn(self, conn):\n def _validate_conn(self, conn):\n def _prepare_proxy(self, conn):\n def _get_timeout(self, timeout):\n def _raise_timeout(self, err, url, timeout_value):\n def _make_request(\n self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw\n ):\n def _absolute_url(self, path):\n def close(self):\n def is_same_host(self, url):\n def urlopen(\n self,\n method,\n url,\n body=None,\n headers=None,\n retries=None,\n redirect=True,\n assert_same_host=True,\n timeout=_Default,\n pool_timeout=None,\n release_conn=None,\n chunked=False,\n body_pos=None,\n **response_kw\n ):\n def _is_ssl_error_message_from_http_proxy(ssl_error):\n def __init__(\n self,\n host,\n port=None,\n strict=False,\n timeout=Timeout.DEFAULT_TIMEOUT,\n maxsize=1,\n block=False,\n headers=None,\n retries=None,\n _proxy=None,\n _proxy_headers=None,\n key_file=None,\n cert_file=None,\n cert_reqs=None,\n key_password=None,\n ca_certs=None,\n ssl_version=None,\n assert_hostname=None,\n assert_fingerprint=None,\n ca_cert_dir=None,\n **conn_kw\n ):\n def _prepare_conn(self, conn):\n def _prepare_proxy(self, conn):\n def _new_conn(self):\n def _validate_conn(self, conn):\ndef connection_from_url(url, **kw):\ndef _normalize_host(host, scheme):\ndef _close_pool_connections(pool):" }, { "identifier": "LocationValueError", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/exceptions.py", "snippet": "class LocationValueError(ValueError, HTTPError):\n \"\"\"Raised when there is something wrong with a given URL input.\"\"\"\n\n pass" }, { "identifier": "MaxRetryError", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/exceptions.py", "snippet": "class MaxRetryError(RequestError):\n \"\"\"Raised when the maximum number of retries is exceeded.\n\n :param pool: The connection pool\n :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool`\n :param string url: The requested Url\n :param exceptions.Exception reason: The underlying error\n\n \"\"\"\n\n def __init__(self, pool, url, reason=None):\n self.reason = reason\n\n message = \"Max retries exceeded with url: %s (Caused by %r)\" % (url, reason)\n\n RequestError.__init__(self, pool, url, message)" }, { "identifier": "ProxySchemeUnknown", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/exceptions.py", "snippet": "class ProxySchemeUnknown(AssertionError, URLSchemeUnknown):\n \"\"\"ProxyManager does not support the supplied scheme\"\"\"\n\n # TODO(t-8ch): Stop inheriting from AssertionError in v2.0.\n\n def __init__(self, scheme):\n # 'localhost' is here because our URL parser parses\n # localhost:8080 -> scheme=localhost, remove if we fix this.\n if scheme == \"localhost\":\n scheme = None\n if scheme is None:\n message = \"Proxy URL had no scheme, should start with http:// or https://\"\n else:\n message = (\n \"Proxy URL had unsupported scheme %s, should use http:// or https://\"\n % scheme\n )\n super(ProxySchemeUnknown, self).__init__(message)" }, { "identifier": "ProxySchemeUnsupported", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/exceptions.py", "snippet": "class ProxySchemeUnsupported(ValueError):\n \"\"\"Fetching HTTPS resources through HTTPS proxies is unsupported\"\"\"\n\n pass" }, { "identifier": "URLSchemeUnknown", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/exceptions.py", "snippet": "class URLSchemeUnknown(LocationValueError):\n \"\"\"Raised when a URL input has an unsupported scheme.\"\"\"\n\n def __init__(self, scheme):\n message = \"Not supported URL scheme %s\" % scheme\n super(URLSchemeUnknown, self).__init__(message)\n\n self.scheme = scheme" }, { "identifier": "six", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/packages/six.py", "snippet": "PY2 = sys.version_info[0] == 2\nPY3 = sys.version_info[0] == 3\nPY34 = sys.version_info[0:2] >= (3, 4)\n MAXSIZE = sys.maxsize\n MAXSIZE = int((1 << 31) - 1)\n MAXSIZE = int((1 << 31) - 1)\n MAXSIZE = int((1 << 63) - 1)\n class X(object):\nclass _LazyDescr(object):\nclass MovedModule(_LazyDescr):\nclass _LazyModule(types.ModuleType):\nclass MovedAttribute(_LazyDescr):\nclass _SixMetaPathImporter(object):\nclass _MovedItems(_LazyModule):\nclass Module_six_moves_urllib_parse(_LazyModule):\nclass Module_six_moves_urllib_error(_LazyModule):\nclass Module_six_moves_urllib_request(_LazyModule):\nclass Module_six_moves_urllib_response(_LazyModule):\nclass Module_six_moves_urllib_robotparser(_LazyModule):\nclass Module_six_moves_urllib(types.ModuleType):\n class Iterator(object):\n class metaclass(type):\n def __len__(self):\ndef _add_doc(func, doc):\ndef _import_module(name):\n def __init__(self, name):\n def __get__(self, obj, tp):\n def __init__(self, name, old, new=None):\n def _resolve(self):\n def __getattr__(self, attr):\n def __init__(self, name):\n def __dir__(self):\n def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):\n def _resolve(self):\n def __init__(self, six_module_name):\n def _add_module(self, mod, *fullnames):\n def _get_module(self, fullname):\n def find_module(self, fullname, path=None):\n def find_spec(self, fullname, path, target=None):\n def __get_module(self, fullname):\n def load_module(self, fullname):\n def is_package(self, fullname):\n def get_code(self, fullname):\n def create_module(self, spec):\n def exec_module(self, module):\n def __dir__(self):\ndef add_move(move):\ndef remove_move(name):\n def advance_iterator(it):\n def callable(obj):\n def get_unbound_function(unbound):\n def create_unbound_method(func, cls):\n def get_unbound_function(unbound):\n def create_bound_method(func, obj):\n def create_unbound_method(func, cls):\n def next(self):\n def iterkeys(d, **kw):\n def itervalues(d, **kw):\n def iteritems(d, **kw):\n def iterlists(d, **kw):\n def iterkeys(d, **kw):\n def itervalues(d, **kw):\n def iteritems(d, **kw):\n def iterlists(d, **kw):\n def b(s):\n def u(s):\n def b(s):\n def u(s):\n def byte2int(bs):\n def indexbytes(buf, i):\ndef assertCountEqual(self, *args, **kwargs):\ndef assertRaisesRegex(self, *args, **kwargs):\ndef assertRegex(self, *args, **kwargs):\ndef assertNotRegex(self, *args, **kwargs):\n def reraise(tp, value, tb=None):\n def exec_(_code_, _globs_=None, _locs_=None):\n def raise_from(value, from_value):\n def print_(*args, **kwargs):\n def write(data):\n def print_(*args, **kwargs):\n def _update_wrapper(\n wrapper,\n wrapped,\n assigned=functools.WRAPPER_ASSIGNMENTS,\n updated=functools.WRAPPER_UPDATES,\n ):\n def wraps(\n wrapped,\n assigned=functools.WRAPPER_ASSIGNMENTS,\n updated=functools.WRAPPER_UPDATES,\n ):\ndef with_metaclass(meta, *bases):\n def __new__(cls, name, this_bases, d):\n def __prepare__(cls, name, this_bases):\ndef add_metaclass(metaclass):\n def wrapper(cls):\ndef ensure_binary(s, encoding=\"utf-8\", errors=\"strict\"):\ndef ensure_str(s, encoding=\"utf-8\", errors=\"strict\"):\ndef ensure_text(s, encoding=\"utf-8\", errors=\"strict\"):\ndef python_2_unicode_compatible(klass):" }, { "identifier": "RequestMethods", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/request.py", "snippet": "class RequestMethods(object):\n \"\"\"\n Convenience mixin for classes who implement a :meth:`urlopen` method, such\n as :class:`urllib3.HTTPConnectionPool` and\n :class:`urllib3.PoolManager`.\n\n Provides behavior for making common types of HTTP request methods and\n decides which type of request field encoding to use.\n\n Specifically,\n\n :meth:`.request_encode_url` is for sending requests whose fields are\n encoded in the URL (such as GET, HEAD, DELETE).\n\n :meth:`.request_encode_body` is for sending requests whose fields are\n encoded in the *body* of the request using multipart or www-form-urlencoded\n (such as for POST, PUT, PATCH).\n\n :meth:`.request` is for making any kind of request, it will look up the\n appropriate encoding format and use one of the above two methods to make\n the request.\n\n Initializer parameters:\n\n :param headers:\n Headers to include with all requests, unless other headers are given\n explicitly.\n \"\"\"\n\n _encode_url_methods = {\"DELETE\", \"GET\", \"HEAD\", \"OPTIONS\"}\n\n def __init__(self, headers=None):\n self.headers = headers or {}\n\n def urlopen(\n self,\n method,\n url,\n body=None,\n headers=None,\n encode_multipart=True,\n multipart_boundary=None,\n **kw\n ): # Abstract\n raise NotImplementedError(\n \"Classes extending RequestMethods must implement \"\n \"their own ``urlopen`` method.\"\n )\n\n def request(self, method, url, fields=None, headers=None, **urlopen_kw):\n \"\"\"\n Make a request using :meth:`urlopen` with the appropriate encoding of\n ``fields`` based on the ``method`` used.\n\n This is a convenience method that requires the least amount of manual\n effort. It can be used in most situations, while still having the\n option to drop down to more specific methods when necessary, such as\n :meth:`request_encode_url`, :meth:`request_encode_body`,\n or even the lowest level :meth:`urlopen`.\n \"\"\"\n method = method.upper()\n\n urlopen_kw[\"request_url\"] = url\n\n if method in self._encode_url_methods:\n return self.request_encode_url(\n method, url, fields=fields, headers=headers, **urlopen_kw\n )\n else:\n return self.request_encode_body(\n method, url, fields=fields, headers=headers, **urlopen_kw\n )\n\n def request_encode_url(self, method, url, fields=None, headers=None, **urlopen_kw):\n \"\"\"\n Make a request using :meth:`urlopen` with the ``fields`` encoded in\n the url. This is useful for request methods like GET, HEAD, DELETE, etc.\n \"\"\"\n if headers is None:\n headers = self.headers\n\n extra_kw = {\"headers\": headers}\n extra_kw.update(urlopen_kw)\n\n if fields:\n url += \"?\" + urlencode(fields)\n\n return self.urlopen(method, url, **extra_kw)\n\n def request_encode_body(\n self,\n method,\n url,\n fields=None,\n headers=None,\n encode_multipart=True,\n multipart_boundary=None,\n **urlopen_kw\n ):\n \"\"\"\n Make a request using :meth:`urlopen` with the ``fields`` encoded in\n the body. This is useful for request methods like POST, PUT, PATCH, etc.\n\n When ``encode_multipart=True`` (default), then\n :func:`urllib3.encode_multipart_formdata` is used to encode\n the payload with the appropriate content type. Otherwise\n :func:`urllib.parse.urlencode` is used with the\n 'application/x-www-form-urlencoded' content type.\n\n Multipart encoding must be used when posting files, and it's reasonably\n safe to use it in other times too. However, it may break request\n signing, such as with OAuth.\n\n Supports an optional ``fields`` parameter of key/value strings AND\n key/filetuple. A filetuple is a (filename, data, MIME type) tuple where\n the MIME type is optional. For example::\n\n fields = {\n 'foo': 'bar',\n 'fakefile': ('foofile.txt', 'contents of foofile'),\n 'realfile': ('barfile.txt', open('realfile').read()),\n 'typedfile': ('bazfile.bin', open('bazfile').read(),\n 'image/jpeg'),\n 'nonamefile': 'contents of nonamefile field',\n }\n\n When uploading a file, providing a filename (the first parameter of the\n tuple) is optional but recommended to best mimic behavior of browsers.\n\n Note that if ``headers`` are supplied, the 'Content-Type' header will\n be overwritten because it depends on the dynamic random boundary string\n which is used to compose the body of the request. The random boundary\n string can be explicitly set with the ``multipart_boundary`` parameter.\n \"\"\"\n if headers is None:\n headers = self.headers\n\n extra_kw = {\"headers\": {}}\n\n if fields:\n if \"body\" in urlopen_kw:\n raise TypeError(\n \"request got values for both 'fields' and 'body', can only specify one.\"\n )\n\n if encode_multipart:\n body, content_type = encode_multipart_formdata(\n fields, boundary=multipart_boundary\n )\n else:\n body, content_type = (\n urlencode(fields),\n \"application/x-www-form-urlencoded\",\n )\n\n extra_kw[\"body\"] = body\n extra_kw[\"headers\"] = {\"Content-Type\": content_type}\n\n extra_kw[\"headers\"].update(headers)\n extra_kw.update(urlopen_kw)\n\n return self.urlopen(method, url, **extra_kw)" }, { "identifier": "connection_requires_http_tunnel", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/util/proxy.py", "snippet": "def connection_requires_http_tunnel(\n proxy_url=None, proxy_config=None, destination_scheme=None\n):\n \"\"\"\n Returns True if the connection requires an HTTP CONNECT through the proxy.\n\n :param URL proxy_url:\n URL of the proxy.\n :param ProxyConfig proxy_config:\n Proxy configuration from poolmanager.py\n :param str destination_scheme:\n The scheme of the destination. (i.e https, http, etc)\n \"\"\"\n # If we're not using a proxy, no way to use a tunnel.\n if proxy_url is None:\n return False\n\n # HTTP destinations never require tunneling, we always forward.\n if destination_scheme == \"http\":\n return False\n\n # Support for forwarding with HTTPS proxies and HTTPS destinations.\n if (\n proxy_url.scheme == \"https\"\n and proxy_config\n and proxy_config.use_forwarding_for_https\n ):\n return False\n\n # Otherwise always use a tunnel.\n return True" }, { "identifier": "Retry", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/util/retry.py", "snippet": "class Retry(object):\n \"\"\"Retry configuration.\n\n Each retry attempt will create a new Retry object with updated values, so\n they can be safely reused.\n\n Retries can be defined as a default for a pool::\n\n retries = Retry(connect=5, read=2, redirect=5)\n http = PoolManager(retries=retries)\n response = http.request('GET', 'http://example.com/')\n\n Or per-request (which overrides the default for the pool)::\n\n response = http.request('GET', 'http://example.com/', retries=Retry(10))\n\n Retries can be disabled by passing ``False``::\n\n response = http.request('GET', 'http://example.com/', retries=False)\n\n Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless\n retries are disabled, in which case the causing exception will be raised.\n\n :param int total:\n Total number of retries to allow. Takes precedence over other counts.\n\n Set to ``None`` to remove this constraint and fall back on other\n counts.\n\n Set to ``0`` to fail on the first retry.\n\n Set to ``False`` to disable and imply ``raise_on_redirect=False``.\n\n :param int connect:\n How many connection-related errors to retry on.\n\n These are errors raised before the request is sent to the remote server,\n which we assume has not triggered the server to process the request.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int read:\n How many times to retry on read errors.\n\n These errors are raised after the request was sent to the server, so the\n request may have side-effects.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int redirect:\n How many redirects to perform. Limit this to avoid infinite redirect\n loops.\n\n A redirect is a HTTP response with a status code 301, 302, 303, 307 or\n 308.\n\n Set to ``0`` to fail on the first retry of this type.\n\n Set to ``False`` to disable and imply ``raise_on_redirect=False``.\n\n :param int status:\n How many times to retry on bad status codes.\n\n These are retries made on responses, where status code matches\n ``status_forcelist``.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int other:\n How many times to retry on other errors.\n\n Other errors are errors that are not connect, read, redirect or status errors.\n These errors might be raised after the request was sent to the server, so the\n request might have side-effects.\n\n Set to ``0`` to fail on the first retry of this type.\n\n If ``total`` is not set, it's a good idea to set this to 0 to account\n for unexpected edge cases and avoid infinite retry loops.\n\n :param iterable allowed_methods:\n Set of uppercased HTTP method verbs that we should retry on.\n\n By default, we only retry on methods which are considered to be\n idempotent (multiple requests with the same parameters end with the\n same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`.\n\n Set to a ``False`` value to retry on any verb.\n\n .. warning::\n\n Previously this parameter was named ``method_whitelist``, that\n usage is deprecated in v1.26.0 and will be removed in v2.0.\n\n :param iterable status_forcelist:\n A set of integer HTTP status codes that we should force a retry on.\n A retry is initiated if the request method is in ``allowed_methods``\n and the response status code is in ``status_forcelist``.\n\n By default, this is disabled with ``None``.\n\n :param float backoff_factor:\n A backoff factor to apply between attempts after the second try\n (most errors are resolved immediately by a second try without a\n delay). urllib3 will sleep for::\n\n {backoff factor} * (2 ** ({number of total retries} - 1))\n\n seconds. If the backoff_factor is 0.1, then :func:`.sleep` will sleep\n for [0.0s, 0.2s, 0.4s, ...] between retries. It will never be longer\n than :attr:`Retry.DEFAULT_BACKOFF_MAX`.\n\n By default, backoff is disabled (set to 0).\n\n :param bool raise_on_redirect: Whether, if the number of redirects is\n exhausted, to raise a MaxRetryError, or to return a response with a\n response code in the 3xx range.\n\n :param bool raise_on_status: Similar meaning to ``raise_on_redirect``:\n whether we should raise an exception, or return a response,\n if status falls in ``status_forcelist`` range and retries have\n been exhausted.\n\n :param tuple history: The history of the request encountered during\n each call to :meth:`~Retry.increment`. The list is in the order\n the requests occurred. Each list item is of class :class:`RequestHistory`.\n\n :param bool respect_retry_after_header:\n Whether to respect Retry-After header on status codes defined as\n :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.\n\n :param iterable remove_headers_on_redirect:\n Sequence of headers to remove from the request when a response\n indicating a redirect is returned before firing off the redirected\n request.\n \"\"\"\n\n #: Default methods to be used for ``allowed_methods``\n DEFAULT_ALLOWED_METHODS = frozenset(\n [\"HEAD\", \"GET\", \"PUT\", \"DELETE\", \"OPTIONS\", \"TRACE\"]\n )\n\n #: Default status codes to be used for ``status_forcelist``\n RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])\n\n #: Default headers to be used for ``remove_headers_on_redirect``\n DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset([\"Cookie\", \"Authorization\"])\n\n #: Maximum backoff time.\n DEFAULT_BACKOFF_MAX = 120\n\n def __init__(\n self,\n total=10,\n connect=None,\n read=None,\n redirect=None,\n status=None,\n other=None,\n allowed_methods=_Default,\n status_forcelist=None,\n backoff_factor=0,\n raise_on_redirect=True,\n raise_on_status=True,\n history=None,\n respect_retry_after_header=True,\n remove_headers_on_redirect=_Default,\n # TODO: Deprecated, remove in v2.0\n method_whitelist=_Default,\n ):\n\n if method_whitelist is not _Default:\n if allowed_methods is not _Default:\n raise ValueError(\n \"Using both 'allowed_methods' and \"\n \"'method_whitelist' together is not allowed. \"\n \"Instead only use 'allowed_methods'\"\n )\n warnings.warn(\n \"Using 'method_whitelist' with Retry is deprecated and \"\n \"will be removed in v2.0. Use 'allowed_methods' instead\",\n DeprecationWarning,\n stacklevel=2,\n )\n allowed_methods = method_whitelist\n if allowed_methods is _Default:\n allowed_methods = self.DEFAULT_ALLOWED_METHODS\n if remove_headers_on_redirect is _Default:\n remove_headers_on_redirect = self.DEFAULT_REMOVE_HEADERS_ON_REDIRECT\n\n self.total = total\n self.connect = connect\n self.read = read\n self.status = status\n self.other = other\n\n if redirect is False or total is False:\n redirect = 0\n raise_on_redirect = False\n\n self.redirect = redirect\n self.status_forcelist = status_forcelist or set()\n self.allowed_methods = allowed_methods\n self.backoff_factor = backoff_factor\n self.raise_on_redirect = raise_on_redirect\n self.raise_on_status = raise_on_status\n self.history = history or tuple()\n self.respect_retry_after_header = respect_retry_after_header\n self.remove_headers_on_redirect = frozenset(\n [h.lower() for h in remove_headers_on_redirect]\n )\n\n def new(self, **kw):\n params = dict(\n total=self.total,\n connect=self.connect,\n read=self.read,\n redirect=self.redirect,\n status=self.status,\n other=self.other,\n status_forcelist=self.status_forcelist,\n backoff_factor=self.backoff_factor,\n raise_on_redirect=self.raise_on_redirect,\n raise_on_status=self.raise_on_status,\n history=self.history,\n remove_headers_on_redirect=self.remove_headers_on_redirect,\n respect_retry_after_header=self.respect_retry_after_header,\n )\n\n # TODO: If already given in **kw we use what's given to us\n # If not given we need to figure out what to pass. We decide\n # based on whether our class has the 'method_whitelist' property\n # and if so we pass the deprecated 'method_whitelist' otherwise\n # we use 'allowed_methods'. Remove in v2.0\n if \"method_whitelist\" not in kw and \"allowed_methods\" not in kw:\n if \"method_whitelist\" in self.__dict__:\n warnings.warn(\n \"Using 'method_whitelist' with Retry is deprecated and \"\n \"will be removed in v2.0. Use 'allowed_methods' instead\",\n DeprecationWarning,\n )\n params[\"method_whitelist\"] = self.allowed_methods\n else:\n params[\"allowed_methods\"] = self.allowed_methods\n\n params.update(kw)\n return type(self)(**params)\n\n @classmethod\n def from_int(cls, retries, redirect=True, default=None):\n \"\"\"Backwards-compatibility for the old retries format.\"\"\"\n if retries is None:\n retries = default if default is not None else cls.DEFAULT\n\n if isinstance(retries, Retry):\n return retries\n\n redirect = bool(redirect) and None\n new_retries = cls(retries, redirect=redirect)\n log.debug(\"Converted retries value: %r -> %r\", retries, new_retries)\n return new_retries\n\n def get_backoff_time(self):\n \"\"\"Formula for computing the current backoff\n\n :rtype: float\n \"\"\"\n # We want to consider only the last consecutive errors sequence (Ignore redirects).\n consecutive_errors_len = len(\n list(\n takewhile(lambda x: x.redirect_location is None, reversed(self.history))\n )\n )\n if consecutive_errors_len <= 1:\n return 0\n\n backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))\n return min(self.DEFAULT_BACKOFF_MAX, backoff_value)\n\n def parse_retry_after(self, retry_after):\n # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4\n if re.match(r\"^\\s*[0-9]+\\s*$\", retry_after):\n seconds = int(retry_after)\n else:\n retry_date_tuple = email.utils.parsedate_tz(retry_after)\n if retry_date_tuple is None:\n raise InvalidHeader(\"Invalid Retry-After header: %s\" % retry_after)\n if retry_date_tuple[9] is None: # Python 2\n # Assume UTC if no timezone was specified\n # On Python2.7, parsedate_tz returns None for a timezone offset\n # instead of 0 if no timezone is given, where mktime_tz treats\n # a None timezone offset as local time.\n retry_date_tuple = retry_date_tuple[:9] + (0,) + retry_date_tuple[10:]\n\n retry_date = email.utils.mktime_tz(retry_date_tuple)\n seconds = retry_date - time.time()\n\n if seconds < 0:\n seconds = 0\n\n return seconds\n\n def get_retry_after(self, response):\n \"\"\"Get the value of Retry-After in seconds.\"\"\"\n\n retry_after = response.headers.get(\"Retry-After\")\n\n if retry_after is None:\n return None\n\n return self.parse_retry_after(retry_after)\n\n def sleep_for_retry(self, response=None):\n retry_after = self.get_retry_after(response)\n if retry_after:\n time.sleep(retry_after)\n return True\n\n return False\n\n def _sleep_backoff(self):\n backoff = self.get_backoff_time()\n if backoff <= 0:\n return\n time.sleep(backoff)\n\n def sleep(self, response=None):\n \"\"\"Sleep between retry attempts.\n\n This method will respect a server's ``Retry-After`` response header\n and sleep the duration of the time requested. If that is not present, it\n will use an exponential backoff. By default, the backoff factor is 0 and\n this method will return immediately.\n \"\"\"\n\n if self.respect_retry_after_header and response:\n slept = self.sleep_for_retry(response)\n if slept:\n return\n\n self._sleep_backoff()\n\n def _is_connection_error(self, err):\n \"\"\"Errors when we're fairly sure that the server did not receive the\n request, so it should be safe to retry.\n \"\"\"\n if isinstance(err, ProxyError):\n err = err.original_error\n return isinstance(err, ConnectTimeoutError)\n\n def _is_read_error(self, err):\n \"\"\"Errors that occur after the request has been started, so we should\n assume that the server began processing it.\n \"\"\"\n return isinstance(err, (ReadTimeoutError, ProtocolError))\n\n def _is_method_retryable(self, method):\n \"\"\"Checks if a given HTTP method should be retried upon, depending if\n it is included in the allowed_methods\n \"\"\"\n # TODO: For now favor if the Retry implementation sets its own method_whitelist\n # property outside of our constructor to avoid breaking custom implementations.\n if \"method_whitelist\" in self.__dict__:\n warnings.warn(\n \"Using 'method_whitelist' with Retry is deprecated and \"\n \"will be removed in v2.0. Use 'allowed_methods' instead\",\n DeprecationWarning,\n )\n allowed_methods = self.method_whitelist\n else:\n allowed_methods = self.allowed_methods\n\n if allowed_methods and method.upper() not in allowed_methods:\n return False\n return True\n\n def is_retry(self, method, status_code, has_retry_after=False):\n \"\"\"Is this method/status code retryable? (Based on allowlists and control\n variables such as the number of total retries to allow, whether to\n respect the Retry-After header, whether this header is present, and\n whether the returned status code is on the list of status codes to\n be retried upon on the presence of the aforementioned header)\n \"\"\"\n if not self._is_method_retryable(method):\n return False\n\n if self.status_forcelist and status_code in self.status_forcelist:\n return True\n\n return (\n self.total\n and self.respect_retry_after_header\n and has_retry_after\n and (status_code in self.RETRY_AFTER_STATUS_CODES)\n )\n\n def is_exhausted(self):\n \"\"\"Are we out of retries?\"\"\"\n retry_counts = (\n self.total,\n self.connect,\n self.read,\n self.redirect,\n self.status,\n self.other,\n )\n retry_counts = list(filter(None, retry_counts))\n if not retry_counts:\n return False\n\n return min(retry_counts) < 0\n\n def increment(\n self,\n method=None,\n url=None,\n response=None,\n error=None,\n _pool=None,\n _stacktrace=None,\n ):\n \"\"\"Return a new Retry object with incremented retry counters.\n\n :param response: A response object, or None, if the server did not\n return a response.\n :type response: :class:`~urllib3.response.HTTPResponse`\n :param Exception error: An error encountered during the request, or\n None if the response was received successfully.\n\n :return: A new ``Retry`` object.\n \"\"\"\n if self.total is False and error:\n # Disabled, indicate to re-raise the error.\n raise six.reraise(type(error), error, _stacktrace)\n\n total = self.total\n if total is not None:\n total -= 1\n\n connect = self.connect\n read = self.read\n redirect = self.redirect\n status_count = self.status\n other = self.other\n cause = \"unknown\"\n status = None\n redirect_location = None\n\n if error and self._is_connection_error(error):\n # Connect retry?\n if connect is False:\n raise six.reraise(type(error), error, _stacktrace)\n elif connect is not None:\n connect -= 1\n\n elif error and self._is_read_error(error):\n # Read retry?\n if read is False or not self._is_method_retryable(method):\n raise six.reraise(type(error), error, _stacktrace)\n elif read is not None:\n read -= 1\n\n elif error:\n # Other retry?\n if other is not None:\n other -= 1\n\n elif response and response.get_redirect_location():\n # Redirect retry?\n if redirect is not None:\n redirect -= 1\n cause = \"too many redirects\"\n redirect_location = response.get_redirect_location()\n status = response.status\n\n else:\n # Incrementing because of a server error like a 500 in\n # status_forcelist and the given method is in the allowed_methods\n cause = ResponseError.GENERIC_ERROR\n if response and response.status:\n if status_count is not None:\n status_count -= 1\n cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status)\n status = response.status\n\n history = self.history + (\n RequestHistory(method, url, error, status, redirect_location),\n )\n\n new_retry = self.new(\n total=total,\n connect=connect,\n read=read,\n redirect=redirect,\n status=status_count,\n other=other,\n history=history,\n )\n\n if new_retry.is_exhausted():\n raise MaxRetryError(_pool, url, error or ResponseError(cause))\n\n log.debug(\"Incremented Retry for (url='%s'): %r\", url, new_retry)\n\n return new_retry\n\n def __repr__(self):\n return (\n \"{cls.__name__}(total={self.total}, connect={self.connect}, \"\n \"read={self.read}, redirect={self.redirect}, status={self.status})\"\n ).format(cls=type(self), self=self)\n\n def __getattr__(self, item):\n if item == \"method_whitelist\":\n # TODO: Remove this deprecated alias in v2.0\n warnings.warn(\n \"Using 'method_whitelist' with Retry is deprecated and \"\n \"will be removed in v2.0. Use 'allowed_methods' instead\",\n DeprecationWarning,\n )\n return self.allowed_methods\n try:\n return getattr(super(Retry, self), item)\n except AttributeError:\n return getattr(Retry, item)" }, { "identifier": "parse_url", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/util/url.py", "snippet": "def parse_url(url):\n \"\"\"\n Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is\n performed to parse incomplete urls. Fields not provided will be None.\n This parser is RFC 3986 and RFC 6874 compliant.\n\n The parser logic and helper functions are based heavily on\n work done in the ``rfc3986`` module.\n\n :param str url: URL to parse into a :class:`.Url` namedtuple.\n\n Partly backwards-compatible with :mod:`urlparse`.\n\n Example::\n\n >>> parse_url('http://google.com/mail/')\n Url(scheme='http', host='google.com', port=None, path='/mail/', ...)\n >>> parse_url('google.com:80')\n Url(scheme=None, host='google.com', port=80, path=None, ...)\n >>> parse_url('/foo?bar')\n Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)\n \"\"\"\n if not url:\n # Empty\n return Url()\n\n source_url = url\n if not SCHEME_RE.search(url):\n url = \"//\" + url\n\n try:\n scheme, authority, path, query, fragment = URI_RE.match(url).groups()\n normalize_uri = scheme is None or scheme.lower() in NORMALIZABLE_SCHEMES\n\n if scheme:\n scheme = scheme.lower()\n\n if authority:\n auth, _, host_port = authority.rpartition(\"@\")\n auth = auth or None\n host, port = _HOST_PORT_RE.match(host_port).groups()\n if auth and normalize_uri:\n auth = _encode_invalid_chars(auth, USERINFO_CHARS)\n if port == \"\":\n port = None\n else:\n auth, host, port = None, None, None\n\n if port is not None:\n port = int(port)\n if not (0 <= port <= 65535):\n raise LocationParseError(url)\n\n host = _normalize_host(host, scheme)\n\n if normalize_uri and path:\n path = _remove_path_dot_segments(path)\n path = _encode_invalid_chars(path, PATH_CHARS)\n if normalize_uri and query:\n query = _encode_invalid_chars(query, QUERY_CHARS)\n if normalize_uri and fragment:\n fragment = _encode_invalid_chars(fragment, FRAGMENT_CHARS)\n\n except (ValueError, AttributeError):\n return six.raise_from(LocationParseError(source_url), None)\n\n # For the sake of backwards compatibility we put empty\n # string values for path if there are any defined values\n # beyond the path in the URL.\n # TODO: Remove this when we break backwards compatibility.\n if not path:\n if query is not None or fragment is not None:\n path = \"\"\n else:\n path = None\n\n # Ensure that each part of the URL is a `str` for\n # backwards compatibility.\n if isinstance(url, six.text_type):\n ensure_func = six.ensure_text\n else:\n ensure_func = six.ensure_str\n\n def ensure_type(x):\n return x if x is None else ensure_func(x)\n\n return Url(\n scheme=ensure_type(scheme),\n auth=ensure_type(auth),\n host=ensure_type(host),\n port=port,\n path=ensure_type(path),\n query=ensure_type(query),\n fragment=ensure_type(fragment),\n )" } ]
import collections import functools import logging from ._collections import HTTPHeaderDict, RecentlyUsedContainer from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme from .exceptions import ( LocationValueError, MaxRetryError, ProxySchemeUnknown, ProxySchemeUnsupported, URLSchemeUnknown, ) from .packages import six from .packages.six.moves.urllib.parse import urljoin from .request import RequestMethods from .util.proxy import connection_requires_http_tunnel from .util.retry import Retry from .util.url import parse_url
14,704
# connections, open a new ConnectionPool. pool = self.pools.get(pool_key) if pool: return pool # Make a fresh ConnectionPool of the desired type scheme = request_context["scheme"] host = request_context["host"] port = request_context["port"] pool = self._new_pool(scheme, host, port, request_context=request_context) self.pools[pool_key] = pool return pool def connection_from_url(self, url, pool_kwargs=None): """ Similar to :func:`urllib3.connectionpool.connection_from_url`. If ``pool_kwargs`` is not provided and a new pool needs to be constructed, ``self.connection_pool_kw`` is used to initialize the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs`` is provided, it is used instead. Note that if a new pool does not need to be created for the request, the provided ``pool_kwargs`` are not used. """ u = parse_url(url) return self.connection_from_host( u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs ) def _merge_pool_kwargs(self, override): """ Merge a dictionary of override values for self.connection_pool_kw. This does not modify self.connection_pool_kw and returns a new dict. Any keys in the override dictionary with a value of ``None`` are removed from the merged dictionary. """ base_pool_kwargs = self.connection_pool_kw.copy() if override: for key, value in override.items(): if value is None: try: del base_pool_kwargs[key] except KeyError: pass else: base_pool_kwargs[key] = value return base_pool_kwargs def _proxy_requires_url_absolute_form(self, parsed_url): """ Indicates if the proxy requires the complete destination URL in the request. Normally this is only needed when not using an HTTP CONNECT tunnel. """ if self.proxy is None: return False return not connection_requires_http_tunnel( self.proxy, self.proxy_config, parsed_url.scheme ) def _validate_proxy_scheme_url_selection(self, url_scheme): """ Validates that were not attempting to do TLS in TLS connections on Python2 or with unsupported SSL implementations. """ if self.proxy is None or url_scheme != "https": return if self.proxy.scheme != "https": return if six.PY2 and not self.proxy_config.use_forwarding_for_https: raise ProxySchemeUnsupported( "Contacting HTTPS destinations through HTTPS proxies " "'via CONNECT tunnels' is not supported in Python 2" ) def urlopen(self, method, url, redirect=True, **kw): """ Same as :meth:`urllib3.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``. The given ``url`` parameter must be absolute, such that an appropriate :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it. """ u = parse_url(url) self._validate_proxy_scheme_url_selection(u.scheme) conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme) kw["assert_same_host"] = False kw["redirect"] = False if "headers" not in kw: kw["headers"] = self.headers.copy() if self._proxy_requires_url_absolute_form(u): response = conn.urlopen(method, url, **kw) else: response = conn.urlopen(method, u.request_uri, **kw) redirect_location = redirect and response.get_redirect_location() if not redirect_location: return response # Support relative URLs for redirecting. redirect_location = urljoin(url, redirect_location) if response.status == 303: # Change the method according to RFC 9110, Section 15.4.4. method = "GET" # And lose the body not to transfer anything sensitive. kw["body"] = None kw["headers"] = HTTPHeaderDict(kw["headers"])._prepare_for_method_change() retries = kw.get("retries")
from __future__ import absolute_import __all__ = ["PoolManager", "ProxyManager", "proxy_from_url"] log = logging.getLogger(__name__) SSL_KEYWORDS = ( "key_file", "cert_file", "cert_reqs", "ca_certs", "ssl_version", "ca_cert_dir", "ssl_context", "key_password", "server_hostname", ) # All known keyword arguments that could be provided to the pool manager, its # pools, or the underlying connections. This is used to construct a pool key. _key_fields = ( "key_scheme", # str "key_host", # str "key_port", # int "key_timeout", # int or float or Timeout "key_retries", # int or Retry "key_strict", # bool "key_block", # bool "key_source_address", # str "key_key_file", # str "key_key_password", # str "key_cert_file", # str "key_cert_reqs", # str "key_ca_certs", # str "key_ssl_version", # str "key_ca_cert_dir", # str "key_ssl_context", # instance of ssl.SSLContext or urllib3.util.ssl_.SSLContext "key_maxsize", # int "key_headers", # dict "key__proxy", # parsed proxy url "key__proxy_headers", # dict "key__proxy_config", # class "key_socket_options", # list of (level (int), optname (int), value (int or str)) tuples "key__socks_options", # dict "key_assert_hostname", # bool or string "key_assert_fingerprint", # str "key_server_hostname", # str ) #: The namedtuple class used to construct keys for the connection pool. #: All custom key schemes should include the fields in this key at a minimum. PoolKey = collections.namedtuple("PoolKey", _key_fields) _proxy_config_fields = ("ssl_context", "use_forwarding_for_https") ProxyConfig = collections.namedtuple("ProxyConfig", _proxy_config_fields) def _default_key_normalizer(key_class, request_context): """ Create a pool key out of a request context dictionary. According to RFC 3986, both the scheme and host are case-insensitive. Therefore, this function normalizes both before constructing the pool key for an HTTPS request. If you wish to change this behaviour, provide alternate callables to ``key_fn_by_scheme``. :param key_class: The class to use when constructing the key. This should be a namedtuple with the ``scheme`` and ``host`` keys at a minimum. :type key_class: namedtuple :param request_context: A dictionary-like object that contain the context for a request. :type request_context: dict :return: A namedtuple that can be used as a connection pool key. :rtype: PoolKey """ # Since we mutate the dictionary, make a copy first context = request_context.copy() context["scheme"] = context["scheme"].lower() context["host"] = context["host"].lower() # These are both dictionaries and need to be transformed into frozensets for key in ("headers", "_proxy_headers", "_socks_options"): if key in context and context[key] is not None: context[key] = frozenset(context[key].items()) # The socket_options key may be a list and needs to be transformed into a # tuple. socket_opts = context.get("socket_options") if socket_opts is not None: context["socket_options"] = tuple(socket_opts) # Map the kwargs to the names in the namedtuple - this is necessary since # namedtuples can't have fields starting with '_'. for key in list(context.keys()): context["key_" + key] = context.pop(key) # Default to ``None`` for keys missing from the context for field in key_class._fields: if field not in context: context[field] = None return key_class(**context) #: A dictionary that maps a scheme to a callable that creates a pool key. #: This can be used to alter the way pool keys are constructed, if desired. #: Each PoolManager makes a copy of this dictionary so they can be configured #: globally here, or individually on the instance. key_fn_by_scheme = { "http": functools.partial(_default_key_normalizer, PoolKey), "https": functools.partial(_default_key_normalizer, PoolKey), } pool_classes_by_scheme = {"http": HTTPConnectionPool, "https": HTTPSConnectionPool} class PoolManager(RequestMethods): """ Allows for arbitrary requests while transparently keeping track of necessary connection pools for you. :param num_pools: Number of connection pools to cache before discarding the least recently used pool. :param headers: Headers to include with all requests, unless other headers are given explicitly. :param \\**connection_pool_kw: Additional parameters are used to create fresh :class:`urllib3.connectionpool.ConnectionPool` instances. Example:: >>> manager = PoolManager(num_pools=2) >>> r = manager.request('GET', 'http://google.com/') >>> r = manager.request('GET', 'http://google.com/mail') >>> r = manager.request('GET', 'http://yahoo.com/') >>> len(manager.pools) 2 """ proxy = None proxy_config = None def __init__(self, num_pools=10, headers=None, **connection_pool_kw): RequestMethods.__init__(self, headers) self.connection_pool_kw = connection_pool_kw self.pools = RecentlyUsedContainer(num_pools) # Locally set the pool classes and keys so other PoolManagers can # override them. self.pool_classes_by_scheme = pool_classes_by_scheme self.key_fn_by_scheme = key_fn_by_scheme.copy() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.clear() # Return False to re-raise any potential exceptions return False def _new_pool(self, scheme, host, port, request_context=None): """ Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and any additional pool keyword arguments. If ``request_context`` is provided, it is provided as keyword arguments to the pool class used. This method is used to actually create the connection pools handed out by :meth:`connection_from_url` and companion methods. It is intended to be overridden for customization. """ pool_cls = self.pool_classes_by_scheme[scheme] if request_context is None: request_context = self.connection_pool_kw.copy() # Although the context has everything necessary to create the pool, # this function has historically only used the scheme, host, and port # in the positional args. When an API change is acceptable these can # be removed. for key in ("scheme", "host", "port"): request_context.pop(key, None) if scheme == "http": for kw in SSL_KEYWORDS: request_context.pop(kw, None) return pool_cls(host, port, **request_context) def clear(self): """ Empty our store of pools and direct them all to close. This will not affect in-flight connections, but they will not be re-used after completion. """ self.pools.clear() def connection_from_host(self, host, port=None, scheme="http", pool_kwargs=None): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is provided, it is merged with the instance's ``connection_pool_kw`` variable and used to create the new connection pool, if one is needed. """ if not host: raise LocationValueError("No host specified.") request_context = self._merge_pool_kwargs(pool_kwargs) request_context["scheme"] = scheme or "http" if not port: port = port_by_scheme.get(request_context["scheme"].lower(), 80) request_context["port"] = port request_context["host"] = host return self.connection_from_context(request_context) def connection_from_context(self, request_context): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context. ``request_context`` must at least contain the ``scheme`` key and its value must be a key in ``key_fn_by_scheme`` instance variable. """ scheme = request_context["scheme"].lower() pool_key_constructor = self.key_fn_by_scheme.get(scheme) if not pool_key_constructor: raise URLSchemeUnknown(scheme) pool_key = pool_key_constructor(request_context) return self.connection_from_pool_key(pool_key, request_context=request_context) def connection_from_pool_key(self, pool_key, request_context=None): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the provided pool key. ``pool_key`` should be a namedtuple that only contains immutable objects. At a minimum it must have the ``scheme``, ``host``, and ``port`` fields. """ with self.pools.lock: # If the scheme, host, or port doesn't match existing open # connections, open a new ConnectionPool. pool = self.pools.get(pool_key) if pool: return pool # Make a fresh ConnectionPool of the desired type scheme = request_context["scheme"] host = request_context["host"] port = request_context["port"] pool = self._new_pool(scheme, host, port, request_context=request_context) self.pools[pool_key] = pool return pool def connection_from_url(self, url, pool_kwargs=None): """ Similar to :func:`urllib3.connectionpool.connection_from_url`. If ``pool_kwargs`` is not provided and a new pool needs to be constructed, ``self.connection_pool_kw`` is used to initialize the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs`` is provided, it is used instead. Note that if a new pool does not need to be created for the request, the provided ``pool_kwargs`` are not used. """ u = parse_url(url) return self.connection_from_host( u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs ) def _merge_pool_kwargs(self, override): """ Merge a dictionary of override values for self.connection_pool_kw. This does not modify self.connection_pool_kw and returns a new dict. Any keys in the override dictionary with a value of ``None`` are removed from the merged dictionary. """ base_pool_kwargs = self.connection_pool_kw.copy() if override: for key, value in override.items(): if value is None: try: del base_pool_kwargs[key] except KeyError: pass else: base_pool_kwargs[key] = value return base_pool_kwargs def _proxy_requires_url_absolute_form(self, parsed_url): """ Indicates if the proxy requires the complete destination URL in the request. Normally this is only needed when not using an HTTP CONNECT tunnel. """ if self.proxy is None: return False return not connection_requires_http_tunnel( self.proxy, self.proxy_config, parsed_url.scheme ) def _validate_proxy_scheme_url_selection(self, url_scheme): """ Validates that were not attempting to do TLS in TLS connections on Python2 or with unsupported SSL implementations. """ if self.proxy is None or url_scheme != "https": return if self.proxy.scheme != "https": return if six.PY2 and not self.proxy_config.use_forwarding_for_https: raise ProxySchemeUnsupported( "Contacting HTTPS destinations through HTTPS proxies " "'via CONNECT tunnels' is not supported in Python 2" ) def urlopen(self, method, url, redirect=True, **kw): """ Same as :meth:`urllib3.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``. The given ``url`` parameter must be absolute, such that an appropriate :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it. """ u = parse_url(url) self._validate_proxy_scheme_url_selection(u.scheme) conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme) kw["assert_same_host"] = False kw["redirect"] = False if "headers" not in kw: kw["headers"] = self.headers.copy() if self._proxy_requires_url_absolute_form(u): response = conn.urlopen(method, url, **kw) else: response = conn.urlopen(method, u.request_uri, **kw) redirect_location = redirect and response.get_redirect_location() if not redirect_location: return response # Support relative URLs for redirecting. redirect_location = urljoin(url, redirect_location) if response.status == 303: # Change the method according to RFC 9110, Section 15.4.4. method = "GET" # And lose the body not to transfer anything sensitive. kw["body"] = None kw["headers"] = HTTPHeaderDict(kw["headers"])._prepare_for_method_change() retries = kw.get("retries")
if not isinstance(retries, Retry):
11
2023-11-27 07:01:39+00:00
24k
NobiDeveloper/Nobita-Filter-Bot
plugins/p_ttishow.py
[ { "identifier": "ADMINS", "path": "info.py", "snippet": "ADMINS = [int(admin) if id_pattern.search(admin) else admin for admin in environ.get('ADMINS', '').split()]" }, { "identifier": "LOG_CHANNEL", "path": "info.py", "snippet": "LOG_CHANNEL = int(environ.get('LOG_CHANNEL', ''))" }, { "identifier": "SUPPORT_CHAT", "path": "info.py", "snippet": "SUPPORT_CHAT = environ.get('SUPPORT_CHAT', 'NobiDeveloperSupport')" }, { "identifier": "MELCOW_NEW_USERS", "path": "info.py", "snippet": "MELCOW_NEW_USERS = is_enabled((environ.get('MELCOW_NEW_USERS', \"True\")), True)" }, { "identifier": "MELCOW_VID", "path": "info.py", "snippet": "MELCOW_VID = environ.get(\"MELCOW_VID\", \"https://telegra.ph/file/61ef9818986cef9554017.jpg\")" }, { "identifier": "CHNL_LNK", "path": "info.py", "snippet": "CHNL_LNK = environ.get('CHNL_LNK', 'https://telegram.me/NobiDeveloper')" }, { "identifier": "GRP_LNK", "path": "info.py", "snippet": "GRP_LNK = environ.get('GRP_LNK', 'https://telegram.me/NobiDeveloperSupport')" }, { "identifier": "db", "path": "database/users_chats_db.py", "snippet": "class Database:\n def __init__(self, uri, database_name):\n def new_user(self, id, name):\n def new_group(self, id, title):\n async def add_user(self, id, name):\n async def is_user_exist(self, id):\n async def total_users_count(self):\n async def remove_ban(self, id):\n async def ban_user(self, user_id, ban_reason=\"No Reason\"):\n async def get_ban_status(self, id):\n async def get_all_users(self):\n async def delete_user(self, user_id):\n async def get_banned(self):\n async def add_chat(self, chat, title):\n async def get_chat(self, chat):\n async def re_enable_chat(self, id):\n async def update_settings(self, id, settings):\n async def get_settings(self, id):\n async def disable_chat(self, chat, reason=\"No Reason\"):\n async def total_chat_count(self):\n async def get_all_chats(self):\n async def get_db_size(self):" }, { "identifier": "Media", "path": "database/ia_filterdb.py", "snippet": "class Media(Document):\n file_id = fields.StrField(attribute='_id')\n file_ref = fields.StrField(allow_none=True)\n file_name = fields.StrField(required=True)\n file_size = fields.IntField(required=True)\n file_type = fields.StrField(allow_none=True)\n mime_type = fields.StrField(allow_none=True)\n caption = fields.StrField(allow_none=True)\n\n class Meta:\n indexes = ('$file_name', )\n collection_name = COLLECTION_NAME" }, { "identifier": "get_size", "path": "utils.py", "snippet": "def get_size(size):\n \"\"\"Get size in readable format\"\"\"\n\n units = [\"Bytes\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\"]\n size = float(size)\n i = 0\n while size >= 1024.0 and i < len(units):\n i += 1\n size /= 1024.0\n return \"%.2f %s\" % (size, units[i])" }, { "identifier": "temp", "path": "utils.py", "snippet": "class temp(object):\n BANNED_USERS = []\n BANNED_CHATS = []\n ME = None\n CURRENT=int(os.environ.get(\"SKIP\", 2))\n CANCEL = False\n MELCOW = {}\n U_NAME = None\n B_NAME = None\n GETALL = {}\n SHORT = {}\n SETTINGS = {}" }, { "identifier": "get_settings", "path": "utils.py", "snippet": "async def get_settings(group_id):\n settings = temp.SETTINGS.get(group_id)\n if not settings:\n settings = await db.get_settings(group_id)\n temp.SETTINGS[group_id] = settings\n return settings" }, { "identifier": "script", "path": "Script.py", "snippet": "class script(object):\n START_TXT = \"\"\"\n<b>{},\n\nɪ ᴄᴀɴ ᴘʀᴏᴠɪᴅᴇ ᴍᴏᴠɪᴇs ᴀɴᴅ sᴇʀɪᴇs,\nᴊᴜsᴛ ᴀᴅᴅ ᴍᴇ ᴛᴏ ʏᴏᴜʀ ɢʀᴏᴜᴘ ᴀɴᴅ ᴇɴᴊᴏʏ 😍\n\n💞 ᴍᴀɪɴᴛᴀɪɴᴇᴅ ʙʏ : <a href='https://telegram.me/MovieVillaYT'>ᴍᴏᴠɪᴇ ᴠɪʟʟᴀ</a></b>\n\"\"\"\n\n HELP_TXT = \"\"\"\n<b>{},\n\n/g_info - ᴛᴏ ᴄʜᴇᴄᴋ ʏᴏᴜʀ ᴠᴀʟᴜᴇꜱ\n/set_tutorial - ᴛᴏ ꜱᴇᴛ ᴄᴜꜱᴛᴏᴍ ᴛᴜᴛᴏʀɪᴀʟ\n/set_shortlink - ᴛᴏ ꜱᴇᴛ ᴄᴜꜱᴛᴏᴍ ꜱʜᴏʀᴛᴇɴᴇʀ\n/rem_tutorial - ᴛᴏ ʀᴇᴍᴏᴠᴇ ᴛᴜᴛᴏʀɪᴀʟ ʟɪɴᴋ\n</b>\"\"\"\n\n ABOUT_TXT = \"\"\"<b>➣ ᴍʏ ɴᴀᴍᴇ ⋟</b> {}\n<b>➢ ᴄʀᴇᴀᴛᴏʀ ⋟</b> <a href=https://youtube.com/@NobiDeveloper>𝘔𝘖𝘝𝘐𝘌 𝘝𝘐𝘓𝘓𝘈</a>\n<b>➣ ʟɪʙʀᴀʀʏ ⋟</b> 𝘱𝘺𝘳𝘰𝘨𝘳𝘢𝘮\n<b>➢ ʟᴀɴɢᴜᴀɢᴇ ⋟</b> 𝘱𝘺𝘵𝘩𝘰𝘯 3\n<b>➣ ᴅᴀᴛᴀʙᴀsᴇ ⋟</b> 𝘮𝘰𝘯𝘨𝘰 𝘥𝘣\n<b>➢ ʙᴏᴛ sᴇʀᴠᴇʀ ⋟</b> 𝘩𝘦𝘳𝘰𝘬𝘶\n<b>➣ ʙᴜɪʟᴅ sᴛᴀᴛs ⋟</b> 𝘷2.0.1 ﹝ʙᴇᴛᴀ﹞\"\"\"\n\n SOURCE_TXT = \"\"\"\n<b>ᴛʜɪꜱ ɪꜱ ᴀɴ ᴏᴘᴇɴ ꜱᴏᴜʀᴄᴇ ᴘʀᴏᴊᴇᴄᴛ.</b>\n\nᴀʟʟ ᴛʜᴇ ꜰɪʟᴇꜱ ɪɴ ᴛʜɪꜱ ʙᴏᴛ ᴀʀᴇ ꜰʀᴇᴇʟʏ ᴀᴠᴀɪʟᴀʙʟᴇ ᴏɴ ᴛʜᴇ ɪɴᴛᴇʀɴᴇᴛ ᴏʀ ᴘᴏꜱᴛᴇᴅ ʙʏ ꜱᴏᴍᴇʙᴏᴅʏ ᴇʟꜱᴇ. ᴊᴜꜱᴛ ꜰᴏʀ ᴇᴀꜱʏ ꜱᴇᴀʀᴄʜɪɴɢ ᴛʜɪꜱ ʙᴏᴛ ɪꜱ ɪɴᴅᴇxɪɴɢ ꜰɪʟᴇꜱ ᴡʜɪᴄʜ ᴀʀᴇ ᴀʟʀᴇᴀᴅʏ ᴜᴘʟᴏᴀᴅᴇᴅ ᴏɴ ᴛᴇʟᴇɢʀᴀᴍ. ᴡᴇ ʀᴇꜱᴘᴇᴄᴛ ᴀʟʟ ᴛʜᴇ ᴄᴏᴘʏʀɪɢʜᴛ ʟᴀᴡꜱ ᴀɴᴅ ᴡᴏʀᴋꜱ ɪɴ ᴄᴏᴍᴘʟɪᴀɴᴄᴇ ᴡɪᴛʜ ᴅᴍᴄᴀ ᴀɴᴅ ᴇᴜᴄᴅ. ɪꜰ ᴀɴʏᴛʜɪɴɢ ɪꜱ ᴀɢᴀɪɴꜱᴛ ʟᴀᴡ ᴘʟᴇᴀꜱᴇ ᴄᴏɴᴛᴀᴄᴛ ᴍᴇ ꜱᴏ ᴛʜᴀᴛ ɪᴛ ᴄᴀɴ ʙᴇ ʀᴇᴍᴏᴠᴇᴅ ᴀꜱᴀᴘ. ɪᴛ ɪꜱ ꜰᴏʀʙɪʙʙᴇɴ ᴛᴏ ᴅᴏᴡɴʟᴏᴀᴅ, ꜱᴛʀᴇᴀᴍ, ʀᴇᴘʀᴏᴅᴜᴄᴇ, ᴏʀ ʙʏ ᴀɴʏ ᴍᴇᴀɴꜱ, ꜱʜᴀʀᴇ, ᴏʀ ᴄᴏɴꜱᴜᴍᴇ, ᴄᴏɴᴛᴇɴᴛ ᴡɪᴛʜᴏᴜᴛ ᴇxᴘʟɪᴄɪᴛ ᴘᴇʀᴍɪꜱꜱɪᴏɴ ꜰʀᴏᴍ ᴛʜᴇ ᴄᴏɴᴛᴇɴᴛ ᴄʀᴇᴀᴛᴏʀ ᴏʀ ʟᴇɢᴀʟ ᴄᴏᴘʏʀɪɢʜᴛ ʜᴏʟᴅᴇʀ. ɪꜰ ʏᴏᴜ ʙᴇʟɪᴇᴠᴇ ᴛʜɪꜱ ʙᴏᴛ ɪꜱ ᴠɪᴏʟᴀᴛɪɴɢ ʏᴏᴜʀ ɪɴᴛᴇʟʟᴇᴄᴛᴜᴀʟ ᴘʀᴏᴘᴇʀᴛʏ, ᴄᴏɴᴛᴀᴄᴛ ᴛʜᴇ ʀᴇꜱᴘᴇᴄᴛɪᴠᴇ ᴄʜᴀɴɴᴇʟꜱ ꜰᴏʀ ʀᴇᴍᴏᴠᴀʟ. ᴛʜᴇ ʙᴏᴛ ᴅᴏᴇꜱ ɴᴏᴛ ᴏᴡɴ ᴀɴʏ ᴏꜰ ᴛʜᴇꜱᴇ ᴄᴏɴᴛᴇɴᴛꜱ, ɪᴛ ᴏɴʟʏ ɪɴᴅᴇx ᴛʜᴇ ꜰɪʟᴇꜱ ꜰʀᴏᴍ ᴛᴇʟᴇɢʀᴀᴍ.\n\n<b><a href=https://telegram.me/NobiDeveloper>~ ᴍᴀɪɴᴛᴀɪɴᴇᴅ ʙʏ @MovieVillaYT</a></b>\n\"\"\"\n\n MANUELFILTER_TXT = \"\"\"\n<b>{},\n\n~ ʏᴏᴜ ᴄᴀɴ ᴇᴀsɪʟʏ ᴄᴜsᴛᴏᴍɪᴢᴇ ᴛʜɪs ʙᴏᴛ ꜰᴏʀ ʏᴏᴜʀ ɢʀᴏᴜᴘ.\n\n~ ᴏɴʟʏ ɢʀᴏᴜᴘ ᴀᴅᴍɪɴ ᴄᴀɴ ᴜsᴇ ᴛʜɪs ᴄᴏᴍᴍᴀɴᴅ ᴀɴᴅ ᴄʜᴀɴɢᴇs sᴇᴛᴛɪɴɢs.\n\n~ ɪᴛ ᴡᴏʀᴋs ᴏɴʟʏ ᴡʜᴇɴ ʏᴏᴜ ᴀʟʀᴇᴀᴅʏ ᴄᴏɴɴᴇᴄᴛ ʏᴏᴜʀ ɢʀᴏᴜᴘ.\n\nᴄᴏᴍᴍᴀɴᴅs ᴀɴᴅ ᴜsᴀɢᴇ -\n\n• /settings - ᴄʜᴀɴɢᴇ sᴇᴛᴛɪɴɢs ᴀs ʏᴏᴜʀ ᴡɪsʜ.</b>\n\"\"\"\n\n GROUP_TXT = \"\"\"\n<b>⍟ ᴄʜᴀɴɴᴇʟs ᴀɴᴅ ɢʀᴏᴜᴘs ᴍᴏᴅᴜʟᴇ ⍟</b>\n\n<b>🍿 ᴍᴏᴠɪᴇꜱ ᴄʜᴀɴɴᴇʟ.\n🗣️ ʙᴏᴛ sᴜᴘᴘᴏʀᴛ ɢʀᴏᴜᴘ.\n🚦 ʙᴏᴛ ᴜᴘᴅᴀᴛᴇs ᴄʜᴀɴɴᴇʟ.\n🎬 ᴍᴏᴠɪᴇ ʀᴇǫᴜᴇsᴛɪɴɢ ɢʀᴏᴜᴘ.</b>\"\"\"\n\n BUTTON_TXT = \"\"\"\n<b>💵 ɪ ʀᴇǫᴜᴇsᴛᴇᴅ ᴛᴏ ʏᴏᴜ 💸\n\nᴘʟᴇᴀsᴇ ᴅᴏɴᴀᴛᴇ ᴛʜᴇ ᴅᴇᴠᴇʟᴏᴘᴇʀ ꜰᴏʀ ᴋᴇᴇᴘɪɴɢ ᴛʜᴇ sᴇʀᴠɪᴄᴇ ᴀʟɪᴠᴇ & ᴋᴇᴇᴘ ʙʀɪɴɢɪɴɢ ᴍᴏʀᴇ ɴᴇᴡ ꜰᴇᴀᴛᴜʀᴇs ꜰᴏʀ ʏᴏᴜ....</b>\n\n𝐘𝐨𝐮 𝐂𝐚𝐧 𝐃𝐨𝐧𝐚𝐭𝐞 𝐀𝐧𝐲 𝐀𝐦𝐨𝐮𝐧𝐭 𝐘𝐨𝐮 𝐇𝐚𝐯𝐞 💷\n\n<b>᚜ ᴘᴀʏᴍᴇɴᴛ ᴍᴇᴛʜᴏᴅs ᚛</b>\n\n💵 <a href='https://telegra.ph/SUPPORT-12-22-2'>𝗚𝗼𝗼𝗴𝗹𝗲 𝗣𝗮𝘆</a>\n💸 <a href='https://telegra.ph/SUPPORT-12-22-2'>𝗣𝗮𝘆𝘁𝗺</a>\n💶 <a href='https://telegra.ph/SUPPORT-12-22-2'>𝗣𝗵𝗼𝗻𝗲𝗣𝗲</a>\n\n𝐂𝐨𝐧𝐭𝐚𝐜𝐭 𝐌𝐞 𝐅𝐨𝐫 𝐊𝐧𝐨𝐰 𝐀𝐛𝐨𝐮𝐭 𝐓𝐡𝐞 𝐏𝐚𝐲𝐦𝐞𝐧𝐭 𝐈𝐧𝐟𝐨\n\n<b>ᴄʟɪᴄᴋ ʜᴇʀᴇ - <a href='https://telegram.me/NobiDeveloperr'>ʙᴏss</a>\nᴄʟɪᴄᴋ ʜᴇʀᴇ - <a href='https://telegram.me/NobiDeveloperr'>ʙᴏss</a></b>\"\"\"\n\n AUTOFILTER_TXT = \"\"\"ʜᴇʟᴘ: <b>ᴀᴜᴛᴏ ꜰɪʟᴛᴇʀ</b>\n<b>ɴᴏᴛᴇ: Fɪʟᴇ Iɴᴅᴇx</b>\n1. ᴍᴀᴋᴇ ᴍᴇ ᴛʜᴇ ᴀᴅᴍɪɴ ᴏꜰ ʏᴏᴜʀ ᴄʜᴀɴɴᴇʟ ɪꜰ ɪᴛ'ꜱ ᴘʀɪᴠᴀᴛᴇ.\n2. ᴍᴀᴋᴇ ꜱᴜʀᴇ ᴛʜᴀᴛ ʏᴏᴜʀ ᴄʜᴀɴɴᴇʟ ᴅᴏᴇꜱ ɴᴏᴛ ᴄᴏɴᴛᴀɪɴꜱ ᴄᴀᴍʀɪᴘꜱ, ᴘᴏʀɴ ᴀɴᴅ ꜰᴀᴋᴇ ꜰɪʟᴇꜱ.\n3. ꜰᴏʀᴡᴀʀᴅ ᴛʜᴇ ʟᴀꜱᴛ ᴍᴇꜱꜱᴀɢᴇ ᴛᴏ ᴍᴇ ᴡɪᴛʜ Qᴜᴏᴛᴇꜱ. ɪ'ʟʟ ᴀᴅᴅ ᴀʟʟ ᴛʜᴇ ꜰɪʟᴇꜱ ɪɴ ᴛʜᴀᴛ ᴄʜᴀɴɴᴇʟ ᴛᴏ ᴍʏ ᴅʙ.\n\n<b>Nᴏᴛᴇ: AᴜᴛᴏFɪʟᴛᴇʀ</b>\n1. Aᴅᴅ ᴛʜᴇ ʙᴏᴛ ᴀs ᴀᴅᴍɪɴ ᴏɴ ʏᴏᴜʀ ɢʀᴏᴜᴘ.\n2. Usᴇ /connect ᴀɴᴅ ᴄᴏɴɴᴇᴄᴛ ʏᴏᴜʀ ɢʀᴏᴜᴘ ᴛᴏ ᴛʜᴇ ʙᴏᴛ.\n3. Usᴇ /settings ᴏɴ ʙᴏᴛ's PM ᴀɴᴅ ᴛᴜʀɴ ᴏɴ AᴜᴛᴏFɪʟᴛᴇʀ ᴏɴ ᴛʜᴇ sᴇᴛᴛɪɴɢs ᴍᴇɴᴜ.\"\"\"\n\n CONNECTION_TXT = \"\"\"ʜᴇʟᴘ: <b>ᴄᴏɴɴᴇᴄᴛɪᴏɴꜱ</b>\n- ᴜꜱᴇᴅ ᴛᴏ ᴄᴏɴɴᴇᴄᴛ ʙᴏᴛ ᴛᴏ ᴘᴍ ꜰᴏʀ ᴍᴀɴᴀɢɪɴɢ ꜰɪʟᴛᴇʀꜱ \n- ɪᴛ ʜᴇʟᴘꜱ ᴛᴏ ᴀᴠᴏɪᴅ ꜱᴘᴀᴍᴍɪɴɢ ɪɴ ɢʀᴏᴜᴘꜱ.\n<b>ɴᴏᴛᴇ:</b>\n1. ᴏɴʟʏ ᴀᴅᴍɪɴꜱ ᴄᴀɴ ᴀᴅᴅ ᴀ ᴄᴏɴɴᴇᴄᴛɪᴏɴ.\n2. ꜱᴇɴᴅ <code>/ᴄᴏɴɴᴇᴄᴛ</code> ꜰᴏʀ ᴄᴏɴɴᴇᴄᴛɪɴɢ ᴍᴇ ᴛᴏ ʏᴏᴜʀ ᴘᴍ\nCᴏᴍᴍᴀɴᴅs Aɴᴅ Usᴀɢᴇ:\n• /connect - <code>ᴄᴏɴɴᴇᴄᴛ ᴀ ᴘᴀʀᴛɪᴄᴜʟᴀʀ ᴄʜᴀᴛ ᴛᴏ ʏᴏᴜʀ ᴘᴍ</code>\n• /disconnect - <code>ᴅɪꜱᴄᴏɴɴᴇᴄᴛ ꜰʀᴏᴍ ᴀ ᴄʜᴀᴛ</code>\n• /connections - <code>ʟɪꜱᴛ ᴀʟʟ ʏᴏᴜʀ ᴄᴏɴɴᴇᴄᴛɪᴏɴꜱ</code>\"\"\"\n\n EXTRAMOD_TXT = \"\"\"ʜᴇʟᴘ: Exᴛʀᴀ Mᴏᴅᴜʟᴇs\n<b>ɴᴏᴛᴇ:</b>\nᴛʜᴇꜱᴇ ᴀʀᴇ ᴛʜᴇ ᴇxᴛʀᴀ ꜰᴇᴀᴛᴜʀᴇꜱ ᴏꜰ ᴛʜɪꜱ ʙᴏᴛ\nCᴏᴍᴍᴀɴᴅs Aɴᴅ Usᴀɢᴇ:\n• /id - <code>ɢᴇᴛ ɪᴅ ᴏꜰ ᴀ ꜱᴘᴇᴄɪꜰɪᴇᴅ ᴜꜱᴇʀ.</code>\n• /info - <code>ɢᴇᴛ ɪɴꜰᴏʀᴍᴀᴛɪᴏɴ ᴀʙᴏᴜᴛ ᴀ ᴜꜱᴇʀ.</code>\n• /imdb - <code>ɢᴇᴛ ᴛʜᴇ ꜰɪʟᴍ ɪɴꜰᴏʀᴍᴀᴛɪᴏɴ ꜰʀᴏᴍ ɪᴍᴅʙ ꜱᴏᴜʀᴄᴇ.</code>\n• /search - <code>ɢᴇᴛ ᴛʜᴇ ꜰɪʟᴍ ɪɴꜰᴏʀᴍᴀᴛɪᴏɴ ꜰʀᴏᴍ ᴠᴀʀɪᴏᴜꜱ ꜱᴏᴜʀᴄᴇꜱ.</code>\"\"\"\n\n ADMIN_TXT = \"\"\"ʜᴇʟᴘ: Aᴅᴍɪɴ Mᴏᴅs\n<b>ɴᴏᴛᴇ:</b>\nTʜɪs Mᴏᴅᴜʟᴇ Oɴʟʏ Wᴏʀᴋs Fᴏʀ Mʏ Aᴅᴍɪɴs\nCᴏᴍᴍᴀɴᴅs Aɴᴅ Usᴀɢᴇ:\n• /logs - <code>ᴛᴏ ɢᴇᴛ ᴛʜᴇ ʀᴇᴄᴇɴᴛ ᴇʀʀᴏʀꜱ</code>\n• /stats - <code>ᴛᴏ ɢᴇᴛ ꜱᴛᴀᴛᴜꜱ ᴏꜰ ꜰɪʟᴇꜱ ɪɴ ᴅʙ. [Tʜɪs Cᴏᴍᴍᴀɴᴅ Cᴀɴ Bᴇ Usᴇᴅ Bʏ Aɴʏᴏɴᴇ]</code>\n• /delete - <code>ᴛᴏ ᴅᴇʟᴇᴛᴇ ᴀ ꜱᴘᴇᴄɪꜰɪᴄ ꜰɪʟᴇ ꜰʀᴏᴍ ᴅʙ.</code>\n• /users - <code>ᴛᴏ ɢᴇᴛ ʟɪꜱᴛ ᴏꜰ ᴍʏ ᴜꜱᴇʀꜱ ᴀɴᴅ ɪᴅꜱ.</code>\n• /chats - <code>ᴛᴏ ɢᴇᴛ ʟɪꜱᴛ ᴏꜰ ᴍʏ ᴄʜᴀᴛꜱ ᴀɴᴅ ɪᴅꜱ</code>\n• /leave - <code>ᴛᴏ ʟᴇᴀᴠᴇ ꜰʀᴏᴍ ᴀ ᴄʜᴀᴛ.</code>\n• /disable - <code>ᴛᴏ ᴅɪꜱᴀʙʟᴇ ᴀ ᴄʜᴀᴛ.</code>\n• /ban - <code>ᴛᴏ ʙᴀɴ ᴀ ᴜꜱᴇʀ.</code>\n• /unban - <code>ᴛᴏ ᴜɴʙᴀɴ ᴀ ᴜꜱᴇʀ.</code>\n• /channel - <code>ᴛᴏ ɢᴇᴛ ʟɪꜱᴛ ᴏꜰ ᴛᴏᴛᴀʟ ᴄᴏɴɴᴇᴄᴛᴇᴅ ᴄʜᴀɴɴᴇʟꜱ</code>\n• /broadcast - <code>ᴛᴏ ʙʀᴏᴀᴅᴄᴀꜱᴛ ᴀ ᴍᴇꜱꜱᴀɢᴇ ᴛᴏ ᴀʟʟ ᴜꜱᴇʀꜱ</code>\n• /grp_broadcast - <code>Tᴏ ʙʀᴏᴀᴅᴄᴀsᴛ ᴀ ᴍᴇssᴀɢᴇ ᴛᴏ ᴀʟʟ ᴄᴏɴɴᴇᴄᴛᴇᴅ ɢʀᴏᴜᴘs.</code>\n• /gfilter - <code>ᴛᴏ ᴀᴅᴅ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀs</code>\n• /gfilters - <code>ᴛᴏ ᴠɪᴇᴡ ʟɪsᴛ ᴏғ ᴀʟʟ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀs</code>\n• /delg - <code>ᴛᴏ ᴅᴇʟᴇᴛᴇ ᴀ sᴘᴇᴄɪғɪᴄ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀ</code>\n• /request - <code>Tᴏ sᴇɴᴅ ᴀ Mᴏᴠɪᴇ/Sᴇʀɪᴇs ʀᴇᴏ̨ᴜᴇsᴛ ᴛᴏ ʙᴏᴛ ᴀᴅᴍɪɴs. Oɴʟʏ ᴡᴏʀᴋs ᴏɴ sᴜᴘᴘᴏʀᴛ ɢʀᴏᴜᴘ. [Tʜɪs Cᴏᴍᴍᴀɴᴅ Cᴀɴ Bᴇ Usᴇᴅ Bʏ Aɴʏᴏɴᴇ]</code>\n• /delallg - <code>Tᴏ ᴅᴇʟᴇᴛᴇ ᴀʟʟ Gғɪʟᴛᴇʀs ғʀᴏᴍ ᴛʜᴇ ʙᴏᴛ's ᴅᴀᴛᴀʙᴀsᴇ.</code>\n• /deletefiles - <code>Tᴏ ᴅᴇʟᴇᴛᴇ CᴀᴍRɪᴘ ᴀɴᴅ PʀᴇDVD Fɪʟᴇs ғʀᴏᴍ ᴛʜᴇ ʙᴏᴛ's ᴅᴀᴛᴀʙᴀsᴇ.</code>\"\"\"\n\n STATUS_TXT = \"\"\"<b>📂 ᴛᴏᴛᴀʟ ꜰɪʟᴇs: <code>{}</code>\n👤 ᴛᴏᴛᴀʟ ᴜsᴇʀs: <code>{}</code>\n♻️ ᴛᴏᴛᴀʟ ᴄʜᴀᴛs: <code>{}</code>\n🗃️ ᴜsᴇᴅ sᴛᴏʀᴀɢᴇ: <code>{}</code>\n🆓 ꜰʀᴇᴇ sᴛᴏʀᴀɢᴇ: <code>{}</code></b>\"\"\"\n\n LOG_TEXT_G = \"\"\"#𝐍𝐞𝐰𝐆𝐫𝐨𝐮𝐩\n\n<b>᚛› 𝐆𝐫𝐨𝐮𝐩 ⪼ {}(<code>{}</code>)</b>\n<b>᚛› 𝐓𝐨𝐭𝐚𝐥 𝐌𝐞𝐦𝐛𝐞𝐫𝐬 ⪼ <code>{}</code></b>\n<b>᚛› 𝐀𝐝𝐝𝐞𝐝 𝐁𝐲 ⪼ {}</b>\n\"\"\"\n\n LOG_TEXT_P = \"\"\"#𝐍𝐞𝐰𝐔𝐬𝐞𝐫\n\n<b>᚛› 𝐈𝐃 - <code>{}</code></b>\n<b>᚛› 𝐍𝐚𝐦𝐞 - {}</b>\n\"\"\"\n\n ALRT_TXT = \"\"\"{},\nᴄʜᴇᴄᴋ ʏᴏᴜʀ ᴏᴡɴ ʀᴇǫᴜᴇ𝗌ᴛ 😤\n\"\"\"\n\n OLD_ALRT_TXT =\"\"\"{},\n\nʏᴏᴜ ᴀʀᴇ ᴜꜱɪɴɢ ᴍʏ ᴏʟᴅ ᴍᴇꜱꜱᴀɢᴇ,\n\nꜱᴇɴᴅ ᴛʜᴇ ʀᴇǫᴜᴇ𝗌ᴛ ᴀɢᴀɪɴ 😊\n\"\"\"\n\n CUDNT_FND = \"\"\"<b>{},</b>\n\n𝗜 𝗰𝗼𝘂𝗹𝗱𝗻'𝘁 𝗳𝗶𝗻𝗱 𝗮𝗻𝘆𝘁𝗵𝗶𝗻𝗴 𝗿𝗲𝗹𝗮𝘁𝗲𝗱 𝘁𝗼 𝘁𝗵𝗮𝘁 𝗱𝗶𝗱 𝘆𝗼𝘂 𝗺𝗲𝗮𝗻 𝗮𝗻𝘆 𝗼𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲𝘀𝗲 ?? 👇\"\"\"\n\n I_CUDNT = \"\"\"<b>{},</b>\n\n𝗜 𝗰𝗼𝘂𝗹𝗱𝗻'𝘁 𝗳𝗶𝗻𝗱 𝗮𝗻𝘆 𝗺𝗼𝘃𝗶𝗲 𝗼𝗿 𝘀𝗲𝗿𝗶𝗲𝘀 𝗶𝗻 𝘁𝗵𝗮𝘁 𝗻𝗮𝗺𝗲.. 😐\"\"\"\n\n I_CUD_NT = \"\"\"ɪ ᴄᴏᴜʟᴅɴ'ᴛ ꜰɪɴᴅ ᴀɴʏ ᴍᴏᴠɪᴇ ʀᴇʟᴀᴛᴇᴅ ᴛᴏ {}.\nᴘʟᴇᴀꜱᴇ ᴄʜᴇᴄᴋ ᴛʜᴇ ꜱᴘᴇʟʟɪɴɢ ᴏɴ ɢᴏᴏɢʟᴇ ᴏʀ ɪᴍᴅʙ...\"\"\"\n\n MVE_NT_FND = \"\"\"<b>ᴍᴏᴠɪᴇ ɴᴏᴛ ꜰᴏᴜɴᴅ...\n\n<u>ʀᴇᴀꜱᴏɴꜱ:</u></b>\n\n𝟷) ꜱᴘᴇʟʟɪɴɢ ᴍɪꜱᴛᴀᴋᴇ\n\n𝟸) ᴏᴛᴛ ᴏʀ ᴅᴠᴅ ɴᴏᴛ ʀᴇʟᴇᴀꜱᴇᴅ\n\n𝟹) ɴᴏᴛ ᴀᴠᴀɪʟᴀʙʟᴇ ɪɴ ᴅᴀᴛᴀʙᴀꜱᴇ\n\n<b><a href=https://telegram.me/NobiDeveloperr>~ ʀᴇǫᴜᴇ𝗌ᴛ ᴛᴏ ᴏᴡɴᴇʀ</a></b>\n\"\"\"\n\n TOP_ALRT_MSG = \"\"\"ꜱᴇᴀʀᴄʜɪɴɢ ɪɴ ᴅᴀᴛᴀʙᴀꜱᴇ...\"\"\"\n\n MELCOW_ENG = \"\"\"<b>{},\n\n📿 ᴡᴇʟᴄᴏᴍᴇ ᴛᴏ ᴏᴜʀ ɢʀᴏᴜᴘ {}\n\n🚬 ᴛʜɪs ɪs ᴀ ᴍᴏᴠɪᴇ ɢʀᴏᴜᴘ\n\n⏳ ᴀʟʟ ᴄᴀᴛᴇɢᴏʀɪᴇs ᴏꜰ ᴍᴏᴠɪᴇs ᴀᴠᴀɪʟᴀʙʟᴇ ʜᴇʀᴇ\n\n🧨 ᴊᴜsᴛ ᴛʏᴘᴇ ᴛʜᴇ ᴍᴏᴠɪᴇ ɴᴀᴍᴇ\n\n🤖 ʙᴏᴛ ᴡɪʟʟ sᴇɴᴅ ʏᴏᴜʀ ᴍᴏᴠɪᴇ\n\n☎️ ʀᴇᴀᴅ ɢʀᴏᴜᴘ ʀᴜʟᴇs ᴛᴏ ᴋɴᴏᴡ ᴍᴏʀᴇ...</b>\"\"\"\n\n SHORTLINK_INFO = \"\"\"\n<b>──────「 <a href='https://telegram.me/NobiDeveloper'>ᴇᴀʀɴ ᴍᴏɴᴇʏ</a> 」──────\n\n➥ ɴᴏᴡ ʏᴏᴜ ᴄᴀɴ ᴀʟsᴏ ᴇᴀʀɴ ʟᴏᴛs ᴏꜰ ᴍᴏɴᴇʏ ꜰʀᴏᴍ ᴛʜɪꜱ ʙᴏᴛ.\n\n›› sᴛᴇᴘ 𝟷 : ʏᴏᴜ ᴍᴜsᴛ ʜᴀᴠᴇ ᴀᴛʟᴇᴀsᴛ ᴏɴᴇ ɢʀᴏᴜᴘ ᴡɪᴛʜ ᴍɪɴɪᴍᴜᴍ 𝟹𝟶𝟶 ᴍᴇᴍʙᴇʀs.\n\n›› sᴛᴇᴘ 𝟸 : ᴍᴀᴋᴇ ᴀᴄᴄᴏᴜɴᴛ ᴏɴ <a href='https://tnshort.net/ref/devilofficial'>ᴛɴʟɪɴᴋ</a> ᴏʀ <a href='https://onepagelink.in/ref/Nobita'>ᴏɴᴇᴘᴀɢᴇʟɪɴᴋ</a>. [ ʏᴏᴜ ᴄᴀɴ ᴀʟsᴏ ᴜsᴇ ᴏᴛʜᴇʀ sʜᴏʀᴛɴᴇʀ ᴡᴇʙsɪᴛᴇ ]\n\n›› sᴛᴇᴘ 𝟹 : ꜰᴏʟʟᴏᴡ ᴛʜᴇsᴇ <a href='https://telegram.me/NobiDeveloper/1063'>ɪɴꜱᴛʀᴜᴄᴛɪᴏɴꜱ</a>.\n\n➥ ᴛʜɪꜱ ʙᴏᴛ ꜰʀᴇᴇ ꜰᴏʀ ᴀʟʟ ʏᴏᴜ ᴄᴀɴ ᴜꜱᴇ ᴛʜɪꜱ ʙᴏᴛ ɪɴ ʏᴏᴜʀ ɢʀᴏᴜᴘs ꜰʀᴇᴇ ᴏꜰ ᴄᴏꜱᴛ.</b>\"\"\"\n\n REQINFO = \"\"\"\n⚠ ɪɴꜰᴏʀᴍᴀᴛɪᴏɴ ⚠\n\nᴀꜰᴛᴇʀ 5 ᴍɪɴᴜᴛᴇꜱ ᴛʜɪꜱ ᴍᴇꜱꜱᴀɢᴇ ᴡɪʟʟ ʙᴇ ᴀᴜᴛᴏᴍᴀᴛɪᴄᴀʟʟʏ ᴅᴇʟᴇᴛᴇᴅ\n\nɪꜰ ʏᴏᴜ ᴅᴏ ɴᴏᴛ ꜱᴇᴇ ᴛʜᴇ ʀᴇǫᴜᴇsᴛᴇᴅ ᴍᴏᴠɪᴇ / sᴇʀɪᴇs ꜰɪʟᴇ, ʟᴏᴏᴋ ᴀᴛ ᴛʜᴇ ɴᴇxᴛ ᴘᴀɢᴇ\"\"\"\n\n SELECT = \"\"\"\nMOVIES ➢ Sᴇʟᴇᴄᴛ \"Lᴀɴɢᴜᴀɢᴇs\"\n\nSERIES ➢ Sᴇʟᴇᴄᴛ \"Sᴇᴀsᴏɴs\"\n\nTɪᴘ: Sᴇʟᴇᴄᴛ \"Lᴀɴɢᴜᴀɢᴇs\" ᴏʀ \"Sᴇᴀsᴏɴs\" Bᴜᴛᴛᴏɴ ᴀɴᴅ Cʟɪᴄᴋ \"Sᴇɴᴅ Aʟʟ\" Tᴏ ɢᴇᴛ Aʟʟ Fɪʟᴇ Lɪɴᴋs ɪɴ ᴀ Sɪɴɢʟᴇ ᴄʟɪᴄᴋ\"\"\"\n\n SINFO = \"\"\"\n▣ ᴛɪᴘs ▣\n\n☆ ᴛʏᴘᴇ ᴄᴏʀʀᴇᴄᴛ sᴘᴇʟʟɪɴɢ (ɢᴏᴏɢʟᴇ)\n\n☆ ɪꜰ ʏᴏᴜ ɴᴏᴛ ɢᴇᴛ ʏᴏᴜʀ ꜰɪʟᴇ ɪɴ ᴛʜɪꜱ ᴘᴀɢᴇ ᴛʜᴇɴ ᴄʟɪᴄᴋ ᴏɴ ɴᴇxᴛ ʙᴜᴛᴛᴏɴ\n\n☆ ᴄᴏɴᴛɪɴᴜᴇ ᴛʜɪs ᴍᴇᴛʜᴏᴅ ᴛᴏ ɢᴇᴛᴛɪɴɢ ʏᴏᴜ ꜰɪʟᴇ\n\n❤️‍🔥 ᴘᴏᴡᴇʀᴇᴅ ʙʏ @NobiDeveloper\n\"\"\"\n\n NORSLTS = \"\"\"\n★ #𝗡𝗼𝗥𝗲𝘀𝘂𝗹𝘁𝘀 ★\n\n𝗜𝗗 <b>: {}</b>\n𝗡𝗮𝗺𝗲 <b>: {}</b>\n𝗠𝗲𝘀𝘀𝗮𝗴𝗲 <b>: {}</b>\"\"\"\n\n CAPTION = \"\"\"\n[{file_name}](https://telegram.me/NobiDeveloper)\n\n<b>•────•────────•────•\n📌 ʀᴇǫᴜᴇsᴛ ɢʀᴏᴜᴘ​ : [ᴄʟɪᴄᴋ ʜᴇʀᴇ](https://telegram.me/AllRequestGroups)\n🎬 ᴍᴏᴠɪᴇs ᴄʜᴀɴɴᴇʟ​ : [ᴄʟɪᴄᴋ ʜᴇʀᴇ](https://telegram.me/MovieVillaYT)\n•────•────────•────•\n\n©️ ᴘᴏᴡᴇʀᴇᴅ ʙʏ : [ᴍᴏᴠɪᴇ ᴠɪʟʟᴀ](https://youtube.com/@NobiDeveloper)</b>\"\"\"\n\n IMDB_TEMPLATE_TXT = \"\"\"\n<b>{title}</b>\n\n⭐️<b>{rating}</b> | ⏰ <b>{runtime}</b> | 📆 <b>{release_date}</b>\n\n● <b>{genres}</b>\n● <b>{languages}</b>\n\n📖 sᴛᴏʀʏ : <b>{plot}</b> \n\n© {message.chat.title}\n\"\"\"\n \n ALL_FILTERS = \"\"\"\n<b>Hᴇʏ {}, Tʜᴇsᴇ ᴀʀᴇ ᴍʏ ᴛʜʀᴇᴇ ᴛʏᴘᴇs ᴏғ ғɪʟᴛᴇʀs.</b>\"\"\"\n \n GFILTER_TXT = \"\"\"\n<b>Wᴇʟᴄᴏᴍᴇ ᴛᴏ Gʟᴏʙᴀʟ Fɪʟᴛᴇʀs. Gʟᴏʙᴀʟ Fɪʟᴛᴇʀs ᴀʀᴇ ᴛʜᴇ ғɪʟᴛᴇʀs sᴇᴛ ʙʏ ʙᴏᴛ ᴀᴅᴍɪɴs ᴡʜɪᴄʜ ᴡɪʟʟ ᴡᴏʀᴋ ᴏɴ ᴀʟʟ ɢʀᴏᴜᴘs.</b>\n \nAᴠᴀɪʟᴀʙʟᴇ ᴄᴏᴍᴍᴀɴᴅs:\n• /gfilter - <code>Tᴏ ᴄʀᴇᴀᴛᴇ ᴀ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀ.</code>\n• /gfilters - <code>Tᴏ ᴠɪᴇᴡ ᴀʟʟ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀs.</code>\n• /delg - <code>Tᴏ ᴅᴇʟᴇᴛᴇ ᴀ ᴘᴀʀᴛɪᴄᴜʟᴀʀ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀ.</code>\n• /delallg - <code>ᴛᴏ ᴅᴇʟᴇᴛᴇ ᴀʟʟ ɢʟᴏʙᴀʟ ꜰɪʟᴛᴇʀꜱ.</code>\"\"\"\n \n FILE_STORE_TXT = \"\"\"\n<b>Fɪʟᴇ sᴛᴏʀᴇ ɪs ᴛʜᴇ ғᴇᴀᴛᴜʀᴇ ᴡʜɪᴄʜ ᴡɪʟʟ ᴄʀᴇᴀᴛᴇ ᴀ sʜᴀʀᴇᴀʙʟᴇ ʟɪɴᴋ ᴏғ ᴀ sɪɴɢʟᴇ ᴏʀ ᴍᴜʟᴛɪᴘʟᴇ ғɪʟᴇs.</b>\n\nAᴠᴀɪʟᴀʙʟᴇ ᴄᴏᴍᴍᴀɴᴅs:\n• /batch - <code>Tᴏ ᴄʀᴇᴀᴛᴇ ᴀ ʙᴀᴛᴄʜ ʟɪɴᴋ ᴏғ ᴍᴜʟᴛɪᴘʟᴇ ғɪʟᴇs.</code>\n• /link - <code>Tᴏ ᴄʀᴇᴀᴛᴇ ᴀ sɪɴɢʟᴇ ғɪʟᴇ sᴛᴏʀᴇ ʟɪɴᴋ.</code>\n• /pbatch - <code>Jᴜsᴛ ʟɪᴋᴇ /batch, ʙᴜᴛ ᴛʜᴇ ғɪʟᴇs ᴡɪʟʟ ʙᴇ sᴇɴᴅ ᴡɪᴛʜ ғᴏʀᴡᴀʀᴅ ʀᴇsᴛʀɪᴄᴛɪᴏɴs.</code>\n• /plink - <code>Jᴜsᴛ ʟɪᴋᴇ /link, ʙᴜᴛ ᴛʜᴇ ғɪʟᴇ ᴡɪʟʟ ʙᴇ sᴇɴᴅ ᴡɪᴛʜ ғᴏʀᴡᴀʀᴅ ʀᴇsᴛʀɪᴄᴛɪᴏɴ.</code>\"\"\"\n\n RESTART_TXT = \"\"\"\n<b>Bᴏᴛ Rᴇsᴛᴀʀᴛᴇᴅ !\n\n📅 Dᴀᴛᴇ : <code>{}</code>\n⏰ Tɪᴍᴇ : <code>{}</code>\n🌐 Tɪᴍᴇᴢᴏɴᴇ : <code>Asia/Kolkata</code>\n🛠️ Bᴜɪʟᴅ Sᴛᴀᴛᴜs: <code>v2.7.1 [ Sᴛᴀʙʟᴇ ]</code></b>\n\"\"\"\n\n LOGO = \"\"\"\n𝑺𝒕𝒂𝒓𝒕𝒊𝒏𝒈.......🥵\"\"\"" } ]
from pyrogram import Client, filters, enums from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery from pyrogram.errors.exceptions.bad_request_400 import MessageTooLong, PeerIdInvalid from info import ADMINS, LOG_CHANNEL, SUPPORT_CHAT, MELCOW_NEW_USERS, MELCOW_VID, CHNL_LNK, GRP_LNK from database.users_chats_db import db from database.ia_filterdb import Media from utils import get_size, temp, get_settings from Script import script from pyrogram.errors import ChatAdminRequired import asyncio
15,236
"""----------------------------------------- https://github.com/NobiDeveloper/Nobita-Filter-Bot --------------------------------------""" @Client.on_message(filters.new_chat_members & filters.group) async def save_group(bot, message): r_j_check = [u.id for u in message.new_chat_members] if temp.ME in r_j_check: if not await db.get_chat(message.chat.id): total=await bot.get_chat_members_count(message.chat.id) r_j = message.from_user.mention if message.from_user else "Anonymous" await bot.send_message(LOG_CHANNEL, script.LOG_TEXT_G.format(message.chat.title, message.chat.id, total, r_j)) await db.add_chat(message.chat.id, message.chat.title) if message.chat.id in temp.BANNED_CHATS: # Inspired from a boat of a banana tree buttons = [[ InlineKeyboardButton('Support', url='https://telegram.me/NobiDeveloperSupport') ]] reply_markup=InlineKeyboardMarkup(buttons) k = await message.reply( text='<b>CHAT NOT ALLOWED 🐞\n\nMy admins has restricted me from working here ! If you want to know more about it contact support..</b>', reply_markup=reply_markup, ) try: await k.pin() except: pass await bot.leave_chat(message.chat.id) return buttons = [[ InlineKeyboardButton('🥷 ʜᴇʟᴘ 🥷', url='https://telegram.me/NobiDeveloperSupport'), InlineKeyboardButton('♻️ ᴜᴘᴅᴀᴛᴇꜱ ♻️', url='https://telegram.me/NobiDeveloper') ]] reply_markup=InlineKeyboardMarkup(buttons) await message.reply_text( text=f"<b>☤ ᴛʜᴀɴᴋ ʏᴏᴜ ꜰᴏʀ ᴀᴅᴅɪɴɢ ᴍᴇ ɪɴ {message.chat.title}\n\n🤖 ᴅᴏɴ’ᴛ ꜰᴏʀɢᴇᴛ ᴛᴏ ᴍᴀᴋᴇ ᴍᴇ ᴀᴅᴍɪɴ 🤖\n\n🕵️ ɪꜰ ʏᴏᴜ ʜᴀᴠᴇ ᴀɴʏ ᴅᴏᴜʙᴛ ʏᴏᴜ ᴄʟᴇᴀʀ ɪᴛ ᴜsɪɴɢ ʙᴇʟᴏᴡ ʙᴜᴛᴛᴏɴs</b>", reply_markup=reply_markup) else:
"""----------------------------------------- https://github.com/NobiDeveloper/Nobita-Filter-Bot --------------------------------------""" @Client.on_message(filters.new_chat_members & filters.group) async def save_group(bot, message): r_j_check = [u.id for u in message.new_chat_members] if temp.ME in r_j_check: if not await db.get_chat(message.chat.id): total=await bot.get_chat_members_count(message.chat.id) r_j = message.from_user.mention if message.from_user else "Anonymous" await bot.send_message(LOG_CHANNEL, script.LOG_TEXT_G.format(message.chat.title, message.chat.id, total, r_j)) await db.add_chat(message.chat.id, message.chat.title) if message.chat.id in temp.BANNED_CHATS: # Inspired from a boat of a banana tree buttons = [[ InlineKeyboardButton('Support', url='https://telegram.me/NobiDeveloperSupport') ]] reply_markup=InlineKeyboardMarkup(buttons) k = await message.reply( text='<b>CHAT NOT ALLOWED 🐞\n\nMy admins has restricted me from working here ! If you want to know more about it contact support..</b>', reply_markup=reply_markup, ) try: await k.pin() except: pass await bot.leave_chat(message.chat.id) return buttons = [[ InlineKeyboardButton('🥷 ʜᴇʟᴘ 🥷', url='https://telegram.me/NobiDeveloperSupport'), InlineKeyboardButton('♻️ ᴜᴘᴅᴀᴛᴇꜱ ♻️', url='https://telegram.me/NobiDeveloper') ]] reply_markup=InlineKeyboardMarkup(buttons) await message.reply_text( text=f"<b>☤ ᴛʜᴀɴᴋ ʏᴏᴜ ꜰᴏʀ ᴀᴅᴅɪɴɢ ᴍᴇ ɪɴ {message.chat.title}\n\n🤖 ᴅᴏɴ’ᴛ ꜰᴏʀɢᴇᴛ ᴛᴏ ᴍᴀᴋᴇ ᴍᴇ ᴀᴅᴍɪɴ 🤖\n\n🕵️ ɪꜰ ʏᴏᴜ ʜᴀᴠᴇ ᴀɴʏ ᴅᴏᴜʙᴛ ʏᴏᴜ ᴄʟᴇᴀʀ ɪᴛ ᴜsɪɴɢ ʙᴇʟᴏᴡ ʙᴜᴛᴛᴏɴs</b>", reply_markup=reply_markup) else:
settings = await get_settings(message.chat.id)
11
2023-11-28 13:36:56+00:00
24k
chenxx89/BFRffusion
models/models.py
[ { "identifier": "timestep_embedding", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):\n \"\"\"\n Create sinusoidal timestep embeddings.\n :param timesteps: a 1-D Tensor of N indices, one per batch element.\n These may be fractional.\n :param dim: the dimension of the output.\n :param max_period: controls the minimum frequency of the embeddings.\n :return: an [N x dim] Tensor of positional embeddings.\n \"\"\"\n if not repeat_only:\n half = dim // 2\n freqs = torch.exp(\n -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half\n ).to(device=timesteps.device)\n args = timesteps[:, None].float() * freqs[None]\n embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)\n if dim % 2:\n embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)\n else:\n embedding = repeat(timesteps, 'b -> b d', d=dim)\n return embedding" }, { "identifier": "UNetModel", "path": "ldm/modules/diffusionmodules/openaimodel.py", "snippet": "class UNetModel(nn.Module):\n \"\"\"\n The full UNet model with attention and timestep embedding.\n :param in_channels: channels in the input Tensor.\n :param model_channels: base channel count for the model.\n :param out_channels: channels in the output Tensor.\n :param num_res_blocks: number of residual blocks per downsample.\n :param attention_resolutions: a collection of downsample rates at which\n attention will take place. May be a set, list, or tuple.\n For example, if this contains 4, then at 4x downsampling, attention\n will be used.\n :param dropout: the dropout probability.\n :param channel_mult: channel multiplier for each level of the UNet.\n :param conv_resample: if True, use learned convolutions for upsampling and\n downsampling.\n :param dims: determines if the signal is 1D, 2D, or 3D.\n :param num_classes: if specified (as an int), then this model will be\n class-conditional with `num_classes` classes.\n :param use_checkpoint: use gradient checkpointing to reduce memory usage.\n :param num_heads: the number of attention heads in each attention layer.\n :param num_heads_channels: if specified, ignore num_heads and instead use\n a fixed channel width per attention head.\n :param num_heads_upsample: works with num_heads to set a different number\n of heads for upsampling. Deprecated.\n :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.\n :param resblock_updown: use residual blocks for up/downsampling.\n :param use_new_attention_order: use a different attention pattern for potentially\n increased efficiency.\n \"\"\"\n\n def __init__(\n self,\n image_size,\n in_channels,\n model_channels,\n out_channels,\n num_res_blocks,\n attention_resolutions,\n dropout=0,\n channel_mult=(1, 2, 4, 8),\n conv_resample=True,\n dims=2,\n num_classes=None,\n use_checkpoint=False,\n use_fp16=False,\n num_heads=-1,\n num_head_channels=-1,\n num_heads_upsample=-1,\n use_scale_shift_norm=False,\n resblock_updown=False,\n use_new_attention_order=False,\n use_spatial_transformer=False, # custom transformer support\n transformer_depth=1, # custom transformer support\n context_dim=None, # custom transformer support\n n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model\n legacy=True,\n disable_self_attentions=None,\n num_attention_blocks=None,\n disable_middle_self_attn=False,\n use_linear_in_transformer=False,\n ):\n super().__init__()\n if use_spatial_transformer:\n assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'\n\n if context_dim is not None:\n assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'\n from omegaconf.listconfig import ListConfig\n if type(context_dim) == ListConfig:\n context_dim = list(context_dim)\n\n if num_heads_upsample == -1:\n num_heads_upsample = num_heads\n\n if num_heads == -1:\n assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'\n\n if num_head_channels == -1:\n assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'\n\n self.image_size = image_size\n self.in_channels = in_channels\n self.model_channels = model_channels\n self.out_channels = out_channels\n if isinstance(num_res_blocks, int):\n self.num_res_blocks = len(channel_mult) * [num_res_blocks]\n else:\n if len(num_res_blocks) != len(channel_mult):\n raise ValueError(\"provide num_res_blocks either as an int (globally constant) or \"\n \"as a list/tuple (per-level) with the same length as channel_mult\")\n self.num_res_blocks = num_res_blocks\n if disable_self_attentions is not None:\n # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not\n assert len(disable_self_attentions) == len(channel_mult)\n if num_attention_blocks is not None:\n assert len(num_attention_blocks) == len(self.num_res_blocks)\n assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))\n print(f\"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. \"\n f\"This option has LESS priority than attention_resolutions {attention_resolutions}, \"\n f\"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, \"\n f\"attention will still not be set.\")\n\n self.attention_resolutions = attention_resolutions\n self.dropout = dropout\n self.channel_mult = channel_mult\n self.conv_resample = conv_resample\n self.num_classes = num_classes\n self.use_checkpoint = use_checkpoint\n self.dtype = th.float16 if use_fp16 else th.float32\n self.num_heads = num_heads\n self.num_head_channels = num_head_channels\n self.num_heads_upsample = num_heads_upsample\n self.predict_codebook_ids = n_embed is not None\n\n time_embed_dim = model_channels * 4\n self.time_embed = nn.Sequential(\n linear(model_channels, time_embed_dim),\n nn.SiLU(),\n linear(time_embed_dim, time_embed_dim),\n )\n\n if self.num_classes is not None:\n if isinstance(self.num_classes, int):\n self.label_emb = nn.Embedding(num_classes, time_embed_dim)\n elif self.num_classes == \"continuous\":\n print(\"setting up linear c_adm embedding layer\")\n self.label_emb = nn.Linear(1, time_embed_dim)\n else:\n raise ValueError()\n\n self.input_blocks = nn.ModuleList(\n [\n TimestepEmbedSequential(\n conv_nd(dims, in_channels, model_channels, 3, padding=1)\n )\n ]\n )\n self._feature_size = model_channels\n input_block_chans = [model_channels]\n ch = model_channels\n ds = 1\n for level, mult in enumerate(channel_mult):\n for nr in range(self.num_res_blocks[level]):\n layers = [\n ResBlock(\n ch,\n time_embed_dim,\n dropout,\n out_channels=mult * model_channels,\n dims=dims,\n use_checkpoint=use_checkpoint,\n use_scale_shift_norm=use_scale_shift_norm,\n )\n ]\n ch = mult * model_channels\n if ds in attention_resolutions:\n if num_head_channels == -1:\n dim_head = ch // num_heads\n else:\n num_heads = ch // num_head_channels\n dim_head = num_head_channels\n if legacy:\n #num_heads = 1\n dim_head = ch // num_heads if use_spatial_transformer else num_head_channels\n if exists(disable_self_attentions):\n disabled_sa = disable_self_attentions[level]\n else:\n disabled_sa = False\n\n if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:\n layers.append(\n AttentionBlock(\n ch,\n use_checkpoint=use_checkpoint,\n num_heads=num_heads,\n num_head_channels=dim_head,\n use_new_attention_order=use_new_attention_order,\n ) if not use_spatial_transformer else SpatialTransformer(\n ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,\n disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,\n use_checkpoint=use_checkpoint\n )\n )\n self.input_blocks.append(TimestepEmbedSequential(*layers))\n self._feature_size += ch\n input_block_chans.append(ch)\n if level != len(channel_mult) - 1:\n out_ch = ch\n self.input_blocks.append(\n TimestepEmbedSequential(\n ResBlock(\n ch,\n time_embed_dim,\n dropout,\n out_channels=out_ch,\n dims=dims,\n use_checkpoint=use_checkpoint,\n use_scale_shift_norm=use_scale_shift_norm,\n down=True,\n )\n if resblock_updown\n else Downsample(\n ch, conv_resample, dims=dims, out_channels=out_ch\n )\n )\n )\n ch = out_ch\n input_block_chans.append(ch)\n ds *= 2\n self._feature_size += ch\n\n if num_head_channels == -1:\n dim_head = ch // num_heads\n else:\n num_heads = ch // num_head_channels\n dim_head = num_head_channels\n if legacy:\n #num_heads = 1\n dim_head = ch // num_heads if use_spatial_transformer else num_head_channels\n self.middle_block = TimestepEmbedSequential(\n ResBlock(\n ch,\n time_embed_dim,\n dropout,\n dims=dims,\n use_checkpoint=use_checkpoint,\n use_scale_shift_norm=use_scale_shift_norm,\n ),\n AttentionBlock(\n ch,\n use_checkpoint=use_checkpoint,\n num_heads=num_heads,\n num_head_channels=dim_head,\n use_new_attention_order=use_new_attention_order,\n ) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn\n ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,\n disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,\n use_checkpoint=use_checkpoint\n ),\n ResBlock(\n ch,\n time_embed_dim,\n dropout,\n dims=dims,\n use_checkpoint=use_checkpoint,\n use_scale_shift_norm=use_scale_shift_norm,\n ),\n )\n self._feature_size += ch\n\n self.output_blocks = nn.ModuleList([])\n for level, mult in list(enumerate(channel_mult))[::-1]:\n for i in range(self.num_res_blocks[level] + 1):\n ich = input_block_chans.pop()\n layers = [\n ResBlock(\n ch + ich,\n time_embed_dim,\n dropout,\n out_channels=model_channels * mult,\n dims=dims,\n use_checkpoint=use_checkpoint,\n use_scale_shift_norm=use_scale_shift_norm,\n )\n ]\n ch = model_channels * mult\n if ds in attention_resolutions:\n if num_head_channels == -1:\n dim_head = ch // num_heads\n else:\n num_heads = ch // num_head_channels\n dim_head = num_head_channels\n if legacy:\n #num_heads = 1\n dim_head = ch // num_heads if use_spatial_transformer else num_head_channels\n if exists(disable_self_attentions):\n disabled_sa = disable_self_attentions[level]\n else:\n disabled_sa = False\n\n if not exists(num_attention_blocks) or i < num_attention_blocks[level]:\n layers.append(\n AttentionBlock(\n ch,\n use_checkpoint=use_checkpoint,\n num_heads=num_heads_upsample,\n num_head_channels=dim_head,\n use_new_attention_order=use_new_attention_order,\n ) if not use_spatial_transformer else SpatialTransformer(\n ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,\n disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,\n use_checkpoint=use_checkpoint\n )\n )\n if level and i == self.num_res_blocks[level]:\n out_ch = ch\n layers.append(\n ResBlock(\n ch,\n time_embed_dim,\n dropout,\n out_channels=out_ch,\n dims=dims,\n use_checkpoint=use_checkpoint,\n use_scale_shift_norm=use_scale_shift_norm,\n up=True,\n )\n if resblock_updown\n else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)\n )\n ds //= 2\n self.output_blocks.append(TimestepEmbedSequential(*layers))\n self._feature_size += ch\n\n self.out = nn.Sequential(\n normalization(ch),\n nn.SiLU(),\n zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),\n )\n if self.predict_codebook_ids:\n self.id_predictor = nn.Sequential(\n normalization(ch),\n conv_nd(dims, model_channels, n_embed, 1),\n #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits\n )\n\n def convert_to_fp16(self):\n \"\"\"\n Convert the torso of the model to float16.\n \"\"\"\n self.input_blocks.apply(convert_module_to_f16)\n self.middle_block.apply(convert_module_to_f16)\n self.output_blocks.apply(convert_module_to_f16)\n\n def convert_to_fp32(self):\n \"\"\"\n Convert the torso of the model to float32.\n \"\"\"\n self.input_blocks.apply(convert_module_to_f32)\n self.middle_block.apply(convert_module_to_f32)\n self.output_blocks.apply(convert_module_to_f32)\n\n def forward(self, x, timesteps=None, context=None, y=None,**kwargs):\n \"\"\"\n Apply the model to an input batch.\n :param x: an [N x C x ...] Tensor of inputs.\n :param timesteps: a 1-D batch of timesteps.\n :param context: conditioning plugged in via crossattn\n :param y: an [N] Tensor of labels, if class-conditional.\n :return: an [N x C x ...] Tensor of outputs.\n \"\"\"\n assert (y is not None) == (\n self.num_classes is not None\n ), \"must specify y if and only if the model is class-conditional\"\n hs = []\n t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)\n emb = self.time_embed(t_emb)\n\n if self.num_classes is not None:\n assert y.shape[0] == x.shape[0]\n emb = emb + self.label_emb(y)\n\n h = x.type(self.dtype)\n for module in self.input_blocks:\n h = module(h, emb, context)\n hs.append(h)\n h = self.middle_block(h, emb, context)\n for module in self.output_blocks:\n h = th.cat([h, hs.pop()], dim=1)\n h = module(h, emb, context)\n h = h.type(x.dtype)\n if self.predict_codebook_ids:\n return self.id_predictor(h)\n else:\n return self.out(h)" }, { "identifier": "LatentDiffusion", "path": "ldm/models/diffusion/ddpm.py", "snippet": "class LatentDiffusion(DDPM):\n \"\"\"main class\"\"\"\n\n def __init__(self,\n first_stage_config,\n cond_stage_config,\n num_timesteps_cond=None,\n cond_stage_key=\"image\",\n cond_stage_trainable=False,\n concat_mode=True,\n cond_stage_forward=None,\n conditioning_key=None,\n scale_factor=1.0,\n scale_by_std=False,\n force_null_conditioning=False,\n *args, **kwargs):\n self.force_null_conditioning = force_null_conditioning\n self.num_timesteps_cond = default(num_timesteps_cond, 1)\n self.scale_by_std = scale_by_std\n assert self.num_timesteps_cond <= kwargs['timesteps']\n # for backwards compatibility after implementation of DiffusionWrapper\n if conditioning_key is None:\n conditioning_key = 'concat' if concat_mode else 'crossattn'\n if cond_stage_config == '__is_unconditional__' and not self.force_null_conditioning:\n conditioning_key = None\n ckpt_path = kwargs.pop(\"ckpt_path\", None)\n reset_ema = kwargs.pop(\"reset_ema\", False)\n reset_num_ema_updates = kwargs.pop(\"reset_num_ema_updates\", False)\n ignore_keys = kwargs.pop(\"ignore_keys\", [])\n super().__init__(conditioning_key=conditioning_key, *args, **kwargs)\n self.concat_mode = concat_mode\n self.cond_stage_trainable = cond_stage_trainable\n self.cond_stage_key = cond_stage_key\n try:\n self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1\n except:\n self.num_downs = 0\n if not scale_by_std:\n self.scale_factor = scale_factor\n else:\n self.register_buffer('scale_factor', torch.tensor(scale_factor))\n self.instantiate_first_stage(first_stage_config)\n self.instantiate_cond_stage(cond_stage_config)\n self.cond_stage_forward = cond_stage_forward\n self.clip_denoised = False\n self.bbox_tokenizer = None\n\n self.restarted_from_ckpt = False\n if ckpt_path is not None:\n self.init_from_ckpt(ckpt_path, ignore_keys)\n self.restarted_from_ckpt = True\n if reset_ema:\n assert self.use_ema\n print(\n f\"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.\")\n self.model_ema = LitEma(self.model)\n if reset_num_ema_updates:\n print(\" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ \")\n assert self.use_ema\n self.model_ema.reset_num_updates()\n\n def make_cond_schedule(self, ):\n self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)\n ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()\n self.cond_ids[:self.num_timesteps_cond] = ids\n\n @rank_zero_only\n @torch.no_grad()\n def on_train_batch_start(self, batch, batch_idx, dataloader_idx):\n # only for very first batch\n if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt:\n assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'\n # set rescale weight to 1./std of encodings\n print(\"### USING STD-RESCALING ###\")\n x = super().get_input(batch, self.first_stage_key)\n x = x.to(self.device)\n encoder_posterior = self.encode_first_stage(x)\n z = self.get_first_stage_encoding(encoder_posterior).detach()\n del self.scale_factor\n self.register_buffer('scale_factor', 1. / z.flatten().std())\n print(f\"setting self.scale_factor to {self.scale_factor}\")\n print(\"### USING STD-RESCALING ###\")\n\n def register_schedule(self,\n given_betas=None, beta_schedule=\"linear\", timesteps=1000,\n linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):\n super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)\n\n self.shorten_cond_schedule = self.num_timesteps_cond > 1\n if self.shorten_cond_schedule:\n self.make_cond_schedule()\n\n def instantiate_first_stage(self, config):\n model = instantiate_from_config(config)\n self.first_stage_model = model.eval()\n self.first_stage_model.train = disabled_train\n for param in self.first_stage_model.parameters():\n param.requires_grad = False\n\n def instantiate_cond_stage(self, config):\n if not self.cond_stage_trainable:\n if config == \"__is_first_stage__\":\n print(\"Using first stage also as cond stage.\")\n self.cond_stage_model = self.first_stage_model\n elif config == \"__is_unconditional__\":\n print(f\"Training {self.__class__.__name__} as an unconditional model.\")\n self.cond_stage_model = None\n # self.be_unconditional = True\n else:\n model = instantiate_from_config(config)\n self.cond_stage_model = model.eval()\n self.cond_stage_model.train = disabled_train\n for param in self.cond_stage_model.parameters():\n param.requires_grad = False\n else:\n assert config != '__is_first_stage__'\n assert config != '__is_unconditional__'\n model = instantiate_from_config(config)\n self.cond_stage_model = model\n\n def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):\n denoise_row = []\n for zd in tqdm(samples, desc=desc):\n denoise_row.append(self.decode_first_stage(zd.to(self.device),\n force_not_quantize=force_no_decoder_quantization))\n n_imgs_per_row = len(denoise_row)\n denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W\n denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')\n denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')\n denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)\n return denoise_grid\n\n def get_first_stage_encoding(self, encoder_posterior):\n if isinstance(encoder_posterior, DiagonalGaussianDistribution):\n z = encoder_posterior.sample()\n elif isinstance(encoder_posterior, torch.Tensor):\n z = encoder_posterior\n else:\n raise NotImplementedError(f\"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented\")\n return self.scale_factor * z\n\n def get_learned_conditioning(self, c):\n if self.cond_stage_forward is None:\n if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):\n c = self.cond_stage_model.encode(c)\n if isinstance(c, DiagonalGaussianDistribution):\n c = c.mode()\n else:\n c = self.cond_stage_model(c)\n else:\n assert hasattr(self.cond_stage_model, self.cond_stage_forward)\n c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)\n return c\n\n def meshgrid(self, h, w):\n y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)\n x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)\n\n arr = torch.cat([y, x], dim=-1)\n return arr\n\n def delta_border(self, h, w):\n \"\"\"\n :param h: height\n :param w: width\n :return: normalized distance to image border,\n wtith min distance = 0 at border and max dist = 0.5 at image center\n \"\"\"\n lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)\n arr = self.meshgrid(h, w) / lower_right_corner\n dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]\n dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]\n edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]\n return edge_dist\n\n def get_weighting(self, h, w, Ly, Lx, device):\n weighting = self.delta_border(h, w)\n weighting = torch.clip(weighting, self.split_input_params[\"clip_min_weight\"],\n self.split_input_params[\"clip_max_weight\"], )\n weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)\n\n if self.split_input_params[\"tie_braker\"]:\n L_weighting = self.delta_border(Ly, Lx)\n L_weighting = torch.clip(L_weighting,\n self.split_input_params[\"clip_min_tie_weight\"],\n self.split_input_params[\"clip_max_tie_weight\"])\n\n L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)\n weighting = weighting * L_weighting\n return weighting\n\n def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code\n \"\"\"\n :param x: img of size (bs, c, h, w)\n :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])\n \"\"\"\n bs, nc, h, w = x.shape\n\n # number of crops in image\n Ly = (h - kernel_size[0]) // stride[0] + 1\n Lx = (w - kernel_size[1]) // stride[1] + 1\n\n if uf == 1 and df == 1:\n fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)\n unfold = torch.nn.Unfold(**fold_params)\n\n fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)\n\n weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)\n normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap\n weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))\n\n elif uf > 1 and df == 1:\n fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)\n unfold = torch.nn.Unfold(**fold_params)\n\n fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),\n dilation=1, padding=0,\n stride=(stride[0] * uf, stride[1] * uf))\n fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)\n\n weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)\n normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap\n weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))\n\n elif df > 1 and uf == 1:\n fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)\n unfold = torch.nn.Unfold(**fold_params)\n\n fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),\n dilation=1, padding=0,\n stride=(stride[0] // df, stride[1] // df))\n fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)\n\n weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)\n normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap\n weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))\n\n else:\n raise NotImplementedError\n\n return fold, unfold, normalization, weighting\n\n @torch.no_grad()\n def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,\n cond_key=None, return_original_cond=False, bs=None, return_x=False):\n x = super().get_input(batch, k)\n if bs is not None:\n x = x[:bs]\n x = x.to(self.device)\n encoder_posterior = self.encode_first_stage(x)\n z = self.get_first_stage_encoding(encoder_posterior).detach()\n\n if self.model.conditioning_key is not None and not self.force_null_conditioning:\n if cond_key is None:\n cond_key = self.cond_stage_key\n if cond_key != self.first_stage_key:\n if cond_key in ['caption', 'coordinates_bbox', \"txt\"]:\n xc = batch[cond_key]\n elif cond_key in ['class_label', 'cls']:\n xc = batch\n else:\n xc = super().get_input(batch, cond_key).to(self.device)\n else:\n xc = x\n if not self.cond_stage_trainable or force_c_encode:\n if isinstance(xc, dict) or isinstance(xc, list):\n c = self.get_learned_conditioning(xc)\n else:\n c = self.get_learned_conditioning(xc.to(self.device))\n else:\n c = xc\n if bs is not None:\n c = c[:bs]\n\n if self.use_positional_encodings:\n pos_x, pos_y = self.compute_latent_shifts(batch)\n ckey = __conditioning_keys__[self.model.conditioning_key]\n c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y}\n\n else:\n c = None\n xc = None\n if self.use_positional_encodings:\n pos_x, pos_y = self.compute_latent_shifts(batch)\n c = {'pos_x': pos_x, 'pos_y': pos_y}\n out = [z, c]\n if return_first_stage_outputs:\n xrec = self.decode_first_stage(z)\n out.extend([x, xrec])\n if return_x:\n out.extend([x])\n if return_original_cond:\n out.append(xc)\n return out\n\n @torch.no_grad()\n def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):\n if predict_cids:\n if z.dim() == 4:\n z = torch.argmax(z.exp(), dim=1).long()\n z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)\n z = rearrange(z, 'b h w c -> b c h w').contiguous()\n\n z = 1. / self.scale_factor * z\n return self.first_stage_model.decode(z)\n\n @torch.no_grad()\n def encode_first_stage(self, x):\n return self.first_stage_model.encode(x)\n\n def shared_step(self, batch, **kwargs):\n x, c = self.get_input(batch, self.first_stage_key)\n loss = self(x, c)\n return loss\n\n def forward(self, x, c, *args, **kwargs):\n t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()\n if self.model.conditioning_key is not None:\n assert c is not None\n # if self.cond_stage_trainable:\n # c = self.get_learned_conditioning(c)\n if self.shorten_cond_schedule: # TODO: drop this option\n tc = self.cond_ids[t].to(self.device)\n c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))\n return self.p_losses(x, c, t, *args, **kwargs)\n\n def apply_model(self, x_noisy, t, cond, return_ids=False):\n if isinstance(cond, dict):\n # hybrid case, cond is expected to be a dict\n pass\n else:\n if not isinstance(cond, list):\n cond = [cond]\n key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'\n cond = {key: cond}\n\n x_recon = self.model(x_noisy, t, **cond)\n\n if isinstance(x_recon, tuple) and not return_ids:\n return x_recon[0]\n else:\n return x_recon\n\n def _predict_eps_from_xstart(self, x_t, t, pred_xstart):\n return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \\\n extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)\n\n def _prior_bpd(self, x_start):\n \"\"\"\n Get the prior KL term for the variational lower-bound, measured in\n bits-per-dim.\n This term can't be optimized, as it only depends on the encoder.\n :param x_start: the [N x C x ...] tensor of inputs.\n :return: a batch of [N] KL values (in bits), one per batch element.\n \"\"\"\n batch_size = x_start.shape[0]\n t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)\n qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)\n kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)\n return mean_flat(kl_prior) / np.log(2.0)\n\n def p_losses(self, x_start, cond, t, noise=None):\n noise = default(noise, lambda: torch.randn_like(x_start))\n x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)\n model_output = self.apply_model(x_noisy, t, cond)\n\n loss_dict = {}\n prefix = 'train' if self.training else 'val'\n\n if self.parameterization == \"x0\":\n target = x_start\n elif self.parameterization == \"eps\":\n target = noise\n elif self.parameterization == \"v\":\n target = self.get_v(x_start, noise, t)\n else:\n raise NotImplementedError()\n\n loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])\n loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})\n\n logvar_t = self.logvar[t].to(self.device)\n loss = loss_simple / torch.exp(logvar_t) + logvar_t\n # loss = loss_simple / torch.exp(self.logvar) + self.logvar\n if self.learn_logvar:\n loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})\n loss_dict.update({'logvar': self.logvar.data.mean()})\n\n loss = self.l_simple_weight * loss.mean()\n\n loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))\n loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()\n loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})\n loss += (self.original_elbo_weight * loss_vlb)\n loss_dict.update({f'{prefix}/loss': loss})\n\n return loss, loss_dict\n\n def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,\n return_x0=False, score_corrector=None, corrector_kwargs=None):\n t_in = t\n model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)\n\n if score_corrector is not None:\n assert self.parameterization == \"eps\"\n model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)\n\n if return_codebook_ids:\n model_out, logits = model_out\n\n if self.parameterization == \"eps\":\n x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)\n elif self.parameterization == \"x0\":\n x_recon = model_out\n else:\n raise NotImplementedError()\n\n if clip_denoised:\n x_recon.clamp_(-1., 1.)\n if quantize_denoised:\n x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)\n model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)\n if return_codebook_ids:\n return model_mean, posterior_variance, posterior_log_variance, logits\n elif return_x0:\n return model_mean, posterior_variance, posterior_log_variance, x_recon\n else:\n return model_mean, posterior_variance, posterior_log_variance\n\n @torch.no_grad()\n def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,\n return_codebook_ids=False, quantize_denoised=False, return_x0=False,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):\n b, *_, device = *x.shape, x.device\n outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,\n return_codebook_ids=return_codebook_ids,\n quantize_denoised=quantize_denoised,\n return_x0=return_x0,\n score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)\n if return_codebook_ids:\n raise DeprecationWarning(\"Support dropped.\")\n model_mean, _, model_log_variance, logits = outputs\n elif return_x0:\n model_mean, _, model_log_variance, x0 = outputs\n else:\n model_mean, _, model_log_variance = outputs\n\n noise = noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n # no noise when t == 0\n nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))\n\n if return_codebook_ids:\n return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)\n if return_x0:\n return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0\n else:\n return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise\n\n @torch.no_grad()\n def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,\n img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,\n score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,\n log_every_t=None):\n if not log_every_t:\n log_every_t = self.log_every_t\n timesteps = self.num_timesteps\n if batch_size is not None:\n b = batch_size if batch_size is not None else shape[0]\n shape = [batch_size] + list(shape)\n else:\n b = batch_size = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=self.device)\n else:\n img = x_T\n intermediates = []\n if cond is not None:\n if isinstance(cond, dict):\n cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else\n list(map(lambda x: x[:batch_size], cond[key])) for key in cond}\n else:\n cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]\n\n if start_T is not None:\n timesteps = min(timesteps, start_T)\n iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',\n total=timesteps) if verbose else reversed(\n range(0, timesteps))\n if type(temperature) == float:\n temperature = [temperature] * timesteps\n\n for i in iterator:\n ts = torch.full((b,), i, device=self.device, dtype=torch.long)\n if self.shorten_cond_schedule:\n assert self.model.conditioning_key != 'hybrid'\n tc = self.cond_ids[ts].to(cond.device)\n cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))\n\n img, x0_partial = self.p_sample(img, cond, ts,\n clip_denoised=self.clip_denoised,\n quantize_denoised=quantize_denoised, return_x0=True,\n temperature=temperature[i], noise_dropout=noise_dropout,\n score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)\n if mask is not None:\n assert x0 is not None\n img_orig = self.q_sample(x0, ts)\n img = img_orig * mask + (1. - mask) * img\n\n if i % log_every_t == 0 or i == timesteps - 1:\n intermediates.append(x0_partial)\n if callback: callback(i)\n if img_callback: img_callback(img, i)\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_loop(self, cond, shape, return_intermediates=False,\n x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, img_callback=None, start_T=None,\n log_every_t=None):\n\n if not log_every_t:\n log_every_t = self.log_every_t\n device = self.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n intermediates = [img]\n if timesteps is None:\n timesteps = self.num_timesteps\n\n if start_T is not None:\n timesteps = min(timesteps, start_T)\n iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(\n range(0, timesteps))\n\n if mask is not None:\n assert x0 is not None\n assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match\n\n for i in iterator:\n ts = torch.full((b,), i, device=device, dtype=torch.long)\n if self.shorten_cond_schedule:\n assert self.model.conditioning_key != 'hybrid'\n tc = self.cond_ids[ts].to(cond.device)\n cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))\n\n img = self.p_sample(img, cond, ts,\n clip_denoised=self.clip_denoised,\n quantize_denoised=quantize_denoised)\n if mask is not None:\n img_orig = self.q_sample(x0, ts)\n img = img_orig * mask + (1. - mask) * img\n\n if i % log_every_t == 0 or i == timesteps - 1:\n intermediates.append(img)\n if callback: callback(i)\n if img_callback: img_callback(img, i)\n\n if return_intermediates:\n return img, intermediates\n return img\n\n @torch.no_grad()\n def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,\n verbose=True, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, shape=None, **kwargs):\n if shape is None:\n shape = (batch_size, self.channels, self.image_size, self.image_size)\n if cond is not None:\n if isinstance(cond, dict):\n cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else\n list(map(lambda x: x[:batch_size], cond[key])) for key in cond}\n else:\n cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]\n return self.p_sample_loop(cond,\n shape,\n return_intermediates=return_intermediates, x_T=x_T,\n verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,\n mask=mask, x0=x0)\n\n @torch.no_grad()\n def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):\n if ddim:\n ddim_sampler = DDIMSampler(self)\n shape = (self.channels, self.image_size, self.image_size)\n samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size,\n shape, cond, verbose=False, **kwargs)\n\n else:\n samples, intermediates = self.sample(cond=cond, batch_size=batch_size,\n return_intermediates=True, **kwargs)\n\n return samples, intermediates\n\n @torch.no_grad()\n def get_unconditional_conditioning(self, batch_size, null_label=None):\n if null_label is not None:\n xc = null_label\n if isinstance(xc, ListConfig):\n xc = list(xc)\n if isinstance(xc, dict) or isinstance(xc, list):\n c = self.get_learned_conditioning(xc)\n else:\n if hasattr(xc, \"to\"):\n xc = xc.to(self.device)\n c = self.get_learned_conditioning(xc)\n else:\n if self.cond_stage_key in [\"class_label\", \"cls\"]:\n xc = self.cond_stage_model.get_unconditional_conditioning(batch_size, device=self.device)\n return self.get_learned_conditioning(xc)\n else:\n raise NotImplementedError(\"todo\")\n if isinstance(c, list): # in case the encoder gives us a list\n for i in range(len(c)):\n c[i] = repeat(c[i], '1 ... -> b ...', b=batch_size).to(self.device)\n else:\n c = repeat(c, '1 ... -> b ...', b=batch_size).to(self.device)\n return c\n\n @torch.no_grad()\n def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=50, ddim_eta=0., return_keys=None,\n quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,\n plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None,\n use_ema_scope=True,\n **kwargs):\n ema_scope = self.ema_scope if use_ema_scope else nullcontext\n use_ddim = ddim_steps is not None\n\n log = dict()\n z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,\n return_first_stage_outputs=True,\n force_c_encode=True,\n return_original_cond=True,\n bs=N)\n N = min(x.shape[0], N)\n n_row = min(x.shape[0], n_row)\n log[\"inputs\"] = x\n log[\"reconstruction\"] = xrec\n if self.model.conditioning_key is not None:\n if hasattr(self.cond_stage_model, \"decode\"):\n xc = self.cond_stage_model.decode(c)\n log[\"conditioning\"] = xc\n elif self.cond_stage_key in [\"caption\", \"txt\"]:\n xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)\n log[\"conditioning\"] = xc\n elif self.cond_stage_key in ['class_label', \"cls\"]:\n try:\n xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[\"human_label\"], size=x.shape[2] // 25)\n log['conditioning'] = xc\n except KeyError:\n # probably no \"human_label\" in batch\n pass\n elif isimage(xc):\n log[\"conditioning\"] = xc\n if ismap(xc):\n log[\"original_conditioning\"] = self.to_rgb(xc)\n\n if plot_diffusion_rows:\n # get diffusion row\n diffusion_row = list()\n z_start = z[:n_row]\n for t in range(self.num_timesteps):\n if t % self.log_every_t == 0 or t == self.num_timesteps - 1:\n t = repeat(torch.tensor([t]), '1 -> b', b=n_row)\n t = t.to(self.device).long()\n noise = torch.randn_like(z_start)\n z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)\n diffusion_row.append(self.decode_first_stage(z_noisy))\n\n diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W\n diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')\n diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')\n diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])\n log[\"diffusion_row\"] = diffusion_grid\n\n if sample:\n # get denoise row\n with ema_scope(\"Sampling\"):\n samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,\n ddim_steps=ddim_steps, eta=ddim_eta)\n # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)\n x_samples = self.decode_first_stage(samples)\n log[\"samples\"] = x_samples\n if plot_denoise_rows:\n denoise_grid = self._get_denoise_row_from_list(z_denoise_row)\n log[\"denoise_row\"] = denoise_grid\n\n if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(\n self.first_stage_model, IdentityFirstStage):\n # also display when quantizing x0 while sampling\n with ema_scope(\"Plotting Quantized Denoised\"):\n samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,\n ddim_steps=ddim_steps, eta=ddim_eta,\n quantize_denoised=True)\n # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,\n # quantize_denoised=True)\n x_samples = self.decode_first_stage(samples.to(self.device))\n log[\"samples_x0_quantized\"] = x_samples\n\n if unconditional_guidance_scale > 1.0:\n uc = self.get_unconditional_conditioning(N, unconditional_guidance_label)\n if self.model.conditioning_key == \"crossattn-adm\":\n uc = {\"c_crossattn\": [uc], \"c_adm\": c[\"c_adm\"]}\n with ema_scope(\"Sampling with classifier-free guidance\"):\n samples_cfg, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,\n ddim_steps=ddim_steps, eta=ddim_eta,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=uc,\n )\n x_samples_cfg = self.decode_first_stage(samples_cfg)\n log[f\"samples_cfg_scale_{unconditional_guidance_scale:.2f}\"] = x_samples_cfg\n\n if inpaint:\n # make a simple center square\n b, h, w = z.shape[0], z.shape[2], z.shape[3]\n mask = torch.ones(N, h, w).to(self.device)\n # zeros will be filled in\n mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.\n mask = mask[:, None, ...]\n with ema_scope(\"Plotting Inpaint\"):\n samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta,\n ddim_steps=ddim_steps, x0=z[:N], mask=mask)\n x_samples = self.decode_first_stage(samples.to(self.device))\n log[\"samples_inpainting\"] = x_samples\n log[\"mask\"] = mask\n\n # outpaint\n mask = 1. - mask\n with ema_scope(\"Plotting Outpaint\"):\n samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta,\n ddim_steps=ddim_steps, x0=z[:N], mask=mask)\n x_samples = self.decode_first_stage(samples.to(self.device))\n log[\"samples_outpainting\"] = x_samples\n\n if plot_progressive_rows:\n with ema_scope(\"Plotting Progressives\"):\n img, progressives = self.progressive_denoising(c,\n shape=(self.channels, self.image_size, self.image_size),\n batch_size=N)\n prog_row = self._get_denoise_row_from_list(progressives, desc=\"Progressive Generation\")\n log[\"progressive_row\"] = prog_row\n\n if return_keys:\n if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:\n return log\n else:\n return {key: log[key] for key in return_keys}\n return log\n\n def configure_optimizers(self):\n lr = self.learning_rate\n params = list(self.model.parameters())\n if self.cond_stage_trainable:\n print(f\"{self.__class__.__name__}: Also optimizing conditioner params!\")\n params = params + list(self.cond_stage_model.parameters())\n if self.learn_logvar:\n print('Diffusion model optimizing logvar')\n params.append(self.logvar)\n opt = torch.optim.AdamW(params, lr=lr)\n if self.use_scheduler:\n assert 'target' in self.scheduler_config\n scheduler = instantiate_from_config(self.scheduler_config)\n\n print(\"Setting up LambdaLR scheduler...\")\n scheduler = [\n {\n 'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),\n 'interval': 'step',\n 'frequency': 1\n }]\n return [opt], scheduler\n return opt\n\n @torch.no_grad()\n def to_rgb(self, x):\n x = x.float()\n if not hasattr(self, \"colorize\"):\n self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)\n x = nn.functional.conv2d(x, weight=self.colorize)\n x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.\n return x" }, { "identifier": "log_txt_as_img", "path": "ldm/util.py", "snippet": "def log_txt_as_img(wh, xc, size=10):\n # wh a tuple of (width, height)\n # xc a list of captions to plot\n b = len(xc)\n txts = list()\n for bi in range(b):\n txt = Image.new(\"RGB\", wh, color=\"white\")\n draw = ImageDraw.Draw(txt)\n font = ImageFont.truetype('font/DejaVuSans.ttf', size=size)\n nc = int(40 * (wh[0] / 256))\n lines = \"\\n\".join(xc[bi][start:start + nc] for start in range(0, len(xc[bi]), nc))\n\n try:\n draw.text((0, 0), lines, fill=\"black\", font=font)\n except UnicodeEncodeError:\n print(\"Cant encode string for logging. Skipping.\")\n\n txt = np.array(txt).transpose(2, 0, 1) / 127.5 - 1.0\n txts.append(txt)\n txts = np.stack(txts)\n txts = torch.tensor(txts)\n return txts" }, { "identifier": "instantiate_from_config", "path": "ldm/util.py", "snippet": "def instantiate_from_config(config):\n if not \"target\" in config:\n if config == '__is_first_stage__':\n return None\n elif config == \"__is_unconditional__\":\n return None\n raise KeyError(\"Expected key `target` to instantiate.\")\n return get_obj_from_str(config[\"target\"])(**config.get(\"params\", dict()))" }, { "identifier": "DDIMSampler", "path": "ldm/models/diffusion/ddim.py", "snippet": "class DDIMSampler(object):\n def __init__(self, model, schedule=\"linear\", **kwargs):\n super().__init__()\n self.model = model\n self.ddpm_num_timesteps = model.num_timesteps\n self.schedule = schedule\n\n def register_buffer(self, name, attr):\n if type(attr) == torch.Tensor:\n if attr.device != torch.device(\"cuda\"):\n attr = attr.to(torch.device(\"cuda\"))\n setattr(self, name, attr)\n\n def make_schedule(self, ddim_num_steps, ddim_discretize=\"uniform\", ddim_eta=0., verbose=True):\n self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,\n num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)\n alphas_cumprod = self.model.alphas_cumprod\n assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'\n to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)\n\n self.register_buffer('betas', to_torch(self.model.betas))\n self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))\n self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))\n\n # calculations for diffusion q(x_t | x_{t-1}) and others\n self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))\n self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))\n self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))\n\n # ddim sampling parameters\n ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),\n ddim_timesteps=self.ddim_timesteps,\n eta=ddim_eta,verbose=verbose)\n self.register_buffer('ddim_sigmas', ddim_sigmas)\n self.register_buffer('ddim_alphas', ddim_alphas)\n self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)\n self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))\n sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(\n (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (\n 1 - self.alphas_cumprod / self.alphas_cumprod_prev))\n self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)\n\n @torch.no_grad()\n def sample(self,\n S,\n batch_size,\n shape,\n conditioning=None,\n callback=None,\n normals_sequence=None,\n img_callback=None,\n quantize_x0=False,\n eta=0.,\n mask=None,\n x0=None,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n verbose=True,\n x_T=None,\n log_every_t=100,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...\n dynamic_threshold=None,\n ucg_schedule=None,\n **kwargs\n ):\n if conditioning is not None:\n if isinstance(conditioning, dict):\n ctmp = conditioning[list(conditioning.keys())[0]]\n while isinstance(ctmp, list): ctmp = ctmp[0]\n cbs = ctmp.shape[0]\n if cbs != batch_size:\n print(f\"Warning: Got {cbs} conditionings but batch-size is {batch_size}\")\n\n elif isinstance(conditioning, list):\n for ctmp in conditioning:\n if ctmp.shape[0] != batch_size:\n print(f\"Warning: Got {cbs} conditionings but batch-size is {batch_size}\")\n\n else:\n if conditioning.shape[0] != batch_size:\n print(f\"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}\")\n\n self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)\n # sampling\n C, H, W = shape\n size = (batch_size, C, H, W)\n # print(f'Data shape for DDIM sampling is {size}, eta {eta}')\n\n samples, intermediates = self.ddim_sampling(conditioning, size,\n callback=callback,\n img_callback=img_callback,\n quantize_denoised=quantize_x0,\n mask=mask, x0=x0,\n ddim_use_original_steps=False,\n noise_dropout=noise_dropout,\n temperature=temperature,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n x_T=x_T,\n log_every_t=log_every_t,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n dynamic_threshold=dynamic_threshold,\n ucg_schedule=ucg_schedule\n )\n return samples, intermediates\n\n @torch.no_grad()\n def ddim_sampling(self, cond, shape,\n x_T=None, ddim_use_original_steps=False,\n callback=None, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, img_callback=None, log_every_t=100,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None, dynamic_threshold=None,\n ucg_schedule=None):\n device = self.model.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n if timesteps is None:\n timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps\n elif timesteps is not None and not ddim_use_original_steps:\n subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1\n timesteps = self.ddim_timesteps[:subset_end]\n\n intermediates = {'x_inter': [img], 'pred_x0': [img]}\n time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)\n total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]\n # print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n # iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)\n\n for i, step in enumerate(time_range):\n index = total_steps - i - 1\n ts = torch.full((b,), step, device=device, dtype=torch.long)\n\n if mask is not None:\n assert x0 is not None\n img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?\n img = img_orig * mask + (1. - mask) * img\n\n if ucg_schedule is not None:\n assert len(ucg_schedule) == len(time_range)\n unconditional_guidance_scale = ucg_schedule[i]\n\n outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,\n quantize_denoised=quantize_denoised, temperature=temperature,\n noise_dropout=noise_dropout, score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n dynamic_threshold=dynamic_threshold)\n img, pred_x0 = outs\n if callback: callback(i)\n if img_callback: img_callback(pred_x0, i)\n\n if index % log_every_t == 0 or index == total_steps - 1:\n intermediates['x_inter'].append(img)\n intermediates['pred_x0'].append(pred_x0)\n\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None,\n dynamic_threshold=None):\n b, *_, device = *x.shape, x.device\n\n if unconditional_conditioning is None or unconditional_guidance_scale == 1.:\n model_output = self.model.apply_model(x, t, c)\n else:\n x_in = torch.cat([x] * 2)\n t_in = torch.cat([t] * 2)\n if isinstance(c, dict):\n assert isinstance(unconditional_conditioning, dict)\n c_in = dict()\n for k in c:\n if isinstance(c[k], list):\n c_in[k] = [torch.cat([\n unconditional_conditioning[k][i],\n c[k][i]]) for i in range(len(c[k]))]\n else:\n c_in[k] = torch.cat([\n unconditional_conditioning[k],\n c[k]])\n elif isinstance(c, list):\n c_in = list()\n assert isinstance(unconditional_conditioning, list)\n for i in range(len(c)):\n c_in.append(torch.cat([unconditional_conditioning[i], c[i]]))\n else:\n c_in = torch.cat([unconditional_conditioning, c])\n model_uncond, model_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)\n model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond)\n\n if self.model.parameterization == \"v\":\n e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)\n else:\n e_t = model_output\n\n if score_corrector is not None:\n assert self.model.parameterization == \"eps\", 'not implemented'\n e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)\n\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n # select parameters corresponding to the currently considered timestep\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)\n sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)\n\n # current prediction for x_0\n if self.model.parameterization != \"v\":\n pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n else:\n pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)\n\n if quantize_denoised:\n pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n\n if dynamic_threshold is not None:\n raise NotImplementedError()\n\n # direction pointing to x_t\n dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t\n noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n return x_prev, pred_x0\n\n @torch.no_grad()\n def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None,\n unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None):\n num_reference_steps = self.ddpm_num_timesteps if use_original_steps else self.ddim_timesteps.shape[0]\n\n assert t_enc <= num_reference_steps\n num_steps = t_enc\n\n if use_original_steps:\n alphas_next = self.alphas_cumprod[:num_steps]\n alphas = self.alphas_cumprod_prev[:num_steps]\n else:\n alphas_next = self.ddim_alphas[:num_steps]\n alphas = torch.tensor(self.ddim_alphas_prev[:num_steps])\n\n x_next = x0\n intermediates = []\n inter_steps = []\n for i in tqdm(range(num_steps), desc='Encoding Image'):\n t = torch.full((x0.shape[0],), i, device=self.model.device, dtype=torch.long)\n if unconditional_guidance_scale == 1.:\n noise_pred = self.model.apply_model(x_next, t, c)\n else:\n assert unconditional_conditioning is not None\n e_t_uncond, noise_pred = torch.chunk(\n self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)),\n torch.cat((unconditional_conditioning, c))), 2)\n noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond)\n\n xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next\n weighted_noise_pred = alphas_next[i].sqrt() * (\n (1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred\n x_next = xt_weighted + weighted_noise_pred\n if return_intermediates and i % (\n num_steps // return_intermediates) == 0 and i < num_steps - 1:\n intermediates.append(x_next)\n inter_steps.append(i)\n elif return_intermediates and i >= num_steps - 2:\n intermediates.append(x_next)\n inter_steps.append(i)\n if callback: callback(i)\n\n out = {'x_encoded': x_next, 'intermediate_steps': inter_steps}\n if return_intermediates:\n out.update({'intermediates': intermediates})\n return x_next, out\n\n @torch.no_grad()\n def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):\n # fast, but does not allow for exact reconstruction\n # t serves as an index to gather the correct alphas\n if use_original_steps:\n sqrt_alphas_cumprod = self.sqrt_alphas_cumprod\n sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod\n else:\n sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)\n sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas\n\n if noise is None:\n noise = torch.randn_like(x0)\n return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +\n extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)\n\n @torch.no_grad()\n def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,\n use_original_steps=False, callback=None):\n\n timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps\n timesteps = timesteps[:t_start]\n\n time_range = np.flip(timesteps)\n total_steps = timesteps.shape[0]\n print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n iterator = tqdm(time_range, desc='Decoding image', total=total_steps)\n x_dec = x_latent\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)\n x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning)\n if callback: callback(i)\n return x_dec" }, { "identifier": "instantiate_from_config", "path": "data/dataset_instantiate.py", "snippet": "def instantiate_from_config(config):\n if not \"target\" in config:\n if config == '__is_first_stage__':\n return None\n elif config == \"__is_unconditional__\":\n return None\n raise KeyError(\"Expected key `target` to instantiate.\")\n return get_obj_from_str(config[\"target\"])(config.get(\"params\", dict()))" }, { "identifier": "calculate_psnr_ssim", "path": "metrics/metrics_all.py", "snippet": "def calculate_psnr_ssim(gt_path, restored_path, test_y_channel = False, crop_border = 0, suffix = '', correct_mean_var = False, show_details =False):\n \"\"\"\n Calculate PSNR and SSIM for images.\n gt_path: Path to gt (Ground-Truth)\n restored_path: Path to restored images\n test_y_channel: If True, test Y channel (In MatLab YCbCr format). If False, test RGB channels.\n crop_border: Crop border for each side\n suffix: Suffix for restored images\n \"\"\"\n print(\"Calculate PSNR and SSIM for images\")\n psnr_all = []\n ssim_all = []\n img_list_gt = sorted(list(scandir(gt_path, recursive=True, full_path=True)))\n img_list_restored = sorted(list(scandir(restored_path, recursive=True, full_path=True)))\n\n if test_y_channel:\n print('Testing Y channel.')\n else:\n print('Testing RGB channels.')\n\n for i, img_path in tqdm(enumerate(img_list_gt)):\n basename, ext = osp.splitext(osp.basename(img_path))\n img_gt = cv2.imread(img_path, cv2.IMREAD_UNCHANGED).astype(np.float32) / 255.\n if suffix == '':\n img_path_restored = img_list_restored[i]\n else:\n img_path_restored = osp.join(restored_path, basename + suffix + ext)\n img_restored = cv2.imread(img_path_restored, cv2.IMREAD_UNCHANGED).astype(np.float32) / 255.\n # img_restored = cv2.imread(img_path_restored, cv2.IMREAD_COLOR).astype(np.float32) / 255.\n img_restored\n if correct_mean_var:\n mean_l = []\n std_l = []\n for j in range(3):\n mean_l.append(np.mean(img_gt[:, :, j]))\n std_l.append(np.std(img_gt[:, :, j]))\n for j in range(3):\n # correct twice\n mean = np.mean(img_restored[:, :, j])\n img_restored[:, :, j] = img_restored[:, :, j] - mean + mean_l[j]\n std = np.std(img_restored[:, :, j])\n img_restored[:, :, j] = img_restored[:, :, j] / std * std_l[j]\n\n mean = np.mean(img_restored[:, :, j])\n img_restored[:, :, j] = img_restored[:, :, j] - mean + mean_l[j]\n std = np.std(img_restored[:, :, j])\n img_restored[:, :, j] = img_restored[:, :, j] / std * std_l[j]\n\n if test_y_channel and img_gt.ndim == 3 and img_gt.shape[2] == 3:\n img_gt = bgr2ycbcr(img_gt, y_only=True)\n img_restored = bgr2ycbcr(img_restored, y_only=True)\n\n # calculate PSNR and SSIM\n psnr = calculate_psnr(img_gt * 255, img_restored * 255, crop_border=crop_border, input_order='HWC')\n ssim = calculate_ssim(img_gt * 255, img_restored * 255, crop_border=crop_border, input_order='HWC')\n if show_details:\n print(f'{basename + suffix + ext:25}. \\tPSNR: {psnr:.6f} dB, \\tSSIM: {ssim:.6f}')\n psnr_all.append(psnr)\n ssim_all.append(ssim)\n Average_psnr = sum(psnr_all) / len(psnr_all)\n Average_ssim = sum(ssim_all) / len(ssim_all)\n print(f'PSNR: {Average_psnr:.6f} dB, SSIM: {Average_ssim:.6f}')\n return Average_psnr, Average_ssim" }, { "identifier": "calculate_lpips", "path": "metrics/metrics_all.py", "snippet": "def calculate_lpips(gt_path, restored_path, suffix = '', show_details =False):\n \"\"\"\n Calculate LPIPS for images.\n gt_path: Path to gt (Ground-Truth)\n restored_path: Path to restored images\n suffix: Suffix for restored images\n \"\"\"\n print(\"Calculate LPIPS for images\")\n loss_fn_vgg = lpips.LPIPS(net='vgg').cuda() # RGB, normalized to [-1,1]\n lpips_all = []\n img_list = sorted(glob.glob(osp.join(gt_path, '*')))\n img_list_restored = sorted(list(scandir(restored_path, recursive=True, full_path=True)))\n\n mean = [0.5, 0.5, 0.5]\n std = [0.5, 0.5, 0.5]\n for i, img_path in tqdm(enumerate(img_list)):\n basename, ext = osp.splitext(osp.basename(img_path))\n img_gt = cv2.imread(img_path, cv2.IMREAD_UNCHANGED).astype(np.float32) / 255.\n\n if suffix == '':\n img_path_restored = img_list_restored[i]\n else:\n img_path_restored = osp.join(restored_path, basename + suffix + ext)\n img_restored = cv2.imread(img_path_restored, cv2.IMREAD_UNCHANGED).astype(np.float32) / 255. \n # img_restored = cv2.imread(img_path_restored, cv2.IMREAD_COLOR).astype(np.float32) / 255. \n\n img_gt, img_restored = img2tensor([img_gt, img_restored], bgr2rgb=True, float32=True)\n # norm to [-1, 1]\n normalize(img_gt, mean, std, inplace=True)\n normalize(img_restored, mean, std, inplace=True)\n\n # calculate lpips\n lpips_val = loss_fn_vgg(img_restored.unsqueeze(0).cuda(), img_gt.unsqueeze(0).cuda())\n lpips_val = lpips_val.cpu().item()\n if show_details:\n print(f'{i+1:3d}: {basename:25}. \\tLPIPS: {lpips_val:.6f}.')\n lpips_all.append(lpips_val)\n Average_lpips = sum(lpips_all) / len(lpips_all)\n print(f'LPIPS: {Average_lpips:.6f}')\n return Average_lpips" }, { "identifier": "calculate_NIQE", "path": "metrics/metrics_all.py", "snippet": "def calculate_NIQE(restored_path, crop_border = 0, show_details =False):\n \"\"\"\n Calculate NIQE for images.\n restored_path: Path to restored images\n crop_border: Crop border for each side\n \"\"\"\n print(\"Calculate NIQE for images\")\n niqe_all = []\n img_list = sorted(scandir(restored_path, recursive=True, full_path=True))\n\n for i, img_path in tqdm(enumerate(img_list)):\n basename, _ = os.path.splitext(os.path.basename(img_path))\n img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)\n\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', category=RuntimeWarning)\n niqe_score = calculate_niqe(img, crop_border, input_order='HWC', convert_to='y')\n if show_details:\n print(f'{i+1:3d}: {basename:25}. \\tNIQE: {niqe_score:.6f}')\n niqe_all.append(niqe_score)\n Average_niqe = sum(niqe_all) / len(niqe_all)\n print(f'NIQE: {Average_niqe:.6f}')\n return Average_niqe " }, { "identifier": "calculate_fid_folder", "path": "metrics/metrics_all.py", "snippet": "def calculate_fid_folder(restored_path):\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n fid_stats = ''\n batch_size = 64\n num_sample = 50000\n num_workers = 4\n backend = 'disk'\n\n # inception model\n inception = load_patched_inception_v3(device)\n\n # create dataset\n opt = {}\n opt['name'] = 'SingleImageDataset'\n opt['type'] = 'SingleImageDataset'\n opt['dataroot_lq'] = restored_path\n opt['io_backend'] = dict(type=backend)\n opt['mean'] = [0.5, 0.5, 0.5]\n opt['std'] = [0.5, 0.5, 0.5]\n dataset = build_dataset(opt)\n\n # create dataloader\n data_loader = DataLoader(\n dataset=dataset,\n batch_size=batch_size,\n shuffle=False,\n num_workers=num_workers,\n sampler=None,\n drop_last=False)\n num_sample = min(num_sample, len(dataset))\n total_batch = math.ceil(num_sample / batch_size)\n\n def data_generator(data_loader, total_batch):\n for idx, data in enumerate(data_loader):\n if idx >= total_batch:\n break\n else:\n yield data['lq']\n\n features = extract_inception_features(data_generator(data_loader, total_batch), inception, total_batch, device)\n features = features.numpy()\n total_len = features.shape[0]\n features = features[:num_sample]\n print(f'Extracted {total_len} features, use the first {features.shape[0]} features to calculate stats.')\n\n sample_mean = np.mean(features, 0)\n sample_cov = np.cov(features, rowvar=False)\n\n # load the dataset stats\n stats = torch.load(fid_stats)\n real_mean = stats['mean']\n real_cov = stats['cov']\n\n # calculate FID metric\n fid = calculate_fid(sample_mean, sample_cov, real_mean, real_cov)\n print('fid:', fid)\n return fid" } ]
import torch import os import numpy as np import math import shutil import safetensors.torch from ldm.modules.diffusionmodules.util import timestep_embedding from einops import rearrange, repeat from torchvision.utils import make_grid from ldm.modules.diffusionmodules.openaimodel import UNetModel from ldm.models.diffusion.ddpm import LatentDiffusion from ldm.util import log_txt_as_img, instantiate_from_config from ldm.models.diffusion.ddim import DDIMSampler from data.dataset_instantiate import instantiate_from_config as instantiate_dataset_from_config from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from metrics.metrics_all import calculate_psnr_ssim, calculate_lpips, calculate_NIQE, calculate_fid_folder from torch.utils.data import DataLoader from PIL import Image from torch.optim.lr_scheduler import LambdaLR from omegaconf import OmegaConf
20,379
def get_state_dict(d): return d.get('state_dict', d) def load_state_dict(ckpt_path, location='cpu'): _, extension = os.path.splitext(ckpt_path) if extension.lower() == ".safetensors": state_dict = safetensors.torch.load_file(ckpt_path, device=location) else: state_dict = get_state_dict(torch.load(ckpt_path, map_location=torch.device(location))) state_dict = get_state_dict(state_dict) print(f'Loaded state_dict from [{ckpt_path}]') return state_dict def create_model(config_path): config = OmegaConf.load(config_path) model = instantiate_from_config(config.model).cpu() print(f'Loaded model config from [{config_path}]') return model
def get_state_dict(d): return d.get('state_dict', d) def load_state_dict(ckpt_path, location='cpu'): _, extension = os.path.splitext(ckpt_path) if extension.lower() == ".safetensors": state_dict = safetensors.torch.load_file(ckpt_path, device=location) else: state_dict = get_state_dict(torch.load(ckpt_path, map_location=torch.device(location))) state_dict = get_state_dict(state_dict) print(f'Loaded state_dict from [{ckpt_path}]') return state_dict def create_model(config_path): config = OmegaConf.load(config_path) model = instantiate_from_config(config.model).cpu() print(f'Loaded model config from [{config_path}]') return model
class ControlledUnetModel(UNetModel):
1
2023-11-30 13:50:58+00:00
24k
IanYeung/MGLD-VSR
ldm/models/diffusion/ddpm.py
[ { "identifier": "log_txt_as_img", "path": "ldm/util.py", "snippet": "def log_txt_as_img(wh, xc, size=10):\n # wh a tuple of (width, height)\n # xc a list of captions to plot\n b = len(xc)\n txts = list()\n for bi in range(b):\n txt = Image.new(\"RGB\", wh, color=\"white\")\n draw = ImageDraw.Draw(txt)\n font = ImageFont.truetype('data/DejaVuSans.ttf', size=size)\n nc = int(40 * (wh[0] / 256))\n lines = \"\\n\".join(xc[bi][start:start + nc] for start in range(0, len(xc[bi]), nc))\n\n try:\n draw.text((0, 0), lines, fill=\"black\", font=font)\n except UnicodeEncodeError:\n print(\"Cant encode string for logging. Skipping.\")\n\n txt = np.array(txt).transpose(2, 0, 1) / 127.5 - 1.0\n txts.append(txt)\n txts = np.stack(txts)\n txts = torch.tensor(txts)\n return txts" }, { "identifier": "exists", "path": "ldm/util.py", "snippet": "def exists(x):\n return x is not None" }, { "identifier": "default", "path": "ldm/util.py", "snippet": "def default(val, d):\n if exists(val):\n return val\n return d() if isfunction(d) else d" }, { "identifier": "ismap", "path": "ldm/util.py", "snippet": "def ismap(x):\n if not isinstance(x, torch.Tensor):\n return False\n return (len(x.shape) == 4) and (x.shape[1] > 3)" }, { "identifier": "isimage", "path": "ldm/util.py", "snippet": "def isimage(x):\n if not isinstance(x, torch.Tensor):\n return False\n return (len(x.shape) == 4) and (x.shape[1] == 3 or x.shape[1] == 1)" }, { "identifier": "mean_flat", "path": "ldm/util.py", "snippet": "def mean_flat(tensor):\n \"\"\"\n https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86\n Take the mean over all non-batch dimensions.\n \"\"\"\n return tensor.mean(dim=list(range(1, len(tensor.shape))))" }, { "identifier": "count_params", "path": "ldm/util.py", "snippet": "def count_params(model, verbose=False):\n total_params = sum(p.numel() for p in model.parameters())\n if verbose:\n print(f\"{model.__class__.__name__} has {total_params * 1.e-6:.2f} M params.\")\n return total_params" }, { "identifier": "instantiate_from_config", "path": "ldm/util.py", "snippet": "def instantiate_from_config(config):\n if not \"target\" in config:\n if config == '__is_first_stage__':\n return None\n elif config == \"__is_unconditional__\":\n return None\n raise KeyError(\"Expected key `target` to instantiate.\")\n return get_obj_from_str(config[\"target\"])(**config.get(\"params\", dict()))" }, { "identifier": "LitEma", "path": "ldm/modules/ema.py", "snippet": "class LitEma(nn.Module):\n def __init__(self, model, decay=0.9999, use_num_upates=True):\n super().__init__()\n if decay < 0.0 or decay > 1.0:\n raise ValueError('Decay must be between 0 and 1')\n\n self.m_name2s_name = {}\n self.register_buffer('decay', torch.tensor(decay, dtype=torch.float32))\n self.register_buffer('num_updates', torch.tensor(0,dtype=torch.int) if use_num_upates\n else torch.tensor(-1,dtype=torch.int))\n\n for name, p in model.named_parameters():\n if p.requires_grad:\n #remove as '.'-character is not allowed in buffers\n s_name = name.replace('.','')\n self.m_name2s_name.update({name:s_name})\n self.register_buffer(s_name,p.clone().detach().data)\n\n self.collected_params = []\n\n def forward(self,model):\n decay = self.decay\n\n if self.num_updates >= 0:\n self.num_updates += 1\n decay = min(self.decay,(1 + self.num_updates) / (10 + self.num_updates))\n\n one_minus_decay = 1.0 - decay\n\n with torch.no_grad():\n m_param = dict(model.named_parameters())\n shadow_params = dict(self.named_buffers())\n\n for key in m_param:\n if m_param[key].requires_grad:\n sname = self.m_name2s_name[key]\n shadow_params[sname] = shadow_params[sname].type_as(m_param[key])\n shadow_params[sname].sub_(one_minus_decay * (shadow_params[sname] - m_param[key]))\n else:\n pass\n # assert not key in self.m_name2s_name\n\n def copy_to(self, model):\n m_param = dict(model.named_parameters())\n shadow_params = dict(self.named_buffers())\n for key in m_param:\n if m_param[key].requires_grad:\n m_param[key].data.copy_(shadow_params[self.m_name2s_name[key]].data)\n else:\n pass\n # assert not key in self.m_name2s_name\n\n def store(self, parameters):\n \"\"\"\n Save the current parameters for restoring later.\n Args:\n parameters: Iterable of `torch.nn.Parameter`; the parameters to be\n temporarily stored.\n \"\"\"\n self.collected_params = [param.clone() for param in parameters]\n\n def restore(self, parameters):\n \"\"\"\n Restore the parameters stored with the `store` method.\n Useful to validate the model with EMA parameters without affecting the\n original optimization process. Store the parameters before the\n `copy_to` method. After validation (or model saving), use this to\n restore the former parameters.\n Args:\n parameters: Iterable of `torch.nn.Parameter`; the parameters to be\n updated with the stored parameters.\n \"\"\"\n for c_param, param in zip(self.collected_params, parameters):\n param.data.copy_(c_param.data)" }, { "identifier": "normal_kl", "path": "ldm/modules/distributions/distributions.py", "snippet": "def normal_kl(mean1, logvar1, mean2, logvar2):\n \"\"\"\n source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12\n Compute the KL divergence between two gaussians.\n Shapes are automatically broadcasted, so batches can be compared to\n scalars, among other use cases.\n \"\"\"\n tensor = None\n for obj in (mean1, logvar1, mean2, logvar2):\n if isinstance(obj, torch.Tensor):\n tensor = obj\n break\n assert tensor is not None, \"at least one argument must be a Tensor\"\n\n # Force variances to be Tensors. Broadcasting helps convert scalars to\n # Tensors, but it does not work for torch.exp().\n logvar1, logvar2 = [\n x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor)\n for x in (logvar1, logvar2)\n ]\n\n return 0.5 * (\n -1.0\n + logvar2\n - logvar1\n + torch.exp(logvar1 - logvar2)\n + ((mean1 - mean2) ** 2) * torch.exp(-logvar2)\n )" }, { "identifier": "DiagonalGaussianDistribution", "path": "ldm/modules/distributions/distributions.py", "snippet": "class DiagonalGaussianDistribution(object):\n def __init__(self, parameters, deterministic=False):\n self.parameters = parameters\n self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)\n self.logvar = torch.clamp(self.logvar, -30.0, 20.0)\n self.deterministic = deterministic\n self.std = torch.exp(0.5 * self.logvar)\n self.var = torch.exp(self.logvar)\n if self.deterministic:\n self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device)\n\n def sample(self):\n x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device)\n return x\n\n def kl(self, other=None):\n if self.deterministic:\n return torch.Tensor([0.])\n else:\n if other is None:\n return 0.5 * torch.sum(torch.pow(self.mean, 2)\n + self.var - 1.0 - self.logvar,\n dim=[1, 2, 3])\n else:\n return 0.5 * torch.sum(\n torch.pow(self.mean - other.mean, 2) / other.var\n + self.var / other.var - 1.0 - self.logvar + other.logvar,\n dim=[1, 2, 3])\n\n def nll(self, sample, dims=[1,2,3]):\n if self.deterministic:\n return torch.Tensor([0.])\n logtwopi = np.log(2.0 * np.pi)\n return 0.5 * torch.sum(\n logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,\n dim=dims)\n\n def mode(self):\n return self.mean" }, { "identifier": "VQModelInterface", "path": "ldm/models/autoencoder.py", "snippet": "class VQModelInterface(VQModel):\n def __init__(self, embed_dim, *args, **kwargs):\n super().__init__(embed_dim=embed_dim, *args, **kwargs)\n self.embed_dim = embed_dim\n\n def encode(self, x):\n h = self.encoder(x)\n h = self.quant_conv(h)\n return h\n\n def decode(self, h, force_not_quantize=False):\n # also go through quantization layer\n if not force_not_quantize:\n quant, emb_loss, info = self.quantize(h)\n else:\n quant = h\n quant = self.post_quant_conv(quant)\n dec = self.decoder(quant)\n return dec" }, { "identifier": "IdentityFirstStage", "path": "ldm/models/autoencoder.py", "snippet": "class IdentityFirstStage(torch.nn.Module):\n def __init__(self, *args, vq_interface=False, **kwargs):\n self.vq_interface = vq_interface # TODO: Should be true by default but check to not break older stuff\n super().__init__()\n\n def encode(self, x, *args, **kwargs):\n return x\n\n def decode(self, x, *args, **kwargs):\n return x\n\n def quantize(self, x, *args, **kwargs):\n if self.vq_interface:\n return x, None, [None, None, None]\n return x\n\n def forward(self, x, *args, **kwargs):\n return x" }, { "identifier": "AutoencoderKL", "path": "ldm/models/autoencoder.py", "snippet": "class AutoencoderKL(pl.LightningModule):\n def __init__(self,\n ddconfig,\n lossconfig,\n embed_dim,\n ckpt_path=None,\n ignore_keys=[],\n image_key=\"image\",\n colorize_nlabels=None,\n monitor=None,\n ):\n super().__init__()\n self.image_key = image_key\n self.encoder = Encoder(**ddconfig)\n self.decoder = Decoder(**ddconfig)\n self.loss = instantiate_from_config(lossconfig)\n assert ddconfig[\"double_z\"]\n self.quant_conv = torch.nn.Conv2d(2*ddconfig[\"z_channels\"], 2*embed_dim, 1)\n self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig[\"z_channels\"], 1)\n self.embed_dim = embed_dim\n if colorize_nlabels is not None:\n assert type(colorize_nlabels)==int\n self.register_buffer(\"colorize\", torch.randn(3, colorize_nlabels, 1, 1))\n if monitor is not None:\n self.monitor = monitor\n if ckpt_path is not None:\n self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)\n\n def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):\n sd = torch.load(path, map_location=\"cpu\")\n if \"state_dict\" in list(sd.keys()):\n sd = sd[\"state_dict\"]\n keys = list(sd.keys())\n for k in keys:\n if 'first_stage_model' in k:\n sd[k[18:]] = sd[k]\n for ik in ignore_keys:\n if k.startswith(ik):\n print(\"Deleting key {} from state_dict.\".format(k))\n del sd[k]\n missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(\n sd, strict=False)\n print(f\"Encoder Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys\")\n if len(missing) > 0:\n print(f\"Missing Keys: {missing}\")\n # if len(unexpected) > 0:\n # print(f\"Unexpected Keys: {unexpected}\")\n\n def encode(self, x, return_encfea=False):\n h = self.encoder(x)\n moments = self.quant_conv(h)\n posterior = DiagonalGaussianDistribution(moments)\n if return_encfea:\n return posterior, moments\n return posterior\n\n def encode_gt(self, x, new_encoder):\n h = new_encoder(x)\n moments = self.quant_conv(h)\n posterior = DiagonalGaussianDistribution(moments)\n return posterior, moments\n\n def decode(self, z):\n z = self.post_quant_conv(z)\n dec = self.decoder(z)\n return dec\n\n def forward(self, input, sample_posterior=True):\n posterior = self.encode(input)\n if sample_posterior:\n z = posterior.sample()\n else:\n z = posterior.mode()\n dec = self.decode(z)\n return dec, posterior\n\n def get_input(self, batch, k):\n x = batch[k]\n if len(x.shape) == 3:\n x = x[..., None]\n # x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()\n x = x.to(memory_format=torch.contiguous_format).float()\n # x = x*2.0-1.0\n return x\n\n def training_step(self, batch, batch_idx, optimizer_idx):\n inputs = self.get_input(batch, self.image_key)\n reconstructions, posterior = self(inputs)\n\n if optimizer_idx == 0:\n # train encoder+decoder+logvar\n aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,\n last_layer=self.get_last_layer(), split=\"train\")\n self.log(\"aeloss\", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)\n self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False)\n return aeloss\n\n if optimizer_idx == 1:\n # train the discriminator\n discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,\n last_layer=self.get_last_layer(), split=\"train\")\n\n self.log(\"discloss\", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)\n self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False)\n return discloss\n\n def validation_step(self, batch, batch_idx):\n inputs = self.get_input(batch, self.image_key)\n reconstructions, posterior = self(inputs)\n aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, 0, self.global_step,\n last_layer=self.get_last_layer(), split=\"val\")\n\n discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, 1, self.global_step,\n last_layer=self.get_last_layer(), split=\"val\")\n\n self.log(\"val/rec_loss\", log_dict_ae[\"val/rec_loss\"])\n self.log_dict(log_dict_ae)\n self.log_dict(log_dict_disc)\n return self.log_dict\n\n def configure_optimizers(self):\n lr = self.learning_rate\n opt_ae = torch.optim.Adam(list(self.encoder.parameters())+\n list(self.decoder.parameters())+\n list(self.quant_conv.parameters())+\n list(self.post_quant_conv.parameters()),\n lr=lr, betas=(0.5, 0.9))\n opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),\n lr=lr, betas=(0.5, 0.9))\n return [opt_ae, opt_disc], []\n\n def get_last_layer(self):\n return self.decoder.conv_out.weight\n\n @torch.no_grad()\n def log_images(self, batch, only_inputs=False, **kwargs):\n log = dict()\n x = self.get_input(batch, self.image_key)\n x = x.to(self.device)\n if not only_inputs:\n xrec, posterior = self(x)\n if x.shape[1] > 3:\n # colorize with random projection\n assert xrec.shape[1] > 3\n x = self.to_rgb(x)\n xrec = self.to_rgb(xrec)\n # log[\"samples\"] = self.decode(torch.randn_like(posterior.sample()))\n log[\"reconstructions\"] = xrec\n log[\"inputs\"] = x\n return log\n\n def to_rgb(self, x):\n assert self.image_key == \"segmentation\"\n if not hasattr(self, \"colorize\"):\n self.register_buffer(\"colorize\", torch.randn(3, x.shape[1], 1, 1).to(x))\n x = F.conv2d(x, weight=self.colorize)\n x = 2.*(x-x.min())/(x.max()-x.min()) - 1.\n return x" }, { "identifier": "make_beta_schedule", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):\n if schedule == \"linear\":\n betas = (\n torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2\n )\n\n elif schedule == \"cosine\":\n timesteps = (\n torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s\n )\n alphas = timesteps / (1 + cosine_s) * np.pi / 2\n alphas = torch.cos(alphas).pow(2)\n alphas = alphas / alphas[0]\n betas = 1 - alphas[1:] / alphas[:-1]\n betas = np.clip(betas, a_min=0, a_max=0.999)\n\n elif schedule == \"sqrt_linear\":\n betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64)\n elif schedule == \"sqrt\":\n betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5\n else:\n raise ValueError(f\"schedule '{schedule}' unknown.\")\n return betas.numpy()" }, { "identifier": "extract_into_tensor", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def extract_into_tensor(a, t, x_shape):\n b, *_ = t.shape\n out = a.gather(-1, t)\n return out.reshape(b, *((1,) * (len(x_shape) - 1)))" }, { "identifier": "noise_like", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def noise_like(shape, device, repeat=False):\n repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))\n noise = lambda: torch.randn(shape, device=device)\n return repeat_noise() if repeat else noise()" }, { "identifier": "DDIMSampler", "path": "ldm/models/diffusion/ddim.py", "snippet": "class DDIMSampler(object):\n def __init__(self, model, schedule=\"linear\", **kwargs):\n super().__init__()\n self.model = model\n self.ddpm_num_timesteps = model.num_timesteps\n self.schedule = schedule\n\n def register_buffer(self, name, attr):\n if type(attr) == torch.Tensor:\n if attr.device != torch.device(\"cuda\"):\n attr = attr.to(torch.device(\"cuda\"))\n setattr(self, name, attr)\n\n def make_schedule(self, ddim_num_steps, ddim_discretize=\"uniform\", ddim_eta=0., verbose=True):\n self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,\n num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)\n alphas_cumprod = self.model.alphas_cumprod\n assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'\n to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)\n\n self.register_buffer('betas', to_torch(self.model.betas))\n self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))\n self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))\n\n # calculations for diffusion q(x_t | x_{t-1}) and others\n self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))\n self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))\n self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))\n\n # ddim sampling parameters\n ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),\n ddim_timesteps=self.ddim_timesteps,\n eta=ddim_eta,verbose=verbose)\n\n self.register_buffer('ddim_sigmas', ddim_sigmas)\n self.register_buffer('ddim_alphas', ddim_alphas)\n self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)\n self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))\n sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(\n (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (\n 1 - self.alphas_cumprod / self.alphas_cumprod_prev))\n self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)\n\n @torch.no_grad()\n def q_sample(self, x_start, t, noise=None, ddim_num_steps=200):\n self.make_schedule(ddim_num_steps=ddim_num_steps)\n noise = default(noise, lambda: torch.randn_like(x_start))\n return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +\n extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)\n\n @torch.no_grad()\n def sample(self,\n S,\n batch_size,\n shape,\n conditioning=None,\n callback=None,\n normals_sequence=None,\n img_callback=None,\n quantize_x0=False,\n eta=0.,\n mask=None,\n x0=None,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n verbose=True,\n x_T=None,\n log_every_t=100,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None,\n # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...\n **kwargs\n ):\n if conditioning is not None:\n if isinstance(conditioning, dict):\n cbs = conditioning[list(conditioning.keys())[0]].shape[0]\n if cbs != batch_size:\n print(f\"Warning: Got {cbs} conditionings but batch-size is {batch_size}\")\n else:\n if conditioning.shape[0] != batch_size:\n print(f\"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}\")\n\n self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)\n # sampling\n C, H, W = shape\n size = (batch_size, C, H, W)\n print(f'Data shape for DDIM sampling is {size}, eta {eta}')\n\n samples, intermediates = self.ddim_sampling(conditioning, size,\n callback=callback,\n img_callback=img_callback,\n quantize_denoised=quantize_x0,\n mask=mask, x0=x0,\n ddim_use_original_steps=False,\n noise_dropout=noise_dropout,\n temperature=temperature,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n x_T=x_T,\n log_every_t=log_every_t,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n )\n return samples, intermediates\n\n @torch.no_grad()\n def ddim_sampling(self, cond, shape,\n x_T=None, ddim_use_original_steps=False,\n callback=None, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, img_callback=None, log_every_t=100,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None,):\n device = self.model.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n if timesteps is None:\n timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps\n elif timesteps is not None and not ddim_use_original_steps:\n subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1\n timesteps = self.ddim_timesteps[:subset_end]\n\n intermediates = {'x_inter': [img], 'pred_x0': [img]}\n time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)\n total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]\n print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)\n\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((b,), step, device=device, dtype=torch.long)\n\n if mask is not None:\n assert x0 is not None\n img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?\n img = img_orig * mask + (1. - mask) * img\n\n outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,\n quantize_denoised=quantize_denoised, temperature=temperature,\n noise_dropout=noise_dropout, score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning)\n img, pred_x0 = outs\n if callback: callback(i)\n if img_callback: img_callback(pred_x0, i)\n\n if index % log_every_t == 0 or index == total_steps - 1:\n intermediates['x_inter'].append(img)\n intermediates['pred_x0'].append(pred_x0)\n\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None):\n b, *_, device = *x.shape, x.device\n\n if unconditional_conditioning is None or unconditional_guidance_scale == 1.:\n e_t = self.model.apply_model(x, t, c)\n else:\n x_in = torch.cat([x] * 2)\n t_in = torch.cat([t] * 2)\n c_in = torch.cat([unconditional_conditioning, c])\n e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)\n e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)\n\n if score_corrector is not None:\n assert self.model.parameterization == \"eps\"\n e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)\n\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n # select parameters corresponding to the currently considered timestep\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)\n sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)\n\n # current prediction for x_0\n pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n if quantize_denoised:\n pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n # direction pointing to x_t\n dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t\n noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n return x_prev, pred_x0\n\n @torch.no_grad()\n def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):\n # fast, but does not allow for exact reconstruction\n # t serves as an index to gather the correct alphas\n if use_original_steps:\n sqrt_alphas_cumprod = self.sqrt_alphas_cumprod\n sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod\n else:\n sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)\n sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas\n\n if noise is None:\n noise = torch.randn_like(x0)\n return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +\n extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)\n\n @torch.no_grad()\n def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,\n use_original_steps=False):\n\n timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps\n timesteps = timesteps[:t_start]\n\n time_range = np.flip(timesteps)\n total_steps = timesteps.shape[0]\n print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n iterator = tqdm(time_range, desc='Decoding image', total=total_steps)\n x_dec = x_latent\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)\n x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning)\n return x_dec\n\n\n @torch.no_grad()\n def p_sample_ddim_sr(self, x, c, struct_c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None):\n b, *_, device = *x.shape, x.device\n\n if unconditional_conditioning is None or unconditional_guidance_scale == 1.:\n e_t = self.model.apply_model(x, t, c, struct_c)\n else:\n x_in = torch.cat([x] * 2)\n t_in = torch.cat([t] * 2)\n c_in = torch.cat([unconditional_conditioning, c])\n e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in, struct_c).chunk(2)\n e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)\n\n if score_corrector is not None:\n assert self.model.parameterization == \"eps\"\n e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)\n\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n # select parameters corresponding to the currently considered timestep\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)\n sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)\n\n # current prediction for x_0\n pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n if quantize_denoised:\n pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n # direction pointing to x_t\n dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t\n noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n return x_prev, pred_x0\n\n @torch.no_grad()\n def decode_sr(self, x_latent, cond, struct_cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,\n use_original_steps=False):\n\n timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps\n timesteps = timesteps[:t_start]\n\n time_range = np.flip(timesteps)\n total_steps = timesteps.shape[0]\n print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n iterator = tqdm(time_range, desc='Decoding image', total=total_steps)\n x_dec = x_latent\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)\n x_dec, _ = self.p_sample_ddim_sr(x_dec, cond, struct_cond, ts, index=index, use_original_steps=use_original_steps,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning)\n return x_dec\n\n @torch.no_grad()\n def sample_sr(self,\n S,\n batch_size,\n shape,\n conditioning=None,\n struct_cond=None,\n callback=None,\n normals_sequence=None,\n img_callback=None,\n quantize_x0=False,\n eta=0.,\n mask=None,\n x0=None,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n verbose=True,\n x_T=None,\n log_every_t=100,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None,\n # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...\n **kwargs\n ):\n if conditioning is not None:\n if isinstance(conditioning, dict):\n cbs = conditioning[list(conditioning.keys())[0]].shape[0]\n if cbs != batch_size:\n print(f\"Warning: Got {cbs} conditionings but batch-size is {batch_size}\")\n else:\n if conditioning.shape[0] != batch_size:\n print(f\"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}\")\n\n self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)\n # sampling\n _, C, H, W = shape\n size = (batch_size, C, H, W)\n print(f'Data shape for DDIM sampling is {size}, eta {eta}')\n\n samples, intermediates = self.ddim_sampling_sr(conditioning, struct_cond, size,\n callback=callback,\n img_callback=img_callback,\n quantize_denoised=quantize_x0,\n mask=mask, x0=x0,\n ddim_use_original_steps=False,\n noise_dropout=noise_dropout,\n temperature=temperature,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n x_T=x_T,\n log_every_t=log_every_t,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n )\n return samples, intermediates\n\n @torch.no_grad()\n def ddim_sampling_sr(self, cond, struct_cond, shape,\n x_T=None, ddim_use_original_steps=False,\n callback=None, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, img_callback=None, log_every_t=100,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None,):\n device = self.model.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n if timesteps is None:\n timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps\n elif timesteps is not None and not ddim_use_original_steps:\n subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1\n timesteps = self.ddim_timesteps[:subset_end]\n\n intermediates = {'x_inter': [img], 'pred_x0': [img]}\n time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)\n total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]\n print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)\n\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((b,), step, device=device, dtype=torch.long)\n\n if mask is not None:\n assert x0 is not None\n img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?\n img = img_orig * mask + (1. - mask) * img\n\n outs = self.p_sample_ddim_sr(img, cond, struct_cond, ts, index=index, use_original_steps=ddim_use_original_steps,\n quantize_denoised=quantize_denoised, temperature=temperature,\n noise_dropout=noise_dropout, score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning)\n img, pred_x0 = outs\n if callback: callback(i)\n if img_callback: img_callback(pred_x0, i)\n\n if index % log_every_t == 0 or index == total_steps - 1:\n intermediates['x_inter'].append(img)\n intermediates['pred_x0'].append(pred_x0)\n\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_ddim_sr(self, x, c, struct_c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None):\n b, *_, device = *x.shape, x.device\n\n if unconditional_conditioning is None or unconditional_guidance_scale == 1.:\n e_t = self.model.apply_model(x, t, c, struct_c)\n else:\n x_in = torch.cat([x] * 2)\n t_in = torch.cat([t] * 2)\n c_in = torch.cat([unconditional_conditioning, c])\n e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in, struct_c).chunk(2)\n e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)\n\n if score_corrector is not None:\n assert self.model.parameterization == \"eps\"\n e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)\n\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n # select parameters corresponding to the currently considered timestep\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)\n sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)\n\n # current prediction for x_0\n pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n if quantize_denoised:\n pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n # direction pointing to x_t\n dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t\n noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n return x_prev, pred_x0\n\n\n @torch.no_grad()\n def sample_sr_t(self,\n S,\n batch_size,\n shape,\n conditioning=None,\n struct_cond=None,\n callback=None,\n normals_sequence=None,\n img_callback=None,\n quantize_x0=False,\n eta=0.,\n mask=None,\n x0=None,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n verbose=True,\n x_T=None,\n log_every_t=100,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None,\n # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...\n **kwargs\n ):\n if conditioning is not None:\n if isinstance(conditioning, dict):\n cbs = conditioning[list(conditioning.keys())[0]].shape[0]\n if cbs != batch_size:\n print(f\"Warning: Got {cbs} conditionings but batch-size is {batch_size}\")\n else:\n if conditioning.shape[0] != batch_size:\n print(f\"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}\")\n\n self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)\n # sampling\n _, C, H, W = shape\n size = (batch_size, C, H, W)\n print(f'Data shape for DDIM sampling is {size}, eta {eta}')\n\n samples, intermediates = self.ddim_sampling_sr_t(conditioning, struct_cond, size,\n callback=callback,\n img_callback=img_callback,\n quantize_denoised=quantize_x0,\n mask=mask, x0=x0,\n ddim_use_original_steps=False,\n noise_dropout=noise_dropout,\n temperature=temperature,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n x_T=x_T,\n log_every_t=log_every_t,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n )\n return samples, intermediates\n\n @torch.no_grad()\n def ddim_sampling_sr_t(self, cond, struct_cond, shape,\n x_T=None, ddim_use_original_steps=False,\n callback=None, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, img_callback=None, log_every_t=100,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None,):\n device = self.model.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n if timesteps is None:\n timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps\n # timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else sorted(set(space_timesteps(1000, [self.ddim_timesteps.shape[0]])))\n timesteps = np.array(timesteps)\n elif timesteps is not None and not ddim_use_original_steps:\n subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1\n timesteps = self.ddim_timesteps[:subset_end]\n\n intermediates = {'x_inter': [img], 'pred_x0': [img]}\n time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)\n total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]\n print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)\n\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((b,), step, device=device, dtype=torch.long)\n\n if mask is not None:\n assert x0 is not None\n img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?\n img = img_orig * mask + (1. - mask) * img\n\n outs = self.p_sample_ddim_sr_t(img, cond, struct_cond, ts, index=index, use_original_steps=ddim_use_original_steps,\n quantize_denoised=quantize_denoised, temperature=temperature,\n noise_dropout=noise_dropout, score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning)\n img, pred_x0 = outs\n if callback: callback(i)\n if img_callback: img_callback(pred_x0, i)\n\n if index % log_every_t == 0 or index == total_steps - 1:\n intermediates['x_inter'].append(img)\n intermediates['pred_x0'].append(pred_x0)\n\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_ddim_sr_t(self, x, c, struct_c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None):\n b, *_, device = *x.shape, x.device\n\n if unconditional_conditioning is None or unconditional_guidance_scale == 1.:\n struct_c_t = self.model.structcond_stage_model(struct_c, t)\n e_t = self.model.apply_model(x, t, c, struct_c_t)\n else:\n assert NotImplementedError\n x_in = torch.cat([x] * 2)\n t_in = torch.cat([t] * 2)\n c_in = torch.cat([unconditional_conditioning, c])\n e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in, struct_c).chunk(2)\n e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)\n\n if score_corrector is not None:\n assert self.model.parameterization == \"eps\"\n e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)\n\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n # select parameters corresponding to the currently considered timestep\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)\n sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)\n\n # current prediction for x_0\n pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n if quantize_denoised:\n pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n # direction pointing to x_t\n dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t\n noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n return x_prev, pred_x0" }, { "identifier": "DiffJPEG", "path": "basicsr/utils/diffjpeg.py", "snippet": "class DiffJPEG(nn.Module):\n \"\"\"This JPEG algorithm result is slightly different from cv2.\n DiffJPEG supports batch processing.\n\n Args:\n differentiable(bool): If True, uses custom differentiable rounding function, if False, uses standard torch.round\n \"\"\"\n\n def __init__(self, differentiable=True):\n super(DiffJPEG, self).__init__()\n if differentiable:\n rounding = diff_round\n else:\n rounding = torch.round\n\n self.compress = CompressJpeg(rounding=rounding)\n self.decompress = DeCompressJpeg(rounding=rounding)\n\n def forward(self, x, quality):\n \"\"\"\n Args:\n x (Tensor): Input image, bchw, rgb, [0, 1]\n quality(float): Quality factor for jpeg compression scheme.\n \"\"\"\n factor = quality\n if isinstance(factor, (int, float)):\n factor = quality_to_factor(factor)\n else:\n for i in range(factor.size(0)):\n factor[i] = quality_to_factor(factor[i])\n h, w = x.size()[-2:]\n h_pad, w_pad = 0, 0\n # why should use 16\n if h % 16 != 0:\n h_pad = 16 - h % 16\n if w % 16 != 0:\n w_pad = 16 - w % 16\n x = F.pad(x, (0, w_pad, 0, h_pad), mode='constant', value=0)\n\n y, cb, cr = self.compress(x, factor=factor)\n recovered = self.decompress(y, cb, cr, (h + h_pad), (w + w_pad), factor=factor)\n recovered = recovered[:, :, 0:h, 0:w]\n return recovered" }, { "identifier": "USMSharp", "path": "basicsr/utils/img_process_util.py", "snippet": "class USMSharp(torch.nn.Module):\n\n def __init__(self, radius=50, sigma=0):\n super(USMSharp, self).__init__()\n if radius % 2 == 0:\n radius += 1\n self.radius = radius\n kernel = cv2.getGaussianKernel(radius, sigma)\n kernel = torch.FloatTensor(np.dot(kernel, kernel.transpose())).unsqueeze_(0)\n self.register_buffer('kernel', kernel)\n\n def forward(self, img, weight=0.5, threshold=10):\n blur = filter2D(img, self.kernel)\n residual = img - blur\n\n mask = torch.abs(residual) * 255 > threshold\n mask = mask.float()\n soft_mask = filter2D(mask, self.kernel)\n sharp = img + weight * residual\n sharp = torch.clip(sharp, 0, 1)\n return soft_mask * sharp + (1 - soft_mask) * img" }, { "identifier": "filter2D", "path": "basicsr/utils/img_process_util.py", "snippet": "def filter2D(img, kernel):\n \"\"\"PyTorch version of cv2.filter2D\n\n Args:\n img (Tensor): (b, c, h, w)\n kernel (Tensor): (b, k, k)\n \"\"\"\n k = kernel.size(-1)\n b, c, h, w = img.size()\n if k % 2 == 1:\n img = F.pad(img, (k // 2, k // 2, k // 2, k // 2), mode='reflect')\n else:\n raise ValueError('Wrong kernel size')\n\n ph, pw = img.size()[-2:]\n\n if kernel.size(0) == 1:\n # apply the same kernel to all batch images\n img = img.view(b * c, 1, ph, pw)\n kernel = kernel.view(1, 1, k, k)\n return F.conv2d(img, kernel, padding=0).view(b, c, h, w)\n else:\n img = img.view(1, b * c, ph, pw)\n kernel = kernel.view(b, 1, k, k).repeat(1, c, 1, 1).view(b * c, 1, k, k)\n return F.conv2d(img, kernel, groups=b * c).view(b, c, h, w)" }, { "identifier": "paired_random_crop", "path": "basicsr/data/transforms.py", "snippet": "def paired_random_crop(img_gts, img_lqs, gt_patch_size, scale, gt_path=None):\n \"\"\"Paired random crop. Support Numpy array and Tensor inputs.\n\n It crops lists of lq and gt images with corresponding locations.\n\n Args:\n img_gts (list[ndarray] | ndarray | list[Tensor] | Tensor): GT images. Note that all images\n should have the same shape. If the input is an ndarray, it will\n be transformed to a list containing itself.\n img_lqs (list[ndarray] | ndarray): LQ images. Note that all images\n should have the same shape. If the input is an ndarray, it will\n be transformed to a list containing itself.\n gt_patch_size (int): GT patch size.\n scale (int): Scale factor.\n gt_path (str): Path to ground-truth. Default: None.\n\n Returns:\n list[ndarray] | ndarray: GT images and LQ images. If returned results\n only have one element, just return ndarray.\n \"\"\"\n\n if not isinstance(img_gts, list):\n img_gts = [img_gts]\n if not isinstance(img_lqs, list):\n img_lqs = [img_lqs]\n\n # determine input type: Numpy array or Tensor\n input_type = 'Tensor' if torch.is_tensor(img_gts[0]) else 'Numpy'\n\n if input_type == 'Tensor':\n h_lq, w_lq = img_lqs[0].size()[-2:]\n h_gt, w_gt = img_gts[0].size()[-2:]\n else:\n h_lq, w_lq = img_lqs[0].shape[0:2]\n h_gt, w_gt = img_gts[0].shape[0:2]\n lq_patch_size = gt_patch_size // scale\n\n if h_gt != h_lq * scale or w_gt != w_lq * scale:\n raise ValueError(f'Scale mismatches. GT ({h_gt}, {w_gt}) is not {scale}x ',\n f'multiplication of LQ ({h_lq}, {w_lq}).')\n if h_lq < lq_patch_size or w_lq < lq_patch_size:\n raise ValueError(f'LQ ({h_lq}, {w_lq}) is smaller than patch size '\n f'({lq_patch_size}, {lq_patch_size}). '\n f'Please remove {gt_path}.')\n\n # randomly choose top and left coordinates for lq patch\n top = random.randint(0, h_lq - lq_patch_size)\n left = random.randint(0, w_lq - lq_patch_size)\n\n # crop lq patch\n if input_type == 'Tensor':\n img_lqs = [v[:, :, top:top + lq_patch_size, left:left + lq_patch_size] for v in img_lqs]\n else:\n img_lqs = [v[top:top + lq_patch_size, left:left + lq_patch_size, ...] for v in img_lqs]\n\n # crop corresponding gt patch\n top_gt, left_gt = int(top * scale), int(left * scale)\n if input_type == 'Tensor':\n img_gts = [v[:, :, top_gt:top_gt + gt_patch_size, left_gt:left_gt + gt_patch_size] for v in img_gts]\n else:\n img_gts = [v[top_gt:top_gt + gt_patch_size, left_gt:left_gt + gt_patch_size, ...] for v in img_gts]\n if len(img_gts) == 1:\n img_gts = img_gts[0]\n if len(img_lqs) == 1:\n img_lqs = img_lqs[0]\n return img_gts, img_lqs" }, { "identifier": "triplet_random_crop", "path": "basicsr/data/transforms.py", "snippet": "def triplet_random_crop(img_gts, img_lqs, img_segs, gt_patch_size, scale, gt_path=None):\n\n if not isinstance(img_gts, list):\n img_gts = [img_gts]\n if not isinstance(img_lqs, list):\n img_lqs = [img_lqs]\n if not isinstance(img_segs, list):\n img_segs = [img_segs]\n\n # determine input type: Numpy array or Tensor\n input_type = 'Tensor' if torch.is_tensor(img_gts[0]) else 'Numpy'\n\n if input_type == 'Tensor':\n h_lq, w_lq = img_lqs[0].size()[-2:]\n h_gt, w_gt = img_gts[0].size()[-2:]\n h_seg, w_seg = img_segs[0].size()[-2:]\n else:\n h_lq, w_lq = img_lqs[0].shape[0:2]\n h_gt, w_gt = img_gts[0].shape[0:2]\n h_seg, w_seg = img_segs[0].shape[0:2]\n lq_patch_size = gt_patch_size // scale\n\n if h_gt != h_lq * scale or w_gt != w_lq * scale:\n raise ValueError(f'Scale mismatches. GT ({h_gt}, {w_gt}) is not {scale}x ',\n f'multiplication of LQ ({h_lq}, {w_lq}).')\n if h_lq < lq_patch_size or w_lq < lq_patch_size:\n raise ValueError(f'LQ ({h_lq}, {w_lq}) is smaller than patch size '\n f'({lq_patch_size}, {lq_patch_size}). '\n f'Please remove {gt_path}.')\n\n # randomly choose top and left coordinates for lq patch\n top = random.randint(0, h_lq - lq_patch_size)\n left = random.randint(0, w_lq - lq_patch_size)\n\n # crop lq patch\n if input_type == 'Tensor':\n img_lqs = [v[:, :, top:top + lq_patch_size, left:left + lq_patch_size] for v in img_lqs]\n else:\n img_lqs = [v[top:top + lq_patch_size, left:left + lq_patch_size, ...] for v in img_lqs]\n\n # crop corresponding gt patch\n top_gt, left_gt = int(top * scale), int(left * scale)\n if input_type == 'Tensor':\n img_gts = [v[:, :, top_gt:top_gt + gt_patch_size, left_gt:left_gt + gt_patch_size] for v in img_gts]\n else:\n img_gts = [v[top_gt:top_gt + gt_patch_size, left_gt:left_gt + gt_patch_size, ...] for v in img_gts]\n\n if input_type == 'Tensor':\n img_segs = [v[:, :, top_gt:top_gt + gt_patch_size, left_gt:left_gt + gt_patch_size] for v in img_segs]\n else:\n img_segs = [v[top_gt:top_gt + gt_patch_size, left_gt:left_gt + gt_patch_size, ...] for v in img_segs]\n\n if len(img_gts) == 1:\n img_gts = img_gts[0]\n if len(img_lqs) == 1:\n img_lqs = img_lqs[0]\n if len(img_segs) == 1:\n img_segs = img_segs[0]\n\n return img_gts, img_lqs, img_segs" }, { "identifier": "random_add_gaussian_noise_pt", "path": "basicsr/data/degradations.py", "snippet": "def random_add_gaussian_noise_pt(img, sigma_range=(0, 1.0), gray_prob=0, clip=True, rounds=False):\n noise = random_generate_gaussian_noise_pt(img, sigma_range, gray_prob)\n out = img + noise\n if clip and rounds:\n out = torch.clamp((out * 255.0).round(), 0, 255) / 255.\n elif clip:\n out = torch.clamp(out, 0, 1)\n elif rounds:\n out = (out * 255.0).round() / 255.\n return out" }, { "identifier": "random_add_poisson_noise_pt", "path": "basicsr/data/degradations.py", "snippet": "def random_add_poisson_noise_pt(img, scale_range=(0, 1.0), gray_prob=0, clip=True, rounds=False):\n noise = random_generate_poisson_noise_pt(img, scale_range, gray_prob)\n out = img + noise\n if clip and rounds:\n out = torch.clamp((out * 255.0).round(), 0, 255) / 255.\n elif clip:\n out = torch.clamp(out, 0, 1)\n elif rounds:\n out = (out * 255.0).round() / 255.\n return out" }, { "identifier": "random_add_speckle_noise_pt", "path": "basicsr/data/degradations.py", "snippet": "def random_add_speckle_noise_pt(img, speckle_std):\n std_range = speckle_std\n std_l = std_range[0]\n std_r = std_range[1]\n mean=0\n std=random.uniform(std_l/255.,std_r/255.)\n gauss=torch.normal(mean=mean,std=std,size=img.size()).to(img.device)\n noisy=img+gauss*img\n noisy=torch.clamp(noisy,0,1)\n return noisy" }, { "identifier": "random_add_saltpepper_noise_pt", "path": "basicsr/data/degradations.py", "snippet": "def random_add_saltpepper_noise_pt(imgs, saltpepper_amount, saltpepper_svsp):\n p_range = saltpepper_amount\n p = random.uniform(p_range[0], p_range[1])\n q_range = saltpepper_svsp\n q = random.uniform(q_range[0], q_range[1])\n\n imgs = imgs.permute(0,2,3,1)\n\n outputs = []\n for i in range(imgs.size(0)):\n img = imgs[i]\n out = img.clone()\n flipped = np.random.choice([True, False], size=img.shape,\n p=[p, 1 - p])\n salted = np.random.choice([True, False], size=img.shape,\n p=[q, 1 - q])\n peppered = ~salted\n temp = flipped & salted\n out[flipped & salted] = 1\n out[flipped & peppered] = 0.\n noisy = torch.clamp(out, 0, 1)\n\n outputs.append(noisy.permute(2,0,1))\n if len(outputs)>1:\n return torch.cat(outputs, dim=0)\n else:\n return outputs[0].unsqueeze(0)" }, { "identifier": "bivariate_Gaussian", "path": "basicsr/data/degradations.py", "snippet": "def bivariate_Gaussian(kernel_size, sig_x, sig_y, theta, grid=None, isotropic=True):\n \"\"\"Generate a bivariate isotropic or anisotropic Gaussian kernel.\n\n In the isotropic mode, only `sig_x` is used. `sig_y` and `theta` is ignored.\n\n Args:\n kernel_size (int):\n sig_x (float):\n sig_y (float):\n theta (float): Radian measurement.\n grid (ndarray, optional): generated by :func:`mesh_grid`,\n with the shape (K, K, 2), K is the kernel size. Default: None\n isotropic (bool):\n\n Returns:\n kernel (ndarray): normalized kernel.\n \"\"\"\n if grid is None:\n grid, _, _ = mesh_grid(kernel_size)\n if isotropic:\n sigma_matrix = np.array([[sig_x**2, 0], [0, sig_x**2]])\n else:\n sigma_matrix = sigma_matrix2(sig_x, sig_y, theta)\n kernel = pdf2(sigma_matrix, grid)\n kernel = kernel / np.sum(kernel)\n return kernel" }, { "identifier": "flow_warp", "path": "basicsr/archs/arch_util.py", "snippet": "def flow_warp(x, flow, interp_mode='bilinear', padding_mode='zeros', align_corners=True, return_mask=False):\n \"\"\"Warp an image or feature map with optical flow.\n\n Args:\n x (Tensor): Tensor with size (n, c, h, w).\n flow (Tensor): Tensor with size (n, h, w, 2), normal value.\n interp_mode (str): 'nearest' or 'bilinear'. Default: 'bilinear'.\n padding_mode (str): 'zeros' or 'border' or 'reflection'.\n Default: 'zeros'.\n align_corners (bool): Before pytorch 1.3, the default value is\n align_corners=True. After pytorch 1.3, the default value is\n align_corners=False. Here, we use the True as default.\n\n Returns:\n Tensor: Warped image or feature map.\n \"\"\"\n assert x.size()[-2:] == flow.size()[1:3]\n _, _, h, w = x.size()\n # create mesh grid\n grid_y, grid_x = torch.meshgrid(torch.arange(0, h).type_as(x), torch.arange(0, w).type_as(x))\n grid = torch.stack((grid_x, grid_y), 2).float() # W(x), H(y), 2\n grid.requires_grad = False\n\n vgrid = grid + flow\n # scale grid to [-1,1]\n vgrid_x = 2.0 * vgrid[:, :, :, 0] / max(w - 1, 1) - 1.0\n vgrid_y = 2.0 * vgrid[:, :, :, 1] / max(h - 1, 1) - 1.0\n vgrid_scaled = torch.stack((vgrid_x, vgrid_y), dim=3)\n output = F.grid_sample(x, vgrid_scaled, mode=interp_mode, padding_mode=padding_mode, align_corners=align_corners)\n \n # TODO, what if align_corners=False\n if not return_mask:\n return output\n\n mask = torch.ones_like(x)\n mask = F.grid_sample(mask, vgrid_scaled, mode=interp_mode, padding_mode=padding_mode, align_corners=align_corners)\n mask[mask < 0.9999] = 0\n mask[mask > 0.0000] = 1\n return output, mask" }, { "identifier": "resize_flow", "path": "basicsr/archs/arch_util.py", "snippet": "def resize_flow(flow, size_type, sizes, interp_mode='bilinear', align_corners=False):\n \"\"\"Resize a flow according to ratio or shape.\n\n Args:\n flow (Tensor): Precomputed flow. shape [N, 2, H, W].\n size_type (str): 'ratio' or 'shape'.\n sizes (list[int | float]): the ratio for resizing or the final output\n shape.\n 1) The order of ratio should be [ratio_h, ratio_w]. For\n downsampling, the ratio should be smaller than 1.0 (i.e., ratio\n < 1.0). For upsampling, the ratio should be larger than 1.0 (i.e.,\n ratio > 1.0).\n 2) The order of output_size should be [out_h, out_w].\n interp_mode (str): The mode of interpolation for resizing.\n Default: 'bilinear'.\n align_corners (bool): Whether align corners. Default: False.\n\n Returns:\n Tensor: Resized flow.\n \"\"\"\n _, _, flow_h, flow_w = flow.size()\n if size_type == 'ratio':\n output_h, output_w = int(flow_h * sizes[0]), int(flow_w * sizes[1])\n elif size_type == 'shape':\n output_h, output_w = sizes[0], sizes[1]\n else:\n raise ValueError(f'Size type should be ratio or shape, but got type {size_type}.')\n\n input_flow = flow.clone()\n ratio_h = output_h / flow_h\n ratio_w = output_w / flow_w\n input_flow[:, 0, :, :] *= ratio_w\n input_flow[:, 1, :, :] *= ratio_h\n resized_flow = F.interpolate(\n input=input_flow, size=(output_h, output_w), mode=interp_mode, align_corners=align_corners)\n return resized_flow" }, { "identifier": "forward_backward_consistency_check", "path": "scripts/util_flow.py", "snippet": "def forward_backward_consistency_check(fwd_flow,\n bwd_flow,\n alpha=0.01,\n beta=0.5):\n # fwd_flow, bwd_flow: [B, 2, H, W]\n # alpha and beta values are following UnFlow\n # (https://arxiv.org/abs/1711.07837)\n assert fwd_flow.dim() == 4 and bwd_flow.dim() == 4\n assert fwd_flow.size(1) == 2 and bwd_flow.size(1) == 2\n flow_mag = torch.norm(fwd_flow, dim=1) + torch.norm(bwd_flow, dim=1) # [B, H, W]\n\n warped_bwd_flow = flow_warp(bwd_flow, fwd_flow) # [B, 2, H, W]\n warped_fwd_flow = flow_warp(fwd_flow, bwd_flow) # [B, 2, H, W]\n\n diff_fwd = torch.norm(fwd_flow + warped_bwd_flow, dim=1) # [B, H, W]\n diff_bwd = torch.norm(bwd_flow + warped_fwd_flow, dim=1)\n\n threshold = alpha * flow_mag + beta\n\n fwd_occ = (diff_fwd > threshold).float() # [B, H, W]\n bwd_occ = (diff_bwd > threshold).float()\n\n return fwd_occ, bwd_occ" }, { "identifier": "get_warped_and_mask", "path": "scripts/util_flow.py", "snippet": "@torch.no_grad()\ndef get_warped_and_mask(flow_model,\n image1,\n image2,\n image3=None,\n pixel_consistency=False):\n if image3 is None:\n image3 = image1\n padder = InputPadder(image1.shape, padding_factor=8)\n image1, image2 = padder.pad(image1[None].cuda(), image2[None].cuda())\n results_dict = flow_model(image1,\n image2,\n attn_splits_list=[2],\n corr_radius_list=[-1],\n prop_radius_list=[-1],\n pred_bidir_flow=True)\n flow_pr = results_dict['flow_preds'][-1] # [B, 2, H, W]\n fwd_flow = padder.unpad(flow_pr[0]).unsqueeze(0) # [1, 2, H, W]\n bwd_flow = padder.unpad(flow_pr[1]).unsqueeze(0) # [1, 2, H, W]\n fwd_occ, bwd_occ = forward_backward_consistency_check(\n fwd_flow, bwd_flow) # [1, H, W] float\n if pixel_consistency:\n warped_image1 = flow_warp(image1, bwd_flow)\n bwd_occ = torch.clamp(\n bwd_occ + (abs(image2 - warped_image1).mean(dim=1) > 255 * 0.25).float(), 0, 1\n ).unsqueeze(0)\n warped_results = flow_warp(image3, bwd_flow)\n return warped_results, bwd_occ, bwd_flow" }, { "identifier": "make_ddim_timesteps", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True):\n if ddim_discr_method == 'uniform':\n c = num_ddpm_timesteps // num_ddim_timesteps\n ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c)))\n elif ddim_discr_method == 'quad':\n ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int)\n else:\n raise NotImplementedError(f'There is no ddim discretization method called \"{ddim_discr_method}\"')\n\n # assert ddim_timesteps.shape[0] == num_ddim_timesteps\n # add one to get the final alpha values right (the ones from first scale to data during sampling)\n steps_out = ddim_timesteps\n if verbose:\n print(f'Selected timesteps for ddim sampler: {steps_out}')\n return steps_out" } ]
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import pytorch_lightning as pl import random import torch.nn.functional as F import copy import os import cv2 import matplotlib.pyplot as plt import numpy as np import numpy as np from torch.optim.lr_scheduler import LambdaLR from einops import rearrange, repeat from contextlib import contextmanager from functools import partial from tqdm import tqdm from torchvision.utils import make_grid from pytorch_lightning.utilities.distributed import rank_zero_only from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config from ldm.modules.ema import LitEma from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution from ldm.models.autoencoder import VQModelInterface, IdentityFirstStage, AutoencoderKL from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like from ldm.models.diffusion.ddim import DDIMSampler from basicsr.utils import DiffJPEG, USMSharp from basicsr.utils.img_process_util import filter2D from basicsr.data.transforms import paired_random_crop, triplet_random_crop from basicsr.data.degradations import random_add_gaussian_noise_pt, random_add_poisson_noise_pt, random_add_speckle_noise_pt, random_add_saltpepper_noise_pt, bivariate_Gaussian from basicsr.archs.arch_util import flow_warp, resize_flow from scripts.util_flow import forward_backward_consistency_check, get_warped_and_mask from ldm.modules.diffusionmodules.util import make_ddim_timesteps from sklearn.decomposition import PCA from numpy import pi, exp, sqrt from numpy import pi, exp, sqrt
20,877
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(",")] #[250,] 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) def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__(self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0., v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1., conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0., ): super().__init__() assert parameterization in ["eps", "x0", "v"], 'currently only supporting "eps" and "x0" and "v"' self.parameterization = parameterization print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if monitor is not None: self.monitor = monitor if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet) self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) self.loss_type = loss_type self.learn_logvar = learn_logvar self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y'} def torch2img(input): input_ = input[0] input_ = input_.permute(1,2,0) input_ = input_.data.cpu().numpy() input_ = (input_ + 1.0) / 2 cv2.imwrite('./test.png', input_[:,:,::-1]*255.0) def cal_pca_components(input, n_components=3): pca = PCA(n_components=n_components) c, h, w = input.size() pca_data = input.permute(1,2,0) pca_data = pca_data.reshape(h*w, c) pca_data = pca.fit_transform(pca_data.data.cpu().numpy()) pca_data = pca_data.reshape((h, w, n_components)) return pca_data def visualize_fea(save_path, fea_img): fig = plt.figure(figsize = (fea_img.shape[1]/10, fea_img.shape[0]/10)) # Your image (W)idth and (H)eight in inches plt.subplots_adjust(left = 0, right = 1.0, top = 1.0, bottom = 0) im = plt.imshow(fea_img, vmin=0.0, vmax=1.0, cmap='jet', aspect='auto') # Show the image plt.savefig(save_path) plt.clf() def calc_mean_std(feat, eps=1e-5): """Calculate mean and std for adaptive_instance_normalization. Args: feat (Tensor): 4D tensor. eps (float): A small value added to the variance to avoid divide-by-zero. Default: 1e-5. """ size = feat.size() assert len(size) == 4, 'The input feature should be 4D tensor.' b, c = size[:2] feat_var = feat.view(b, c, -1).var(dim=2) + eps feat_std = feat_var.sqrt().view(b, c, 1, 1) feat_mean = feat.view(b, c, -1).mean(dim=2).view(b, c, 1, 1) return feat_mean, feat_std def adaptive_instance_normalization(content_feat, style_feat): """Adaptive instance normalization. Adjust the reference features to have the similar color and illuminations as those in the degradate features. Args: content_feat (Tensor): The reference feature. style_feat (Tensor): The degradate features. """ size = content_feat.size() style_mean, style_std = calc_mean_std(style_feat) content_mean, content_std = calc_mean_std(content_feat) normalized_feat = (content_feat - content_mean.expand(size)) / content_std.expand(size) return normalized_feat * style_std.expand(size) + style_mean.expand(size) 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(",")] #[250,] 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) def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__(self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0., v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1., conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0., ): super().__init__() assert parameterization in ["eps", "x0", "v"], 'currently only supporting "eps" and "x0" and "v"' self.parameterization = parameterization print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if monitor is not None: self.monitor = monitor if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet) self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) self.loss_type = loss_type self.learn_logvar = learn_logvar self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
if exists(given_betas):
1
2023-11-30 01:50:29+00:00
24k
Czm369/MixPL
mmdet/datasets/transforms/transforms.py
[ { "identifier": "TRANSFORMS", "path": "mmdet/registry.py", "snippet": "TRANSFORMS = Registry(\n 'transform',\n parent=MMENGINE_TRANSFORMS,\n locations=['mmdet.datasets.transforms'])" }, { "identifier": "autocast_box_type", "path": "mmdet/structures/bbox/box_type.py", "snippet": "def autocast_box_type(dst_box_type='hbox') -> Callable:\n \"\"\"A decorator which automatically casts results['gt_bboxes'] to the\n destination box type.\n\n It commenly used in mmdet.datasets.transforms to make the transforms up-\n compatible with the np.ndarray type of results['gt_bboxes'].\n\n The speed of processing of np.ndarray and BaseBoxes data are the same:\n\n - np.ndarray: 0.0509 img/s\n - BaseBoxes: 0.0551 img/s\n\n Args:\n dst_box_type (str): Destination box type.\n \"\"\"\n _, box_type_cls = get_box_type(dst_box_type)\n\n def decorator(func: Callable) -> Callable:\n\n def wrapper(self, results: dict, *args, **kwargs) -> dict:\n if ('gt_bboxes' not in results\n or isinstance(results['gt_bboxes'], BaseBoxes)):\n return func(self, results)\n elif isinstance(results['gt_bboxes'], np.ndarray):\n results['gt_bboxes'] = box_type_cls(\n results['gt_bboxes'], clone=False)\n if 'mix_results' in results:\n for res in results['mix_results']:\n if isinstance(res['gt_bboxes'], np.ndarray):\n res['gt_bboxes'] = box_type_cls(\n res['gt_bboxes'], clone=False)\n\n _results = func(self, results, *args, **kwargs)\n\n # In some cases, the function will process gt_bboxes in-place\n # Simultaneously convert inputting and outputting gt_bboxes\n # back to np.ndarray\n if isinstance(_results, dict) and 'gt_bboxes' in _results:\n if isinstance(_results['gt_bboxes'], BaseBoxes):\n _results['gt_bboxes'] = _results['gt_bboxes'].numpy()\n if isinstance(results['gt_bboxes'], BaseBoxes):\n results['gt_bboxes'] = results['gt_bboxes'].numpy()\n return _results\n else:\n raise TypeError(\n \"auto_box_type requires results['gt_bboxes'] to \"\n 'be BaseBoxes or np.ndarray, but got '\n f\"{type(results['gt_bboxes'])}\")\n\n return wrapper\n\n return decorator" }, { "identifier": "HorizontalBoxes", "path": "mmdet/structures/bbox/horizontal_boxes.py", "snippet": "class HorizontalBoxes(BaseBoxes):\n \"\"\"The horizontal box class used in MMDetection by default.\n\n The ``box_dim`` of ``HorizontalBoxes`` is 4, which means the length of\n the last dimension of the data should be 4. Two modes of box data are\n supported in ``HorizontalBoxes``:\n\n - 'xyxy': Each row of data indicates (x1, y1, x2, y2), which are the\n coordinates of the left-top and right-bottom points.\n - 'cxcywh': Each row of data indicates (x, y, w, h), where (x, y) are the\n coordinates of the box centers and (w, h) are the width and height.\n\n ``HorizontalBoxes`` only restores 'xyxy' mode of data. If the the data is\n in 'cxcywh' mode, users need to input ``in_mode='cxcywh'`` and The code\n will convert the 'cxcywh' data to 'xyxy' automatically.\n\n Args:\n data (Tensor or np.ndarray or Sequence): The box data with shape of\n (..., 4).\n dtype (torch.dtype, Optional): data type of boxes. Defaults to None.\n device (str or torch.device, Optional): device of boxes.\n Default to None.\n clone (bool): Whether clone ``boxes`` or not. Defaults to True.\n mode (str, Optional): the mode of boxes. If it is 'cxcywh', the\n `data` will be converted to 'xyxy' mode. Defaults to None.\n \"\"\"\n\n box_dim: int = 4\n\n def __init__(self,\n data: Union[Tensor, np.ndarray],\n dtype: torch.dtype = None,\n device: DeviceType = None,\n clone: bool = True,\n in_mode: Optional[str] = None) -> None:\n super().__init__(data=data, dtype=dtype, device=device, clone=clone)\n if isinstance(in_mode, str):\n if in_mode not in ('xyxy', 'cxcywh'):\n raise ValueError(f'Get invalid mode {in_mode}.')\n if in_mode == 'cxcywh':\n self.tensor = self.cxcywh_to_xyxy(self.tensor)\n\n @staticmethod\n def cxcywh_to_xyxy(boxes: Tensor) -> Tensor:\n \"\"\"Convert box coordinates from (cx, cy, w, h) to (x1, y1, x2, y2).\n\n Args:\n boxes (Tensor): cxcywh boxes tensor with shape of (..., 4).\n\n Returns:\n Tensor: xyxy boxes tensor with shape of (..., 4).\n \"\"\"\n ctr, wh = boxes.split((2, 2), dim=-1)\n return torch.cat([(ctr - wh / 2), (ctr + wh / 2)], dim=-1)\n\n @staticmethod\n def xyxy_to_cxcywh(boxes: Tensor) -> Tensor:\n \"\"\"Convert box coordinates from (x1, y1, x2, y2) to (cx, cy, w, h).\n\n Args:\n boxes (Tensor): xyxy boxes tensor with shape of (..., 4).\n\n Returns:\n Tensor: cxcywh boxes tensor with shape of (..., 4).\n \"\"\"\n xy1, xy2 = boxes.split((2, 2), dim=-1)\n return torch.cat([(xy2 + xy1) / 2, (xy2 - xy1)], dim=-1)\n\n @property\n def cxcywh(self) -> Tensor:\n \"\"\"Return a tensor representing the cxcywh boxes.\"\"\"\n return self.xyxy_to_cxcywh(self.tensor)\n\n @property\n def centers(self) -> Tensor:\n \"\"\"Return a tensor representing the centers of boxes.\"\"\"\n boxes = self.tensor\n return (boxes[..., :2] + boxes[..., 2:]) / 2\n\n @property\n def areas(self) -> Tensor:\n \"\"\"Return a tensor representing the areas of boxes.\"\"\"\n boxes = self.tensor\n return (boxes[..., 2] - boxes[..., 0]) * (\n boxes[..., 3] - boxes[..., 1])\n\n @property\n def widths(self) -> Tensor:\n \"\"\"Return a tensor representing the widths of boxes.\"\"\"\n boxes = self.tensor\n return boxes[..., 2] - boxes[..., 0]\n\n @property\n def heights(self) -> Tensor:\n \"\"\"Return a tensor representing the heights of boxes.\"\"\"\n boxes = self.tensor\n return boxes[..., 3] - boxes[..., 1]\n\n def flip_(self,\n img_shape: Tuple[int, int],\n direction: str = 'horizontal') -> None:\n \"\"\"Flip boxes horizontally or vertically in-place.\n\n Args:\n img_shape (Tuple[int, int]): A tuple of image height and width.\n direction (str): Flip direction, options are \"horizontal\",\n \"vertical\" and \"diagonal\". Defaults to \"horizontal\"\n \"\"\"\n assert direction in ['horizontal', 'vertical', 'diagonal']\n flipped = self.tensor\n boxes = flipped.clone()\n if direction == 'horizontal':\n flipped[..., 0] = img_shape[1] - boxes[..., 2]\n flipped[..., 2] = img_shape[1] - boxes[..., 0]\n elif direction == 'vertical':\n flipped[..., 1] = img_shape[0] - boxes[..., 3]\n flipped[..., 3] = img_shape[0] - boxes[..., 1]\n else:\n flipped[..., 0] = img_shape[1] - boxes[..., 2]\n flipped[..., 1] = img_shape[0] - boxes[..., 3]\n flipped[..., 2] = img_shape[1] - boxes[..., 0]\n flipped[..., 3] = img_shape[0] - boxes[..., 1]\n\n def translate_(self, distances: Tuple[float, float]) -> None:\n \"\"\"Translate boxes in-place.\n\n Args:\n distances (Tuple[float, float]): translate distances. The first\n is horizontal distance and the second is vertical distance.\n \"\"\"\n boxes = self.tensor\n assert len(distances) == 2\n self.tensor = boxes + boxes.new_tensor(distances).repeat(2)\n\n def clip_(self, img_shape: Tuple[int, int]) -> None:\n \"\"\"Clip boxes according to the image shape in-place.\n\n Args:\n img_shape (Tuple[int, int]): A tuple of image height and width.\n \"\"\"\n boxes = self.tensor\n boxes[..., 0::2] = boxes[..., 0::2].clamp(0, img_shape[1])\n boxes[..., 1::2] = boxes[..., 1::2].clamp(0, img_shape[0])\n\n def rotate_(self, center: Tuple[float, float], angle: float) -> None:\n \"\"\"Rotate all boxes in-place.\n\n Args:\n center (Tuple[float, float]): Rotation origin.\n angle (float): Rotation angle represented in degrees. Positive\n values mean clockwise rotation.\n \"\"\"\n boxes = self.tensor\n rotation_matrix = boxes.new_tensor(\n cv2.getRotationMatrix2D(center, -angle, 1))\n\n corners = self.hbox2corner(boxes)\n corners = torch.cat(\n [corners, corners.new_ones(*corners.shape[:-1], 1)], dim=-1)\n corners_T = torch.transpose(corners, -1, -2)\n corners_T = torch.matmul(rotation_matrix, corners_T)\n corners = torch.transpose(corners_T, -1, -2)\n self.tensor = self.corner2hbox(corners)\n\n def project_(self, homography_matrix: Union[Tensor, np.ndarray]) -> None:\n \"\"\"Geometric transformat boxes in-place.\n\n Args:\n homography_matrix (Tensor or np.ndarray]):\n Shape (3, 3) for geometric transformation.\n \"\"\"\n boxes = self.tensor\n if isinstance(homography_matrix, np.ndarray):\n homography_matrix = boxes.new_tensor(homography_matrix)\n corners = self.hbox2corner(boxes)\n corners = torch.cat(\n [corners, corners.new_ones(*corners.shape[:-1], 1)], dim=-1)\n corners_T = torch.transpose(corners, -1, -2)\n corners_T = torch.matmul(homography_matrix, corners_T)\n corners = torch.transpose(corners_T, -1, -2)\n # Convert to homogeneous coordinates by normalization\n corners = corners[..., :2] / corners[..., 2:3]\n self.tensor = self.corner2hbox(corners)\n\n @staticmethod\n def hbox2corner(boxes: Tensor) -> Tensor:\n \"\"\"Convert box coordinates from (x1, y1, x2, y2) to corners ((x1, y1),\n (x2, y1), (x1, y2), (x2, y2)).\n\n Args:\n boxes (Tensor): Horizontal box tensor with shape of (..., 4).\n\n Returns:\n Tensor: Corner tensor with shape of (..., 4, 2).\n \"\"\"\n x1, y1, x2, y2 = torch.split(boxes, 1, dim=-1)\n corners = torch.cat([x1, y1, x2, y1, x1, y2, x2, y2], dim=-1)\n return corners.reshape(*corners.shape[:-1], 4, 2)\n\n @staticmethod\n def corner2hbox(corners: Tensor) -> Tensor:\n \"\"\"Convert box coordinates from corners ((x1, y1), (x2, y1), (x1, y2),\n (x2, y2)) to (x1, y1, x2, y2).\n\n Args:\n corners (Tensor): Corner tensor with shape of (..., 4, 2).\n\n Returns:\n Tensor: Horizontal box tensor with shape of (..., 4).\n \"\"\"\n if corners.numel() == 0:\n return corners.new_zeros((0, 4))\n min_xy = corners.min(dim=-2)[0]\n max_xy = corners.max(dim=-2)[0]\n return torch.cat([min_xy, max_xy], dim=-1)\n\n def rescale_(self, scale_factor: Tuple[float, float]) -> None:\n \"\"\"Rescale boxes w.r.t. rescale_factor in-place.\n\n Note:\n Both ``rescale_`` and ``resize_`` will enlarge or shrink boxes\n w.r.t ``scale_facotr``. The difference is that ``resize_`` only\n changes the width and the height of boxes, but ``rescale_`` also\n rescales the box centers simultaneously.\n\n Args:\n scale_factor (Tuple[float, float]): factors for scaling boxes.\n The length should be 2.\n \"\"\"\n boxes = self.tensor\n assert len(scale_factor) == 2\n scale_factor = boxes.new_tensor(scale_factor).repeat(2)\n self.tensor = boxes * scale_factor\n\n def resize_(self, scale_factor: Tuple[float, float]) -> None:\n \"\"\"Resize the box width and height w.r.t scale_factor in-place.\n\n Note:\n Both ``rescale_`` and ``resize_`` will enlarge or shrink boxes\n w.r.t ``scale_facotr``. The difference is that ``resize_`` only\n changes the width and the height of boxes, but ``rescale_`` also\n rescales the box centers simultaneously.\n\n Args:\n scale_factor (Tuple[float, float]): factors for scaling box\n shapes. The length should be 2.\n \"\"\"\n boxes = self.tensor\n assert len(scale_factor) == 2\n ctrs = (boxes[..., 2:] + boxes[..., :2]) / 2\n wh = boxes[..., 2:] - boxes[..., :2]\n scale_factor = boxes.new_tensor(scale_factor)\n wh = wh * scale_factor\n xy1 = ctrs - 0.5 * wh\n xy2 = ctrs + 0.5 * wh\n self.tensor = torch.cat([xy1, xy2], dim=-1)\n\n def is_inside(self,\n img_shape: Tuple[int, int],\n all_inside: bool = False,\n allowed_border: int = 0) -> BoolTensor:\n \"\"\"Find boxes inside the image.\n\n Args:\n img_shape (Tuple[int, int]): A tuple of image height and width.\n all_inside (bool): Whether the boxes are all inside the image or\n part inside the image. Defaults to False.\n allowed_border (int): Boxes that extend beyond the image shape\n boundary by more than ``allowed_border`` are considered\n \"outside\" Defaults to 0.\n Returns:\n BoolTensor: A BoolTensor indicating whether the box is inside\n the image. Assuming the original boxes have shape (m, n, 4),\n the output has shape (m, n).\n \"\"\"\n img_h, img_w = img_shape\n boxes = self.tensor\n if all_inside:\n return (boxes[:, 0] >= -allowed_border) & \\\n (boxes[:, 1] >= -allowed_border) & \\\n (boxes[:, 2] < img_w + allowed_border) & \\\n (boxes[:, 3] < img_h + allowed_border)\n else:\n return (boxes[..., 0] < img_w + allowed_border) & \\\n (boxes[..., 1] < img_h + allowed_border) & \\\n (boxes[..., 2] > -allowed_border) & \\\n (boxes[..., 3] > -allowed_border)\n\n def find_inside_points(self,\n points: Tensor,\n is_aligned: bool = False) -> BoolTensor:\n \"\"\"Find inside box points. Boxes dimension must be 2.\n\n Args:\n points (Tensor): Points coordinates. Has shape of (m, 2).\n is_aligned (bool): Whether ``points`` has been aligned with boxes\n or not. If True, the length of boxes and ``points`` should be\n the same. Defaults to False.\n\n Returns:\n BoolTensor: A BoolTensor indicating whether a point is inside\n boxes. Assuming the boxes has shape of (n, 4), if ``is_aligned``\n is False. The index has shape of (m, n). If ``is_aligned`` is\n True, m should be equal to n and the index has shape of (m, ).\n \"\"\"\n boxes = self.tensor\n assert boxes.dim() == 2, 'boxes dimension must be 2.'\n\n if not is_aligned:\n boxes = boxes[None, :, :]\n points = points[:, None, :]\n else:\n assert boxes.size(0) == points.size(0)\n\n x_min, y_min, x_max, y_max = boxes.unbind(dim=-1)\n return (points[..., 0] >= x_min) & (points[..., 0] <= x_max) & \\\n (points[..., 1] >= y_min) & (points[..., 1] <= y_max)\n\n def create_masks(self, img_shape: Tuple[int, int]) -> BitmapMasks:\n \"\"\"\n Args:\n img_shape (Tuple[int, int]): A tuple of image height and width.\n\n Returns:\n :obj:`BitmapMasks`: Converted masks\n \"\"\"\n img_h, img_w = img_shape\n boxes = self.tensor\n\n xmin, ymin = boxes[:, 0:1], boxes[:, 1:2]\n xmax, ymax = boxes[:, 2:3], boxes[:, 3:4]\n gt_masks = np.zeros((len(boxes), img_h, img_w), dtype=np.uint8)\n for i in range(len(boxes)):\n gt_masks[i,\n int(ymin[i]):int(ymax[i]),\n int(xmin[i]):int(xmax[i])] = 1\n return BitmapMasks(gt_masks, img_h, img_w)\n\n @staticmethod\n def overlaps(boxes1: BaseBoxes,\n boxes2: BaseBoxes,\n mode: str = 'iou',\n is_aligned: bool = False,\n eps: float = 1e-6) -> Tensor:\n \"\"\"Calculate overlap between two set of boxes with their types\n converted to ``HorizontalBoxes``.\n\n Args:\n boxes1 (:obj:`BaseBoxes`): BaseBoxes with shape of (m, box_dim)\n or empty.\n boxes2 (:obj:`BaseBoxes`): BaseBoxes with shape of (n, box_dim)\n or empty.\n mode (str): \"iou\" (intersection over union), \"iof\" (intersection\n over foreground). Defaults to \"iou\".\n is_aligned (bool): If True, then m and n must be equal. Defaults\n to False.\n eps (float): A value added to the denominator for numerical\n stability. Defaults to 1e-6.\n\n Returns:\n Tensor: shape (m, n) if ``is_aligned`` is False else shape (m,)\n \"\"\"\n boxes1 = boxes1.convert_to('hbox')\n boxes2 = boxes2.convert_to('hbox')\n return bbox_overlaps(\n boxes1.tensor,\n boxes2.tensor,\n mode=mode,\n is_aligned=is_aligned,\n eps=eps)\n\n @staticmethod\n def from_instance_masks(masks: MaskType) -> 'HorizontalBoxes':\n \"\"\"Create horizontal boxes from instance masks.\n\n Args:\n masks (:obj:`BitmapMasks` or :obj:`PolygonMasks`): BitmapMasks or\n PolygonMasks instance with length of n.\n\n Returns:\n :obj:`HorizontalBoxes`: Converted boxes with shape of (n, 4).\n \"\"\"\n num_masks = len(masks)\n boxes = np.zeros((num_masks, 4), dtype=np.float32)\n if isinstance(masks, BitmapMasks):\n x_any = masks.masks.any(axis=1)\n y_any = masks.masks.any(axis=2)\n for idx in range(num_masks):\n x = np.where(x_any[idx, :])[0]\n y = np.where(y_any[idx, :])[0]\n if len(x) > 0 and len(y) > 0:\n # use +1 for x_max and y_max so that the right and bottom\n # boundary of instance masks are fully included by the box\n boxes[idx, :] = np.array(\n [x[0], y[0], x[-1] + 1, y[-1] + 1], dtype=np.float32)\n elif isinstance(masks, PolygonMasks):\n for idx, poly_per_obj in enumerate(masks.masks):\n # simply use a number that is big enough for comparison with\n # coordinates\n xy_min = np.array([masks.width * 2, masks.height * 2],\n dtype=np.float32)\n xy_max = np.zeros(2, dtype=np.float32)\n for p in poly_per_obj:\n xy = np.array(p).reshape(-1, 2).astype(np.float32)\n xy_min = np.minimum(xy_min, np.min(xy, axis=0))\n xy_max = np.maximum(xy_max, np.max(xy, axis=0))\n boxes[idx, :2] = xy_min\n boxes[idx, 2:] = xy_max\n else:\n raise TypeError(\n '`masks` must be `BitmapMasks` or `PolygonMasks`, '\n f'but got {type(masks)}.')\n return HorizontalBoxes(boxes)" }, { "identifier": "BitmapMasks", "path": "mmdet/structures/mask/structures.py", "snippet": "class BitmapMasks(BaseInstanceMasks):\n \"\"\"This class represents masks in the form of bitmaps.\n\n Args:\n masks (ndarray): ndarray of masks in shape (N, H, W), where N is\n the number of objects.\n height (int): height of masks\n width (int): width of masks\n\n Example:\n >>> from mmdet.data_elements.mask.structures import * # NOQA\n >>> num_masks, H, W = 3, 32, 32\n >>> rng = np.random.RandomState(0)\n >>> masks = (rng.rand(num_masks, H, W) > 0.1).astype(np.int64)\n >>> self = BitmapMasks(masks, height=H, width=W)\n\n >>> # demo crop_and_resize\n >>> num_boxes = 5\n >>> bboxes = np.array([[0, 0, 30, 10.0]] * num_boxes)\n >>> out_shape = (14, 14)\n >>> inds = torch.randint(0, len(self), size=(num_boxes,))\n >>> device = 'cpu'\n >>> interpolation = 'bilinear'\n >>> new = self.crop_and_resize(\n ... bboxes, out_shape, inds, device, interpolation)\n >>> assert len(new) == num_boxes\n >>> assert new.height, new.width == out_shape\n \"\"\"\n\n def __init__(self, masks, height, width):\n self.height = height\n self.width = width\n if len(masks) == 0:\n self.masks = np.empty((0, self.height, self.width), dtype=np.uint8)\n else:\n assert isinstance(masks, (list, np.ndarray))\n if isinstance(masks, list):\n assert isinstance(masks[0], np.ndarray)\n assert masks[0].ndim == 2 # (H, W)\n else:\n assert masks.ndim == 3 # (N, H, W)\n\n self.masks = np.stack(masks).reshape(-1, height, width)\n assert self.masks.shape[1] == self.height\n assert self.masks.shape[2] == self.width\n\n def __getitem__(self, index):\n \"\"\"Index the BitmapMask.\n\n Args:\n index (int | ndarray): Indices in the format of integer or ndarray.\n\n Returns:\n :obj:`BitmapMasks`: Indexed bitmap masks.\n \"\"\"\n masks = self.masks[index].reshape(-1, self.height, self.width)\n return BitmapMasks(masks, self.height, self.width)\n\n def __iter__(self):\n return iter(self.masks)\n\n def __repr__(self):\n s = self.__class__.__name__ + '('\n s += f'num_masks={len(self.masks)}, '\n s += f'height={self.height}, '\n s += f'width={self.width})'\n return s\n\n def __len__(self):\n \"\"\"Number of masks.\"\"\"\n return len(self.masks)\n\n def rescale(self, scale, interpolation='nearest'):\n \"\"\"See :func:`BaseInstanceMasks.rescale`.\"\"\"\n if len(self.masks) == 0:\n new_w, new_h = mmcv.rescale_size((self.width, self.height), scale)\n rescaled_masks = np.empty((0, new_h, new_w), dtype=np.uint8)\n else:\n rescaled_masks = np.stack([\n mmcv.imrescale(mask, scale, interpolation=interpolation)\n for mask in self.masks\n ])\n height, width = rescaled_masks.shape[1:]\n return BitmapMasks(rescaled_masks, height, width)\n\n def resize(self, out_shape, interpolation='nearest'):\n \"\"\"See :func:`BaseInstanceMasks.resize`.\"\"\"\n if len(self.masks) == 0:\n resized_masks = np.empty((0, *out_shape), dtype=np.uint8)\n else:\n resized_masks = np.stack([\n mmcv.imresize(\n mask, out_shape[::-1], interpolation=interpolation)\n for mask in self.masks\n ])\n return BitmapMasks(resized_masks, *out_shape)\n\n def flip(self, flip_direction='horizontal'):\n \"\"\"See :func:`BaseInstanceMasks.flip`.\"\"\"\n assert flip_direction in ('horizontal', 'vertical', 'diagonal')\n\n if len(self.masks) == 0:\n flipped_masks = self.masks\n else:\n flipped_masks = np.stack([\n mmcv.imflip(mask, direction=flip_direction)\n for mask in self.masks\n ])\n return BitmapMasks(flipped_masks, self.height, self.width)\n\n def pad(self, out_shape, pad_val=0):\n \"\"\"See :func:`BaseInstanceMasks.pad`.\"\"\"\n if len(self.masks) == 0:\n padded_masks = np.empty((0, *out_shape), dtype=np.uint8)\n else:\n padded_masks = np.stack([\n mmcv.impad(mask, shape=out_shape, pad_val=pad_val)\n for mask in self.masks\n ])\n return BitmapMasks(padded_masks, *out_shape)\n\n def crop(self, bbox):\n \"\"\"See :func:`BaseInstanceMasks.crop`.\"\"\"\n assert isinstance(bbox, np.ndarray)\n assert bbox.ndim == 1\n\n # clip the boundary\n bbox = bbox.copy()\n bbox[0::2] = np.clip(bbox[0::2], 0, self.width)\n bbox[1::2] = np.clip(bbox[1::2], 0, self.height)\n x1, y1, x2, y2 = bbox\n w = np.maximum(x2 - x1, 1)\n h = np.maximum(y2 - y1, 1)\n\n if len(self.masks) == 0:\n cropped_masks = np.empty((0, h, w), dtype=np.uint8)\n else:\n cropped_masks = self.masks[:, y1:y1 + h, x1:x1 + w]\n return BitmapMasks(cropped_masks, h, w)\n\n def crop_and_resize(self,\n bboxes,\n out_shape,\n inds,\n device='cpu',\n interpolation='bilinear',\n binarize=True):\n \"\"\"See :func:`BaseInstanceMasks.crop_and_resize`.\"\"\"\n if len(self.masks) == 0:\n empty_masks = np.empty((0, *out_shape), dtype=np.uint8)\n return BitmapMasks(empty_masks, *out_shape)\n\n # convert bboxes to tensor\n if isinstance(bboxes, np.ndarray):\n bboxes = torch.from_numpy(bboxes).to(device=device)\n if isinstance(inds, np.ndarray):\n inds = torch.from_numpy(inds).to(device=device)\n\n num_bbox = bboxes.shape[0]\n fake_inds = torch.arange(\n num_bbox, device=device).to(dtype=bboxes.dtype)[:, None]\n rois = torch.cat([fake_inds, bboxes], dim=1) # Nx5\n rois = rois.to(device=device)\n if num_bbox > 0:\n gt_masks_th = torch.from_numpy(self.masks).to(device).index_select(\n 0, inds).to(dtype=rois.dtype)\n targets = roi_align(gt_masks_th[:, None, :, :], rois, out_shape,\n 1.0, 0, 'avg', True).squeeze(1)\n if binarize:\n resized_masks = (targets >= 0.5).cpu().numpy()\n else:\n resized_masks = targets.cpu().numpy()\n else:\n resized_masks = []\n return BitmapMasks(resized_masks, *out_shape)\n\n def expand(self, expanded_h, expanded_w, top, left):\n \"\"\"See :func:`BaseInstanceMasks.expand`.\"\"\"\n if len(self.masks) == 0:\n expanded_mask = np.empty((0, expanded_h, expanded_w),\n dtype=np.uint8)\n else:\n expanded_mask = np.zeros((len(self), expanded_h, expanded_w),\n dtype=np.uint8)\n expanded_mask[:, top:top + self.height,\n left:left + self.width] = self.masks\n return BitmapMasks(expanded_mask, expanded_h, expanded_w)\n\n def translate(self,\n out_shape,\n offset,\n direction='horizontal',\n border_value=0,\n interpolation='bilinear'):\n \"\"\"Translate the BitmapMasks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n offset (int | float): The offset for translate.\n direction (str): The translate direction, either \"horizontal\"\n or \"vertical\".\n border_value (int | float): Border value. Default 0 for masks.\n interpolation (str): Same as :func:`mmcv.imtranslate`.\n\n Returns:\n BitmapMasks: Translated BitmapMasks.\n\n Example:\n >>> from mmdet.data_elements.mask.structures import BitmapMasks\n >>> self = BitmapMasks.random(dtype=np.uint8)\n >>> out_shape = (32, 32)\n >>> offset = 4\n >>> direction = 'horizontal'\n >>> border_value = 0\n >>> interpolation = 'bilinear'\n >>> # Note, There seem to be issues when:\n >>> # * the mask dtype is not supported by cv2.AffineWarp\n >>> new = self.translate(out_shape, offset, direction,\n >>> border_value, interpolation)\n >>> assert len(new) == len(self)\n >>> assert new.height, new.width == out_shape\n \"\"\"\n if len(self.masks) == 0:\n translated_masks = np.empty((0, *out_shape), dtype=np.uint8)\n else:\n masks = self.masks\n if masks.shape[-2:] != out_shape:\n empty_masks = np.zeros((masks.shape[0], *out_shape),\n dtype=masks.dtype)\n min_h = min(out_shape[0], masks.shape[1])\n min_w = min(out_shape[1], masks.shape[2])\n empty_masks[:, :min_h, :min_w] = masks[:, :min_h, :min_w]\n masks = empty_masks\n translated_masks = mmcv.imtranslate(\n masks.transpose((1, 2, 0)),\n offset,\n direction,\n border_value=border_value,\n interpolation=interpolation)\n if translated_masks.ndim == 2:\n translated_masks = translated_masks[:, :, None]\n translated_masks = translated_masks.transpose(\n (2, 0, 1)).astype(self.masks.dtype)\n return BitmapMasks(translated_masks, *out_shape)\n\n def shear(self,\n out_shape,\n magnitude,\n direction='horizontal',\n border_value=0,\n interpolation='bilinear'):\n \"\"\"Shear the BitmapMasks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n magnitude (int | float): The magnitude used for shear.\n direction (str): The shear direction, either \"horizontal\"\n or \"vertical\".\n border_value (int | tuple[int]): Value used in case of a\n constant border.\n interpolation (str): Same as in :func:`mmcv.imshear`.\n\n Returns:\n BitmapMasks: The sheared masks.\n \"\"\"\n if len(self.masks) == 0:\n sheared_masks = np.empty((0, *out_shape), dtype=np.uint8)\n else:\n sheared_masks = mmcv.imshear(\n self.masks.transpose((1, 2, 0)),\n magnitude,\n direction,\n border_value=border_value,\n interpolation=interpolation)\n if sheared_masks.ndim == 2:\n sheared_masks = sheared_masks[:, :, None]\n sheared_masks = sheared_masks.transpose(\n (2, 0, 1)).astype(self.masks.dtype)\n return BitmapMasks(sheared_masks, *out_shape)\n\n def rotate(self,\n out_shape,\n angle,\n center=None,\n scale=1.0,\n border_value=0,\n interpolation='bilinear'):\n \"\"\"Rotate the BitmapMasks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n angle (int | float): Rotation angle in degrees. Positive values\n mean counter-clockwise rotation.\n center (tuple[float], optional): Center point (w, h) of the\n rotation in source image. If not specified, the center of\n the image will be used.\n scale (int | float): Isotropic scale factor.\n border_value (int | float): Border value. Default 0 for masks.\n interpolation (str): Same as in :func:`mmcv.imrotate`.\n\n Returns:\n BitmapMasks: Rotated BitmapMasks.\n \"\"\"\n if len(self.masks) == 0:\n rotated_masks = np.empty((0, *out_shape), dtype=self.masks.dtype)\n else:\n rotated_masks = mmcv.imrotate(\n self.masks.transpose((1, 2, 0)),\n angle,\n center=center,\n scale=scale,\n border_value=border_value,\n interpolation=interpolation)\n if rotated_masks.ndim == 2:\n # case when only one mask, (h, w)\n rotated_masks = rotated_masks[:, :, None] # (h, w, 1)\n rotated_masks = rotated_masks.transpose(\n (2, 0, 1)).astype(self.masks.dtype)\n return BitmapMasks(rotated_masks, *out_shape)\n\n @property\n def areas(self):\n \"\"\"See :py:attr:`BaseInstanceMasks.areas`.\"\"\"\n return self.masks.sum((1, 2))\n\n def to_ndarray(self):\n \"\"\"See :func:`BaseInstanceMasks.to_ndarray`.\"\"\"\n return self.masks\n\n def to_tensor(self, dtype, device):\n \"\"\"See :func:`BaseInstanceMasks.to_tensor`.\"\"\"\n return torch.tensor(self.masks, dtype=dtype, device=device)\n\n @classmethod\n def random(cls,\n num_masks=3,\n height=32,\n width=32,\n dtype=np.uint8,\n rng=None):\n \"\"\"Generate random bitmap masks for demo / testing purposes.\n\n Example:\n >>> from mmdet.data_elements.mask.structures import BitmapMasks\n >>> self = BitmapMasks.random()\n >>> print('self = {}'.format(self))\n self = BitmapMasks(num_masks=3, height=32, width=32)\n \"\"\"\n from mmdet.utils.util_random import ensure_rng\n rng = ensure_rng(rng)\n masks = (rng.rand(num_masks, height, width) > 0.1).astype(dtype)\n self = cls(masks, height=height, width=width)\n return self\n\n @classmethod\n def cat(cls: Type[T], masks: Sequence[T]) -> T:\n \"\"\"Concatenate a sequence of masks into one single mask instance.\n\n Args:\n masks (Sequence[BitmapMasks]): A sequence of mask instances.\n\n Returns:\n BitmapMasks: Concatenated mask instance.\n \"\"\"\n assert isinstance(masks, Sequence)\n if len(masks) == 0:\n raise ValueError('masks should not be an empty list.')\n assert all(isinstance(m, cls) for m in masks)\n\n mask_array = np.concatenate([m.masks for m in masks], axis=0)\n return cls(mask_array, *mask_array.shape[1:])" }, { "identifier": "PolygonMasks", "path": "mmdet/structures/mask/structures.py", "snippet": "class PolygonMasks(BaseInstanceMasks):\n \"\"\"This class represents masks in the form of polygons.\n\n Polygons is a list of three levels. The first level of the list\n corresponds to objects, the second level to the polys that compose the\n object, the third level to the poly coordinates\n\n Args:\n masks (list[list[ndarray]]): The first level of the list\n corresponds to objects, the second level to the polys that\n compose the object, the third level to the poly coordinates\n height (int): height of masks\n width (int): width of masks\n\n Example:\n >>> from mmdet.data_elements.mask.structures import * # NOQA\n >>> masks = [\n >>> [ np.array([0, 0, 10, 0, 10, 10., 0, 10, 0, 0]) ]\n >>> ]\n >>> height, width = 16, 16\n >>> self = PolygonMasks(masks, height, width)\n\n >>> # demo translate\n >>> new = self.translate((16, 16), 4., direction='horizontal')\n >>> assert np.all(new.masks[0][0][1::2] == masks[0][0][1::2])\n >>> assert np.all(new.masks[0][0][0::2] == masks[0][0][0::2] + 4)\n\n >>> # demo crop_and_resize\n >>> num_boxes = 3\n >>> bboxes = np.array([[0, 0, 30, 10.0]] * num_boxes)\n >>> out_shape = (16, 16)\n >>> inds = torch.randint(0, len(self), size=(num_boxes,))\n >>> device = 'cpu'\n >>> interpolation = 'bilinear'\n >>> new = self.crop_and_resize(\n ... bboxes, out_shape, inds, device, interpolation)\n >>> assert len(new) == num_boxes\n >>> assert new.height, new.width == out_shape\n \"\"\"\n\n def __init__(self, masks, height, width):\n assert isinstance(masks, list)\n if len(masks) > 0:\n assert isinstance(masks[0], list)\n assert isinstance(masks[0][0], np.ndarray)\n\n self.height = height\n self.width = width\n self.masks = masks\n\n def __getitem__(self, index):\n \"\"\"Index the polygon masks.\n\n Args:\n index (ndarray | List): The indices.\n\n Returns:\n :obj:`PolygonMasks`: The indexed polygon masks.\n \"\"\"\n if isinstance(index, np.ndarray):\n if index.dtype == bool:\n index = np.where(index)[0].tolist()\n else:\n index = index.tolist()\n if isinstance(index, list):\n masks = [self.masks[i] for i in index]\n else:\n try:\n masks = self.masks[index]\n except Exception:\n raise ValueError(\n f'Unsupported input of type {type(index)} for indexing!')\n if len(masks) and isinstance(masks[0], np.ndarray):\n masks = [masks] # ensure a list of three levels\n return PolygonMasks(masks, self.height, self.width)\n\n def __iter__(self):\n return iter(self.masks)\n\n def __repr__(self):\n s = self.__class__.__name__ + '('\n s += f'num_masks={len(self.masks)}, '\n s += f'height={self.height}, '\n s += f'width={self.width})'\n return s\n\n def __len__(self):\n \"\"\"Number of masks.\"\"\"\n return len(self.masks)\n\n def rescale(self, scale, interpolation=None):\n \"\"\"see :func:`BaseInstanceMasks.rescale`\"\"\"\n new_w, new_h = mmcv.rescale_size((self.width, self.height), scale)\n if len(self.masks) == 0:\n rescaled_masks = PolygonMasks([], new_h, new_w)\n else:\n rescaled_masks = self.resize((new_h, new_w))\n return rescaled_masks\n\n def resize(self, out_shape, interpolation=None):\n \"\"\"see :func:`BaseInstanceMasks.resize`\"\"\"\n if len(self.masks) == 0:\n resized_masks = PolygonMasks([], *out_shape)\n else:\n h_scale = out_shape[0] / self.height\n w_scale = out_shape[1] / self.width\n resized_masks = []\n for poly_per_obj in self.masks:\n resized_poly = []\n for p in poly_per_obj:\n p = p.copy()\n p[0::2] = p[0::2] * w_scale\n p[1::2] = p[1::2] * h_scale\n resized_poly.append(p)\n resized_masks.append(resized_poly)\n resized_masks = PolygonMasks(resized_masks, *out_shape)\n return resized_masks\n\n def flip(self, flip_direction='horizontal'):\n \"\"\"see :func:`BaseInstanceMasks.flip`\"\"\"\n assert flip_direction in ('horizontal', 'vertical', 'diagonal')\n if len(self.masks) == 0:\n flipped_masks = PolygonMasks([], self.height, self.width)\n else:\n flipped_masks = []\n for poly_per_obj in self.masks:\n flipped_poly_per_obj = []\n for p in poly_per_obj:\n p = p.copy()\n if flip_direction == 'horizontal':\n p[0::2] = self.width - p[0::2]\n elif flip_direction == 'vertical':\n p[1::2] = self.height - p[1::2]\n else:\n p[0::2] = self.width - p[0::2]\n p[1::2] = self.height - p[1::2]\n flipped_poly_per_obj.append(p)\n flipped_masks.append(flipped_poly_per_obj)\n flipped_masks = PolygonMasks(flipped_masks, self.height,\n self.width)\n return flipped_masks\n\n def crop(self, bbox):\n \"\"\"see :func:`BaseInstanceMasks.crop`\"\"\"\n assert isinstance(bbox, np.ndarray)\n assert bbox.ndim == 1\n\n # clip the boundary\n bbox = bbox.copy()\n bbox[0::2] = np.clip(bbox[0::2], 0, self.width)\n bbox[1::2] = np.clip(bbox[1::2], 0, self.height)\n x1, y1, x2, y2 = bbox\n w = np.maximum(x2 - x1, 1)\n h = np.maximum(y2 - y1, 1)\n\n if len(self.masks) == 0:\n cropped_masks = PolygonMasks([], h, w)\n else:\n # reference: https://github.com/facebookresearch/fvcore/blob/main/fvcore/transforms/transform.py # noqa\n crop_box = geometry.box(x1, y1, x2, y2).buffer(0.0)\n cropped_masks = []\n # suppress shapely warnings util it incorporates GEOS>=3.11.2\n # reference: https://github.com/shapely/shapely/issues/1345\n initial_settings = np.seterr()\n np.seterr(invalid='ignore')\n for poly_per_obj in self.masks:\n cropped_poly_per_obj = []\n for p in poly_per_obj:\n p = p.copy()\n p = geometry.Polygon(p.reshape(-1, 2)).buffer(0.0)\n # polygon must be valid to perform intersection.\n if not p.is_valid:\n continue\n cropped = p.intersection(crop_box)\n if cropped.is_empty:\n continue\n if isinstance(cropped,\n geometry.collection.BaseMultipartGeometry):\n cropped = cropped.geoms\n else:\n cropped = [cropped]\n # one polygon may be cropped to multiple ones\n for poly in cropped:\n # ignore lines or points\n if not isinstance(\n poly, geometry.Polygon) or not poly.is_valid:\n continue\n coords = np.asarray(poly.exterior.coords)\n # remove an extra identical vertex at the end\n coords = coords[:-1]\n coords[:, 0] -= x1\n coords[:, 1] -= y1\n cropped_poly_per_obj.append(coords.reshape(-1))\n # a dummy polygon to avoid misalignment between masks and boxes\n if len(cropped_poly_per_obj) == 0:\n cropped_poly_per_obj = [np.array([0, 0, 0, 0, 0, 0])]\n cropped_masks.append(cropped_poly_per_obj)\n np.seterr(**initial_settings)\n cropped_masks = PolygonMasks(cropped_masks, h, w)\n return cropped_masks\n\n def pad(self, out_shape, pad_val=0):\n \"\"\"padding has no effect on polygons`\"\"\"\n return PolygonMasks(self.masks, *out_shape)\n\n def expand(self, *args, **kwargs):\n \"\"\"TODO: Add expand for polygon\"\"\"\n raise NotImplementedError\n\n def crop_and_resize(self,\n bboxes,\n out_shape,\n inds,\n device='cpu',\n interpolation='bilinear',\n binarize=True):\n \"\"\"see :func:`BaseInstanceMasks.crop_and_resize`\"\"\"\n out_h, out_w = out_shape\n if len(self.masks) == 0:\n return PolygonMasks([], out_h, out_w)\n\n if not binarize:\n raise ValueError('Polygons are always binary, '\n 'setting binarize=False is unsupported')\n\n resized_masks = []\n for i in range(len(bboxes)):\n mask = self.masks[inds[i]]\n bbox = bboxes[i, :]\n x1, y1, x2, y2 = bbox\n w = np.maximum(x2 - x1, 1)\n h = np.maximum(y2 - y1, 1)\n h_scale = out_h / max(h, 0.1) # avoid too large scale\n w_scale = out_w / max(w, 0.1)\n\n resized_mask = []\n for p in mask:\n p = p.copy()\n # crop\n # pycocotools will clip the boundary\n p[0::2] = p[0::2] - bbox[0]\n p[1::2] = p[1::2] - bbox[1]\n\n # resize\n p[0::2] = p[0::2] * w_scale\n p[1::2] = p[1::2] * h_scale\n resized_mask.append(p)\n resized_masks.append(resized_mask)\n return PolygonMasks(resized_masks, *out_shape)\n\n def translate(self,\n out_shape,\n offset,\n direction='horizontal',\n border_value=None,\n interpolation=None):\n \"\"\"Translate the PolygonMasks.\n\n Example:\n >>> self = PolygonMasks.random(dtype=np.int64)\n >>> out_shape = (self.height, self.width)\n >>> new = self.translate(out_shape, 4., direction='horizontal')\n >>> assert np.all(new.masks[0][0][1::2] == self.masks[0][0][1::2])\n >>> assert np.all(new.masks[0][0][0::2] == self.masks[0][0][0::2] + 4) # noqa: E501\n \"\"\"\n assert border_value is None or border_value == 0, \\\n 'Here border_value is not '\\\n f'used, and defaultly should be None or 0. got {border_value}.'\n if len(self.masks) == 0:\n translated_masks = PolygonMasks([], *out_shape)\n else:\n translated_masks = []\n for poly_per_obj in self.masks:\n translated_poly_per_obj = []\n for p in poly_per_obj:\n p = p.copy()\n if direction == 'horizontal':\n p[0::2] = np.clip(p[0::2] + offset, 0, out_shape[1])\n elif direction == 'vertical':\n p[1::2] = np.clip(p[1::2] + offset, 0, out_shape[0])\n translated_poly_per_obj.append(p)\n translated_masks.append(translated_poly_per_obj)\n translated_masks = PolygonMasks(translated_masks, *out_shape)\n return translated_masks\n\n def shear(self,\n out_shape,\n magnitude,\n direction='horizontal',\n border_value=0,\n interpolation='bilinear'):\n \"\"\"See :func:`BaseInstanceMasks.shear`.\"\"\"\n if len(self.masks) == 0:\n sheared_masks = PolygonMasks([], *out_shape)\n else:\n sheared_masks = []\n if direction == 'horizontal':\n shear_matrix = np.stack([[1, magnitude],\n [0, 1]]).astype(np.float32)\n elif direction == 'vertical':\n shear_matrix = np.stack([[1, 0], [magnitude,\n 1]]).astype(np.float32)\n for poly_per_obj in self.masks:\n sheared_poly = []\n for p in poly_per_obj:\n p = np.stack([p[0::2], p[1::2]], axis=0) # [2, n]\n new_coords = np.matmul(shear_matrix, p) # [2, n]\n new_coords[0, :] = np.clip(new_coords[0, :], 0,\n out_shape[1])\n new_coords[1, :] = np.clip(new_coords[1, :], 0,\n out_shape[0])\n sheared_poly.append(\n new_coords.transpose((1, 0)).reshape(-1))\n sheared_masks.append(sheared_poly)\n sheared_masks = PolygonMasks(sheared_masks, *out_shape)\n return sheared_masks\n\n def rotate(self,\n out_shape,\n angle,\n center=None,\n scale=1.0,\n border_value=0,\n interpolation='bilinear'):\n \"\"\"See :func:`BaseInstanceMasks.rotate`.\"\"\"\n if len(self.masks) == 0:\n rotated_masks = PolygonMasks([], *out_shape)\n else:\n rotated_masks = []\n rotate_matrix = cv2.getRotationMatrix2D(center, -angle, scale)\n for poly_per_obj in self.masks:\n rotated_poly = []\n for p in poly_per_obj:\n p = p.copy()\n coords = np.stack([p[0::2], p[1::2]], axis=1) # [n, 2]\n # pad 1 to convert from format [x, y] to homogeneous\n # coordinates format [x, y, 1]\n coords = np.concatenate(\n (coords, np.ones((coords.shape[0], 1), coords.dtype)),\n axis=1) # [n, 3]\n rotated_coords = np.matmul(\n rotate_matrix[None, :, :],\n coords[:, :, None])[..., 0] # [n, 2, 1] -> [n, 2]\n rotated_coords[:, 0] = np.clip(rotated_coords[:, 0], 0,\n out_shape[1])\n rotated_coords[:, 1] = np.clip(rotated_coords[:, 1], 0,\n out_shape[0])\n rotated_poly.append(rotated_coords.reshape(-1))\n rotated_masks.append(rotated_poly)\n rotated_masks = PolygonMasks(rotated_masks, *out_shape)\n return rotated_masks\n\n def to_bitmap(self):\n \"\"\"convert polygon masks to bitmap masks.\"\"\"\n bitmap_masks = self.to_ndarray()\n return BitmapMasks(bitmap_masks, self.height, self.width)\n\n @property\n def areas(self):\n \"\"\"Compute areas of masks.\n\n This func is modified from `detectron2\n <https://github.com/facebookresearch/detectron2/blob/ffff8acc35ea88ad1cb1806ab0f00b4c1c5dbfd9/detectron2/structures/masks.py#L387>`_.\n The function only works with Polygons using the shoelace formula.\n\n Return:\n ndarray: areas of each instance\n \"\"\" # noqa: W501\n area = []\n for polygons_per_obj in self.masks:\n area_per_obj = 0\n for p in polygons_per_obj:\n area_per_obj += self._polygon_area(p[0::2], p[1::2])\n area.append(area_per_obj)\n return np.asarray(area)\n\n def _polygon_area(self, x, y):\n \"\"\"Compute the area of a component of a polygon.\n\n Using the shoelace formula:\n https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates\n\n Args:\n x (ndarray): x coordinates of the component\n y (ndarray): y coordinates of the component\n\n Return:\n float: the are of the component\n \"\"\" # noqa: 501\n return 0.5 * np.abs(\n np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))\n\n def to_ndarray(self):\n \"\"\"Convert masks to the format of ndarray.\"\"\"\n if len(self.masks) == 0:\n return np.empty((0, self.height, self.width), dtype=np.uint8)\n bitmap_masks = []\n for poly_per_obj in self.masks:\n bitmap_masks.append(\n polygon_to_bitmap(poly_per_obj, self.height, self.width))\n return np.stack(bitmap_masks)\n\n def to_tensor(self, dtype, device):\n \"\"\"See :func:`BaseInstanceMasks.to_tensor`.\"\"\"\n if len(self.masks) == 0:\n return torch.empty((0, self.height, self.width),\n dtype=dtype,\n device=device)\n ndarray_masks = self.to_ndarray()\n return torch.tensor(ndarray_masks, dtype=dtype, device=device)\n\n @classmethod\n def random(cls,\n num_masks=3,\n height=32,\n width=32,\n n_verts=5,\n dtype=np.float32,\n rng=None):\n \"\"\"Generate random polygon masks for demo / testing purposes.\n\n Adapted from [1]_\n\n References:\n .. [1] https://gitlab.kitware.com/computer-vision/kwimage/-/blob/928cae35ca8/kwimage/structs/polygon.py#L379 # noqa: E501\n\n Example:\n >>> from mmdet.data_elements.mask.structures import PolygonMasks\n >>> self = PolygonMasks.random()\n >>> print('self = {}'.format(self))\n \"\"\"\n from mmdet.utils.util_random import ensure_rng\n rng = ensure_rng(rng)\n\n def _gen_polygon(n, irregularity, spikeyness):\n \"\"\"Creates the polygon by sampling points on a circle around the\n centre. Random noise is added by varying the angular spacing\n between sequential points, and by varying the radial distance of\n each point from the centre.\n\n Based on original code by Mike Ounsworth\n\n Args:\n n (int): number of vertices\n irregularity (float): [0,1] indicating how much variance there\n is in the angular spacing of vertices. [0,1] will map to\n [0, 2pi/numberOfVerts]\n spikeyness (float): [0,1] indicating how much variance there is\n in each vertex from the circle of radius aveRadius. [0,1]\n will map to [0, aveRadius]\n\n Returns:\n a list of vertices, in CCW order.\n \"\"\"\n from scipy.stats import truncnorm\n\n # Generate around the unit circle\n cx, cy = (0.0, 0.0)\n radius = 1\n\n tau = np.pi * 2\n\n irregularity = np.clip(irregularity, 0, 1) * 2 * np.pi / n\n spikeyness = np.clip(spikeyness, 1e-9, 1)\n\n # generate n angle steps\n lower = (tau / n) - irregularity\n upper = (tau / n) + irregularity\n angle_steps = rng.uniform(lower, upper, n)\n\n # normalize the steps so that point 0 and point n+1 are the same\n k = angle_steps.sum() / (2 * np.pi)\n angles = (angle_steps / k).cumsum() + rng.uniform(0, tau)\n\n # Convert high and low values to be wrt the standard normal range\n # https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.truncnorm.html\n low = 0\n high = 2 * radius\n mean = radius\n std = spikeyness\n a = (low - mean) / std\n b = (high - mean) / std\n tnorm = truncnorm(a=a, b=b, loc=mean, scale=std)\n\n # now generate the points\n radii = tnorm.rvs(n, random_state=rng)\n x_pts = cx + radii * np.cos(angles)\n y_pts = cy + radii * np.sin(angles)\n\n points = np.hstack([x_pts[:, None], y_pts[:, None]])\n\n # Scale to 0-1 space\n points = points - points.min(axis=0)\n points = points / points.max(axis=0)\n\n # Randomly place within 0-1 space\n points = points * (rng.rand() * .8 + .2)\n min_pt = points.min(axis=0)\n max_pt = points.max(axis=0)\n\n high = (1 - max_pt)\n low = (0 - min_pt)\n offset = (rng.rand(2) * (high - low)) + low\n points = points + offset\n return points\n\n def _order_vertices(verts):\n \"\"\"\n References:\n https://stackoverflow.com/questions/1709283/how-can-i-sort-a-coordinate-list-for-a-rectangle-counterclockwise\n \"\"\"\n mlat = verts.T[0].sum() / len(verts)\n mlng = verts.T[1].sum() / len(verts)\n\n tau = np.pi * 2\n angle = (np.arctan2(mlat - verts.T[0], verts.T[1] - mlng) +\n tau) % tau\n sortx = angle.argsort()\n verts = verts.take(sortx, axis=0)\n return verts\n\n # Generate a random exterior for each requested mask\n masks = []\n for _ in range(num_masks):\n exterior = _order_vertices(_gen_polygon(n_verts, 0.9, 0.9))\n exterior = (exterior * [(width, height)]).astype(dtype)\n masks.append([exterior.ravel()])\n\n self = cls(masks, height, width)\n return self\n\n @classmethod\n def cat(cls: Type[T], masks: Sequence[T]) -> T:\n \"\"\"Concatenate a sequence of masks into one single mask instance.\n\n Args:\n masks (Sequence[PolygonMasks]): A sequence of mask instances.\n\n Returns:\n PolygonMasks: Concatenated mask instance.\n \"\"\"\n assert isinstance(masks, Sequence)\n if len(masks) == 0:\n raise ValueError('masks should not be an empty list.')\n assert all(isinstance(m, cls) for m in masks)\n\n mask_list = list(itertools.chain(*[m.masks for m in masks]))\n return cls(mask_list, masks[0].height, masks[0].width)" }, { "identifier": "log_img_scale", "path": "mmdet/utils/logger.py", "snippet": "def log_img_scale(img_scale, shape_order='hw', skip_square=False):\n \"\"\"Log image size.\n\n Args:\n img_scale (tuple): Image size to be logged.\n shape_order (str, optional): The order of image shape.\n 'hw' for (height, width) and 'wh' for (width, height).\n Defaults to 'hw'.\n skip_square (bool, optional): Whether to skip logging for square\n img_scale. Defaults to False.\n\n Returns:\n bool: Whether to have done logging.\n \"\"\"\n if shape_order == 'hw':\n height, width = img_scale\n elif shape_order == 'wh':\n width, height = img_scale\n else:\n raise ValueError(f'Invalid shape_order {shape_order}.')\n\n if skip_square and (height == width):\n return False\n\n caller = get_caller_name()\n print_log(\n f'image shape: height={height}, width={width} in {caller}',\n logger='current')\n\n return True" } ]
import copy import inspect import math import warnings import cv2 import mmcv import numpy as np import albumentations from typing import List, Optional, Sequence, Tuple, Union from mmcv.image import imresize from mmcv.image.geometric import _scale_size from mmcv.transforms import BaseTransform from mmcv.transforms import Pad as MMCV_Pad from mmcv.transforms import RandomFlip as MMCV_RandomFlip from mmcv.transforms import Resize as MMCV_Resize from mmcv.transforms.utils import avoid_cache_randomness, cache_randomness from mmengine.dataset import BaseDataset from mmengine.utils import is_str from numpy import random from mmdet.registry import TRANSFORMS from mmdet.structures.bbox import HorizontalBoxes, autocast_box_type from mmdet.structures.mask import BitmapMasks, PolygonMasks from mmdet.utils import log_img_scale from imagecorruptions import corrupt from albumentations import Compose
15,904
# Copyright (c) OpenMMLab. All rights reserved. try: except ImportError: corrupt = None try: except ImportError: albumentations = None Compose = None Number = Union[int, float] def _fixed_scale_size( size: Tuple[int, int], scale: Union[float, int, tuple], ) -> Tuple[int, int]: """Rescale a size by a ratio. Args: size (tuple[int]): (w, h). scale (float | tuple(float)): Scaling factor. Returns: tuple[int]: scaled size. """ if isinstance(scale, (float, int)): scale = (scale, scale) w, h = size # don't need o.5 offset return int(w * float(scale[0])), int(h * float(scale[1])) def rescale_size(old_size: tuple, scale: Union[float, int, tuple], return_scale: bool = False) -> tuple: """Calculate the new size to be rescaled to. Args: old_size (tuple[int]): The old size (w, h) of image. scale (float | tuple[int]): The scaling factor or maximum size. If it is a float number, then the image will be rescaled by this factor, else if it is a tuple of 2 integers, then the image will be rescaled as large as possible within the scale. return_scale (bool): Whether to return the scaling factor besides the rescaled image size. Returns: tuple[int]: The new rescaled image size. """ w, h = old_size if isinstance(scale, (float, int)): if scale <= 0: raise ValueError(f'Invalid scale {scale}, must be positive.') scale_factor = scale elif isinstance(scale, tuple): max_long_edge = max(scale) max_short_edge = min(scale) scale_factor = min(max_long_edge / max(h, w), max_short_edge / min(h, w)) else: raise TypeError( f'Scale must be a number or tuple of int, but got {type(scale)}') # only change this new_size = _fixed_scale_size((w, h), scale_factor) if return_scale: return new_size, scale_factor else: return new_size def imrescale( img: np.ndarray, scale: Union[float, Tuple[int, int]], return_scale: bool = False, interpolation: str = 'bilinear', backend: Optional[str] = None ) -> Union[np.ndarray, Tuple[np.ndarray, float]]: """Resize image while keeping the aspect ratio. Args: img (ndarray): The input image. scale (float | tuple[int]): The scaling factor or maximum size. If it is a float number, then the image will be rescaled by this factor, else if it is a tuple of 2 integers, then the image will be rescaled as large as possible within the scale. return_scale (bool): Whether to return the scaling factor besides the rescaled image. interpolation (str): Same as :func:`resize`. backend (str | None): Same as :func:`resize`. Returns: ndarray: The rescaled image. """ h, w = img.shape[:2] new_size, scale_factor = rescale_size((w, h), scale, return_scale=True) rescaled_img = imresize( img, new_size, interpolation=interpolation, backend=backend) if return_scale: return rescaled_img, scale_factor else: return rescaled_img
# Copyright (c) OpenMMLab. All rights reserved. try: except ImportError: corrupt = None try: except ImportError: albumentations = None Compose = None Number = Union[int, float] def _fixed_scale_size( size: Tuple[int, int], scale: Union[float, int, tuple], ) -> Tuple[int, int]: """Rescale a size by a ratio. Args: size (tuple[int]): (w, h). scale (float | tuple(float)): Scaling factor. Returns: tuple[int]: scaled size. """ if isinstance(scale, (float, int)): scale = (scale, scale) w, h = size # don't need o.5 offset return int(w * float(scale[0])), int(h * float(scale[1])) def rescale_size(old_size: tuple, scale: Union[float, int, tuple], return_scale: bool = False) -> tuple: """Calculate the new size to be rescaled to. Args: old_size (tuple[int]): The old size (w, h) of image. scale (float | tuple[int]): The scaling factor or maximum size. If it is a float number, then the image will be rescaled by this factor, else if it is a tuple of 2 integers, then the image will be rescaled as large as possible within the scale. return_scale (bool): Whether to return the scaling factor besides the rescaled image size. Returns: tuple[int]: The new rescaled image size. """ w, h = old_size if isinstance(scale, (float, int)): if scale <= 0: raise ValueError(f'Invalid scale {scale}, must be positive.') scale_factor = scale elif isinstance(scale, tuple): max_long_edge = max(scale) max_short_edge = min(scale) scale_factor = min(max_long_edge / max(h, w), max_short_edge / min(h, w)) else: raise TypeError( f'Scale must be a number or tuple of int, but got {type(scale)}') # only change this new_size = _fixed_scale_size((w, h), scale_factor) if return_scale: return new_size, scale_factor else: return new_size def imrescale( img: np.ndarray, scale: Union[float, Tuple[int, int]], return_scale: bool = False, interpolation: str = 'bilinear', backend: Optional[str] = None ) -> Union[np.ndarray, Tuple[np.ndarray, float]]: """Resize image while keeping the aspect ratio. Args: img (ndarray): The input image. scale (float | tuple[int]): The scaling factor or maximum size. If it is a float number, then the image will be rescaled by this factor, else if it is a tuple of 2 integers, then the image will be rescaled as large as possible within the scale. return_scale (bool): Whether to return the scaling factor besides the rescaled image. interpolation (str): Same as :func:`resize`. backend (str | None): Same as :func:`resize`. Returns: ndarray: The rescaled image. """ h, w = img.shape[:2] new_size, scale_factor = rescale_size((w, h), scale, return_scale=True) rescaled_img = imresize( img, new_size, interpolation=interpolation, backend=backend) if return_scale: return rescaled_img, scale_factor else: return rescaled_img
@TRANSFORMS.register_module()
0
2023-11-30 08:58:00+00:00
24k
SEU-ProactiveSecurity-Group/MalPurifier
core/defense/amd_dla.py
[ { "identifier": "Max", "path": "core/attack/max.py", "snippet": "class Max(BaseAttack):\n \"\"\"\n Max攻击:迭代地从多个攻击方法中选择结果。\n\n 参数\n --------\n @param attack_list: List, 已实例化的攻击对象的列表。\n @param varepsilon: Float, 用于判断收敛性的标量。\n \"\"\"\n\n def __init__(self, attack_list, varepsilon=1e-20,\n is_attacker=True, oblivion=False, kappa=1., manipulation_x=None, omega=None, device=None):\n \"\"\"\n 构造函数\n\n 参数:\n - attack_list: 已实例化的攻击对象的列表,至少应该有一个攻击方法。\n - varepsilon: 用于判断收敛性的标量,默认值为1e-20。\n - is_attacker: Bool, 表示是否为攻击者,默认为True。\n - oblivion: Bool, 一个布尔标志(其功能在这里并未详细说明),默认为False。\n - kappa: Float, 一个浮点数参数,默认为1。\n - manipulation_x: 可能与数据的处理或操纵有关,具体用途未详细说明。\n - omega: 参数omega的具体用途未详细说明。\n - device: 设备,例如'cuda'或'cpu',用于执行计算。\n\n 注意:\n - 在初始化过程中,会首先检查`attack_list`是否包含至少一个攻击对象。\n \"\"\"\n super(Max, self).__init__(is_attacker, oblivion, kappa, manipulation_x, omega, device) # 调用父类的构造函数\n assert len(attack_list) > 0, '至少需要一个攻击方法。' # 确保提供了至少一个攻击对象\n self.attack_list = attack_list # 设置攻击列表\n self.varepsilon = varepsilon # 设置varepsilon值\n self.device = device # 设置计算设备\n\n def perturb(self, model, x, label=None, steps_max=5, min_lambda_=1e-5, max_lambda_=1e5, verbose=False):\n \"\"\"\n 扰动节点特征\n\n 参数\n -----------\n @param model: 受害者模型。\n @param x: torch.FloatTensor, 形状为[batch_size, vocab_dim]的特征向量。\n @param label: torch.LongTensor, 真实标签。\n @param steps_max: Integer, 最大的迭代次数。\n @param min_lambda_: float, 平衡对手检测器的重要性(如果存在)。\n @param max_lambda_: float, 同上。\n @param verbose: Boolean, 是否打印详细日志。\n\n 返回值\n --------\n adv_x: 扰动后的数据。\n \"\"\"\n\n # 判断输入数据是否有效\n if x is None or x.shape[0] <= 0:\n return []\n\n # 将模型设为评估模式,主要是为了禁用一些在训练模式下的特殊层,比如Dropout\n model.eval()\n\n # 获取输入数据x在当前模型下的损失和完成状态\n with torch.no_grad():\n loss, done = self.get_scores(model, x, label)\n\n # 存储当前的损失为前一次的损失\n pre_loss = loss\n\n # 获取输入数据的数量以及其他的维度信息\n n, red_n = x.size()[0], x.size()[1:]\n red_ind = list(range(2, len(x.size()) + 1))\n\n # 初始化攻击样本为输入数据的拷贝\n adv_x = x.detach().clone()\n\n # 初始化停止标志,用于表示哪些样本已经完成了攻击\n stop_flag = torch.zeros(n, dtype=torch.bool, device=self.device)\n\n # 开始主循环,进行多次迭代以改进攻击效果\n for t in range(steps_max):\n # 计算还未完成攻击的样本数量\n num_sample_red = n - torch.sum(stop_flag)\n \n # 如果所有样本都已完成攻击,结束循环\n if num_sample_red <= 0:\n break\n\n # 获取那些还未完成攻击的样本的真实标签\n red_label = label[~stop_flag]\n pertbx = []\n\n # 对于攻击方法列表中的每种攻击方法,尝试对数据进行扰动\n for attack in self.attack_list:\n # 确保每种攻击方法都实现了perturb方法\n assert 'perturb' in type(attack).__dict__.keys()\n\n # 对于某些特定的攻击方法,在第二次及以后的迭代中取消随机化\n if t > 0 and 'use_random' in attack.__dict__.keys():\n attack.use_random = False\n\n # 对于名为\"Orthogonal\"的攻击方法,进行特殊处理\n if 'Orthogonal' in type(attack).__name__:\n pertbx.append(attack.perturb(model=model, x=adv_x[~stop_flag], label=red_label))\n else:\n pertbx.append(attack.perturb(model=model, x=adv_x[~stop_flag], label=red_label,\n min_lambda_=1e-5,\n max_lambda_=1e5,\n ))\n # 将所有攻击方法产生的扰动数据合并\n pertbx = torch.vstack(pertbx)\n\n\n # 不需要计算梯度,提高计算效率\n with torch.no_grad():\n # 将真实标签复制若干次以匹配所有的攻击列表\n red_label_ext = torch.cat([red_label] * len(self.attack_list))\n \n # 获取每种攻击方法产生的损失值和成功状态\n loss, done = self.get_scores(model, pertbx, red_label_ext)\n \n # 调整损失和成功状态的形状以方便后续计算\n loss = loss.reshape(len(self.attack_list), num_sample_red).permute(1, 0)\n done = done.reshape(len(self.attack_list), num_sample_red).permute(1, 0)\n \n # 判断哪些样本至少有一种攻击方法成功\n success_flag = torch.any(done, dim=-1)\n \n # 对于没有成功的样本,将其标记为1以进行后续处理\n done[~torch.any(done, dim=-1)] = 1\n \n # 调整损失值,对于成功的攻击方法,损失值保持不变;对于失败的,损失值变为最小值\n loss = (loss * done.to(torch.float)) + torch.min(loss) * (~done).to(torch.float)\n \n # 调整扰动数据的形状以方便后续计算\n pertbx = pertbx.reshape(len(self.attack_list), num_sample_red, *red_n).permute([1, 0, *red_ind])\n \n # 选择造成最大损失的扰动数据\n _, indices = loss.max(dim=-1)\n adv_x[~stop_flag] = pertbx[torch.arange(num_sample_red), indices]\n \n # 获取选中的扰动数据的损失值\n a_loss = loss[torch.arange(num_sample_red), indices]\n \n # 复制当前的停止标志\n pre_stop_flag = stop_flag.clone()\n \n # 更新停止标志,如果损失值变化很小或者某种攻击方法成功,则停止迭代\n stop_flag[~stop_flag] = (torch.abs(pre_loss[~stop_flag] - a_loss) < self.varepsilon) | success_flag\n \n # 更新前一个损失值\n pre_loss[~pre_stop_flag] = a_loss\n\n # 如果需要打印日志\n if verbose:\n # 评估最终的扰动数据的成功状态\n with torch.no_grad():\n _, done = self.get_scores(model, adv_x, label)\n # 打印攻击成功率\n logger.info(f\"max: attack effectiveness {done.sum().item() / x.size()[0] * 100}%.\")\n\n # 返回最终的扰动数据\n return adv_x\n\n\n def perturb_dae(self, predict_model, purifier, x, label=None, steps_max=5, min_lambda_=1e-5, max_lambda_=1e5, verbose=False, oblivion=False):\n \"\"\"\n 扰动节点特征\n\n 参数\n -----------\n @param model: 受害者模型。\n @param x: torch.FloatTensor, 形状为[batch_size, vocab_dim]的特征向量。\n @param label: torch.LongTensor, 真实标签。\n @param steps_max: Integer, 最大的迭代次数。\n @param min_lambda_: float, 平衡对手检测器的重要性(如果存在)。\n @param max_lambda_: float, 同上。\n @param verbose: Boolean, 是否打印详细日志。\n\n 返回值\n --------\n adv_x: 扰动后的数据。\n \"\"\"\n\n # 判断输入数据是否有效\n if x is None or x.shape[0] <= 0:\n return []\n\n # 将模型设为评估模式,主要是为了禁用一些在训练模式下的特殊层,比如Dropout\n predict_model.eval()\n purifier.eval()\n\n # 获取输入数据x在当前模型下的损失和完成状态\n with torch.no_grad():\n if not oblivion:\n purified_x = purifier(x.detach().clone().float()).to(torch.double)\n else:\n purified_x = x.detach().clone()\n loss, done = self.get_scores(predict_model, purified_x, label)\n\n # 存储当前的损失为前一次的损失\n pre_loss = loss\n\n # 获取输入数据的数量以及其他的维度信息\n n, red_n = x.size()[0], x.size()[1:]\n red_ind = list(range(2, len(x.size()) + 1))\n\n # 初始化攻击样本为输入数据的拷贝\n adv_x = x.detach().clone()\n\n # 初始化停止标志,用于表示哪些样本已经完成了攻击\n stop_flag = torch.zeros(n, dtype=torch.bool, device=self.device)\n\n # 开始主循环,进行多次迭代以改进攻击效果\n for t in range(steps_max):\n # 计算还未完成攻击的样本数量\n num_sample_red = n - torch.sum(stop_flag)\n \n # 如果所有样本都已完成攻击,结束循环\n if num_sample_red <= 0:\n break\n\n # 获取那些还未完成攻击的样本的真实标签\n red_label = label[~stop_flag]\n pertbx = []\n\n # 对于攻击方法列表中的每种攻击方法,尝试对数据进行扰动\n for attack in self.attack_list:\n # 确保每种攻击方法都实现了perturb方法\n assert 'perturb' in type(attack).__dict__.keys()\n\n # 对于某些特定的攻击方法,在第二次及以后的迭代中取消随机化\n if t > 0 and 'use_random' in attack.__dict__.keys():\n attack.use_random = False\n\n # 对于名为\"Orthogonal\"的攻击方法,进行特殊处理\n if 'Orthogonal' in type(attack).__name__:\n pertbx.append(attack.perturb_dae(predict_model=predict_model, purifier=purifier, x=adv_x[~stop_flag], label=red_label, oblivion=oblivion))\n else:\n pertbx.append(attack.perturb_dae(model=predict_model, purifier=purifier, x=adv_x[~stop_flag], label=red_label,\n min_lambda_=1e-5,\n max_lambda_=1e5,\n oblivion=oblivion\n ))\n\n # 将所有攻击方法产生的扰动数据合并\n pertbx = torch.vstack(pertbx)\n\n\n # 不需要计算梯度,提高计算效率\n with torch.no_grad():\n # 将真实标签复制若干次以匹配所有的攻击列表\n red_label_ext = torch.cat([red_label] * len(self.attack_list))\n \n # 获取每种攻击方法产生的损失值和成功状态\n if not oblivion:\n purified_pertbx = purifier(pertbx.detach().clone().float()).to(torch.double)\n else:\n purified_pertbx = pertbx.detach().clone()\n\n loss, done = self.get_scores(predict_model, purified_pertbx, red_label_ext)\n \n # 调整损失和成功状态的形状以方便后续计算\n loss = loss.reshape(len(self.attack_list), num_sample_red).permute(1, 0)\n done = done.reshape(len(self.attack_list), num_sample_red).permute(1, 0)\n \n # 判断哪些样本至少有一种攻击方法成功\n success_flag = torch.any(done, dim=-1)\n \n # 对于没有成功的样本,将其标记为1以进行后续处理\n done[~torch.any(done, dim=-1)] = 1\n \n # 调整损失值,对于成功的攻击方法,损失值保持不变;对于失败的,损失值变为最小值\n loss = (loss * done.to(torch.float)) + torch.min(loss) * (~done).to(torch.float)\n \n # 调整扰动数据的形状以方便后续计算\n pertbx = pertbx.reshape(len(self.attack_list), num_sample_red, *red_n).permute([1, 0, *red_ind])\n \n # 选择造成最大损失的扰动数据\n _, indices = loss.max(dim=-1)\n adv_x[~stop_flag] = pertbx[torch.arange(num_sample_red), indices]\n \n # 获取选中的扰动数据的损失值\n a_loss = loss[torch.arange(num_sample_red), indices]\n \n # 复制当前的停止标志\n pre_stop_flag = stop_flag.clone()\n \n # 更新停止标志,如果损失值变化很小或者某种攻击方法成功,则停止迭代\n stop_flag[~stop_flag] = (torch.abs(pre_loss[~stop_flag] - a_loss) < self.varepsilon) | success_flag\n \n # 更新前一个损失值\n pre_loss[~pre_stop_flag] = a_loss\n\n # 如果需要打印日志\n if verbose:\n # 评估最终的扰动数据的成功状态\n with torch.no_grad():\n purified_adv_x = purifier(adv_x.detach().clone().float()).to(torch.double)\n _, done = self.get_scores(predict_model, purified_adv_x, label)\n # 打印攻击成功率\n logger.info(f\"max: attack effectiveness {done.sum().item() / x.size()[0] * 100}%.\")\n\n # 返回最终的扰动数据\n return adv_x\n\n\n # 这个get_scores函数的主要目的是计算扰动数据在给定模型上的损失值,并判断模型对这些扰动数据的预测是否成功完成。\n # 对于具有检测器功能的模型,还会考虑模型的额外输出来决定预测的完成状态。\n def get_scores(self, model, pertb_x, label):\n \"\"\"\n 获取扰动数据在模型上的损失值和预测标签的完成状态。\n\n 参数:\n @param model: 模型对象,即受攻击的目标模型。\n @param pertb_x: torch.Tensor,扰动后的数据。\n @param label: torch.Tensor,扰动数据的真实标签。\n\n 返回:\n - loss_no_reduction: 每个样本的损失值(无降维处理)。\n - done: Boolean Tensor,表示模型对每个样本的预测是否成功完成。\n \"\"\"\n # 判断模型是否具有检测器功能,如果有,则获取模型的两个输出:logits_f 和 prob_g。\n if hasattr(model, 'is_detector_enabled'):\n logits_f, prob_g = model.forward(pertb_x)\n else:\n # 如果模型没有检测器功能,只获取一个输出logits_f。\n logits_f = model.forward(pertb_x)\n\n # 使用交叉熵计算每个样本的损失值\n ce = F.cross_entropy(logits_f, label, reduction='none')\n\n # 获取模型的预测标签\n y_pred = logits_f.argmax(1)\n\n # 如果模型具有检测器功能且不处于\"oblivion\"模式,则进行特殊处理。\n # 使用模型的输出prob_g来判断是否成功完成了预测。\n if hasattr(model, 'is_detector_enabled') and (not self.oblivion):\n tau = model.get_tau_sample_wise(y_pred)\n loss_no_reduction = -prob_g\n done = (y_pred != label) & (prob_g <= tau)\n else:\n # 如果模型没有检测器功能或处于\"oblivion\"模式,则使用交叉熵损失来判断是否成功完成了预测。\n loss_no_reduction = ce\n done = y_pred != label\n\n return loss_no_reduction, done" }, { "identifier": "StepwiseMax", "path": "core/attack/stepwise_max.py", "snippet": "class StepwiseMax(BaseAttack):\n \"\"\"\n Stepwise max攻击方法,这是一个结合了pgd l1, pgd l2, 和 pgd linf三种攻击方式的方法。\n\n 参数\n ----------\n @param use_random: bool类型,是否使用随机的起始点。\n @param rounding_threshold: float类型,用于四舍五入实数的阈值。\n @param is_attacker: bool类型,是否扮演攻击者角色(注意:防御者执行对抗性训练)。\n @param oblivion: bool类型,是否知道敌手指示器。\n @param kappa: 攻击信心度。\n @param manipulation_x: 可操作性。\n @param omega: 与每个api相对应的互依赖api的索引。\n @param device: 设备,'cpu'或'cuda'。\n\n \"\"\"\n\n def __init__(self, use_random=False, rounding_threshold=0.5,\n is_attacker=True, oblivion=False, kappa=1., manipulation_x=None, omega=None, device=None):\n super(StepwiseMax, self).__init__(is_attacker, oblivion, kappa, manipulation_x, omega, device)\n \n # 是否使用随机起点\n self.use_random = use_random\n \n # 断言确保四舍五入阈值在(0, 1)之间\n assert 0 < rounding_threshold < 1\n \n # 设置四舍五入的阈值\n self.round_threshold = rounding_threshold\n \n # lambda_用于正则化,通常与优化的损失一起使用\n self.lambda_ = 1.\n\n def perturb_dae(self, model, purifier, x, label=None,\n steps=100,\n step_check=1,\n sl_l1=1.,\n sl_l2=1.,\n sl_linf=0.01,\n min_lambda_=1e-5,\n max_lambda_=1e5,\n is_score_round=True,\n base=10.,\n verbose=False,\n oblivion=False):\n \"\"\"\n 对模型进行增强攻击。\n\n @param model: PyTorch模型,待攻击目标。\n @param x: Tensor, 原始输入数据。\n @param label: Tensor或None, 输入数据对应的标签。\n @param steps: int, 攻击的总步数。\n @param step_check: int, 检查间隔,即多少步进行一次检查。\n @param sl_l1: float, L1范数的步长。\n @param sl_l2: float, L2范数的步长。\n @param sl_linf: float, Linf范数的步长。\n @param min_lambda_: float, lambda的最小值。\n @param max_lambda_: float, lambda的最大值。\n @param is_score_round: Boolean, 是否对分数进行四舍五入。\n @param base: float, 基数。\n @param verbose: Boolean, 是否输出详细信息。\n \"\"\"\n # torch.manual_seed(int(random.random() * 100)) # 设置随机种子\n # 参数校验\n assert 0 < min_lambda_ <= max_lambda_\n assert steps >= 0 and (step_check >= 1) and 1 >= sl_l1 > 0 and sl_l2 >= 0 and sl_linf >= 0\n \n model.eval() # 将模型设置为评估模式\n purifier.eval()\n \n # 根据模型是否具有某种属性来设置lambda的初值\n if hasattr(model, 'is_detector_enabled'):\n self.lambda_ = min_lambda_\n else:\n self.lambda_ = max_lambda_\n \n # 如果不是攻击者,从预定义的步骤中随机选择一个\n if not self.is_attacker:\n step_checks = [1, 10, 25, 50]\n step_check = random.choice(step_checks)\n \n # 计算每个小步骤中需要的迭代次数\n mini_steps = [step_check] * (steps // step_check)\n mini_steps = mini_steps + [steps % step_check] if steps % step_check != 0 else mini_steps\n \n # 获取输入的维度信息\n n, red_n = x.size()[0], x.size()[1:]\n red_ind = list(range(2, len(x.size()) + 1))\n \n adv_x = x.detach().clone() # 获取输入数据的副本\n while self.lambda_ <= max_lambda_:\n pert_x_cont = None\n prev_done = None\n for i, mini_step in enumerate(mini_steps):\n with torch.no_grad():\n # 如果是第一步并且启用了随机初始化,那么获取一个随机的起始点\n if i == 0:\n adv_x = get_x0(adv_x, rounding_threshold=self.round_threshold, is_sample=True)\n # 计算损失和完成标志\n if not oblivion:\n purified_adv = purifier(adv_x.detach().clone().float()).to(torch.double)\n else:\n purified_adv = adv_x.detach().clone()\n _, done = self.get_loss(model, purified_adv, label, self.lambda_)\n \n # print(\"done:\", done)\n \n # 如果所有的都完成了,就退出循环\n if torch.all(done):\n break\n \n # 对于那些没有完成的数据,重新计算扰动\n # print(\"i:\", i)\n if i == 0:\n # print(\"~done:\", (~done))\n adv_x[~done] = x[~done]\n prev_done = done.clone()\n else:\n if (adv_x[~done]).shape[0] == (pert_x_cont[~done[~prev_done]]).shape[0]:\n adv_x[~done] = pert_x_cont[~done[~prev_done]]\n else:\n updated_mask = (~done) & (~prev_done[:len(done)])\n num_to_select = updated_mask.sum().item()\n selected_perturbations = pert_x_cont[:num_to_select]\n adv_x[updated_mask] = selected_perturbations\n\n prev_done = done.clone() \n \n # 对那些未完成的数据进行真正的扰动\n num_sample_red = torch.sum(~done).item()\n pert_x_l1, pert_x_l2, pert_x_linf = self._perturb_dae(model, purifier, adv_x[~done], label[~done],\n mini_step,\n sl_l1,\n sl_l2,\n sl_linf,\n lambda_=self.lambda_,\n oblivion=False\n )\n # print(\"pert_x_l1, pert_x_l2, pert_x_linf\", pert_x_l1, pert_x_l2, pert_x_linf)\n # 不计算梯度地执行下列操作\n with torch.no_grad():\n # 构造一个包含三种扰动的列表\n pertb_x_list = [pert_x_linf, pert_x_l2, pert_x_l1]\n n_attacks = len(pertb_x_list) # 获取攻击的数量(即3)\n pertbx = torch.vstack(pertb_x_list) # 垂直堆叠这三种扰动\n label_ext = torch.cat([label[~done]] * n_attacks) # 扩展标签列表,使其与扰动列表长度匹配\n\n # 如果不是攻击者并且不需要四舍五入得分,则获取得分\n # 否则,先对扰动进行四舍五入,再获取得分\n if not oblivion:\n purified_pertbx = purifier(pertbx.detach().clone().float()).to(torch.double)\n else:\n purified_pertbx = pertbx.detach().clone()\n if (not self.is_attacker) and (not is_score_round): \n scores, _done = self.get_scores(model, purified_pertbx, label_ext)\n else:\n scores, _done = self.get_scores(model, round_x(purified_pertbx, self.round_threshold), label_ext)\n \n # 如果得分的最大值大于0,则设置为该值,否则设置为0\n max_v = scores.amax() if scores.amax() > 0 else 0.\n scores[_done] += max_v # 对完成的得分增加max_v\n\n # 重新整形扰动和得分张量,以便后续操作\n pertbx = pertbx.reshape(n_attacks, num_sample_red, *red_n).permute([1, 0, *red_ind])\n scores = scores.reshape(n_attacks, num_sample_red).permute(1, 0)\n\n # 从得分张量中获取最大得分及其索引\n _2, s_idx = scores.max(dim=-1)\n # 使用索引从扰动张量中选择具有最高误导性的扰动\n pert_x_cont = pertbx[torch.arange(num_sample_red), s_idx]\n # print(\"pert_x_cont.shape\", pert_x_cont.shape)\n # 更新经过扰动的数据adv_x\n adv_x[~done] = pert_x_cont if not self.is_attacker else round_x(pert_x_cont, self.round_threshold)\n \n # 更新lambda值以便于下一次循环\n self.lambda_ *= base\n # 如果lambda值检查失败,则中断循环\n if not self.check_lambda(model):\n break\n # 如果是攻击者,对最终的扰动结果进行四舍五入\n if self.is_attacker:\n adv_x = round_x(adv_x, self.round_threshold)\n \n # 不计算梯度地获取最后的损失和完成标志\n with torch.no_grad():\n purified_adv = purifier(adv_x.detach().clone().float()).to(torch.double)\n _, done = self.get_loss(model, purified_adv, label, self.lambda_)\n # 如果设置了详细输出,打印攻击效果的百分比\n if verbose:\n logger.info(f\"step-wise max: attack effectiveness {done.sum().item() / done.size()[0] * 100:.3f}%.\")\n # 返回扰动后的数据\n return adv_x\n\n\n def perturb(self, model, x, label=None,\n steps=100,\n step_check=1,\n sl_l1=1.,\n sl_l2=1.,\n sl_linf=0.01,\n min_lambda_=1e-5,\n max_lambda_=1e5,\n is_score_round=True,\n base=10.,\n verbose=False):\n \"\"\"\n 对模型进行增强攻击。\n\n @param model: PyTorch模型,待攻击目标。\n @param x: Tensor, 原始输入数据。\n @param label: Tensor或None, 输入数据对应的标签。\n @param steps: int, 攻击的总步数。\n @param step_check: int, 检查间隔,即多少步进行一次检查。\n @param sl_l1: float, L1范数的步长。\n @param sl_l2: float, L2范数的步长。\n @param sl_linf: float, Linf范数的步长。\n @param min_lambda_: float, lambda的最小值。\n @param max_lambda_: float, lambda的最大值。\n @param is_score_round: Boolean, 是否对分数进行四舍五入。\n @param base: float, 基数。\n @param verbose: Boolean, 是否输出详细信息。\n \"\"\"\n # torch.manual_seed(int(random.random() * 100)) # 设置随机种子\n # 参数校验\n assert 0 < min_lambda_ <= max_lambda_\n assert steps >= 0 and (step_check >= 1) and 1 >= sl_l1 > 0 and sl_l2 >= 0 and sl_linf >= 0\n \n model.eval() # 将模型设置为评估模式\n \n # 根据模型是否具有某种属性来设置lambda的初值\n if hasattr(model, 'is_detector_enabled'):\n self.lambda_ = min_lambda_\n else:\n self.lambda_ = max_lambda_\n \n # 如果不是攻击者,从预定义的步骤中随机选择一个\n if not self.is_attacker:\n step_checks = [1, 10, 25, 50]\n step_check = random.choice(step_checks)\n \n # 计算每个小步骤中需要的迭代次数\n mini_steps = [step_check] * (steps // step_check)\n mini_steps = mini_steps + [steps % step_check] if steps % step_check != 0 else mini_steps\n \n # 获取输入的维度信息\n n, red_n = x.size()[0], x.size()[1:]\n red_ind = list(range(2, len(x.size()) + 1))\n \n adv_x = x.detach().clone() # 获取输入数据的副本\n while self.lambda_ <= max_lambda_:\n pert_x_cont = None\n prev_done = None\n for i, mini_step in enumerate(mini_steps):\n with torch.no_grad():\n # 如果是第一步并且启用了随机初始化,那么获取一个随机的起始点\n if i == 0:\n adv_x = get_x0(adv_x, rounding_threshold=self.round_threshold, is_sample=True)\n _, done = self.get_loss(model, adv_x, label, self.lambda_)\n \n # print(\"done:\", done)\n \n # 如果所有的都完成了,就退出循环\n if torch.all(done):\n break\n \n # 对于那些没有完成的数据,重新计算扰动\n # print(\"i:\", i)\n if i == 0:\n # print(\"~done:\", (~done))\n adv_x[~done] = x[~done]\n prev_done = done.clone()\n else:\n if (adv_x[~done]).shape[0] == (pert_x_cont[~done[~prev_done]]).shape[0]:\n adv_x[~done] = pert_x_cont[~done[~prev_done]]\n else:\n updated_mask = (~done) & (~prev_done[:len(done)])\n num_to_select = updated_mask.sum().item()\n selected_perturbations = pert_x_cont[:num_to_select]\n adv_x[updated_mask] = selected_perturbations\n\n prev_done = done.clone() \n \n # 对那些未完成的数据进行真正的扰动\n num_sample_red = torch.sum(~done).item()\n pert_x_l1, pert_x_l2, pert_x_linf = self._perturb(model, adv_x[~done], label[~done],\n mini_step,\n sl_l1,\n sl_l2,\n sl_linf,\n lambda_=self.lambda_\n )\n # print(\"pert_x_l1, pert_x_l2, pert_x_linf\", pert_x_l1, pert_x_l2, pert_x_linf)\n # 不计算梯度地执行下列操作\n with torch.no_grad():\n # 构造一个包含三种扰动的列表\n pertb_x_list = [pert_x_linf, pert_x_l2, pert_x_l1]\n n_attacks = len(pertb_x_list) # 获取攻击的数量(即3)\n pertbx = torch.vstack(pertb_x_list) # 垂直堆叠这三种扰动\n label_ext = torch.cat([label[~done]] * n_attacks) # 扩展标签列表,使其与扰动列表长度匹配\n\n # 如果不是攻击者并且不需要四舍五入得分,则获取得分\n # 否则,先对扰动进行四舍五入,再获取得分\n if (not self.is_attacker) and (not is_score_round):\n scores, _done = self.get_scores(model, pertbx, label_ext)\n else:\n scores, _done = self.get_scores(model, round_x(pertbx, self.round_threshold), label_ext)\n \n # 如果得分的最大值大于0,则设置为该值,否则设置为0\n max_v = scores.amax() if scores.amax() > 0 else 0.\n scores[_done] += max_v # 对完成的得分增加max_v\n\n # 重新整形扰动和得分张量,以便后续操作\n pertbx = pertbx.reshape(n_attacks, num_sample_red, *red_n).permute([1, 0, *red_ind])\n scores = scores.reshape(n_attacks, num_sample_red).permute(1, 0)\n\n # 从得分张量中获取最大得分及其索引\n _2, s_idx = scores.max(dim=-1)\n # 使用索引从扰动张量中选择具有最高误导性的扰动\n pert_x_cont = pertbx[torch.arange(num_sample_red), s_idx]\n # print(\"pert_x_cont.shape\", pert_x_cont.shape)\n # 更新经过扰动的数据adv_x\n adv_x[~done] = pert_x_cont if not self.is_attacker else round_x(pert_x_cont, self.round_threshold)\n \n # 更新lambda值以便于下一次循环\n self.lambda_ *= base\n # 如果lambda值检查失败,则中断循环\n if not self.check_lambda(model):\n break\n # 如果是攻击者,对最终的扰动结果进行四舍五入\n if self.is_attacker:\n adv_x = round_x(adv_x, self.round_threshold)\n \n # 不计算梯度地获取最后的损失和完成标志\n with torch.no_grad():\n _, done = self.get_loss(model, adv_x, label, self.lambda_)\n # 如果设置了详细输出,打印攻击效果的百分比\n if verbose:\n logger.info(f\"step-wise max: attack effectiveness {done.sum().item() / done.size()[0] * 100:.3f}%.\")\n # 返回扰动后的数据\n return adv_x\n\n def _perturb(self, model, x, label=None,\n steps=1,\n step_length_l1=1.,\n step_length_l2=0.5,\n step_length_linf=0.01,\n lambda_=1.,\n ):\n \"\"\"\n 对节点的特征向量进行扰动\n\n 参数\n -----------\n @param model: 受害者模型\n @param x: torch.FloatTensor, 节点特征向量(每个表示一个图中的API出现次数)形状为 [batch_size, vocab_dim]\n @param label: torch.LongTensor, 真实的标签\n @param steps: 整数, 迭代的最大次数\n @param step_length_l1: 每次迭代的步长,L1范数\n @param step_length_l2: 每次迭代的步长,L2范数\n @param step_length_linf: 每次迭代的步长,Linf范数\n @param lambda_: 浮点数, 惩罚因子\n \"\"\"\n if x is None or x.shape[0] <= 0:\n return []\n \n self.lambda_ = lambda_\n \n # 确保L1步长在[0,1]之间\n assert 0 <= step_length_l1 <= 1, \"期望在 [0,1] 之间的实数值,但得到 {}\".format(step_length_l1)\n model.eval()\n adv_x = x.detach()\n \n def one_iteration(_adv_x, norm_type):\n # 基于当前的扰动输入来计算梯度\n if \"rnn\" in model.model_save_path:\n model.train()\n if \"lstm\" in model.model_save_path:\n model.train() \n var_adv_x = torch.autograd.Variable(_adv_x, requires_grad=True) # 将_adv_x转换为一个可以进行自动梯度计算的变量\n loss, done = self.get_loss(model, var_adv_x, label, self.lambda_) # 获取模型在扰动输入上的损失\n grads = torch.autograd.grad(loss.mean(), var_adv_x, allow_unused=True)\n if grads[0] is None:\n grad = torch.zeros_like(var_adv_x)\n else:\n grad = grads[0].data\n\n # 寻找允许的位置来插入和移除API\n pos_insertion = (_adv_x <= 0.5) * 1 * (_adv_x >= 0.) # 寻找API的可插入位置:特征值在0和0.5之间\n grad4insertion = (grad > 0) * pos_insertion * grad # 根据梯度正值计算插入API的梯度\n\n pos_removal = (_adv_x > 0.5) * 1 # 寻找API的可移除位置:特征值大于0.5\n grad4removal = (grad <= 0) * (pos_removal & self.manipulation_x) * grad # 根据梯度负值计算移除API的梯度\n\n if self.is_attacker:\n # 对于攻击者,处理那些互相依赖的API\n checking_nonexist_api = (pos_removal ^ self.omega) & self.omega # 检查不存在的API\n grad4removal[:, self.api_flag] += torch.sum(grad * checking_nonexist_api, dim=-1, keepdim=True) # 考虑API之间的关系,调整移除API的梯度\n\n # 合并插入和移除的梯度\n grad = grad4removal + grad4insertion\n\n # 根据不同的范数类型,计算扰动值\n if norm_type == 'linf':\n perturbation = torch.sign(grad) # 计算梯度符号来获取无穷范数扰动方向\n if self.is_attacker:\n perturbation += (torch.any(perturbation[:, self.api_flag] < 0, dim=-1, keepdim=True) * checking_nonexist_api)\n return torch.clamp(_adv_x + step_length_linf * perturbation, min=0., max=1.) # 应用扰动并确保结果在[0,1]范围内\n\n elif norm_type == 'l2':\n l2norm = torch.linalg.norm(grad, dim=-1, keepdim=True) # 计算L2范数\n perturbation = torch.minimum(\n torch.tensor(1., dtype=_adv_x.dtype, device=_adv_x.device),\n grad / l2norm\n ) # 计算L2范数下的扰动方向\n perturbation = torch.where(torch.isnan(perturbation), 0., perturbation) # 处理NaN值\n perturbation = torch.where(torch.isinf(perturbation), 1., perturbation) # 处理Inf值\n if self.is_attacker:\n min_val = torch.amin(perturbation, dim=-1, keepdim=True).clamp_(max=0.)\n perturbation += (torch.any(perturbation[:, self.api_flag] < 0, dim=-1, keepdim=True) * torch.abs(min_val) * checking_nonexist_api)\n return torch.clamp(_adv_x + step_length_l2 * perturbation, min=0., max=1.)\n\n elif norm_type == 'l1':\n val, idx = torch.abs(grad).topk(int(1. / step_length_l1), dim=-1) # 获取梯度的绝对值的top-k值和相应的索引\n perturbation = F.one_hot(idx, num_classes=_adv_x.shape[-1]).sum(dim=1) # 根据索引计算L1范数下的扰动方向\n perturbation = torch.sign(grad) * perturbation # 使用梯度的符号来调整扰动方向\n if self.is_attacker:\n perturbation += (torch.any(perturbation[:, self.api_flag] < 0, dim=-1, keepdim=True) * checking_nonexist_api)\n return torch.clamp(_adv_x + step_length_l1 * perturbation, min=0., max=1.)\n\n else:\n raise NotImplementedError # 如果范数类型不在L1、L2、Linf中,则引发异常\n\n\n # 为每种范数执行迭代\n adv_x_l1 = adv_x.clone()\n for t in range(steps):\n adv_x_l1 = one_iteration(adv_x_l1, norm_type='l1')\n \n adv_x_l2 = adv_x.clone()\n for t in range(steps):\n adv_x_l2 = one_iteration(adv_x_l2, norm_type='l2')\n \n adv_x_linf = adv_x.clone()\n for t in range(steps):\n adv_x_linf = one_iteration(adv_x_linf, norm_type='linf')\n \n return adv_x_l1, adv_x_l2, adv_x_linf\n\n\n def _perturb_dae(self, model, purifier, x, label=None,\n steps=1,\n step_length_l1=1.,\n step_length_l2=0.5,\n step_length_linf=0.01,\n lambda_=1.,\n oblivion=False):\n \"\"\"\n 对节点的特征向量进行扰动\n\n 参数\n -----------\n @param model: 受害者模型\n @param x: torch.FloatTensor, 节点特征向量(每个表示一个图中的API出现次数)形状为 [batch_size, vocab_dim]\n @param label: torch.LongTensor, 真实的标签\n @param steps: 整数, 迭代的最大次数\n @param step_length_l1: 每次迭代的步长,L1范数\n @param step_length_l2: 每次迭代的步长,L2范数\n @param step_length_linf: 每次迭代的步长,Linf范数\n @param lambda_: 浮点数, 惩罚因子\n \"\"\"\n if x is None or x.shape[0] <= 0:\n return []\n \n self.lambda_ = lambda_\n \n # 确保L1步长在[0,1]之间\n assert 0 <= step_length_l1 <= 1, \"期望在 [0,1] 之间的实数值,但得到 {}\".format(step_length_l1)\n model.eval()\n adv_x = x.detach()\n \n\n def one_iteration(_adv_x, norm_type):\n # 基于当前的扰动输入来计算梯度\n var_adv_x = torch.autograd.Variable(_adv_x, requires_grad=True) # 将_adv_x转换为一个可以进行自动梯度计算的变量\n if not oblivion:\n purified_var = purifier(var_adv_x.detach().clone().float()).to(torch.double)\n else:\n purified_var = var_adv_x.detach().clone()\n loss, done = self.get_loss(model, purified_var, label, self.lambda_) # 获取模型在扰动输入上的损失\n grads = torch.autograd.grad(loss.mean(), var_adv_x, allow_unused=True)\n if grads[0] is None:\n grad = torch.zeros_like(var_adv_x)\n else:\n grad = grads[0].data\n\n # 寻找允许的位置来插入和移除API\n pos_insertion = (_adv_x <= 0.5) * 1 * (_adv_x >= 0.) # 寻找API的可插入位置:特征值在0和0.5之间\n grad4insertion = (grad > 0) * pos_insertion * grad # 根据梯度正值计算插入API的梯度\n\n pos_removal = (_adv_x > 0.5) * 1 # 寻找API的可移除位置:特征值大于0.5\n grad4removal = (grad <= 0) * (pos_removal & self.manipulation_x) * grad # 根据梯度负值计算移除API的梯度\n\n if self.is_attacker:\n # 对于攻击者,处理那些互相依赖的API\n checking_nonexist_api = (pos_removal ^ self.omega) & self.omega # 检查不存在的API\n grad4removal[:, self.api_flag] += torch.sum(grad * checking_nonexist_api, dim=-1, keepdim=True) # 考虑API之间的关系,调整移除API的梯度\n\n # 合并插入和移除的梯度\n grad = grad4removal + grad4insertion\n\n # 根据不同的范数类型,计算扰动值\n if norm_type == 'linf':\n perturbation = torch.sign(grad) # 计算梯度符号来获取无穷范数扰动方向\n if self.is_attacker:\n perturbation += (torch.any(perturbation[:, self.api_flag] < 0, dim=-1, keepdim=True) * checking_nonexist_api)\n return torch.clamp(_adv_x + step_length_linf * perturbation, min=0., max=1.) # 应用扰动并确保结果在[0,1]范围内\n\n elif norm_type == 'l2':\n l2norm = torch.linalg.norm(grad, dim=-1, keepdim=True) # 计算L2范数\n perturbation = torch.minimum(\n torch.tensor(1., dtype=_adv_x.dtype, device=_adv_x.device),\n grad / l2norm\n ) # 计算L2范数下的扰动方向\n perturbation = torch.where(torch.isnan(perturbation), 0., perturbation) # 处理NaN值\n perturbation = torch.where(torch.isinf(perturbation), 1., perturbation) # 处理Inf值\n if self.is_attacker:\n min_val = torch.amin(perturbation, dim=-1, keepdim=True).clamp_(max=0.)\n perturbation += (torch.any(perturbation[:, self.api_flag] < 0, dim=-1, keepdim=True) * torch.abs(min_val) * checking_nonexist_api)\n return torch.clamp(_adv_x + step_length_l2 * perturbation, min=0., max=1.)\n\n elif norm_type == 'l1':\n val, idx = torch.abs(grad).topk(int(1. / step_length_l1), dim=-1) # 获取梯度的绝对值的top-k值和相应的索引\n perturbation = F.one_hot(idx, num_classes=_adv_x.shape[-1]).sum(dim=1) # 根据索引计算L1范数下的扰动方向\n perturbation = torch.sign(grad) * perturbation # 使用梯度的符号来调整扰动方向\n if self.is_attacker:\n perturbation += (torch.any(perturbation[:, self.api_flag] < 0, dim=-1, keepdim=True) * checking_nonexist_api)\n return torch.clamp(_adv_x + step_length_l1 * perturbation, min=0., max=1.)\n\n else:\n raise NotImplementedError # 如果范数类型不在L1、L2、Linf中,则引发异常\n\n\n # 为每种范数执行迭代\n adv_x_l1 = adv_x.clone()\n for t in range(steps):\n adv_x_l1 = one_iteration(adv_x_l1, norm_type='l1')\n \n adv_x_l2 = adv_x.clone()\n for t in range(steps):\n adv_x_l2 = one_iteration(adv_x_l2, norm_type='l2')\n \n adv_x_linf = adv_x.clone()\n for t in range(steps):\n adv_x_linf = one_iteration(adv_x_linf, norm_type='linf')\n \n return adv_x_l1, adv_x_l2, adv_x_linf\n\n def get_scores(self, model, pertb_x, label):\n # 如果模型有 'is_detector_enabled' 这个属性\n if hasattr(model, 'is_detector_enabled'):\n # 获取模型的输出,logits_f 是模型的原始输出,prob_g 是一个概率值\n logits_f, prob_g = model.forward(pertb_x)\n else:\n # 如果模型没有 'is_detector_enabled' 这个属性,只获取模型的原始输出\n logits_f = model.forward(pertb_x)\n\n # 获取预测的类别\n y_pred = logits_f.argmax(1)\n \n # 计算交叉熵损失\n ce = F.cross_entropy(logits_f, label, reduction='none')\n \n # 如果模型有 'is_detector_enabled' 这个属性,并且 self.oblivion 为 False\n if hasattr(model, 'is_detector_enabled') and (not self.oblivion):\n # 获取样本的阈值\n tau = model.get_tau_sample_wise(y_pred)\n # 计算损失,加入了 prob_g 这个概率值的惩罚项\n loss_no_reduction = ce - self.lambda_ * prob_g\n # 判断预测是否错误,并且 prob_g 是否小于等于阈值 tau\n done = (y_pred != label) & (prob_g <= tau)\n else:\n # 如果没有 'is_detector_enabled' 这个属性或 self.oblivion 为 True,损失仍然是交叉熵损失\n loss_no_reduction = ce\n # 判断预测是否错误\n done = y_pred != label\n\n # 返回损失值和判断结果c\n return loss_no_reduction, done" }, { "identifier": "MalwareDetectionDNN", "path": "core/defense/md_dnn.py", "snippet": "class MalwareDetectionDNN(nn.Module):\n def __init__(self, input_size, n_classes, device='cpu', name='DNN', **kwargs):\n \"\"\"\n 初始化恶意软件检测器\n\n 参数:\n ----------\n @param input_size: 整数,输入向量的维度数量。\n @param n_classes: 整数,表示分类的数量,例如二分类问题中n=2。\n @param device: 字符串,可以是'cpu'或'cuda',表示模型应该在CPU还是GPU上运行。\n @param name: 字符串,用于命名模型。\n \"\"\"\n super(MalwareDetectionDNN, self).__init__() # 调用父类初始化\n self.input_size = input_size # 定义输入尺寸\n self.n_classes = n_classes # 定义分类数量\n self.device = device # 定义运行设备\n self.name = name # 定义模型名称\n\n self.parse_args(**kwargs) # 解析额外参数\n\n self.dense_layers = [] # 初始化一个空的密集层列表\n \n # 检查是否至少有一个隐藏层\n if len(self.dense_hidden_units) >= 1:\n # 添加第一个密集层\n self.dense_layers.append(nn.Linear(self.input_size, self.dense_hidden_units[0]))\n else:\n # 如果没有隐藏层,抛出异常\n raise ValueError(\"Expect at least one hidden layer.\")\n\n # 为每一对连续的隐藏单元添加一个密集层\n for i in range(len(self.dense_hidden_units[0:-1])):\n self.dense_layers.append(nn.Linear(self.dense_hidden_units[i], \n self.dense_hidden_units[i + 1]))\n \n # 添加最后一个连接到输出层的密集层\n self.dense_layers.append(nn.Linear(self.dense_hidden_units[-1], self.n_classes))\n \n # 将密集层添加到模型中以进行跟踪\n for idx_i, dense_layer in enumerate(self.dense_layers):\n self.add_module('nn_model_layer_{}'.format(idx_i), dense_layer)\n\n # 根据参数选择使用SELU或ReLU激活函数\n if self.smooth:\n self.activation_func = F.selu # 使用SELU激活函数\n else:\n self.activation_func = F.relu # 使用ReLU激活函数\n\n # 定义模型的保存路径\n self.model_save_path = path.join(config.get('experiments', 'md_dnn') + '_' + self.name,\n 'model.pth')\n \n # 日志中打印模型的结构信息\n logger.info('========================================dnn model architecture===============================')\n logger.info(self)\n logger.info('===============================================end==========================================')\n\n\n def parse_args(self,\n dense_hidden_units=None,\n dropout=0.6,\n alpha_=0.2,\n smooth=False,\n **kwargs\n ):\n \"\"\"\n 解析并设置网络的超参数。\n\n 参数:\n ----------\n dense_hidden_units : list, 可选\n 网络中每个隐藏层的单元数。如果没有指定,则默认为两个隐藏层,每层200个单元。\n dropout : float, 可选\n dropout正则化的比率,默认为0.6。\n alpha_ : float, 可选\n 某些激活函数的参数,默认为0.2。\n smooth : bool, 可选\n 是否使用平滑的激活函数,默认为False。\n **kwargs : dict\n 其他超参数。\n \"\"\"\n\n # 如果用户没有指定隐藏层,使用默认的配置\n if dense_hidden_units is None:\n self.dense_hidden_units = [200, 200]\n # 如果用户指定了一个列表,使用它\n elif isinstance(dense_hidden_units, list):\n self.dense_hidden_units = dense_hidden_units\n # 否则抛出一个异常\n else:\n raise TypeError(\"Expect a list of hidden units.\")\n\n # 设置dropout, alpha和smooth参数\n self.dropout = dropout\n self.alpha_ = alpha_\n self.smooth = smooth\n\n # 从kwargs中获取并设置proc_number\n self.proc_number = kwargs.get('proc_number', None) # 如果不存在,则返回None\n\n # 如果还有其他参数,记录警告,因为这些参数可能是未知的\n if len(kwargs) > 0:\n logger.warning(\"Unknown hyper-parameters {}\".format(str(kwargs)))\n\n\n def forward(self, x):\n \"\"\"\n 使输入数据 x 通过神经网络\n \n 参数\n ----------\n @param x: 2D张量,特征表示\n \"\"\"\n # 遍历神经网络的每一层,除了最后一层\n for dense_layer in self.dense_layers[:-1]:\n x = self.activation_func(dense_layer(x)) # 使用激活函数处理每一层的输出\n\n # 对处理过的数据进行 dropout 操作,用于防止过拟合\n latent_representation = F.dropout(x, self.dropout, training=self.training)\n \n # 用最后一层进行处理,得到logits(未归一化的预测或分类得分)\n logits = self.dense_layers[-1](latent_representation)\n return logits\n\n def inference(self, test_data_producer):\n \"\"\"\n 进行模型推理,获得预测的置信度和真实标签\n \n 参数\n ----------\n @param test_data_producer: 数据生产者或数据加载器,用于产生测试数据\n \n 返回值\n ----------\n 返回预测的置信度和真实标签\n \"\"\"\n confidences = [] # 存储每批数据的预测置信度\n gt_labels = [] # 存储每批数据的真实标签\n self.eval() # 设置模型为评估模式\n\n # 使用torch.no_grad()来告诉PyTorch不要在推理过程中计算梯度\n with torch.no_grad():\n # 遍历每一批测试数据\n for x, y in test_data_producer:\n # 将数据转移到指定的设备(CPU或GPU)并调整数据类型\n x, y = utils.to_device(x.double(), y.long(), self.device)\n # 得到每一批数据的logits\n logits = self.forward(x)\n # 使用softmax函数得到每一批数据的置信度,并将其添加到confidences列表中\n confidences.append(F.softmax(logits, dim=-1))\n # 将每一批数据的真实标签添加到gt_labels列表中\n gt_labels.append(y)\n\n # 将所有批次的置信度垂直堆叠成一个张量\n confidences = torch.vstack(confidences)\n # 将所有批次的真实标签连接成一个张量\n gt_labels = torch.cat(gt_labels, dim=0)\n \n return confidences, gt_labels\n\n def inference_dae(self, test_data_producer):\n \"\"\"\n 进行模型推理,获得预测的置信度和真实标签\n \n 参数\n ----------\n @param test_data_producer: 数据生产者或数据加载器,用于产生测试数据\n \n 返回值\n ----------\n 返回预测的置信度和真实标签\n \"\"\"\n confidences = [] # 存储每批数据的预测置信度\n gt_labels = [] # 存储每批数据的真实标签\n self.eval() # 设置模型为评估模式\n\n # 使用torch.no_grad()来告诉PyTorch不要在推理过程中计算梯度\n with torch.no_grad():\n # 遍历每一批测试数据\n for x, y in test_data_producer:\n # 将数据转移到指定的设备(CPU或GPU)并调整数据类型\n x, y = utils.to_device(x.double(), y.long(), self.device)\n # 得到每一批数据的logits\n logits = self.forward(x)\n # 使用softmax函数得到每一批数据的置信度,并将其添加到confidences列表中\n confidences.append(F.softmax(logits, dim=-1))\n # 将每一批数据的真实标签添加到gt_labels列表中\n gt_labels.append(y)\n \n return confidences, gt_labels\n\n\n def get_important_attributes(self, test_data_producer, target_label=1):\n \"\"\"\n 使用集成梯度(Integrated Gradients)方法获取重要的属性/特征\n\n 参数\n ----------\n @param test_data_producer: 数据生产者或数据加载器,用于产生测试数据\n @param target_label: 目标标签,默认为1\n \n 返回值\n ----------\n 返回重要的属性/特征\n \"\"\"\n attributions = [] # 存储属性或特征的重要性得分\n gt_labels = [] # 存储真实标签\n\n # 定义一个使用集成梯度方法的包装器\n def _ig_wrapper(_x):\n logits = self.forward(_x)\n return F.softmax(logits, dim=-1)\n\n # 初始化集成梯度对象\n ig = IntegratedGradients(_ig_wrapper)\n\n # 遍历测试数据集\n for i, (x, y) in enumerate(test_data_producer):\n # 将数据和标签转移到指定的设备上\n x, y = utils.to_device(x.double(), y.long(), self.device)\n # 使x能够计算梯度\n x.requires_grad = True\n # 定义基线,用于集成梯度的计算\n baseline = torch.zeros_like(x, dtype=torch.double, device=self.device)\n # 计算属性的重要性\n attribution_bs = ig.attribute(x,\n baselines=baseline,\n target=target_label)\n # 将所有批次的属性垂直堆叠\n attribution = torch.hstack(attribution_bs)\n # 保存得到的属性重要性得分和真实标签\n attributions.append(attribution.clone().detach().cpu().numpy())\n gt_labels.append(y.clone().detach().cpu().numpy())\n # 将真实标签保存为.npy文件\n np.save('./labels', np.concatenate(gt_labels))\n \n return np.vstack(attributions)\n\n\n def inference_batch_wise(self, x):\n \"\"\"\n 仅支持恶意软件样本的批量推理\n \n 参数\n ----------\n @param x: 输入数据的张量\n \n 返回值\n ----------\n 返回推理的置信度和标签\n \"\"\"\n # 确保输入是一个张量\n assert isinstance(x, torch.Tensor)\n \n # 获得模型的输出\n logit = self.forward(x)\n \n # 返回每个样本的置信度和一个与logit形状相同的全1数组(表示恶意软件样本)\n return torch.softmax(logit, dim=-1).detach().cpu().numpy(), np.ones((logit.size()[0],))\n\n\n def predict(self, test_data_producer, indicator_masking=True):\n \"\"\"\n 预测标签并进行评估\n\n 参数\n --------\n @param test_data_producer: torch.DataLoader, 用于生成测试数据的数据加载器\n \"\"\"\n # 进行评估\n confidence, y_true = self.inference(test_data_producer)\n y_pred = confidence.argmax(1).cpu().numpy() # 预测标签\n y_true = y_true.cpu().numpy() # 真实标签\n \n # print(\"y_true.shape:\", y_true.shape)\n # print(\"y_pred.shape:\", y_pred.shape)\n \n # 使用sklearn的评估指标进行评估\n from sklearn.metrics import f1_score, accuracy_score, confusion_matrix, balanced_accuracy_score\n accuracy = accuracy_score(y_true, y_pred)\n b_accuracy = balanced_accuracy_score(y_true, y_pred)\n \n MSG = \"The accuracy on the test dataset is {:.5f}%\"\n logger.info(MSG.format(accuracy * 100))\n \n MSG = \"The balanced accuracy on the test dataset is {:.5f}%\"\n logger.info(MSG.format(b_accuracy * 100))\n\n # 检查数据中是否存在缺失的类别\n if np.any([np.all(y_true == i) for i in range(self.n_classes)]):\n logger.warning(\"class absent.\")\n return\n\n # 计算混淆矩阵\n tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()\n fpr = fp / float(tn + fp) # 计算假阳性率\n fnr = fn / float(tp + fn) # 计算假阴性率\n f1 = f1_score(y_true, y_pred, average='binary') # 计算F1分数\n\n print(\"Other evaluation metrics we may need:\")\n MSG = \"False Negative Rate (FNR) is {:.5f}%、False Positive Rate (FPR) is {:.5f}%, F1 score is {:.5f}%\"\n logger.info(MSG.format(fnr * 100, fpr * 100, f1 * 100))\n\n\n def customize_loss(self, logits, gt_labels, representation=None, mini_batch_idx=None):\n \"\"\"\n 自定义损失函数\n\n 参数\n --------\n @param logits: Tensor, 模型的输出\n @param gt_labels: Tensor, 真实的标签\n @param representation: Tensor, 可选参数,表示特征表示\n @param mini_batch_idx: Int, 可选参数,表示小批次的索引\n \n 返回值\n --------\n 返回交叉熵损失\n \"\"\"\n return F.cross_entropy(logits, gt_labels)\n\n\n def fit(self, train_data_producer, validation_data_producer, epochs=100, lr=0.005, weight_decay=0., weight_sampling=0.5, verbose=True):\n \"\"\"\n 训练恶意软件检测器,根据验证集上的交叉熵损失选择最佳模型。\n\n 参数\n ----------\n @param train_data_producer: 对象, 用于生成一批训练数据的迭代器\n @param validation_data_producer: 对象, 用于生成验证数据的迭代器\n @param epochs: 整数, 训练的周期数\n @param lr: 浮点数, Adam优化器的学习率\n @param weight_decay: 浮点数, 惩罚因子\n @param verbose: 布尔值, 是否显示详细的日志\n \"\"\"\n # 初始化优化器\n optimizer = optim.Adam(self.parameters(), lr=lr, weight_decay=weight_decay)\n best_avg_acc = 0. # 记录验证集上的最佳准确率\n best_epoch = 0 # 记录最佳准确率对应的周期\n total_time = 0. # 总的训练时间\n\n # 获取训练数据批次的数量\n nbatches = len(train_data_producer)\n \n # 进行指定次数的训练周期\n for i in range(epochs):\n # 设置模型为训练模式\n self.train()\n # 初始化列表用于保存每批数据的损失值和准确率\n losses, accuracies = [], []\n\n # 对每个训练数据批次进行遍历\n for idx_batch, (x_train, y_train) in enumerate(train_data_producer):\n # 将数据转移到指定的计算设备(例如GPU或CPU)\n x_train, y_train = utils.to_device(x_train.double(), y_train.long(), self.device)\n\n # 记录开始训练的时间\n start_time = time.time()\n\n # 清空之前累积的梯度\n optimizer.zero_grad() \n \n # 对输入数据进行前向传播\n logits = self.forward(x_train) \n \n # 根据模型的输出和真实标签计算损失\n loss_train = self.customize_loss(logits, y_train) \n\n # 对损失进行反向传播\n loss_train.backward()\n \n # 使用优化器更新模型参数\n optimizer.step()\n\n # 计算训练这批数据所花费的总时间\n total_time += time.time() - start_time\n \n # 计算这批数据上的准确率\n acc_train = (logits.argmax(1) == y_train).sum().item() / x_train.size()[0]\n \n # 将时间转换为分钟和秒\n mins, secs = int(total_time / 60), int(total_time % 60)\n \n # 将这批数据的损失和准确率加入到列表中\n losses.append(loss_train.item())\n accuracies.append(acc_train)\n\n # 如果开启了详细输出模式,显示当前训练进度和这批数据上的损失和准确率\n if verbose:\n logger.info(f'小批次: {i * nbatches + idx_batch + 1}/{epochs * nbatches} | 训练时间为 {mins:.0f} 分钟, {secs} 秒。')\n logger.info(f'训练损失(小批次级别): {losses[-1]:.4f} | 训练精度: {acc_train * 100:.2f}')\n\n\n self.eval() # 将模型设置为评估模式\n avg_acc_val = []\n\n with torch.no_grad(): # 确保在评估模式下不进行梯度的计算\n for x_val, y_val in validation_data_producer:\n # 将数据移动到指定设备(例如GPU或CPU)上,并确保数据的类型为双精度浮点数和长整型\n x_val, y_val = utils.to_device(x_val.double(), y_val.long(), self.device)\n \n # 使用模型进行前向传播,得到输出结果\n logits = self.forward(x_val)\n \n # 计算验证数据上的准确率\n acc_val = (logits.argmax(1) == y_val).sum().item() / x_val.size()[0]\n \n # 保存每一批验证数据的准确率\n avg_acc_val.append(acc_val)\n \n # 计算所有验证数据的平均准确率\n avg_acc_val = np.mean(avg_acc_val)\n\n # 如果当前周期的验证精度超过之前的最佳验证精度\n if avg_acc_val >= best_avg_acc:\n # 更新最佳验证精度\n best_avg_acc = avg_acc_val\n best_epoch = i\n \n # 检查模型保存路径是否存在,如果不存在,则创建\n if not path.exists(self.model_save_path):\n utils.mkdir(path.dirname(self.model_save_path))\n \n # 保存当前的模型参数\n torch.save(self.state_dict(), self.model_save_path)\n \n # 如果开启了详细输出模式,显示模型保存路径\n if verbose:\n print(f'模型保存在路径: {self.model_save_path}')\n\n # 如果开启了详细输出模式,显示训练损失、训练精度、验证精度和最佳验证精度\n if verbose:\n logger.info(f'训练损失(周期级别): {np.mean(losses):.4f} | 训练精度: {np.mean(accuracies) * 100:.2f}')\n logger.info(f'验证精度: {avg_acc_val * 100:.2f} | 最佳验证精度: {best_avg_acc * 100:.2f} 在第 {best_epoch} 个周期')\n\n def load(self):\n \"\"\"\n 从磁盘加载模型参数\n \"\"\"\n self.load_state_dict(torch.load(self.model_save_path))" }, { "identifier": "DetectorTemplate", "path": "core/defense/amd_template.py", "snippet": "class DetectorTemplate(object):\n def __init__(self):\n self.tau = None # 阈值变量\n self.is_detector_enabled = True # 表示检测器是否启用的标志\n\n def forward(self, x):\n \"\"\"\n 类预测与密度估计\n \"\"\"\n raise NotImplementedError\n\n def get_threshold(self):\n \"\"\"\n 计算拒绝异常值的阈值\n \"\"\"\n raise NotImplementedError\n\n def get_tau_sample_wise(self):\n \"\"\"\n 获取每个样本的tau值\n \"\"\"\n raise NotImplementedError\n\n def indicator(self):\n \"\"\"\n 返回一个布尔标志向量,指示是否拒绝一个样本\n \"\"\"\n raise NotImplementedError" }, { "identifier": "config", "path": "config.py", "snippet": "def parser_config():" }, { "identifier": "utils", "path": "tools/utils.py", "snippet": "ENC_KEY = 'cab228a122d3486bac7fab148e8b5aba'\n MSG = \"No such directory or file {} exists!\".format(sample_dir)\n MSG = \"A directory or a list of paths are allowed!\"\ndef pool_initializer():\ndef retrive_files_set(base_dir, dir_ext, file_ext):\n def get_file_name(root_dir, file_ext):\ndef check_dir(sample_dir):\ndef dump_joblib(data, path):\ndef read_joblib(path):\ndef load_json(json_path):\ndef dump_json(obj_dict, file_path):\ndef dump_pickle(data, path, use_gzip=False):\ndef read_pickle(path, use_gzip=False):\ndef dump_pickle_frd_space(data, path):\ndef read_pickle_frd_space(path):\ndef dump_list_of_lists(data, path):\ndef read_list_of_lists(path):\ndef mkdir(target):\ndef read_txt(path, mode='r'):\ndef dump_txt(data_str, path, mode='w'):\ndef read_file_by_fileinput(file_path, inplace=True):\n def __init__(self, manager, use_cache=True):\n def is_cached(self, key):\n def reset(self):\n def get(self, key):\n def cache(self, key, img, lbl):\ndef build_kwargs(keys, arg_dict):\ndef inverse_kwargs(vars):\ndef save_args(fout, args):\ndef load_args(fout):\ndef get_group_args(args, args_parser, title):\ndef tensor_coo_sp_to_ivs(sparse_tensor):\ndef ivs_to_tensor_coo_sp(ivs, device='cpu'):\ndef sp_to_symmetric_sp(sparse_mx):\ndef sparse_mx_to_torch_sparse_tensor(sparse_mx):\ndef to_tensor(feature_x=None, labels=None, device='cpu'):\n def _to_torch_tensor(mat):\ndef to_device(feature_x=None, labels=None, device='cpu'):\ndef psn(x_tensor, prob, lower_value=0., upper_value=1.):\n def __init__(self):\n def __call__(self, module):\ndef round_x(x, alpha=0.5):\ndef get_x0(x, rounding_threshold=0.5, is_sample=False):\ndef or_tensors(x_1, x_2):\ndef xor_tensors(x_1, x_2):\ndef get_mal_data(x_batch, y_batch):\ndef get_mal_ben_data(x_batch, y_batch):\ndef java_class_name2smali_name(cls):\ndef remove_duplicate(components):\ndef crypt_identifier(idf, seed=2345):\n def md5_transform():\ndef random_string(code):\n def sha1_transform():\ndef string_on_code(code):\n def md5_transform():\ndef random_name(seed=2345, code='abc'):\ndef apply_encryption(base_string):\ndef get_sha256(file_path):\nclass SimplifyClass:\nclass NonnegWeightConstraint(object):" } ]
import time import os.path as path import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import numpy as np from core.attack.max import Max from core.attack.stepwise_max import StepwiseMax from core.defense.md_dnn import MalwareDetectionDNN from core.defense.amd_template import DetectorTemplate from config import config, logging, ErrorHandler from tools import utils from sklearn.metrics import f1_score, accuracy_score, confusion_matrix, balanced_accuracy_score
19,698
""" @inproceedings{sperl2020dla, title={DLA: dense-layer-analysis for adversarial example detection}, author={Sperl, Philip and Kao, Ching-Yu and Chen, Peng and Lei, Xiao and B{\"o}ttinger, Konstantin}, booktitle={2020 IEEE European Symposium on Security and Privacy (EuroS\&P)}, pages={198--215}, year={2020}, organization={IEEE} } This implementation is not an official version, but adapted from: https://github.com/v-wangg/OrthogonalPGD/ """ from __future__ import absolute_import from __future__ import division from __future__ import print_function logger = logging.getLogger('core.defense.amd_dla') logger.addHandler(ErrorHandler)
""" @inproceedings{sperl2020dla, title={DLA: dense-layer-analysis for adversarial example detection}, author={Sperl, Philip and Kao, Ching-Yu and Chen, Peng and Lei, Xiao and B{\"o}ttinger, Konstantin}, booktitle={2020 IEEE European Symposium on Security and Privacy (EuroS\&P)}, pages={198--215}, year={2020}, organization={IEEE} } This implementation is not an official version, but adapted from: https://github.com/v-wangg/OrthogonalPGD/ """ from __future__ import absolute_import from __future__ import division from __future__ import print_function logger = logging.getLogger('core.defense.amd_dla') logger.addHandler(ErrorHandler)
class AMalwareDetectionDLA(nn.Module, DetectorTemplate):
3
2023-11-27 02:00:23+00:00
24k
Matrixeigs/UncertaintyManagementInteroperablePowerTransportationSystems
TestCaseDistributionSystems/uc_mmgs_tess_stochastic.py
[ { "identifier": "case33", "path": "TestCaseDistributionSystems/test_cases/case33.py", "snippet": "def case33():\n \"\"\"Power flow data for 33 bus, 6 generator case.\n Please see L{caseformat} for details on the case file format.\n\n Based on data from ...\n\n Alsac, O. & Stott, B., I{\"Optimal Load Flow with Steady State Security\"},\n IEEE Transactions on Power Apparatus and Systems, Vol. PAS 93, No. 3,\n 1974, pp. 745-751.\n\n ... with branch parameters rounded to nearest 0.01, shunt values divided\n by 100 and shunt on bus 10 moved to bus 5, load at bus 5 zeroed out.\n Generator locations, costs and limits and bus areas were taken from ...\n\n Ferrero, R.W., Shahidehpour, S.M., Ramesh, V.C., I{\"Transaction analysis\n in deregulated power systems using game theory\"}, IEEE Transactions on\n Power Systems, Vol. 12, No. 3, Aug 1997, pp. 1340-1347.\n\n Generator Q limits were derived from Alsac & Stott, using their Pmax\n capacities. V limits and line |S| limits taken from Alsac & Stott.\n\n @return: Power flow data for 30 bus, 6 generator case.\n @see: U{http://www.pserc.cornell.edu/matpower/}\n \"\"\"\n ppc = {\"version\": '2'}\n\n ##----- Power Flow Data -----##\n ## system MVA base\n ppc[\"baseMVA\"] = 100.0\n\n ## bus data\n # bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin\n ppc[\"bus\"] = array([\n [1, 3, 0, 0, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [2, 1, 0.1, 0.06, 0, 0, 1, 1, 0, 12.66, 1, 1.1, 0.95],\n [3, 1, 0.09, 0.04, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [4, 1, 0.12, 0.08, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [5, 1, 0.06, 0.03, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [6, 1, 0.06, 0.02, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [7, 1, 0.2, 0.1, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [8, 1, 0.2, 0.1, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [9, 1, 0.06, 0.02, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [10, 1, 0.06, 0.02, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [11, 1, 0.045, 0.03, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [12, 1, 0.06, 0.035, 0, 0, 2, 1, 0, 12.66, 1, 1.05, 0.95],\n [13, 1, 0.06, 0.035, 0, 0, 2, 1, 0, 12.66, 1, 1.1, 0.95],\n [14, 1, 0.12, 0.08, 0, 0, 2, 1, 0, 12.66, 1, 1.05, 0.95],\n [15, 1, 0.06, 0.01, 0, 0, 2, 1, 0, 12.66, 1, 1.05, 0.95],\n [16, 1, 0.06, 0.02, 0, 0, 2, 1, 0, 12.66, 1, 1.05, 0.95],\n [17, 1, 0.06, 0.02, 0, 0, 2, 1, 0, 12.66, 1, 1.05, 0.95],\n [18, 1, 0.09, 0.04, 0, 0, 2, 1, 0, 12.66, 1, 1.05, 0.95],\n [19, 1, 0.09, 0.04, 0, 0, 2, 1, 0, 12.66, 1, 1.05, 0.95],\n [20, 1, 0.09, 0.04, 0, 0, 2, 1, 0, 12.66, 1, 1.05, 0.95],\n [21, 1, 0.09, 0.04, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [22, 2, 0.09, 0.04, 0, 0, 3, 1, 0, 12.66, 1, 1.1, 0.95],\n [23, 2, 0.09, 0.05, 0, 0, 2, 1, 0, 12.66, 1, 1.1, 0.95],\n [24, 1, 0.42, 0.20, 0, 0.04, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [25, 1, 0.42, 0.2, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [26, 1, 0.06, 0.025, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [27, 1, 0.06, 0.025, 0, 0, 3, 1, 0, 12.66, 1, 1.1, 0.95],\n [28, 1, 0.06, 0.02, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [29, 1, 0.12, 0.07, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [30, 1, 0.2, 0.6, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [31, 1, 0.15, 0.07, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [32, 1, 0.21, 0.1, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [33, 1, 0.06, 0.04, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n ])\n\n ## generator data\n # bus, Pg, Qg, Qmax, Qmin, Vg, mBase, status, Pmax, Pmin, Pc1, Pc2,\n # Qc1min, Qc1max, Qc2min, Qc2max, ramp_agc, ramp_10, ramp_30, ramp_q, apf, start-up time, shut-down time and initial condition!\n ppc[\"gen\"] = array([\n [1, 23.54, 0, 150, -20, 1, 100, 1, 80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 1],\n ])\n\n ## branch data\n # fbus, tbus, r, x, b, rateA, rateB, rateC, ratio, angle, status, angmin, angmax\n ppc[\"branch\"] = array([\n [1, 2, 0.057525912, 0.029324489, 0, 130, 130, 130, 0, 0, 1, -360, 360],\n [2, 3, 0.307595167, 0.15666764, 0, 130, 130, 130, 0, 0, 1, -360, 360],\n [3, 4, 0.228356656, 0.116299674, 0, 65, 65, 65, 0, 0, 1, -360, 360],\n [4, 5, 0.237777928, 0.121103899, 0, 130, 130, 130, 0, 0, 1, -360, 360],\n [5, 6, 0.510994811, 0.441115179, 0, 130, 130, 130, 0, 0, 1, -360, 360],\n [6, 7, 0.116798814, 0.386084969, 0, 65, 65, 65, 0, 0, 1, -360, 360],\n [7, 8, 0.44386045, 0.146684835, 0, 90, 90, 90, 0, 0, 1, -360, 360],\n [8, 9, 0.642643047, 0.461704714, 0, 70, 70, 70, 0, 0, 1, -360, 360],\n [9, 10, 0.651378001, 0.461704714, 0, 130, 130, 130, 0, 0, 1, -360, 360],\n [10, 11, 0.122663712, 0.040555144, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [11, 12, 0.233597628, 0.077241951, 0, 65, 65, 65, 0, 0, 1, -360, 360],\n [12, 13, 0.915922324, 0.720633708, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [13, 14, 0.337917936, 0.444796338, 0, 65, 65, 65, 0, 0, 1, -360, 360],\n [14, 15, 0.368739846, 0.328184702, 0, 65, 65, 65, 0, 0, 1, -360, 360],\n [15, 16, 0.465635443, 0.340039282, 0, 65, 65, 65, 0, 0, 1, -360, 360],\n [16, 17, 0.804239697, 1.073775422, 0, 65, 65, 65, 0, 0, 1, -360, 360],\n [17, 18, 0.456713311, 0.358133116, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [2, 19, 0.102323747, 0.097644308, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [19, 20, 0.938508419, 0.845668336, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [20, 21, 0.255497406, 0.298485858, 0, 16, 16, 16, 0, 0, 1, -360, 360],\n [21, 22, 0.442300637, 0.584805173, 0, 16, 16, 16, 0, 0, 1, -360, 360],\n [3, 23, 0.28151509, 0.192356167, 0, 16, 16, 16, 0, 0, 1, -360, 360],\n [23, 24, 0.560284909, 0.442425422, 0, 16, 16, 16, 0, 0, 1, -360, 360],\n [24, 25, 0.559037059, 0.43743402, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [6, 26, 0.126656834, 0.064513875, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [26, 27, 0.177319567, 0.090281989, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [27, 28, 0.660736881, 0.582559042, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [28, 29, 0.501760717, 0.437122057, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [29, 30, 0.316642084, 0.161284687, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [30, 31, 0.607952801, 0.600840053, 0, 16, 16, 16, 0, 0, 1, -360, 360],\n [31, 32, 0.193728802, 0.225798562, 0, 16, 16, 16, 0, 0, 1, -360, 360],\n [32, 33, 0.212758523, 0.330805188, 0, 16, 16, 16, 0, 0, 1, -360, 360],\n [7, 20, 1.2479, 1.2479, 0, 16, 16, 16, 0, 0, 0, -360, 360],\n [8, 14, 1.2479, 1.2479, 0, 16, 16, 16, 0, 0, 0, -360, 360],\n [11, 21, 1.2479, 1.2479, 0, 16, 16, 16, 0, 0, 0, -360, 360],\n [17, 32, 0.3120, 0.3120, 0, 65, 65, 65, 0, 0, 0, -360, 360],\n [24, 28, 0.3120, 0.3120, 0, 16, 16, 16, 0, 0, 0, -360, 360]\n ])\n\n ##----- OPF Data -----##\n ## area data\n # area refbus\n ppc[\"areas\"] = array([\n [1, 8],\n [2, 23],\n [3, 26],\n ])\n\n ## generator cost data\n # 1 startup shutdown n x1 y1 ... xn yn\n # 2 startup shutdown n c(n-1) ... c0\n ppc[\"gencost\"] = array([\n [0, 0, 0, 3, 0.0, 20, 0]\n ])\n\n return ppc" }, { "identifier": "micro_grid", "path": "TestCasesMicrogrids/test_cases/cases_unit_commitment.py", "snippet": "AC_PD = array([323.0284, 308.2374, 318.1886, 307.9809, 331.2170, 368.6539, 702.0040, 577.7045, 1180.4547, 1227.6240,\n 1282.9344, 1311.9738, 1268.9502, 1321.7436, 1323.9218, 1327.1464, 1386.9117, 1321.6387, 1132.0476,\n 1109.2701, 882.5698, 832.4520, 349.3568, 299.9920])\nDC_PD = array([287.7698, 287.7698, 287.7698, 287.7698, 299.9920, 349.3582, 774.4047, 664.0625, 1132.6996, 1107.7366,\n 1069.6837, 1068.9819, 1027.3295, 1096.3820, 1109.4778, 1110.7039, 1160.1270, 1078.7839, 852.2514,\n 791.5814, 575.4085, 551.1441, 349.3568, 299.992])\nDG = {\"PMIN\": 0,\n \"PMAX\": 5,\n \"QMIN\": -5,\n \"QMAX\": 5,\n \"COST_A\": 0.01,\n \"COST_B\": 0.5}\nUG = {\"PMIN\": -5,\n \"PMAX\": 5,\n \"QMIN\": -5,\n \"QMAX\": 5,\n \"COST\": Price_UG, } # The cost should be a profile\nESS = {\"PDC_MAX\": 5,\n \"PCH_MAX\": 5,\n \"EFF_DC\": 0.95,\n \"EFF_CH\": 0.95,\n \"E0\": 10,\n \"EMIN\": 5,\n \"EMAX\": 20, }\nBIC = {\"PMAX\": 5,\n \"QMAX\": 5,\n \"SMAX\": 5,\n \"EFF_AC2DC\": 0.9,\n \"EFF_DC2AC\": 0.9, }\nMG = {\"PMAX\": 5,\n \"PMIN\": -5,\n \"QMAX\": 5,\n \"QMIN\": -5\n }\nPD = {\"AC\": AC_PD / max(AC_PD),\n \"AC_MAX\": 5,\n \"DC\": DC_PD / max(DC_PD),\n \"DC_MAX\": 5}\nQD = {\"AC\": AC_PD / max(AC_PD),\n \"AC_MAX\": 5, }\nPV = {\"PMAX\": 0,\n \"COST\": 0}" }, { "identifier": "PBIC_AC2DC", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "PBIC_AC2DC = 4" }, { "identifier": "PG", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "PG = 0" }, { "identifier": "PESS_DC", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "PESS_DC = 8" }, { "identifier": "PBIC_DC2AC", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "PBIC_DC2AC = 5" }, { "identifier": "PUG", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "PUG = 2" }, { "identifier": "PESS_CH", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "PESS_CH = 7" }, { "identifier": "PMESS", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "PMESS = 10 # Reactive power unit commitment of" }, { "identifier": "EESS", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "EESS = 9" }, { "identifier": "NX_MG", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "NX_MG = 11" }, { "identifier": "QBIC", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "QBIC = 6" }, { "identifier": "QUG", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "QUG = 3" }, { "identifier": "QG", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "QG = 1" }, { "identifier": "DataBaseManagement", "path": "TestCaseDistributionSystems/database_management.py", "snippet": "class DataBaseManagement():\n\n def __init__(self, host=\"localhost\", user=\"root\", password=\"Ntu@1003\", db=\"mess\"):\n \"\"\"\n Initialized the database connection string\n :param host: host ip\n :param user: user name\n :param password: password\n :param db: database name\n :return\n \"\"\"\n self.db = pymysql.connect(host=host, user=user, password=password, db=db)\n\n def create_table(self, table_name, nl=32, nb=33, ng=6, nmg=3, nmes=3):\n \"\"\"\n Creat table name\n :param table_name:\n :param nb:\n :param nb:\n :param ng:\n :return: no return value\n \"\"\"\n cursor = self.db.cursor()\n sql = \"DROP TABLE IF EXISTS \"\n cursor.execute(sql + table_name)\n if table_name == \"distribution_networks\":\n sql_start = \"\"\"CREATE TABLE distribution_networks (\"\"\"\n sql = 'SCENARIO INT,\\n TIME INT NOT NULL,\\n '\n for i in range(nl):\n sql += \"PIJ{0} DECIMAL(8,6),\\n \".format(i)\n for i in range(nl):\n sql += \"QIJ{0} DECIMAL(8,6),\\n \".format(i)\n for i in range(nl):\n sql += \"IIJ{0} DECIMAL(8,6),\\n \".format(i)\n for i in range(nb):\n sql += \"V{0} DECIMAL(8,6),\\n \".format(i)\n for i in range(ng):\n sql += \"PG{0} DECIMAL(8,6),\\n \".format(i)\n for i in range(ng - 1):\n sql += \"QG{0} DECIMAL(8,6),\\n \".format(i)\n sql += \"QG{0} DECIMAL(8,6)\\n \".format(ng - 1)\n sql_end = \"\"\")\"\"\"\n elif table_name == \"micro_grids\":\n sql_start = \"\"\"CREATE TABLE micro_grids (\"\"\"\n sql = 'SCENARIO INT,\\n MG INT,\\n TIME INT,\\n '\n sql += 'PG DECIMAL(7,4),\\n QG DECIMAL(7,4),\\n PUG DECIMAL(7,4),\\n QUG DECIMAL(7,4),\\n '\n sql += 'PBIC_AC2DC DECIMAL(7,4),\\n PBIC_DC2AC DECIMAL(7,4),\\n QBIC DECIMAL(7,4),\\n PESS_CH DECIMAL(7,4),\\n '\n sql += 'PESS_DC DECIMAL(7,4),\\n EESS DECIMAL(7,4),\\n PMESS DECIMAL(7,4)'\n sql_end = \"\"\")\"\"\"\n elif table_name == \"mobile_energy_storage_systems\":\n sql_start = \"\"\"CREATE TABLE mobile_energy_storage_systems (\"\"\"\n sql = 'SCENARIO INT,\\n MESS INT,\\n TIME INT,\\n'\n for i in range(nmg):\n sql += \"PDC_MG{0} DECIMAL(7,4),\\n \".format(i)\n for i in range(nmg):\n sql += \"PCH_MG{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"EESS DECIMAL(7,4)\\n \"\n sql_end = \"\"\")\"\"\"\n elif table_name == \"first_stage_solutions\": # First-stage solution table\n sql_start = \"\"\"CREATE TABLE first_stage_solutions (\"\"\"\n sql = 'TIME INT,\\n'\n for i in range(ng):\n sql += \"PG{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"RG{0} DECIMAL(7,4),\\n \".format(i)\n for i in range(nmg - 1):\n sql += \"PG_MG{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"RG_MG{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"IESS{0} INT,\\n \".format(i)\n sql += \"PESS_DC{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"PESS_CH{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"RESS{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"ESS{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"PG_MG{0} DECIMAL(7,4),\\n \".format(nmg - 1)\n sql += \"RG_MG{0} DECIMAL(7,4),\\n \".format(nmg - 1)\n sql += \"IESS{0} INT,\\n \".format(nmg - 1)\n sql += \"PESS_DC{0} DECIMAL(7,4),\\n \".format(nmg - 1)\n sql += \"PESS_CH{0} DECIMAL(7,4),\\n \".format(nmg - 1)\n sql += \"RESS{0} DECIMAL(7,4),\\n \".format(nmg - 1)\n sql += \"ESS{0} DECIMAL(7,4)\\n \".format(nmg - 1)\n sql_end = \"\"\")\"\"\"\n elif table_name == \"fisrt_stage_mess\": # First-stage solution table\n sql_start = \"\"\"CREATE TABLE fisrt_stage_mess (\"\"\"\n sql = 'MESS INT,\\n TIME INT,\\n'\n for i in range(nmg):\n sql += \"IDC_MG{0} INT,\\n \".format(i)\n for i in range(nmg):\n sql += \"PDC_MG{0} DECIMAL(7,4),\\n \".format(i)\n for i in range(nmg):\n sql += \"PCH_MG{0} DECIMAL(7,4),\\n \".format(i)\n for i in range(nmg):\n sql += \"RMESS{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"MESS_F_STOP INT,\\n \"\n sql += \"MESS_T_STOP INT\\n \"\n sql_end = \"\"\")\"\"\"\n else:\n sql_start = \"\"\"CREATE TABLE scenarios (\"\"\"\n sql = 'SCENARIO INT,\\n WEIGHT DECIMAL(7,4),\\n TIME INT,\\n'\n for i in range(nb):\n sql += \"PD{0} DECIMAL(7,4),\\n \".format(i)\n for i in range(nmg):\n sql += \"PD_AC{0} DECIMAL(7,4),\\n \".format(i)\n for i in range(nmg - 1):\n sql += \"PD_DC{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"PD_DC{0} DECIMAL(7,4)\\n\".format(nmg - 1)\n sql_end = \"\"\")\"\"\"\n\n cursor.execute(sql_start + sql + sql_end)\n cursor.close()\n\n def insert_data_ds(self, table_name, nl=32, nb=33, ng=6, scenario=0, time=0, pij=0, qij=0, lij=0, vi=0, pg=0, qg=0):\n \"\"\"\n Insert data into table_name\n :param table_name:\n :param nl:\n :param nb:\n :param ng:\n :param pij:\n :param qij:\n :param lij:\n :param vi:\n :param pg:\n :param qg:\n :return:\n \"\"\"\n cursor = self.db.cursor()\n sql_start = \"INSERT INTO \" + table_name + \" (\"\n sql = \"SCENARIO,TIME,\"\n value = \"{0},{1},\".format(scenario, time)\n for i in range(nl):\n sql += \"PIJ{0},\".format(i)\n value += \"{0},\".format(pij[i])\n for i in range(nl):\n sql += \"QIJ{0},\".format(i)\n value += \"{0},\".format(qij[i])\n for i in range(nl):\n sql += \"IIJ{0},\".format(i)\n value += \"{0},\".format(lij[i])\n for i in range(nb):\n sql += \"V{0},\".format(i)\n value += \"{0},\".format(vi[i])\n for i in range(ng):\n sql += \"PG{0},\".format(i)\n value += \"{0},\".format(pg[i])\n for i in range(ng - 1):\n sql += \"QG{0},\".format(i)\n value += \"{0},\".format(qg[i])\n sql += \"QG{0}\".format(ng - 1)\n value += \"{0}\".format(qg[ng - 1])\n\n sql += \") VALUES (\" + value + \")\"\n\n cursor.execute(sql_start + sql)\n self.db.commit()\n cursor.close()\n\n def insert_data_mg(self, table_name, scenario=0, time=0, mg=0, pg=0, qg=0, pug=0, qug=0, pbic_ac2dc=0, pbic_dc2ac=0,\n qbic=0, pess_ch=0, pess_dc=0, eess=0, pmess=0):\n \"\"\"\n insert microgrid data\n :param table_name:\n :param scenario:\n :param time:\n :param mg:\n :param pg:\n :param qg:\n :param pug:\n :param qug:\n :param pbic_ac2dc:\n :param pbic_dc2ac:\n :param qbic:\n :param pess_ch:\n :param pess_dc:\n :param eess:\n :param pmess:\n :return:\n \"\"\"\n cursor = self.db.cursor()\n sql_start = \"INSERT INTO \" + table_name + \" (\"\n sql = \"SCENARIO,MG,TIME,\"\n value = \"{0},{1},{2},\".format(scenario, mg, time)\n sql += \"PG,QG,PUG,QUG,PBIC_AC2DC,PBIC_DC2AC,QBIC,PESS_CH,PESS_DC,EESS,PMESS\"\n value += \"{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}\".format(pg, qg, pug, qug, pbic_ac2dc, pbic_dc2ac, qbic,\n pess_ch, pess_dc, eess, pmess)\n sql += \") VALUES (\" + value + \")\"\n cursor.execute(sql_start + sql)\n self.db.commit()\n cursor.close()\n\n def insert_data_first_stage_mess(self, table_name, time=0, mess=0, imess=[0, 0, 0], pmess_ch=[0, 0, 0],\n pmess_dc=[0, 0, 0], rmess=[0, 0, 0], mess_f_stop=0, mess_t_stop=0, nmg=3):\n \"\"\"\n insert mobile energy storage systems data in the first-stage\n :param table_name:\n :param scenario:\n :param time:\n :param mess:\n :param pess_ch:\n :param pess_dc:\n :param eess:\n :param nmg:\n :return:\n \"\"\"\n cursor = self.db.cursor()\n sql_start = \"INSERT INTO \" + table_name + \" (\"\n sql = \"MESS,TIME,\"\n value = \"{0},{1},\".format(mess, time)\n for i in range(nmg):\n sql += \"IDC_MG{0},\".format(i)\n value += \"{0},\".format(imess[i])\n for i in range(nmg):\n sql += \"PDC_MG{0},\".format(i)\n value += \"{0},\".format(pmess_dc[i])\n for i in range(nmg):\n sql += \"PCH_MG{0},\".format(i)\n value += \"{0},\".format(pmess_ch[i])\n for i in range(nmg):\n sql += \"RMESS{0},\".format(i)\n value += \"{0},\".format(rmess[i])\n sql += \"MESS_F_STOP,MESS_T_STOP\"\n value += \"{0},{1}\".format(mess_f_stop, mess_t_stop)\n sql += \") VALUES (\" + value + \")\"\n cursor.execute(sql_start + sql)\n self.db.commit()\n cursor.close()\n\n def insert_data_mess(self, table_name, scenario=0, time=0, mess=0, pmess_ch=[0, 0, 0], pmess_dc=[0, 0, 0],\n emess=0, nmg=3):\n \"\"\"\n insert mobile energy storage systems data\n :param table_name:\n :param scenario:\n :param time:\n :param mess:\n :param pess_ch:\n :param pess_dc:\n :param eess:\n :param nmg:\n :return:\n \"\"\"\n cursor = self.db.cursor()\n sql_start = \"INSERT INTO \" + table_name + \" (\"\n sql = \"SCENARIO,MESS,TIME,\"\n value = \"{0},{1},{2},\".format(scenario, mess, time)\n for i in range(nmg):\n sql += \"PDC_MG{0},\".format(i)\n value += \"{0},\".format(pmess_dc[i])\n for i in range(nmg):\n sql += \"PCH_MG{0},\".format(i)\n value += \"{0},\".format(pmess_ch[i])\n sql += \"EESS\"\n value += \"{0}\".format(emess)\n sql += \") VALUES (\" + value + \")\"\n cursor.execute(sql_start + sql)\n self.db.commit()\n cursor.close()\n\n def insert_data_first_stage(self, table_name, time=0, ng=2, nmg=2, pg=[0, 0], rg=[0, 0], pg_mg=[0, 0],\n rg_mg=[0, 0], iess=[0, 0], pess_dc=[0, 0], pess_ch=[0, 0], ress=[0, 0], ess=[0, 0]):\n \"\"\"\n insert scenario data\n :param table_name:\n :param scenario:\n :param weight:\n :param time:\n :param nb:\n :param nmg:\n :param pd:\n :param pd_ac:\n :param pd_dc:\n :return:\n \"\"\"\n cursor = self.db.cursor()\n sql_start = \"INSERT INTO \" + table_name + \" (\"\n sql = \"TIME,\"\n value = \"{0},\".format(time)\n for i in range(ng):\n sql += \"PG{0},\".format(i)\n sql += \"RG{0},\".format(i)\n value += \"{0},\".format(pg[i])\n value += \"{0},\".format(rg[i])\n if nmg > 1:\n for i in range(nmg - 1):\n sql += \"PG_MG{0},\".format(i)\n sql += \"RG_MG{0},\".format(i)\n sql += \"IESS{0},\".format(i)\n sql += \"PESS_DC{0},\".format(i)\n sql += \"PESS_CH{0},\".format(i)\n sql += \"RESS{0},\".format(i)\n sql += \"ESS{0},\".format(i)\n value += \"{0},\".format(pg_mg[i])\n value += \"{0},\".format(rg_mg[i])\n value += \"{0},\".format(iess[i])\n value += \"{0},\".format(pess_dc[i])\n value += \"{0},\".format(pess_ch[i])\n value += \"{0},\".format(ress[i])\n value += \"{0},\".format(ess[i])\n sql += \"PG_MG{0},\".format(nmg - 1)\n sql += \"RG_MG{0},\".format(nmg - 1)\n sql += \"IESS{0},\".format(nmg - 1)\n sql += \"PESS_DC{0},\".format(nmg - 1)\n sql += \"PESS_CH{0},\".format(nmg - 1)\n sql += \"RESS{0},\".format(nmg - 1)\n sql += \"ESS{0}\".format(nmg - 1)\n value += \"{0},\".format(pg_mg[nmg - 1])\n value += \"{0},\".format(rg_mg[nmg - 1])\n value += \"{0},\".format(iess[nmg - 1])\n value += \"{0},\".format(pess_dc[nmg - 1])\n value += \"{0},\".format(pess_ch[nmg - 1])\n value += \"{0},\".format(ress[nmg - 1])\n value += \"{0}\".format(ess[nmg - 1])\n else:\n sql += \"PG_MG{0},\".format(nmg - 1)\n sql += \"RG_MG{0},\".format(nmg - 1)\n sql += \"IESS{0},\".format(nmg - 1)\n sql += \"PESS_DC{0},\".format(nmg - 1)\n sql += \"PESS_CH{0},\".format(nmg - 1)\n sql += \"RESS{0},\".format(nmg - 1)\n sql += \"ESS{0}\".format(nmg - 1)\n value += \"{0},\".format(pg_mg)\n value += \"{0},\".format(rg_mg)\n value += \"{0},\".format(iess)\n value += \"{0},\".format(pess_dc)\n value += \"{0},\".format(pess_ch)\n value += \"{0},\".format(ress)\n value += \"{0}\".format(ess)\n\n sql += \") VALUES (\" + value + \")\"\n cursor.execute(sql_start + sql)\n self.db.commit()\n cursor.close()\n\n def insert_data_scenario(self, table_name, scenario=0, weight=0, time=0, nb=1, nmg=2, pd=[0, 0], pd_ac=[0, 0],\n pd_dc=[0, 0]):\n cursor = self.db.cursor()\n sql_start = \"INSERT INTO \" + table_name + \" (\"\n sql = \"SCENARIO,WEIGHT,TIME,\"\n value = \"{0},{1},{2},\".format(scenario, weight, time)\n for i in range(nb):\n sql += \"PD{0},\".format(i)\n value += \"{0},\".format(pd[i])\n for i in range(nmg):\n sql += \"PD_AC{0},\".format(i)\n value += \"{0},\".format(pd_ac[i])\n for i in range(nmg - 1):\n sql += \"PD_DC{0},\".format(i)\n value += \"{0},\".format(pd_dc[i])\n if nmg > 1:\n sql += \"PD_DC{0}\".format(nmg - 1)\n value += \"{0}\".format(pd_dc[nmg - 1])\n\n sql += \") VALUES (\" + value + \")\"\n cursor.execute(sql_start + sql)\n self.db.commit()\n cursor.close()\n\n def inquery_data_scenario(self, table_name, scenario=0, time=0):\n cursor = self.db.cursor()\n # sql = \"SELECT * FROM \" + table_name + \" ;\"\n sql = \"SELECT * FROM \" + table_name + \" WHERE SCENARIO={0} AND TIME={1};\".format(scenario, time)\n cursor.execute(sql)\n data = cursor.fetchall()\n n_data = len(data[0])\n\n temp = []\n for i in range(n_data): temp.append(float(data[0][i]))\n\n cursor.close()\n return temp" }, { "identifier": "ScenarioReduction", "path": "StochasticOptimization/scenario_reduction.py", "snippet": "class ScenarioReduction():\n def __init__(self):\n self.name = \"Scenario reduction\"\n\n def run(self, scenario, weight, n_reduced, power):\n \"\"\"\n\n :param scenario: A fan scenario tree, when more stage are considered, some merge operation can be implemented\n :param weight: Weight of each scenario\n :param n_reduced: Number of scenarios needs to be reduced\n :param power: The power in the distance calculation\n :return:\n \"\"\"\n n_scenario = scenario.shape[0] # number of original scenarios\n c = zeros((n_scenario, n_scenario))\n # Calculate the c matrix\n for i in range(n_scenario):\n for j in range(n_scenario):\n c[i, j] = linalg.norm((scenario[i, :] - scenario[j, :]), 2)\n c[i, j] = max([1, linalg.norm(scenario[i, :], power - 1), linalg.norm(scenario[j, :], power - 1)]) * \\\n c[i, j]\n\n J = arange(n_scenario) # The original index range\n J_reduced = array([])\n # Implement the iteration\n for n in range(n_reduced): # find the minimal distance\n print(\"The reduction is in process {0}\".format(n))\n c_n = inf * ones(n_scenario)\n c_n[J] = 0\n for u in J:\n # Delete the i-th distance\n J_temp = delete(J, where(J == u))\n for k in J_temp:\n c_k_j = delete(c[int(k)], J_temp)\n c_n[int(u)] += weight[int(k)] * min(c_k_j)\n u_i = argmin(c_n)\n J_reduced = append(J_reduced, u_i)\n J = delete(J, where(J == u_i))\n # Optimal redistribution\n p_s = weight.copy()\n p_s[J_reduced.astype(int)] = 0\n\n for i in J_reduced:\n c_temp = c[int(i), :]\n c_temp[J_reduced.astype(int)] = inf\n index = argmin(c_temp)\n p_s[index] += weight[int(i)]\n\n scenario_reduced = scenario[J.astype(int), :]\n weight_reduced = p_s[J.astype(int)]\n\n return scenario_reduced, weight_reduced" } ]
from TestCaseDistributionSystems.test_cases import case33 from TestCasesMicrogrids.test_cases.cases_unit_commitment import micro_grid from TestCasesTransportationSystems.test_cases import case3, TIME, LOCATION from numpy import zeros, shape, ones, diag, concatenate, eye from scipy.sparse import csr_matrix as sparse from scipy.sparse import hstack, vstack, lil_matrix from numpy import flatnonzero as find from numpy import array, tile, arange, random from pypower.idx_brch import F_BUS, T_BUS, BR_R, BR_X, RATE_A from pypower.idx_bus import PD, VMAX, VMIN, QD from pypower.idx_gen import GEN_BUS, PMAX, PMIN, QMAX, QMIN from pypower.ext2int import ext2int from Solvers.mixed_integer_quadratic_constrained_cplex import mixed_integer_quadratic_constrained_programming as miqcp from Solvers.mixed_integer_solvers_cplex import mixed_integer_linear_programming as milp from copy import deepcopy from TestCaseDistributionSystems.data_format.idx_MG import PBIC_AC2DC, PG, PESS_DC, PBIC_DC2AC, PUG, PESS_CH, \ PMESS, EESS, NX_MG, QBIC, QUG, QG from TestCaseDistributionSystems.database_management import DataBaseManagement from StochasticOptimization.scenario_reduction import ScenarioReduction
15,826
beq = concatenate((beq, beq_temp)) nv_second_stage = nv_index_ev[-1] nv_first_stage = self.nv_first_stage self.nv_second_stage = nv_second_stage Qc = dict() # 4) Pij**2+Qij**2<=Vi*Iij for t in range(T): for i in range(nl): Qc[(T * nl + T * nmg) * index + t * nl + i] = [ [int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i + nl), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i + 2 * nl), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + f[i] + 3 * nl)], [int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i + nl), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + f[i] + 3 * nl), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i + 2 * nl)], [1, 1, -1 / 2, -1 / 2]] Rc = zeros(nl * T) # 5) (Pbic_ac2dc+Pbic_dc2ac)**2+Qbic**2<=Sbic**2 Rc_temp = zeros(nmg * T) for i in range(nmg): for t in range(T): Qc[(T * nl + T * nmg) * index + T * nl + T * i + t] = [ [int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_AC2DC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_DC2AC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_AC2DC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_DC2AC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + QBIC)], [int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_AC2DC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_DC2AC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_DC2AC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_AC2DC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + QBIC)], [1, 1, 1, 1, 1]] Rc_temp[i * T + t] = mgs[i]["BIC"]["SMAX"] ** 2 Rc = concatenate([Rc, Rc_temp]) ## IV. Coupling constraints between the first stage and second stage decision variables # pg, pg_mg, pess_mg, pess_tess # Ts*x+Ws*ys<=hs ## IV) Formulate the coupling constraints between the first-stage and second-stage problems # 1) -Pg -Rg + pg <= 0 _nv_first_stage = self._nv_first_stage Ts = lil_matrix((ng * T, nv_first_stage)) Ws = lil_matrix((ng * T, nv_second_stage)) hs = zeros(ng * T) for i in range(T): for j in range(ng): Ts[i * ng + j, i * _nv_first_stage + ng * 3 + j] = -1 Ts[i * ng + j, i * _nv_first_stage + ng * 4 + j] = -1 Ws[i * ng + j, i * _nv_second_stage + 3 * nl + nb + j] = 1 # 2) Pg-Rg - pg <= 0 Ts_temp = lil_matrix((ng * T, nv_first_stage)) Ws_temp = lil_matrix((ng * T, nv_second_stage)) hs_temp = zeros(ng * T) for i in range(T): for j in range(ng): Ts_temp[i * ng + j, i * _nv_first_stage + ng * 3 + j] = 1 Ts_temp[i * ng + j, i * _nv_first_stage + ng * 4 + j] = -1 Ws_temp[i * ng + j, i * _nv_second_stage + 3 * nl + nb + j] = -1 Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 3) Qg <= IgQg_max Ts_temp = lil_matrix((ng * T, nv_first_stage)) Ws_temp = lil_matrix((ng * T, nv_second_stage)) hs_temp = zeros(ng * T) for i in range(T): for j in range(ng): Ts_temp[i * ng + j, i * _nv_first_stage + ng * 2 + j] = -qg_u[j] Ws_temp[i * ng + j, i * _nv_second_stage + 3 * nl + nb + ng + j] = 1 Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 4) Qg >= IgQg_min Ts_temp = lil_matrix((ng * T, nv_first_stage)) Ws_temp = lil_matrix((ng * T, nv_second_stage)) hs_temp = zeros(ng * T) for i in range(T): for j in range(ng): Ts_temp[i * ng + j, i * _nv_first_stage + ng * 2 + j] = qg_l[j] Ws_temp[i * ng + j, i * _nv_second_stage + 3 * nl + nb + ng + j] = -1 Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 3) -Pg_mg - Rg_mg + pg_mg <= 0 Ts_temp = lil_matrix((nmg * T, nv_first_stage)) Ws_temp = lil_matrix((nmg * T, nv_second_stage)) hs_temp = zeros(nmg * T) for i in range(T): for j in range(nmg): Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + j] = -1 Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg + j] = -1 Ws_temp[i * nmg + j, nv_index[j] + i * NX_MG + PG] = 1 Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 4) Pg_mg - Rg_mg - pg_mg <= 0 Ts_temp = lil_matrix((nmg * T, nv_first_stage)) Ws_temp = lil_matrix((nmg * T, nv_second_stage)) hs_temp = zeros(nmg * T) for i in range(T): for j in range(nmg): Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + j] = 1 Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg + j] = -1 Ws_temp[i * nmg + j, nv_index[j] + i * NX_MG + PG] = -1 Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 5) pess_dc - pess_ch <= Pess_dc - Pess_ch + Ress Ts_temp = lil_matrix((nmg * T, nv_first_stage)) Ws_temp = lil_matrix((nmg * T, nv_second_stage)) hs_temp = zeros(nmg * T) for i in range(T): for j in range(nmg): Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg * 2 + j] = 1 # Charging Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg * 3 + j] = -1 # Dis-charging Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg * 4 + j] = -1 # Reserve Ws_temp[i * nmg + j, nv_index[j] + i * NX_MG + PESS_CH] = -1
""" Stochastic optimal power flow with multiple microgrids and mobile energy storage systems @author: Zhao Tianyang @e-mail: [email protected] @date: 10 Jan 2019 Major updates: 1) Update code style using PEP 8 -- Style Guide for Python Code 2) Store data in database 3) Scenario generation and reduction 4) Automatic results analysis Nomenclature: nV: number of variables mg: microgrid ds: distribution systems me: mobile energy storage systems ch: charging dc: discharging ele: electricity tra: traffic i,j,k: index t: time index T: time periods tns:traffic networks pns:power networks """ class StochasticDynamicOptimalPowerFlowTess(): def __init__(self): self.name = "Stochastic optimal power flow with tess" def main(self, power_networks, micro_grids, profile, mess, traffic_networks, ns=100): """ Main entrance for network reconfiguration problems :param case: electric network information :param profile: load profile within the distribution networks :param micrgrids: dictionary for microgrids :param tess: dictionary for tess :return: network reconfiguration, distribution network status, and microgrid status """ T = len(profile) # Time spans self.T = T nmg = len(micro_grids) # Number of microgrids self.nmg = nmg nmes = len(mess) # Number of mobile energy storage systems self.nmes = nmes nb_tra = traffic_networks["bus"].shape[0] # Number of buses in the transportation networks self.nb_tra = nb_tra assert nb_tra == nmg, "The microgrids within the transportation networks are not synchronized!" # 1) Formulate the first stage optimization problem model_first_stage = self.first_stage_problem_formualtion(pns=power_networks, mgs=micro_grids, mess=mess, tns=traffic_networks) # (sol_first_stage, obj, success) = milp(model_first_stage["c"], Aeq=model_first_stage["Aeq"], # beq=model_first_stage["beq"], # A=model_first_stage["A"], b=model_first_stage["b"], # vtypes=model_first_stage["vtypes"], # xmax=model_first_stage["ub"], xmin=model_first_stage["lb"]) # sol_first_stage = self.first_stage_solution_validation(sol=sol_first_stage) # 2) Formulate the second stage optimization problem # Formulate the second stage scenarios (ds_second_stage, mgs_second_stage, weight) = self.scenario_generation_reduction(profile=profile, micro_grids=micro_grids, ns=ns, pns=power_networks, ns_reduced=round(0.98 * ns)) ns -= round(0.98 * ns) model_second_stage = {} for i in range(ns): model_second_stage[i] = self.second_stage_problem_formualtion(pns=power_networks, mgs=mgs_second_stage[i], mess=mess, tns=traffic_networks, profile=ds_second_stage[i, :], index=i, weight=weight[i]) # 3) Merge the first-stage problem and second stage problem lb = model_first_stage["lb"] ub = model_first_stage["ub"] vtypes = model_first_stage["vtypes"] c = model_first_stage["c"] Qc = dict() if model_first_stage["Aeq"] is not None: neq = model_first_stage["Aeq"].shape[0] else: neq = 0 if model_first_stage["A"] is not None: nineq = model_first_stage["A"].shape[0] else: nineq = 0 nv_first_stage = self.nv_first_stage nv_second_stage = self.nv_second_stage q = zeros(nv_first_stage) nv_index = zeros(ns + 1).astype(int) neq_index = zeros(ns + 1).astype(int) nineq_index = zeros(ns + 1).astype(int) neq_index[0] = neq nineq_index[0] = nineq nv_index[0] = nv_first_stage beq = model_first_stage["beq"] for i in range(ns): if model_second_stage[i]["Aeq"] is not None: neq_index[i + 1] = neq_index[i] + model_second_stage[i]["Aeq"].shape[0] else: neq_index[i + 1] = neq_index[i] if model_second_stage[i]["Ts"] is not None: nineq_index[i + 1] = nineq_index[i] + model_second_stage[i]["Ts"].shape[0] else: nineq_index[i + 1] = nineq_index[i] nv_index[i + 1] = nv_index[i] + nv_second_stage c = concatenate([c, model_second_stage[i]["c"]]) q = concatenate([q, model_second_stage[i]["q"]]) lb = concatenate([lb, model_second_stage[i]["lb"]]) ub = concatenate([ub, model_second_stage[i]["ub"]]) vtypes += model_second_stage[i]["vtypes"] beq = concatenate([beq, model_second_stage[i]["beq"]]) Aeq_full = lil_matrix((neq_index[-1], nv_index[-1])) Aeq_full[0:neq_index[0], 0:nv_index[0]] = model_first_stage["Aeq"] rc = zeros(0) for i in range(ns): Aeq_full[neq_index[i]:neq_index[i + 1], nv_index[i]:nv_index[i + 1]] = model_second_stage[i]["Aeq"] Qc.update(model_second_stage[i]["Qc"]) rc = concatenate([rc, model_second_stage[i]["rc"]]) A_full = lil_matrix((nineq_index[-1], nv_index[-1])) b = model_first_stage["b"] A_full[0:int(nineq_index[0]), 0:int(nv_index[0])] = model_first_stage["A"] for i in range(ns): A_full[nineq_index[i]:nineq_index[i + 1], 0:nv_index[0]] = model_second_stage[i]["Ts"] A_full[nineq_index[i]:nineq_index[i + 1], nv_index[i]:nv_index[i + 1]] = model_second_stage[i]["Ws"] b = concatenate([b, model_second_stage[i]["hs"]]) # 3) Obtain the results for first-stage and second stage optimization problems # 3.1) Obtain the integrated solution (sol, obj, success) = miqcp(c, q, Aeq=Aeq_full, beq=beq, A=A_full, b=b, Qc=Qc, rc=rc, xmin=lb, xmax=ub, vtypes=vtypes) # 3.2) decouple the solution into multiple subsystems sol_first_stage = sol[0:nv_second_stage] sol_second_stage = {} for i in range(ns): sol_second_stage[i] = sol[int(nv_index[i]):int(nv_index[i + 1])] # 4) Verify the first-stage and second stage optization problem # 4.1) First-stage solution sol_first_stage = self.first_stage_solution_validation(sol=sol_first_stage) # 4.2) Second-stage solution sol_second_stage_checked = {} db_management = DataBaseManagement() db_management.create_table(table_name="distribution_networks", nl=self.nl, nb=self.nb, ng=self.ng) db_management.create_table(table_name="micro_grids", nmg=self.nmg) db_management.create_table(table_name="mobile_energy_storage_systems", nmg=self.nmg) db_management.create_table(table_name="first_stage_solutions", nmg=self.nmg, ng=self.ng, nmes=self.nmes) db_management.create_table(table_name="fisrt_stage_mess", nmg=self.nmg) for t in range(T): db_management.insert_data_first_stage(table_name="first_stage_solutions", time=t, ng=self.ng, nmg=self.nmg, pg=sol_first_stage["pg"][:, t].tolist(), rg=sol_first_stage["rg"][:, t].tolist(), pg_mg=sol_first_stage["pg_mg"][:, t].tolist(), rg_mg=sol_first_stage["rg_mg"][:, t].tolist(), pess_ch=sol_first_stage["pess_ch"][:, t].tolist(), pess_dc=sol_first_stage["pess_dc"][:, t].tolist(), ress=sol_first_stage["ress"][:, t].tolist(), ess=sol_first_stage["eess"][:, t].tolist(), iess=sol_first_stage["iess"][:, t].tolist()) for i in range(nmes): for t in range(T): db_management.insert_data_first_stage_mess(table_name="fisrt_stage_mess", nmg=self.nmg, time=t, mess=i, imess=sol_first_stage["MESS"][i]["idc"][:, t].tolist(), rmess=sol_first_stage["MESS"][i]["rmess"][:, t].tolist(), pmess_ch= sol_first_stage["MESS"][i]["pmess_ch"][:, t].tolist(), pmess_dc= sol_first_stage["MESS"][i]["pmess_dc"][:, t].tolist(), mess_f_stop=sol_first_stage["MESS"][i]["VRP"][t + 1][0], mess_t_stop=sol_first_stage["MESS"][i]["VRP"][t + 1][1]) for i in range(ns): sol_second_stage_checked[i] = self.second_stage_solution_validation(sol_second_stage[i]) for i in range(ns): for t in range(T): db_management.insert_data_ds(table_name="distribution_networks", nl=self.nl, nb=self.nb, ng=self.ng, scenario=i, time=t, pij=sol_second_stage_checked[i]["DS"]["pij"][:, t].tolist(), qij=sol_second_stage_checked[i]["DS"]["qij"][:, t].tolist(), lij=sol_second_stage_checked[i]["DS"]["lij"][:, t].tolist(), vi=sol_second_stage_checked[i]["DS"]["vi"][:, t].tolist(), pg=sol_second_stage_checked[i]["DS"]["pg"][:, t].tolist(), qg=sol_second_stage_checked[i]["DS"]["qg"][:, t].tolist(), ) for i in range(ns): for j in range(nmg): for t in range(T): db_management.insert_data_mg(table_name="micro_grids", scenario=i, time=t, mg=j, pg=sol_second_stage_checked[i]["MG"]["pg"][j, t], qg=sol_second_stage_checked[i]["MG"]["qg"][j, t], pug=sol_second_stage_checked[i]["MG"]["pug"][j, t], qug=sol_second_stage_checked[i]["MG"]["qug"][j, t], pbic_ac2dc=sol_second_stage_checked[i]["MG"]["pbic_ac2dc"][j, t], pbic_dc2ac=sol_second_stage_checked[i]["MG"]["pbic_dc2ac"][j, t], qbic=sol_second_stage_checked[i]["MG"]["qbic"][j, t], pess_ch=sol_second_stage_checked[i]["MG"]["pess_ch"][j, t], pess_dc=sol_second_stage_checked[i]["MG"]["pess_dc"][j, t], eess=sol_second_stage_checked[i]["MG"]["eess"][j, t], pmess=sol_second_stage_checked[i]["MG"]["pmess"][j, t]) for i in range(ns): for j in range(nmes): for t in range(T): db_management.insert_data_mess(table_name="mobile_energy_storage_systems", scenario=i, time=t, mess=j, nmg=self.nmg, pmess_dc= sol_second_stage_checked[i]["MESS"][j]["pmess_dc"][:, t].tolist(), pmess_ch= sol_second_stage_checked[i]["MESS"][j]["pmess_ch"][:, t].tolist(), emess=sol_second_stage_checked[i]["MESS"][j]["emess"][0, t]) # 4.3) Cross validation of the first-stage and second-stage decision variables tess_check = {} for i in range(ns): tess_temp = {} for j in range(nmes): tess_temp[j] = sol_second_stage_checked[i]["MESS"][j]["pmess_dc"] - \ sol_second_stage_checked[i]["MESS"][j]["pmess_ch"] - \ sol_first_stage["MESS"][j]["pmess_dc"] + \ sol_first_stage["MESS"][j]["pmess_ch"] - \ sol_first_stage["MESS"][j]["rmess"] tess_temp[j + nmes] = sol_second_stage_checked[i]["MESS"][j]["pmess_ch"] - \ sol_second_stage_checked[i]["MESS"][j]["pmess_dc"] - \ sol_first_stage["MESS"][j]["pmess_ch"] + \ sol_first_stage["MESS"][j]["pmess_dc"] - \ sol_first_stage["MESS"][j]["rmess"] tess_check[i] = tess_temp # return sol_distribution_network, sol_microgrids, sol_tess return sol_first_stage, sol_second_stage_checked def first_stage_problem_formualtion(self, pns, mgs, mess, tns): """ Problem formulation for the first stage optimization, Decision variables include, DGs within power networks, DGs within MGs, EESs within MGs and TESSs :param power_networks: Parameters for the power networks :param micro_grids: Parameters for the microgrids :param tess: Parameters for the mobile energy storage systems :param traffic_networks: Parameters for the transportation networks :return: Formulated first-stage problem """ T = self.T # Time slots nmg = self.nmg # Number of mgs nmes = self.nmes # Number of tess mpc = ext2int(pns) baseMVA, bus, gen, branch, gencost = mpc["baseMVA"], mpc["bus"], mpc["gen"], mpc["branch"], mpc["gencost"] ng = shape(mpc['gen'])[0] ## number of dispatchable injections nb = shape(mpc["bus"])[0] self.nb = nb self.ng = ng # Obtain the initial status, start-up and shut down of generators Ig0 = gen[:, -1].astype(int) MIN_DOWN = gen[:, -2].astype(int) MIN_UP = gen[:, -3].astype(int) alpha_l = zeros(ng) beta_l = zeros(ng) Ig_l = zeros(ng) pg_l = zeros(ng) # Boundary for DGs within distribution networks rg_l = zeros(ng) alpha_u = ones(ng) beta_u = ones(ng) Ig_u = ones(ng) pg_u = gen[:, PMAX] / baseMVA rg_u = gen[:, PMAX] / baseMVA c_alpha = gencost[:, 0] c_beta = gencost[:, 1] c_ig = gencost[:, 6] cg = gencost[:, 5] * baseMVA cr = zeros(ng) pg_mg_l = zeros(nmg) # Boundary for DGs within MGs rg_mg_l = zeros(nmg) pg_mg_u = zeros(nmg) rg_mg_u = zeros(nmg) cg_mg = zeros(nmg) cr_mg = zeros(nmg) for i in range(nmg): pg_mg_l[i] = mgs[i]["DG"]["PMIN"] pg_mg_u[i] = mgs[i]["DG"]["PMAX"] rg_mg_u[i] = mgs[i]["DG"]["PMAX"] cg_mg[i] = mgs[i]["DG"]["COST_B"] pes_ch_l = zeros(nmg) # Lower boundary for ESSs within MGs pes_dc_l = zeros(nmg) ees_l = zeros(nmg) res_l = zeros(nmg) ies_l = zeros(nmg) pes_ch_u = zeros(nmg) # Upper boundary for ESSs within MGs pes_dc_u = zeros(nmg) ees_u = zeros(nmg) res_u = zeros(nmg) ies_u = ones(nmg) ces_ch = zeros(nmg) # Cost boundary for ESSs within MGs ces_dc = zeros(nmg) ces_r = zeros(nmg) ces = zeros(nmg) ces_i = zeros(nmg) for i in range(nmg): pes_ch_u[i] = mgs[i]["ESS"]["PCH_MAX"] pes_dc_u[i] = mgs[i]["ESS"]["PDC_MAX"] + mgs[i]["ESS"]["PCH_MAX"] res_u[i] = mgs[i]["ESS"]["PCH_MAX"] ees_l[i] = mgs[i]["ESS"]["EMIN"] ees_u[i] = mgs[i]["ESS"]["EMAX"] _nv_first_stage = ng * 5 + nmg * 2 + nmg * 5 nv_first_stage = _nv_first_stage * T # Formulate the boundaries lb = concatenate( [tile(concatenate( [alpha_l, beta_l, Ig_l, pg_l, rg_l, pg_mg_l, rg_mg_l, pes_ch_l, pes_dc_l, res_l, ees_l, ies_l]), T)]) ub = concatenate( [tile(concatenate( [alpha_u, beta_u, Ig_u, pg_u, rg_u, pg_mg_u, rg_mg_u, pes_ch_u, pes_dc_u, res_u, ees_u, ies_u]), T)]) # Objective value c = concatenate( [tile(concatenate([c_alpha, c_beta, c_ig, cg, cr, cg_mg, cr_mg, ces_ch, ces_dc, ces, ces_r, ces_i]), T)]) # Variable types vtypes = (["b"] * ng * 3 + ["c"] * (ng * 2 + nmg * 2 + nmg * 4) + ["b"] * nmg) * T ## Constraint sets # 1) Pg+Rg<=PguIg A = lil_matrix((ng * T, nv_first_stage)) b = zeros(ng * T) for t in range(T): for j in range(ng): A[t * ng + j, t * _nv_first_stage + ng * 3 + j] = 1 A[t * ng + j, t * _nv_first_stage + ng * 4 + j] = 1 A[t * ng + j, t * _nv_first_stage + ng * 2 + j] = -pg_u[j] # 2) Pg-Rg>=IgPgl A_temp = lil_matrix((ng * T, nv_first_stage)) b_temp = zeros(ng * T) for t in range(T): for j in range(ng): A_temp[t * ng + j, t * _nv_first_stage + ng * 3 + j] = -1 A_temp[t * ng + j, t * _nv_first_stage + ng * 4 + j] = 1 A_temp[t * ng + j, t * _nv_first_stage + j] = pg_l[j] A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # 3) Start-up and shut-down constraints of DGs UP_LIMIT = zeros(ng).astype(int) DOWN_LIMIT = zeros(ng).astype(int) for i in range(ng): UP_LIMIT[i] = T - MIN_UP[i] DOWN_LIMIT[i] = T - MIN_DOWN[i] # 3.1) Up limit A_temp = lil_matrix((sum(UP_LIMIT), nv_first_stage)) b_temp = zeros(sum(UP_LIMIT)) for i in range(ng): for t in range(MIN_UP[i], T): for k in range(t - MIN_UP[i], t): A_temp[sum(UP_LIMIT[0:i]) + t - MIN_UP[i], k * _nv_first_stage + i] = 1 A_temp[sum(UP_LIMIT[0:i]) + t - MIN_UP[i], t * _nv_first_stage + ng * 2 + i] = -1 A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # # 3.2) Down limit A_temp = lil_matrix((sum(DOWN_LIMIT), nv_first_stage)) b_temp = ones(sum(DOWN_LIMIT)) for i in range(ng): for t in range(MIN_DOWN[i], T): for k in range(t - MIN_DOWN[i], t): A_temp[sum(DOWN_LIMIT[0:i]) + t - MIN_DOWN[i], k * _nv_first_stage + ng + i] = 1 A_temp[sum(DOWN_LIMIT[0:i]) + t - MIN_DOWN[i], t * _nv_first_stage + ng * 2 + i] = 1 A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # 4) Status transformation of each unit Aeq = lil_matrix((T * ng, nv_first_stage)) beq = zeros(T * ng) for i in range(ng): for t in range(T): Aeq[i * T + t, t * _nv_first_stage + i] = 1 Aeq[i * T + t, t * _nv_first_stage + ng + i] = -1 Aeq[i * T + t, t * _nv_first_stage + ng * 2 + i] = -1 if t != 0: Aeq[i * T + t, (t - 1) * _nv_first_stage + ng * 2 + i] = 1 else: beq[i * T + t] = -Ig0[i] # 3) Pg_mg+Rg_mg<=Pg_mg_u A_temp = lil_matrix((nmg * T, nv_first_stage)) b_temp = zeros(nmg * T) for t in range(T): for j in range(nmg): A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + j] = 1 A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg + j] = 1 b_temp[t * nmg + j] = pg_mg_u[j] A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # 4) Pg_mg-Rg_mg<=Pg_mg_l A_temp = lil_matrix((nmg * T, nv_first_stage)) b_temp = zeros(nmg * T) for t in range(T): for j in range(nmg): A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + j] = -1 A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg + j] = 1 b_temp[t * nmg + j] = pg_mg_l[j] A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # 5) Pess_dc-Pess_ch+Ress<=Pess_dc_max A_temp = lil_matrix((nmg * T, nv_first_stage)) b_temp = zeros(nmg * T) for t in range(T): for j in range(nmg): A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + j] = -1 A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + nmg + j] = 1 A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + nmg * 2 + j] = 1 b_temp[t * nmg + j] = pes_dc_u[j] A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # 6) Pess_ch-Pess_dc+Ress<=Pess_ch_max A_temp = lil_matrix((nmg * T, nv_first_stage)) b_temp = zeros(nmg * T) for t in range(T): for j in range(nmg): A_temp[t * nmg + j, ng * 5 + nmg * 2 + t] = 1 A_temp[t * nmg + j, ng * 5 + nmg * 2 + nmg + t] = -1 A_temp[t * nmg + j, ng * 5 + nmg * 2 + nmg * 2 + t] = 1 b_temp[t * nmg + j] = pes_ch_u[j] A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # 7) Energy storage balance equation Aeq_temp = lil_matrix((T * nmg, nv_first_stage)) beq_temp = zeros(T * nmg) for t in range(T): for j in range(nmg): Aeq_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + nmg * 3 + j] = 1 Aeq_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + j] = -mgs[j]["ESS"]["EFF_CH"] Aeq_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + nmg + j] = 1 / mgs[j]["ESS"]["EFF_DC"] if t == 0: beq_temp[i * nmg + j] = mgs[j]["ESS"]["E0"] else: Aeq_temp[i * nmg + j, (i - 1) * _nv_first_stage + ng * 5 + nmg * 2 + nmg * 3 + j] = -1 Aeq = vstack([Aeq, Aeq_temp]) beq = concatenate([beq, beq_temp]) # 8) Pess_ch<=I*Pess_ch_max A_temp = lil_matrix((nmg * T, nv_first_stage)) b_temp = zeros(nmg * T) for t in range(T): for j in range(nmg): A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + j] = 1 A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + nmg * 4 + j] = -pes_ch_u[j] A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # 9) Pess_dc<=(1-I)*Pess_dc_max A_temp = lil_matrix((nmg * T, nv_first_stage)) b_temp = zeros(nmg * T) for t in range(T): for j in range(nmg): A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + nmg + j] = 1 A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + nmg * 4 + j] = pes_dc_u[j] b_temp[t * nmg + j] = pes_dc_u[j] A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # 2) Transportation energy storage systems problem model_mess = {} for i in range(nmes): model_mess[i] = self.problem_formulation_tess(mess=mess[i], tns=tns) # 3) Merge the DGs, ESSs and TESSs neq = Aeq.shape[0] nineq = A.shape[0] nV_index = zeros(nmes + 1).astype(int) neq_index = zeros(nmes + 1).astype(int) nineq_index = zeros(nmes + 1).astype(int) nV_index[0] = nv_first_stage neq_index[0] = neq nineq_index[0] = nineq for i in range(nmes): nV_index[i + 1] = nV_index[i] + len(model_mess[i]["c"]) neq_index[i + 1] = neq_index[i] + model_mess[i]["Aeq"].shape[0] nineq_index[i + 1] = nineq_index[i] + model_mess[i]["A"].shape[0] neq += model_mess[i]["Aeq"].shape[0] nineq += model_mess[i]["A"].shape[0] # Merge the objective function, boundaries, types and rhs c = concatenate([c, model_mess[i]["c"]]) lb = concatenate([lb, model_mess[i]["lb"]]) ub = concatenate([ub, model_mess[i]["ub"]]) vtypes += model_mess[i]["vtypes"] beq = concatenate([beq, model_mess[i]["beq"]]) b = concatenate([b, model_mess[i]["b"]]) A_full = lil_matrix((nineq_index[-1], nV_index[-1])) Aeq_full = lil_matrix((neq_index[-1], nV_index[-1])) if Aeq is not None: Aeq_full[0:int(neq_index[0]), 0:int(nV_index[0])] = Aeq if A is not None: A_full[0:int(nineq_index[0]), 0:int(nV_index[0])] = A for i in range(nmes): Aeq_full[neq_index[i]:neq_index[i + 1], nV_index[i]:nV_index[i + 1]] = model_mess[i]["Aeq"] A_full[nineq_index[i]:nineq_index[i + 1], nV_index[i]:nV_index[i + 1]] = model_mess[i]["A"] self.nv_first_stage = nV_index[-1] # The number of first stage decision variables self._nv_first_stage = _nv_first_stage model_first_stage = {"c": c, "lb": lb, "ub": ub, "vtypes": vtypes, "A": A_full, "b": b, "Aeq": Aeq_full, "beq": beq, } return model_first_stage def first_stage_solution_validation(self, sol): """ Validation of the first-stage solution :param sol: The first stage solution :return: the first stage solution """ T = self.T ng = self.ng nmg = self.nmg nmes = self.nmes # Set-points of DGs within DSs, MGs and ESSs _nv_first_stage = self._nv_first_stage alpha = zeros((ng, T)) beta = zeros((ng, T)) Ig = zeros((ng, T)) Pg = zeros((ng, T)) Rg = zeros((ng, T)) Pg_mg = zeros((nmg, T)) Rg_mg = zeros((nmg, T)) Pess_dc = zeros((nmg, T)) Pess_ch = zeros((nmg, T)) Ress = zeros((nmg, T)) Eess = zeros((nmg, T)) Iess = zeros((nmg, T)) for i in range(T): alpha[:, i] = sol[_nv_first_stage * i:_nv_first_stage * i + ng] beta[:, i] = sol[_nv_first_stage * i + ng:_nv_first_stage * i + ng * 2] Ig[:, i] = sol[_nv_first_stage * i + ng * 2:_nv_first_stage * i + ng * 3] Pg[:, i] = sol[_nv_first_stage * i + ng * 3:_nv_first_stage * i + ng * 4] Rg[:, i] = sol[_nv_first_stage * i + ng * 4:_nv_first_stage * i + ng * 5] Pg_mg[:, i] = sol[_nv_first_stage * i + ng * 5:_nv_first_stage * i + ng * 5 + nmg] Rg_mg[:, i] = sol[_nv_first_stage * i + ng * 5 + nmg:_nv_first_stage * i + ng * 5 + nmg * 2] Pess_ch[:, i] = sol[_nv_first_stage * i + ng * 5 + nmg * 2:_nv_first_stage * i + ng * 5 + nmg * 3] Pess_dc[:, i] = sol[_nv_first_stage * i + ng * 5 + nmg * 3:_nv_first_stage * i + ng * 5 + nmg * 4] Ress[:, i] = sol[_nv_first_stage * i + ng * 5 + nmg * 4:_nv_first_stage * i + ng * 5 + nmg * 5] Eess[:, i] = sol[_nv_first_stage * i + ng * 5 + nmg * 5:_nv_first_stage * i + ng * 5 + nmg * 6] Iess[:, i] = sol[_nv_first_stage * i + ng * 5 + nmg * 6:_nv_first_stage * i + ng * 5 + nmg * 7] # Set-points and scheduling of mobile energy storage systems nv_tra = self.nv_tra nl_traffic = self.nl_tra n_stops = self.n_stops nb_tra_ele = self.nb_tra_ele sol_ev = {} for i in range(nmes): ev_temp = {} ev_temp["VRP"] = [] for t in range(nl_traffic): if sol[_nv_first_stage * T + nv_tra * i + t] > 0: # obtain the solution for vrp if self.connection_matrix[t, TIME] > 0: for j in range(int(self.connection_matrix[t, TIME])): ev_temp["VRP"].append(((self.connection_matrix[t, F_BUS] - 1) % nmg, (self.connection_matrix[t, T_BUS] - 1) % nmg)) else: ev_temp["VRP"].append(((self.connection_matrix[t, F_BUS] - 1) % nmg, (self.connection_matrix[t, T_BUS] - 1) % nmg)) ev_temp["idc"] = zeros((nb_tra_ele, T)) ev_temp["pmess_dc"] = zeros((nb_tra_ele, T)) ev_temp["pmess_ch"] = zeros((nb_tra_ele, T)) ev_temp["rmess"] = zeros((nb_tra_ele, T)) for t in range(T): for k in range(nb_tra_ele): ev_temp["idc"][k, t] = sol[_nv_first_stage * T + nv_tra * i + nl_traffic + nb_tra_ele * t + k] ev_temp["pmess_dc"][k, t] = \ sol[_nv_first_stage * T + nv_tra * i + nl_traffic + n_stops + nb_tra_ele * t + k] ev_temp["pmess_ch"][k, t] = \ sol[_nv_first_stage * T + nv_tra * i + nl_traffic + n_stops * 2 + nb_tra_ele * t + k] ev_temp["rmess"][k, t] = \ sol[_nv_first_stage * T + nv_tra * i + nl_traffic + n_stops * 3 + nb_tra_ele * t + k] sol_ev[i] = ev_temp sol_first_stage = {"alpha": alpha, "beta": beta, "ig": Ig, "rg": Rg, "pg": Pg, "pg_mg": Pg_mg, "rg_mg": Rg_mg, "pess_ch": Pess_ch, "pess_dc": Pess_dc, "ress": Ress, "eess": Eess, "iess": Iess, "MESS": sol_ev, } return sol_first_stage def second_stage_problem_formualtion(self, pns, mgs, mess, tns, profile, index=0, weight=1): """ Second-stage problem formulation, the decision variables includes DGs within power networks, DGs within MGs, EESs within MGs and TESSs and other systems' information :param power_networks: :param micro_grids: :param tess: :param traffic_networks: :return: The second stage problems as list, including coupling constraints, and other constraint set """ # I) Formulate the problem for distribution systems operator T = self.T mpc = ext2int(pns) baseMVA, bus, gen, branch, gencost = mpc["baseMVA"], mpc["bus"], mpc["gen"], mpc["branch"], mpc["gencost"] nb = shape(mpc['bus'])[0] ## number of buses nl = shape(mpc['branch'])[0] ## number of branches ng = shape(mpc['gen'])[0] ## number of dispatchable injections nmg = self.nmg nmes = self.nmes self.nl = nl self.nb = nb self.ng = ng m = zeros(nmg) ## list of integration index pmg_l = zeros(nmg) ## list of lower boundary pmg_u = zeros(nmg) ## list of upper boundary qmg_l = zeros(nmg) ## list of lower boundary qmg_u = zeros(nmg) ## list of upper boundary for i in range(nmg): m[i] = mgs[i]["BUS"] pmg_l[i] = mgs[i]["UG"]["PMIN"] / 1000 / baseMVA pmg_u[i] = mgs[i]["UG"]["PMAX"] / 1000 / baseMVA qmg_l[i] = mgs[i]["UG"]["QMIN"] / 1000 / baseMVA qmg_u[i] = mgs[i]["UG"]["QMAX"] / 1000 / baseMVA f = branch[:, F_BUS] ## list of "from" buses t = branch[:, T_BUS] ## list of "to" buses i = range(nl) ## double set of row indices self.f = f ## record from bus for each branch # Connection matrix Cf = sparse((ones(nl), (i, f)), (nl, nb)) Ct = sparse((ones(nl), (i, t)), (nl, nb)) Cg = sparse((ones(ng), (gen[:, GEN_BUS], range(ng))), (nb, ng)) Cmg = sparse((ones(nmg), (m, range(nmg))), (nb, nmg)) Branch_R = branch[:, BR_R] Branch_X = branch[:, BR_X] Cf = Cf.T Ct = Ct.T # Obtain the boundary information slmax = branch[:, RATE_A] / baseMVA pij_l = -slmax qij_l = -slmax lij_l = zeros(nl) vm_l = bus[:, VMIN] ** 2 pg_l = gen[:, PMIN] / baseMVA qg_l = gen[:, QMIN] / baseMVA pij_u = slmax qij_u = slmax lij_u = slmax vm_u = bus[:, VMAX] ** 2 pg_u = 2 * gen[:, PMAX] / baseMVA qg_u = 2 * gen[:, QMAX] / baseMVA _nv_second_stage = int(3 * nl + nb + 2 * ng + 2 * nmg) self._nv_second_stage = _nv_second_stage # Number of decision variable within each time slot lb = concatenate([tile(concatenate([pij_l, qij_l, lij_l, vm_l, pg_l, qg_l, pmg_l, qmg_l]), T)]) ub = concatenate([tile(concatenate([pij_u, qij_u, lij_u, vm_u, pg_u, qg_u, pmg_u, qmg_u]), T)]) vtypes = ["c"] * _nv_second_stage * T nv_ds = _nv_second_stage * T # Number of total decision variables # Add system level constraints # 1) Active power balance Aeq_p = lil_matrix((nb * T, nv_ds)) beq_p = zeros(nb * T) for i in range(T): Aeq_p[i * nb:(i + 1) * nb, i * _nv_second_stage: (i + 1) * _nv_second_stage] = \ hstack([Ct - Cf, zeros((nb, nl)), -diag(Ct * Branch_R) * Ct, zeros((nb, nb)), Cg, zeros((nb, ng)), -Cmg, zeros((nb, nmg))]) beq_p[i * nb:(i + 1) * nb] = profile[i * nb:(i + 1) * nb] / baseMVA # 2) Reactive power balance Aeq_q = lil_matrix((nb * T, nv_ds)) beq_q = zeros(nb * T) for i in range(T): Aeq_q[i * nb:(i + 1) * nb, i * _nv_second_stage: (i + 1) * _nv_second_stage] = \ hstack([zeros((nb, nl)), Ct - Cf, -diag(Ct * Branch_X) * Ct, zeros((nb, nb)), zeros((nb, ng)), Cg, zeros((nb, nmg)), -Cmg]) for j in range(nb): if bus[j, PD] > 0: beq_q[i * nb:(i + 1) * nb] = profile[i * nb + j] / bus[j, PD] * bus[j, QD] / baseMVA # 3) KVL equation Aeq_kvl = lil_matrix((nl * T, nv_ds)) beq_kvl = zeros(nl * T) for i in range(T): Aeq_kvl[i * nl:(i + 1) * nl, i * _nv_second_stage: i * _nv_second_stage + nl] = -2 * diag(Branch_R) Aeq_kvl[i * nl:(i + 1) * nl, i * _nv_second_stage + nl: i * _nv_second_stage + 2 * nl] = -2 * diag(Branch_X) Aeq_kvl[i * nl:(i + 1) * nl, i * _nv_second_stage + 2 * nl: i * _nv_second_stage + 3 * nl] = diag( Branch_R ** 2) + diag(Branch_X ** 2) Aeq_kvl[i * nl:(i + 1) * nl, i * _nv_second_stage + 3 * nl:i * _nv_second_stage + 3 * nl + nb] = ( Cf.T - Ct.T).toarray() Aeq = vstack([Aeq_p, Aeq_q, Aeq_kvl]) beq = concatenate([beq_p, beq_q, beq_kvl]) c = zeros(nv_ds) q = zeros(nv_ds) c0 = 0 for t in range(T): for i in range(ng): c[t * _nv_second_stage + i + 3 * nl + nb] = gencost[i, 5] * baseMVA q[t * _nv_second_stage + i + 3 * nl + nb] = gencost[i, 4] * baseMVA * baseMVA c0 += gencost[i, 6] # Coupling constraints between the distribution systems and micro_grids Ax2y = lil_matrix((2 * nmg * T, nv_ds)) # connection matrix with the microgrids for i in range(T): for j in range(nmg): # Active power Ax2y[i * nmg + j, i * _nv_second_stage + 3 * nl + nb + 2 * ng + j] = 1000 * baseMVA # Reactive power Ax2y[nmg * T + i * nmg + j, i * _nv_second_stage + 3 * nl + nb + 2 * ng + nmg + j] = 1000 * baseMVA # II) Formulate the problem for microgrids model_microgrids = {} for i in range(nmg): model_microgrids[i] = self.problem_formulation_microgrid(mg=mgs[i], mess=mess) # II.A) Combine the distribution system operation problem and microgrid systems if Aeq is not None: neq_ds = Aeq.shape[0] else: neq_ds = 0 nVariables = int(nv_ds) neq = int(neq_ds) nv_index = zeros(nmg + 1).astype(int) neq_index = zeros(nmg + 1).astype(int) nv_index[0] = nv_ds neq_index[0] = int(neq_ds) for i in range(nmg): nv_index[i + 1] = nv_index[i] + len(model_microgrids[i]["c"]) neq_index[i + 1] = neq_index[i] + model_microgrids[i]["Aeq"].shape[0] nVariables += len(model_microgrids[i]["c"]) neq += int(model_microgrids[i]["Aeq"].shape[0]) Aeq_full = lil_matrix((int(neq_index[-1]), int(nv_index[-1]))) Aeq_full[0:neq_ds, 0:nv_ds] = Aeq for i in range(nmg): lb = concatenate([lb, model_microgrids[i]["lb"]]) ub = concatenate([ub, model_microgrids[i]["ub"]]) c = concatenate([c, model_microgrids[i]["c"]]) q = concatenate([q, model_microgrids[i]["q"]]) vtypes += model_microgrids[i]["vtypes"] beq = concatenate([beq, model_microgrids[i]["beq"]]) Aeq_full[neq_index[i]:neq_index[i + 1], nv_index[i]:nv_index[i + 1]] = model_microgrids[i]["Aeq"] # Add coupling constraints, between the microgrids and distribution networks Ay2x = lil_matrix((2 * nmg * T, nv_index[-1] - nv_index[0])) for i in range(T): for j in range(nmg): Ay2x[i * nmg + j, int(nv_index[j] - nv_index[0]) + i * NX_MG + PUG] = -1 Ay2x[nmg * T + i * nmg + j, int(nv_index[j] - nv_index[0]) + i * NX_MG + QUG] = -1 Aeq_temp = hstack([Ax2y, Ay2x]) beq_temp = zeros(2 * nmg * T) Aeq_full = vstack([Aeq_full, Aeq_temp]) beq = concatenate([beq, beq_temp]) # III) Formulate the optimization problem for tess in the second stage optimization model_tess = {} for i in range(nmes): model_tess[i] = self.problem_formulation_tess_second_stage(mess=mess[i]) # III.1) Merge the models of mirogrids and distribution # Formulate the index nv_index_ev = zeros(1 + nmes).astype(int) neq_index_temp = zeros(1 + nmes).astype(int) nv_index_ev[0] = int(Aeq_full.shape[1]) neq_index_temp[0] = int(Aeq_full.shape[0]) for i in range(nmes): nv_index_ev[i + 1] = nv_index_ev[i] + len(model_tess[i]["c"]) neq_index_temp[i + 1] = neq_index_temp[i] + model_tess[i]["Aeq"].shape[0] Aeq = lil_matrix((int(neq_index_temp[-1]), int(nv_index_ev[-1]))) Aeq[0:int(neq_index_temp[0]), 0:int(nv_index_ev[0])] = Aeq_full for i in range(nmes): lb = concatenate([lb, model_tess[i]["lb"]]) ub = concatenate([ub, model_tess[i]["ub"]]) c = concatenate([c, model_tess[i]["c"]]) q = concatenate([q, model_tess[i]["q"]]) vtypes += model_tess[i]["vtypes"] beq = concatenate([beq, model_tess[i]["beq"]]) Aeq[neq_index_temp[i]:neq_index_temp[i + 1], nv_index_ev[i]:nv_index_ev[i + 1]] = model_tess[i]["Aeq"] # III.2) Coupling constraints between the microgrids and mobile energy storage systems # Additional equal constraints, nmg*T Aeq_temp = lil_matrix((nmg * T, nv_index_ev[-1])) beq_temp = zeros(nmg * T) for i in range(nmg): for t in range(T): Aeq_temp[i * T + t, nv_index[i] + t * NX_MG + PMESS] = 1 # TESSs injections to the MGs for j in range(nmes): Aeq_temp[i * T + t, nv_index_ev[j] + t * self.nb_tra_ele + i] = -1 # Discharging Aeq_temp[i * T + t, nv_index_ev[j] + self.nb_tra_ele * T + t * self.nb_tra_ele + i] = 1 # Sort by order Aeq = vstack([Aeq, Aeq_temp]) beq = concatenate((beq, beq_temp)) nv_second_stage = nv_index_ev[-1] nv_first_stage = self.nv_first_stage self.nv_second_stage = nv_second_stage Qc = dict() # 4) Pij**2+Qij**2<=Vi*Iij for t in range(T): for i in range(nl): Qc[(T * nl + T * nmg) * index + t * nl + i] = [ [int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i + nl), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i + 2 * nl), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + f[i] + 3 * nl)], [int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i + nl), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + f[i] + 3 * nl), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i + 2 * nl)], [1, 1, -1 / 2, -1 / 2]] Rc = zeros(nl * T) # 5) (Pbic_ac2dc+Pbic_dc2ac)**2+Qbic**2<=Sbic**2 Rc_temp = zeros(nmg * T) for i in range(nmg): for t in range(T): Qc[(T * nl + T * nmg) * index + T * nl + T * i + t] = [ [int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_AC2DC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_DC2AC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_AC2DC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_DC2AC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + QBIC)], [int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_AC2DC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_DC2AC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_DC2AC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_AC2DC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + QBIC)], [1, 1, 1, 1, 1]] Rc_temp[i * T + t] = mgs[i]["BIC"]["SMAX"] ** 2 Rc = concatenate([Rc, Rc_temp]) ## IV. Coupling constraints between the first stage and second stage decision variables # pg, pg_mg, pess_mg, pess_tess # Ts*x+Ws*ys<=hs ## IV) Formulate the coupling constraints between the first-stage and second-stage problems # 1) -Pg -Rg + pg <= 0 _nv_first_stage = self._nv_first_stage Ts = lil_matrix((ng * T, nv_first_stage)) Ws = lil_matrix((ng * T, nv_second_stage)) hs = zeros(ng * T) for i in range(T): for j in range(ng): Ts[i * ng + j, i * _nv_first_stage + ng * 3 + j] = -1 Ts[i * ng + j, i * _nv_first_stage + ng * 4 + j] = -1 Ws[i * ng + j, i * _nv_second_stage + 3 * nl + nb + j] = 1 # 2) Pg-Rg - pg <= 0 Ts_temp = lil_matrix((ng * T, nv_first_stage)) Ws_temp = lil_matrix((ng * T, nv_second_stage)) hs_temp = zeros(ng * T) for i in range(T): for j in range(ng): Ts_temp[i * ng + j, i * _nv_first_stage + ng * 3 + j] = 1 Ts_temp[i * ng + j, i * _nv_first_stage + ng * 4 + j] = -1 Ws_temp[i * ng + j, i * _nv_second_stage + 3 * nl + nb + j] = -1 Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 3) Qg <= IgQg_max Ts_temp = lil_matrix((ng * T, nv_first_stage)) Ws_temp = lil_matrix((ng * T, nv_second_stage)) hs_temp = zeros(ng * T) for i in range(T): for j in range(ng): Ts_temp[i * ng + j, i * _nv_first_stage + ng * 2 + j] = -qg_u[j] Ws_temp[i * ng + j, i * _nv_second_stage + 3 * nl + nb + ng + j] = 1 Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 4) Qg >= IgQg_min Ts_temp = lil_matrix((ng * T, nv_first_stage)) Ws_temp = lil_matrix((ng * T, nv_second_stage)) hs_temp = zeros(ng * T) for i in range(T): for j in range(ng): Ts_temp[i * ng + j, i * _nv_first_stage + ng * 2 + j] = qg_l[j] Ws_temp[i * ng + j, i * _nv_second_stage + 3 * nl + nb + ng + j] = -1 Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 3) -Pg_mg - Rg_mg + pg_mg <= 0 Ts_temp = lil_matrix((nmg * T, nv_first_stage)) Ws_temp = lil_matrix((nmg * T, nv_second_stage)) hs_temp = zeros(nmg * T) for i in range(T): for j in range(nmg): Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + j] = -1 Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg + j] = -1 Ws_temp[i * nmg + j, nv_index[j] + i * NX_MG + PG] = 1 Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 4) Pg_mg - Rg_mg - pg_mg <= 0 Ts_temp = lil_matrix((nmg * T, nv_first_stage)) Ws_temp = lil_matrix((nmg * T, nv_second_stage)) hs_temp = zeros(nmg * T) for i in range(T): for j in range(nmg): Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + j] = 1 Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg + j] = -1 Ws_temp[i * nmg + j, nv_index[j] + i * NX_MG + PG] = -1 Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 5) pess_dc - pess_ch <= Pess_dc - Pess_ch + Ress Ts_temp = lil_matrix((nmg * T, nv_first_stage)) Ws_temp = lil_matrix((nmg * T, nv_second_stage)) hs_temp = zeros(nmg * T) for i in range(T): for j in range(nmg): Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg * 2 + j] = 1 # Charging Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg * 3 + j] = -1 # Dis-charging Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg * 4 + j] = -1 # Reserve Ws_temp[i * nmg + j, nv_index[j] + i * NX_MG + PESS_CH] = -1
Ws_temp[i * nmg + j, nv_index[j] + i * NX_MG + PESS_DC] = 1
4
2023-11-27 15:57:53+00:00
24k
girgle/DouZero_For_New_HLDDZ
main.py
[ { "identifier": "GameHelper", "path": "GameHelper.py", "snippet": "class GameHelper:\n def __init__(self):\n self.ScreenZoomRate = None\n self.counter = QTime()\n self.Pics = {}\n self.PicsCV = {}\n st = time.time()\n self.Handle = win32gui.FindWindow(\"UnityWndClass\", None)\n self.Interrupt = False\n self.RealRate = (1440, 810)\n self.GetZoomRate()\n for file in os.listdir(\"./pics\"):\n info = file.split(\".\")\n if info[1] == \"png\":\n tmpImage = Image.open(\"./pics/\" + file)\n imgCv = cv2.imread(\"./pics/\" + file)\n self.Pics.update({info[0]: tmpImage})\n self.PicsCV.update({info[0]: imgCv})\n\n def sleep(self, ms):\n self.counter.restart()\n while self.counter.elapsed() < ms:\n QtWidgets.QApplication.processEvents(QEventLoop.AllEvents, 50)\n\n def Screenshot(self, region=None): # -> (im, (left, top))\n try_count = 3\n success = False\n while try_count > 0 and not success:\n try:\n try_count -= 1\n self.Handle = win32gui.FindWindow(\"UnityWndClass\", None)\n hwnd = self.Handle\n left, top, right, bot = win32gui.GetWindowRect(hwnd)\n width = right - left\n height = bot - top\n self.RealRate = (width, height)\n width = int(width)\n height = int(height)\n hwndDC = win32gui.GetWindowDC(hwnd)\n mfcDC = win32ui.CreateDCFromHandle(hwndDC)\n saveDC = mfcDC.CreateCompatibleDC()\n saveBitMap = win32ui.CreateBitmap()\n saveBitMap.CreateCompatibleBitmap(mfcDC, width, height)\n saveDC.SelectObject(saveBitMap)\n result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 3)\n bmpinfo = saveBitMap.GetInfo()\n bmpstr = saveBitMap.GetBitmapBits(True)\n im = Image.frombuffer(\n \"RGB\",\n (bmpinfo['bmWidth'], bmpinfo['bmHeight']),\n bmpstr, 'raw', 'BGRX', 0, 1)\n win32gui.DeleteObject(saveBitMap.GetHandle())\n saveDC.DeleteDC()\n mfcDC.DeleteDC()\n win32gui.ReleaseDC(hwnd, hwndDC)\n im = im.resize((1440, 810))\n if region is not None:\n im = im.crop((region[0], region[1], region[0] + region[2], region[1] + region[3]))\n if result:\n success = True\n return im, (left, top)\n except Exception as e:\n print(\"截图时出现错误:\", repr(e))\n self.sleep(200)\n return None, (0, 0)\n\n def GetZoomRate(self):\n self.ScreenZoomRate = ctypes.windll.shcore.GetScaleFactorForDevice(0) / 100\n\n def LocateOnScreen(self, templateName, region, confidence=0.8, img=None):\n if img is not None:\n image = img\n else:\n image, _ = self.Screenshot()\n imgcv = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)\n return LocateOnImage(imgcv, self.PicsCV[templateName], region=region, confidence=confidence)\n\n def ClickOnImage(self, templateName, region=None, confidence=0.8, img=None):\n if img is not None:\n image = img\n else:\n image, _ = self.Screenshot()\n imgcv = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)\n result = LocateOnImage(imgcv, self.PicsCV[templateName], region=region, confidence=confidence)\n\n if result is not None:\n self.LeftClick(result)\n print(result)\n\n def LeftClick(self, pos):\n x, y = pos\n x = (x / 1440) * self.RealRate[0]\n y = (y / 810) * self.RealRate[1]\n x = int(x)\n y = int(y)\n self.Handle = win32gui.FindWindow(\"UnityWndClass\", None)\n left, top, _, _ = win32gui.GetWindowRect(self.Handle)\n x, y = int(left + x), int(top + y)\n\n pyautogui.mouseDown(x, y, button='left')\n time.sleep(0.1)\n pyautogui.mouseUp(x, y, button='left')\n time.sleep(0.1)\n pyautogui.moveTo(int(left + 1000), int(top + 550))\n\n '''win32gui.SetActiveWindow(self.Handle)\n lParam = win32api.MAKELONG(x, y)\n\n win32gui.PostMessage(self.Handle, WM_ACTIVATE, WA_ACTIVE, lParam)\n win32gui.PostMessage(self.Handle, WM_ACTIVATE, WA_ACTIVE, lParam)\n win32gui.PostMessage(self.Handle, WM_MOUSEMOVE, MK_LBUTTON, lParam)\n win32gui.PostMessage(self.Handle, WM_LBUTTONDOWN, MK_LBUTTON, lParam)\n win32gui.PostMessage(self.Handle, WM_LBUTTONUP, MK_LBUTTON, lParam)'''\n\n def LeftClick2(self, pos):\n x, y = pos\n x = (x / 1440) * self.RealRate[0]\n y = (y / 810) * self.RealRate[1]\n x = int(x)\n y = int(y)\n self.Handle = win32gui.FindWindow(\"UnityWndClass\", None)\n left, top, _, _ = win32gui.GetWindowRect(self.Handle)\n x, y = int(left + x), int(top + y)\n\n pyautogui.mouseDown(x, y, button='left')\n time.sleep(0.1)\n pyautogui.mouseUp(x, y, button='left')" }, { "identifier": "get_move_type", "path": "douzero/env/move_detector.py", "snippet": "def get_move_type(move):\n move_size = len(move)\n move_dict = collections.Counter(move)\n\n if move_size == 0:\n return {'type': TYPE_0_PASS}\n\n if move_size == 1:\n return {'type': TYPE_1_SINGLE, 'rank': move[0]}\n\n if move_size == 2:\n if move[0] == move[1]:\n return {'type': TYPE_2_PAIR, 'rank': move[0]}\n elif move == [20, 30]: # Kings\n return {'type': TYPE_5_KING_BOMB}\n else:\n return {'type': TYPE_15_WRONG}\n\n if move_size == 3:\n if len(move_dict) == 1:\n return {'type': TYPE_3_TRIPLE, 'rank': move[0]}\n else:\n return {'type': TYPE_15_WRONG}\n\n if move_size == 4:\n if len(move_dict) == 1:\n return {'type': TYPE_4_BOMB, 'rank': move[0]}\n elif len(move_dict) == 2:\n if move[0] == move[1] == move[2] or move[1] == move[2] == move[3]:\n return {'type': TYPE_6_3_1, 'rank': move[1]}\n else:\n return {'type': TYPE_15_WRONG}\n else:\n return {'type': TYPE_15_WRONG}\n\n if is_continuous_seq(move):\n return {'type': TYPE_8_SERIAL_SINGLE, 'rank': move[0], 'len': len(move)}\n\n if move_size == 5:\n if len(move_dict) == 2:\n return {'type': TYPE_7_3_2, 'rank': move[2]}\n else:\n return {'type': TYPE_15_WRONG}\n\n count_dict = collections.defaultdict(int)\n for c, n in move_dict.items():\n count_dict[n] += 1\n\n if move_size == 6:\n if (len(move_dict) == 2 or len(move_dict) == 3) and count_dict.get(4) == 1 and \\\n (count_dict.get(2) == 1 or count_dict.get(1) == 2):\n return {'type': TYPE_13_4_2, 'rank': move[2]}\n\n if move_size == 8 and (((len(move_dict) == 3 or len(move_dict) == 2) and\n (count_dict.get(4) == 1 and count_dict.get(2) == 2)) or count_dict.get(4) == 2):\n return {'type': TYPE_14_4_22, 'rank': max([c for c, n in move_dict.items() if n == 4])}\n\n mdkeys = sorted(move_dict.keys())\n if len(move_dict) == count_dict.get(2) and is_continuous_seq(mdkeys):\n return {'type': TYPE_9_SERIAL_PAIR, 'rank': mdkeys[0], 'len': len(mdkeys)}\n\n if len(move_dict) == count_dict.get(3) and is_continuous_seq(mdkeys):\n return {'type': TYPE_10_SERIAL_TRIPLE, 'rank': mdkeys[0], 'len': len(mdkeys)}\n\n # Check Type 11 (serial 3+1) and Type 12 (serial 3+2)\n if count_dict.get(3, 0) >= MIN_TRIPLES:\n serial_3 = list()\n single = list()\n pair = list()\n\n for k, v in move_dict.items():\n if v == 3:\n serial_3.append(k)\n elif v == 1:\n single.append(k)\n elif v == 2:\n pair.append(k)\n else: # no other possibilities\n return {'type': TYPE_15_WRONG}\n\n serial_3.sort()\n if is_continuous_seq(serial_3):\n if len(serial_3) == len(single)+len(pair)*2:\n return {'type': TYPE_11_SERIAL_3_1, 'rank': serial_3[0], 'len': len(serial_3)}\n if len(serial_3) == len(pair) and len(move_dict) == len(serial_3) * 2:\n return {'type': TYPE_12_SERIAL_3_2, 'rank': serial_3[0], 'len': len(serial_3)}\n\n if len(serial_3) == 4:\n if is_continuous_seq(serial_3[1:]):\n return {'type': TYPE_11_SERIAL_3_1, 'rank': serial_3[1], 'len': len(serial_3) - 1}\n if is_continuous_seq(serial_3[:-1]):\n return {'type': TYPE_11_SERIAL_3_1, 'rank': serial_3[0], 'len': len(serial_3) - 1}\n\n return {'type': TYPE_15_WRONG}" }, { "identifier": "Ui_Form", "path": "MainWindow.py", "snippet": "class Ui_Form(object):\n def setupUi(self, Form):\n Form.setObjectName(\"Form\")\n Form.resize(677, 450)\n font = QtGui.QFont()\n font.setFamily(\"Arial\")\n font.setPointSize(9)\n font.setBold(True)\n font.setItalic(False)\n font.setWeight(75)\n Form.setFont(font)\n Form.setWindowOpacity(0.8)\n self.WinRate = QtWidgets.QLabel(Form)\n self.WinRate.setGeometry(QtCore.QRect(320, 120, 121, 51))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.WinRate.setFont(font)\n self.WinRate.setAlignment(QtCore.Qt.AlignCenter)\n self.WinRate.setObjectName(\"WinRate\")\n self.UserHandCards = QtWidgets.QLabel(Form)\n self.UserHandCards.setGeometry(QtCore.QRect(30, 330, 351, 31))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.UserHandCards.setFont(font)\n self.UserHandCards.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)\n self.UserHandCards.setObjectName(\"UserHandCards\")\n self.ThreeLandlordCards = QtWidgets.QLabel(Form)\n self.ThreeLandlordCards.setGeometry(QtCore.QRect(30, 120, 121, 51))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.ThreeLandlordCards.setFont(font)\n self.ThreeLandlordCards.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)\n self.ThreeLandlordCards.setObjectName(\"ThreeLandlordCards\")\n self.BidWinrate = QtWidgets.QLabel(Form)\n self.BidWinrate.setGeometry(QtCore.QRect(30, 220, 161, 31))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.BidWinrate.setFont(font)\n self.BidWinrate.setObjectName(\"BidWinrate\")\n self.PreWinrate = QtWidgets.QLabel(Form)\n self.PreWinrate.setGeometry(QtCore.QRect(30, 280, 161, 31))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.PreWinrate.setFont(font)\n self.PreWinrate.setObjectName(\"PreWinrate\")\n self.label = QtWidgets.QLabel(Form)\n self.label.setGeometry(QtCore.QRect(490, 320, 101, 41))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.label.setFont(font)\n self.label.setAlignment(QtCore.Qt.AlignCenter)\n self.label.setObjectName(\"label\")\n self.LPlayedCard = QtWidgets.QLabel(Form)\n self.LPlayedCard.setGeometry(QtCore.QRect(170, 120, 102, 51))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.LPlayedCard.setFont(font)\n self.LPlayedCard.setAlignment(QtCore.Qt.AlignCenter)\n self.LPlayedCard.setObjectName(\"LPlayedCard\")\n self.splitter_2 = QtWidgets.QSplitter(Form)\n self.splitter_2.setGeometry(QtCore.QRect(20, 380, 621, 41))\n self.splitter_2.setOrientation(QtCore.Qt.Horizontal)\n self.splitter_2.setObjectName(\"splitter_2\")\n self.SingleButton = QtWidgets.QPushButton(self.splitter_2)\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.SingleButton.setFont(font)\n self.SingleButton.setObjectName(\"SingleButton\")\n self.LoopButton = QtWidgets.QPushButton(self.splitter_2)\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.LoopButton.setFont(font)\n self.LoopButton.setObjectName(\"LoopButton\")\n self.StopButton = QtWidgets.QPushButton(self.splitter_2)\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.StopButton.setFont(font)\n self.StopButton.setObjectName(\"StopButton\")\n self.tableWidget = QtWidgets.QTableWidget(Form)\n self.tableWidget.setGeometry(QtCore.QRect(20, 10, 611, 75))\n self.tableWidget.setMaximumSize(QtCore.QSize(16777215, 75))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(12)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.tableWidget.setFont(font)\n self.tableWidget.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.tableWidget.setStyleSheet(\"QTableWidget{\\n\"\n\"color:#DCDCDC;\\n\"\n\"background:#444444;\\n\"\n\"border:1px solid #242424;\\n\"\n\"alternate-background-color:#525252;\\n\"\n\"gridline-color:#242424;\\n\"\n\"}\\n\"\n\" \\n\"\n\"QTableWidget::item:selected{\\n\"\n\"color:#DCDCDC;\\n\"\n\"background:qlineargradient(spread:pad,x1:0,y1:0,x2:0,y2:1,stop:0 #484848,stop:1 #383838);\\n\"\n\"}\\n\"\n\" \\n\"\n\"QTableWidget::item:hover{\\n\"\n\"background:#5B5B5B;\\n\"\n\"}\\n\"\n\"QHeaderView::section{\\n\"\n\"text-align:center;\\n\"\n\"background:#5E5E5E;\\n\"\n\"padding:3px;\\n\"\n\"margin:0px;\\n\"\n\"color:#DCDCDC;\\n\"\n\"border:1px solid #242424;\\n\"\n\"border-left-width:0;\\n\"\n\"}\\n\"\n\" \\n\"\n\"QScrollBar:vertical{\\n\"\n\"background:#484848;\\n\"\n\"padding:0px;\\n\"\n\"border-radius:6px;\\n\"\n\"max-width:12px;\\n\"\n\"}\\n\"\n\" \\n\"\n\" \\n\"\n\"QScrollBar::handle:vertical{\\n\"\n\"background:#CCCCCC;\\n\"\n\"}\\n\"\n\" \\n\"\n\"QScrollBar::handle:hover:vertical,QScrollBar::handle:pressed:vertical{\\n\"\n\"background:#A7A7A7;\\n\"\n\"}\\n\"\n\"QScrollBar::sub-page:vertical{\\n\"\n\"background:444444;\\n\"\n\"}\\n\"\n\" \\n\"\n\" \\n\"\n\"QScrollBar::add-page:vertical{\\n\"\n\"background:5B5B5B;\\n\"\n\"}\\n\"\n\" \\n\"\n\"QScrollBar::add-line:vertical{\\n\"\n\"background:none;\\n\"\n\"}\\n\"\n\"QScrollBar::sub-line:vertical{\\n\"\n\"background:none;\\n\"\n\"}\")\n self.tableWidget.setFrameShadow(QtWidgets.QFrame.Sunken)\n self.tableWidget.setMidLineWidth(-1)\n self.tableWidget.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n self.tableWidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n self.tableWidget.setAutoScroll(False)\n self.tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)\n self.tableWidget.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)\n self.tableWidget.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)\n self.tableWidget.setTextElideMode(QtCore.Qt.ElideNone)\n self.tableWidget.setObjectName(\"tableWidget\")\n self.tableWidget.setColumnCount(15)\n self.tableWidget.setRowCount(1)\n item = QtWidgets.QTableWidgetItem()\n self.tableWidget.setVerticalHeaderItem(0, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(0, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(1, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(2, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(3, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(4, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(5, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(6, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(7, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(8, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(9, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(10, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(11, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(12, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(13, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(14, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 0, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 1, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 2, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 3, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 4, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 5, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 6, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 7, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 8, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 9, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 10, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 11, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 12, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 13, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 14, item)\n self.tableWidget.horizontalHeader().setVisible(True)\n self.tableWidget.horizontalHeader().setCascadingSectionResizes(True)\n self.tableWidget.horizontalHeader().setDefaultSectionSize(41)\n self.tableWidget.horizontalHeader().setStretchLastSection(True)\n self.tableWidget.verticalHeader().setVisible(False)\n self.tableWidget.verticalHeader().setCascadingSectionResizes(False)\n self.tableWidget.verticalHeader().setDefaultSectionSize(40)\n self.tableWidget.verticalHeader().setHighlightSections(True)\n self.tableWidget.verticalHeader().setMinimumSectionSize(40)\n self.tableWidget.verticalHeader().setSortIndicatorShown(False)\n self.RPlayedCard = QtWidgets.QLabel(Form)\n self.RPlayedCard.setGeometry(QtCore.QRect(490, 120, 102, 51))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.RPlayedCard.setFont(font)\n self.RPlayedCard.setAlignment(QtCore.Qt.AlignCenter)\n self.RPlayedCard.setObjectName(\"RPlayedCard\")\n self.PredictedCard = QtWidgets.QLabel(Form)\n self.PredictedCard.setGeometry(QtCore.QRect(320, 190, 121, 51))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.PredictedCard.setFont(font)\n self.PredictedCard.setStyleSheet(\"\")\n self.PredictedCard.setFrameShape(QtWidgets.QFrame.Panel)\n self.PredictedCard.setLineWidth(1)\n self.PredictedCard.setAlignment(QtCore.Qt.AlignCenter)\n self.PredictedCard.setObjectName(\"PredictedCard\")\n\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n\n def retranslateUi(self, Form):\n _translate = QtCore.QCoreApplication.translate\n Form.setWindowTitle(_translate(\"Form\", \"Hi\"))\n self.WinRate.setText(_translate(\"Form\", \"评分\"))\n self.UserHandCards.setText(_translate(\"Form\", \"手牌\"))\n self.ThreeLandlordCards.setText(_translate(\"Form\", \"地主牌\"))\n self.BidWinrate.setText(_translate(\"Form\", \"叫牌胜率:\"))\n self.PreWinrate.setText(_translate(\"Form\", \"局前胜率:\"))\n self.label.setText(_translate(\"Form\", \"游戏状态\"))\n self.LPlayedCard.setText(_translate(\"Form\", \"上家出牌区域\"))\n self.SingleButton.setText(_translate(\"Form\", \"单局\"))\n self.LoopButton.setText(_translate(\"Form\", \" 连续\"))\n self.StopButton.setText(_translate(\"Form\", \"停止\"))\n item = self.tableWidget.horizontalHeaderItem(0)\n item.setText(_translate(\"Form\", \"大\"))\n item = self.tableWidget.horizontalHeaderItem(1)\n item.setText(_translate(\"Form\", \"小\"))\n item = self.tableWidget.horizontalHeaderItem(2)\n item.setText(_translate(\"Form\", \"2\"))\n item = self.tableWidget.horizontalHeaderItem(3)\n item.setText(_translate(\"Form\", \"A\"))\n item = self.tableWidget.horizontalHeaderItem(4)\n item.setText(_translate(\"Form\", \"K\"))\n item = self.tableWidget.horizontalHeaderItem(5)\n item.setText(_translate(\"Form\", \"Q\"))\n item = self.tableWidget.horizontalHeaderItem(6)\n item.setText(_translate(\"Form\", \"J\"))\n item = self.tableWidget.horizontalHeaderItem(7)\n item.setText(_translate(\"Form\", \"10\"))\n item = self.tableWidget.horizontalHeaderItem(8)\n item.setText(_translate(\"Form\", \"9\"))\n item = self.tableWidget.horizontalHeaderItem(9)\n item.setText(_translate(\"Form\", \"8\"))\n item = self.tableWidget.horizontalHeaderItem(10)\n item.setText(_translate(\"Form\", \"7\"))\n item = self.tableWidget.horizontalHeaderItem(11)\n item.setText(_translate(\"Form\", \"6\"))\n item = self.tableWidget.horizontalHeaderItem(12)\n item.setText(_translate(\"Form\", \"5\"))\n item = self.tableWidget.horizontalHeaderItem(13)\n item.setText(_translate(\"Form\", \"4\"))\n item = self.tableWidget.horizontalHeaderItem(14)\n item.setText(_translate(\"Form\", \"3\"))\n __sortingEnabled = self.tableWidget.isSortingEnabled()\n self.tableWidget.setSortingEnabled(False)\n item = self.tableWidget.item(0, 0)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 1)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 2)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 3)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 4)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 5)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 6)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 7)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 8)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 9)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 10)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 11)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 12)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 13)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 14)\n item.setText(_translate(\"Form\", \"0\"))\n self.tableWidget.setSortingEnabled(__sortingEnabled)\n self.RPlayedCard.setText(_translate(\"Form\", \"下家出牌区域\"))\n self.PredictedCard.setText(_translate(\"Form\", \"AI出牌区域\"))" }, { "identifier": "GameEnv", "path": "douzero/env/game.py", "snippet": "class GameEnv(object):\n\n def __init__(self, players):\n\n self.card_play_action_seq = []\n\n self.three_landlord_cards = None\n self.game_over = False\n\n self.acting_player_position = None\n self.player_utility_dict = None\n\n self.players = players\n\n self.last_move_dict = {'landlord': [],\n 'landlord_up': [],\n 'landlord_down': []}\n\n self.played_cards = {'landlord': [],\n 'landlord_up': [],\n 'landlord_down': []}\n\n self.last_move = []\n self.last_two_moves = []\n\n self.num_wins = {'landlord': 0,\n 'farmer': 0}\n\n self.num_scores = {'landlord': 0,\n 'farmer': 0}\n\n self.info_sets = {'landlord': InfoSet('landlord'),\n 'landlord_up': InfoSet('landlord_up'),\n 'landlord_down': InfoSet('landlord_down')}\n\n self.bomb_num = 0\n self.last_pid = 'landlord'\n\n self.bid_info = [[1, 1, 1],\n [1, 1, 1],\n [1, 1, 1],\n [1, 1, 1]]\n self.bid_count = 0\n self.multiply_count = {'landlord': 1,\n 'landlord_up': 1,\n 'landlord_down': 1}\n self.step_count = 0\n\n\n def card_play_init(self, card_play_data):\n self.info_sets['landlord'].player_hand_cards = \\\n card_play_data['landlord']\n self.info_sets['landlord_up'].player_hand_cards = \\\n card_play_data['landlord_up']\n self.info_sets['landlord_down'].player_hand_cards = \\\n card_play_data['landlord_down']\n self.three_landlord_cards = card_play_data['three_landlord_cards']\n self.get_acting_player_position()\n self.game_infoset = self.get_infoset()\n\n\n def game_done(self):\n if len(self.info_sets['landlord'].player_hand_cards) == 0 or \\\n len(self.info_sets['landlord_up'].player_hand_cards) == 0 or \\\n len(self.info_sets['landlord_down'].player_hand_cards) == 0:\n # if one of the three players discards his hand,\n # then game is over.\n self.compute_player_utility()\n self.update_num_wins_scores()\n\n self.game_over = True\n\n def compute_player_utility(self):\n\n if len(self.info_sets['landlord'].player_hand_cards) == 0:\n self.player_utility_dict = {'landlord': 2,\n 'farmer': -1}\n else:\n self.player_utility_dict = {'landlord': -2,\n 'farmer': 1}\n\n def update_num_wins_scores(self):\n for pos, utility in self.player_utility_dict.items():\n base_score = 2 if pos == 'landlord' else 1\n if utility > 0:\n self.num_wins[pos] += 1\n self.winner = pos\n self.num_scores[pos] += base_score * (2 ** self.bomb_num)\n else:\n self.num_scores[pos] -= base_score * (2 ** self.bomb_num)\n\n def get_winner(self):\n return self.winner\n\n def get_bomb_num(self):\n return self.bomb_num\n\n def step(self, position, action=[]):\n win_rate = 0\n if self.acting_player_position == position:\n action, actions_confidence = self.players[1].act(self.game_infoset)\n # 计算胜率\n win_rate = actions_confidence\n # win_rate = max(actions_confidence, -1)\n # win_rate = min(win_rate, 1)\n # win_rate = str(round(float((win_rate + 1) / 2), 4))\n\n if len(action) > 0:\n self.last_pid = self.acting_player_position\n\n if action in bombs:\n self.bomb_num += 1\n\n self.last_move_dict[\n self.acting_player_position] = action.copy()\n\n self.card_play_action_seq.append((position, action))\n self.update_acting_player_hand_cards(action)\n\n self.played_cards[self.acting_player_position] += action\n\n if self.acting_player_position == 'landlord' and \\\n len(action) > 0 and \\\n len(self.three_landlord_cards) > 0:\n for card in action:\n if len(self.three_landlord_cards) > 0:\n if card in self.three_landlord_cards:\n self.three_landlord_cards.remove(card)\n else:\n break\n self.game_done()\n if not self.game_over:\n self.get_acting_player_position()\n self.game_infoset = self.get_infoset()\n # 返回动作和胜率,只有玩家角色会接受返回值\n action_message = {\"action\": str(''.join([EnvCard2RealCard[c] for c in action])),\n \"win_rate\": str(round(float(win_rate), 4))}\n return action_message\n\n def get_last_move(self):\n last_move = []\n if len(self.card_play_action_seq) != 0:\n if len(self.card_play_action_seq[-1][1]) == 0:\n last_move = self.card_play_action_seq[-2][1]\n else:\n last_move = self.card_play_action_seq[-1][1]\n\n return last_move\n\n def get_last_two_moves(self):\n last_two_moves = [[], []]\n for card in self.card_play_action_seq[-2:]:\n last_two_moves.insert(0, card[1])\n last_two_moves = last_two_moves[:2]\n return last_two_moves\n\n def get_acting_player_position(self):\n if self.acting_player_position is None:\n self.acting_player_position = 'landlord'\n\n else:\n if self.acting_player_position == 'landlord':\n self.acting_player_position = 'landlord_down'\n\n elif self.acting_player_position == 'landlord_down':\n self.acting_player_position = 'landlord_up'\n\n else:\n self.acting_player_position = 'landlord'\n\n return self.acting_player_position\n\n def update_acting_player_hand_cards(self, action):\n if action != []:\n # 更新玩家手牌,删除对应的牌\n if self.acting_player_position == self.players[0]:\n for card in action:\n self.info_sets[self.acting_player_position].player_hand_cards.remove(card)\n # 更新另外两个玩家手牌,删除相同数量的牌\n else:\n del self.info_sets[self.acting_player_position].player_hand_cards[0:len(action)]\n self.info_sets[self.acting_player_position].player_hand_cards.sort()\n\n def get_legal_card_play_actions(self):\n mg = MovesGener(\n self.info_sets[self.acting_player_position].player_hand_cards)\n\n action_sequence = self.card_play_action_seq\n\n rival_move = []\n if len(action_sequence) != 0:\n if len(action_sequence[-1][1]) == 0:\n rival_move = action_sequence[-2][1]\n else:\n rival_move = action_sequence[-1][1]\n\n rival_type = md.get_move_type(rival_move)\n rival_move_type = rival_type['type']\n rival_move_len = rival_type.get('len', 1)\n moves = list()\n\n if rival_move_type == md.TYPE_0_PASS:\n moves = mg.gen_moves()\n\n elif rival_move_type == md.TYPE_1_SINGLE:\n all_moves = mg.gen_type_1_single()\n moves = ms.filter_type_1_single(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_2_PAIR:\n all_moves = mg.gen_type_2_pair()\n moves = ms.filter_type_2_pair(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_3_TRIPLE:\n all_moves = mg.gen_type_3_triple()\n moves = ms.filter_type_3_triple(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_4_BOMB:\n all_moves = mg.gen_type_4_bomb() + mg.gen_type_5_king_bomb()\n moves = ms.filter_type_4_bomb(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_5_KING_BOMB:\n moves = []\n\n elif rival_move_type == md.TYPE_6_3_1:\n all_moves = mg.gen_type_6_3_1()\n moves = ms.filter_type_6_3_1(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_7_3_2:\n all_moves = mg.gen_type_7_3_2()\n moves = ms.filter_type_7_3_2(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_8_SERIAL_SINGLE:\n all_moves = mg.gen_type_8_serial_single(repeat_num=rival_move_len)\n moves = ms.filter_type_8_serial_single(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_9_SERIAL_PAIR:\n all_moves = mg.gen_type_9_serial_pair(repeat_num=rival_move_len)\n moves = ms.filter_type_9_serial_pair(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_10_SERIAL_TRIPLE:\n all_moves = mg.gen_type_10_serial_triple(repeat_num=rival_move_len)\n moves = ms.filter_type_10_serial_triple(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_11_SERIAL_3_1:\n all_moves = mg.gen_type_11_serial_3_1(repeat_num=rival_move_len)\n moves = ms.filter_type_11_serial_3_1(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_12_SERIAL_3_2:\n all_moves = mg.gen_type_12_serial_3_2(repeat_num=rival_move_len)\n moves = ms.filter_type_12_serial_3_2(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_13_4_2:\n all_moves = mg.gen_type_13_4_2()\n moves = ms.filter_type_13_4_2(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_14_4_22:\n all_moves = mg.gen_type_14_4_22()\n moves = ms.filter_type_14_4_22(all_moves, rival_move)\n\n if rival_move_type not in [md.TYPE_0_PASS,\n md.TYPE_4_BOMB, md.TYPE_5_KING_BOMB]:\n moves = moves + mg.gen_type_4_bomb() + mg.gen_type_5_king_bomb()\n\n if len(rival_move) != 0: # rival_move is not 'pass'\n moves = moves + [[]]\n\n for m in moves:\n m.sort()\n\n return moves\n\n def reset(self):\n self.card_play_action_seq = []\n\n self.three_landlord_cards = None\n self.game_over = False\n\n self.acting_player_position = None\n self.player_utility_dict = None\n\n self.last_move_dict = {'landlord': [],\n 'landlord_up': [],\n 'landlord_down': []}\n\n self.played_cards = {'landlord': [],\n 'landlord_up': [],\n 'landlord_down': []}\n\n self.last_move = []\n self.last_two_moves = []\n\n self.info_sets = {'landlord': InfoSet('landlord'),\n 'landlord_up': InfoSet('landlord_up'),\n 'landlord_down': InfoSet('landlord_down')}\n\n self.bomb_num = 0\n self.last_pid = 'landlord'\n self.bid_info = [[1, 1, 1],\n [1, 1, 1],\n [1, 1, 1],\n [1, 1, 1]]\n self.bid_count = 0\n self.multiply_count = {'landlord': 0,\n 'landlord_up': 0,\n 'landlord_down': 0}\n self.step_count = 0\n\n def get_infoset(self):\n self.info_sets[\n self.acting_player_position].last_pid = self.last_pid\n\n self.info_sets[\n self.acting_player_position].legal_actions = \\\n self.get_legal_card_play_actions()\n\n self.info_sets[\n self.acting_player_position].bomb_num = self.bomb_num\n\n self.info_sets[\n self.acting_player_position].last_move = self.get_last_move()\n\n self.info_sets[\n self.acting_player_position].last_two_moves = self.get_last_two_moves()\n\n self.info_sets[\n self.acting_player_position].last_move_dict = self.last_move_dict\n\n self.info_sets[self.acting_player_position].num_cards_left_dict = \\\n {pos: len(self.info_sets[pos].player_hand_cards)\n for pos in ['landlord', 'landlord_up', 'landlord_down']}\n\n self.info_sets[self.acting_player_position].other_hand_cards = []\n\n '''\n 调整计算其他人手牌的方法,整副牌减去玩家手牌与出过的牌\n for pos in ['landlord', 'landlord_up', 'landlord_down']:\n if pos != self.acting_player_position:\n self.info_sets[\n self.acting_player_position].other_hand_cards += \\\n self.info_sets[pos].player_hand_cards\n '''\n # 把出过的牌中三个子列表合成一个列表\n played_cards_tmp = []\n for i in list(self.played_cards.values()):\n played_cards_tmp.extend(i)\n # 出过的牌和玩家手上的牌\n played_and_hand_cards = played_cards_tmp + self.info_sets[self.acting_player_position].player_hand_cards\n # 整副牌减去出过的牌和玩家手上的牌,就是其他人的手牌\n for i in set(AllEnvCard):\n self.info_sets[\n self.acting_player_position].other_hand_cards.extend([i] * (AllEnvCard.count(i) - played_and_hand_cards.count(i)))\n\n self.info_sets[self.acting_player_position].played_cards = \\\n self.played_cards\n self.info_sets[self.acting_player_position].three_landlord_cards = \\\n self.three_landlord_cards\n self.info_sets[self.acting_player_position].card_play_action_seq = \\\n self.card_play_action_seq\n\n self.info_sets[\n self.acting_player_position].all_handcards = \\\n {pos: self.info_sets[pos].player_hand_cards\n for pos in ['landlord', 'landlord_up', 'landlord_down']}\n\n # Custom bid info\n self.info_sets[self.acting_player_position].bid_info = bid_infos[self.acting_player_position]\n\n return deepcopy(self.info_sets[self.acting_player_position])" }, { "identifier": "DeepAgent", "path": "douzero/evaluation/deep_agent.py", "snippet": "class DeepAgent:\n\n def __init__(self, position, model_path):\n self.model_type = \"old\"\n if \"general\" in model_path:\n self.model_type = \"general\"\n elif \"resnet\" in model_path:\n self.model_type = \"resnet\"\n self.model = _load_model(position, model_path, self.model_type)\n\n def act(self, infoset):\n obs = get_obs(infoset, model_type=self.model_type)\n z_batch = torch.from_numpy(obs['z_batch']).float()\n x_batch = torch.from_numpy(obs['x_batch']).float()\n if torch.cuda.is_available():\n z_batch, x_batch = z_batch.cuda(), x_batch.cuda()\n y_pred = self.model.forward(z_batch, x_batch, return_value=True)['values']\n y_pred = y_pred.detach().cpu().numpy()\n\n best_action_index = np.argmax(y_pred, axis=0)[0]\n best_action = infoset.legal_actions[best_action_index]\n best_action_confidence = y_pred[best_action_index]\n return best_action, best_action_confidence" } ]
import GameHelper as gh import os import sys import time import threading import pyautogui import win32gui import multiprocessing as mp import DetermineColor as DC import cv2 import numpy as np import traceback import BidModel import LandlordModel import FarmerModel from GameHelper import GameHelper from PIL import Image from skimage.metrics import structural_similarity as ssim from collections import defaultdict from douzero.env.move_detector import get_move_type from PyQt5 import QtGui, QtWidgets, QtCore from PyQt5.QtWidgets import QTableWidgetItem, QInputDialog, QMessageBox from PyQt5.QtGui import QPixmap, QIcon from PyQt5.QtCore import QTime, QEventLoop, Qt from MainWindow import Ui_Form from douzero.env.game import GameEnv from douzero.evaluation.deep_agent import DeepAgent
15,236
def init_display(self): self.WinRate.setText("评分") self.label.setText("游戏状态") self.label.setStyleSheet('background-color: rgba(255, 0, 0, 0);') self.UserHandCards.setText("手牌") # self.LBrowser.clear() # self.RBrowser.clear() self.LPlayedCard.setText("上家出牌区域") self.RPlayedCard.setText("下家出牌区域") self.PredictedCard.setText("AI出牌区域") self.ThreeLandlordCards.setText("地主牌") self.recorder2zero() for player in self.Players: player.setStyleSheet('background-color: rgba(0, 255, 0, 0);') def init_cards(self): self.RunGame = True GameHelper.Interrupt = False self.user_hand_cards_real = "" self.user_hand_cards_env = [] # 其他玩家出牌 self.other_played_cards_real = "" self.other_played_cards_env = [] # 其他玩家手牌(整副牌减去玩家手牌,后续再减掉历史出牌) self.other_hand_cards = [] # 三张底牌 self.three_landlord_cards_real = "" self.three_landlord_cards_env = [] # 玩家角色代码:0-地主上家, 1-地主, 2-地主下家 self.user_position_code = None self.user_position = "" # 开局时三个玩家的手牌 self.card_play_data_list = {} # 识别玩家手牌 self.user_hand_cards_real = self.find_my_cards() while len(self.user_hand_cards_real) != 17 and len(self.user_hand_cards_real) != 20: self.detect_start_btn() if not self.RunGame: break self.sleep(200) self.user_hand_cards_real = self.find_my_cards() self.user_hand_cards_env = [RealCard2EnvCard[c] for c in list(self.user_hand_cards_real)] # 识别三张底牌 self.three_landlord_cards_real = self.find_landlord_cards() self.ThreeLandlordCards.setText("底牌:" + self.three_landlord_cards_real) self.three_landlord_cards_env = [RealCard2EnvCard[c] for c in list(self.three_landlord_cards_real)] while len(self.three_landlord_cards_env) != 3: self.detect_start_btn() if not self.RunGame: break if len(self.three_landlord_cards_env) > 3: self.ThreeLandlordCardsConfidence += 0.05 elif len(self.three_landlord_cards_env) < 3: self.ThreeLandlordCardsConfidence -= 0.05 self.three_landlord_cards_real = self.find_landlord_cards() self.ThreeLandlordCards.setText("底牌:" + self.three_landlord_cards_real) self.three_landlord_cards_env = [RealCard2EnvCard[c] for c in list(self.three_landlord_cards_real)] # 识别玩家的角色 self.sleep(500) self.user_position_code = self.find_landlord(self.LandlordFlagPos) self.sleep(200) while self.user_position_code is None: self.detect_start_btn() if not self.RunGame: break self.user_position_code = self.find_landlord(self.LandlordFlagPos) self.sleep(200) print("正在出牌人的代码: ", self.user_position_code) if self.user_position_code is None: items = ("地主上家", "地主", "地主下家") item, okPressed = QInputDialog.getItem(self, "选择角色", "未识别到地主,请手动选择角色:", items, 0, False) if okPressed and item: self.user_position_code = items.index(item) else: return self.user_position = ['landlord_up', 'landlord', 'landlord_down'][self.user_position_code] print("我现在在地主的方向:", self.user_position) for player in self.Players: player.setStyleSheet('background-color: rgba(0, 255, 0, 0);') self.Players[self.user_position_code].setStyleSheet('background-color: rgba(0, 255, 0, 0.5);') # 整副牌减去玩家手上的牌,就是其他人的手牌,再分配给另外两个角色(如何分配对AI判断没有影响) for i in set(AllEnvCard): self.other_hand_cards.extend([i] * (AllEnvCard.count(i) - self.user_hand_cards_env.count(i))) self.other_hands_cards_str = str(''.join([EnvCard2RealCard[c] for c in self.other_hand_cards]))[::-1] self.cards_recorder(self.other_hands_cards_str) self.card_play_data_list.update({ 'three_landlord_cards': self.three_landlord_cards_env, ['landlord_up', 'landlord', 'landlord_down'][(self.user_position_code + 0) % 3]: self.user_hand_cards_env, ['landlord_up', 'landlord', 'landlord_down'][(self.user_position_code + 1) % 3]: self.other_hand_cards[0:17] if (self.user_position_code + 1) % 3 != 1 else self.other_hand_cards[17:], ['landlord_up', 'landlord', 'landlord_down'][(self.user_position_code + 2) % 3]: self.other_hand_cards[0:17] if (self.user_position_code + 1) % 3 == 1 else self.other_hand_cards[17:] }) print("开始对局") print("手牌:", self.user_hand_cards_real) print("地主牌:", self.three_landlord_cards_real) # 生成手牌结束,校验手牌数量 if len(self.card_play_data_list["three_landlord_cards"]) != 3: QMessageBox.critical(self, "底牌识别出错", "底牌必须是3张!", QMessageBox.Yes, QMessageBox.Yes) self.init_display() return if len(self.card_play_data_list["landlord_up"]) != 17 or \ len(self.card_play_data_list["landlord_down"]) != 17 or \ len(self.card_play_data_list["landlord"]) != 20: QMessageBox.critical(self, "手牌识别出错", "初始手牌数目有误", QMessageBox.Yes, QMessageBox.Yes) self.init_display() return # 出牌顺序:0-玩家出牌, 1-玩家下家出牌, 2-玩家上家出牌 self.play_order = 0 if self.user_position == "landlord" else 1 if self.user_position == "landlord_up" else 2 # 创建一个代表玩家的AI ai_players = [0, 0] ai_players[0] = self.user_position ai_players[1] = DeepAgent(self.user_position, self.card_play_model_path_dict[self.user_position])
# -*- coding: utf-8 -*- # Created by: Raf # Modify by: Vincentzyx EnvCard2RealCard = {3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'T', 11: 'J', 12: 'Q', 13: 'K', 14: 'A', 17: '2', 20: 'X', 30: 'D'} RealCard2EnvCard = {'3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14, '2': 17, 'X': 20, 'D': 30} AllEnvCard = [3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 17, 17, 17, 17, 20, 30] AllCards = ['D', 'X', '2', 'A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3'] helper = GameHelper() class MyPyQT_Form(QtWidgets.QWidget, Ui_Form): def __init__(self): super(MyPyQT_Form, self).__init__() self.other_hands_cards_str = None self.stop_sign = None self.loop_sign = None self.env = None self.three_landlord_cards_env = None self.three_landlord_cards_real = None self.user_hand_cards_env = None self.user_hand_cards_real = None self.play_order = None self.card_play_data_list = None self.other_hand_cards = None self.other_played_cards_env = None self.other_played_cards_real = None self.user_position = None self.user_position_code = None self.setupUi(self) self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | # 使能最小化按钮 QtCore.Qt.WindowStaysOnTopHint | # 窗体总在最前端 QtCore.Qt.WindowCloseButtonHint) self.setWindowIcon(QIcon(':/pics/favicon.ico')) self.setWindowTitle("DouZero欢乐斗地主v2.0") self.setFixedSize(self.width(), self.height()) # 固定窗体大小 self.move(50, 50) # self.setWindowIcon(QIcon('pics/favicon.ico')) window_pale = QtGui.QPalette() # window_pale.setBrush(self.backgroundRole(), QtGui.QBrush(QtGui.QPixmap("pics/bg.png"))) self.setPalette(window_pale) self.SingleButton.clicked.connect(self.game_single) self.LoopButton.clicked.connect(self.game_loop) self.StopButton.clicked.connect(self.stop) # self.Players = [self.RPlayer, self.Player, self.LPlayer] self.Players = [self.RPlayedCard, self.PredictedCard, self.LPlayedCard] self.counter = QTime() # 参数 self.MyConfidence = 0.8 # 我的牌的置信度 self.OtherConfidence = 0.8 # 别人的牌的置信度 self.WhiteConfidence = 0.85 # 检测白块的置信度 self.LandlordFlagConfidence = 0.8 # 检测地主标志的置信度 self.ThreeLandlordCardsConfidence = 0.8 # 检测地主底牌的置信度 self.PassConfidence = 0.7 self.PassConfidence = 0.8 self.WaitTime = 1 # 等待状态稳定延时 self.MyFilter = 40 # 我的牌检测结果过滤参数 self.OtherFilter = 25 # 别人的牌检测结果过滤参数 self.SleepTime = 0.1 # 循环中睡眠时间 self.RunGame = False self.AutoPlay = False self.BidThreshold1 = 65 # 叫地主阈值 self.BidThreshold2 = 72 # 抢地主阈值 self.JiabeiThreshold = ( (85, 72), # 叫地主 超级加倍 加倍 阈值 (85, 75) # 叫地主 超级加倍 加倍 阈值 (在地主是抢来的情况下) ) self.MingpaiThreshold = 92 # 坐标 self.MyHandCardsPos = (180, 560, 1050, 90) # 我的截图区域 self.LPlayedCardsPos = (320, 280, 500, 120) # 左边出牌截图区域 self.RPlayedCardsPos = (600, 280, 500, 120) # 右边出牌截图区域 self.LandlordCardsPos = (600, 33, 220, 103) # 地主底牌截图区域 self.LPassPos = (360, 360, 120, 80) # 左边不出截图区域 self.RPassPos = (940, 360, 120, 80) # 右边不出截图区域 self.PassBtnPos = (200, 450, 1000, 120) # 要不起截图区域 self.GeneralBtnPos = (200, 450, 1000, 120) # 叫地主、抢地主、加倍按钮截图区域 self.LandlordFlagPos = [(1247, 245, 48, 52), (12, 661, 51, 53), (123, 243, 52, 54)] # 地主标志截图区域(右-我-左) self.card_play_model_path_dict = { 'landlord': "baselines/resnet/resnet_landlord.ckpt", 'landlord_up': "baselines/resnet/resnet_landlord_up.ckpt", 'landlord_down': "baselines/resnet/resnet_landlord_down.ckpt" } def game_single(self): self.loop_sign = 0 self.stop_sign = 0 self.detect_start_btn() self.before_start() self.init_cards() def game_loop(self): self.loop_sign = 1 self.stop_sign = 0 while True: if self.stop_sign == 1: break self.detect_start_btn() self.before_start() self.init_cards() self.sleep(5000) def stop(self): self.stop_sign = 1 print("按下停止键") try: self.RunGame = False self.loop_sign = 0 self.env.game_over = True self.env.reset() self.init_display() self.PreWinrate.setText("局前胜率: ") self.BidWinrate.setText("叫牌胜率: ") except AttributeError as e: traceback.print_exc() def init_display(self): self.WinRate.setText("评分") self.label.setText("游戏状态") self.label.setStyleSheet('background-color: rgba(255, 0, 0, 0);') self.UserHandCards.setText("手牌") # self.LBrowser.clear() # self.RBrowser.clear() self.LPlayedCard.setText("上家出牌区域") self.RPlayedCard.setText("下家出牌区域") self.PredictedCard.setText("AI出牌区域") self.ThreeLandlordCards.setText("地主牌") self.recorder2zero() for player in self.Players: player.setStyleSheet('background-color: rgba(0, 255, 0, 0);') def init_cards(self): self.RunGame = True GameHelper.Interrupt = False self.user_hand_cards_real = "" self.user_hand_cards_env = [] # 其他玩家出牌 self.other_played_cards_real = "" self.other_played_cards_env = [] # 其他玩家手牌(整副牌减去玩家手牌,后续再减掉历史出牌) self.other_hand_cards = [] # 三张底牌 self.three_landlord_cards_real = "" self.three_landlord_cards_env = [] # 玩家角色代码:0-地主上家, 1-地主, 2-地主下家 self.user_position_code = None self.user_position = "" # 开局时三个玩家的手牌 self.card_play_data_list = {} # 识别玩家手牌 self.user_hand_cards_real = self.find_my_cards() while len(self.user_hand_cards_real) != 17 and len(self.user_hand_cards_real) != 20: self.detect_start_btn() if not self.RunGame: break self.sleep(200) self.user_hand_cards_real = self.find_my_cards() self.user_hand_cards_env = [RealCard2EnvCard[c] for c in list(self.user_hand_cards_real)] # 识别三张底牌 self.three_landlord_cards_real = self.find_landlord_cards() self.ThreeLandlordCards.setText("底牌:" + self.three_landlord_cards_real) self.three_landlord_cards_env = [RealCard2EnvCard[c] for c in list(self.three_landlord_cards_real)] while len(self.three_landlord_cards_env) != 3: self.detect_start_btn() if not self.RunGame: break if len(self.three_landlord_cards_env) > 3: self.ThreeLandlordCardsConfidence += 0.05 elif len(self.three_landlord_cards_env) < 3: self.ThreeLandlordCardsConfidence -= 0.05 self.three_landlord_cards_real = self.find_landlord_cards() self.ThreeLandlordCards.setText("底牌:" + self.three_landlord_cards_real) self.three_landlord_cards_env = [RealCard2EnvCard[c] for c in list(self.three_landlord_cards_real)] # 识别玩家的角色 self.sleep(500) self.user_position_code = self.find_landlord(self.LandlordFlagPos) self.sleep(200) while self.user_position_code is None: self.detect_start_btn() if not self.RunGame: break self.user_position_code = self.find_landlord(self.LandlordFlagPos) self.sleep(200) print("正在出牌人的代码: ", self.user_position_code) if self.user_position_code is None: items = ("地主上家", "地主", "地主下家") item, okPressed = QInputDialog.getItem(self, "选择角色", "未识别到地主,请手动选择角色:", items, 0, False) if okPressed and item: self.user_position_code = items.index(item) else: return self.user_position = ['landlord_up', 'landlord', 'landlord_down'][self.user_position_code] print("我现在在地主的方向:", self.user_position) for player in self.Players: player.setStyleSheet('background-color: rgba(0, 255, 0, 0);') self.Players[self.user_position_code].setStyleSheet('background-color: rgba(0, 255, 0, 0.5);') # 整副牌减去玩家手上的牌,就是其他人的手牌,再分配给另外两个角色(如何分配对AI判断没有影响) for i in set(AllEnvCard): self.other_hand_cards.extend([i] * (AllEnvCard.count(i) - self.user_hand_cards_env.count(i))) self.other_hands_cards_str = str(''.join([EnvCard2RealCard[c] for c in self.other_hand_cards]))[::-1] self.cards_recorder(self.other_hands_cards_str) self.card_play_data_list.update({ 'three_landlord_cards': self.three_landlord_cards_env, ['landlord_up', 'landlord', 'landlord_down'][(self.user_position_code + 0) % 3]: self.user_hand_cards_env, ['landlord_up', 'landlord', 'landlord_down'][(self.user_position_code + 1) % 3]: self.other_hand_cards[0:17] if (self.user_position_code + 1) % 3 != 1 else self.other_hand_cards[17:], ['landlord_up', 'landlord', 'landlord_down'][(self.user_position_code + 2) % 3]: self.other_hand_cards[0:17] if (self.user_position_code + 1) % 3 == 1 else self.other_hand_cards[17:] }) print("开始对局") print("手牌:", self.user_hand_cards_real) print("地主牌:", self.three_landlord_cards_real) # 生成手牌结束,校验手牌数量 if len(self.card_play_data_list["three_landlord_cards"]) != 3: QMessageBox.critical(self, "底牌识别出错", "底牌必须是3张!", QMessageBox.Yes, QMessageBox.Yes) self.init_display() return if len(self.card_play_data_list["landlord_up"]) != 17 or \ len(self.card_play_data_list["landlord_down"]) != 17 or \ len(self.card_play_data_list["landlord"]) != 20: QMessageBox.critical(self, "手牌识别出错", "初始手牌数目有误", QMessageBox.Yes, QMessageBox.Yes) self.init_display() return # 出牌顺序:0-玩家出牌, 1-玩家下家出牌, 2-玩家上家出牌 self.play_order = 0 if self.user_position == "landlord" else 1 if self.user_position == "landlord_up" else 2 # 创建一个代表玩家的AI ai_players = [0, 0] ai_players[0] = self.user_position ai_players[1] = DeepAgent(self.user_position, self.card_play_model_path_dict[self.user_position])
self.env = GameEnv(ai_players)
3
2023-12-01 04:04:30+00:00
24k
super1207/satoricq
satori.py
[ { "identifier": "AdapterKook", "path": "kook_adapter.py", "snippet": "class AdapterKook:\n def __init__(self,config = {}) -> None:\n '''用于初始化一些配置信息,尽量不要在这里阻塞,因为此处不具备异步环境,如果你需要读写配置文件,请在init_after中进行'''\n self._access_token = config[\"access_token\"]\n self._http_url = \"https://www.kookapp.cn/api/v3\"\n self._is_stop = False\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n self._queue = Queue(maxsize=100)\n self._id = 0\n self._sn = 0\n self._self_id = None\n\n\n async def enable(self) -> None:\n '''适配器启用的时候会调用,可以不理,也可以没这个函数\n 配合下面的停用函数,适配器可以得到自己在整个系统中的状态,进而进行一些优化\n 如,如果适配器处于停用状态,适配器可以自行选择关闭网络连接,以节省资源,当然,也可以不理会\n '''\n pass\n\n async def disable(self) -> None:\n '''适配器停用的时候会调用,可以不理,也可以没这个函数'''\n pass\n \n async def release(self) -> None:\n '''适配器释放的时候会调用一次,应该在这里停用ws连接\n 一般认为,适配器会和真正的协议端建立连接,所以,这个函数大多数时候是需要写的\n 但是,这个函数允许资源延迟释放,只要能释放就行\n 你可以在这个函数里面进行数据保存之类的,这种用途下,请阻塞这个函数,直到保存完成\n '''\n self._is_stop = True\n\n async def get_msg(self) -> dict:\n '''阻塞并等待消息返回,如果你的适配器不具备接收消息的能力,请不要写这个函数'''\n return await self._queue.get()\n \n\n async def _ws_recv(self,websocket):\n try:\n reply = await asyncio.wait_for(websocket.recv(),0.1)\n return reply\n except asyncio.TimeoutError:\n return None\n\n async def _ws_connect(self):\n self._login_status = SatoriLogin.LoginStatus.CONNECT\n ws_url = (await self._api_call(\"/gateway/index?compress=0\"))[\"url\"]\n async with connect(ws_url) as websocket:\n tm = time.time()\n while not self._is_stop:\n reply = await self._ws_recv(websocket)\n if not reply:\n now_time = time.time()\n if now_time - tm > 30:\n tm = now_time\n await websocket.send(json.dumps({\"s\": 2,\"sn\": self._sn}))\n continue\n js = json.loads(reply)\n s = js[\"s\"]\n if s == 5:raise Exception(\"recv reset ws\")\n elif s == 3:pass # heartbeat\n elif s == 1:\n self._login_status = SatoriLogin.LoginStatus.ONLINE\n print(\"kook:ws连接成功\")\n elif s == 0:\n self._sn = js[\"sn\"]\n asyncio.create_task(self._event_deal(js[\"d\"]))\n\n async def _ws_server(self) -> None:\n while not self._is_stop:\n try:\n await self._ws_connect()\n except:\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n print(traceback.format_exc())\n await asyncio.sleep(3)\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n\n async def init_after(self) -> None:\n '''适配器创建之后会调用一次,应该在这里进行ws连接等操作,如果不需要,可以不写'''\n asyncio.create_task(self._ws_server())\n\n def _kook_msg_to_satori(self,msg_type:int,message:str)->str:\n ret = \"\"\n if msg_type == 2: #图片\n ret += \"<img src={}/>\".format(json.dumps(message))\n else:\n def kook_msg_f(msg):\n ret = \"\"\n is_f = False\n for ch in msg:\n if is_f:\n is_f = False\n ret += ch\n elif ch == \"\\\\\":\n is_f = True\n else:\n ret += ch\n return ret\n \n index = 0\n msg_list = message.split(\"(met)\")\n for it in msg_list:\n if index % 2 == 0:\n ret += satori_to_plain(kook_msg_f(it))\n else:\n if it == \"all\":\n ret += \"<at type=\\\"all\\\"/>\"\n else:\n ret += \"<at id=\\\"{}\\\"/>\".format(it)\n index += 1\n return ret\n\n\n async def _deal_group_message_event(self,data,user_id:str):\n group_id = data[\"target_id\"]\n kook_msg = data[\"content\"]\n extra = data[\"extra\"]\n author = extra[\"author\"]\n msg_type = data[\"type\"]\n\n if msg_type == 10:#卡牌\n return\n satori_msg = self._kook_msg_to_satori(msg_type,kook_msg)\n\n satori_evt = SatoriGroupMessageCreatedEvent(\n id=self._id,\n self_id=self._self_id,\n timestamp=data[\"msg_timestamp\"],\n platform=\"kook\",\n channel=SatoriChannel(\n id=\"GROUP_\"+group_id,\n type=SatoriChannel.ChannelType.TEXT,\n name=extra[\"channel_name\"]\n ),\n message=SatoriMessage(\n id=data[\"msg_id\"],\n content=satori_msg,\n created_at=data[\"msg_timestamp\"]\n ),\n user=SatoriUser(\n id=author[\"id\"],\n name=author[\"username\"],\n avatar=author[\"avatar\"],\n is_bot=author[\"bot\"]\n ),\n member=SatoriGuildMember(\n nick=author[\"nickname\"],\n avatar=author[\"avatar\"]\n ),\n guild=SatoriGuild(\n id=extra[\"guild_id\"]\n ),\n role=SatoriGuildRole(\n id=json.dumps(sorted(author[\"roles\"]))\n )\n )\n self._id += 1\n self._queue.put_nowait(satori_evt.to_dict())\n\n async def _deal_private_message_event(self,data,user_id:str):\n\n kook_msg = data[\"content\"]\n extra = data[\"extra\"]\n author = extra[\"author\"]\n msg_type = data[\"type\"]\n\n if msg_type == 10:#卡牌\n return\n satori_msg = self._kook_msg_to_satori(msg_type,kook_msg)\n\n satori_evt = SatoriPrivateMessageCreatedEvent(\n id=self._id,\n self_id=self._self_id,\n timestamp=data[\"msg_timestamp\"],\n channel=SatoriChannel(\n id=user_id,\n type=SatoriChannel.ChannelType.TEXT,\n name=author[\"username\"]\n ),\n message=SatoriMessage(\n id=data[\"msg_id\"],\n content=satori_msg,\n created_at=data[\"msg_timestamp\"]\n ),\n user=SatoriUser(\n id=user_id,\n name=author[\"username\"],\n avatar=author[\"avatar\"],\n is_bot=author[\"bot\"]\n ),\n platform=\"kook\"\n ).to_dict()\n self._id += 1\n self._queue.put_nowait(satori_evt)\n\n async def _deal_group_increase_event(self,data):\n extra = data[\"extra\"]\n satori_evt = {\n \"id\":self._id,\n \"type\":\"guild-member-added\",\n \"platform\":\"kook\",\n \"self_id\":self._self_id,\n \"timestamp\":data[\"msg_timestamp\"],\n \"guild\":SatoriGuild(id=data[\"target_id\"]).to_dict(),\n \"member\":SatoriGuildMember(joined_at=extra[\"body\"][\"joined_at\"]).to_dict(),\n \"user\":SatoriUser(id=extra[\"body\"][\"user_id\"]).to_dict()\n }\n self._id += 1\n self._queue.put_nowait(satori_evt)\n\n\n\n async def _deal_group_evt(self,data):\n user_id:str = data[\"author_id\"]\n if user_id == \"1\": # system message\n tp = data[\"type\"]\n if tp != 255:\n return\n sub_type = data[\"extra\"][\"type\"]\n if sub_type == \"joined_guild\":\n await self._deal_group_increase_event(data)\n else:\n if self._self_id:\n if user_id != self._self_id:\n await self._deal_group_message_event(data,user_id)\n\n\n async def _deal_person_evt(self,data):\n user_id:str = data[\"author_id\"]\n if user_id != 1: # 不是系统消息\n if self._self_id:\n if user_id != self._self_id:\n await self._deal_private_message_event(data,user_id)\n\n\n async def _event_deal(self,data:dict):\n try:\n tp = data[\"channel_type\"]\n if tp == \"GROUP\":\n await self._deal_group_evt(data)\n else:\n await self._deal_person_evt(data)\n except:\n print(traceback.format_exc())\n \n async def _api_call(self,path,data = None) -> dict:\n url:str = self._http_url + path\n headers = {\"Authorization\":\"Bot {}\".format(self._access_token)}\n if data == None:\n async with httpx.AsyncClient() as client:\n return (await client.get(url,headers=headers)).json()[\"data\"]\n else:\n async with httpx.AsyncClient() as client:\n return (await client.post(url,headers=headers,data=data)).json()[\"data\"]\n\n def _make_kook_text(self,text):\n ret = \"\"\n for ch in text:\n if ch in [\"\\\\\",\"*\",\"~\",\"[\",\"(\",\")\",\"]\",\"-\",\">\",\"`\"]:\n ret += \"\\\\\"\n ret += ch\n return ret\n \n async def _satori_to_kook(self,satori_obj) -> [dict]:\n to_send_data = []\n last_type = 1\n for node in satori_obj:\n if isinstance(node,str):\n text = self._make_kook_text(node)\n if last_type == 1 and len(to_send_data) != 0:\n l = len(to_send_data)\n to_send_data[l - 1][\"content\"] += text\n else:\n to_send_data.append({\n \"type\":1,\n \"content\":text\n })\n last_type = 1\n else:\n if node[\"type\"] == \"at\":\n type = get_json_or(node[\"attrs\"],\"type\",None)\n id = get_json_or(node[\"attrs\"],\"id\",None)\n if type == \"all\":\n text = \"(met)all(met)\"\n elif id != None:\n text = \"(met){}(met)\".format(self._make_kook_text(id))\n if last_type == 1 and len(to_send_data) != 0:\n l = len(to_send_data)\n to_send_data[l - 1][\"content\"] += text\n else:\n to_send_data.append({\n \"type\":1,\n \"content\":text\n })\n last_type = 1\n elif node[\"type\"] == \"img\":\n img_url:str = node[\"attrs\"][\"src\"]\n kook_img_url = \"\"\n if img_url.startswith(\"https://img.kookapp.cn\"):\n kook_img_url = img_url\n else:\n if img_url.startswith(\"data:image/\"):\n base64_start = img_url.find(\"base64,\")\n img_content = base64.b64decode(img_url[base64_start + 7:])\n else:\n async with httpx.AsyncClient() as client:\n img_content = (await client.get(img_url)).content\n files = {\n 'file':('test',img_content)\n }\n headers = {\"Authorization\":\"Bot {}\".format(self._access_token)}\n async with httpx.AsyncClient() as client:\n ret = (await client.post(self._http_url + \"/asset/create\",files=files,headers=headers)).json()\n kook_img_url = ret[\"data\"][\"url\"]\n to_send_data.append({\n \"type\":2,\n \"content\":kook_img_url\n })\n last_type = 2\n return to_send_data\n \n async def create_message(self,platform:str,self_id:str,channel_id:str,content:str):\n '''发送消息'''\n satori_obj = parse_satori_html(content)\n to_sends = await self._satori_to_kook(satori_obj)\n if channel_id.startswith(\"GROUP_\"):\n channel_id = int(channel_id[6:])\n to_ret = []\n for it in to_sends:\n ret = await self._api_call(\"/message/create\",{\"content\":it[\"content\"],\"type\":it[\"type\"],\"target_id\":channel_id})\n to_ret.append(SatoriMessage(id=ret[\"msg_id\"],content=\"\").to_dict())\n return to_ret\n else:\n to_ret = []\n for it in to_sends:\n ret = await self._api_call(\"/direct-message/create\",{\"content\":it[\"content\"],\"type\":it[\"type\"],\"target_id\":channel_id})\n to_ret.append(SatoriMessage(id=ret[\"msg_id\"],content=\"\").to_dict())\n return to_ret\n \n async def get_login(self,platform:Optional[str],self_id:Optional[str]) -> [dict]:\n '''获取登录信息,如果platform和self_id为空,那么应该返回一个列表'''\n obret = (await self._api_call(\"/user/me\"))\n satori_ret = SatoriLogin(\n status=self._login_status,\n user=SatoriUser(\n id=obret[\"id\"],\n name=obret[\"username\"],\n avatar=get_json_or(obret,\"avatar\",None),\n is_bot=True\n ),\n self_id=obret[\"id\"],\n platform=\"kook\"\n ).to_dict()\n self._self_id = obret[\"id\"]\n if platform == None and self_id == None:\n return [satori_ret]\n else:\n return satori_ret\n \n async def get_guild_member(self,platform:Optional[str],self_id:Optional[str],guild_id:str,user_id:str) -> [dict]:\n '''获取群组成员信息'''\n url = \"/user/view?user_id={}&guild_id={}\".format(user_id,guild_id)\n obret = (await self._api_call(url))\n satori_ret = SatoriGuildMember(\n user=SatoriUser(\n id=obret[\"id\"],\n name=get_json_or(obret,\"username\",None),\n avatar=get_json_or(obret,\"avatar\",None),\n is_bot=get_json_or(obret,\"bot\",None)\n ),\n nick=get_json_or(obret,\"nickname\",None),\n avatar=get_json_or(obret,\"avatar\",None),\n joined_at=get_json_or(obret,\"join_time\",None)\n ).to_dict()\n return satori_ret\n \n async def get_user(self,platform:Optional[str],self_id:Optional[str],user_id:str) -> [dict]:\n '''获取用户信息'''\n url = \"/user/view?user_id={}\".format(user_id)\n obret = (await self._api_call(url))\n satori_ret = SatoriUser(\n id=obret[\"id\"],\n name=obret[\"username\"],\n avatar=obret[\"avatar\"],\n is_bot=obret[\"bot\"],\n ).to_dict()\n return satori_ret\n \n async def get_channel_list(self,platform:Optional[str],self_id:Optional[str],guild_id:str) -> [dict]:\n '''获取频道列表'''\n url = \"/channel/list?guild_id={}\".format(guild_id)\n obret = (await self._api_call(url))\n ret_list = []\n items = get_json_or(obret,\"items\",None)\n for it in items:\n channel_type = it[\"type\"]\n channel_id = \"GROUP_\" + it[\"id\"]\n channel_name = it[\"name\"]\n channel_parent = it[\"parent_id\"]\n if channel_type == 1:\n ret_list.append(SatoriChannel(\n id=channel_id,\n name=channel_name,\n type=SatoriChannel.ChannelType.TEXT,\n parent_id=channel_parent\n ).to_dict())\n page_total = get_json_or(obret,\"data\",1)\n if page_total > 1:\n for i in range(2,page_total + 1):\n url = \"/channel/list?guild_id={}&page={}\".format(guild_id,i)\n obret = (await self._api_call(url))\n items = get_json_or(obret,\"items\",None)\n for it in items:\n channel_type = it[\"type\"]\n channel_id = \"GROUP_\" + it[\"id\"]\n channel_name = it[\"name\"]\n channel_parent = it[\"parent_id\"]\n if channel_type == 1:\n ret_list.append(SatoriChannel(\n id=channel_id,\n name=channel_name,\n type=SatoriChannel.ChannelType.TEXT,\n parent=channel_parent\n ).to_dict())\n return {\"data\":ret_list}" }, { "identifier": "AdapterMihoyo", "path": "mihoyo_adapter.py", "snippet": "class AdapterMihoyo:\n def __init__(self,config = {}) -> None:\n '''用于初始化一些配置信息,尽量不要在这里阻塞,因为此处不具备异步环境,如果你需要读写配置文件,请在init_after中进行'''\n self._http_url = \"https://bbs-api.miyoushe.com\"\n self._is_stop = False\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n self._queue = Queue(maxsize=100)\n self._id = 0\n self._sn = 1\n self._self_id = config[\"bot_id\"]\n self._secret = config[\"secret\"]\n self._villa_id = config[\"villa_id\"]\n\n\n async def enable(self) -> None:\n '''适配器启用的时候会调用,可以不理,也可以没这个函数\n 配合下面的停用函数,适配器可以得到自己在整个系统中的状态,进而进行一些优化\n 如,如果适配器处于停用状态,适配器可以自行选择关闭网络连接,以节省资源,当然,也可以不理会\n '''\n pass\n\n async def disable(self) -> None:\n '''适配器停用的时候会调用,可以不理,也可以没这个函数'''\n pass\n \n async def release(self) -> None:\n '''适配器释放的时候会调用一次,应该在这里停用ws连接\n 一般认为,适配器会和真正的协议端建立连接,所以,这个函数大多数时候是需要写的\n 但是,这个函数允许资源延迟释放,只要能释放就行\n 你可以在这个函数里面进行数据保存之类的,这种用途下,请阻塞这个函数,直到保存完成\n '''\n self._is_stop = True\n\n async def get_msg(self) -> dict:\n '''阻塞并等待消息返回,如果你的适配器不具备接收消息的能力,请不要写这个函数'''\n return await self._queue.get()\n\n async def _send_ws_pack(self,ws,ws_dat,biztype):\n magic = 0xBABEFACE.to_bytes(length=4, byteorder='little', signed=False)\n if biztype == 7:\n pb_pack = bytes(PLogin(\n uid=int(ws_dat[\"uid\"]),\n token=self._villa_id + \".\" + self._secret + \".\" + self._self_id,\n platform=ws_dat[\"platform\"],\n app_id=ws_dat[\"app_id\"],\n device_id=ws_dat[\"device_id\"]\n ))\n elif biztype == 6:\n pb_pack = bytes(PHeartBeat(\n client_timestamp=str(int(round(time.time() * 1000)))\n ))\n else:\n raise Exception(\"unkonw biztype:{}\".format(biztype))\n \n wid = self._sn\n self._sn += 1\n\n flag = 1\n appid = 104\n headerlen = 24\n datalen = headerlen + len(pb_pack)\n\n to_send = magic\n to_send += datalen.to_bytes(length=4, byteorder='little', signed=False)\n to_send += headerlen.to_bytes(length=4, byteorder='little', signed=False)\n to_send += wid.to_bytes(length=8, byteorder='little', signed=False)\n to_send += flag.to_bytes(length=4, byteorder='little', signed=False)\n to_send += biztype.to_bytes(length=4, byteorder='little', signed=False)\n to_send += appid.to_bytes(length=4, byteorder='little', signed=True)\n to_send += pb_pack\n\n await ws.send(to_send)\n \n async def _ws_recv(self,websocket):\n try:\n reply = await asyncio.wait_for(websocket.recv(),0.1)\n return reply\n except asyncio.TimeoutError:\n return None\n\n async def _ws_connect(self):\n self._login_status = SatoriLogin.LoginStatus.CONNECT\n ws_dat = (await self._api_call(\"/vila/api/bot/platform/getWebsocketInfo\"))\n # print(ws_dat)\n ws_url = ws_dat[\"websocket_url\"]\n async with connect(ws_url) as websocket:\n await self._send_ws_pack(websocket,ws_dat,biztype=7)\n tm = time.time()\n while not self._is_stop:\n reply = await self._ws_recv(websocket)\n if not reply:\n now_time = time.time()\n if now_time - tm > 30:\n tm = now_time\n await self._send_ws_pack(websocket,ws_dat,biztype=6)\n continue\n biztype = int.from_bytes(reply[24:28],byteorder='little',signed=False)\n if biztype == 7: # 登录返回\n login_reply = PLoginReply().parse(reply[32:])\n if login_reply.code == 0:\n print(\"mihoyo:ws连接成功\")\n self._login_status = SatoriLogin.LoginStatus.ONLINE\n continue\n else:\n print(\"mihoyo:ws连接失败\",login_reply.to_json())\n break\n elif biztype == 53:\n print(\"mihoyo:ws被踢下线\")\n pkoff = PKickOff().parse(reply[32:])\n print(\"mihoyo:\" + pkoff.reason)\n break\n elif biztype == 52:\n print(\"mihoyo:ws服务关机\")\n break\n elif biztype == 6:\n heart_reply = PHeartBeatReply().parse(reply[32:])\n if heart_reply.code != 0:\n print(\"mihoyo:ws心跳失败\")\n break\n elif biztype == 30001: # 正常处理\n evt = RobotEvent().parse(reply[32:]).to_dict()\n asyncio.create_task(self._event_deal(evt))\n\n async def _ws_server(self) -> None:\n while not self._is_stop:\n try:\n await self._ws_connect()\n except:\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n traceback.print_exc()\n await asyncio.sleep(3)\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n\n async def init_after(self) -> None:\n asyncio.create_task(self._ws_server())\n\n def _mihoyo_msg_to_satori(self,content_obj)->str:\n ret = \"\"\n entities = content_obj[\"content\"][\"entities\"]\n text = content_obj[\"content\"][\"text\"]\n l = len(text)\n i = 0\n while i < l:\n for en in entities:\n if en[\"offset\"] == i:\n print(en)\n i += en[\"length\"]\n if en[\"entity\"][\"type\"] == \"mention_all\": # 实际上收不到\n ret += \"<at type=\\\"all\\\"/>\"\n elif en[\"entity\"][\"type\"] == \"mentioned_robot\":\n ret += \"<at id=\\\"{}\\\"/>\".format(en[\"entity\"][\"bot_id\"])\n elif en[\"entity\"][\"type\"] == \"mentioned_user\":\n ret += \"<at id=\\\"{}\\\"/>\".format(en[\"entity\"][\"user_id\"])\n break\n else:\n ret += satori_to_plain(text[i])\n i += 1\n return ret\n async def _deal_group_message_event(self,data):\n extendData = data[\"extendData\"]\n\n sendMessage = extendData[\"sendMessage\"]\n user_id = sendMessage[\"fromUserId\"]\n villaId = sendMessage[\"villaId\"]\n roomId = sendMessage[\"roomId\"]\n\n villaRoomId = villaId + \"_\" + roomId\n\n content_obj = json.loads(sendMessage[\"content\"])\n\n extra_obj = json.loads(content_obj[\"user\"][\"extra\"])\n\n satori_msg = self._mihoyo_msg_to_satori(content_obj) # todo\n\n satori_evt = SatoriGroupMessageCreatedEvent(\n id=self._id,\n self_id=self._self_id,\n timestamp=int(data[\"sendAt\"]) * 1000,\n platform=\"mihoyo\",\n channel=SatoriChannel(\n id=villaRoomId,\n type=SatoriChannel.ChannelType.TEXT,\n ),\n message=SatoriMessage(\n id=data[\"id\"],\n content=satori_msg,\n created_at=int(sendMessage[\"sendAt\"])\n ),\n user=SatoriUser(\n id=user_id,\n name=sendMessage[\"nickname\"],\n avatar=content_obj[\"user\"][\"portraitUri\"]\n ),\n member=SatoriGuildMember(\n nick=sendMessage[\"nickname\"],\n avatar=content_obj[\"user\"][\"portraitUri\"]\n ),\n guild=SatoriGuild(\n id=villaId\n ),\n role=SatoriGuildRole(\n id=extra_obj[\"member_roles\"][\"name\"],\n name=extra_obj[\"member_roles\"][\"name\"]\n )\n )\n self._id += 1\n self._queue.put_nowait(satori_evt.to_dict())\n\n async def _event_deal(self,data:dict):\n try:\n event_type = data[\"type\"]\n if event_type == \"SendMessage\":\n await self._deal_group_message_event(data)\n except:\n print(traceback.format_exc())\n\n \n async def _api_call(self,path,data = None,villa_id = 0) -> dict:\n url:str = self._http_url + path\n headers = {\"x-rpc-bot_id\":self._self_id,\"x-rpc-bot_secret\":self._secret}\n if villa_id == 0:\n headers[\"x-rpc-bot_villa_id\"] = self._villa_id\n else:\n headers[\"x-rpc-bot_villa_id\"] = villa_id\n if data == None:\n async with httpx.AsyncClient() as client:\n return (await client.get(url,headers=headers)).json()[\"data\"]\n else:\n headers[\"Content-Type\"] = \"application/json\"\n async with httpx.AsyncClient() as client:\n ret = (await client.post(url,headers=headers,data=data)).json()\n if ret[\"retcode\"] != 0:\n print(\"mihoyo:\",ret)\n return ret[\"data\"]\n\n \n async def _satori_to_mihoyo(self,satori_obj,villa_id) -> [dict]:\n to_send_data = []\n last_type = 1\n for node in satori_obj:\n if isinstance(node,str):\n text = node\n if last_type == 1 and len(to_send_data) != 0:\n l = len(to_send_data)\n to_send_data[l - 1][\"text\"] += text\n else:\n to_send_data.append({\n \"type\":1,\n \"text\":text,\n \"entities\":[]\n })\n last_type = 1\n else:\n if node[\"type\"] == \"at\":\n type = get_json_or(node[\"attrs\"],\"type\",None)\n id = get_json_or(node[\"attrs\"],\"id\",None)\n if type == \"all\":\n text = \"@全体成员\"\n elif id != None:\n text = \"@\" + id\n else:\n continue\n\n if last_type != 1 or len(to_send_data) == 0:\n to_send_data.append({\n \"type\":1,\n \"text\":\"\",\n \"entities\":[]\n })\n last_type = 1\n\n l = len(to_send_data)\n ll = len(to_send_data[l - 1][\"text\"])\n to_send_data[l - 1][\"text\"] += text\n if type == \"all\":\n to_send_data[l - 1][\"entities\"].append({\n \"entity\": {\n \"type\": \"mention_all\"\n },\n \"length\":5,\n \"offset\":ll\n })\n else:\n if id.startswith(\"bot_\"):\n to_send_data[l - 1][\"entities\"].append({\n \"entity\": {\n \"type\": \"mentioned_robot\",\n \"bot_id\": id\n },\n \"length\":len(id) + 1,\n \"offset\":ll\n })\n else:\n to_send_data[l - 1][\"entities\"].append({\n \"entity\": {\n \"type\": \"mentioned_user\",\n \"user_id\": id\n },\n \"length\":len(id) + 1,\n \"offset\":ll\n })\n\n elif node[\"type\"] == \"img\":\n img_url:str = node[\"attrs\"][\"src\"]\n mihoyo_img_url = \"\"\n if img_url.startswith(\"data:image/\"):\n base64_start = img_url.find(\"base64,\")\n img_content = base64.b64decode(img_url[base64_start + 7:])\n else:\n async with httpx.AsyncClient() as client:\n img_content = (await client.get(img_url)).content\n ext = imghdr.what(file = \"\",h=img_content)\n m = hashlib.md5()\n m.update(img_content)\n headers = {\"x-rpc-bot_id\":self._self_id,\"x-rpc-bot_secret\":self._secret,\"x-rpc-bot_villa_id\":villa_id}\n upload_info_url = self._http_url + \"/vila/api/bot/platform/getUploadImageParams\"\n async with httpx.AsyncClient() as client:\n req = client.build_request(\"GET\",upload_info_url,json={\n \"md5\":m.hexdigest(),\n \"ext\":ext\n },headers=headers)\n file_params = (await client.send(req)).json()[\"data\"][\"params\"]\n files = {\n \"x:extra\":file_params[\"callback_var\"][\"x:extra\"],\n \"OSSAccessKeyId\":file_params[\"accessid\"],\n \"signature\":file_params[\"signature\"],\n \"success_action_status\":file_params[\"success_action_status\"],\n \"name\":file_params[\"name\"],\n \"callback\":file_params[\"callback\"],\n \"x-oss-content-type\":file_params[\"x_oss_content_type\"],\n \"key\":file_params[\"key\"],\n \"policy\":file_params[\"policy\"],\n \"Content-Disposition\":file_params[\"content_disposition\"],\n 'file':('test',img_content)\n }\n async with httpx.AsyncClient() as client:\n ret = (await client.post(file_params[\"host\"],files=files)).json()\n mihoyo_img_url = ret[\"data\"][\"url\"]\n to_send_data.append({\n \"type\":2,\n \"url\":mihoyo_img_url,\n })\n last_type = 2\n to_send_data2 = []\n for it in to_send_data:\n type = it[\"type\"]\n if type == 1:\n to_send_data2.append({\n \"object_name\":\"MHY:Text\",\n \"msg_content\":json.dumps({\n \"content\":{\n \"text\":it[\"text\"],\n \"entities\":it[\"entities\"]\n }\n })})\n elif type == 2:\n to_send_data2.append({\n \"object_name\":\"MHY:Image\",\n \"msg_content\":json.dumps({\n \"content\":{\n \"url\":it[\"url\"]\n }\n \n })})\n \n return to_send_data2\n \n async def create_message(self,platform:str,self_id:str,channel_id:str,content:str):\n '''发送消息'''\n villa_id = channel_id.split(\"_\")[0]\n satori_obj = parse_satori_html(content)\n to_sends = await self._satori_to_mihoyo(satori_obj,villa_id)\n to_ret = []\n # print(to_sends)\n for it in to_sends:\n it[\"room_id\"] = channel_id.split(\"_\")[1]\n ret = await self._api_call(\"/vila/api/bot/platform/sendMessage\",json.dumps(it),villa_id=villa_id)\n to_ret.append(SatoriMessage(id=ret[\"bot_msg_id\"],content=\"\").to_dict())\n return to_ret\n \n \n async def get_login(self,platform:Optional[str],self_id:Optional[str]) -> [dict]:\n '''获取登录信息,如果platform和self_id为空,那么应该返回一个列表'''\n satori_ret = SatoriLogin(\n status=self._login_status,\n user=SatoriUser(\n id=self._self_id,\n is_bot=True\n ),\n self_id=self._self_id,\n platform=\"mihoyo\"\n ).to_dict()\n if platform == None and self_id == None:\n return [satori_ret]\n else:\n return satori_ret\n\n async def get_guild_member(self,platform:Optional[str],self_id:Optional[str],guild_id:str,user_id:str) -> [dict]:\n '''获取群组成员信息'''\n url = self._http_url + \"/vila/api/bot/platform/getMember\"\n headers = {\"x-rpc-bot_id\":self._self_id,\"x-rpc-bot_secret\":self._secret,\"x-rpc-bot_villa_id\":guild_id}\n async with httpx.AsyncClient() as client:\n req = client.build_request(\"GET\",url,json={\n \"uid\":user_id\n },headers=headers)\n obret = (await client.send(req)).json()[\"data\"][\"member\"]\n satori_ret = SatoriGuildMember(\n user=SatoriUser(\n id=obret[\"basic\"][\"uid\"],\n name=obret[\"basic\"][\"nickname\"],\n avatar=obret[\"basic\"][\"avatar_url\"],\n is_bot=False\n ),\n nick=obret[\"basic\"][\"nickname\"],\n avatar=obret[\"basic\"][\"avatar_url\"],\n joined_at=int(obret[\"joined_at\"] + \"000\")\n ).to_dict()\n return satori_ret" }, { "identifier": "AdapterOnebot", "path": "onebot_adapter.py", "snippet": "class AdapterOnebot:\n def __init__(self,config = {}) -> None:\n '''用于初始化一些配置信息,尽量不要在这里阻塞,因为此处不具备异步环境,如果你需要读写配置文件,请在init_after中进行'''\n self._http_url = config[\"http_url\"]\n self._ws_url = config[\"ws_url\"]\n if \"access_token\" in config:\n self._access_token = config[\"access_token\"]\n else:\n self._access_token = None\n self._is_stop = False\n self._login_status = 3 # DISCONNECT\n self._queue = Queue(maxsize=100)\n self._id = 0\n\n def _cqarr_to_satori(self,cqarr):\n ret = \"\"\n for node in cqarr:\n if node[\"type\"] == \"text\":\n ret += satori_to_plain(node[\"data\"][\"text\"])\n elif node[\"type\"] == \"at\":\n qq = node[\"data\"][\"qq\"]\n if qq == \"all\":\n ret += \"<at type=\\\"all\\\"/>\"\n else:\n ret += \"<at id={}/>\".format(json.dumps(qq))\n elif node[\"type\"] == \"image\":\n url = node[\"data\"][\"url\"]\n ret += \"<img src={}/>\".format(json.dumps(url))\n return ret\n\n async def enable(self) -> None:\n '''适配器启用的时候会调用,可以不理,也可以没这个函数\n 配合下面的停用函数,适配器可以得到自己在整个系统中的状态,进而进行一些优化\n 如,如果适配器处于停用状态,适配器可以自行选择关闭网络连接,以节省资源,当然,也可以不理会\n '''\n pass\n\n async def disable(self) -> None:\n '''适配器停用的时候会调用,可以不理,也可以没这个函数'''\n pass\n \n async def release(self) -> None:\n '''适配器释放的时候会调用一次,应该在这里停用ws连接\n 一般认为,适配器会和真正的协议端建立连接,所以,这个函数大多数时候是需要写的\n 但是,这个函数允许资源延迟释放,只要能释放就行\n 你可以在这个函数里面进行数据保存之类的,这种用途下,请阻塞这个函数,直到保存完成\n '''\n self._is_stop = True\n\n async def get_msg(self) -> dict:\n '''阻塞并等待消息返回,如果你的适配器不具备接收消息的能力,请不要写这个函数'''\n return await self._queue.get()\n\n async def init_after(self) -> None:\n '''适配器创建之后会调用一次,应该在这里进行ws连接等操作,如果不需要,可以不写'''\n async def _ws_server(self:AdapterOnebot) -> None:\n while not self._is_stop:\n try:\n self._login_status = 2 # CONNECT\n async with connect(self._ws_url) as websocket:\n print(\"onebot:ws已经连接\")\n self._login_status = 1 # ONLINE\n try:\n while True:\n try:\n reply = await asyncio.wait_for(websocket.recv(),0.1)\n await self._event_deal(json.loads(reply))\n except asyncio.TimeoutError:\n if self._is_stop:\n await websocket.close()\n except asyncio.QueueFull:\n print(\"队列满\")\n except Exception as e:\n print(e) \n except Exception as e:\n print(e)\n print(\"onebot:ws连接已经断开\")\n self._login_status = 3 # DISCONNECT\n asyncio.create_task(_ws_server(self))\n \n async def _event_deal(self,evt:dict):\n '''自己定义的事件转化函数'''\n post_type = evt[\"post_type\"]\n if post_type == \"message\":\n message_type = evt[\"message_type\"]\n sender = evt[\"sender\"]\n if message_type == \"group\":\n channel_obj = {\n \"id\":\"GROUP_\"+str(evt[\"group_id\"]),\n \"type\":0,\n \"name\":None,\n \"parent_id\":None\n }\n guild_obj = {\n \"id\":\"GROUP_\"+str(evt[\"group_id\"]),\n \"name\":None,\n \"avatar\":None\n }\n user_obj = {\n \"id\":str(evt[\"user_id\"]),\n \"name\":get_json_or(sender,\"nickname\",None),\n \"nick\":get_json_or(sender,\"nickname\",None),\n \"avatar\":get_json_or(sender,\"avatar\",None),\n \"is_bot\":None\n }\n joined_at = get_json_or(sender,\"join_time\",None)\n if joined_at:\n joined_at = int(str(joined_at) + \"000\")\n member_obj = {\n \"nick\":get_json_or(sender,\"card\",None),\n \"avatar\":get_json_or(sender,\"avatar\",None),\n \"joined_at\":joined_at\n }\n message_obj = {\n \"id\":str(evt[\"message_id\"]),\n \"content\":self._cqarr_to_satori(_cqmsg_to_arr(evt[\"message\"])),\n \"created_at\":int(str(evt[\"time\"] ) + \"000\")\n }\n role_obj = {\n \"id\":get_json_or(sender, \"role\",\"member\"),\n \"name\":get_json_or(sender,\"role\",\"member\")\n }\n satori_evt = {\n \"id\":self._id,\n \"type\":\"message-created\",\n \"platform\":\"onebot\",\n \"self_id\":str(evt[\"self_id\"]),\n \"timestamp\":int(str(evt[\"time\"] ) + \"000\"),\n \"channel\":channel_obj,\n \"guild\":guild_obj,\n \"member\":member_obj,\n \"message\":message_obj,\n \"role\":role_obj,\n \"user\":user_obj\n }\n self._id += 1\n self._queue.put_nowait(satori_evt)\n elif message_type == \"private\":\n channel_obj = {\n \"id\":str(evt[\"user_id\"]),\n \"type\":1,\n \"name\":None,\n \"parent_id\":None\n }\n user_obj = {\n \"id\":str(evt[\"user_id\"]),\n \"name\":get_json_or(sender,\"nickname\",None),\n \"nick\":get_json_or(sender,\"nickname\",None),\n \"avatar\":get_json_or(sender,\"avatar\",None),\n \"is_bot\":None\n }\n joined_at = get_json_or(sender,\"join_time\",None)\n if joined_at:\n joined_at = int(str(joined_at) + \"000\")\n message_obj = {\n \"id\":str(evt[\"message_id\"]),\n \"content\":self._cqarr_to_satori(_cqmsg_to_arr(evt[\"message\"])),\n \"created_at\":int(str(evt[\"time\"] ) + \"000\")\n }\n satori_evt = {\n \"id\":self._id,\n \"type\":\"message-created\",\n \"platform\":\"onebot\",\n \"self_id\":str(evt[\"self_id\"]),\n \"timestamp\":int(str(evt[\"time\"] ) + \"000\"),\n \"channel\":channel_obj,\n \"message\":message_obj,\n \"user\":user_obj\n }\n self._id += 1\n self._queue.put_nowait(satori_evt)\n elif post_type == \"notice\":\n notice_type = evt[\"notice_type\"]\n if notice_type == \"group_increase\":\n guild_obj = {\n \"id\":\"GROUP_\"+str(evt[\"group_id\"]),\n \"name\":None,\n \"avatar\":None\n }\n member_obj = {\n \"nick\":None,\n \"avatar\":get_json_or(evt,\"avatar\",None),\n \"joined_at\":int(str(evt[\"time\"] ) + \"000\")\n }\n user_obj = {\n \"id\":str(evt[\"user_id\"]),\n \"name\":None,\n \"nick\":None,\n \"avatar\":None,\n \"is_bot\":None\n }\n satori_evt = {\n \"id\":self._id,\n \"type\":\"guild-member-added\",\n \"platform\":\"onebot\",\n \"self_id\":str(evt[\"self_id\"]),\n \"timestamp\":int(str(evt[\"time\"] ) + \"000\"),\n \"guild\":guild_obj,\n \"member\":member_obj,\n \"user\":user_obj\n }\n self._id += 1\n self._queue.put_nowait(satori_evt)\n\n async def _api_call(self,path,data) -> dict:\n url:str = self._http_url + path\n if self._access_token:\n headers = {\"Authorization\":\"Bearer {}\".format(self._access_token)}\n else:\n headers = {}\n async with httpx.AsyncClient() as client:\n # headers[\"Content-Type\"] = \"application/json\"\n return (await client.post(url,headers=headers,data=data)).json()\n \n async def _satori_to_cq(self,satori_obj) -> str:\n ret = \"\"\n for node in satori_obj:\n if isinstance(node,str):\n ret += _cq_text_encode(node)\n else:\n if node[\"type\"] == \"at\":\n type = get_json_or(node[\"attrs\"],\"type\",None)\n id = get_json_or(node[\"attrs\"],\"id\",None)\n if type == \"all\":\n ret += \"[CQ:at,qq=all]\"\n elif id != None:\n ret += \"[CQ:at,qq={}]\".format(_cq_params_encode(id))\n elif node[\"type\"] == \"img\":\n img_url = node[\"attrs\"][\"src\"]\n if img_url.startswith(\"data:image/\"):\n base64_start = img_url.find(\"base64,\")\n img_url = \"base64://\" + img_url[base64_start + 7:]\n ret += \"[CQ:image,file={}]\".format(_cq_params_encode(img_url)) \n\n return ret\n\n\n async def create_message(self,platform:str,self_id:str,channel_id:str,content:str):\n '''发送消息'''\n satori_obj = parse_satori_html(content)\n to_send = await self._satori_to_cq(satori_obj)\n if channel_id.startswith(\"GROUP_\"):\n group_id = int(channel_id[6:])\n ret = await self._api_call(\"/send_group_msg\",{\"group_id\":group_id,\"message\":to_send})\n return [{\"id\":str(ret[\"data\"][\"message_id\"]),\"content\":\"\"}]\n else:\n user_id = int(channel_id)\n ret = await self._api_call(\"/send_private_msg\",{\"user_id\":user_id,\"message\":to_send})\n return [{\"id\":str(ret[\"data\"][\"message_id\"]),\"content\":\"\"}]\n \n async def get_login(self,platform:Optional[str],self_id:Optional[str]) -> [dict]:\n '''获取登录信息,如果platform和self_id为空,那么应该返回一个列表'''\n obret = (await self._api_call(\"/get_login_info\",{}))[\"data\"]\n satori_ret = {\n \"user\":{\n \"id\":str(obret[\"user_id\"]),\n \"name\":obret[\"nickname\"],\n \"nick\":obret[\"nickname\"],\n \"avatar\":get_json_or(obret,\"avatar\",None),\n \"is_bot\":None\n },\n \"self_id\":str(obret[\"user_id\"]),\n \"platform\":\"onebot\",\n \"status\":self._login_status,\n }\n if platform == None and self_id == None:\n return [satori_ret]\n else:\n return satori_ret\n \n async def get_guild_member(self,platform:Optional[str],self_id:Optional[str],guild_id:str,user_id:str) -> [dict]:\n '''获取群组成员信息'''\n obret = (await self._api_call(\"/get_group_member_info\",{\n \"group_id\":int(guild_id[6:]),\n \"user_id\":int(user_id)\n }))[\"data\"]\n joined_at = get_json_or(obret,\"join_time\",None)\n if joined_at:\n joined_at = int(str(joined_at) + \"000\")\n satori_ret = {\n \"user\":{\n \"id\":str(obret[\"user_id\"]),\n \"name\":get_json_or(obret,\"nickname\",None),\n \"nick\":get_json_or(obret,\"card\",None),\n \"avatar\":get_json_or(obret,\"avatar\",None),\n \"is_bot\":None\n },\n \"nick\":get_json_or(obret,\"card\",None),\n \"avatar\":get_json_or(obret,\"avatar\",None),\n \"joined_at\":joined_at,\n }\n return satori_ret" }, { "identifier": "Config", "path": "config.py", "snippet": "class Config:\n def __init__(self) -> None:\n self.botlist:list = []\n self.web_port:int = 8080\n self.web_host:str = \"127.0.0.1\"\n self.access_token:str = \"\"\n \n async def read_config(self):\n async with aiofiles.open('config.json', mode='r') as f:\n json_dat = json5.loads(await f.read())\n self.botlist = json_dat[\"botlist\"]\n self.web_port = json_dat[\"web_port\"]\n self.web_host = json_dat[\"web_host\"]\n self.access_token = json_dat[\"access_token\"]" }, { "identifier": "AdapterQQ", "path": "qq_adapter.py", "snippet": "class AdapterQQ:\n def __init__(self,config = {}) -> None:\n '''用于初始化一些配置信息,尽量不要在这里阻塞,因为此处不具备异步环境,如果你需要读写配置文件,请在init_after中进行'''\n self._botqq = config[\"botqq\"]\n self._appid = config[\"appid\"]\n self._token = config[\"token\"]\n if \"withgroup\" in config:\n self._withgroup = config[\"withgroup\"]\n else:\n self._withgroup = None\n self._appsecret = config[\"appsecret\"]\n self._http_url = \"https://api.sgroup.qq.com\"\n self._is_stop = False\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n self._queue = Queue(maxsize=100)\n self._id = 0\n self._sn = None\n self._self_id = None\n self._access_token = None\n self._expires_in = 0\n self.msgid_map = dict()\n # self._self_name = None\n\n\n async def enable(self) -> None:\n '''适配器启用的时候会调用,可以不理,也可以没这个函数\n 配合下面的停用函数,适配器可以得到自己在整个系统中的状态,进而进行一些优化\n 如,如果适配器处于停用状态,适配器可以自行选择关闭网络连接,以节省资源,当然,也可以不理会\n '''\n pass\n\n async def disable(self) -> None:\n '''适配器停用的时候会调用,可以不理,也可以没这个函数'''\n pass\n \n async def release(self) -> None:\n '''适配器释放的时候会调用一次,应该在这里停用ws连接\n 一般认为,适配器会和真正的协议端建立连接,所以,这个函数大多数时候是需要写的\n 但是,这个函数允许资源延迟释放,只要能释放就行\n 你可以在这个函数里面进行数据保存之类的,这种用途下,请阻塞这个函数,直到保存完成\n '''\n self._is_stop = True\n\n async def get_msg(self) -> dict:\n '''阻塞并等待消息返回,如果你的适配器不具备接收消息的能力,请不要写这个函数'''\n return await self._queue.get()\n \n\n async def _ws_recv(self,websocket):\n try:\n reply = await asyncio.wait_for(websocket.recv(),0.1)\n return reply\n except asyncio.TimeoutError:\n return None\n\n async def _ws_connect(self):\n self._login_status = SatoriLogin.LoginStatus.CONNECT\n ws_url = (await self._api_call(\"/gateway\"))[\"url\"]\n async with connect(ws_url) as websocket:\n tm = time.time()\n while not self._is_stop:\n reply = await self._ws_recv(websocket)\n if not reply:\n now_time = time.time()\n if now_time - tm > 30:\n tm = now_time\n await websocket.send(json.dumps({\"op\": 1,\"d\": self._sn}))\n continue\n js = json.loads(reply)\n op = js[\"op\"]\n if op == 0: # 事件\n self._sn = js[\"s\"]\n t = js[\"t\"]\n if t == \"READY\":\n print(\"qq:ws连接成功\")\n print(json.dumps(js))\n self._login_status = SatoriLogin.LoginStatus.ONLINE\n else:\n print(json.dumps(js))\n asyncio.create_task(self._deal_event(js))\n elif op == 1: # 心跳\n await websocket.send(json.dumps({\"op\":11}))\n elif op == 7: # 重连\n print(\"qq:服务端要求重连\")\n break\n elif op == 9: # 参数错误\n print(\"qq:参数错误:\",json.dumps(js))\n break\n elif op == 10: # ws建立成功\n if self._withgroup:\n await websocket.send(json.dumps({\n \"op\":2,\n \"d\":{\n \"token\":\"QQBot {}\".format(self._access_token),\n \"intents\":0 | (1 << 0) | (1 << 1) | (1 << 30) | (1 << 25),\n \"shard\":[0, 1],\n }\n }))\n else:\n await websocket.send(json.dumps({\n \"op\":2,\n \"d\":{\n \"token\":\"QQBot {}\".format(self._access_token),\n \"intents\":0 | (1 << 0) | (1 << 1) | (1 << 30),\n \"shard\":[0, 1],\n }\n }))\n elif op == 11: # HTTP Callback ACK\n pass\n\n async def _ws_server(self) -> None:\n while not self._is_stop:\n try:\n await self._ws_connect()\n except:\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n print(traceback.format_exc())\n await asyncio.sleep(3)\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n\n async def _token_refresh(self):\n async with httpx.AsyncClient() as client:\n if not self._expires_in or int(self._expires_in) < 60 * 5:\n url = \"https://bots.qq.com/app/getAppAccessToken\"\n ret = (await client.post(url,json={\n \"appId\":self._appid,\n \"clientSecret\":self._appsecret\n })).json()\n self._access_token = ret[\"access_token\"]\n self._expires_in = ret[\"expires_in\"]\n # print(ret)\n\n async def _qqarr_to_satori(self,qqmsg_arr):\n ret = \"\"\n for it in qqmsg_arr:\n if it[\"type\"] == \"text\":\n ret += satori_to_plain(it[\"data\"])\n else:\n if it[\"data\"].startswith(\"<@!\"):\n user_id = it[\"data\"][3:len(it[\"data\"]) - 1]\n ret += \"<at id=\\\"{}\\\">\".format(satori_to_plain(user_id))\n elif it[\"data\"].startswith(\"<@\"):\n user_id = it[\"data\"][2:len(it[\"data\"]) - 1]\n ret += \"<at id=\\\"{}\\\">\".format(satori_to_plain(user_id))\n return ret\n \n async def _deal_channel_event(self,data):\n qqmsg_arr = _qqmsg_to_arr(data[\"content\"])\n # print(\"qqmsg_arr\",qqmsg_arr)\n satori_msg = await self._qqarr_to_satori(qqmsg_arr)\n self.msgid_map[\"CHANNEL_\"+data[\"channel_id\"]] = data[\"id\"]\n satori_evt = SatoriGroupMessageCreatedEvent(\n id=self._id,\n self_id=self._self_id,\n timestamp=int(time.mktime(time.strptime(data[\"timestamp\"], \"%Y-%m-%dT%H:%M:%S%z\"))) * 1000,\n platform=\"qq_guild\",\n channel=SatoriChannel(\n id=\"CHANNEL_\"+data[\"channel_id\"],\n type=SatoriChannel.ChannelType.TEXT,\n ),\n message=SatoriMessage(\n id=data[\"id\"],\n content=satori_msg,\n created_at=int(time.mktime(time.strptime(data[\"timestamp\"], \"%Y-%m-%dT%H:%M:%S%z\"))) * 1000\n ),\n user=SatoriUser(\n id=data[\"author\"][\"id\"],\n name=data[\"author\"][\"username\"],\n avatar=data[\"author\"][\"avatar\"],\n is_bot=data[\"author\"][\"bot\"]\n ),\n member=SatoriGuildMember(\n nick=data[\"member\"][\"nick\"],\n avatar=data[\"author\"][\"avatar\"],\n joined_at=int(time.mktime(time.strptime(data[\"member\"][\"joined_at\"], \"%Y-%m-%dT%H:%M:%S%z\"))) * 1000\n ),\n guild=SatoriGuild(\n id=data[\"guild_id\"]\n ),\n role=SatoriGuildRole(\n id=json.dumps(sorted(data[\"member\"][\"roles\"]))\n )\n )\n self._id += 1\n self._queue.put_nowait(satori_evt.to_dict())\n\n async def _deal_group_event(self,data):\n qqmsg_arr = _qqmsg_to_arr(data[\"content\"])\n # print(\"qqmsg_arr\",qqmsg_arr)\n satori_msg = await self._qqarr_to_satori(qqmsg_arr)\n self.msgid_map[\"GROUP_\"+data[\"group_id\"]] = data[\"id\"]\n satori_evt = SatoriGroupMessageCreatedEvent(\n id=self._id,\n self_id=self._botqq,\n timestamp=int(time.mktime(time.strptime(data[\"timestamp\"], \"%Y-%m-%dT%H:%M:%S%z\"))) * 1000,\n platform=\"qq_group\",\n channel=SatoriChannel(\n id=\"GROUP_\"+data[\"group_id\"],\n type=SatoriChannel.ChannelType.TEXT,\n ),\n message=SatoriMessage(\n id=data[\"id\"],\n content=satori_msg,\n created_at=int(time.mktime(time.strptime(data[\"timestamp\"], \"%Y-%m-%dT%H:%M:%S%z\"))) * 1000\n ),\n user=SatoriUser(\n id=data[\"author\"][\"id\"]\n ),\n member=SatoriGuildMember(\n ),\n guild=SatoriGuild(\n id=\"GROUP_\"+data[\"group_id\"]\n ),\n role=SatoriGuildRole(\n id=\"unkonw\",\n name=\"unkonw\"\n )\n )\n self._id += 1\n self._queue.put_nowait(satori_evt.to_dict())\n\n async def _deal_event(self,event):\n try:\n type = event[\"t\"]\n if type == \"AT_MESSAGE_CREATE\":\n d = event[\"d\"]\n if (\"channel_id\" in d) and d[\"channel_id\"]:\n await self._deal_channel_event(d)\n else:\n if type == \"GROUP_AT_MESSAGE_CREATE\":\n d = event[\"d\"]\n if (\"group_id\" in d) and d[\"group_id\"]:\n await self._deal_group_event(d)\n except:\n print(traceback.format_exc())\n\n async def _token_refresh_task(self):\n while True:\n try:\n await self._token_refresh()\n index = 0\n while index < 60: # 每60秒检测一次token是否过期\n await asyncio.sleep(1)\n if self._is_stop:\n break\n index += 1\n if self._is_stop:break\n except:\n print(traceback.format_exc())\n\n async def init_after(self) -> None:\n '''适配器创建之后会调用一次,应该在这里进行ws连接等操作,如果不需要,可以不写'''\n try:\n await self._token_refresh()\n except:\n print(traceback.format_exc())\n asyncio.create_task(self._token_refresh_task())\n asyncio.create_task(self._ws_server())\n\n async def _api_call(self,path,data = None) -> dict:\n url:str = self._http_url + path\n headers = {\"Authorization\":\"QQBot {}\".format(self._access_token),\"X-Union-Appid\":self._appid}\n if data == None:\n async with httpx.AsyncClient() as client:\n return (await client.get(url,headers=headers)).json()\n else:\n async with httpx.AsyncClient() as client:\n ret = (await client.post(url,headers=headers,json=data))\n # print(ret.content)\n return ret.json()\n\n def _make_qq_text(self,text:str):\n ret = text\n ret = ret.replace(\"&\",\"&amp;\")\n ret = ret.replace(\"<\",\"&lt;\")\n ret = ret.replace(\">\",\"&gt;\")\n return ret\n \n async def _satori_to_qq(self,satori_obj,platform = \"qq_guild\") -> [dict]:\n to_reply_id = None\n ret_text = \"\"\n ret_img = []\n for node in satori_obj:\n if isinstance(node,str):\n text = self._make_qq_text(node)\n ret_text += text\n else:\n if node[\"type\"] == \"at\":\n type = get_json_or(node[\"attrs\"],\"type\",None)\n id = get_json_or(node[\"attrs\"],\"id\",None)\n if type == \"all\":\n # 注意,机器人不支持at all,不能发,也不能收,这里假装at all了\n ret_text += \"@全体成员\"\n # text = \"<@everyone>\"\n elif id != None:\n ret_text += \"<@{}>\".format(self._make_qq_text(id))\n elif node[\"type\"] == \"img\":\n img_url:str = node[\"attrs\"][\"src\"]\n if img_url.startswith(\"data:image/\"):\n base64_start = img_url.find(\"base64,\")\n img_content = base64.b64decode(img_url[base64_start + 7:])\n ret_img.append(img_content)\n else:\n if platform == \"qq_guild\":\n async with httpx.AsyncClient() as client:\n img_content = (await client.get(img_url)).content\n ret_img.append(img_content)\n else:\n ret_img.append(img_url)\n elif node[\"type\"] == \"passive\":\n to_reply_id = node[\"attrs\"][\"id\"]\n \n ret_vec = []\n ret_vec.append({\n \"content\":ret_text,\n \"file_image\":None,\n \"to_reply_id\":to_reply_id\n })\n if len(ret_img) != 0:\n ret_vec[0][\"file_image\"] = ret_img[0]\n for img in ret_img[1:]:\n ret_vec.append({\n \"content\":\"\",\n \"file_image\":img,\n \"to_reply_id\":to_reply_id\n })\n return ret_vec\n \n async def create_message(self,platform:str,self_id:str,channel_id:str,content:str):\n '''发送消息'''\n to_reply_id = self.msgid_map[channel_id]\n satori_obj = parse_satori_html(content)\n to_sends = await self._satori_to_qq(satori_obj,platform)\n # print(to_sends)\n if channel_id.startswith(\"CHANNEL_\") and platform == \"qq_guild\":\n channel_id = channel_id[8:]\n to_ret = []\n for it in to_sends:\n if it[\"to_reply_id\"]:to_reply_id = it[\"to_reply_id\"]\n async with httpx.AsyncClient() as client:\n headers = {\"Authorization\":\"QQBot {}\".format(self._access_token),\"X-Union-Appid\":self._appid,\"Accept\":\"application/json\"}\n url:str = self._http_url + \"/channels/{}/messages\".format(channel_id)\n data = {\n \"msg_id\":to_reply_id,\n \"content\":it[\"content\"]\n }\n if it[\"file_image\"]:\n ret = (await client.post(url,headers=headers,data=data,files={\"file_image\":it[\"file_image\"]})).json()\n else:\n ret = (await client.post(url,headers=headers,json=data)).json()\n # print(ret)\n to_ret.append(SatoriMessage(id=ret[\"id\"],content=\"\").to_dict())\n return to_ret\n elif channel_id.startswith(\"GROUP_\") and platform == \"qq_group\":\n channel_id = channel_id[6:]\n to_ret = []\n msg_seq = 1\n for it in to_sends:\n if it[\"to_reply_id\"]:to_reply_id = it[\"to_reply_id\"]\n async with httpx.AsyncClient() as client:\n headers = {\"Authorization\":\"QQBot {}\".format(self._access_token),\"X-Union-Appid\":self._appid,\"Accept\":\"application/json\"}\n url:str = self._http_url + \"/v2/groups/{}/messages\".format(channel_id)\n data = {\n \"msg_id\":to_reply_id,\n \"content\":it[\"content\"],\n \"msg_type\":0,\n \"msg_seq\":msg_seq,\n # \"image\": 目前暂不支持\n }\n msg_seq += 1\n ret = (await client.post(url,headers=headers,json=data)).json()\n # print(ret)\n to_ret.append(SatoriMessage(id=ret[\"msg_id\"],content=\"\").to_dict())\n return to_ret\n \n async def get_login(self,platform:Optional[str],self_id:Optional[str]) -> [dict]:\n '''获取登录信息,如果platform和self_id为空,那么应该返回一个列表'''\n\n if platform == \"qq_group\":\n return SatoriLogin(\n status=self._login_status,\n user=SatoriUser(\n id=self._botqq,\n is_bot=True\n ),\n self_id=self._botqq,\n platform=\"qq_group\"\n ).to_dict()\n else: \n obret = (await self._api_call(\"/users/@me\"))\n satori_ret = SatoriLogin(\n status=self._login_status,\n user=SatoriUser(\n id=obret[\"id\"],\n name=obret[\"username\"],\n avatar=obret[\"avatar\"],\n is_bot=True\n ),\n self_id=obret[\"id\"],\n platform=\"qq_guild\"\n ).to_dict()\n self._self_id = obret[\"id\"]\n if platform == \"qq_guild\":\n return satori_ret\n elif platform == None:\n if not self._withgroup:\n return [satori_ret]\n else:\n return [satori_ret,SatoriLogin(\n status=self._login_status,\n user=SatoriUser(\n id=self._botqq,\n is_bot=True\n ),\n self_id=self._botqq,\n platform=\"qq_group\"\n ).to_dict()]\n \n async def get_guild_member(self,platform:Optional[str],self_id:Optional[str],guild_id:str,user_id:str) -> [dict]:\n '''获取群组成员信息'''\n if platform == \"qq_guild\":\n url = \"/guilds/{}/members/{}\".format(guild_id,user_id)\n obret = (await self._api_call(url))\n satori_ret = SatoriGuildMember(\n user=SatoriUser(\n id=obret[\"user\"][\"id\"],\n name=obret[\"user\"][\"username\"],\n avatar=obret[\"user\"][\"avatar\"],\n is_bot=obret[\"user\"][\"bot\"]\n ),\n nick=get_json_or(obret,\"nick\",None),\n avatar=obret[\"user\"][\"avatar\"],\n joined_at=int(time.mktime(time.strptime(obret[\"joined_at\"], \"%Y-%m-%dT%H:%M:%S%z\"))) * 1000\n ).to_dict()\n return satori_ret" }, { "identifier": "remove_json_null", "path": "tool.py", "snippet": "def remove_json_null(js) -> dict:\n '''将json中的None字段删除'''\n if isinstance(js,dict):\n st = {}\n for key in js:\n if js[key] != None:\n st[key] = remove_json_null(js[key])\n return st\n elif isinstance(js,list):\n lst = []\n for it in js:\n lst.append(remove_json_null(it))\n return lst\n else:\n return js" } ]
import asyncio import aiohttp import json import uuid from kook_adapter import AdapterKook from mihoyo_adapter import AdapterMihoyo from onebot_adapter import AdapterOnebot from config import Config from aiohttp import web from qq_adapter import AdapterQQ from tool import remove_json_null
16,772
class Satori: def __init__(self) -> None: self._config:Config = Config() self.adapterlist = [] self.wsmap = {} self._evt_id = 100 async def _get_adapter(self,platform,self_id): ''' 用于获取适配器 ''' for adapter in self.adapterlist: info = adapter["info"] for bot in info: if self_id == bot["self_id"] and bot["platform"] == platform: return adapter["adapter"] return None async def ws_send_json(ws,js) -> None: js = remove_json_null(js) print("--------ws_send_json",json.dumps(js)) await ws.send_json(js) async def _handle_http_normal(self,request:web.Request): print("----http normal",request) '''在这里处理普通api调用''' # 鉴权 if self._config.access_token != "": if request.headers.get("Authorization") != "Bearer " + self._config.access_token: print("token err") return web.Response(text="token err") method = request.url.path platform = request.headers.get("X-Platform") self_id = request.headers.get("X-Self-ID")
class Satori: def __init__(self) -> None: self._config:Config = Config() self.adapterlist = [] self.wsmap = {} self._evt_id = 100 async def _get_adapter(self,platform,self_id): ''' 用于获取适配器 ''' for adapter in self.adapterlist: info = adapter["info"] for bot in info: if self_id == bot["self_id"] and bot["platform"] == platform: return adapter["adapter"] return None async def ws_send_json(ws,js) -> None: js = remove_json_null(js) print("--------ws_send_json",json.dumps(js)) await ws.send_json(js) async def _handle_http_normal(self,request:web.Request): print("----http normal",request) '''在这里处理普通api调用''' # 鉴权 if self._config.access_token != "": if request.headers.get("Authorization") != "Bearer " + self._config.access_token: print("token err") return web.Response(text="token err") method = request.url.path platform = request.headers.get("X-Platform") self_id = request.headers.get("X-Self-ID")
adapter:AdapterOnebot = await self._get_adapter(platform,self_id)
2
2023-12-03 13:53:47+00:00
24k