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
mikeshardmind/wakfu-utils
wakautosolver/versioned_entrypoints.py
[ { "identifier": "encode", "path": "wakautosolver/b2048/encoder.py", "snippet": "def encode(bys: bytes, /) -> str:\n ret = StringIO()\n stage = 0\n remaining = 0\n\n for byte in bys:\n need = 11 - remaining\n if need < 8:\n remaining = 8 - need\n index = (s...
import traceback import zlib from collections.abc import Callable from typing import Literal from msgspec import Struct, field, msgpack from msgspec.structs import asdict from .b2048 import encode as b2048encode from .object_parsing import load_item_source_data from .restructured_types import DUMMY_MAX, DUMMY_MIN, ClassElements, ElementsEnum, Priority, StatPriority, Stats from .restructured_types import SetMaximums as RealSetMaxs from .restructured_types import SetMinimums as RealSetMins from .solver import ImpossibleStatError, SolveError, solve, v1Config from .wakforge_buildcodes import Buildv1 as WFBuild
7,674
ignore_existing_items: bool = False forbidden_sources: list[Literal["arch", "horde", "pvp", "ultimate_boss"]] = field(default_factory=list) stats_maxs: SetMaximums = field(default_factory=SetMaximums) class v2Result(Struct): build_code: str | None = None error_code: str | None = None item_ids: list[int] = field(default_factory=list) debug_info: str | None = None def compressed_encode(obj: object) -> str: compressor = zlib.compressobj(level=9, wbits=-15) packed = msgpack.encode(obj) return b2048encode(compressor.compress(packed) + compressor.flush()) def partial_solve_v2( *, build_code: str, config: v2Config, progress_callback: Callable[[int, int], None] | None = None, ) -> v2Result: # pyodide proxies aren't actually lists... config.allowed_rarities = [i for i in config.allowed_rarities if i] config.forbidden_items = [i for i in config.forbidden_items if i] config.forbidden_sources = [s for s in config.forbidden_sources if s] # This may look redundant, but it's exceptionally cheap validation try: config = msgpack.decode(msgpack.encode(config), type=v2Config) except Exception as exc: # noqa: BLE001 msg = traceback.format_exception(exc) return v2Result(None, "Invalid config (get debug info if opening an issue)", debug_info=compressed_encode(msg)) target_stats = config.target_stats.to_real() item_sources = load_item_source_data() forbidden_ids: set[int] = set() for source in config.forbidden_sources: forbidden_ids |= getattr(item_sources, source) forbidden_ids -= item_sources.non_finite_arch_horde config.forbidden_items.extend(forbidden_ids) if not config.objectives.is_valid: msg = ("objectives", config.objectives) return v2Result(None, "Invalid config (get debug info if opening an issue)", debug_info=compressed_encode(msg)) build = WFBuild.from_code(build_code) if config.ignore_existing_items: build.clear_items() stats = build.get_allocated_stats().to_stat_values(build.classenum) item_ids = [i.item_id for i in build.get_items() if i.item_id > 0] ap = target_stats.ap - stats.ap mp = target_stats.mp - stats.mp wp = target_stats.wp - stats.wp ra = target_stats.ra - stats.ra forbidden_rarities = [i for i in range(1, 8) if i not in config.allowed_rarities] # TODO: modify internals to not need this level of wrapping lookup: dict[Priority, Literal["full", "half", "none"]] = { Priority.full_negative_only: "full", Priority.half_negative_only: "half", } cfg = v1Config( lv=build.level, wakfu_class=build.classenum, ap=ap, mp=mp, wp=wp, ra=ra, stat_minimums=target_stats, stat_maximums=config.stats_maxs.to_real(), base_stats=stats, baseap=stats.ap, basemp=stats.mp, basera=stats.ra, bawewp=stats.wp, bcrit=stats.critical_hit, bcmast=stats.critical_mastery, bmast=stats.elemental_mastery, num_mastery=config.objectives.elements.bit_count(), forbid_rarity=forbidden_rarities, idforce=item_ids, dist=config.objectives.distance_mastery == Priority.prioritized, melee=config.objectives.melee_mastery == Priority.prioritized, heal=config.objectives.heal_mastery == Priority.prioritized, zerk=config.objectives.berserk_mastery == Priority.prioritized, rear=config.objectives.rear_mastery == Priority.prioritized, negrear=lookup.get(config.objectives.rear_mastery, "none"), negzerk=lookup.get(config.objectives.berserk_mastery, "none"), dry_run=config.dry_run, hard_cap_depth=35, tolerance=_adaptive_tolerance_map.get(build.level, 14), search_depth=1, elements=config.objectives.elements, ) try: result = solve(cfg, progress_callback=progress_callback) best = result[0] except ImpossibleStatError as exc: return v2Result(None, exc.args[0], debug_info=None) except (IndexError, SolveError): return v2Result(None, "No possible solution found", debug_info=None) except Exception as exc: # noqa: BLE001 msg = traceback.format_exception(exc) return v2Result(None, "Unknown error, see debug info", debug_info=compressed_encode(msg)) score, found_items = best found_item_ids = [i.item_id for i in found_items] if config.dry_run: return v2Result(None, None, found_item_ids, None) ecount = config.objectives.elements.bit_count()
""" This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Copyright (C) 2023 Michael Hall <https://github.com/mikeshardmind> """ from __future__ import annotations ClassNames = Literal[ "Feca", "Osa", "Enu", "Sram", "Xel", "Eca", "Eni", "Iop", "Cra", "Sadi", "Sac", "Panda", "Rogue", "Masq", "Ougi", "Fog", "Elio", "Hupper", ] _adaptive_tolerance_map: dict[int, int] = { 20: 20, 35: 35, 50: 50, 65: 30, 80: 30, 95: 30, 110: 30, 125: 15, 140: 15, 155: 15, 170: 15, 185: 15, 200: 14, 215: 15, 230: 14, } v1Result = tuple[list[int] | None, str | None] # Exists because versioning class SetMinimums(Struct, frozen=True, gc=True): ap: int = DUMMY_MIN mp: int = DUMMY_MIN wp: int = DUMMY_MIN ra: int = DUMMY_MIN crit: int = DUMMY_MIN crit_mastery: int = DUMMY_MIN elemental_mastery: int = DUMMY_MIN one_element_mastery: int = DUMMY_MIN two_element_mastery: int = DUMMY_MIN three_element_mastery: int = DUMMY_MIN distance_mastery: int = DUMMY_MIN rear_mastery: int = DUMMY_MIN heal_mastery: int = DUMMY_MIN beserk_mastery: int = DUMMY_MIN melee_mastery: int = DUMMY_MIN control: int = DUMMY_MIN block: int = DUMMY_MIN fd: int = DUMMY_MIN heals_performed: int = DUMMY_MIN lock: int = DUMMY_MIN dodge: int = DUMMY_MIN armor_given: int = DUMMY_MIN def to_real(self) -> RealSetMins: data = asdict(self) for new, old in ( ("critical_hit", "crit"), ("critical_mastery", "crit_mastery"), ("mastery_3_elements", "three_element_mastery"), ("mastery_2_elements", "two_element_mastery"), ("mastery_1_element", "one_element_mastery"), ("healing_mastery", "heal_mastery"), ("berserk_mastery", "beserk_mastery"), ): data[new] = data.pop(old) return RealSetMins(**data) class SetMaximums(Struct, frozen=True, gc=True): ap: int = DUMMY_MAX mp: int = DUMMY_MAX wp: int = DUMMY_MAX ra: int = DUMMY_MAX crit: int = DUMMY_MAX crit_mastery: int = DUMMY_MAX elemental_mastery: int = DUMMY_MAX one_element_mastery: int = DUMMY_MAX two_element_mastery: int = DUMMY_MAX three_element_mastery: int = DUMMY_MAX distance_mastery: int = DUMMY_MAX rear_mastery: int = DUMMY_MAX heal_mastery: int = DUMMY_MAX beserk_mastery: int = DUMMY_MAX melee_mastery: int = DUMMY_MAX control: int = DUMMY_MAX block: int = DUMMY_MAX fd: int = DUMMY_MAX heals_performed: int = DUMMY_MAX lock: int = DUMMY_MAX dodge: int = DUMMY_MAX armor_given: int = DUMMY_MAX def to_real(self) -> RealSetMaxs: data = asdict(self) for new, old in ( ("critical_hit", "crit"), ("critical_mastery", "crit_mastery"), ("mastery_3_elements", "three_element_mastery"), ("mastery_2_elements", "two_element_mastery"), ("mastery_1_element", "one_element_mastery"), ("healing_mastery", "heal_mastery"), ("berserk_mastery", "beserk_mastery"), ): data[new] = data.pop(old) return RealSetMaxs(**data) def partial_solve_v1( *, lv: int, stats: Stats, target_stats: RealSetMins, equipped_items: list[int], num_mastery: int, allowed_rarities: list[int], dist: bool = False, melee: bool = False, heal: bool = False, zerk: bool = False, rear: bool = False, dry_run: bool = False, ) -> v1Result: """ Doesn't handle sublimations, passives, etc yet Use from pyodide: // passing in other values besides the below // may cause problems with solve quality for v1 let targets = SetMinimum.callKwargs({ap: 12, mp: 6, ra: 2, wp: 0}); // for the full list of supported Stats, see Stats class let stats = Stats.callKwargs({ap: 7, mp: 4, ...}); let [result, error] = partial_solve_v1.callKwargs( { stats: stats, target_stats: targets, } ) """ ap = target_stats.ap - stats.ap mp = target_stats.mp - stats.mp ra = target_stats.ra - stats.ra wp = target_stats.wp - stats.wp forbidden_rarities = [i for i in range(1, 8) if i not in allowed_rarities] equipped = [i for i in equipped_items if i] if equipped_items else [] cfg = v1Config( lv=lv, ap=ap, mp=mp, wp=wp, ra=ra, baseap=stats.ap, basemp=stats.mp, basera=stats.ra, bawewp=stats.wp, bcrit=stats.critical_hit - 3, # wakforge is doing something wrong here, won't be fixes for this entrypoint bcmast=stats.critical_mastery, bmast=stats.elemental_mastery, num_mastery=num_mastery, forbid_rarity=forbidden_rarities, idforce=equipped, dist=dist, melee=melee, heal=heal, zerk=zerk, rear=rear, dry_run=dry_run, hard_cap_depth=15, tolerance=_adaptive_tolerance_map.get(lv, 14), search_depth=1 if dry_run else 1, ) try: result = solve(cfg) best = result[0] except (IndexError, SolveError): return (None, "No possible solution found") _score, items = best item_ids = [i.item_id for i in items] return (item_ids, None) class v2Config(Struct): allowed_rarities: list[int] = field(default_factory=lambda: [1, 2, 3, 4, 5, 6, 7]) target_stats: SetMinimums = field(default_factory=SetMinimums) dry_run: bool = False objectives: StatPriority = field(default_factory=StatPriority) forbidden_items: list[int] = field(default_factory=list) ignore_existing_items: bool = False forbidden_sources: list[Literal["arch", "horde", "pvp", "ultimate_boss"]] = field(default_factory=list) stats_maxs: SetMaximums = field(default_factory=SetMaximums) class v2Result(Struct): build_code: str | None = None error_code: str | None = None item_ids: list[int] = field(default_factory=list) debug_info: str | None = None def compressed_encode(obj: object) -> str: compressor = zlib.compressobj(level=9, wbits=-15) packed = msgpack.encode(obj) return b2048encode(compressor.compress(packed) + compressor.flush()) def partial_solve_v2( *, build_code: str, config: v2Config, progress_callback: Callable[[int, int], None] | None = None, ) -> v2Result: # pyodide proxies aren't actually lists... config.allowed_rarities = [i for i in config.allowed_rarities if i] config.forbidden_items = [i for i in config.forbidden_items if i] config.forbidden_sources = [s for s in config.forbidden_sources if s] # This may look redundant, but it's exceptionally cheap validation try: config = msgpack.decode(msgpack.encode(config), type=v2Config) except Exception as exc: # noqa: BLE001 msg = traceback.format_exception(exc) return v2Result(None, "Invalid config (get debug info if opening an issue)", debug_info=compressed_encode(msg)) target_stats = config.target_stats.to_real() item_sources = load_item_source_data() forbidden_ids: set[int] = set() for source in config.forbidden_sources: forbidden_ids |= getattr(item_sources, source) forbidden_ids -= item_sources.non_finite_arch_horde config.forbidden_items.extend(forbidden_ids) if not config.objectives.is_valid: msg = ("objectives", config.objectives) return v2Result(None, "Invalid config (get debug info if opening an issue)", debug_info=compressed_encode(msg)) build = WFBuild.from_code(build_code) if config.ignore_existing_items: build.clear_items() stats = build.get_allocated_stats().to_stat_values(build.classenum) item_ids = [i.item_id for i in build.get_items() if i.item_id > 0] ap = target_stats.ap - stats.ap mp = target_stats.mp - stats.mp wp = target_stats.wp - stats.wp ra = target_stats.ra - stats.ra forbidden_rarities = [i for i in range(1, 8) if i not in config.allowed_rarities] # TODO: modify internals to not need this level of wrapping lookup: dict[Priority, Literal["full", "half", "none"]] = { Priority.full_negative_only: "full", Priority.half_negative_only: "half", } cfg = v1Config( lv=build.level, wakfu_class=build.classenum, ap=ap, mp=mp, wp=wp, ra=ra, stat_minimums=target_stats, stat_maximums=config.stats_maxs.to_real(), base_stats=stats, baseap=stats.ap, basemp=stats.mp, basera=stats.ra, bawewp=stats.wp, bcrit=stats.critical_hit, bcmast=stats.critical_mastery, bmast=stats.elemental_mastery, num_mastery=config.objectives.elements.bit_count(), forbid_rarity=forbidden_rarities, idforce=item_ids, dist=config.objectives.distance_mastery == Priority.prioritized, melee=config.objectives.melee_mastery == Priority.prioritized, heal=config.objectives.heal_mastery == Priority.prioritized, zerk=config.objectives.berserk_mastery == Priority.prioritized, rear=config.objectives.rear_mastery == Priority.prioritized, negrear=lookup.get(config.objectives.rear_mastery, "none"), negzerk=lookup.get(config.objectives.berserk_mastery, "none"), dry_run=config.dry_run, hard_cap_depth=35, tolerance=_adaptive_tolerance_map.get(build.level, 14), search_depth=1, elements=config.objectives.elements, ) try: result = solve(cfg, progress_callback=progress_callback) best = result[0] except ImpossibleStatError as exc: return v2Result(None, exc.args[0], debug_info=None) except (IndexError, SolveError): return v2Result(None, "No possible solution found", debug_info=None) except Exception as exc: # noqa: BLE001 msg = traceback.format_exception(exc) return v2Result(None, "Unknown error, see debug info", debug_info=compressed_encode(msg)) score, found_items = best found_item_ids = [i.item_id for i in found_items] if config.dry_run: return v2Result(None, None, found_item_ids, None) ecount = config.objectives.elements.bit_count()
remaining_elements = [e for e in ElementsEnum if e not in config.objectives.elements]
2
2023-10-10 21:54:23+00:00
12k
bittranslateio/bittranslate
neurons/validator.py
[ { "identifier": "Validator", "path": "bittranslate/validator.py", "snippet": "class Validator:\n def __init__(self, device: str = \"cpu\", out_dir: str= \"bittranslate_out/\" ):\n self._reward_models = [BertScore(device=device), VectorSim(device=device)]\n\n self._reward_weights = [0.5,...
import os import torch import argparse import traceback import pkg_resources import bittensor as bt import random import copy import anyio import anyio.to_thread import threading from typing import List, Optional from dataclasses import dataclass from queue import SimpleQueue, Empty from bittranslate import Validator from bittranslate.logging import log_elapsed_time from neurons.auto_update import check_for_updates from neurons.protocol import Translate from neurons.api_server import ApiServer
7,215
median = scores.median() for uid, hotkey in enumerate(hotkeys): if hotkey != metagraph.hotkeys[uid]: scores[uid] = median bt.logging.debug(f"New hotkey: {uid}. Setting score to {median}") # Did the most recent metagraph update increase the number of UIDs? # Occurs during creation of subnet as registrations fill up. if len(hotkeys) < len(metagraph.hotkeys): # Create new list of scores with correct length. new_scores = torch.zeros((metagraph.n)) # Copy scores we do have onto new scores. min_len = min(len(hotkeys), len(scores)) new_scores[:min_len] = scores[:min_len] bt.logging.debug(f"UID length increased. Previous scores: {scores}. New scores: {new_scores}") # Update scores. scores = new_scores return scores @dataclass class SynapseWithEvent: """ Object that API server can send to main thread to be serviced. """ input_synapse: Translate event: threading.Event output_synapse: Translate api_queue = SimpleQueue() # Queue of SynapseEventPair async def forward(synapse: Translate) -> Translate: """ Forward function for API server. """ synapse_with_event = SynapseWithEvent( input_synapse=synapse, event=threading.Event(), output_synapse=Translate(source_lang="en", target_lang="pl", source_texts=["sample"]) ) api_queue.put(synapse_with_event) # Wait until the main thread marks this synapse as processed. await anyio.to_thread.run_sync(synapse_with_event.event.wait) return synapse_with_event.output_synapse def main( config ): # Set up logging with the provided configuration and directory. bt.logging(config=config, logging_dir=config.full_path) bt.logging.info(f"Running validator for subnet: {config.netuid} on network: {config.subtensor.chain_endpoint} with config:") # Log the configuration for reference. bt.logging.info(config) # These are core Bittensor classes to interact with the network. bt.logging.info("Setting up bittensor objects.") # The wallet holds the cryptographic key pairs for the validator. wallet = bt.wallet( config = config ) bt.logging.info(f"Wallet: {wallet}") # The subtensor is our connection to the Bittensor blockchain. subtensor = bt.subtensor( config = config ) bt.logging.info(f"Subtensor: {subtensor}") # Dendrite is the RPC client; it lets us send messages to other nodes (axons) in the network. dendrite = bt.dendrite( wallet = wallet ) bt.logging.info(f"Dendrite: {dendrite}") # The metagraph holds the state of the network, letting us know about other miners. metagraph = subtensor.metagraph( config.netuid ) bt.logging.info(f"Metagraph: {metagraph}") hotkeys: List[str] = copy.deepcopy(metagraph.hotkeys) if wallet.hotkey.ss58_address not in metagraph.hotkeys: bt.logging.error(f"\nYour validator: {wallet} if not registered to chain connection: {subtensor} \nRun btcli register and try again.") exit() else: # Each miner gets a unique identity (UID) in the network for differentiation. my_subnet_uid = metagraph.hotkeys.index(wallet.hotkey.ss58_address) bt.logging.info(f"Running validator on uid: {my_subnet_uid}") bt.logging.info("Building validation weights.") scores = torch.zeros_like(metagraph.S, dtype=torch.float32) bt.logging.info(f"Weights: {scores}") alpha = 0.999 ## Custom Initialization bt.logging.info(f"Loading validator components...") validator = Validator(device=config.device, out_dir=config.out_dir) bt.logging.info(f"Done validator components.") if config.enable_api: # external requests api_server = ApiServer( axon_port=config.axon.port, forward_fn=forward, api_json=config.api_json, lang_pairs=validator._lang_pairs, max_char=config.max_char, ngrok_domain=config.ngrok_domain ) api_server.start() bt.logging.info("Starting validator loop.") step = 0 while True: try: bt.logging.info(f"\n\nStep: {step}") # We sleep at the top of the loop such that the queue access is more readable. # This results in one extra delay at the beginning of a validator's startup, # which is not a significant issue.
# The MIT License (MIT) # Copyright © 2023 Yuma Rao # Copyright © 2023 Opentensor Foundation # 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. # Bittensor Validator Template: def get_config(): parser = argparse.ArgumentParser() parser.add_argument('--device', default="cuda", help="The device used for the validator's components.") # Adds override arguments for network and netuid. parser.add_argument( '--netuid', type = int, default = 2, help = "The chain subnet uid." ) parser.add_argument( "--max_char", type=int, default=1024, help="The maximum allowed characters for an incoming request.", ) parser.add_argument( "--batch_size", type=int, default=2, help="Number of source texts to send to each miner." ) parser.add_argument( "--step_delay", type=int, default=12, help="Number of seconds to sleep between steps." ) parser.add_argument( "--miners_per_step", type=int, default=8, help="Number of miners query in each step." ) parser.add_argument( "--track_steps", type=int, default=100, help="Number of steps before tracked scores and texts are saved." ) parser.add_argument( "--out_dir", type=str, default="bittranslate_out/", help="Output directory for tracked results." ) parser.add_argument( "--enable_api", action="store_true", help="If set, a callable API will be activated." ) parser.add_argument( "--score_api", action="store_true", help="If set, responses from API requests will be used to modify scores." ) parser.add_argument( "--api_json", type=str, default="neurons/api.json", help="A path to a a config file for the API." ) parser.add_argument( "--no_artificial_eval", action="store_true", help="If set, artificial data will not be sent to miners for the purpose of scoring. We only recommend setting this to true to when debugging the API." ) parser.add_argument( "--ngrok_domain", help=( "If set, expose the API over 'ngrok' to the specified domain." ) ) parser.add_argument( "--update_steps", type=int, default=500, help=( "The number of steps until we check if there has been a new version. If 0, no searching will be performed." ) ) parser.add_argument( "--no_restart", help=( "If set, the process is not restarted when a new version is detected." ) ) # Adds subtensor specific arguments i.e. --subtensor.chain_endpoint ... --subtensor.network ... bt.subtensor.add_args(parser) # Adds logging specific arguments i.e. --logging.debug ..., --logging.trace .. or --logging.logging_dir ... bt.logging.add_args(parser) # Adds wallet specific arguments i.e. --wallet.name ..., --wallet.hotkey ./. or --wallet.path ... bt.wallet.add_args(parser) bt.axon.add_args(parser) # Parse the config (will take command-line arguments if provided) # To print help message, run python3 template/miner.py --help config = bt.config(parser) # Logging is crucial for monitoring and debugging purposes. config.full_path = os.path.expanduser( "{}/{}/{}/netuid{}/{}".format( config.logging.logging_dir, config.wallet.name, config.wallet.hotkey, config.netuid, 'validator', ) ) # Ensure the logging directory exists. if not os.path.exists(config.full_path): os.makedirs(config.full_path, exist_ok=True) # Return the parsed config. return config def clamp(min: int, max: int, x: int) -> int: """ Clamp `x` into the range `[min,max]`. """ if x<min: return min if x>max: return max return x def translation_for_source_text_in_response( response: Translate, source_text_index: int ) -> str: """ Get the translated text corresponding to a particular source text on a miner's response. """ if source_text_index >= len(response.translated_texts): return "BLANK" response_text = response.translated_texts[source_text_index] if len(response_text) > config.max_char: # TODO log return "BLANK" if type(response_text) != str: # TODO log return "BLANK" return response_text def translations_for_source_text( responses: List[Translate], source_text_index: int ) -> List[str]: """ Return a list of translations for a given source text, from a set of responses. Each translation corresponds to a different miner. """ return [ translation_for_source_text_in_response( response=response, source_text_index=source_text_index ) for response in responses ] def build_translations_per_source_text( responses: List[Translate] ) -> List[List[str]]: """ Assemble a list of lists, where if viewed as a matrix, each row corresponds to different miner's responses to the same source text. Returns `translations`, where `translations[source_index][miner_index]=...` """ return [ translations_for_source_text( responses=responses, source_text_index=source_text_index ) # It is OK to trust this arbitrary response's "source_texts" field # because we set `allow_mutation=False` in the protocol. for source_text_index, _ in enumerate(responses[0].source_texts) ] # source: https://github.com/opentensor/text-prompting/blob/6c493cbce0c621e28ded203d947ce47a9ae062ea/prompting/validators/utils.py#L102 def update_scores_from_metagraph( scores: torch.FloatTensor, metagraph: bt.metagraph, hotkeys: List[str] ) -> List[float]: """ Update the per-UID scores based on recent metagraph updates. Inputs are current scores, recently synced metagraph, and list of hotkeys from before metagraph sync. Output is updated scores. """ # For any UIDs which have a new hotkey, # set the score to the median. median = scores.median() for uid, hotkey in enumerate(hotkeys): if hotkey != metagraph.hotkeys[uid]: scores[uid] = median bt.logging.debug(f"New hotkey: {uid}. Setting score to {median}") # Did the most recent metagraph update increase the number of UIDs? # Occurs during creation of subnet as registrations fill up. if len(hotkeys) < len(metagraph.hotkeys): # Create new list of scores with correct length. new_scores = torch.zeros((metagraph.n)) # Copy scores we do have onto new scores. min_len = min(len(hotkeys), len(scores)) new_scores[:min_len] = scores[:min_len] bt.logging.debug(f"UID length increased. Previous scores: {scores}. New scores: {new_scores}") # Update scores. scores = new_scores return scores @dataclass class SynapseWithEvent: """ Object that API server can send to main thread to be serviced. """ input_synapse: Translate event: threading.Event output_synapse: Translate api_queue = SimpleQueue() # Queue of SynapseEventPair async def forward(synapse: Translate) -> Translate: """ Forward function for API server. """ synapse_with_event = SynapseWithEvent( input_synapse=synapse, event=threading.Event(), output_synapse=Translate(source_lang="en", target_lang="pl", source_texts=["sample"]) ) api_queue.put(synapse_with_event) # Wait until the main thread marks this synapse as processed. await anyio.to_thread.run_sync(synapse_with_event.event.wait) return synapse_with_event.output_synapse def main( config ): # Set up logging with the provided configuration and directory. bt.logging(config=config, logging_dir=config.full_path) bt.logging.info(f"Running validator for subnet: {config.netuid} on network: {config.subtensor.chain_endpoint} with config:") # Log the configuration for reference. bt.logging.info(config) # These are core Bittensor classes to interact with the network. bt.logging.info("Setting up bittensor objects.") # The wallet holds the cryptographic key pairs for the validator. wallet = bt.wallet( config = config ) bt.logging.info(f"Wallet: {wallet}") # The subtensor is our connection to the Bittensor blockchain. subtensor = bt.subtensor( config = config ) bt.logging.info(f"Subtensor: {subtensor}") # Dendrite is the RPC client; it lets us send messages to other nodes (axons) in the network. dendrite = bt.dendrite( wallet = wallet ) bt.logging.info(f"Dendrite: {dendrite}") # The metagraph holds the state of the network, letting us know about other miners. metagraph = subtensor.metagraph( config.netuid ) bt.logging.info(f"Metagraph: {metagraph}") hotkeys: List[str] = copy.deepcopy(metagraph.hotkeys) if wallet.hotkey.ss58_address not in metagraph.hotkeys: bt.logging.error(f"\nYour validator: {wallet} if not registered to chain connection: {subtensor} \nRun btcli register and try again.") exit() else: # Each miner gets a unique identity (UID) in the network for differentiation. my_subnet_uid = metagraph.hotkeys.index(wallet.hotkey.ss58_address) bt.logging.info(f"Running validator on uid: {my_subnet_uid}") bt.logging.info("Building validation weights.") scores = torch.zeros_like(metagraph.S, dtype=torch.float32) bt.logging.info(f"Weights: {scores}") alpha = 0.999 ## Custom Initialization bt.logging.info(f"Loading validator components...") validator = Validator(device=config.device, out_dir=config.out_dir) bt.logging.info(f"Done validator components.") if config.enable_api: # external requests api_server = ApiServer( axon_port=config.axon.port, forward_fn=forward, api_json=config.api_json, lang_pairs=validator._lang_pairs, max_char=config.max_char, ngrok_domain=config.ngrok_domain ) api_server.start() bt.logging.info("Starting validator loop.") step = 0 while True: try: bt.logging.info(f"\n\nStep: {step}") # We sleep at the top of the loop such that the queue access is more readable. # This results in one extra delay at the beginning of a validator's startup, # which is not a significant issue.
with log_elapsed_time("sleeping"):
1
2023-10-09 12:08:05+00:00
12k
grainseed/monitask
sam/segment_anything/automatic_mask_generator.py
[ { "identifier": "Sam", "path": "sam/segment_anything/modeling/sam.py", "snippet": "class Sam(nn.Module):\r\n mask_threshold: float = 0.0\r\n image_format: str = \"RGB\"\r\n\r\n def __init__(\r\n self,\r\n image_encoder: ImageEncoderViT,\r\n prompt_encoder: PromptEncoder,\r\...
import numpy as np import torch import cv2 # type: ignore # noqa: F401 from torchvision.ops.boxes import batched_nms, box_area # type: ignore from typing import Any, Dict, List, Optional, Tuple from .modeling import Sam from .predictor import SamPredictor from .utils.amg import ( MaskData, area_from_rle, batch_iterator, batched_mask_to_box, box_xyxy_to_xywh, build_all_layer_point_grids, calculate_stability_score, coco_encode_rle, generate_crop_boxes, is_box_near_crop_edge, mask_to_rle_pytorch, remove_small_regions, rle_to_mask, uncrop_boxes_xyxy, uncrop_masks, uncrop_points, ) from pycocotools import mask as mask_utils # type: ignore # noqa: F401
8,572
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. class SamAutomaticMaskGenerator: def __init__( self,
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. class SamAutomaticMaskGenerator: def __init__( self,
model: Sam,
0
2023-10-14 13:45:54+00:00
12k
zhaoyizhou1123/mbrcsl
examples/roboverse/run_dt_roboverse.py
[ { "identifier": "DecisionTransformer", "path": "offlinerlkit/policy/decision_transformer/decision_transformer.py", "snippet": "class DecisionTransformer(TrajectoryModel):\n\n \"\"\"\n This model uses GPT to model (Return_1, state_1, action_1, Return_2, state_2, ...)\n \"\"\"\n\n def __init__...
import numpy as np import torch import os import argparse import roboverse import datetime from offlinerlkit.policy import DecisionTransformer from offlinerlkit.policy_trainer import SequenceTrainer, TrainerConfig from offlinerlkit.utils.set_up_seed import set_up_seed from offlinerlkit.utils.roboverse_utils import PickPlaceObsWrapper, DoubleDrawerObsWrapper, get_pickplace_dataset_dt, get_doubledrawer_dataset_dt from offlinerlkit.utils.none_or_str import none_or_str from offlinerlkit.utils.dataset import TrajCtxFloatLengthDataset from offlinerlkit.utils.logger import Logger, make_log_dirs
9,809
''' Recommended hyperparameters: pickplace, horizon=40 doubledraweropen, horizon=50 doubledrawercloseopen, horizon=80 doubledrawerpickplaceopen, horizon=80 ''' def get_args(): parser = argparse.ArgumentParser() # general parser.add_argument("--algo-name", type=str, default="dt") parser.add_argument("--task", type=str, default="pickplace", help="task name") parser.add_argument("--seed", type=int, default=0) parser.add_argument("--num_workers", type=int, default=1, help="Dataloader workers, align with cpu number") parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu") parser.add_argument("--last_eval", action="store_false") # env config parser.add_argument('--data_dir', type=str, required=True) parser.add_argument('--horizon', type=int, default=40, help="max path length for pickplace") # transformer mode parser.add_argument("--n_layer", type=int, default=4) parser.add_argument("--n_head", type=int, default=4) parser.add_argument("--n_embd", type=int, default=32) parser.add_argument('--ctx', type=int, default=10) parser.add_argument('--embed_dim', type=int, default=128, help="dt token embedding dimension") # Train parser.add_argument("--epoch", type=int, default=100) parser.add_argument("--eval_episodes", type=int, default=100) parser.add_argument("--batch_size", type=int, default=256) parser.add_argument('--lr', type=float, default=6e-3, help="learning rate of Trainer" ) parser.add_argument('--goal_mul', type=float, default=1., help="goal = max_dataset_return * goal_mul") parser.add_argument('--sample', action='store_false', help="Sample action by probs, or choose the largest prob") return parser.parse_args() def discount_cumsum(x, gamma): discount_cumsum = np.zeros_like(x) discount_cumsum[-1] = x[-1] for t in reversed(range(x.shape[0]-1)): discount_cumsum[t] = x[t] + gamma * discount_cumsum[t+1] return discount_cumsum def train(args = get_args()): set_up_seed(args.seed) # create env and dataset if args.task == 'pickplace': env = roboverse.make('Widow250PickTray-v0') env = PickPlaceObsWrapper(env) obs_space = env.observation_space args.obs_shape = obs_space.shape obs_dim = np.prod(args.obs_shape) args.action_shape = env.action_space.shape action_dim = np.prod(args.action_shape) prior_data_path = os.path.join(args.data_dir, "pickplace_prior.npy") task_data_path = os.path.join(args.data_dir, "pickplace_task.npy")
''' Recommended hyperparameters: pickplace, horizon=40 doubledraweropen, horizon=50 doubledrawercloseopen, horizon=80 doubledrawerpickplaceopen, horizon=80 ''' def get_args(): parser = argparse.ArgumentParser() # general parser.add_argument("--algo-name", type=str, default="dt") parser.add_argument("--task", type=str, default="pickplace", help="task name") parser.add_argument("--seed", type=int, default=0) parser.add_argument("--num_workers", type=int, default=1, help="Dataloader workers, align with cpu number") parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu") parser.add_argument("--last_eval", action="store_false") # env config parser.add_argument('--data_dir', type=str, required=True) parser.add_argument('--horizon', type=int, default=40, help="max path length for pickplace") # transformer mode parser.add_argument("--n_layer", type=int, default=4) parser.add_argument("--n_head", type=int, default=4) parser.add_argument("--n_embd", type=int, default=32) parser.add_argument('--ctx', type=int, default=10) parser.add_argument('--embed_dim', type=int, default=128, help="dt token embedding dimension") # Train parser.add_argument("--epoch", type=int, default=100) parser.add_argument("--eval_episodes", type=int, default=100) parser.add_argument("--batch_size", type=int, default=256) parser.add_argument('--lr', type=float, default=6e-3, help="learning rate of Trainer" ) parser.add_argument('--goal_mul', type=float, default=1., help="goal = max_dataset_return * goal_mul") parser.add_argument('--sample', action='store_false', help="Sample action by probs, or choose the largest prob") return parser.parse_args() def discount_cumsum(x, gamma): discount_cumsum = np.zeros_like(x) discount_cumsum[-1] = x[-1] for t in reversed(range(x.shape[0]-1)): discount_cumsum[t] = x[t] + gamma * discount_cumsum[t+1] return discount_cumsum def train(args = get_args()): set_up_seed(args.seed) # create env and dataset if args.task == 'pickplace': env = roboverse.make('Widow250PickTray-v0') env = PickPlaceObsWrapper(env) obs_space = env.observation_space args.obs_shape = obs_space.shape obs_dim = np.prod(args.obs_shape) args.action_shape = env.action_space.shape action_dim = np.prod(args.action_shape) prior_data_path = os.path.join(args.data_dir, "pickplace_prior.npy") task_data_path = os.path.join(args.data_dir, "pickplace_task.npy")
trajs = get_pickplace_dataset_dt(
6
2023-10-11 08:36:06+00:00
12k
parklab/Salamander
src/salamander/nmf_framework/corrnmf.py
[ { "identifier": "match_signatures_pair", "path": "src/salamander/utils.py", "snippet": "def match_signatures_pair(\n signatures1: pd.DataFrame, signatures2: pd.DataFrame, metric=\"cosine\"\n):\n \"\"\"\n Match a pair of signature catalogs using their pairwise column distances,\n see https://...
from abc import abstractmethod from scipy.spatial.distance import squareform from scipy.special import gammaln from ..utils import match_signatures_pair, shape_checker, type_checker from ._utils_klnmf import kl_divergence, poisson_llh, samplewise_kl_divergence from .initialization import initialize from .signature_nmf import SignatureNMF import numpy as np import pandas as pd
8,050
* self.dim_embeddings * self.n_samples * np.log(2 * np.pi * self.sigma_sq) ) elbo -= np.sum(self.U**2) / (2 * self.sigma_sq) return elbo @property def objective(self) -> str: return "maximize" def _surrogate_objective_function(self, penalize_sample_embeddings=True) -> float: """ The surrogate lower bound of the ELBO. """ p = self._update_p() exposures = self.exposures.values aux = np.log(self.W)[:, :, None] + np.log(exposures)[None, :, :] - np.log(p) sof_value = np.einsum("VD,VKD,VKD->", self.X, p, aux, optimize="greedy").item() sof_value -= np.sum(gammaln(1 + self.X)) sof_value -= np.sum(exposures) sof_value -= ( 0.5 * self.dim_embeddings * self.n_signatures * np.log(2 * np.pi * self.sigma_sq) ) sof_value -= np.sum(self.L**2) / (2 * self.sigma_sq) if penalize_sample_embeddings: sof_value -= ( 0.5 * self.dim_embeddings * self.n_samples * np.log(2 * np.pi * self.sigma_sq) ) sof_value -= np.sum(self.U**2) / (2 * self.sigma_sq) return sof_value def loglikelihood(self): return self.objective_function() @property def _n_parameters(self): """ There are n_features * n_signatures parameters corresponding to the signature matrix, each embedding corresponds to dim_embeddings parameters, and each signature & sample has a real valued bias. Finally, the model variance is a single positive real number. """ n_parameters_signatures = self.n_features * self.n_signatures n_parameters_embeddings = self.dim_embeddings * ( self.n_signatures + self.n_samples ) n_parameters_biases = self.n_samples + self.n_signatures n_parameters_exposures = n_parameters_embeddings + n_parameters_biases n_parameters = n_parameters_signatures + n_parameters_exposures + 1 return n_parameters @abstractmethod def _update_alpha(self): pass @abstractmethod def _update_sigma_sq(self): pass @abstractmethod def _update_W(self): pass @abstractmethod def _update_p(self): pass @abstractmethod def _update_l(self, index, aux_row, outer_prods_U): r""" Input: ------ index: int The index of the signature whose embedding is updated aux_row: nd.ndarray Row of the following matrix: aux_kd = \sum_v X_vd * p_vkd. This auxiliary matrix is used for updating the signatures and the sample embeddidngs. The aux_row argument is the k-th row of aux, where k is equal to 'index'. outer_prods_U: np.ndarray All outer products of the sample embeddings. shape: (n_samples, dim_embeddings, dim_embeddings) """ @abstractmethod def _update_u(self, index, aux_col, outer_prods_L): r""" Input: ------ index: int The index of the sample whose embedding is updated aux_col: nd.ndarray Column of the following matrix: aux_kd = \sum_v X_vd * p_vkd. This auxiliary matrix is used for updating the signatures and the sample embeddidngs. The aux_col argument is the d-th row of aux, where d is equal to 'index'. outer_prods_L: np.ndarray All outer products of the signature embeddings. shape: (n_signatures, dim_embeddings, dim_embeddings) """ def _check_given_biases(self, given_biases, expected_n_biases, name): type_checker(name, given_biases, np.ndarray)
EPSILON = np.finfo(np.float32).eps class CorrNMF(SignatureNMF): r""" The abstract class CorrNMF unifies the structure of deterministic and stochastic algorithms to fit the parameters of correlated NMF (CorrNMF). The model parameters are the signature and sample biases, the variance, and the signature matrix. The latent variables are the signature and sample embeddings. Overview: Every child class has to implement the following methods: - _update_alpha: update the sample exposure biases \alpha - _update_beta: update the signature exposure biases \beta - _update_sigma_sq: update the embedding distribution variance \sigma^2 - _update_W: update the signature matrix W - _update_p: update the auxiliary parameters p - _update_l: update a single signature embedding l - _update_u: update a single sample embedding u - fit: Run CorrNMF for a given mutation count data. The following attributes are implemented in CorrNMF: - signatures: pd.DataFrame The signature matrix including mutation type names and signature names - exposures: pd.DataFrame The exposure matrix including the signature names and sample names - reconstruction_error: float The reconstruction error between the count matrix and the reconstructed count matrix. - samplewise_reconstruction_error: np.ndarray The samplewise reconstruction error between the sample counts and the reconstructed sample counts. - _n_parameters: The number of parameters fitted in CorrNMF - objective: str "minimize" or "maximize". CorrNMF maximizes the objective function. - corr_signatures: pd.DataFrame The signature correlation matrix induced by the signature embeddings - corr_samples: pd.DataFrame The sample correlation matrix induced by the sample embeddings The following methods are implemented in CorrNMF: - objective_function: The evidence lower bound (ELBO) of the log-likelihood. Note: The ELBO is sometimes called the variational lower bound. - _surrogate_objective_function: A surrogate lower bound of the ELBO after introducing the auxiliary parameters p. In contrast to the original objective_function, the surrogate is strictly convex in the signature and sample embeddings - loglikelihood: The loglikelihood of the underyling generative model - _initialize: Initialize all model parameters and latent variables depending on the initialization method chosen - _get_embedding_data: A helper function for the embedding plot that returns the signature and sample embeddings - _get_default_embedding_annotations: A helper function for the embedding plot that returns the signature names More specific docstrings are written for the respective attributes and methods. """ def __init__( self, n_signatures=1, dim_embeddings=None, init_method="nndsvd", min_iterations=500, max_iterations=10000, conv_test_freq=10, tol=1e-7, ): """ Input: ------ n_signatures: int The number of underlying signatures that are assumed to have generated the mutation count data dim_embeddings: int The assumed dimension of the signature and sample embeddings. Should be smaller or equal to the number of signatures as a dimension equal to the number of signatures covers the case of independent signatures. The smaller the embedding dimension, the stronger the enforced correlation structure on both signatures and samples. init_method: str One of "custom", "flat", "hierarchical_cluster", "nndsvd", "nndsvda", "nndsvdar" "random" and "separableNMF". See the initialization module for further details. min_iterations: int The minimum number of iterations to perform during inference max_iterations: int The maximum number of iterations to perform during inference conv_test_freq: int The frequency at which the algorithm is tested for convergence. The objective function value is only computed every 'conv_test_freq' many iterations, which also affects a potentially saved history of the objective function values. tol: float The CorrNMF algorithm is converged when the relative change of the surrogate objective function of one iteration is smaller than the tolerance 'tol'. """ super().__init__( n_signatures, init_method, min_iterations, max_iterations, conv_test_freq, tol, ) if dim_embeddings is None: dim_embeddings = n_signatures self.dim_embeddings = dim_embeddings # initialize data/fitting-dependent attributes self.W = None self.alpha = None self.beta = None self.L = None self.U = None self.sigma_sq = None @property def signatures(self) -> pd.DataFrame: signatures = pd.DataFrame( self.W, index=self.mutation_types, columns=self.signature_names ) return signatures @property def exposures(self) -> pd.DataFrame: """ In contrast to the classical NMF framework, the exposure matrix is restructured and determined by the signature & sample biases and embeddings. """ exposures = pd.DataFrame( np.exp(self.alpha + self.beta[:, np.newaxis] + self.L.T @ self.U), index=self.signature_names, columns=self.sample_names, ) return exposures @property def reconstruction_error(self): return kl_divergence(self.X, self.W, self.exposures.values) @property def samplewise_reconstruction_error(self): return samplewise_kl_divergence(self.X, self.W, self.exposures.values) def objective_function(self, penalize_sample_embeddings=True) -> float: """ The evidence lower bound (ELBO) """ elbo = poisson_llh(self.X, self.signatures.values, self.exposures.values) elbo -= ( 0.5 * self.dim_embeddings * self.n_signatures * np.log(2 * np.pi * self.sigma_sq) ) elbo -= np.sum(self.L**2) / (2 * self.sigma_sq) if penalize_sample_embeddings: elbo -= ( 0.5 * self.dim_embeddings * self.n_samples * np.log(2 * np.pi * self.sigma_sq) ) elbo -= np.sum(self.U**2) / (2 * self.sigma_sq) return elbo @property def objective(self) -> str: return "maximize" def _surrogate_objective_function(self, penalize_sample_embeddings=True) -> float: """ The surrogate lower bound of the ELBO. """ p = self._update_p() exposures = self.exposures.values aux = np.log(self.W)[:, :, None] + np.log(exposures)[None, :, :] - np.log(p) sof_value = np.einsum("VD,VKD,VKD->", self.X, p, aux, optimize="greedy").item() sof_value -= np.sum(gammaln(1 + self.X)) sof_value -= np.sum(exposures) sof_value -= ( 0.5 * self.dim_embeddings * self.n_signatures * np.log(2 * np.pi * self.sigma_sq) ) sof_value -= np.sum(self.L**2) / (2 * self.sigma_sq) if penalize_sample_embeddings: sof_value -= ( 0.5 * self.dim_embeddings * self.n_samples * np.log(2 * np.pi * self.sigma_sq) ) sof_value -= np.sum(self.U**2) / (2 * self.sigma_sq) return sof_value def loglikelihood(self): return self.objective_function() @property def _n_parameters(self): """ There are n_features * n_signatures parameters corresponding to the signature matrix, each embedding corresponds to dim_embeddings parameters, and each signature & sample has a real valued bias. Finally, the model variance is a single positive real number. """ n_parameters_signatures = self.n_features * self.n_signatures n_parameters_embeddings = self.dim_embeddings * ( self.n_signatures + self.n_samples ) n_parameters_biases = self.n_samples + self.n_signatures n_parameters_exposures = n_parameters_embeddings + n_parameters_biases n_parameters = n_parameters_signatures + n_parameters_exposures + 1 return n_parameters @abstractmethod def _update_alpha(self): pass @abstractmethod def _update_sigma_sq(self): pass @abstractmethod def _update_W(self): pass @abstractmethod def _update_p(self): pass @abstractmethod def _update_l(self, index, aux_row, outer_prods_U): r""" Input: ------ index: int The index of the signature whose embedding is updated aux_row: nd.ndarray Row of the following matrix: aux_kd = \sum_v X_vd * p_vkd. This auxiliary matrix is used for updating the signatures and the sample embeddidngs. The aux_row argument is the k-th row of aux, where k is equal to 'index'. outer_prods_U: np.ndarray All outer products of the sample embeddings. shape: (n_samples, dim_embeddings, dim_embeddings) """ @abstractmethod def _update_u(self, index, aux_col, outer_prods_L): r""" Input: ------ index: int The index of the sample whose embedding is updated aux_col: nd.ndarray Column of the following matrix: aux_kd = \sum_v X_vd * p_vkd. This auxiliary matrix is used for updating the signatures and the sample embeddidngs. The aux_col argument is the d-th row of aux, where d is equal to 'index'. outer_prods_L: np.ndarray All outer products of the signature embeddings. shape: (n_signatures, dim_embeddings, dim_embeddings) """ def _check_given_biases(self, given_biases, expected_n_biases, name): type_checker(name, given_biases, np.ndarray)
shape_checker(name, given_biases, (expected_n_biases,))
1
2023-10-08 04:29:42+00:00
12k
shadlc/FreeKill-Web-Panel
src/v1.py
[ { "identifier": "restful", "path": "src/utils.py", "snippet": "def restful(code: int, msg: str = '', data: dict = {}) -> None:\n retcode = 1\n if code == 200:\n retcode = 0\n return jsonify({'code': code,\n 'retcode': retcode,\n 'msg': msg,\n 'data': data...
import os import re import json import time from flask import Response from flask_classful import FlaskView, route, request from src.utils import restful, isPortBusy, startGameServer, stopGameServer, deleteGameServer, updateGameServer, backupGameServer, getGameServerStat, getGameTransTable, readGameConfig, writeGameConfig, isFileExists, runTmuxCmd, runScreenCmd, appendFile, runCmdCorrect, getSessionPid, getGitTree, setPackVersionForServer from src.game_server import Server from src.controller import Controller from src.utils import config
8,975
info_dict = server.details(self.controller.server_list) return restful(200, '', info_dict) return restful(404, '未找到该服务器') @route('player_list', methods=['GET']) def player_list(self): name = request.args.get('name', '') for server in self.controller.list: if server.name == name: info_dict = server.getPlayerList() return restful(200, '', info_dict) return restful(404, '未找到该服务器') @route('room_list', methods=['GET']) def room_list(self): name = request.args.get('name', '') for server in self.controller.list: if server.name == name: info_dict = server.getRoomList() return restful(200, '', info_dict) return restful(404, '未找到该服务器') @route('trans_table', methods=['GET']) def trans_table(self): name = request.args.get('name', '') raw = request.args.get('raw', False) for server in self.controller.list: if server.name == name: trans_table = getGameTransTable(server.path, raw) return restful(200, '', trans_table) return restful(404, '未找到该服务器') @route('execute', methods=['POST']) def execute(self): name = request.json.get('name', '') cmd = request.json.get('cmd', '') for char in ['`', '"', '$', '\x01']: cmd = cmd.replace(char, f'\\{char}') server_list = self.controller.getList() for server in server_list: if server.name == name: is_port_busy = isPortBusy(server.port) if cmd == 'start' and not is_port_busy: appendFile(f'{server.path}/{config.log_file}', '\x01') time.sleep(0.1) error = server.start() if error: return restful(400, error) self.controller.connection.set(server.name, 'path', server.path) self.controller.connection.set(server.name, 'pid', server.pid) return restful(200, '服务器启动成功') elif not is_port_busy: return restful(405, '服务器未启动,请先启动') else: if server.session_type == 'tmux': runTmuxCmd(name, cmd) elif server.handled: runScreenCmd(name, cmd) else: return restful(403, '无法与终端交互,请关闭服务器后由本程序接管启动') return restful(200, '') return restful(404, '未找到该服务器') @route('add_server', methods=['POST']) def add_server(self): name = request.json.get('name', None) port = int(request.json.get('port')) if request.json.get('port').isdigit() else None path = request.json.get('path', None) desc = request.json.get('desc', None) icon = request.json.get('icon', None) capacity = int(request.json.get('capacity')) if request.json.get('capacity').isdigit() else None temp_ban_time = int(request.json.get('temp_ban_time')) if request.json.get('temp_ban_time').isdigit() else None motd = request.json.get('motd', None) enable_bots = request.json.get('enable_bots', None) if enable_bots != None: enable_bots = bool(enable_bots) session_type = request.json.get('session_type', None) server_list = self.controller.getList() if not name: return restful(405, f'服务器名称不能为空') elif not port: return restful(405, f'服务器端口无效') elif not path: return restful(405, f'服务器启动路径不能为空') elif name in [server.name for server in server_list]: return restful(409, f'该服务器名称重名:{name}') elif match := re.search(r'([<>:;"/\\\|\?\*\x00-\x1F\x7F\'\`\s])', name): result = match.groups()[0] return restful(409, f'该服务器名称存在不可用字符:<{result}>') elif isPortBusy(port): return restful(409, f'该端口已被占用:{port}') elif port < 1025 or port > 65535: return restful(409, f'该端口不可用:{port}') elif not isFileExists(os.path.join(path,'FreeKill')): return restful(409, f'该路径无效\n确保该路径下存在可执行的“FreeKill”文件') elif match := re.search(r'([<>:;"\\|\?\*\x00-\x1F\x7F\'\`\s])', path): result = match.groups()[0] return restful(409, f'该服务器路径存在不可用字符:<{result}>') elif path in [server.path for server in server_list]: return restful(409, f'该路径已经启动了一个服务器') elif session_type not in ['tmux', 'screen']: return restful(409, f'本程序仅支持启动tmux或screen服') elif session_type == 'tmux' and not runCmdCorrect('tmux -V'): return restful(409, f'服务器未安装tmux,无法以此方式启动') elif session_type == 'screen' and not runCmdCorrect('screen -v'): return restful(409, f'服务器未安装screen,无法以此方式启动') if e := writeGameConfig(path, { "description": desc, "iconUrl": icon, "capacity": capacity, "tempBanTime": temp_ban_time, "motd": motd, "enableBots": enable_bots, }): return restful(400, f'服务器配置写入错误,启动失败:\n{e}') pid = startGameServer(name, port, path, session_type) if pid == 0: return restful(400, '服务器启动失败,请联系管理员')
class V1API(FlaskView): def __init__(self): super().__init__() self.controller : Controller @route('/') def index(self): return 'V1 API' @route('servers', methods=['GET']) def servers(self): server_dict_list = [] server_list = self.controller.getList() for server in server_list: server_dict_list.append(server.info(self.controller.server_list)) return restful(200, '', {'list': server_dict_list}) @route('details', methods=['GET']) def details(self): name = request.args.get('name', '') server_list = self.controller.getList() for server in server_list: if server.name == name: info_dict = server.details(self.controller.server_list) return restful(200, '', info_dict) return restful(404, '未找到该服务器') @route('player_list', methods=['GET']) def player_list(self): name = request.args.get('name', '') for server in self.controller.list: if server.name == name: info_dict = server.getPlayerList() return restful(200, '', info_dict) return restful(404, '未找到该服务器') @route('room_list', methods=['GET']) def room_list(self): name = request.args.get('name', '') for server in self.controller.list: if server.name == name: info_dict = server.getRoomList() return restful(200, '', info_dict) return restful(404, '未找到该服务器') @route('trans_table', methods=['GET']) def trans_table(self): name = request.args.get('name', '') raw = request.args.get('raw', False) for server in self.controller.list: if server.name == name: trans_table = getGameTransTable(server.path, raw) return restful(200, '', trans_table) return restful(404, '未找到该服务器') @route('execute', methods=['POST']) def execute(self): name = request.json.get('name', '') cmd = request.json.get('cmd', '') for char in ['`', '"', '$', '\x01']: cmd = cmd.replace(char, f'\\{char}') server_list = self.controller.getList() for server in server_list: if server.name == name: is_port_busy = isPortBusy(server.port) if cmd == 'start' and not is_port_busy: appendFile(f'{server.path}/{config.log_file}', '\x01') time.sleep(0.1) error = server.start() if error: return restful(400, error) self.controller.connection.set(server.name, 'path', server.path) self.controller.connection.set(server.name, 'pid', server.pid) return restful(200, '服务器启动成功') elif not is_port_busy: return restful(405, '服务器未启动,请先启动') else: if server.session_type == 'tmux': runTmuxCmd(name, cmd) elif server.handled: runScreenCmd(name, cmd) else: return restful(403, '无法与终端交互,请关闭服务器后由本程序接管启动') return restful(200, '') return restful(404, '未找到该服务器') @route('add_server', methods=['POST']) def add_server(self): name = request.json.get('name', None) port = int(request.json.get('port')) if request.json.get('port').isdigit() else None path = request.json.get('path', None) desc = request.json.get('desc', None) icon = request.json.get('icon', None) capacity = int(request.json.get('capacity')) if request.json.get('capacity').isdigit() else None temp_ban_time = int(request.json.get('temp_ban_time')) if request.json.get('temp_ban_time').isdigit() else None motd = request.json.get('motd', None) enable_bots = request.json.get('enable_bots', None) if enable_bots != None: enable_bots = bool(enable_bots) session_type = request.json.get('session_type', None) server_list = self.controller.getList() if not name: return restful(405, f'服务器名称不能为空') elif not port: return restful(405, f'服务器端口无效') elif not path: return restful(405, f'服务器启动路径不能为空') elif name in [server.name for server in server_list]: return restful(409, f'该服务器名称重名:{name}') elif match := re.search(r'([<>:;"/\\\|\?\*\x00-\x1F\x7F\'\`\s])', name): result = match.groups()[0] return restful(409, f'该服务器名称存在不可用字符:<{result}>') elif isPortBusy(port): return restful(409, f'该端口已被占用:{port}') elif port < 1025 or port > 65535: return restful(409, f'该端口不可用:{port}') elif not isFileExists(os.path.join(path,'FreeKill')): return restful(409, f'该路径无效\n确保该路径下存在可执行的“FreeKill”文件') elif match := re.search(r'([<>:;"\\|\?\*\x00-\x1F\x7F\'\`\s])', path): result = match.groups()[0] return restful(409, f'该服务器路径存在不可用字符:<{result}>') elif path in [server.path for server in server_list]: return restful(409, f'该路径已经启动了一个服务器') elif session_type not in ['tmux', 'screen']: return restful(409, f'本程序仅支持启动tmux或screen服') elif session_type == 'tmux' and not runCmdCorrect('tmux -V'): return restful(409, f'服务器未安装tmux,无法以此方式启动') elif session_type == 'screen' and not runCmdCorrect('screen -v'): return restful(409, f'服务器未安装screen,无法以此方式启动') if e := writeGameConfig(path, { "description": desc, "iconUrl": icon, "capacity": capacity, "tempBanTime": temp_ban_time, "motd": motd, "enableBots": enable_bots, }): return restful(400, f'服务器配置写入错误,启动失败:\n{e}') pid = startGameServer(name, port, path, session_type) if pid == 0: return restful(400, '服务器启动失败,请联系管理员')
server = Server()
19
2023-10-14 12:34:08+00:00
12k
wilhelmagren/finq
finq/portfolio.py
[ { "identifier": "Asset", "path": "finq/asset.py", "snippet": "class Asset(object):\n \"\"\" \"\"\"\n\n def __init__(\n self,\n data: pd.Series,\n name: str,\n *,\n market: Optional[str] = None,\n index_name: Optional[str] = None,\n price_type: str =...
import logging import pandas as pd import numpy as np import scipy.optimize as scipyopt import matplotlib.pyplot as plt from functools import wraps from tqdm import tqdm from finq.asset import Asset from finq.datasets import Dataset from finq.exceptions import ( FinqError, InvalidCombinationOfArgumentsError, InvalidPortfolioWeightsError, ObjectiveFunctionError, PortfolioNotYetOptimizedError, ) from finq.formulas import ( period_returns, sharpe_ratio, weighted_returns, weighted_variance, ) from typing import ( Any, Callable, List, Dict, Tuple, Union, Optional, )
10,019
""" """ # For a full list of `scipy` optimization methods and references, see the link below. # https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html _supported_optimization_methods = ( "Nelder-Mead", "Powell", "CG", "BFGS", "Newton-CG", "L-BFGS-B", "TNC", "COBYLA", "SLSQP", "trust-constr", "dogleg", "trust-ncg", "trust-exact", "trust-krylov", ) _weight_initializations = { "lognormal": np.random.lognormal, "normal": np.random.normal, "uniform": np.random.uniform, } def __init__( self, data: Union[Dataset, List[Asset], np.ndarray, pd.DataFrame], *, weights: Optional[np.ndarray] = None, names: Optional[Union[Dict[str, str], List[str]]] = None, symbols: Optional[Union[Dict[str, str], List[str]]] = None, confidence_level: float = 0.95, risk_free_rate: float = 5e-3, n_trading_days: int = 252, objective_function: Optional[Callable] = None, objective_function_args: Tuple[Any, ...] = (), objective_bounds: Optional[List[Tuple[int, ...]]] = None, objective_constraints: Optional[Tuple[Dict, ...]] = None, ): """ """ if isinstance(data, Dataset): assets = data.as_assets() data = list(assets.values()) symbols = list(assets.keys()) if not isinstance(data, list): if names is None and symbols is None and not isinstance(data, pd.DataFrame): raise InvalidCombinationOfArgumentsError( "You need to provide the names and ticker symbols of each asset that you " "want to include in your portfolio if the data you provided is neither a " "`list` of `Asset` objects or a `pd.DataFrame`. You can also try " "providing only one of the arguments `names` and `symbols`, but then as " "a dictionary of the form `key=name` `value=symbol`." ) if isinstance(data, list): symbols = [a.name for a in data] data = np.array([a.data for a in data]) if isinstance(data, pd.DataFrame): symbols = data.columns data = data.to_numpy().T if isinstance(names, dict): symbols = list(names.values()) names = list(names.keys()) if isinstance(symbols, dict): names = list(symbols.keys()) symbols = list(symbols.values()) self._data = data self._weights = weights self._names = names self._symbols = symbols self._confidence_level = confidence_level self._risk_free_rate = risk_free_rate self._n_trading_days = n_trading_days self._random_portfolios = None self._objective_function = objective_function self._objective_function_args = objective_function_args self._objective_bounds = objective_bounds self._objective_constraints = objective_constraints def weights_are_normalized(self) -> bool: """ """ return np.allclose(self._weights.sum(), 1.0, rtol=1e-6) def initialize_random_weights( self, distribution: Union[str, Callable], *args: Tuple[Any, ...], **kwargs: Dict[str, Any], ): """ """ if isinstance(distribution, str): distribution = self._weight_initializations.get(distribution, None) if distribution is None: raise ValueError( "You provided a non valid weight initialization distribution." ) weights = distribution(*args, **kwargs) self._weights = weights / weights.sum() def check_valid_weights(func) -> Callable: """ """ @wraps(func) def _check_valid_weights(self, *args, **kwargs) -> Optional[FinqError]: """ """ if self._weights is None:
""" MIT License Copyright (c) 2023 Wilhelm Ågren 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 created: 2023-10-20 Last updated: 2023-11-10 """ log = logging.getLogger(__name__) class Portfolio(object): """ """ # For a full list of `scipy` optimization methods and references, see the link below. # https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html _supported_optimization_methods = ( "Nelder-Mead", "Powell", "CG", "BFGS", "Newton-CG", "L-BFGS-B", "TNC", "COBYLA", "SLSQP", "trust-constr", "dogleg", "trust-ncg", "trust-exact", "trust-krylov", ) _weight_initializations = { "lognormal": np.random.lognormal, "normal": np.random.normal, "uniform": np.random.uniform, } def __init__( self, data: Union[Dataset, List[Asset], np.ndarray, pd.DataFrame], *, weights: Optional[np.ndarray] = None, names: Optional[Union[Dict[str, str], List[str]]] = None, symbols: Optional[Union[Dict[str, str], List[str]]] = None, confidence_level: float = 0.95, risk_free_rate: float = 5e-3, n_trading_days: int = 252, objective_function: Optional[Callable] = None, objective_function_args: Tuple[Any, ...] = (), objective_bounds: Optional[List[Tuple[int, ...]]] = None, objective_constraints: Optional[Tuple[Dict, ...]] = None, ): """ """ if isinstance(data, Dataset): assets = data.as_assets() data = list(assets.values()) symbols = list(assets.keys()) if not isinstance(data, list): if names is None and symbols is None and not isinstance(data, pd.DataFrame): raise InvalidCombinationOfArgumentsError( "You need to provide the names and ticker symbols of each asset that you " "want to include in your portfolio if the data you provided is neither a " "`list` of `Asset` objects or a `pd.DataFrame`. You can also try " "providing only one of the arguments `names` and `symbols`, but then as " "a dictionary of the form `key=name` `value=symbol`." ) if isinstance(data, list): symbols = [a.name for a in data] data = np.array([a.data for a in data]) if isinstance(data, pd.DataFrame): symbols = data.columns data = data.to_numpy().T if isinstance(names, dict): symbols = list(names.values()) names = list(names.keys()) if isinstance(symbols, dict): names = list(symbols.keys()) symbols = list(symbols.values()) self._data = data self._weights = weights self._names = names self._symbols = symbols self._confidence_level = confidence_level self._risk_free_rate = risk_free_rate self._n_trading_days = n_trading_days self._random_portfolios = None self._objective_function = objective_function self._objective_function_args = objective_function_args self._objective_bounds = objective_bounds self._objective_constraints = objective_constraints def weights_are_normalized(self) -> bool: """ """ return np.allclose(self._weights.sum(), 1.0, rtol=1e-6) def initialize_random_weights( self, distribution: Union[str, Callable], *args: Tuple[Any, ...], **kwargs: Dict[str, Any], ): """ """ if isinstance(distribution, str): distribution = self._weight_initializations.get(distribution, None) if distribution is None: raise ValueError( "You provided a non valid weight initialization distribution." ) weights = distribution(*args, **kwargs) self._weights = weights / weights.sum() def check_valid_weights(func) -> Callable: """ """ @wraps(func) def _check_valid_weights(self, *args, **kwargs) -> Optional[FinqError]: """ """ if self._weights is None:
raise PortfolioNotYetOptimizedError(
6
2023-10-09 19:02:54+00:00
12k
lmb-freiburg/ldce
ldm/models/diffusion/classifier.py
[ { "identifier": "EncoderUNetModel", "path": "ldm/modules/diffusionmodules/openaimodel.py", "snippet": "class EncoderUNetModel(nn.Module):\n \"\"\"\n The half UNet model with attention and timestep embedding.\n For usage, see UNet.\n \"\"\"\n\n def __init__(\n self,\n image_s...
import os import torch import pytorch_lightning as pl import kornia.augmentation as K import torchvision from torch import nn from torch import Tensor from omegaconf import OmegaConf from torch.nn import functional as F from torch.nn import Linear from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from copy import deepcopy from einops import rearrange from glob import glob from natsort import natsorted from torchvision.models import resnet18 from ldm.modules.diffusionmodules.openaimodel import EncoderUNetModel, UNetModel from ldm.util import log_txt_as_img, default, ismap, instantiate_from_config
8,184
if self.label_key == 'segmentation': targets = rearrange(targets, 'b h w c -> b c h w') for down in range(self.numd): h, w = targets.shape[-2:] targets = F.interpolate(targets, size=(h // 2, w // 2), mode='nearest') # targets = rearrange(targets,'b c h w -> b h w c') return targets def compute_top_k(self, logits, labels, k, reduction="mean"): _, top_ks = torch.topk(logits, k, dim=1) if reduction == "mean": return (top_ks == labels[:, None]).float().sum(dim=-1).mean().item() elif reduction == "none": return (top_ks == labels[:, None]).float().sum(dim=-1) def on_train_epoch_start(self): # save some memory self.diffusion_model.model.to('cpu') @torch.no_grad() def write_logs(self, loss, logits, targets): log_prefix = 'train' if self.training else 'val' log = {} log[f"{log_prefix}/loss"] = loss.mean() log[f"{log_prefix}/acc@1"] = self.compute_top_k( logits, targets, k=1, reduction="mean" ) log[f"{log_prefix}/acc@5"] = self.compute_top_k( logits, targets, k=5, reduction="mean" ) self.log_dict(log, prog_bar=False, logger=True, on_step=self.training, on_epoch=True) self.log('loss', log[f"{log_prefix}/loss"], prog_bar=True, logger=False) #self.log('global_step', self.global_step, logger=False, on_epoch=False, prog_bar=True) lr = self.optimizers().param_groups[0]['lr'] self.log('lr_abs', lr, on_step=True, logger=True, on_epoch=False, prog_bar=True) def shared_step(self, batch, t=None): x, *_ = self.diffusion_model.get_input(batch, k=self.diffusion_model.first_stage_key) if self.latent_transform is not None and self.trainer.training: #print("Applying latent transform") x = self.latent_transform(x) targets = self.get_conditioning(batch) if targets.dim() == 4: targets = targets.argmax(dim=1) if t is None: t = torch.randint(0, self.diffusion_model.num_timesteps //self.diffusion_classifier_steps_ratio, (x.shape[0],), device=self.device).long() else: t = torch.full(size=(x.shape[0],), fill_value=t, device=self.device).long() x_noisy = self.get_x_noisy(x, t) logits = self(x_noisy, t) loss = F.cross_entropy(logits, targets, reduction='none') self.write_logs(loss.detach(), logits.detach(), targets.detach()) loss = loss.mean() return loss, logits, x_noisy, targets def training_step(self, batch, batch_idx): loss, *_ = self.shared_step(batch) return loss def reset_noise_accs(self): self.noisy_acc = {t: {'acc@1': [], 'acc@5': []} for t in range(0, self.diffusion_model.num_timesteps //self.diffusion_classifier_steps_ratio, self.diffusion_model.log_every_t // self.diffusion_classifier_steps_ratio )} def on_validation_start(self): self.reset_noise_accs() @torch.no_grad() def validation_step(self, batch, batch_idx): loss, *_ = self.shared_step(batch, t=0) for t in self.noisy_acc: _, logits, _, targets = self.shared_step(batch, t) self.noisy_acc[t]['acc@1'].append(self.compute_top_k(logits, targets, k=1, reduction='mean')) self.noisy_acc[t]['acc@5'].append(self.compute_top_k(logits, targets, k=5, reduction='mean')) #log noisy_acc @t [f'inputs@t{current_time}'] # added log self.log(f'val/noisy_acc@{t}@1', self.noisy_acc[t]['acc@1'][-1], on_step=False, on_epoch=True) self.log(f'val/noisy_acc@{t}@5', self.noisy_acc[t]['acc@5'][-1], on_step=False, on_epoch=True) return loss def configure_optimizers(self): optimizer = AdamW(self.model.parameters(), lr=self.learning_rate, weight_decay=self.weight_decay) if self.use_scheduler: scheduler = instantiate_from_config(self.scheduler_config) print("Setting up LambdaLR scheduler...") scheduler = [ { 'scheduler': LambdaLR(optimizer, lr_lambda=scheduler.schedule), 'interval': 'step', 'frequency': 1 }] return [optimizer], scheduler return optimizer @torch.no_grad() def log_images(self, batch, N=8, *args, **kwargs): log = dict() x = self.get_input(batch, self.diffusion_model.first_stage_key) log['inputs'] = x # z, *_ = self.diffusion_model.get_input(batch, k=self.diffusion_model.first_stage_key) # log["inputs_after_first_stage"] = z #log image after first stage model y = self.get_conditioning(batch) if self.label_key == 'class_label':
__models__ = { 'class_label': EncoderUNetModel, 'segmentation': UNetModel } def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self class DataAugmentation(nn.Module): """Module to perform data augmentation using Kornia on torch tensors.""" def __init__(self, apply_color_jitter: bool = False, latent = False) -> None: super().__init__() self._apply_color_jitter = apply_color_jitter self._latent = latent self.transforms = K.AugmentationSequential( K.RandomErasing(p=0.1, scale=(0.01, 0.33), ratio=(0.3, 3.3), value=0.45), K.RandomHorizontalFlip(p=0.5), K.RandomAffine(360, [0.1, 0.1], [0.7, 1.2], [30., 50.], p=0.5), K.RandomPerspective(0.5, p=0.3), K.RandomChannelShuffle(p=0.3), K.RandomThinPlateSpline(p=0.3), same_on_batch=False, ) if latent else K.AugmentationSequential( K.RandomErasing(p=0.1, scale=(0.01, 0.33), ratio=(0.3, 3.3), value=0.45), K.RandomHorizontalFlip(p=0.2), K.RandomAffine(360, [0.1, 0.1], [0.7, 1.2], [30., 50.], p=0.2), K.RandomPerspective(0.5, p=0.2), #K.RandomChannelShuffle(p=0.2), K.RandomThinPlateSpline(p=0.2), K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.1), same_on_batch=False, ) self.jitter = K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.2) @torch.no_grad() # disable gradients for effiency def forward(self, x: Tensor) -> Tensor: #print("ranges of x before: ", x.min(), x.max()) # covert from -1 to 1 to 0 to 1 x = (x + 1) / 2 x_out = self.transforms(x) # BxCxHxW if self._apply_color_jitter and not self._latent: x_out = self.jitter(x_out) # convert back to -1 to 1 x_out = x_out * 2 - 1 #print("ranges of x after: ", x_out.min(), x_out.max()) return x_out class NoisyLatentImageClassifier(pl.LightningModule): def __init__(self, diffusion_path, num_classes, ckpt_path=None, pool='attention', label_key=None, diffusion_classifier_steps_ratio=10, diffusion_ckpt_path=None, scheduler_config=None, backbone='unet_encoder', weight_decay=1.e-2, log_steps=10, monitor='val/loss', image_aug = False, latent_aug = False, *args, **kwargs): super().__init__(*args, **kwargs) self.num_classes = num_classes self.backbone = backbone # get latest config of diffusion model #diffusion_config = natsorted(glob(os.path.join(diffusion_path, 'configs', '*-project.yaml')))[-1] self.diffusion_config = OmegaConf.load(diffusion_path).model self.diffusion_ckpt_path = diffusion_ckpt_path self.diffusion_classifier_steps_ratio = diffusion_classifier_steps_ratio #print("getting diffusion path", self.diffusion_config.params, self.diffusion_ckpt_path) self.diffusion_config.params.ckpt_path = diffusion_ckpt_path self.load_diffusion() self.monitor = monitor self.numd = self.diffusion_model.first_stage_model.encoder.num_resolutions - 1 self.log_time_interval = self.diffusion_model.num_timesteps //self.diffusion_classifier_steps_ratio // log_steps self.log_steps = log_steps self.label_key = label_key if not hasattr(self.diffusion_model, 'cond_stage_key') \ else self.diffusion_model.cond_stage_key assert self.label_key is not None, 'label_key neither in diffusion model nor in model.params' if self.label_key not in __models__: raise NotImplementedError() self.load_classifier(ckpt_path, pool) self.scheduler_config = scheduler_config self.use_scheduler = self.scheduler_config is not None self.weight_decay = weight_decay self.image_transform = DataAugmentation(apply_color_jitter= True) if image_aug else None self.latent_transform = DataAugmentation(apply_color_jitter= True, latent = True) if latent_aug else None 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}") def load_diffusion(self): model = instantiate_from_config(self.diffusion_config) self.diffusion_model = model.eval() self.diffusion_model.train = disabled_train for param in self.diffusion_model.parameters(): param.requires_grad = False def load_classifier(self, ckpt_path, pool): if self.backbone == 'unet_encoder': model_config = deepcopy(self.diffusion_config.params.unet_config.params) model_config.in_channels = self.diffusion_config.params.unet_config.params.out_channels model_config.out_channels = self.num_classes if self.label_key == 'class_label': model_config.pool = pool self.model = __models__[self.label_key](**model_config) #check if model is in torchvision models else: print("Looking for model from torchvision.models") try: self.model = getattr(torchvision.models, self.backbone)(pretrained=True) except: raise NotImplementedError(f"Model {self.backbone} not implemented") if hasattr(self.model, 'fc'): try: self.model.fc = Linear(self.model.fc.in_features, self.num_classes) except: raise NotImplementedError(f"Model {self.backbone} final layer mistmatch") elif hasattr(self.model, 'classifier'): try: print(f"classifier size is {len(self.model.classifier)}") self.model.classifier[-1] = Linear(self.model.classifier[-1].in_features, self.num_classes) except: raise NotImplementedError(f"Model {self.backbone} final layer mistmatch") else: raise NotImplementedError(f"Model {self.backbone} final layer structure not recognized") if ckpt_path is not None: print('#####################################################################') print(f'load from ckpt "{ckpt_path}"') print('#####################################################################') self.init_from_ckpt(ckpt_path) @torch.no_grad() def get_x_noisy(self, x, t, noise=None): noise = default(noise, lambda: torch.randn_like(x)) continuous_sqrt_alpha_cumprod = None # if self.diffusion_model.use_continuous_noise: # continuous_sqrt_alpha_cumprod = self.diffusion_model.sample_continuous_noise_level(x.shape[0], t + 1) # # todo: make sure t+1 is correct here return self.diffusion_model.q_sample(x_start=x, t=t, noise=noise) def forward(self, x_noisy, t, *args, **kwargs): return self.model(x_noisy) #, t) @torch.no_grad() 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() if self.image_transform is not None and self.trainer.training: #print("Applying image transform") x = self.image_transform(x) return x @torch.no_grad() def get_conditioning(self, batch, k=None): if k is None: k = self.label_key assert k is not None, 'Needs to provide label key' targets = batch[k].to(self.device) if self.label_key == 'segmentation': targets = rearrange(targets, 'b h w c -> b c h w') for down in range(self.numd): h, w = targets.shape[-2:] targets = F.interpolate(targets, size=(h // 2, w // 2), mode='nearest') # targets = rearrange(targets,'b c h w -> b h w c') return targets def compute_top_k(self, logits, labels, k, reduction="mean"): _, top_ks = torch.topk(logits, k, dim=1) if reduction == "mean": return (top_ks == labels[:, None]).float().sum(dim=-1).mean().item() elif reduction == "none": return (top_ks == labels[:, None]).float().sum(dim=-1) def on_train_epoch_start(self): # save some memory self.diffusion_model.model.to('cpu') @torch.no_grad() def write_logs(self, loss, logits, targets): log_prefix = 'train' if self.training else 'val' log = {} log[f"{log_prefix}/loss"] = loss.mean() log[f"{log_prefix}/acc@1"] = self.compute_top_k( logits, targets, k=1, reduction="mean" ) log[f"{log_prefix}/acc@5"] = self.compute_top_k( logits, targets, k=5, reduction="mean" ) self.log_dict(log, prog_bar=False, logger=True, on_step=self.training, on_epoch=True) self.log('loss', log[f"{log_prefix}/loss"], prog_bar=True, logger=False) #self.log('global_step', self.global_step, logger=False, on_epoch=False, prog_bar=True) lr = self.optimizers().param_groups[0]['lr'] self.log('lr_abs', lr, on_step=True, logger=True, on_epoch=False, prog_bar=True) def shared_step(self, batch, t=None): x, *_ = self.diffusion_model.get_input(batch, k=self.diffusion_model.first_stage_key) if self.latent_transform is not None and self.trainer.training: #print("Applying latent transform") x = self.latent_transform(x) targets = self.get_conditioning(batch) if targets.dim() == 4: targets = targets.argmax(dim=1) if t is None: t = torch.randint(0, self.diffusion_model.num_timesteps //self.diffusion_classifier_steps_ratio, (x.shape[0],), device=self.device).long() else: t = torch.full(size=(x.shape[0],), fill_value=t, device=self.device).long() x_noisy = self.get_x_noisy(x, t) logits = self(x_noisy, t) loss = F.cross_entropy(logits, targets, reduction='none') self.write_logs(loss.detach(), logits.detach(), targets.detach()) loss = loss.mean() return loss, logits, x_noisy, targets def training_step(self, batch, batch_idx): loss, *_ = self.shared_step(batch) return loss def reset_noise_accs(self): self.noisy_acc = {t: {'acc@1': [], 'acc@5': []} for t in range(0, self.diffusion_model.num_timesteps //self.diffusion_classifier_steps_ratio, self.diffusion_model.log_every_t // self.diffusion_classifier_steps_ratio )} def on_validation_start(self): self.reset_noise_accs() @torch.no_grad() def validation_step(self, batch, batch_idx): loss, *_ = self.shared_step(batch, t=0) for t in self.noisy_acc: _, logits, _, targets = self.shared_step(batch, t) self.noisy_acc[t]['acc@1'].append(self.compute_top_k(logits, targets, k=1, reduction='mean')) self.noisy_acc[t]['acc@5'].append(self.compute_top_k(logits, targets, k=5, reduction='mean')) #log noisy_acc @t [f'inputs@t{current_time}'] # added log self.log(f'val/noisy_acc@{t}@1', self.noisy_acc[t]['acc@1'][-1], on_step=False, on_epoch=True) self.log(f'val/noisy_acc@{t}@5', self.noisy_acc[t]['acc@5'][-1], on_step=False, on_epoch=True) return loss def configure_optimizers(self): optimizer = AdamW(self.model.parameters(), lr=self.learning_rate, weight_decay=self.weight_decay) if self.use_scheduler: scheduler = instantiate_from_config(self.scheduler_config) print("Setting up LambdaLR scheduler...") scheduler = [ { 'scheduler': LambdaLR(optimizer, lr_lambda=scheduler.schedule), 'interval': 'step', 'frequency': 1 }] return [optimizer], scheduler return optimizer @torch.no_grad() def log_images(self, batch, N=8, *args, **kwargs): log = dict() x = self.get_input(batch, self.diffusion_model.first_stage_key) log['inputs'] = x # z, *_ = self.diffusion_model.get_input(batch, k=self.diffusion_model.first_stage_key) # log["inputs_after_first_stage"] = z #log image after first stage model y = self.get_conditioning(batch) if self.label_key == 'class_label':
y = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"])
2
2023-10-10 09:40:10+00:00
12k
casszhao/PruneHall
summac/train_summac.py
[ { "identifier": "select_freer_gpu", "path": "summac/utils_misc.py", "snippet": "def select_freer_gpu():\n freer_gpu = str(get_freer_gpu())\n print(\"Will use GPU: %s\" % (freer_gpu))\n os.environ['CUDA_LAUNCH_BLOCKING'] = \"1\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"+freer_gpu\n ret...
from .utils_misc import select_freer_gpu from torch.utils.data import DataLoader, RandomSampler from .utils_optim import build_optimizer from .benchmark import SummaCBenchmark, load_factcc from .model_summac import SummaCConv, model_map import torch, tqdm, nltk, numpy as np, argparse, json import os, time
7,231
select_freer_gpu() def train(model="mnli", granularity="sentence", nli_labels="e", pre_file="", num_epochs=5, optimizer="adam", train_batch_size=32, learning_rate=0.1, bins="even50", silent=False, norm_histo=False): experiment = "%s_%s_%s_%s" % (model, granularity, bins, nli_labels) if not silent: print("Experiment name: %s" % (experiment)) if len(pre_file) == 0: standard_pre_file = "/home/phillab/data/summac_cache/train_%s_%s.jsonl" % (model, granularity) if os.path.isfile(standard_pre_file): pre_file = standard_pre_file precomputed = len(pre_file) > 0 device = "cpu" if precomputed else "cuda" if model == "multi": models = ["mnli", "anli", "vitc"] elif model == "multi2": models = ["mnli", "vitc", "vitc-only", "vitc-base"] else: models = [model] model = SummaCConv(models=models, granularity=granularity, nli_labels=nli_labels, device=device, bins=bins, norm_histo=norm_histo) optimizer = build_optimizer(model, learning_rate=learning_rate, optimizer_name=optimizer) if not silent: print("Model Loaded") def sent_tok(text): sentences = nltk.tokenize.sent_tokenize(text) return [sent for sent in sentences if len(sent)>10] def collate_func(inps): documents, claims, labels = [], [], [] for inp in inps: if len(sent_tok(inp["claim"])) > 0 and len(sent_tok(inp["document"])) > 0: documents.append(inp["document"]) claims.append(inp["claim"]) labels.append(inp["label"]) labels = torch.LongTensor(labels).to(device) return documents, claims, labels def collate_pre(inps): documents = [inp["document"] for inp in inps] claims = [inp["claim"] for inp in inps] # images = [[np.array(im) for im in inp["image"]] for inp in inps] images = [np.array(inp["image"]) for inp in inps] labels = torch.LongTensor([inp["label"] for inp in inps]).to(device) return documents, claims, images, labels if precomputed: d_train = [] with open(pre_file, "r") as f: for line in f: d_train.append(json.loads(line)) dl_train = DataLoader(dataset=d_train, batch_size=train_batch_size, sampler=RandomSampler(d_train), collate_fn=collate_pre) else:
select_freer_gpu() def train(model="mnli", granularity="sentence", nli_labels="e", pre_file="", num_epochs=5, optimizer="adam", train_batch_size=32, learning_rate=0.1, bins="even50", silent=False, norm_histo=False): experiment = "%s_%s_%s_%s" % (model, granularity, bins, nli_labels) if not silent: print("Experiment name: %s" % (experiment)) if len(pre_file) == 0: standard_pre_file = "/home/phillab/data/summac_cache/train_%s_%s.jsonl" % (model, granularity) if os.path.isfile(standard_pre_file): pre_file = standard_pre_file precomputed = len(pre_file) > 0 device = "cpu" if precomputed else "cuda" if model == "multi": models = ["mnli", "anli", "vitc"] elif model == "multi2": models = ["mnli", "vitc", "vitc-only", "vitc-base"] else: models = [model] model = SummaCConv(models=models, granularity=granularity, nli_labels=nli_labels, device=device, bins=bins, norm_histo=norm_histo) optimizer = build_optimizer(model, learning_rate=learning_rate, optimizer_name=optimizer) if not silent: print("Model Loaded") def sent_tok(text): sentences = nltk.tokenize.sent_tokenize(text) return [sent for sent in sentences if len(sent)>10] def collate_func(inps): documents, claims, labels = [], [], [] for inp in inps: if len(sent_tok(inp["claim"])) > 0 and len(sent_tok(inp["document"])) > 0: documents.append(inp["document"]) claims.append(inp["claim"]) labels.append(inp["label"]) labels = torch.LongTensor(labels).to(device) return documents, claims, labels def collate_pre(inps): documents = [inp["document"] for inp in inps] claims = [inp["claim"] for inp in inps] # images = [[np.array(im) for im in inp["image"]] for inp in inps] images = [np.array(inp["image"]) for inp in inps] labels = torch.LongTensor([inp["label"] for inp in inps]).to(device) return documents, claims, images, labels if precomputed: d_train = [] with open(pre_file, "r") as f: for line in f: d_train.append(json.loads(line)) dl_train = DataLoader(dataset=d_train, batch_size=train_batch_size, sampler=RandomSampler(d_train), collate_fn=collate_pre) else:
d_train = load_factcc(cut="train")
3
2023-10-13 11:29:39+00:00
12k
cpuimage/minSDXLTF
stable_diffusion_xl/stable_diffusion_xl.py
[ { "identifier": "SimpleTokenizer", "path": "stable_diffusion_xl/clip_tokenizer.py", "snippet": "class SimpleTokenizer:\n def __init__(self, bpe_path=None):\n bpe_path = bpe_path or tf.keras.utils.get_file(\n \"bpe_simple_vocab_16e6.txt.gz\",\n \"https://github.com/openai/...
import numpy as np import tensorflow as tf from PIL import Image from scipy.ndimage import correlate1d from .clip_tokenizer import SimpleTokenizer from .diffusion_model import DiffusionXLModel from .image_decoder import ImageDecoder from .image_encoder import ImageEncoder from .long_prompt_weighting import get_weighted_text_embeddings from .scheduler import Scheduler from .text_encoder_laion import TextEncoderLaion, TextEncoderLaionProj from .text_encoder_openai import TextEncoderOpenAi
10,336
# Copyright 2022 The KerasCV Authors # # 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 # # https://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. """Keras implementation of StableDiffusionXL.""" MAX_PROMPT_LENGTH = 77 class StableDiffusionXLBase: """Base class for stable diffusion xl model.""" def __init__(self, img_height=1024, img_width=1024, jit_compile=False, active_lcm=False): self.img_height = img_height self.img_width = img_width # lazy initialize the component models and the tokenizer self._image_encoder = None self._text_encoder_laion = None self._text_encoder_laion_proj = None self._text_encoder_openai = None self._diffusion_model = None self._image_decoder = None self._tokenizer = None self.jit_compile = jit_compile self.active_lcm = active_lcm
# Copyright 2022 The KerasCV Authors # # 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 # # https://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. """Keras implementation of StableDiffusionXL.""" MAX_PROMPT_LENGTH = 77 class StableDiffusionXLBase: """Base class for stable diffusion xl model.""" def __init__(self, img_height=1024, img_width=1024, jit_compile=False, active_lcm=False): self.img_height = img_height self.img_width = img_width # lazy initialize the component models and the tokenizer self._image_encoder = None self._text_encoder_laion = None self._text_encoder_laion_proj = None self._text_encoder_openai = None self._diffusion_model = None self._image_decoder = None self._tokenizer = None self.jit_compile = jit_compile self.active_lcm = active_lcm
self.scheduler = Scheduler(active_lcm=active_lcm)
5
2023-10-14 18:40:16+00:00
12k
cumulo-autumn/StreamDiffusion
examples/screen/main.py
[ { "identifier": "receive_images", "path": "utils/viewer.py", "snippet": "def receive_images(queue: Queue, fps_queue: Queue) -> None:\n \"\"\"\n Setup the Tkinter window and start the thread to receive images.\n\n Parameters\n ----------\n queue : Queue\n The queue to receive images...
import os import sys import time import threading import torch import PIL.Image import mss import fire import tkinter as tk from multiprocessing import Process, Queue, get_context from multiprocessing.connection import Connection from typing import List, Literal, Dict, Optional from streamdiffusion.image_utils import pil2tensor from utils.viewer import receive_images from utils.wrapper import StreamDiffusionWrapper
8,251
use_denoising_batch=use_denoising_batch, cfg_type=cfg_type, seed=seed, ) stream.prepare( prompt=prompt, negative_prompt=negative_prompt, num_inference_steps=50, guidance_scale=guidance_scale, delta=delta, ) monitor = monitor_receiver.recv() event = threading.Event() input_screen = threading.Thread(target=screen, args=(event, height, width, monitor)) input_screen.start() time.sleep(5) while True: try: if not close_queue.empty(): # closing check break if len(inputs) < frame_buffer_size: time.sleep(0.005) continue start_time = time.time() sampled_inputs = [] for i in range(frame_buffer_size): index = (len(inputs) // frame_buffer_size) * i sampled_inputs.append(inputs[len(inputs) - index - 1]) input_batch = torch.cat(sampled_inputs) inputs.clear() output_images = stream.stream( input_batch.to(device=stream.device, dtype=stream.dtype) ).cpu() if frame_buffer_size == 1: output_images = [output_images] for output_image in output_images: queue.put(output_image, block=False) fps = 1 / (time.time() - start_time) fps_queue.put(fps) except KeyboardInterrupt: break print("closing image_generation_process...") event.set() # stop capture thread input_screen.join() print(f"fps: {fps}") def main( model_id_or_path: str = "KBlueLeaf/kohaku-v2.1", lora_dict: Optional[Dict[str, float]] = None, prompt: str = "1girl with brown dog hair, thick glasses, smiling", negative_prompt: str = "low quality, bad quality, blurry, low resolution", frame_buffer_size: int = 1, width: int = 512, height: int = 512, acceleration: Literal["none", "xformers", "tensorrt"] = "xformers", use_denoising_batch: bool = True, seed: int = 2, cfg_type: Literal["none", "full", "self", "initialize"] = "self", guidance_scale: float = 1.4, delta: float = 0.5, do_add_noise: bool = False, enable_similar_image_filter: bool = True, similar_image_filter_threshold: float = 0.99, similar_image_filter_max_skip_frame: float = 10, ) -> None: """ Main function to start the image generation and viewer processes. """ ctx = get_context('spawn') queue = ctx.Queue() fps_queue = ctx.Queue() close_queue = Queue() monitor_sender, monitor_receiver = ctx.Pipe() process1 = ctx.Process( target=image_generation_process, args=( queue, fps_queue, close_queue, model_id_or_path, lora_dict, prompt, negative_prompt, frame_buffer_size, width, height, acceleration, use_denoising_batch, seed, cfg_type, guidance_scale, delta, do_add_noise, enable_similar_image_filter, similar_image_filter_threshold, similar_image_filter_max_skip_frame, monitor_receiver, ), ) process1.start() monitor_process = ctx.Process( target=monitor_setting_process, args=( width, height, monitor_sender, ), ) monitor_process.start() monitor_process.join()
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..")) inputs = [] top = 0 left = 0 def screen( event: threading.Event, height: int = 512, width: int = 512, monitor: Dict[str, int] = {"top": 300, "left": 200, "width": 512, "height": 512}, ): global inputs with mss.mss() as sct: while True: if event.is_set(): print("terminate read thread") break img = sct.grab(monitor) img = PIL.Image.frombytes("RGB", img.size, img.bgra, "raw", "BGRX") img.resize((height, width)) inputs.append(pil2tensor(img)) print('exit : screen') def dummy_screen( width: int, height: int, ): root = tk.Tk() root.title("Press Enter to start") root.geometry(f"{width}x{height}") root.resizable(False, False) root.attributes("-alpha", 0.8) root.configure(bg="black") def destroy(event): root.destroy() root.bind("<Return>", destroy) def update_geometry(event): global top, left top = root.winfo_y() left = root.winfo_x() root.bind("<Configure>", update_geometry) root.mainloop() return {"top": top, "left": left, "width": width, "height": height} def monitor_setting_process( width: int, height: int, monitor_sender: Connection, ) -> None: monitor = dummy_screen(width, height) monitor_sender.send(monitor) def image_generation_process( queue: Queue, fps_queue: Queue, close_queue: Queue, model_id_or_path: str, lora_dict: Optional[Dict[str, float]], prompt: str, negative_prompt: str, frame_buffer_size: int, width: int, height: int, acceleration: Literal["none", "xformers", "tensorrt"], use_denoising_batch: bool, seed: int, cfg_type: Literal["none", "full", "self", "initialize"], guidance_scale: float, delta: float, do_add_noise: bool, enable_similar_image_filter: bool, similar_image_filter_threshold: float, similar_image_filter_max_skip_frame: float, monitor_receiver : Connection, ) -> None: """ Process for generating images based on a prompt using a specified model. Parameters ---------- queue : Queue The queue to put the generated images in. fps_queue : Queue The queue to put the calculated fps. model_id_or_path : str The name of the model to use for image generation. lora_dict : Optional[Dict[str, float]], optional The lora_dict to load, by default None. Keys are the LoRA names and values are the LoRA scales. Example: {'LoRA_1' : 0.5 , 'LoRA_2' : 0.7 ,...} prompt : str The prompt to generate images from. negative_prompt : str, optional The negative prompt to use. frame_buffer_size : int, optional The frame buffer size for denoising batch, by default 1. width : int, optional The width of the image, by default 512. height : int, optional The height of the image, by default 512. acceleration : Literal["none", "xformers", "tensorrt"], optional The acceleration method, by default "tensorrt". use_denoising_batch : bool, optional Whether to use denoising batch or not, by default True. seed : int, optional The seed, by default 2. if -1, use random seed. cfg_type : Literal["none", "full", "self", "initialize"], optional The cfg_type for img2img mode, by default "self". You cannot use anything other than "none" for txt2img mode. guidance_scale : float, optional The CFG scale, by default 1.2. delta : float, optional The delta multiplier of virtual residual noise, by default 1.0. do_add_noise : bool, optional Whether to add noise for following denoising steps or not, by default True. enable_similar_image_filter : bool, optional Whether to enable similar image filter or not, by default False. similar_image_filter_threshold : float, optional The threshold for similar image filter, by default 0.98. similar_image_filter_max_skip_frame : int, optional The max skip frame for similar image filter, by default 10. """ global inputs stream = StreamDiffusionWrapper( model_id_or_path=model_id_or_path, lora_dict=lora_dict, t_index_list=[32, 45], frame_buffer_size=frame_buffer_size, width=width, height=height, warmup=10, acceleration=acceleration, do_add_noise=do_add_noise, enable_similar_image_filter=enable_similar_image_filter, similar_image_filter_threshold=similar_image_filter_threshold, similar_image_filter_max_skip_frame=similar_image_filter_max_skip_frame, mode="img2img", use_denoising_batch=use_denoising_batch, cfg_type=cfg_type, seed=seed, ) stream.prepare( prompt=prompt, negative_prompt=negative_prompt, num_inference_steps=50, guidance_scale=guidance_scale, delta=delta, ) monitor = monitor_receiver.recv() event = threading.Event() input_screen = threading.Thread(target=screen, args=(event, height, width, monitor)) input_screen.start() time.sleep(5) while True: try: if not close_queue.empty(): # closing check break if len(inputs) < frame_buffer_size: time.sleep(0.005) continue start_time = time.time() sampled_inputs = [] for i in range(frame_buffer_size): index = (len(inputs) // frame_buffer_size) * i sampled_inputs.append(inputs[len(inputs) - index - 1]) input_batch = torch.cat(sampled_inputs) inputs.clear() output_images = stream.stream( input_batch.to(device=stream.device, dtype=stream.dtype) ).cpu() if frame_buffer_size == 1: output_images = [output_images] for output_image in output_images: queue.put(output_image, block=False) fps = 1 / (time.time() - start_time) fps_queue.put(fps) except KeyboardInterrupt: break print("closing image_generation_process...") event.set() # stop capture thread input_screen.join() print(f"fps: {fps}") def main( model_id_or_path: str = "KBlueLeaf/kohaku-v2.1", lora_dict: Optional[Dict[str, float]] = None, prompt: str = "1girl with brown dog hair, thick glasses, smiling", negative_prompt: str = "low quality, bad quality, blurry, low resolution", frame_buffer_size: int = 1, width: int = 512, height: int = 512, acceleration: Literal["none", "xformers", "tensorrt"] = "xformers", use_denoising_batch: bool = True, seed: int = 2, cfg_type: Literal["none", "full", "self", "initialize"] = "self", guidance_scale: float = 1.4, delta: float = 0.5, do_add_noise: bool = False, enable_similar_image_filter: bool = True, similar_image_filter_threshold: float = 0.99, similar_image_filter_max_skip_frame: float = 10, ) -> None: """ Main function to start the image generation and viewer processes. """ ctx = get_context('spawn') queue = ctx.Queue() fps_queue = ctx.Queue() close_queue = Queue() monitor_sender, monitor_receiver = ctx.Pipe() process1 = ctx.Process( target=image_generation_process, args=( queue, fps_queue, close_queue, model_id_or_path, lora_dict, prompt, negative_prompt, frame_buffer_size, width, height, acceleration, use_denoising_batch, seed, cfg_type, guidance_scale, delta, do_add_noise, enable_similar_image_filter, similar_image_filter_threshold, similar_image_filter_max_skip_frame, monitor_receiver, ), ) process1.start() monitor_process = ctx.Process( target=monitor_setting_process, args=( width, height, monitor_sender, ), ) monitor_process.start() monitor_process.join()
process2 = ctx.Process(target=receive_images, args=(queue, fps_queue))
0
2023-11-28 13:40:30+00:00
12k
zhyever/PatchFusion
ui_prediction.py
[ { "identifier": "parse_unknown", "path": "zoedepth/utils/arg_utils.py", "snippet": "def parse_unknown(unknown_args):\n clean = []\n for a in unknown_args:\n if \"=\" in a:\n k, v = a.split(\"=\")\n clean.extend([k, v])\n else:\n clean.append(a)\n\n ...
import gradio as gr import tempfile import torch import numpy as np import argparse import matplotlib import cv2 import torch.nn.functional as F import gradio as gr import numpy as np import trimesh import tempfile from PIL import Image from zoedepth.utils.arg_utils import parse_unknown from zoedepth.models.builder import build_model from zoedepth.utils.config import get_config_user from infer_user import regular_tile_param, random_tile_param from zoedepth.models.base_models.midas import Resize from torchvision.transforms import Compose from PIL import Image from torchvision import transforms from zoedepth.models.base_models.midas import Resize from torchvision.transforms import Compose from zoedepth.utils.geometry import depth_to_points, create_triangles from functools import partial
9,100
# 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 def depth_edges_mask(depth, occ_filter_thr): """Returns a mask of edges in the depth map. Args: depth: 2D numpy array of shape (H, W) with dtype float32. Returns: mask: 2D numpy array of shape (H, W) with dtype bool. """ # Compute the x and y gradients of the depth map. depth_dx, depth_dy = np.gradient(depth) # Compute the gradient magnitude. depth_grad = np.sqrt(depth_dx ** 2 + depth_dy ** 2) # Compute the edge mask. # mask = depth_grad > 0.05 # default in zoedepth mask = depth_grad > occ_filter_thr # preserve more edges (?) return mask def load_state_dict(model, state_dict): """Load state_dict into model, handling DataParallel and DistributedDataParallel. Also checks for "model" key in state_dict. DataParallel prefixes state_dict keys with 'module.' when saving. If the model is not a DataParallel model but the state_dict is, then prefixes are removed. If the model is a DataParallel model but the state_dict is not, then prefixes are added. """ state_dict = state_dict.get('model', state_dict) # if model is a DataParallel model, then state_dict keys are prefixed with 'module.' do_prefix = isinstance( model, (torch.nn.DataParallel, torch.nn.parallel.DistributedDataParallel)) state = {} for k, v in state_dict.items(): if k.startswith('module.') and not do_prefix: k = k[7:] if not k.startswith('module.') and do_prefix: k = 'module.' + k state[k] = v model.load_state_dict(state, strict=True) print("Loaded successfully") return model def load_wts(model, checkpoint_path): ckpt = torch.load(checkpoint_path, map_location='cpu') return load_state_dict(model, ckpt) def load_ckpt(model, checkpoint): model = load_wts(model, checkpoint) print("Loaded weights from {0}".format(checkpoint)) return model parser = argparse.ArgumentParser() parser.add_argument("--ckp_path", type=str, required=True) parser.add_argument("-m", "--model", type=str, default="zoedepth") parser.add_argument("--model_cfg_path", type=str, default="") args, unknown_args = parser.parse_known_args() overwrite_kwargs = parse_unknown(unknown_args) overwrite_kwargs['model_cfg_path'] = args.model_cfg_path overwrite_kwargs["model"] = args.model config = get_config_user(args.model, **overwrite_kwargs) config["pretrained_resource"] = '' model = build_model(config) model = load_ckpt(model, args.ckp_path) model.eval() model.cuda() def colorize(value, cmap='magma_r', vmin=None, vmax=None): # normalize vmin = value.min() if vmin is None else vmin # vmax = value.max() if vmax is None else vmax vmax = np.percentile(value, 95) if vmax is None else vmax if vmin != vmax: value = (value - vmin) / (vmax - vmin) # vmin..vmax else: value = value * 0. cmapper = matplotlib.cm.get_cmap(cmap) value = cmapper(value, bytes=True) # ((1)xhxwx4) value = value[:, :, :3] # bgr -> rgb # rgb_value = value[..., ::-1] rgb_value = value return rgb_value def predict_depth(model, image, mode, pn, reso, ps): pil_image = image image = transforms.ToTensor()(pil_image).unsqueeze(0).cuda() image_height, image_width = image.shape[-2], image.shape[-1] if reso != '': image_resolution = (int(reso.split('x')[0]), int(reso.split('x')[1])) else: image_resolution = (2160, 3840) image_hr = F.interpolate(image, image_resolution, mode='bicubic', align_corners=True)
# 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 def depth_edges_mask(depth, occ_filter_thr): """Returns a mask of edges in the depth map. Args: depth: 2D numpy array of shape (H, W) with dtype float32. Returns: mask: 2D numpy array of shape (H, W) with dtype bool. """ # Compute the x and y gradients of the depth map. depth_dx, depth_dy = np.gradient(depth) # Compute the gradient magnitude. depth_grad = np.sqrt(depth_dx ** 2 + depth_dy ** 2) # Compute the edge mask. # mask = depth_grad > 0.05 # default in zoedepth mask = depth_grad > occ_filter_thr # preserve more edges (?) return mask def load_state_dict(model, state_dict): """Load state_dict into model, handling DataParallel and DistributedDataParallel. Also checks for "model" key in state_dict. DataParallel prefixes state_dict keys with 'module.' when saving. If the model is not a DataParallel model but the state_dict is, then prefixes are removed. If the model is a DataParallel model but the state_dict is not, then prefixes are added. """ state_dict = state_dict.get('model', state_dict) # if model is a DataParallel model, then state_dict keys are prefixed with 'module.' do_prefix = isinstance( model, (torch.nn.DataParallel, torch.nn.parallel.DistributedDataParallel)) state = {} for k, v in state_dict.items(): if k.startswith('module.') and not do_prefix: k = k[7:] if not k.startswith('module.') and do_prefix: k = 'module.' + k state[k] = v model.load_state_dict(state, strict=True) print("Loaded successfully") return model def load_wts(model, checkpoint_path): ckpt = torch.load(checkpoint_path, map_location='cpu') return load_state_dict(model, ckpt) def load_ckpt(model, checkpoint): model = load_wts(model, checkpoint) print("Loaded weights from {0}".format(checkpoint)) return model parser = argparse.ArgumentParser() parser.add_argument("--ckp_path", type=str, required=True) parser.add_argument("-m", "--model", type=str, default="zoedepth") parser.add_argument("--model_cfg_path", type=str, default="") args, unknown_args = parser.parse_known_args() overwrite_kwargs = parse_unknown(unknown_args) overwrite_kwargs['model_cfg_path'] = args.model_cfg_path overwrite_kwargs["model"] = args.model config = get_config_user(args.model, **overwrite_kwargs) config["pretrained_resource"] = '' model = build_model(config) model = load_ckpt(model, args.ckp_path) model.eval() model.cuda() def colorize(value, cmap='magma_r', vmin=None, vmax=None): # normalize vmin = value.min() if vmin is None else vmin # vmax = value.max() if vmax is None else vmax vmax = np.percentile(value, 95) if vmax is None else vmax if vmin != vmax: value = (value - vmin) / (vmax - vmin) # vmin..vmax else: value = value * 0. cmapper = matplotlib.cm.get_cmap(cmap) value = cmapper(value, bytes=True) # ((1)xhxwx4) value = value[:, :, :3] # bgr -> rgb # rgb_value = value[..., ::-1] rgb_value = value return rgb_value def predict_depth(model, image, mode, pn, reso, ps): pil_image = image image = transforms.ToTensor()(pil_image).unsqueeze(0).cuda() image_height, image_width = image.shape[-2], image.shape[-1] if reso != '': image_resolution = (int(reso.split('x')[0]), int(reso.split('x')[1])) else: image_resolution = (2160, 3840) image_hr = F.interpolate(image, image_resolution, mode='bicubic', align_corners=True)
preprocess = Compose([Resize(512, 384, keep_aspect_ratio=False, ensure_multiple_of=32, resize_method="minimal")])
6
2023-12-04 08:43:15+00:00
12k
LTH14/rcg
main_adm.py
[ { "identifier": "NativeScalerWithGradNormCount", "path": "util/misc.py", "snippet": "class NativeScalerWithGradNormCount:\n state_dict_key = \"amp_scaler\"\n\n def __init__(self):\n self._scaler = torch.cuda.amp.GradScaler()\n\n def __call__(self, loss, optimizer, clip_grad=None, paramet...
import argparse import datetime import json import numpy as np import os import time import copy import torch import torch.backends.cudnn as cudnn import torchvision.transforms as transforms import torchvision.datasets as datasets import timm import util.misc as misc import pretrained_enc.models_pretrained_enc as models_pretrained_enc from pathlib import Path from torch.utils.tensorboard import SummaryWriter from util.misc import NativeScalerWithGradNormCount as NativeScaler from engine_adm import train_one_epoch, gen_img from pixel_generator.guided_diffusion.resample import create_named_schedule_sampler from pixel_generator.guided_diffusion.script_util import ( model_and_diffusion_defaults, create_model_and_diffusion, create_gaussian_diffusion, args_to_dict, ) from rdm.util import load_model from rdm.models.diffusion.ddim import DDIMSampler from omegaconf import OmegaConf
8,696
sampler_train = torch.utils.data.RandomSampler(dataset_train) data_loader_train = torch.utils.data.DataLoader( dataset_train, sampler=sampler_train, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True, ) # load model model, diffusion = create_model_and_diffusion( **args_to_dict(args, model_and_diffusion_defaults().keys()) ) model.to(device) schedule_sampler = create_named_schedule_sampler(args.schedule_sampler, diffusion) # pre-trained encoder if args.rep_cond: assert args.pretrained_enc_path is not None pretrained_encoder = models_pretrained_enc.__dict__[args.pretrained_enc_arch](proj_dim=args.rep_dim) # load pre-trained encoder parameters if 'moco' in args.pretrained_enc_arch: pretrained_encoder = models_pretrained_enc.load_pretrained_moco(pretrained_encoder, args.pretrained_enc_path) else: raise NotImplementedError for param in pretrained_encoder.parameters(): param.requires_grad = False pretrained_encoder.to(device) pretrained_encoder.eval() else: pretrained_encoder = None # pre-trained RDM if args.rep_cond: rdm_config = OmegaConf.load(args.pretrained_rdm_cfg) ldm_model = load_model(rdm_config, args.pretrained_rdm_ckpt) rdm_sampler = DDIMSampler(ldm_model) else: rdm_sampler = None # sampling diffusion gen_diffusion = create_gaussian_diffusion( steps=args.diffusion_steps, learn_sigma=args.learn_sigma, noise_schedule=args.noise_schedule, use_kl=args.use_kl, predict_xstart=args.predict_xstart, rescale_timesteps=args.rescale_timesteps, rescale_learned_sigmas=args.rescale_learned_sigmas, timestep_respacing=args.gen_timestep_respacing, ) model_without_ddp = model print("Model = %s" % str(model_without_ddp)) eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size() if args.lr is None: # only base_lr is specified args.lr = args.blr * eff_batch_size print("base lr: %.2e" % (args.lr / eff_batch_size)) print("actual lr: %.2e" % args.lr) print("accumulate grad iterations: %d" % args.accum_iter) print("effective batch size: %d" % eff_batch_size) if args.distributed: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True) model_without_ddp = model.module # Log parameters params = list(model_without_ddp.parameters()) n_params = sum(p.numel() for p in model_without_ddp.parameters() if p.requires_grad) print("Number of trainable parameters: {}M".format(n_params / 1e6)) if global_rank == 0: log_writer.add_scalar('num_params', n_params / 1e6, 0) optimizer = torch.optim.AdamW(params, lr=args.lr, weight_decay=args.weight_decay) print(optimizer) loss_scaler = NativeScaler() # Resume training or from pre-trained unconditional ADM if os.path.exists(os.path.join(args.resume, "checkpoint-last.pth")): resume_path = os.path.join(args.resume, "checkpoint-last.pth") else: resume_path = args.resume if resume_path: checkpoint = torch.load(args.resume, map_location='cpu') model_without_ddp.load_state_dict(checkpoint['model']) model_params = list(model_without_ddp.parameters()) ema_state_dict = checkpoint['model_ema'] ema_params = [ema_state_dict[name].cuda() for name, _ in model_without_ddp.named_parameters()] print("Resume checkpoint %s" % args.resume) if 'optimizer' in checkpoint and 'epoch' in checkpoint and not (hasattr(args, 'eval') and args.eval): optimizer.load_state_dict(checkpoint['optimizer']) args.start_epoch = checkpoint['epoch'] + 1 if 'scaler' in checkpoint: loss_scaler.load_state_dict(checkpoint['scaler']) print("With optim & sched!") else: model_params = list(model_without_ddp.parameters()) ema_params = copy.deepcopy(model_params) print("Training from scratch") if args.evaluate: print("Start evaluating") gen_img(model, model_without_ddp, gen_diffusion, ema_params, rdm_sampler, args, 0, batch_size=16, log_writer=log_writer, use_ema=True) return print(f"Start training for {args.epochs} epochs") start_time = time.time() for epoch in range(args.start_epoch, args.epochs): if args.distributed: data_loader_train.sampler.set_epoch(epoch)
assert timm.__version__ == "0.3.2" # version check def get_args_parser(): parser = argparse.ArgumentParser('ADM training', add_help=False) parser.add_argument('--batch_size', default=4, type=int, help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus') parser.add_argument('--epochs', default=400, type=int) parser.add_argument('--accum_iter', default=1, type=int, help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)') # config parser.add_argument('--image_size', default=256, type=int, help='images input size') parser.add_argument('--config', type=str, help='config file') # Optimizer parameters parser.add_argument('--weight_decay', type=float, default=0.05, help='weight decay (default: 0.05)') parser.add_argument('--lr', type=float, default=None, metavar='LR', help='learning rate (absolute lr)') parser.add_argument('--blr', type=float, default=1e-6, metavar='LR', help='base learning rate: absolute_lr = base_lr * total_batch_size') parser.add_argument('--min_lr', type=float, default=0., metavar='LR', help='lower lr bound for cyclic schedulers that hit 0') parser.add_argument('--cosine_lr', action='store_true', help='Use cosine lr scheduling.') parser.add_argument('--warmup_epochs', default=0, type=int) # ADM parameters parser.add_argument('--schedule_sampler', default='uniform', type=str) parser.add_argument('--lr_anneal_steps', default=0, type=int) parser.add_argument('--microbatch', default=-1, type=int) parser.add_argument('--ema_rate', default=0.9999, type=float) parser.add_argument('--use_fp16', action='store_true') parser.add_argument('--fp16_scale_growth', default=1e-3, type=float) # ADM model parameters parser.add_argument('--num_channels', default=128, type=int) parser.add_argument('--num_res_blocks', default=2, type=int) parser.add_argument('--num_heads', default=4, type=int) parser.add_argument('--num_heads_upsample', default=-1, type=int) parser.add_argument('--num_head_channels', default=-1, type=int) parser.add_argument('--attention_resolutions', default="16,8", type=str) parser.add_argument('--channel_mult', default="", type=str) parser.add_argument('--dropout', default=0.0, type=float) parser.add_argument('--class_cond', action='store_true') parser.add_argument('--use_checkpoint', action='store_true') parser.add_argument('--use_scale_shift_norm', action='store_true') parser.add_argument('--resblock_updown', action='store_true') parser.add_argument('--use_new_attention_order', action='store_true') # ADM diffusion parameters parser.add_argument('--learn_sigma', action='store_true') parser.add_argument('--use_kl', action='store_true') parser.add_argument('--predict_xstart', action='store_true') parser.add_argument('--rescale_timesteps', action='store_true') parser.add_argument('--rescale_learned_sigmas', action='store_true') parser.add_argument('--diffusion_steps', default=1000, type=int) parser.add_argument('--noise_schedule', default="linear", type=str) parser.add_argument('--timestep_respacing', default="", type=str) # RDM parameters parser.add_argument('--rep_cond', action='store_true') parser.add_argument('--rep_dim', default=256, type=int) parser.add_argument('--pretrained_enc_arch', default=None, type=str) parser.add_argument('--pretrained_enc_path', default=None, type=str) parser.add_argument('--rdm_steps', default=250, type=int) parser.add_argument('--rdm_eta', default=1.0, type=float) parser.add_argument('--pretrained_rdm_cfg', default=None, type=str) parser.add_argument('--pretrained_rdm_ckpt', default=None, type=str) # ADM generation parameters parser.add_argument('--evaluate', action='store_true', help="perform only evaluation") parser.add_argument('--eval_freq', type=int, default=8, help='evaluation frequency') parser.add_argument('--num_images', default=50000, type=int) parser.add_argument('--use_ddim', action='store_true') parser.add_argument('--gen_timestep_respacing', default="", type=str) # Dataset parameters parser.add_argument('--data_path', default='./data/imagenet', type=str, help='dataset path') parser.add_argument('--output_dir', default='./output_dir', help='path where to save, empty for no saving') parser.add_argument('--log_dir', default='./output_dir', help='path where to tensorboard log') parser.add_argument('--device', default='cuda', help='device to use for training / testing') parser.add_argument('--seed', default=0, type=int) parser.add_argument('--resume', default='', help='resume from checkpoint') parser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='start epoch') parser.add_argument('--num_workers', default=10, type=int) parser.add_argument('--pin_mem', action='store_true', help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem') parser.set_defaults(pin_mem=True) # distributed training parameters parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--local_rank', default=-1, type=int) parser.add_argument('--dist_on_itp', action='store_true') parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') return parser def main(args): misc.init_distributed_mode(args) print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__)))) print("{}".format(args).replace(', ', ',\n')) device = torch.device(args.device) # fix the seed for reproducibility seed = args.seed + misc.get_rank() torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True num_tasks = misc.get_world_size() global_rank = misc.get_rank() if global_rank == 0 and args.log_dir is not None: os.makedirs(args.log_dir, exist_ok=True) log_writer = SummaryWriter(log_dir=args.log_dir) else: log_writer = None transform_train = transforms.Compose([ transforms.Resize(256, interpolation=3), transforms.RandomCrop(256), transforms.RandomHorizontalFlip(), transforms.ToTensor()]) dataset_train = datasets.ImageFolder(os.path.join(args.data_path, 'train'), transform=transform_train) print(dataset_train) if True: # args.distributed: sampler_train = torch.utils.data.DistributedSampler( dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True ) print("Sampler_train = %s" % str(sampler_train)) else: sampler_train = torch.utils.data.RandomSampler(dataset_train) data_loader_train = torch.utils.data.DataLoader( dataset_train, sampler=sampler_train, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True, ) # load model model, diffusion = create_model_and_diffusion( **args_to_dict(args, model_and_diffusion_defaults().keys()) ) model.to(device) schedule_sampler = create_named_schedule_sampler(args.schedule_sampler, diffusion) # pre-trained encoder if args.rep_cond: assert args.pretrained_enc_path is not None pretrained_encoder = models_pretrained_enc.__dict__[args.pretrained_enc_arch](proj_dim=args.rep_dim) # load pre-trained encoder parameters if 'moco' in args.pretrained_enc_arch: pretrained_encoder = models_pretrained_enc.load_pretrained_moco(pretrained_encoder, args.pretrained_enc_path) else: raise NotImplementedError for param in pretrained_encoder.parameters(): param.requires_grad = False pretrained_encoder.to(device) pretrained_encoder.eval() else: pretrained_encoder = None # pre-trained RDM if args.rep_cond: rdm_config = OmegaConf.load(args.pretrained_rdm_cfg) ldm_model = load_model(rdm_config, args.pretrained_rdm_ckpt) rdm_sampler = DDIMSampler(ldm_model) else: rdm_sampler = None # sampling diffusion gen_diffusion = create_gaussian_diffusion( steps=args.diffusion_steps, learn_sigma=args.learn_sigma, noise_schedule=args.noise_schedule, use_kl=args.use_kl, predict_xstart=args.predict_xstart, rescale_timesteps=args.rescale_timesteps, rescale_learned_sigmas=args.rescale_learned_sigmas, timestep_respacing=args.gen_timestep_respacing, ) model_without_ddp = model print("Model = %s" % str(model_without_ddp)) eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size() if args.lr is None: # only base_lr is specified args.lr = args.blr * eff_batch_size print("base lr: %.2e" % (args.lr / eff_batch_size)) print("actual lr: %.2e" % args.lr) print("accumulate grad iterations: %d" % args.accum_iter) print("effective batch size: %d" % eff_batch_size) if args.distributed: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True) model_without_ddp = model.module # Log parameters params = list(model_without_ddp.parameters()) n_params = sum(p.numel() for p in model_without_ddp.parameters() if p.requires_grad) print("Number of trainable parameters: {}M".format(n_params / 1e6)) if global_rank == 0: log_writer.add_scalar('num_params', n_params / 1e6, 0) optimizer = torch.optim.AdamW(params, lr=args.lr, weight_decay=args.weight_decay) print(optimizer) loss_scaler = NativeScaler() # Resume training or from pre-trained unconditional ADM if os.path.exists(os.path.join(args.resume, "checkpoint-last.pth")): resume_path = os.path.join(args.resume, "checkpoint-last.pth") else: resume_path = args.resume if resume_path: checkpoint = torch.load(args.resume, map_location='cpu') model_without_ddp.load_state_dict(checkpoint['model']) model_params = list(model_without_ddp.parameters()) ema_state_dict = checkpoint['model_ema'] ema_params = [ema_state_dict[name].cuda() for name, _ in model_without_ddp.named_parameters()] print("Resume checkpoint %s" % args.resume) if 'optimizer' in checkpoint and 'epoch' in checkpoint and not (hasattr(args, 'eval') and args.eval): optimizer.load_state_dict(checkpoint['optimizer']) args.start_epoch = checkpoint['epoch'] + 1 if 'scaler' in checkpoint: loss_scaler.load_state_dict(checkpoint['scaler']) print("With optim & sched!") else: model_params = list(model_without_ddp.parameters()) ema_params = copy.deepcopy(model_params) print("Training from scratch") if args.evaluate: print("Start evaluating") gen_img(model, model_without_ddp, gen_diffusion, ema_params, rdm_sampler, args, 0, batch_size=16, log_writer=log_writer, use_ema=True) return print(f"Start training for {args.epochs} epochs") start_time = time.time() for epoch in range(args.start_epoch, args.epochs): if args.distributed: data_loader_train.sampler.set_epoch(epoch)
train_stats = train_one_epoch(
1
2023-12-01 02:08:50+00:00
12k
baaivision/GeoDream
threestudio/models/geometry/geodream_geometry_volume.py
[ { "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[Uni...
from dataclasses import dataclass, field from threestudio.models.geometry.base import ( BaseGeometry, BaseImplicitGeometry, contract_to_unisphere, ) from threestudio.models.networks import get_encoding, get_mlp from threestudio.utils.ops import get_activation from threestudio.utils.typing import * from threestudio.models.geometry.grid_sampler import grid_sample_3d, tricubic_sample_3d import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import threestudio
8,194
if self.cfg.sdf_network_grad: print("sdf_layers network is training") else: for p in self.sdf_layers.parameters(): p.requires_grad_(False) print("sdf_layers network is freezeing") # volume weight volume_weight = torch.load(self.cfg.init_volume_path) self.volume = nn.Parameter(volume_weight, requires_grad=True) print("volume network is loading weight at " + self.cfg.init_volume_path) def get_activated_density( self, points: Float[Tensor, "*N Di"], density: Float[Tensor, "*N 1"] ) -> Tuple[Float[Tensor, "*N 1"], Float[Tensor, "*N 1"]]: density_bias: Union[float, Float[Tensor, "*N 1"]] if self.cfg.density_bias == "blob_dreamfusion": # pre-activation density bias density_bias = ( self.cfg.density_blob_scale * torch.exp( -0.5 * (points**2).sum(dim=-1) / self.cfg.density_blob_std**2 )[..., None] ) elif self.cfg.density_bias == "blob_magic3d": # pre-activation density bias density_bias = ( self.cfg.density_blob_scale * ( 1 - torch.sqrt((points**2).sum(dim=-1)) / self.cfg.density_blob_std )[..., None] ) elif isinstance(self.cfg.density_bias, float): density_bias = self.cfg.density_bias else: raise ValueError(f"Unknown density bias {self.cfg.density_bias}") raw_density: Float[Tensor, "*N 1"] = density + density_bias density = get_activation(self.cfg.density_activation)(raw_density) return raw_density, density def forward( self, points: Float[Tensor, "*N Di"], viewdirs, dists, output_normal: bool = False ) -> Dict[str, Float[Tensor, "..."]]: grad_enabled = torch.is_grad_enabled() if output_normal and self.cfg.normal_type == "analytic": torch.set_grad_enabled(True) points.requires_grad_(True) points_unscaled = points # points in the original scale sdf, feature_vector = self.sdf(points.view(-1, self.cfg.n_input_dims)) output = { "density": sdf, } g = self.gradient(points.view(-1, self.cfg.n_input_dims)) alphas = self.get_alpha(points.view(-1, self.cfg.n_input_dims), viewdirs, dists, feature_vector, sdf, g) output.update({"ALPHA": alphas}) points_norm = contract_to_unisphere( points, self.bbox, self.unbounded ) # points normalized to (0, 1) enc = self.encoding(points_norm.view(-1, self.cfg.n_input_dims)) if self.cfg.n_feature_dims > 0: features = self.feature_network(enc).view( *points.shape[:-1], self.cfg.n_feature_dims ) output.update({"features": features}) torch.set_grad_enabled(grad_enabled) return output def forward_density(self, points: Float[Tensor, "*N Di"]) -> Float[Tensor, "*N 1"]: points_unscaled = points density, _ = self.sdf(points.view(-1, self.cfg.n_input_dims)) density = density.reshape(*points.shape[:-1], 1) return density def forward_field( self, points: Float[Tensor, "*N Di"] ) -> Tuple[Float[Tensor, "*N 1"], Optional[Float[Tensor, "*N 3"]]]: sdf, _ = self.sdf(points.view(-1, self.cfg.n_input_dims)) sdf = sdf.reshape(*points.shape[:-1], 1) deformation: Optional[Float[Tensor, "*N 3"]] = None return sdf, deformation def forward_level( self, field: Float[Tensor, "*N 1"], threshold: float ) -> Float[Tensor, "*N 1"]: return field - threshold def export(self, points: Float[Tensor, "*N Di"], **kwargs) -> Dict[str, Any]: out: Dict[str, Any] = {} if self.cfg.n_feature_dims == 0: return out points_unscaled = points points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded) enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims)) features = self.feature_network(enc).view( *points.shape[:-1], self.cfg.n_feature_dims ) out.update( { "features": features, } ) return out @staticmethod @torch.no_grad() def create_from(
class Embedding(nn.Module): def __init__(self, in_channels, N_freqs, logscale=True, normalize=False): """ Defines a function that embeds x to (x, sin(2^k x), cos(2^k x), ...) in_channels: number of input channels (3 for both xyz and direction) """ super(Embedding, self).__init__() self.N_freqs = N_freqs self.in_channels = in_channels self.funcs = [torch.sin, torch.cos] self.out_channels = in_channels * (len(self.funcs) * N_freqs + 1) self.normalize = normalize if logscale: self.freq_bands = 2 ** torch.linspace(0, N_freqs - 1, N_freqs) else: self.freq_bands = torch.linspace(1, 2 ** (N_freqs - 1), N_freqs) def forward(self, x): """ Embeds x to (x, sin(2^k x), cos(2^k x), ...) Different from the paper, "x" is also in the output See https://github.com/bmild/nerf/issues/12 Inputs: x: (B, self.in_channels) Outputs: out: (B, self.out_channels) """ out = [x] for freq in self.freq_bands: for func in self.funcs: if self.normalize: out += [func(freq * x) / freq] else: out += [func(freq * x)] return torch.cat(out, -1) @threestudio.register("geodream-geometry") class GeodreamGeometryVolume(BaseImplicitGeometry): @dataclass class Config(BaseImplicitGeometry.Config): n_input_dims: int = 3 n_feature_dims: int = 3 density_activation: Optional[str] = "softplus" density_bias: Union[float, str] = "blob_magic3d" density_blob_scale: float = 10.0 density_blob_std: float = 0.5 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, } ) normal_type: Optional[ str ] = "finite_difference" # in ['pred', 'finite_difference', 'finite_difference_laplacian'] finite_difference_normal_eps: float = 0.01 # automatically determine the threshold isosurface_threshold: Union[float, str] = 25.0 init_volume_path: str = "con_volume_lod0.pth" one2345_weight: str = "pretrain.pth" sdf_network_grad: bool = False cfg: Config def configure(self) -> None: super().configure() self.encoding = get_encoding( self.cfg.n_input_dims, self.cfg.pos_encoding_config ) if self.cfg.n_feature_dims > 0: self.feature_network = get_mlp( self.encoding.n_output_dims, self.cfg.n_feature_dims, self.cfg.mlp_network_config, ) self.sdf_layers = SdfLayer() self.deviation_network = SingleVarianceNetwork(self.cfg.one2345_weight) # sdf_layers weight sdf_layers_weight = torch.load(self.cfg.one2345_weight)['sdf_network_lod0'] selected_state_dict = {} prefix = 'sdf_layer' for key, value in sdf_layers_weight.items(): if key.startswith(prefix): selected_state_dict[key[10:]] = value# key need remove sdf_layer prefix self.sdf_layers.load_state_dict(selected_state_dict) print("sdf_layers is loading weight at " + self.cfg.one2345_weight) # sdf_layers freeze if self.cfg.sdf_network_grad: print("sdf_layers network is training") else: for p in self.sdf_layers.parameters(): p.requires_grad_(False) print("sdf_layers network is freezeing") # volume weight volume_weight = torch.load(self.cfg.init_volume_path) self.volume = nn.Parameter(volume_weight, requires_grad=True) print("volume network is loading weight at " + self.cfg.init_volume_path) def get_activated_density( self, points: Float[Tensor, "*N Di"], density: Float[Tensor, "*N 1"] ) -> Tuple[Float[Tensor, "*N 1"], Float[Tensor, "*N 1"]]: density_bias: Union[float, Float[Tensor, "*N 1"]] if self.cfg.density_bias == "blob_dreamfusion": # pre-activation density bias density_bias = ( self.cfg.density_blob_scale * torch.exp( -0.5 * (points**2).sum(dim=-1) / self.cfg.density_blob_std**2 )[..., None] ) elif self.cfg.density_bias == "blob_magic3d": # pre-activation density bias density_bias = ( self.cfg.density_blob_scale * ( 1 - torch.sqrt((points**2).sum(dim=-1)) / self.cfg.density_blob_std )[..., None] ) elif isinstance(self.cfg.density_bias, float): density_bias = self.cfg.density_bias else: raise ValueError(f"Unknown density bias {self.cfg.density_bias}") raw_density: Float[Tensor, "*N 1"] = density + density_bias density = get_activation(self.cfg.density_activation)(raw_density) return raw_density, density def forward( self, points: Float[Tensor, "*N Di"], viewdirs, dists, output_normal: bool = False ) -> Dict[str, Float[Tensor, "..."]]: grad_enabled = torch.is_grad_enabled() if output_normal and self.cfg.normal_type == "analytic": torch.set_grad_enabled(True) points.requires_grad_(True) points_unscaled = points # points in the original scale sdf, feature_vector = self.sdf(points.view(-1, self.cfg.n_input_dims)) output = { "density": sdf, } g = self.gradient(points.view(-1, self.cfg.n_input_dims)) alphas = self.get_alpha(points.view(-1, self.cfg.n_input_dims), viewdirs, dists, feature_vector, sdf, g) output.update({"ALPHA": alphas}) points_norm = contract_to_unisphere( points, self.bbox, self.unbounded ) # points normalized to (0, 1) enc = self.encoding(points_norm.view(-1, self.cfg.n_input_dims)) if self.cfg.n_feature_dims > 0: features = self.feature_network(enc).view( *points.shape[:-1], self.cfg.n_feature_dims ) output.update({"features": features}) torch.set_grad_enabled(grad_enabled) return output def forward_density(self, points: Float[Tensor, "*N Di"]) -> Float[Tensor, "*N 1"]: points_unscaled = points density, _ = self.sdf(points.view(-1, self.cfg.n_input_dims)) density = density.reshape(*points.shape[:-1], 1) return density def forward_field( self, points: Float[Tensor, "*N Di"] ) -> Tuple[Float[Tensor, "*N 1"], Optional[Float[Tensor, "*N 3"]]]: sdf, _ = self.sdf(points.view(-1, self.cfg.n_input_dims)) sdf = sdf.reshape(*points.shape[:-1], 1) deformation: Optional[Float[Tensor, "*N 3"]] = None return sdf, deformation def forward_level( self, field: Float[Tensor, "*N 1"], threshold: float ) -> Float[Tensor, "*N 1"]: return field - threshold def export(self, points: Float[Tensor, "*N Di"], **kwargs) -> Dict[str, Any]: out: Dict[str, Any] = {} if self.cfg.n_feature_dims == 0: return out points_unscaled = points points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded) enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims)) features = self.feature_network(enc).view( *points.shape[:-1], self.cfg.n_feature_dims ) out.update( { "features": features, } ) return out @staticmethod @torch.no_grad() def create_from(
other: BaseGeometry,
0
2023-12-01 01:59:42+00:00
12k
dvlab-research/LLaMA-VID
llamavid/model/llamavid_arch.py
[ { "identifier": "BertConfig", "path": "llamavid/model/qformer.py", "snippet": "class BertEmbeddings(nn.Module):\nclass BertSelfAttention(nn.Module):\nclass BertSelfOutput(nn.Module):\nclass BertAttention(nn.Module):\nclass BertIntermediate(nn.Module):\nclass BertOutput(nn.Module):\nclass BertLayer(nn.Mo...
from abc import ABC, abstractmethod from transformers import BertTokenizer from transformers.models.bert.modeling_bert import BertLMHeadModel as BertLMHeadModelRaw from .qformer import BertConfig from .qformer import BertLMHeadModel as BertLMHeadModelQF from .multimodal_encoder.builder import build_vision_tower from .multimodal_projector.builder import build_vision_projector from llamavid.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN import os import json import numpy as np import torch import torch.nn as nn import torch.nn.functional as F
7,361
continue image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0] cur_new_input_embeds = [] if labels is not None: cur_labels = labels[batch_idx] cur_new_labels = [] assert cur_labels.shape == cur_input_ids.shape if not long_video: token_idx = 0 while image_token_indices.numel() > 0: if isinstance(image_features, list): cur_image_features = image_features[cur_image_idx][token_idx] else: cur_image_features = image_features[cur_image_idx] image_token_start = image_token_indices[0] if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False): cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start-1]).detach()) cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[image_token_start-1:image_token_start])) cur_new_input_embeds.append(cur_image_features) cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[image_token_start+1:image_token_start+2])) if labels is not None: cur_new_labels.append(cur_labels[:image_token_start]) cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype)) cur_new_labels.append(cur_labels[image_token_start:image_token_start+1]) cur_labels = cur_labels[image_token_start+2:] else: cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start])) cur_new_input_embeds.append(cur_image_features) if labels is not None: cur_new_labels.append(cur_labels[:image_token_start]) cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype)) cur_labels = cur_labels[image_token_start+1:] if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False): cur_input_ids = cur_input_ids[image_token_start+2:] else: cur_input_ids = cur_input_ids[image_token_start+1:] image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0] token_idx += 1 # changle image idx after processing one sample cur_image_idx += 1 if cur_input_ids.numel() > 0: if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False): cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids).detach()) else: cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids)) if labels is not None: cur_new_labels.append(cur_labels) cur_new_input_embeds = [x.to(device=self.device) for x in cur_new_input_embeds] cur_new_input_embeds = torch.cat(cur_new_input_embeds, dim=0) new_input_embeds.append(cur_new_input_embeds) if labels is not None: cur_new_labels = torch.cat(cur_new_labels, dim=0) new_labels.append(cur_new_labels) else: cur_new_input_embeds = torch.Tensor(len(cur_input_ids), self.config.hidden_size).to(dtype=self.dtype, device=self.device) text_token_indices = torch.where(cur_input_ids != IMAGE_TOKEN_INDEX)[0] if not self.training and self.get_model().embed_tokens.weight.device != cur_input_ids.device: model_device = self.get_model().embed_tokens.weight.device data_device = cur_input_ids.device cur_input_ids_text = cur_input_ids[text_token_indices].to(device=model_device) cur_new_input_embeds[text_token_indices] = self.get_model().embed_tokens(cur_input_ids_text).to(device=data_device) else: cur_new_input_embeds[text_token_indices] = self.get_model().embed_tokens(cur_input_ids[text_token_indices]) cur_image_features = image_features[cur_image_idx] cur_new_input_embeds[image_token_indices] = cur_image_features new_input_embeds.append(cur_new_input_embeds) if labels is not None: new_labels.append(cur_labels) cur_image_idx += 1 if any(x.shape != new_input_embeds[0].shape for x in new_input_embeds): max_len = max(x.shape[0] for x in new_input_embeds) new_input_embeds_align = [] for cur_new_embed in new_input_embeds: cur_new_embed = torch.cat((cur_new_embed, torch.zeros((max_len - cur_new_embed.shape[0], cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0) new_input_embeds_align.append(cur_new_embed) new_input_embeds = torch.stack(new_input_embeds_align, dim=0) if labels is not None: new_labels_align = [] _new_labels = new_labels for cur_new_label in new_labels: cur_new_label = torch.cat((cur_new_label, torch.full((max_len - cur_new_label.shape[0],), IGNORE_INDEX, dtype=cur_new_label.dtype, device=cur_new_label.device)), dim=0) new_labels_align.append(cur_new_label) new_labels = torch.stack(new_labels_align, dim=0) # only used for right padding in tokenlizer if attention_mask is not None: new_attention_mask = [] for cur_attention_mask, cur_new_labels, cur_new_labels_align in zip(attention_mask, _new_labels, new_labels): new_attn_mask_pad_left = torch.full((cur_new_labels.shape[0] - labels.shape[1],), True, dtype=attention_mask.dtype, device=attention_mask.device) new_attn_mask_pad_right = torch.full((cur_new_labels_align.shape[0] - cur_new_labels.shape[0],), False, dtype=attention_mask.dtype, device=attention_mask.device) cur_new_attention_mask = torch.cat((new_attn_mask_pad_left, cur_attention_mask, new_attn_mask_pad_right), dim=0) new_attention_mask.append(cur_new_attention_mask) attention_mask = torch.stack(new_attention_mask, dim=0) assert attention_mask.shape == new_labels.shape else: new_input_embeds = torch.stack(new_input_embeds, dim=0) if labels is not None: new_labels = torch.stack(new_labels, dim=0) # only used for right padding in tokenlizer if attention_mask is not None: new_attn_mask_pad_left = torch.full((attention_mask.shape[0], new_input_embeds.shape[1] - input_ids.shape[1]), True, dtype=attention_mask.dtype, device=attention_mask.device) attention_mask = torch.cat((new_attn_mask_pad_left, attention_mask), dim=1) assert attention_mask.shape == new_input_embeds.shape[:2] return None, attention_mask, past_key_values, new_input_embeds, new_labels def initialize_vision_tokenizer(self, model_args, tokenizer): if model_args.mm_use_im_patch_token: tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True) self.resize_token_embeddings(len(tokenizer)) if model_args.mm_use_im_start_end:
# Copyright 2023 Haotian Liu # # 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. # ------------------------------------------------------------------------ # Modified from LLaVA (https://github.com/haotian-liu/LLaVA) # Copyright 2023 Yanwei Li # ------------------------------------------------------------------------ class LLaMAVIDMetaModel: def __init__(self, config): super(LLaMAVIDMetaModel, self).__init__(config) if hasattr(config, "mm_vision_tower"): self.vision_tower = build_vision_tower(config, delay_load=True) self.mm_projector = build_vision_projector(config) def get_vision_tower(self): vision_tower = getattr(self, 'vision_tower', None) if type(vision_tower) is list: vision_tower = vision_tower[0] return vision_tower def initialize_vision_modules(self, model_args, fsdp=None, max_token=2048): vision_tower = model_args.vision_tower mm_vision_select_layer = model_args.mm_vision_select_layer mm_vision_select_feature = model_args.mm_vision_select_feature pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter self.config.mm_vision_tower = vision_tower self.config.image_processor = getattr(model_args, 'image_processor', None) vision_tower = build_vision_tower(model_args) if fsdp is not None and len(fsdp) > 0: self.vision_tower = [vision_tower] else: self.vision_tower = vision_tower self.config.use_mm_proj = True self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear') self.config.mm_hidden_size = vision_tower.hidden_size self.config.mm_vision_select_layer = mm_vision_select_layer self.config.mm_vision_select_feature = mm_vision_select_feature self.config.max_token = max_token if getattr(self, 'mm_projector', None) is None: self.mm_projector = build_vision_projector(self.config) else: # In case it is frozen by LoRA for p in self.mm_projector.parameters(): p.requires_grad = True if pretrain_mm_mlp_adapter is not None: mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu') def get_w(weights, keyword): return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k} self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector')) def initialize_attention_modules(self, model_args, for_eval=False): pretrain_mm_mlp_adapter = getattr(model_args, "pretrain_mm_mlp_adapter", None) pretrain_qformer = getattr(model_args, "pretrain_qformer", None) self.config.bert_type = getattr(model_args, "bert_type", "qformer") self.config.num_query = getattr(model_args, "num_query", 32) self.config.compress_type = getattr(model_args, "compress_type", None) if 'pretrain' in self.config.bert_type: # for qformer that use evaclip for prtrain att_feat_size = 1408 else: att_feat_size = self.config.mm_hidden_size self.vlm_att_tokenlizer, self.vlm_att_encoder, self.vlm_att_query = self.init_bert(att_feat_size, truncation_side="left") self.vlm_att_projector = torch.nn.Linear(self.vlm_att_encoder.config.hidden_size, self.config.mm_hidden_size) self.vlm_att_key_projector = torch.nn.Linear(self.config.mm_hidden_size, self.config.mm_hidden_size) self.vlm_att_val_projector = torch.nn.Linear(self.config.mm_hidden_size, self.config.hidden_size) if "raw" in self.config.bert_type: self.vlm_att_bert_proj = torch.nn.Linear(att_feat_size, self.vlm_att_encoder.config.hidden_size) elif "pretrain" in self.config.bert_type and self.config.mm_hidden_size!=att_feat_size: self.vlm_att_bert_proj = torch.nn.Linear(self.config.mm_hidden_size, att_feat_size) else: self.vlm_att_bert_proj = None def get_w(weights, keyword): return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k} if 'qformer_pretrain' in self.config.bert_type: self.vlm_att_ln = torch.nn.LayerNorm(att_feat_size) if pretrain_qformer is not None: print("Loading pretrained qformer weights...") qformer_weight = torch.load(pretrain_qformer, map_location='cpu')['model'] bert_weight = {_key: qformer_weight[_key] for _key in qformer_weight if 'bert' in _key} self.vlm_att_encoder.load_state_dict(get_w(bert_weight, 'Qformer')) self.vlm_att_ln.load_state_dict(get_w(qformer_weight, 'ln_vision')) self.vlm_att_query.data = qformer_weight['query_tokens'] if 'freeze_all' in self.config.bert_type: print("Freezing all qformer weights...") self.vlm_att_encoder.requires_grad_(False) self.vlm_att_ln.requires_grad_(False) self.vlm_att_query.requires_grad_(False) self.vlm_att_projector.requires_grad_(False) self.vlm_att_key_projector.requires_grad_(False) self.vlm_att_val_projector.requires_grad_(False) elif 'freeze' in self.config.bert_type: print("Freezing pretrained qformer weights...") self.vlm_att_encoder.requires_grad_(False) self.vlm_att_ln.requires_grad_(False) self.vlm_att_query.requires_grad_(False) if pretrain_mm_mlp_adapter is not None: att_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu') else: trainable_module = ['vlm_att_encoder', 'vlm_att_projector', 'vlm_att_key_projector', 'vlm_att_val_projector', 'vlm_att_query', 'vlm_att_visual_proj', 'vlm_att_ln'] if hasattr(model_args, 'model_name_or_path'): model_save_path = model_args.model_name_or_path else: model_save_path = model_args.model_path model_idx_path = getattr(model_args, 'model_path', model_save_path) weight_file = json.load(open(os.path.join(model_idx_path, 'pytorch_model.bin.index.json'), 'r'))['weight_map'] model_path = set([weight_file[_key] for _key in weight_file if any([_module in _key for _module in trainable_module])]) att_projector_weights = {} for _model in model_path: att_projector_weights.update(torch.load(os.path.join(model_idx_path, _model), map_location='cpu')) if len(att_projector_weights) == 0: return bert_dict = get_w(att_projector_weights, 'vlm_att_encoder') if "bert.embeddings.position_ids" not in bert_dict and "raw_bert" not in self.config.bert_type: bert_dict["bert.embeddings.position_ids"] = self.vlm_att_encoder.bert.embeddings.position_ids print('Loading pretrained weights...') self.vlm_att_encoder.load_state_dict(bert_dict) self.vlm_att_projector.load_state_dict(get_w(att_projector_weights, 'vlm_att_projector')) self.vlm_att_key_projector.load_state_dict(get_w(att_projector_weights, 'vlm_att_key_projector')) self.vlm_att_val_projector.load_state_dict(get_w(att_projector_weights, 'vlm_att_val_projector')) if "qformer" in self.config.bert_type: print('Loading vlm_att_query weights...') self.vlm_att_query.data = att_projector_weights['model.vlm_att_query'] if "pretrain" in self.config.bert_type: print('Loading vlm_att_ln weights...') self.vlm_att_ln.load_state_dict(get_w(att_projector_weights, 'vlm_att_ln')) if self.vlm_att_bert_proj is not None: print('Loading vlm_att_bert_proj weights...') self.vlm_att_bert_proj.load_state_dict(get_w(att_projector_weights, 'vlm_att_bert_proj')) if for_eval: weight_type = torch.float16 device_type = self.mm_projector[0].weight.device self.vlm_att_encoder = self.vlm_att_encoder.to(device=device_type, dtype=weight_type) self.vlm_att_projector = self.vlm_att_projector.to(device=device_type, dtype=weight_type) self.vlm_att_key_projector = self.vlm_att_key_projector.to(device=device_type, dtype=weight_type) self.vlm_att_val_projector = self.vlm_att_val_projector.to(device=device_type, dtype=weight_type) if "qformer" in self.config.bert_type: self.vlm_att_query.data = self.vlm_att_query.data.to(device=device_type, dtype=weight_type) if "pretrain" in self.config.bert_type: self.vlm_att_ln = self.vlm_att_ln.to(device=device_type, dtype=weight_type) if self.vlm_att_bert_proj is not None: self.vlm_att_bert_proj = self.vlm_att_bert_proj.to(device=device_type, dtype=weight_type) def init_bert(self, vision_width, cross_attention_freq=2, truncation_side="right"): # initialize BERT tokenizer tokenizer = BertTokenizer.from_pretrained("bert-base-uncased", truncation_side=truncation_side) tokenizer.add_special_tokens({"bos_token": "[DEC]"}) # initialize BERT encoder_config = BertConfig.from_pretrained("bert-base-uncased") encoder_config.encoder_width = vision_width # insert cross-attention layer every other block encoder_config.add_cross_attention = True encoder_config.cross_attention_freq = cross_attention_freq query_tokens = None if "qformer" in self.config.bert_type: mm_model = BertLMHeadModelQF.from_pretrained( "bert-base-uncased", config=encoder_config ) query_tokens = nn.Parameter( torch.zeros(1, self.config.num_query, encoder_config.hidden_size) ) query_tokens.data.normal_(mean=0.0, std=encoder_config.initializer_range) elif "raw" in self.config.bert_type: encoder_config.is_decoder = True mm_model = BertLMHeadModelRaw.from_pretrained( "bert-base-uncased", config=encoder_config ) else: raise NotImplementedError("BERT type not implemented...") mm_model.resize_token_embeddings(len(tokenizer)) mm_model.cls = None if "layer" in self.config.bert_type: layer_num = int(self.config.bert_type.split(':')[-1]) mm_model.bert.encoder.layer = mm_model.bert.encoder.layer[:layer_num] print(f"Only use {layer_num} layers in BERT...") return tokenizer, mm_model, query_tokens class LLaMAVIDMetaForCausalLM(ABC): @abstractmethod def get_model(self): pass def get_vision_tower(self): return self.get_model().get_vision_tower() def encode_images(self, images, prompts=None, image_counts=None, long_video=False): if long_video: # use pre-computed features image_features = images else: image_features = self.get_model().get_vision_tower()(images) image_features = self.vlm_attention(image_features, prompts=prompts, image_counts=image_counts, long_video=long_video) return image_features def vlm_attention(self, image_features, prompts=None, image_counts=None, long_video=False): img_feat_lst = [] if image_counts is None: assert len(image_features) == len(prompts), f"Size mismatch! image_features: {len(image_features)}, prompts: {len(prompts)}" else: assert len(prompts) == len(image_counts), f"Size mismatch! prompts: {len(prompts)}, image_counts: {len(image_counts)}" image_atts = torch.ones(image_features.size()[:-1], dtype=torch.long).to(image_features.device) total_count = 0 # calculate each image feat according to the prompt for _idx in range(len(prompts)): assert isinstance(prompts[_idx], list), f"Prompt should be a list, but got {type(prompts[_idx])}" input_token = self.get_model().vlm_att_tokenlizer( prompts[_idx], padding='longest', truncation=True, max_length=256, return_tensors="pt" ).to(image_features.device) input_ids = input_token.input_ids attention_masks = input_token.attention_mask if image_counts is None: img_feat_prompt = image_features[_idx, None].expand(len(prompts[_idx]), -1, -1) img_att_prompt = image_atts[_idx, None].expand(len(prompts[_idx]), -1) else: # shape: [prompt_num*frame_num, image_shape, feat_dim] img_feat_prompt = image_features[total_count:total_count+image_counts[_idx]] img_feat_prompt = img_feat_prompt[None].expand(len(prompts[_idx]), -1, -1, -1).flatten(0,1) img_att_prompt = image_atts[total_count:total_count+image_counts[_idx]] img_att_prompt = img_att_prompt[None].expand(len(prompts[_idx]), -1, -1).flatten(0,1) input_ids = input_ids[:,None].expand(-1, image_counts[_idx], -1).flatten(0,1) attention_masks = attention_masks[:,None].expand(-1, image_counts[_idx], -1).flatten(0,1) total_count += image_counts[_idx] if "pretrain" in self.config.bert_type and self.get_model().vlm_att_bert_proj is not None: bert_feat = self.get_model().vlm_att_bert_proj(img_feat_prompt) else: bert_feat = img_feat_prompt.clone() # remove cls embedding if self.config.mm_vision_select_feature == 'patch': if img_feat_prompt.shape[1]%2 == 1: img_feat_prompt = img_feat_prompt[:, 1:] if "qformer" in self.config.bert_type: query_tokens = self.get_model().vlm_att_query.expand(bert_feat.shape[0], -1, -1) query_atts = torch.cat([torch.ones(query_tokens.size()[:-1], dtype=torch.long).to(bert_feat.device), attention_masks],dim=1) if 'pretrain' in self.config.bert_type: mm_img_in = self.get_model().vlm_att_ln(bert_feat) else: mm_img_in = bert_feat if long_video: outputs = [] block_size = 64 for L in range(0, len(input_ids), block_size): R = L + block_size mm_output = self.get_model().vlm_att_encoder.bert( input_ids[L:R], query_embeds=query_tokens[L:R], attention_mask=query_atts[L:R], encoder_hidden_states=mm_img_in[L:R], encoder_attention_mask=img_att_prompt[L:R], return_dict=True, ) mm_output = mm_output.last_hidden_state[:,:query_tokens.shape[1]] outputs.append(mm_output) mm_output = torch.cat(outputs) torch.cuda.empty_cache() else: mm_output = self.get_model().vlm_att_encoder.bert( input_ids, query_embeds=query_tokens, attention_mask=query_atts, encoder_hidden_states=mm_img_in, encoder_attention_mask=img_att_prompt, return_dict=True, ) mm_output = mm_output.last_hidden_state[:,:query_tokens.shape[1]] elif "raw" in self.config.bert_type: if self.config.mm_vision_select_feature == 'patch' and bert_feat.shape[1]%2 == 1: bert_feat = bert_feat[:, 1:] img_att_prompt = img_att_prompt[:, 1:] mm_output = self.get_model().vlm_att_encoder.bert( input_ids, attention_mask=attention_masks, encoder_hidden_states=self.get_model().vlm_att_bert_proj(bert_feat), encoder_attention_mask=img_att_prompt, return_dict=True, ) mm_output = mm_output.last_hidden_state else: raise ValueError(f'Unexpected bert type: {self.config.bert_type}') text_q = self.get_model().vlm_att_projector(mm_output) final_token = self.token_generation(text_q, img_feat_prompt, long_video=long_video) if image_counts is not None: # shape: [prompt_num, frame_num*image_shape, feat_dim] final_token = final_token.reshape(len(prompts[_idx]), image_counts[_idx], *final_token.shape[-2:]) final_token = final_token.flatten(1,2) img_feat_lst.append(final_token) return img_feat_lst def token_generation(self, text_q, vis_embed, long_video=False): ctx_embed = self.get_model().vlm_att_key_projector(vis_embed) # Key part 1: calculate context-related embedding ctx_embed = text_q @ ctx_embed.transpose(-1,-2) ctx_embed = ctx_embed / (vis_embed.shape[-1] ** 0.5) if not long_video: ctx_embed = (ctx_embed.softmax(-1) @ vis_embed).mean(1) else: block_size = 64 outputs = [] ctx_score = ctx_embed.softmax(-1) for L in range(0, len(ctx_score), block_size): R = L + block_size sub_embed = (ctx_score[L:R] @ vis_embed[L:R]).mean(1) outputs.append(sub_embed) ctx_embed = torch.cat(outputs) torch.cuda.empty_cache() ctx_embed = self.get_model().vlm_att_val_projector(ctx_embed[:,None]) # Key part 2: calculate visual embedding if self.config.compress_type is not None: if 'grid' in self.config.compress_type: grid_size = int(self.config.compress_type.split('grid:')[-1]) cur_shape = int(vis_embed.shape[1]**0.5) assert grid_size > 1, f'Grid size should be larger than 1, but got {grid_size}' vis_embed = vis_embed.reshape(vis_embed.shape[0], cur_shape, cur_shape, -1) grid_stride = cur_shape // grid_size vis_embed = F.avg_pool2d(vis_embed.permute(0, 3, 1, 2), padding=0, kernel_size=grid_stride, stride=grid_stride) vis_embed = vis_embed.permute(0, 2, 3, 1).flatten(1,2) elif 'mean' in self.config.compress_type: vis_embed = vis_embed.mean(dim=1, keepdim=True) # concat token in shape (B, n+1, C) vis_embed = self.get_model().mm_projector(vis_embed) final_token = torch.cat([ctx_embed, vis_embed], dim=1) return final_token def update_prompt(self, prompts=None): self.prompts = prompts def prepare_inputs_labels_for_multimodal( self, input_ids, attention_mask, past_key_values, labels, images, prompts=None ): if prompts is None and hasattr(self, 'prompts'): prompts = self.prompts vision_tower = self.get_vision_tower() if vision_tower is None or images is None or input_ids.shape[1] == 1: if past_key_values is not None and vision_tower is not None and images is not None and input_ids.shape[1] == 1: attention_mask = torch.ones((attention_mask.shape[0], past_key_values[-1][-1].shape[-2] + 1), dtype=attention_mask.dtype, device=attention_mask.device) return input_ids, attention_mask, past_key_values, None, labels # pre-process images for long video if images[0].shape[-1] > 1000: long_video = True else: long_video = False if type(images) is list or images.ndim == 5: # not reseshape for long video if not long_video: images = [image if len(image.shape) == 4 else image.unsqueeze(0) for image in images] image_counts = [image.shape[0] for image in images] concat_images = torch.cat(images, dim=0) image_features = self.encode_images(concat_images, prompts, image_counts, long_video=long_video) else: image_features = self.encode_images(images, prompts, long_video=long_video) new_input_embeds = [] new_labels = [] if labels is not None else None cur_image_idx = 0 for batch_idx, cur_input_ids in enumerate(input_ids): if (cur_input_ids == IMAGE_TOKEN_INDEX).sum() == 0: # multimodal LLM, but the current sample is not multimodal # FIXME: this is a hacky fix, for deepspeed zero3 to work half_len = cur_input_ids.shape[0] // 2 if isinstance(image_features, list): cur_image_features = image_features[cur_image_idx][0] else: cur_image_features = image_features[cur_image_idx] cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids[:half_len]) cur_input_embeds_2 = self.get_model().embed_tokens(cur_input_ids[half_len:]) cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0], cur_input_embeds_2], dim=0) new_input_embeds.append(cur_input_embeds) if labels is not None: new_labels.append(labels[batch_idx]) cur_image_idx += 1 continue image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0] cur_new_input_embeds = [] if labels is not None: cur_labels = labels[batch_idx] cur_new_labels = [] assert cur_labels.shape == cur_input_ids.shape if not long_video: token_idx = 0 while image_token_indices.numel() > 0: if isinstance(image_features, list): cur_image_features = image_features[cur_image_idx][token_idx] else: cur_image_features = image_features[cur_image_idx] image_token_start = image_token_indices[0] if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False): cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start-1]).detach()) cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[image_token_start-1:image_token_start])) cur_new_input_embeds.append(cur_image_features) cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[image_token_start+1:image_token_start+2])) if labels is not None: cur_new_labels.append(cur_labels[:image_token_start]) cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype)) cur_new_labels.append(cur_labels[image_token_start:image_token_start+1]) cur_labels = cur_labels[image_token_start+2:] else: cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start])) cur_new_input_embeds.append(cur_image_features) if labels is not None: cur_new_labels.append(cur_labels[:image_token_start]) cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype)) cur_labels = cur_labels[image_token_start+1:] if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False): cur_input_ids = cur_input_ids[image_token_start+2:] else: cur_input_ids = cur_input_ids[image_token_start+1:] image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0] token_idx += 1 # changle image idx after processing one sample cur_image_idx += 1 if cur_input_ids.numel() > 0: if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False): cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids).detach()) else: cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids)) if labels is not None: cur_new_labels.append(cur_labels) cur_new_input_embeds = [x.to(device=self.device) for x in cur_new_input_embeds] cur_new_input_embeds = torch.cat(cur_new_input_embeds, dim=0) new_input_embeds.append(cur_new_input_embeds) if labels is not None: cur_new_labels = torch.cat(cur_new_labels, dim=0) new_labels.append(cur_new_labels) else: cur_new_input_embeds = torch.Tensor(len(cur_input_ids), self.config.hidden_size).to(dtype=self.dtype, device=self.device) text_token_indices = torch.where(cur_input_ids != IMAGE_TOKEN_INDEX)[0] if not self.training and self.get_model().embed_tokens.weight.device != cur_input_ids.device: model_device = self.get_model().embed_tokens.weight.device data_device = cur_input_ids.device cur_input_ids_text = cur_input_ids[text_token_indices].to(device=model_device) cur_new_input_embeds[text_token_indices] = self.get_model().embed_tokens(cur_input_ids_text).to(device=data_device) else: cur_new_input_embeds[text_token_indices] = self.get_model().embed_tokens(cur_input_ids[text_token_indices]) cur_image_features = image_features[cur_image_idx] cur_new_input_embeds[image_token_indices] = cur_image_features new_input_embeds.append(cur_new_input_embeds) if labels is not None: new_labels.append(cur_labels) cur_image_idx += 1 if any(x.shape != new_input_embeds[0].shape for x in new_input_embeds): max_len = max(x.shape[0] for x in new_input_embeds) new_input_embeds_align = [] for cur_new_embed in new_input_embeds: cur_new_embed = torch.cat((cur_new_embed, torch.zeros((max_len - cur_new_embed.shape[0], cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0) new_input_embeds_align.append(cur_new_embed) new_input_embeds = torch.stack(new_input_embeds_align, dim=0) if labels is not None: new_labels_align = [] _new_labels = new_labels for cur_new_label in new_labels: cur_new_label = torch.cat((cur_new_label, torch.full((max_len - cur_new_label.shape[0],), IGNORE_INDEX, dtype=cur_new_label.dtype, device=cur_new_label.device)), dim=0) new_labels_align.append(cur_new_label) new_labels = torch.stack(new_labels_align, dim=0) # only used for right padding in tokenlizer if attention_mask is not None: new_attention_mask = [] for cur_attention_mask, cur_new_labels, cur_new_labels_align in zip(attention_mask, _new_labels, new_labels): new_attn_mask_pad_left = torch.full((cur_new_labels.shape[0] - labels.shape[1],), True, dtype=attention_mask.dtype, device=attention_mask.device) new_attn_mask_pad_right = torch.full((cur_new_labels_align.shape[0] - cur_new_labels.shape[0],), False, dtype=attention_mask.dtype, device=attention_mask.device) cur_new_attention_mask = torch.cat((new_attn_mask_pad_left, cur_attention_mask, new_attn_mask_pad_right), dim=0) new_attention_mask.append(cur_new_attention_mask) attention_mask = torch.stack(new_attention_mask, dim=0) assert attention_mask.shape == new_labels.shape else: new_input_embeds = torch.stack(new_input_embeds, dim=0) if labels is not None: new_labels = torch.stack(new_labels, dim=0) # only used for right padding in tokenlizer if attention_mask is not None: new_attn_mask_pad_left = torch.full((attention_mask.shape[0], new_input_embeds.shape[1] - input_ids.shape[1]), True, dtype=attention_mask.dtype, device=attention_mask.device) attention_mask = torch.cat((new_attn_mask_pad_left, attention_mask), dim=1) assert attention_mask.shape == new_input_embeds.shape[:2] return None, attention_mask, past_key_values, new_input_embeds, new_labels def initialize_vision_tokenizer(self, model_args, tokenizer): if model_args.mm_use_im_patch_token: tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True) self.resize_token_embeddings(len(tokenizer)) if model_args.mm_use_im_start_end:
num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
8
2023-11-28 09:45:37+00:00
12k
horseee/DeepCache
DeepCache/sdxl/unet_2d_condition.py
[ { "identifier": "UNetMidBlock2DCrossAttn", "path": "DeepCache/sdxl/unet_2d_blocks.py", "snippet": "class UNetMidBlock2DCrossAttn(nn.Module):\n def __init__(\n self,\n in_channels: int,\n temb_channels: int,\n dropout: float = 0.0,\n num_layers: int = 1,\n tra...
from dataclasses import dataclass from typing import Any, Dict, List, Optional, Tuple, Union from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.loaders import UNet2DConditionLoadersMixin from diffusers.utils import BaseOutput, logging from diffusers.models.activations import get_activation from diffusers.models.attention_processor import ( ADDED_KV_ATTENTION_PROCESSORS, CROSS_ATTENTION_PROCESSORS, AttentionProcessor, AttnAddedKVProcessor, AttnProcessor, ) from diffusers.models.embeddings import ( GaussianFourierProjection, ImageHintTimeEmbedding, ImageProjection, ImageTimeEmbedding, PositionNet, TextImageProjection, TextImageTimeEmbedding, TextTimeEmbedding, TimestepEmbedding, Timesteps, ) from diffusers.models.modeling_utils import ModelMixin from .unet_2d_blocks import ( UNetMidBlock2DCrossAttn, UNetMidBlock2DSimpleCrossAttn, get_down_block, get_up_block, ) import torch import torch.nn as nn import torch.utils.checkpoint import time
9,700
else: text_time_embedding_from_dim = cross_attention_dim self.add_embedding = TextTimeEmbedding( text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads ) elif addition_embed_type == "text_image": # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use # case when `addition_embed_type == "text_image"` (Kadinsky 2.1)` self.add_embedding = TextImageTimeEmbedding( text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim ) elif addition_embed_type == "text_time": self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift) self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) elif addition_embed_type == "image": # Kandinsky 2.2 self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim) elif addition_embed_type == "image_hint": # Kandinsky 2.2 ControlNet self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim) elif addition_embed_type is not None: raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.") if time_embedding_act_fn is None: self.time_embed_act = None else: self.time_embed_act = get_activation(time_embedding_act_fn) self.down_blocks = nn.ModuleList([]) self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): if mid_block_only_cross_attention is None: mid_block_only_cross_attention = only_cross_attention only_cross_attention = [only_cross_attention] * len(down_block_types) if mid_block_only_cross_attention is None: mid_block_only_cross_attention = False if isinstance(num_attention_heads, int): num_attention_heads = (num_attention_heads,) * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) if isinstance(cross_attention_dim, int): cross_attention_dim = (cross_attention_dim,) * len(down_block_types) if isinstance(layers_per_block, int): layers_per_block = [layers_per_block] * len(down_block_types) if isinstance(transformer_layers_per_block, int): transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types) if class_embeddings_concat: # The time embeddings are concatenated with the class embeddings. The dimension of the # time embeddings passed to the down, middle, and up blocks is twice the dimension of the # regular time embeddings blocks_time_embed_dim = time_embed_dim * 2 else: blocks_time_embed_dim = time_embed_dim # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 down_block = get_down_block( down_block_type, num_layers=layers_per_block[i], transformer_layers_per_block=transformer_layers_per_block[i], in_channels=input_channel, out_channels=output_channel, temb_channels=blocks_time_embed_dim, add_downsample=not is_final_block, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim[i], num_attention_heads=num_attention_heads[i], downsample_padding=downsample_padding, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, attention_type=attention_type, resnet_skip_time_act=resnet_skip_time_act, resnet_out_scale_factor=resnet_out_scale_factor, cross_attention_norm=cross_attention_norm, attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel, dropout=dropout, ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlock2DCrossAttn": self.mid_block = UNetMidBlock2DCrossAttn( transformer_layers_per_block=transformer_layers_per_block[-1], in_channels=block_out_channels[-1], temb_channels=blocks_time_embed_dim, dropout=dropout, resnet_eps=norm_eps, resnet_act_fn=act_fn, output_scale_factor=mid_block_scale_factor, resnet_time_scale_shift=resnet_time_scale_shift, cross_attention_dim=cross_attention_dim[-1], num_attention_heads=num_attention_heads[-1], resnet_groups=norm_num_groups, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, upcast_attention=upcast_attention, attention_type=attention_type, ) elif mid_block_type == "UNetMidBlock2DSimpleCrossAttn":
# 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. logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class UNet2DConditionOutput(BaseOutput): """ The output of [`UNet2DConditionModel`]. Args: sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model. """ sample: torch.FloatTensor = None class UNet2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin): r""" A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample shaped output. This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented for all models (such as downloading or saving). Parameters: sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`): Height and width of input/output sample. in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample. out_channels (`int`, *optional*, defaults to 4): Number of channels in the output. center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample. flip_sin_to_cos (`bool`, *optional*, defaults to `False`): Whether to flip the sin to cos in the time embedding. freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding. down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`): The tuple of downsample blocks to use. mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`): Block type for middle of UNet, it can be either `UNetMidBlock2DCrossAttn` or `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped. up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`): The tuple of upsample blocks to use. only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`): Whether to include self-attention in the basic transformer blocks, see [`~models.attention.BasicTransformerBlock`]. block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`): The tuple of output channels for each block. layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block. downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution. mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block. dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use. norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization. If `None`, normalization and activation layers is skipped in post-processing. norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization. cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280): The dimension of the cross attention features. transformer_layers_per_block (`int` or `Tuple[int]`, *optional*, defaults to 1): The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`], [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`]. encoder_hid_dim (`int`, *optional*, defaults to None): If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim` dimension to `cross_attention_dim`. encoder_hid_dim_type (`str`, *optional*, defaults to `None`): If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`. attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads. num_attention_heads (`int`, *optional*): The number of attention heads. If not defined, defaults to `attention_head_dim` resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`. class_embed_type (`str`, *optional*, defaults to `None`): The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`, `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`. addition_embed_type (`str`, *optional*, defaults to `None`): Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or "text". "text" will use the `TextTimeEmbedding` layer. addition_time_embed_dim: (`int`, *optional*, defaults to `None`): Dimension for the timestep embeddings. num_class_embeds (`int`, *optional*, defaults to `None`): Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing class conditioning with `class_embed_type` equal to `None`. time_embedding_type (`str`, *optional*, defaults to `positional`): The type of position embedding to use for timesteps. Choose from `positional` or `fourier`. time_embedding_dim (`int`, *optional*, defaults to `None`): An optional override for the dimension of the projected time embedding. time_embedding_act_fn (`str`, *optional*, defaults to `None`): Optional activation function to use only once on the time embeddings before they are passed to the rest of the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`. timestep_post_act (`str`, *optional*, defaults to `None`): The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`. time_cond_proj_dim (`int`, *optional*, defaults to `None`): The dimension of `cond_proj` layer in the timestep embedding. conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer. conv_out_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_out` layer. projection_class_embeddings_input_dim (`int`, *optional*): The dimension of the `class_labels` input when `class_embed_type="projection"`. Required when `class_embed_type="projection"`. class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time embeddings with the class embeddings. mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`): Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False` otherwise. """ _supports_gradient_checkpointing = True @register_to_config def __init__( self, sample_size: Optional[int] = None, in_channels: int = 4, out_channels: int = 4, center_input_sample: bool = False, flip_sin_to_cos: bool = True, freq_shift: int = 0, down_block_types: Tuple[str] = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ), mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn", up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"), only_cross_attention: Union[bool, Tuple[bool]] = False, block_out_channels: Tuple[int] = (320, 640, 1280, 1280), layers_per_block: Union[int, Tuple[int]] = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, dropout: float = 0.0, act_fn: str = "silu", norm_num_groups: Optional[int] = 32, norm_eps: float = 1e-5, cross_attention_dim: Union[int, Tuple[int]] = 1280, transformer_layers_per_block: Union[int, Tuple[int]] = 1, encoder_hid_dim: Optional[int] = None, encoder_hid_dim_type: Optional[str] = None, attention_head_dim: Union[int, Tuple[int]] = 8, num_attention_heads: Optional[Union[int, Tuple[int]]] = None, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, addition_embed_type: Optional[str] = None, addition_time_embed_dim: Optional[int] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", resnet_skip_time_act: bool = False, resnet_out_scale_factor: int = 1.0, time_embedding_type: str = "positional", time_embedding_dim: Optional[int] = None, time_embedding_act_fn: Optional[str] = None, timestep_post_act: Optional[str] = None, time_cond_proj_dim: Optional[int] = None, conv_in_kernel: int = 3, conv_out_kernel: int = 3, projection_class_embeddings_input_dim: Optional[int] = None, attention_type: str = "default", class_embeddings_concat: bool = False, mid_block_only_cross_attention: Optional[bool] = None, cross_attention_norm: Optional[str] = None, addition_embed_type_num_heads=64, ): super().__init__() self.sample_size = sample_size if num_attention_heads is not None: raise ValueError( "At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19." ) # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. num_attention_heads = num_attention_heads or attention_head_dim # Check inputs if len(down_block_types) != len(up_block_types): raise ValueError( 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}." ) if len(block_out_channels) != len(down_block_types): raise ValueError( 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}." ) if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types): raise ValueError( 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}." ) if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types): raise ValueError( f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}." ) if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types): raise ValueError( 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}." ) if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types): raise ValueError( f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}." ) if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types): raise ValueError( f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}." ) # input conv_in_padding = (conv_in_kernel - 1) // 2 self.conv_in = nn.Conv2d( in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding ) # time if time_embedding_type == "fourier": time_embed_dim = time_embedding_dim or block_out_channels[0] * 2 if time_embed_dim % 2 != 0: raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.") self.time_proj = GaussianFourierProjection( time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos ) timestep_input_dim = time_embed_dim elif time_embedding_type == "positional": time_embed_dim = time_embedding_dim or block_out_channels[0] * 4 self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] else: raise ValueError( f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`." ) self.time_embedding = TimestepEmbedding( timestep_input_dim, time_embed_dim, act_fn=act_fn, post_act_fn=timestep_post_act, cond_proj_dim=time_cond_proj_dim, ) if encoder_hid_dim_type is None and encoder_hid_dim is not None: encoder_hid_dim_type = "text_proj" self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type) logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.") if encoder_hid_dim is None and encoder_hid_dim_type is not None: raise ValueError( f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}." ) if encoder_hid_dim_type == "text_proj": self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim) elif encoder_hid_dim_type == "text_image_proj": # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use # case when `addition_embed_type == "text_image_proj"` (Kadinsky 2.1)` self.encoder_hid_proj = TextImageProjection( text_embed_dim=encoder_hid_dim, image_embed_dim=cross_attention_dim, cross_attention_dim=cross_attention_dim, ) elif encoder_hid_dim_type == "image_proj": # Kandinsky 2.2 self.encoder_hid_proj = ImageProjection( image_embed_dim=encoder_hid_dim, cross_attention_dim=cross_attention_dim, ) elif encoder_hid_dim_type is not None: raise ValueError( f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'." ) else: self.encoder_hid_proj = None # class embedding if class_embed_type is None and num_class_embeds is not None: self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim) elif class_embed_type == "timestep": self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) elif class_embed_type == "projection": if projection_class_embeddings_input_dim is None: raise ValueError( "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set" ) # The projection `class_embed_type` is the same as the timestep `class_embed_type` except # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings # 2. it projects from an arbitrary input dimension. # # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations. # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings. # As a result, `TimestepEmbedding` can be passed arbitrary vectors. self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) elif class_embed_type == "simple_projection": if projection_class_embeddings_input_dim is None: raise ValueError( "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set" ) self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim) else: self.class_embedding = None if addition_embed_type == "text": if encoder_hid_dim is not None: text_time_embedding_from_dim = encoder_hid_dim else: text_time_embedding_from_dim = cross_attention_dim self.add_embedding = TextTimeEmbedding( text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads ) elif addition_embed_type == "text_image": # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use # case when `addition_embed_type == "text_image"` (Kadinsky 2.1)` self.add_embedding = TextImageTimeEmbedding( text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim ) elif addition_embed_type == "text_time": self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift) self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) elif addition_embed_type == "image": # Kandinsky 2.2 self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim) elif addition_embed_type == "image_hint": # Kandinsky 2.2 ControlNet self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim) elif addition_embed_type is not None: raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.") if time_embedding_act_fn is None: self.time_embed_act = None else: self.time_embed_act = get_activation(time_embedding_act_fn) self.down_blocks = nn.ModuleList([]) self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): if mid_block_only_cross_attention is None: mid_block_only_cross_attention = only_cross_attention only_cross_attention = [only_cross_attention] * len(down_block_types) if mid_block_only_cross_attention is None: mid_block_only_cross_attention = False if isinstance(num_attention_heads, int): num_attention_heads = (num_attention_heads,) * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) if isinstance(cross_attention_dim, int): cross_attention_dim = (cross_attention_dim,) * len(down_block_types) if isinstance(layers_per_block, int): layers_per_block = [layers_per_block] * len(down_block_types) if isinstance(transformer_layers_per_block, int): transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types) if class_embeddings_concat: # The time embeddings are concatenated with the class embeddings. The dimension of the # time embeddings passed to the down, middle, and up blocks is twice the dimension of the # regular time embeddings blocks_time_embed_dim = time_embed_dim * 2 else: blocks_time_embed_dim = time_embed_dim # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 down_block = get_down_block( down_block_type, num_layers=layers_per_block[i], transformer_layers_per_block=transformer_layers_per_block[i], in_channels=input_channel, out_channels=output_channel, temb_channels=blocks_time_embed_dim, add_downsample=not is_final_block, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim[i], num_attention_heads=num_attention_heads[i], downsample_padding=downsample_padding, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, attention_type=attention_type, resnet_skip_time_act=resnet_skip_time_act, resnet_out_scale_factor=resnet_out_scale_factor, cross_attention_norm=cross_attention_norm, attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel, dropout=dropout, ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlock2DCrossAttn": self.mid_block = UNetMidBlock2DCrossAttn( transformer_layers_per_block=transformer_layers_per_block[-1], in_channels=block_out_channels[-1], temb_channels=blocks_time_embed_dim, dropout=dropout, resnet_eps=norm_eps, resnet_act_fn=act_fn, output_scale_factor=mid_block_scale_factor, resnet_time_scale_shift=resnet_time_scale_shift, cross_attention_dim=cross_attention_dim[-1], num_attention_heads=num_attention_heads[-1], resnet_groups=norm_num_groups, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, upcast_attention=upcast_attention, attention_type=attention_type, ) elif mid_block_type == "UNetMidBlock2DSimpleCrossAttn":
self.mid_block = UNetMidBlock2DSimpleCrossAttn(
1
2023-12-01 10:54:04+00:00
12k
alvinliu0/HumanGaussian
threestudio/systems/base.py
[ { "identifier": "Exporter", "path": "threestudio/models/exporters/base.py", "snippet": "class Exporter(BaseObject):\n @dataclass\n class Config(BaseObject.Config):\n save_video: bool = False\n\n cfg: Config\n\n def configure(\n self,\n geometry: BaseImplicitGeometry,\n ...
import os import pytorch_lightning as pl import torch.nn.functional as F import threestudio from dataclasses import dataclass, field from threestudio.models.exporters.base import Exporter, ExporterOutput from threestudio.systems.utils import parse_optimizer, parse_scheduler from threestudio.utils.base import Updateable, update_if_possible from threestudio.utils.config import parse_structured from threestudio.utils.misc import C, cleanup, get_device, load_module_weights from threestudio.utils.saving import SaverMixin from threestudio.utils.typing import * from threestudio.utils.config import load_config, parse_structured
8,566
class BaseSystem(pl.LightningModule, Updateable, SaverMixin): @dataclass class Config: loggers: dict = field(default_factory=dict) loss: dict = field(default_factory=dict) optimizer: dict = field(default_factory=dict) scheduler: Optional[dict] = None weights: Optional[str] = None weights_ignore_modules: Optional[List[str]] = None cleanup_after_validation_step: bool = False cleanup_after_test_step: bool = False cfg: Config def __init__(self, cfg, resumed=False) -> None: super().__init__() self.cfg = parse_structured(self.Config, cfg) self._save_dir: Optional[str] = None self._resumed: bool = resumed self._resumed_eval: bool = False self._resumed_eval_status: dict = {"global_step": 0, "current_epoch": 0} if "loggers" in cfg: self.create_loggers(cfg.loggers) self.configure() if self.cfg.weights is not None: self.load_weights(self.cfg.weights, self.cfg.weights_ignore_modules) self.post_configure() def load_weights(self, weights: str, ignore_modules: Optional[List[str]] = None):
class BaseSystem(pl.LightningModule, Updateable, SaverMixin): @dataclass class Config: loggers: dict = field(default_factory=dict) loss: dict = field(default_factory=dict) optimizer: dict = field(default_factory=dict) scheduler: Optional[dict] = None weights: Optional[str] = None weights_ignore_modules: Optional[List[str]] = None cleanup_after_validation_step: bool = False cleanup_after_test_step: bool = False cfg: Config def __init__(self, cfg, resumed=False) -> None: super().__init__() self.cfg = parse_structured(self.Config, cfg) self._save_dir: Optional[str] = None self._resumed: bool = resumed self._resumed_eval: bool = False self._resumed_eval_status: dict = {"global_step": 0, "current_epoch": 0} if "loggers" in cfg: self.create_loggers(cfg.loggers) self.configure() if self.cfg.weights is not None: self.load_weights(self.cfg.weights, self.cfg.weights_ignore_modules) self.post_configure() def load_weights(self, weights: str, ignore_modules: Optional[List[str]] = None):
state_dict, epoch, global_step = load_module_weights(
10
2023-11-27 02:39:39+00:00
12k
ShunyuanZheng/GPS-Gaussian
train_stage2.py
[ { "identifier": "StereoHumanDataset", "path": "lib/human_loader.py", "snippet": "class StereoHumanDataset(Dataset):\n def __init__(self, opt, phase='train'):\n self.opt = opt\n self.use_processed_data = opt.use_processed_data\n self.phase = phase\n if self.phase == 'train'...
import logging import numpy as np import cv2 import os import torch import torch.optim as optim import warnings from pathlib import Path from tqdm import tqdm from datetime import datetime from lib.human_loader import StereoHumanDataset from lib.network import RtStereoHumanModel from config.stereo_human_config import ConfigStereoHuman as config from lib.train_recoder import Logger, file_backup from lib.GaussianRender import pts2render from lib.loss import l1_loss, ssim, psnr from torch.cuda.amp import GradScaler from torch.utils.data import DataLoader
7,676
from __future__ import print_function, division warnings.filterwarnings("ignore", category=UserWarning) class Trainer: def __init__(self, cfg_file): self.cfg = cfg_file
from __future__ import print_function, division warnings.filterwarnings("ignore", category=UserWarning) class Trainer: def __init__(self, cfg_file): self.cfg = cfg_file
self.model = RtStereoHumanModel(self.cfg, with_gs_render=True)
1
2023-12-04 06:12:57+00:00
12k
EricGuo5513/momask-codes
visualization/InverseKinematics.py
[ { "identifier": "Animation", "path": "visualization/Animation.py", "snippet": "class Animation:\n \"\"\"\n Animation is a numpy-like wrapper for animation data\n\n Animation data consists of several arrays consisting\n of F frames and J joints.\n\n The animation is specified by\n\n ...
import numpy as np import scipy.linalg as linalg import torch from visualization import Animation from visualization import AnimationStructure from visualization.Quaternions import Quaternions from torch import nn
8,368
class BasicInverseKinematics: """ Basic Inverse Kinematics Solver This is an extremely simple full body IK solver. It works given the following conditions: * All joint targets must be specified * All joint targets must be in reach * All joint targets must not differ extremely from the starting pose * No bone length constraints can be violated * The root translation and rotation are set to good initial values It works under the observation that if the _directions_ the joints are pointing toward match the _directions_ of the vectors between the target joints then the pose should match that of the target pose. Therefore it iterates over joints rotating each joint such that the vectors between it and it's children match that of the target positions. Parameters ---------- animation : Animation animation input positions : (F, J, 3) ndarray target positions for each frame F and each joint J iterations : int Optional number of iterations. If the above conditions are met 1 iteration should be enough, therefore the default is 1 silent : bool Optional if to suppress output defaults to False """ def __init__(self, animation, positions, iterations=1, silent=True): self.animation = animation self.positions = positions self.iterations = iterations self.silent = silent def __call__(self): children = AnimationStructure.children_list(self.animation.parents) for i in range(self.iterations): for j in AnimationStructure.joints(self.animation.parents): c = np.array(children[j]) if len(c) == 0: continue
class BasicInverseKinematics: """ Basic Inverse Kinematics Solver This is an extremely simple full body IK solver. It works given the following conditions: * All joint targets must be specified * All joint targets must be in reach * All joint targets must not differ extremely from the starting pose * No bone length constraints can be violated * The root translation and rotation are set to good initial values It works under the observation that if the _directions_ the joints are pointing toward match the _directions_ of the vectors between the target joints then the pose should match that of the target pose. Therefore it iterates over joints rotating each joint such that the vectors between it and it's children match that of the target positions. Parameters ---------- animation : Animation animation input positions : (F, J, 3) ndarray target positions for each frame F and each joint J iterations : int Optional number of iterations. If the above conditions are met 1 iteration should be enough, therefore the default is 1 silent : bool Optional if to suppress output defaults to False """ def __init__(self, animation, positions, iterations=1, silent=True): self.animation = animation self.positions = positions self.iterations = iterations self.silent = silent def __call__(self): children = AnimationStructure.children_list(self.animation.parents) for i in range(self.iterations): for j in AnimationStructure.joints(self.animation.parents): c = np.array(children[j]) if len(c) == 0: continue
anim_transforms = Animation.transforms_global(self.animation)
0
2023-11-29 19:21:27+00:00
12k
Doubiiu/DynamiCrafter
scripts/evaluation/inference.py
[ { "identifier": "DDIMSampler", "path": "lvdm/models/samplers/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.schedu...
import argparse, os, sys, glob import datetime, time import torch import torchvision import torchvision.transforms as transforms from omegaconf import OmegaConf from tqdm import tqdm from einops import rearrange, repeat from collections import OrderedDict from pytorch_lightning import seed_everything from PIL import Image from lvdm.models.samplers.ddim import DDIMSampler from lvdm.models.samplers.ddim_multiplecond import DDIMSampler as DDIMSampler_multicond from utils.utils import instantiate_from_config
8,644
file_list.sort() return file_list def load_model_checkpoint(model, ckpt): state_dict = torch.load(ckpt, map_location="cpu") if "state_dict" in list(state_dict.keys()): state_dict = state_dict["state_dict"] model.load_state_dict(state_dict, strict=True) else: # deepspeed new_pl_sd = OrderedDict() for key in state_dict['module'].keys(): new_pl_sd[key[16:]]=state_dict['module'][key] model.load_state_dict(new_pl_sd) print('>>> model checkpoint loaded.') return model def load_prompts(prompt_file): f = open(prompt_file, 'r') prompt_list = [] for idx, line in enumerate(f.readlines()): l = line.strip() if len(l) != 0: prompt_list.append(l) f.close() return prompt_list def load_data_prompts(data_dir, video_size=(256,256), video_frames=16, gfi=False): transform = transforms.Compose([ transforms.Resize(min(video_size)), transforms.CenterCrop(video_size), transforms.ToTensor(), transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))]) ## load prompts prompt_file = get_filelist(data_dir, ['txt']) assert len(prompt_file) > 0, "Error: found NO prompt file!" ###### default prompt default_idx = 0 default_idx = min(default_idx, len(prompt_file)-1) if len(prompt_file) > 1: print(f"Warning: multiple prompt files exist. The one {os.path.split(prompt_file[default_idx])[1]} is used.") ## only use the first one (sorted by name) if multiple exist ## load video file_list = get_filelist(data_dir, ['jpg', 'png', 'jpeg', 'JPEG', 'PNG']) # assert len(file_list) == n_samples, "Error: data and prompts are NOT paired!" data_list = [] filename_list = [] prompt_list = load_prompts(prompt_file[default_idx]) n_samples = len(prompt_list) for idx in range(n_samples): image = Image.open(file_list[idx]).convert('RGB') image_tensor = transform(image).unsqueeze(1) # [c,1,h,w] frame_tensor = repeat(image_tensor, 'c t h w -> c (repeat t) h w', repeat=video_frames) data_list.append(frame_tensor) _, filename = os.path.split(file_list[idx]) filename_list.append(filename) return filename_list, data_list, prompt_list def save_results(prompt, samples, filename, fakedir, fps=8, loop=False): filename = filename.split('.')[0]+'.mp4' prompt = prompt[0] if isinstance(prompt, list) else prompt ## save video videos = [samples] savedirs = [fakedir] for idx, video in enumerate(videos): if video is None: continue # b,c,t,h,w video = video.detach().cpu() video = torch.clamp(video.float(), -1., 1.) n = video.shape[0] video = video.permute(2, 0, 1, 3, 4) # t,n,c,h,w if loop: video = video[:-1,...] frame_grids = [torchvision.utils.make_grid(framesheet, nrow=int(n), padding=0) for framesheet in video] #[3, 1*h, n*w] grid = torch.stack(frame_grids, dim=0) # stack in temporal dim [t, 3, h, n*w] grid = (grid + 1.0) / 2.0 grid = (grid * 255).to(torch.uint8).permute(0, 2, 3, 1) path = os.path.join(savedirs[idx], filename) torchvision.io.write_video(path, grid, fps=fps, video_codec='h264', options={'crf': '10'}) ## crf indicates the quality def save_results_seperate(prompt, samples, filename, fakedir, fps=10, loop=False): prompt = prompt[0] if isinstance(prompt, list) else prompt ## save video videos = [samples] savedirs = [fakedir] for idx, video in enumerate(videos): if video is None: continue # b,c,t,h,w video = video.detach().cpu() if loop: # remove the last frame video = video[:,:,:-1,...] video = torch.clamp(video.float(), -1., 1.) n = video.shape[0] for i in range(n): grid = video[i,...] grid = (grid + 1.0) / 2.0 grid = (grid * 255).to(torch.uint8).permute(1, 2, 3, 0) #thwc path = os.path.join(savedirs[idx].replace('samples', 'samples_separate'), f'{filename.split(".")[0]}_sample{i}.mp4') torchvision.io.write_video(path, grid, fps=fps, video_codec='h264', options={'crf': '10'}) def get_latent_z(model, videos): b, c, t, h, w = videos.shape x = rearrange(videos, 'b c t h w -> (b t) c h w') z = model.encode_first_stage(x) z = rearrange(z, '(b t) c h w -> b c t h w', b=b, t=t) return z def image_guided_synthesis(model, prompts, videos, noise_shape, n_samples=1, ddim_steps=50, ddim_eta=1., \ unconditional_guidance_scale=1.0, cfg_img=None, fs=None, text_input=False, multiple_cond_cfg=False, loop=False, gfi=False, **kwargs):
sys.path.insert(1, os.path.join(sys.path[0], '..', '..')) def get_filelist(data_dir, postfixes): patterns = [os.path.join(data_dir, f"*.{postfix}") for postfix in postfixes] file_list = [] for pattern in patterns: file_list.extend(glob.glob(pattern)) file_list.sort() return file_list def load_model_checkpoint(model, ckpt): state_dict = torch.load(ckpt, map_location="cpu") if "state_dict" in list(state_dict.keys()): state_dict = state_dict["state_dict"] model.load_state_dict(state_dict, strict=True) else: # deepspeed new_pl_sd = OrderedDict() for key in state_dict['module'].keys(): new_pl_sd[key[16:]]=state_dict['module'][key] model.load_state_dict(new_pl_sd) print('>>> model checkpoint loaded.') return model def load_prompts(prompt_file): f = open(prompt_file, 'r') prompt_list = [] for idx, line in enumerate(f.readlines()): l = line.strip() if len(l) != 0: prompt_list.append(l) f.close() return prompt_list def load_data_prompts(data_dir, video_size=(256,256), video_frames=16, gfi=False): transform = transforms.Compose([ transforms.Resize(min(video_size)), transforms.CenterCrop(video_size), transforms.ToTensor(), transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))]) ## load prompts prompt_file = get_filelist(data_dir, ['txt']) assert len(prompt_file) > 0, "Error: found NO prompt file!" ###### default prompt default_idx = 0 default_idx = min(default_idx, len(prompt_file)-1) if len(prompt_file) > 1: print(f"Warning: multiple prompt files exist. The one {os.path.split(prompt_file[default_idx])[1]} is used.") ## only use the first one (sorted by name) if multiple exist ## load video file_list = get_filelist(data_dir, ['jpg', 'png', 'jpeg', 'JPEG', 'PNG']) # assert len(file_list) == n_samples, "Error: data and prompts are NOT paired!" data_list = [] filename_list = [] prompt_list = load_prompts(prompt_file[default_idx]) n_samples = len(prompt_list) for idx in range(n_samples): image = Image.open(file_list[idx]).convert('RGB') image_tensor = transform(image).unsqueeze(1) # [c,1,h,w] frame_tensor = repeat(image_tensor, 'c t h w -> c (repeat t) h w', repeat=video_frames) data_list.append(frame_tensor) _, filename = os.path.split(file_list[idx]) filename_list.append(filename) return filename_list, data_list, prompt_list def save_results(prompt, samples, filename, fakedir, fps=8, loop=False): filename = filename.split('.')[0]+'.mp4' prompt = prompt[0] if isinstance(prompt, list) else prompt ## save video videos = [samples] savedirs = [fakedir] for idx, video in enumerate(videos): if video is None: continue # b,c,t,h,w video = video.detach().cpu() video = torch.clamp(video.float(), -1., 1.) n = video.shape[0] video = video.permute(2, 0, 1, 3, 4) # t,n,c,h,w if loop: video = video[:-1,...] frame_grids = [torchvision.utils.make_grid(framesheet, nrow=int(n), padding=0) for framesheet in video] #[3, 1*h, n*w] grid = torch.stack(frame_grids, dim=0) # stack in temporal dim [t, 3, h, n*w] grid = (grid + 1.0) / 2.0 grid = (grid * 255).to(torch.uint8).permute(0, 2, 3, 1) path = os.path.join(savedirs[idx], filename) torchvision.io.write_video(path, grid, fps=fps, video_codec='h264', options={'crf': '10'}) ## crf indicates the quality def save_results_seperate(prompt, samples, filename, fakedir, fps=10, loop=False): prompt = prompt[0] if isinstance(prompt, list) else prompt ## save video videos = [samples] savedirs = [fakedir] for idx, video in enumerate(videos): if video is None: continue # b,c,t,h,w video = video.detach().cpu() if loop: # remove the last frame video = video[:,:,:-1,...] video = torch.clamp(video.float(), -1., 1.) n = video.shape[0] for i in range(n): grid = video[i,...] grid = (grid + 1.0) / 2.0 grid = (grid * 255).to(torch.uint8).permute(1, 2, 3, 0) #thwc path = os.path.join(savedirs[idx].replace('samples', 'samples_separate'), f'{filename.split(".")[0]}_sample{i}.mp4') torchvision.io.write_video(path, grid, fps=fps, video_codec='h264', options={'crf': '10'}) def get_latent_z(model, videos): b, c, t, h, w = videos.shape x = rearrange(videos, 'b c t h w -> (b t) c h w') z = model.encode_first_stage(x) z = rearrange(z, '(b t) c h w -> b c t h w', b=b, t=t) return z def image_guided_synthesis(model, prompts, videos, noise_shape, n_samples=1, ddim_steps=50, ddim_eta=1., \ unconditional_guidance_scale=1.0, cfg_img=None, fs=None, text_input=False, multiple_cond_cfg=False, loop=False, gfi=False, **kwargs):
ddim_sampler = DDIMSampler(model) if not multiple_cond_cfg else DDIMSampler_multicond(model)
1
2023-11-27 12:34:23+00:00
12k
dvlab-research/LLMGA
llmga/diffusers/tests/pipelines/stable_diffusion_2/test_stable_diffusion_latent_upscale.py
[ { "identifier": "TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS", "path": "llmga/diffusers/tests/pipelines/pipeline_params.py", "snippet": "TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS = frozenset([\"prompt\", \"image\", \"negative_prompt\"])" }, { "identifier": "TEXT_GUIDED_IMAGE_VARIATION_PARAMS", "...
import gc import random import unittest import numpy as np import torch import diffusers from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, EulerDiscreteScheduler, StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline, UNet2DConditionModel, ) from diffusers.schedulers import KarrasDiffusionSchedulers from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin
8,576
# coding=utf-8 # Copyright 2023 HuggingFace Inc. # # 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. enable_full_determinism() def check_same_shape(tensor_list): shapes = [tensor.shape for tensor in tensor_list] return all(shape == shapes[0] for shape in shapes[1:]) class StableDiffusionLatentUpscalePipelineFastTests(
# coding=utf-8 # Copyright 2023 HuggingFace Inc. # # 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. enable_full_determinism() def check_same_shape(tensor_list): shapes = [tensor.shape for tensor in tensor_list] return all(shape == shapes[0] for shape in shapes[1:]) class StableDiffusionLatentUpscalePipelineFastTests(
PipelineLatentTesterMixin, PipelineKarrasSchedulerTesterMixin, PipelineTesterMixin, unittest.TestCase
2
2023-11-27 18:46:55+00:00
12k
HumanAIGC/Cloth2Tex
phase1_inference.py
[ { "identifier": "ClothRenderer", "path": "renderer/cloth_renderer.py", "snippet": "class ClothRenderer(object):\n \n def __init__(self, objfile, resolution=512, focal_distance=1.6, scale_factor=1):\n self.device = torch.device(\"cuda:0\")\n\n self.img_size = resolution\n self....
import argparse import datetime import torch import torchvision import torch.nn as nn import torch.optim as optim import numpy as np import pickle import os import os.path as osp import torchvision import torchvision.transforms as transforms import torch.nn.functional as F import thinplate as tps import time import matplotlib.pyplot as plt import importlib import random import json import cv2 from torchvision.models.feature_extraction import create_feature_extractor, get_graph_node_names from renderer.cloth_renderer import ClothRenderer from PIL import Image from utils.frequency import extract_ampl_phase from utils.binary_function import Binarize from utils.tvl_loss import TVLoss, TVMaskLoss from tqdm import tqdm from pytorch3d.io import load_obj, save_obj from itertools import chain from pytorch3d.structures import Meshes from pytorch3d.transforms import RotateAxisAngle from pytorch3d.loss import ( mesh_edge_loss, mesh_laplacian_smoothing, mesh_normal_consistency, ) from lib.deformation_graph import DeformationGraph from lib.mesh_sampling import generate_transform_matrices_coma from lib.utils_dg import to_edge_index, to_sparse, get_vert_connectivity, scipy_to_torch_sparse from models import DeformGraphModel from torch_geometric.transforms import FaceToEdge from torch_geometric.data import Data from psbody.mesh import Mesh from torch_geometric.io import read_ply
8,910
# -*- coding: utf-8 -*- """ @date: 2023.03.29-31 week13 @func: PhaseI inference code. """ class Trainer(object): def __init__(self, objfile, savedir, resolution=512, focal_distance=2, verts_num=9648, scale_factor=1.0): self.device = torch.device("cuda") #set mesh and visualizer---------------------- self.cloth_renderer = ClothRenderer(objfile, resolution, focal_distance, scale_factor) if os.path.exists(os.path.join("experiments", savedir)): pass else: os.makedirs(os.path.join("experiments", savedir)) self.savedir = savedir self.uv = torch.ones((1, 512, 512, 3)).cuda() self.uv.requires_grad = True self.optimizer = optim.Adam([self.uv], lr=5e-3, betas=(0.5, 0.999)) # define loss self.criterion = nn.MSELoss() # nn.L1Loss() nn.MSELoss() self.mse = nn.MSELoss() self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # You can choose TVMaskLoss and test if it is suitable for your case. self.tvl_loss = TVLoss(weight=1) # TVMaskLoss(weight=1) or TVLoss(weight=1) # self.tvl_loss = TVMaskLoss(weight=1) self.canonical_mesh = self.cloth_renderer.canonical_mesh self.deform_verts = self.cloth_renderer.verts.to(self.device) self.deform_verts.requires_grad = False
# -*- coding: utf-8 -*- """ @date: 2023.03.29-31 week13 @func: PhaseI inference code. """ class Trainer(object): def __init__(self, objfile, savedir, resolution=512, focal_distance=2, verts_num=9648, scale_factor=1.0): self.device = torch.device("cuda") #set mesh and visualizer---------------------- self.cloth_renderer = ClothRenderer(objfile, resolution, focal_distance, scale_factor) if os.path.exists(os.path.join("experiments", savedir)): pass else: os.makedirs(os.path.join("experiments", savedir)) self.savedir = savedir self.uv = torch.ones((1, 512, 512, 3)).cuda() self.uv.requires_grad = True self.optimizer = optim.Adam([self.uv], lr=5e-3, betas=(0.5, 0.999)) # define loss self.criterion = nn.MSELoss() # nn.L1Loss() nn.MSELoss() self.mse = nn.MSELoss() self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # You can choose TVMaskLoss and test if it is suitable for your case. self.tvl_loss = TVLoss(weight=1) # TVMaskLoss(weight=1) or TVLoss(weight=1) # self.tvl_loss = TVMaskLoss(weight=1) self.canonical_mesh = self.cloth_renderer.canonical_mesh self.deform_verts = self.cloth_renderer.verts.to(self.device) self.deform_verts.requires_grad = False
self.deform_graph = DeformationGraph(vert_number=verts_num)
5
2023-12-01 06:03:38+00:00
12k
sherwinbahmani/4dfy
threestudio/systems/base.py
[ { "identifier": "Exporter", "path": "threestudio/models/exporters/base.py", "snippet": "class Exporter(BaseObject):\n @dataclass\n class Config(BaseObject.Config):\n save_video: bool = False\n\n cfg: Config\n\n def configure(\n self,\n geometry: BaseImplicitGeometry,\n ...
import os import pytorch_lightning as pl import threestudio from dataclasses import dataclass, field from threestudio.models.exporters.base import Exporter, ExporterOutput from threestudio.systems.utils import parse_optimizer, parse_scheduler from threestudio.utils.base import Updateable, update_if_possible from threestudio.utils.config import parse_structured from threestudio.utils.misc import C, cleanup, get_device, load_module_weights from threestudio.utils.saving import SaverMixin from threestudio.utils.typing import * from threestudio.utils.config import load_config, parse_structured
9,485
def on_train_batch_start(self, batch, batch_idx, unused=0): self.preprocess_data(batch, "train") self.dataset = self.trainer.train_dataloader.dataset update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def on_validation_batch_start(self, batch, batch_idx, dataloader_idx=0): self.preprocess_data(batch, "validation") self.dataset = self.trainer.val_dataloaders.dataset update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def on_test_batch_start(self, batch, batch_idx, dataloader_idx=0): self.preprocess_data(batch, "test") self.dataset = self.trainer.test_dataloaders.dataset update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def on_predict_batch_start(self, batch, batch_idx, dataloader_idx=0): self.preprocess_data(batch, "predict") self.dataset = self.trainer.predict_dataloaders.dataset update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def update_step(self, epoch: int, global_step: int, on_load_weights: bool = False): pass def on_before_optimizer_step(self, optimizer): """ # some gradient-related debugging goes here, example: from lightning.pytorch.utilities import grad_norm norms = grad_norm(self.geometry, norm_type=2) print(norms) """ pass class BaseLift3DSystem(BaseSystem): @dataclass class Config(BaseSystem.Config): geometry_type: str = "" geometry: dict = field(default_factory=dict) geometry_convert_from: Optional[str] = None geometry_convert_inherit_texture: bool = False # used to override configurations of the previous geometry being converted from, # for example isosurface_threshold geometry_convert_override: dict = field(default_factory=dict) material_type: str = "" material: dict = field(default_factory=dict) background_type: str = "" background: dict = field(default_factory=dict) renderer_type: str = "" renderer: dict = field(default_factory=dict) guidance_type: str = "" guidance: dict = field(default_factory=dict) prompt_processor_type: str = "" prompt_processor: dict = field(default_factory=dict) simultan: bool = False guidance_type_image: str = "" guidance_image: dict = field(default_factory=dict) prompt_processor_type_image: str = "" prompt_processor_image: dict = field(default_factory=dict) guidance_type_multi_view: str = "" guidance_multi_view: dict = field(default_factory=dict) prompt_processor_type_multi_view: str = "" prompt_processor_multi_view: dict = field(default_factory=dict) guidance_type_video: str = "" guidance_video: dict = field(default_factory=dict) prompt_processor_type_video: str = "" prompt_processor_video: dict = field(default_factory=dict) # geometry export configurations, no need to specify in training exporter_type: str = "mesh-exporter" exporter: dict = field(default_factory=dict) cfg: Config def configure(self) -> None: if ( self.cfg.geometry_convert_from # from_coarse must be specified and not self.cfg.weights # not initialized from coarse when weights are specified and not self.resumed # not initialized from coarse when resumed from checkpoints ): threestudio.info("Initializing geometry from a given checkpoint ...") prev_cfg = load_config( os.path.join( os.path.dirname(self.cfg.geometry_convert_from), "../configs/parsed.yaml", ) ) # TODO: hard-coded relative path prev_system_cfg: BaseLift3DSystem.Config = parse_structured( self.Config, prev_cfg.system ) prev_geometry_cfg = prev_system_cfg.geometry prev_geometry_cfg.update(self.cfg.geometry_convert_override) prev_geometry = threestudio.find(prev_system_cfg.geometry_type)( prev_geometry_cfg ) state_dict, epoch, global_step = load_module_weights( self.cfg.geometry_convert_from, module_name="geometry", map_location="cpu", ) prev_geometry.load_state_dict(state_dict, strict=False) # restore step-dependent states prev_geometry.do_update_step(epoch, global_step, on_load_weights=True) # convert from coarse stage geometry
class BaseSystem(pl.LightningModule, Updateable, SaverMixin): @dataclass class Config: loggers: dict = field(default_factory=dict) loss: dict = field(default_factory=dict) optimizer: dict = field(default_factory=dict) scheduler: Optional[dict] = None weights: Optional[str] = None weights_ignore_modules: Optional[List[str]] = None cleanup_after_validation_step: bool = False cleanup_after_test_step: bool = False cfg: Config def __init__(self, cfg, resumed=False) -> None: super().__init__() self.cfg = parse_structured(self.Config, cfg) self._save_dir: Optional[str] = None self._resumed: bool = resumed self._resumed_eval: bool = False self._resumed_eval_status: dict = {"global_step": 0, "current_epoch": 0} if "loggers" in cfg: self.create_loggers(cfg.loggers) self.configure() if self.cfg.weights is not None: self.load_weights(self.cfg.weights, self.cfg.weights_ignore_modules) self.post_configure() def load_weights(self, weights: str, ignore_modules: Optional[List[str]] = None): state_dict, epoch, global_step = load_module_weights( weights, ignore_modules=ignore_modules, map_location="cpu" ) self.load_state_dict(state_dict, strict=False) # restore step-dependent states self.do_update_step(epoch, global_step, on_load_weights=True) def set_resume_status(self, current_epoch: int, global_step: int): # restore correct epoch and global step in eval self._resumed_eval = True self._resumed_eval_status["current_epoch"] = current_epoch self._resumed_eval_status["global_step"] = global_step @property def resumed(self): # whether from resumed checkpoint return self._resumed @property def true_global_step(self): if self._resumed_eval: return self._resumed_eval_status["global_step"] else: return self.global_step @property def true_current_epoch(self): if self._resumed_eval: return self._resumed_eval_status["current_epoch"] else: return self.current_epoch def configure(self) -> None: pass def post_configure(self) -> None: """ executed after weights are loaded """ pass def C(self, value: Any) -> float: return C(value, self.true_current_epoch, self.true_global_step) def configure_optimizers(self): optim = parse_optimizer(self.cfg.optimizer, self) ret = { "optimizer": optim, } if self.cfg.scheduler is not None: ret.update( { "lr_scheduler": parse_scheduler(self.cfg.scheduler, optim), } ) return ret def training_step(self, batch, batch_idx): raise NotImplementedError def validation_step(self, batch, batch_idx): raise NotImplementedError def on_validation_batch_end(self, outputs, batch, batch_idx): if self.cfg.cleanup_after_validation_step: # cleanup to save vram cleanup() def on_validation_epoch_end(self): raise NotImplementedError def test_step(self, batch, batch_idx): raise NotImplementedError def on_test_batch_end(self, outputs, batch, batch_idx): if self.cfg.cleanup_after_test_step: # cleanup to save vram cleanup() def on_test_epoch_end(self): pass def predict_step(self, batch, batch_idx): raise NotImplementedError def on_predict_batch_end(self, outputs, batch, batch_idx): if self.cfg.cleanup_after_test_step: # cleanup to save vram cleanup() def on_predict_epoch_end(self): pass def preprocess_data(self, batch, stage): pass """ Implementing on_after_batch_transfer of DataModule does the same. But on_after_batch_transfer does not support DP. """ def on_train_batch_start(self, batch, batch_idx, unused=0): self.preprocess_data(batch, "train") self.dataset = self.trainer.train_dataloader.dataset update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def on_validation_batch_start(self, batch, batch_idx, dataloader_idx=0): self.preprocess_data(batch, "validation") self.dataset = self.trainer.val_dataloaders.dataset update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def on_test_batch_start(self, batch, batch_idx, dataloader_idx=0): self.preprocess_data(batch, "test") self.dataset = self.trainer.test_dataloaders.dataset update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def on_predict_batch_start(self, batch, batch_idx, dataloader_idx=0): self.preprocess_data(batch, "predict") self.dataset = self.trainer.predict_dataloaders.dataset update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def update_step(self, epoch: int, global_step: int, on_load_weights: bool = False): pass def on_before_optimizer_step(self, optimizer): """ # some gradient-related debugging goes here, example: from lightning.pytorch.utilities import grad_norm norms = grad_norm(self.geometry, norm_type=2) print(norms) """ pass class BaseLift3DSystem(BaseSystem): @dataclass class Config(BaseSystem.Config): geometry_type: str = "" geometry: dict = field(default_factory=dict) geometry_convert_from: Optional[str] = None geometry_convert_inherit_texture: bool = False # used to override configurations of the previous geometry being converted from, # for example isosurface_threshold geometry_convert_override: dict = field(default_factory=dict) material_type: str = "" material: dict = field(default_factory=dict) background_type: str = "" background: dict = field(default_factory=dict) renderer_type: str = "" renderer: dict = field(default_factory=dict) guidance_type: str = "" guidance: dict = field(default_factory=dict) prompt_processor_type: str = "" prompt_processor: dict = field(default_factory=dict) simultan: bool = False guidance_type_image: str = "" guidance_image: dict = field(default_factory=dict) prompt_processor_type_image: str = "" prompt_processor_image: dict = field(default_factory=dict) guidance_type_multi_view: str = "" guidance_multi_view: dict = field(default_factory=dict) prompt_processor_type_multi_view: str = "" prompt_processor_multi_view: dict = field(default_factory=dict) guidance_type_video: str = "" guidance_video: dict = field(default_factory=dict) prompt_processor_type_video: str = "" prompt_processor_video: dict = field(default_factory=dict) # geometry export configurations, no need to specify in training exporter_type: str = "mesh-exporter" exporter: dict = field(default_factory=dict) cfg: Config def configure(self) -> None: if ( self.cfg.geometry_convert_from # from_coarse must be specified and not self.cfg.weights # not initialized from coarse when weights are specified and not self.resumed # not initialized from coarse when resumed from checkpoints ): threestudio.info("Initializing geometry from a given checkpoint ...") prev_cfg = load_config( os.path.join( os.path.dirname(self.cfg.geometry_convert_from), "../configs/parsed.yaml", ) ) # TODO: hard-coded relative path prev_system_cfg: BaseLift3DSystem.Config = parse_structured( self.Config, prev_cfg.system ) prev_geometry_cfg = prev_system_cfg.geometry prev_geometry_cfg.update(self.cfg.geometry_convert_override) prev_geometry = threestudio.find(prev_system_cfg.geometry_type)( prev_geometry_cfg ) state_dict, epoch, global_step = load_module_weights( self.cfg.geometry_convert_from, module_name="geometry", map_location="cpu", ) prev_geometry.load_state_dict(state_dict, strict=False) # restore step-dependent states prev_geometry.do_update_step(epoch, global_step, on_load_weights=True) # convert from coarse stage geometry
prev_geometry = prev_geometry.to(get_device())
9
2023-11-29 05:15:56+00:00
12k
rlawjdghek/StableVITON
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 ...
import torch import torch.nn as nn import numpy as np import pytorch_lightning as pl import itertools import torchvision.transforms as T import random import torch.nn.functional as F from torch.optim.lr_scheduler import LambdaLR from einops import rearrange, repeat from contextlib import contextmanager, nullcontext from functools import partial from tqdm import tqdm from torchvision.utils import make_grid from pytorch_lightning.utilities.distributed import rank_zero_only from omegaconf import ListConfig from torchvision.transforms.functional import resize from diffusers.models.autoencoder_kl import AutoencoderKLOutput from diffusers.models.vae import DecoderOutput 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 IdentityFirstStage, AutoencoderKL from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like, zero_module, conv_nd from ldm.models.diffusion.ddim import DDIMSampler
10,659
""" 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 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., make_it_fit=False, ucg_training=None, reset_ema=False, reset_num_ema_updates=False, l_cond_simple_weight=1.0, l_cond_recon_weight=1.0, **kwargs ): 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.unet_config = unet_config 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.imagenet_norm = T.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)) self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight self.l_cond_simple_weight = l_cond_simple_weight self.l_cond_recon_weight = l_cond_recon_weight if monitor is not None: self.monitor = monitor self.make_it_fit = make_it_fit
""" 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 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., make_it_fit=False, ucg_training=None, reset_ema=False, reset_num_ema_updates=False, l_cond_simple_weight=1.0, l_cond_recon_weight=1.0, **kwargs ): 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.unet_config = unet_config 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.imagenet_norm = T.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)) self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight self.l_cond_simple_weight = l_cond_simple_weight self.l_cond_recon_weight = l_cond_recon_weight if monitor is not None: self.monitor = monitor self.make_it_fit = make_it_fit
if reset_ema: assert exists(ckpt_path)
1
2023-12-02 05:56:58+00:00
12k
ContextualAI/HALOs
trainers.py
[ { "identifier": "AutoModelForCausalLMWithValueHead", "path": "models.py", "snippet": "class AutoModelForCausalLMWithValueHead(PreTrainedModelWrapper):\n r\"\"\"\n An autoregressive model with a value head in addition to the language model head.\n\n Class attributes:\n - **transformers_pa...
import torch import torch.nn.functional as F import torch.nn as nn import transformers import gc import torch.distributed as dist import tensor_parallel as tp import contextlib import dataloader import numpy as np import wandb import tqdm import random import os import time import json import functools from models import AutoModelForCausalLMWithValueHead from omegaconf import OmegaConf, DictConfig from transformers import AutoTokenizer from torch.distributed.fsdp import ( FullyShardedDataParallel as FSDP, MixedPrecision, StateDictType, BackwardPrefetch, ShardingStrategy, CPUOffload, ) from torch.distributed.fsdp.api import FullStateDictConfig, FullOptimStateDictConfig from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy, size_based_auto_wrap_policy from utils import ( slice_and_move_batch_for_device, formatted_dict, all_gather_if_needed, pad_to_length, get_block_class_from_model, rank0_print, get_batch_logps, masked_mean, masked_var, entropy_from_logits, delete_dict, rowwise_product, ) from collections import defaultdict from typing import Optional, Dict, List, Union, Tuple from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( checkpoint_wrapper, apply_activation_checkpointing, CheckpointImpl, )
7,859
L(x, y) := 1 - sigmoid(beta * (0 - [log p_policy(y|x) - log p_reference(y|x)])) """ chosen_logratios = (policy_chosen_logps - reference_chosen_logps) rejected_logratios = (policy_rejected_logps - reference_rejected_logps) losses = torch.cat((1 - F.sigmoid(self.config.loss.beta * (chosen_logratios - 0)), 1 - F.sigmoid(self.config.loss.beta * (0 - rejected_logratios))), 0) chosen_rewards = self.config.loss.beta * (policy_chosen_logps - reference_chosen_logps).detach() rejected_rewards = self.config.loss.beta * (policy_rejected_logps - reference_rejected_logps).detach() return losses, chosen_rewards, rejected_rewards class PPOTrainer(BasicTrainer): """One-step, offline variant of PPO.""" def forward(self, model: AutoModelForCausalLMWithValueHead, batch: Dict[str, Union[List, torch.LongTensor]], is_policy: bool=True) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: """Run the given model on the given batch of inputs. Args: model: model to run forward pass on batch: input batch (forward pass will be run on keys with prefix 'chosen') masks: binary-valued tensor shape (batch size, sequence length) is_policy: whether the model is the policy or reference Returns: all_logps: batch log probabilities at the token level of shape (batch size, sequence length) all_logits: corresponding logits of shape (batch size, sequence length) all_values: values predicted for each token, of shape (batch size, sequence length) """ if is_policy: # here the prefix 'chosen' is a misnomer, since it can refer to the dispreferred generations # the 'status' field contains the actual status of the generations all_logits, _, all_values = model(batch['target_combined_input_ids'], attention_mask=batch['target_combined_attention_mask']) all_values = all_values[:, :-1].contiguous().to(self.rank) else: all_logits = model(batch['target_combined_input_ids'], attention_mask=batch['target_combined_attention_mask'], use_cache=(not self.is_mistral)).logits.to(self.policy_dtype) all_values = None all_logps = get_batch_logps(all_logits.to(self.policy_dtype), batch['target_labels'], average_log_prob=False, token_level=True) # Returned tensors will have sequence length that is one less than the inputs (to account for label shifting). all_logits = all_logits[:, :-1].contiguous().to(self.rank) all_logps = all_logps.contiguous().to(self.rank) return all_logps, all_logits, all_values def compute_advantages(self, values: torch.FloatTensor, rewards: torch.FloatTensor, masks: torch.FloatTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor]: """ Estimate the advantages and rewards for every token taken. Args: values: the estimated values of the tokens. Should already be detached from graph. rewards: signal from the environment as to whether the generation is good or bad. In the basic implementation, this is only one nonzero reward, on the last unpadded token of each sequence. torch tensor of shape (batch size, sequence length) masks: torch tensor of shape (batch size, sequence length); 1 if token should be considered and 0 otherwise Returns: advantages: torch tensor of shape (batch size, sequence length) returns: Also called 'rewards-to-go'. Only tokens after the current token are used to calculate this: http://rail.eecs.berkeley.edu/deeprlcourse/static/slides/lec-5.pdf torch tensor of shape (batch size, sequence length) """ values = values * masks rewards = rewards * masks gae = 0 # generalized advantage estimation seq_len = rewards.shape[-1] advantages_reversed = [] discounted_future_reward = torch.zeros_like(rewards[:,0]) discounted_future_rewards_reversed = [] for t in reversed(range(seq_len)): # see https://towardsdatascience.com/proximal-policy-optimization-tutorial-part-2-2-gae-and-ppo-loss-fe1b3c5549e8 delta = rewards[:, t] + self.config.loss.gamma * (values[:, t + 1] if t < seq_len - 1 else 0.0) - values[:, t] gae = delta + self.config.loss.gamma * self.config.loss.lam * gae advantages_reversed.append(gae) discounted_future_rewards_reversed.append(discounted_future_reward) discounted_future_reward = rewards[:, t] + self.config.loss.gamma * discounted_future_reward advantages = (torch.stack(advantages_reversed[::-1]).transpose(0, 1) * masks) returns = (advantages + values).contiguous().to(self.rank) discounted_future_rewards = (torch.stack(discounted_future_rewards_reversed[::-1]).transpose(0, 1) * masks).contiguous().to(self.rank) # normalizing advantages leads to more stable learning mean_adv, var_adv = masked_mean(advantages, masks), masked_var(advantages, masks) normalized_advantages = (advantages - mean_adv) * torch.rsqrt(var_adv + 1e-8) normalized_advantages = (normalized_advantages * masks).detach().contiguous().to(self.rank) return normalized_advantages, returns, discounted_future_rewards def loss(self, batch: Dict, episode: Dict) -> Tuple[torch.FloatTensor, Dict]: """ Given the batch statistics and the current episode's values, calculate the loss and return some loss statistics. Args: batch: dictionary containing batch data (shoud have keys 'values', 'returns', 'advantages', 'logprobs', 'masks') episode: dictionary containing the episode data (should have keys 'logits', 'values', 'logprobs') Returns: loss: combined policy and critic loss of shape (1,) loss_stats: dictionary of episode/batch statistics """ value_losses = (episode['values'] - batch['discounted_future_rewards'].detach()) ** 2 critic_loss = 0.5 * masked_mean(value_losses, batch['masks']) ratio = torch.exp(episode['logprobs'] - batch['logprobs']) policy_losses = -batch['advantages'] * ratio policy_losses_clipped = -batch['advantages'] * torch.clamp(ratio, self.config.loss.cliprange, 1 / self.config.loss.cliprange) policy_loss = masked_mean(torch.max(policy_losses, policy_losses_clipped), batch['masks']) KL_penalty = masked_mean(batch['logprobs'] - episode['logprobs'], batch['masks']) loss = policy_loss + self.config.loss.critic_coef * critic_loss + self.config.loss.KL_coef * KL_penalty loss_stats = { 'loss/total' : loss.detach(), 'loss/critic' : critic_loss.detach(), 'loss/policy' : policy_loss.detach(), 'clipfrac/policy' : masked_mean(torch.gt(policy_losses_clipped, policy_losses).float(), batch['masks']).detach(),
# Copyright (c) 2023 Contextual AI, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """ Extendable Trainer classes for aligning LLMs. The specific class that should be used should be specified in the loss file under config/loss. The BasicTrainer contains the core methods (e.g., sharding, basic training loop, etc.). The SFTTrainer, PairedPreferenceTrainer, and UnpairedPreferenceTrainer all subclass BasicTrainer and override the get_batch_metrics() and (optionally) forward() methods. The trainer for each loss should subclass either PairedPreferenceTrainer or UnpairedPreferenceTrainer. """ torch.backends.cuda.matmul.allow_tf32 = True class BasicTrainer(object): def __init__(self, tokenizer: AutoTokenizer, config: DictConfig, train_iterator: dataloader.DataLoader, eval_iterator: dataloader.DataLoader, policy: nn.Module, reference_model: Optional[nn.Module] = None, rank: int = 0, world_size: int = 1, fsdp: bool = False, ): """A trainer for a language model, supporting either SFT, HALO, or offline PPO training. """ self.seed = config.seed torch.manual_seed(self.seed) np.random.seed(self.seed) random.seed(self.seed) self.rank = rank self.device = torch.device('cuda', self.rank) self.world_size = world_size self.config = config self.run_dir = config.local_run_dir self.fsdp = fsdp self.tokenizer = tokenizer self.policy = policy self.policy_dtype = getattr(torch, config.model.policy_dtype) self.reference_model = reference_model self.example_counter = 0 self.batch_counter = 0 self.train_iterator = train_iterator self.eval_iterator = eval_iterator self.eval_batches = list(self.eval_iterator) rank0_print(f'Loaded {len(self.eval_batches)} eval batches of size {config.model.eval_batch_size}') if self.fsdp: self.shard() self.is_mistral = 'mistral' in self.config.model.name_or_path.lower() def shard(self): """ Shard the policy model and reference model (if applicable) using FDSP. """ assert self.config.model.block_name is not None, 'must specify model.block_name (e.g., GPT2Block or GPTNeoXLayer) for FSDP' wrap_class = get_block_class_from_model(self.policy.pretrained_model if self.config.loss.name == 'ppo' else self.policy, self.config.model.block_name) model_auto_wrap_policy = functools.partial(transformer_auto_wrap_policy, transformer_layer_cls={wrap_class},) shared_fsdp_kwargs = dict( auto_wrap_policy=model_auto_wrap_policy, sharding_strategy=ShardingStrategy.FULL_SHARD, cpu_offload=CPUOffload(offload_params=False), backward_prefetch=BackwardPrefetch.BACKWARD_PRE, device_id=self.rank, ignored_modules=None, limit_all_gathers=False, use_orig_params=False, sync_module_states=False ) rank0_print('Sharding models...') mp_dtype = getattr(torch, self.config.model.fsdp_policy_mp) if self.config.model.fsdp_policy_mp is not None else None policy_mp_policy = MixedPrecision(param_dtype=mp_dtype, reduce_dtype=mp_dtype, buffer_dtype=mp_dtype) if self.config.loss.name == 'ppo': self.policy.pretrained_model = FSDP(self.policy.pretrained_model, **shared_fsdp_kwargs, mixed_precision=policy_mp_policy) # shard the value head according to size v_head_shared_fsdp_kwargs = dict( auto_wrap_policy=functools.partial(size_based_auto_wrap_policy, min_num_params=100), sharding_strategy=ShardingStrategy.FULL_SHARD, cpu_offload=CPUOffload(offload_params=False), backward_prefetch=BackwardPrefetch.BACKWARD_PRE, device_id=self.rank, ignored_modules=None, limit_all_gathers=False, use_orig_params=False, sync_module_states=False ) self.policy.v_head = FSDP(self.policy.v_head, **v_head_shared_fsdp_kwargs) else: self.policy = FSDP(self.policy, **shared_fsdp_kwargs, mixed_precision=policy_mp_policy) if self.reference_model is not None: self.reference_model = FSDP(self.reference_model, **shared_fsdp_kwargs, mixed_precision=policy_mp_policy) if self.config.model.activation_checkpointing: rank0_print('Attempting to enable activation checkpointing...') try: # use activation checkpointing, according to: # https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/ # first, verify we have FSDP activation support ready by importing: except Exception as e: rank0_print('FSDP activation checkpointing not available:', e) else: check_fn = lambda submodule: isinstance(submodule, wrap_class) rank0_print('Applying activation checkpointing wrapper to policy...') if self.config.loss.name == 'ppo': apply_activation_checkpointing(self.policy.pretrained_model, checkpoint_wrapper_fn=checkpoint_wrapper, check_fn=check_fn) else: apply_activation_checkpointing(self.policy, checkpoint_wrapper_fn=checkpoint_wrapper, check_fn=check_fn) if self.reference_model is not None: apply_activation_checkpointing(self.reference_model, checkpoint_wrapper_fn=checkpoint_wrapper, check_fn=check_fn) rank0_print('FSDP activation checkpointing enabled!') print('Loaded model on rank', self.rank) dist.barrier() def get_batch_samples(self, batch: Dict[str, torch.LongTensor]) -> Tuple[str, str]: """Generate samples from the policy.""" ctx = lambda: (FSDP.summon_full_params(self.policy, writeback=False, recurse=False) if self.fsdp else contextlib.nullcontext()) with ctx(): policy_output = self.policy.generate( batch['prompt_input_ids'], attention_mask=batch['prompt_attention_mask'], max_length=self.config.model.max_length, do_sample=True, pad_token_id=self.tokenizer.pad_token_id, top_p=self.config.top_p, ) policy_output = pad_to_length(policy_output, self.config.model.max_length, self.tokenizer.pad_token_id) policy_output = all_gather_if_needed(policy_output, self.rank, self.world_size) policy_output_decoded = self.tokenizer.batch_decode(policy_output, skip_special_tokens=True) return policy_output_decoded def loss(self, policy_chosen_logps: torch.FloatTensor, policy_rejected_logps: torch.FloatTensor, reference_chosen_logps: torch.FloatTensor, reference_rejected_logps: torch.FloatTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: """ Args: policy_chosen_logps: Log probabilities of the policy model for the chosen responses. Shape: (batch_size,) policy_rejected_logps: Log probabilities of the policy model for the rejected responses. Shape: (batch_size,) reference_chosen_logps: Log probabilities of the reference model for the chosen responses. Shape: (batch_size,) reference_rejected_logps: Log probabilities of the reference model for the rejected responses. Shape: (batch_size,) Returns: A tuple of three tensors: (losses, chosen_rewards, rejected_rewards). The losses tensor contains the losses, one for each example (sif chosen_only or rejected_only, only n/2 losses). The chosen_rewards and rejected_rewards tensors contain the rewards for the chosen and rejected responses, respectively, for reporting. Note that rejected responses do not factor into the loss, only the reward calculation. """ raise NotImplementedError def get_batch_metrics(self, batch: Dict[str, Union[List, torch.LongTensor]], mode: str=None) -> Tuple[torch.FloatTensor, Dict]: """Compute the loss and other metrics for the given batch of inputs. Arg: batch: dictionary of inputs for the batch (what is required will vary depending on the trainer) mode: one of 'train', 'eval', 'sample' """ raise NotImplementedError def eval(self) -> Dict[str, Dict]: """ Run evaluation on all the examples in the test data and return the metrics from get_batch_metrics. This is close-ended evaluation and measures the performance of a single model on a single dataset. It does not compare two models to eacch other. Returns: A dict of form: { 'metadata': the Hydra config 'results': a dict of batch metrics (averaged across all of the test data) } """ rank0_print(f'Running evaluation') self.policy.eval() if self.reference_model is not None: self.reference_model.eval() all_eval_metrics = defaultdict(list) for eval_batch in (tqdm.tqdm(self.eval_batches, desc='Computing eval metrics') if self.rank == 0 else self.eval_batches): local_eval_batch = slice_and_move_batch_for_device(eval_batch, self.rank, self.world_size, self.rank) with torch.no_grad(): _, eval_metrics = self.get_batch_metrics(local_eval_batch, mode='eval') for k, v in eval_metrics.items(): all_eval_metrics[k].extend(v) mean_eval_metrics = {} for k, v in all_eval_metrics.items(): if len(v) > 0: mean_eval_metrics[k] = sum(v) / len(v) results = { 'metadata': OmegaConf.to_object(self.config), 'results': formatted_dict(mean_eval_metrics), } return results def sample(self) -> List[Dict[str, str]]: """ Generate samples from the policy model. Returns: A list of samples, each of which is of the form: { 'prompt': the input 'chosen': the generation chosen by the human for the given prompt 'policy': the generation from the policy model } """ all_policy_samples, all_prompts, all_chosen = [], [], [] samples = [] self.policy.eval() if self.reference_model is not None: self.reference_model.eval() for eval_batch in self.eval_batches: local_eval_batch = slice_and_move_batch_for_device(eval_batch, self.rank, self.world_size, self.rank) policy_samples = self.get_batch_samples(local_eval_batch) chosen_samples = [] # for DPO-like losses, chosen_text is the field that will contain the text; target_text for all other losses # be sure to remove EOS token if present for x in (eval_batch['target_text'] if 'target_text' in eval_batch else eval_batch['chosen_text']): if self.tokenizer.eos_token in x: x = x[:x.rfind(self.tokenizer.eos_token)] chosen_samples.append(x) all_prompts.extend(eval_batch['prompt_text']) all_chosen.extend(chosen_samples) all_policy_samples.extend(policy_samples) if self.config.n_samples is not None and len(all_prompts) > self.config.n_samples: break else: rank0_print(f"Generated {len(all_prompts)} samples ...") for i in range(len(all_prompts)): samples.append({ 'prompt' : all_prompts[i], 'chosen' : all_chosen[i], 'policy' : all_policy_samples[i][len(all_prompts[i]):], }) return samples def train(self): """Begin either SFT or HALO training, with periodic evaluation. This is subclassed when implementing PPO.""" rank0_print(f'Using {self.config.optimizer} optimizer with learning rate {self.config.lr}') self.optimizer = getattr(torch.optim, self.config.optimizer)(self.policy.parameters(), lr=self.config.lr) self.scheduler = torch.optim.lr_scheduler.LambdaLR(self.optimizer, lr_lambda=lambda step: min(1.0, (step + 1) / (self.config.warmup_steps + 1))) if self.reference_model is not None: self.reference_model.eval() last_log = None gradients_accumulated = 0 batch_metrics = defaultdict(list) for batch in self.train_iterator: # EVALUATION if self.example_counter % self.config.eval_every == 0 and (self.example_counter > 0 or self.config.do_first_eval): rank0_print(f'Running evaluation after {self.example_counter} train examples') self.policy.eval() all_eval_metrics = defaultdict(list) for eval_batch in (tqdm.tqdm(self.eval_batches, desc='Computing eval metrics') if self.rank == 0 else self.eval_batches): local_eval_batch = slice_and_move_batch_for_device(eval_batch, self.rank, self.world_size, self.rank) with torch.no_grad(): _, eval_metrics = self.get_batch_metrics(local_eval_batch, mode='eval') for k, v in eval_metrics.items(): all_eval_metrics[k].extend(v) delete_dict(local_eval_batch) mean_eval_metrics = {} for k, v in all_eval_metrics.items(): if len(v) > 0: mean_eval_metrics[k] = sum(v) / len(v) rank0_print(f'eval after {self.example_counter}: {formatted_dict(mean_eval_metrics)}') if self.config.wandb.enabled and self.rank == 0: wandb.log(mean_eval_metrics, step=self.example_counter) if self.example_counter > 0: if self.config.debug: rank0_print('skipping save in debug mode') elif self.config.intermediate_checkpoints: output_dir = os.path.join(self.run_dir, f'step-{self.example_counter}') rank0_print(f'creating checkpoint to write to {output_dir}...') self.save(output_dir, mean_eval_metrics) delete_dict(all_eval_metrics) delete_dict(mean_eval_metrics) #### TRAINING self.policy.train() start_time = time.time() local_microbatch = slice_and_move_batch_for_device(batch, self.rank, self.world_size, self.rank) loss, metrics = self.get_batch_metrics(local_microbatch) (loss / self.config.model.gradient_accumulation_steps).backward() for k, v in metrics.items(): batch_metrics[k].extend(v) gradients_accumulated += 1 if gradients_accumulated == self.config.model.gradient_accumulation_steps: grad_norm = self.clip_gradient() batch_metrics['grad_norm'].append(grad_norm) self.optimizer.step() self.optimizer.zero_grad() self.scheduler.step() gradients_accumulated = 0 step_time = time.time() - start_time examples_per_second = self.config.model.batch_size / step_time batch_metrics['examples_per_second'].append(examples_per_second) self.batch_counter += 1 self.example_counter += self.config.model.batch_size delete_dict(local_microbatch) delete_dict(metrics) if gradients_accumulated == 0 and (last_log is None or time.time() - last_log > self.config.minimum_log_interval_secs): mean_train_metrics = {} for k, v in batch_metrics.items(): if len(v) > 0: mean_train_metrics[k] = sum(v) / len(v) mean_train_metrics['counters/examples'] = self.example_counter mean_train_metrics['counters/updates'] = self.batch_counter rank0_print(f'train stats after {self.example_counter} examples: {formatted_dict(mean_train_metrics)}') if self.config.wandb.enabled and self.rank == 0: wandb.log(mean_train_metrics, step=self.example_counter) last_log = time.time() delete_dict(batch_metrics) delete_dict(mean_train_metrics) delete_dict(batch) batch_metrics = defaultdict(list) # explicitly empty cache if less than 100MB available r = torch.cuda.memory_reserved(self.rank) a = torch.cuda.memory_allocated(self.rank) if (r - a) / 1024 < 100: gc.collect() torch.cuda.empty_cache() else: rank0_print(f'skipping logging after {self.example_counter} examples to avoid logging too frequently') def clip_gradient(self): """Clip the gradient norm of the parameters of a non-FSDP policy.""" return torch.nn.utils.clip_grad_norm_(self.policy.parameters(), self.config.model.max_grad_norm).item() def write_state_dict(self, step: int, state: Dict[str, torch.Tensor], metrics: Dict, filename: str, dir_name: Optional[str] = None): """Write a checkpoint to disk. Args: step : current training step state: current state of training (model or optimizer, if applicable) metrics: dictionary of metrics to save dir_name: directory in which to save """ if dir_name is None: dir_name = os.path.join(self.run_dir, f'LATEST') os.makedirs(dir_name, exist_ok=True) output_path = os.path.join(dir_name, filename) rank0_print(f'writing checkpoint to {output_path}...') torch.save({ 'step_idx': step, 'state': state, 'metrics': metrics if metrics is not None else {}, }, output_path) def save(self, output_dir: Optional[str] = None, metrics: Optional[Dict] = None, save_model_only: bool=True): """ Save tokenizer, policy model, optimizer, scheduler state to disk, gathering from all processes and saving only on the rank 0 process. """ if self.fsdp: save_policy = FullStateDictConfig(offload_to_cpu=True, rank0_only=True) with FSDP.state_dict_type(self.policy, StateDictType.FULL_STATE_DICT, state_dict_config=save_policy): policy_state_dict = self.policy.state_dict() if self.rank == 0: self.write_state_dict(self.example_counter, policy_state_dict, metrics, 'policy.pt', output_dir) self.tokenizer.save_pretrained(self.run_dir) # save tokenizer in HF format del policy_state_dict dist.barrier() if not save_model_only: save_policy = FullOptimStateDictConfig(offload_to_cpu=True, rank0_only=True) with FSDP.state_dict_type(self.policy, StateDictType.FULL_STATE_DICT, optim_state_dict_config=save_policy): optimizer_state_dict = FSDP.optim_state_dict(self.policy, self.optimizer) if self.rank == 0: self.write_state_dict(self.example_counter, optimizer_state_dict, metrics, 'optimizer.pt', output_dir) del optimizer_state_dict dist.barrier() if self.rank == 0: scheduler_state_dict = self.scheduler.state_dict() self.write_state_dict(self.example_counter, scheduler_state_dict, metrics, 'scheduler.pt', output_dir) del scheduler_state_dict dist.barrier() else: self.tokenizer.save_pretrained(self.run_dir) # save tokenizer in HF format policy_state_dict = self.policy.state_dict() self.write_state_dict(self.example_counter, policy_state_dict, metrics, 'policy.pt', output_dir) del policy_state_dict if not save_model_only: optimizer_state_dict = self.optimizer.state_dict() self.write_state_dict(self.example_counter, optimizer_state_dict, metrics, 'optimizer.pt', output_dir) del optimizer_state_dict scheduler_state_dict = self.scheduler.state_dict() self.write_state_dict(self.example_counter, scheduler_state_dict, metrics, 'scheduler.pt', output_dir) del scheduler_state_dict class SFTTrainer(BasicTrainer): def get_batch_metrics(self, batch: Dict[str, Union[List, torch.LongTensor]], mode: str=None): """Compute the loss and other metrics for the given batch of inputs. Args: batch: dictionary of inputs for the batch (should contain 'target_attention_mask', 'target_input_input_ids', 'target_labels' where 'target' corresponds to the SFT example) mode: one of 'train', 'eval', 'sample' """ metrics = {} if mode is None: mode = self.config.mode policy_chosen_logits = self.policy(batch['target_combined_input_ids'], attention_mask=batch['target_combined_attention_mask'], use_cache=(not self.is_mistral)).logits.to(self.policy_dtype) policy_chosen_logps = get_batch_logps(policy_chosen_logits, batch['target_labels'], average_log_prob=False) losses = -policy_chosen_logps policy_chosen_logps = all_gather_if_needed(policy_chosen_logps.detach(), self.rank, self.world_size) all_devices_losses = all_gather_if_needed(losses.detach(), self.rank, self.world_size) metrics[f'logps_{mode}/chosen'] = policy_chosen_logps.float().cpu().numpy().tolist() metrics[f'loss/{mode}'] = all_devices_losses.float().cpu().numpy().tolist() return losses.mean(), metrics class UnpairedPreferenceTrainer(BasicTrainer): """A trainer for any loss that doesn't use paired preference, like KTO.""" def forward(self, model: nn.Module, batch: Dict[str, Union[List, torch.LongTensor]]) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.BoolTensor]: """Run the given model on the given batch of inputs. Returns: chosen_logps: log probabilities of chosen examples (should be batch size / 2 if data was read in correctly) rejected_logps: log probabilities of rejected examples (should be batch size / 2 if data was read in correctly) """ all_logits = model(batch['target_combined_input_ids'], attention_mask=batch['target_combined_attention_mask'], use_cache=(not self.is_mistral)).logits.to(self.policy_dtype) all_logps = get_batch_logps(all_logits, batch['target_labels'], average_log_prob=False) assert all_logps.shape[0] == len(batch['status']) chosen_idx = [i for i in range(all_logps.shape[0]) if batch['status'][i] == 'chosen'] rejected_idx = [i for i in range(all_logps.shape[0]) if batch['status'][i] == 'rejected'] chosen_logps = all_logps[chosen_idx, ...] rejected_logps = all_logps[rejected_idx, ...] return chosen_logps, rejected_logps def get_batch_metrics(self, batch: Dict[str, Union[List, torch.LongTensor]], mode: str=None): """Compute the loss and other metrics for the given batch of inputs.""" metrics = {} if mode is None: mode = self.config.mode if self.reference_model is None: policy_chosen_logps, policy_rejected_logps = self.forward(self.policy, batch) losses, chosen_rewards, rejected_rewards = self.loss(policy_chosen_logps, policy_rejected_logps) else: policy_chosen_logps, policy_rejected_logps = self.forward(self.policy, batch) with torch.no_grad(): reference_chosen_logps, reference_rejected_logps = self.forward(self.reference_model, batch) losses, chosen_rewards, rejected_rewards = self.loss(policy_chosen_logps, policy_rejected_logps, reference_chosen_logps, reference_rejected_logps) # all_gather treats empty lists/tensors poorly, and empty lists can occur because a batch can contain all chosen or all rejected example # therefore, concatenate chosen + rejected rewards before all_gather combined_rewards = torch.cat((chosen_rewards.detach(), rejected_rewards.detach()), 0) combined_statuses = torch.Tensor([1] * len(chosen_rewards) + [0] * len(rejected_rewards)).to(self.device) all_rewards = all_gather_if_needed(combined_rewards, self.rank, self.world_size) all_statuses = all_gather_if_needed(combined_statuses, self.rank, self.world_size) chosen_rewards_idx = [ i for i in range(len(all_statuses)) if all_statuses[i].item() == 1 ] rejected_rewards_idx = [ i for i in range(len(all_statuses)) if all_statuses[i].item() == 0 ] all_devices_losses = all_gather_if_needed(losses.detach(), self.rank, self.world_size) metrics[f'rewards_{mode}/chosen'] = all_rewards[chosen_rewards_idx].float().cpu().numpy().tolist() metrics[f'rewards_{mode}/rejected'] = all_rewards[rejected_rewards_idx].float().cpu().numpy().tolist() metrics[f'rewards_{mode}/margins'] = [(all_rewards[chosen_rewards_idx].mean().nan_to_num(0) - all_rewards[rejected_rewards_idx].mean().nan_to_num(0)).item()] metrics[f'loss/{mode}'] = all_devices_losses.float().cpu().numpy().tolist() del policy_chosen_logps, policy_rejected_logps del combined_rewards, combined_statuses, all_rewards, all_statuses, chosen_rewards_idx, rejected_rewards_idx, all_devices_losses if self.reference_model: del reference_chosen_logps, reference_rejected_logps return losses.mean(), metrics class PairedPreferenceTrainer(BasicTrainer): """A trainer for any loss that uses paired preference, like DPO.""" def concatenated_inputs(self, batch: Dict[str, Union[List, torch.LongTensor]]) -> Dict[str, torch.LongTensor]: """Concatenate the chosen and rejected inputs into a single tensor. The first half is chosen outputs, the second half is rejected. Args: batch: A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors of shape (batch_size, sequence_length). Returns: A dictionary containing the concatenated inputs under the key 'concatenated_input_ids'. """ max_length = max(batch['chosen_combined_input_ids'].shape[1], batch['rejected_combined_input_ids'].shape[1]) concatenated_batch = {} for k in batch: if k.startswith('chosen') and isinstance(batch[k], torch.Tensor): pad_value = -100 if 'labels' in k else 0 concatenated_key = k.replace('chosen', 'concatenated') concatenated_batch[concatenated_key] = pad_to_length(batch[k], max_length, pad_value=pad_value) for k in batch: if k.startswith('rejected') and isinstance(batch[k], torch.Tensor): pad_value = -100 if 'labels' in k else 0 concatenated_key = k.replace('rejected', 'concatenated') concatenated_batch[concatenated_key] = torch.cat(( concatenated_batch[concatenated_key], pad_to_length(batch[k], max_length, pad_value=pad_value), ), dim=0) return concatenated_batch def forward(self, model: nn.Module, batch: Dict[str, Union[List, torch.LongTensor]]) -> Tuple[torch.FloatTensor, torch.FloatTensor]: """Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together. Return two tensors of shape (batch size), one of the chosen examples, another of the rejected ones. """ concatenated_batch = self.concatenated_inputs(batch) all_logits = model(concatenated_batch['concatenated_combined_input_ids'], attention_mask=concatenated_batch['concatenated_combined_attention_mask'], use_cache=(not self.is_mistral)).logits.to(self.policy_dtype) all_logps = get_batch_logps(all_logits, concatenated_batch['concatenated_labels'], average_log_prob=False) chosen_logps = all_logps[:batch['chosen_combined_input_ids'].shape[0]] rejected_logps = all_logps[batch['chosen_combined_input_ids'].shape[0]:] return chosen_logps, rejected_logps def get_batch_metrics(self, batch: Dict[str, Union[List, torch.LongTensor]], mode: str=None): """Compute the loss and other metrics for the given batch of inputs.""" metrics = {} if mode is None: mode = self.config.mode if self.reference_model is None: policy_chosen_logps, policy_rejected_logps = self.forward(self.policy, batch) losses, chosen_rewards, rejected_rewards = self.loss(policy_chosen_logps, policy_rejected_logps) else: policy_chosen_logps, policy_rejected_logps = self.forward(self.policy, batch) with torch.no_grad(): reference_chosen_logps, reference_rejected_logps = self.forward(self.reference_model, batch) losses, chosen_rewards, rejected_rewards = self.loss(policy_chosen_logps, policy_rejected_logps, reference_chosen_logps, reference_rejected_logps) # accuracy calculated on unpaired examples (for apples-to-apples comparison with UnpairedPreferenceTrainer) reward_accuracies = (chosen_rewards > rejected_rewards.flip(dims=[0])).float() chosen_rewards = all_gather_if_needed(chosen_rewards, self.rank, self.world_size) rejected_rewards = all_gather_if_needed(rejected_rewards, self.rank, self.world_size) reward_accuracies = all_gather_if_needed(reward_accuracies, self.rank, self.world_size) policy_chosen_logps = all_gather_if_needed(policy_chosen_logps.detach(), self.rank, self.world_size) policy_rejected_logps = all_gather_if_needed(policy_rejected_logps.detach(), self.rank, self.world_size) all_devices_losses = all_gather_if_needed(losses.detach(), self.rank, self.world_size) metrics[f'rewards_{mode}/chosen'] = chosen_rewards.float().cpu().numpy().tolist() metrics[f'rewards_{mode}/rejected'] = rejected_rewards.float().cpu().numpy().tolist() metrics[f'rewards_{mode}/accuracies'] = reward_accuracies.float().cpu().numpy().tolist() metrics[f'rewards_{mode}/margins'] = (chosen_rewards - rejected_rewards).float().cpu().numpy().tolist() metrics[f'logps_{mode}/rejected'] = policy_rejected_logps.float().cpu().numpy().tolist() metrics[f'logps_{mode}/chosen'] = policy_chosen_logps.float().cpu().numpy().tolist() metrics[f'loss/{mode}'] = all_devices_losses.float().cpu().numpy().tolist() del chosen_rewards, rejected_rewards, reward_accuracies, policy_chosen_logps, policy_rejected_logps, all_devices_losses if self.reference_model: del reference_chosen_logps, reference_rejected_logps return losses.mean(), metrics class DPOTrainer(PairedPreferenceTrainer): def loss(self, policy_chosen_logps: torch.FloatTensor, policy_rejected_logps: torch.FloatTensor, reference_chosen_logps: torch.FloatTensor, reference_rejected_logps: torch.FloatTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: """Compute the DPO loss for a batch of policy and reference model log probabilities.""" pi_logratios = policy_chosen_logps - policy_rejected_logps ref_logratios = reference_chosen_logps - reference_rejected_logps logits = pi_logratios - ref_logratios losses = -F.logsigmoid(self.config.loss.beta * logits) chosen_rewards = self.config.loss.beta * (policy_chosen_logps - reference_chosen_logps).detach() rejected_rewards = self.config.loss.beta * (policy_rejected_logps - reference_rejected_logps).detach() return losses, chosen_rewards, rejected_rewards class CDPOTrainer(PairedPreferenceTrainer): def loss(self, policy_chosen_logps: torch.FloatTensor, policy_rejected_logps: torch.FloatTensor, reference_chosen_logps: torch.FloatTensor, reference_rejected_logps: torch.FloatTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: """Compute the CDPO loss for a batch of policy and reference model log probabilities.""" forward_losses = -F.logsigmoid(self.config.loss.beta * ((policy_chosen_logps - reference_chosen_logps) - (policy_rejected_logps - reference_rejected_logps))) reverse_losses = -F.logsigmoid(self.config.loss.beta * ((policy_rejected_logps - reference_rejected_logps) - (policy_chosen_logps - reference_chosen_logps))) losses = (1 - self.config.loss.epsilon) * forward_losses + self.config.loss.epsilon * reverse_losses chosen_rewards = self.config.loss.beta * (policy_chosen_logps - reference_chosen_logps).detach() rejected_rewards = self.config.loss.beta * (policy_rejected_logps - reference_rejected_logps).detach() return losses, chosen_rewards, rejected_rewards class SLiCTrainer(PairedPreferenceTrainer): def loss(self, policy_chosen_logps: torch.FloatTensor, policy_rejected_logps: torch.FloatTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: """Compute the SLIC loss as defined by Zhao et al. in https://arxiv.org/pdf/2305.10425.pdf Calibration loss defined as: L(x, y) := max(0, beta - log p_policy(y_chosen|x) + log p_rejected(y|x)) For the cross-entropy loss, just use the NLL of the chosen sequence (equivalent to SFT). """ cal_loss = torch.clamp(self.config.loss.beta - policy_chosen_logps + policy_rejected_logps, min=0) reg_loss = -policy_chosen_logps losses = cal_loss + self.config.loss.lambda_coef * reg_loss chosen_rewards = policy_chosen_logps.detach() rejected_rewards = policy_rejected_logps.detach() return losses, chosen_rewards, rejected_rewards class SimpleKTOTrainer(UnpairedPreferenceTrainer): def loss(self, policy_chosen_logps: torch.FloatTensor, policy_rejected_logps: torch.FloatTensor, reference_chosen_logps: torch.FloatTensor, reference_rejected_logps: torch.FloatTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: """Compute the Kahneman-Tversky loss for a batch of policy and reference model log probabilities. For each batch of n/2 chosen examples and n/2 rejected examples (belonging to n different inputs), calculate the loss as follows. If generation y ~ p_chosen, where x' ~ are the examples with rejected generations, we have the 'chosen' loss: L(x, y) := 1 - sigmoid(beta * ([log p_policy(y|x) - log p_reference(y|x)] - KL(p_policy(y_rejected|x') || p_reference(y_rejected|x'))) If generation y ~ p_rejected, , where x' ~ are the examples with chosen generations, we have the 'rejected' loss: L(x, y) := 1 - sigmoid(beta * (KL(p_policy(y_chosen|x') || p_reference(y_chosen|x')) - [log p_policy(y|x) - log p_reference(y|x)])) """ chosen_KL = (policy_chosen_logps - reference_chosen_logps).mean().clamp(min=0) rejected_KL = (policy_rejected_logps - reference_rejected_logps).mean().clamp(min=0) chosen_logratios = (policy_chosen_logps - reference_chosen_logps) rejected_logratios = (policy_rejected_logps - reference_rejected_logps) losses = torch.cat((1 - F.sigmoid(self.config.loss.beta * (chosen_logratios - rejected_KL)), 1 - F.sigmoid(self.config.loss.beta * (chosen_KL - rejected_logratios))), 0) chosen_rewards = self.config.loss.beta * (policy_chosen_logps - reference_chosen_logps).detach() rejected_rewards = self.config.loss.beta * (policy_rejected_logps - reference_rejected_logps).detach() return losses, chosen_rewards, rejected_rewards class KTOTrainer(UnpairedPreferenceTrainer): def loss(self, policy_chosen_logps: torch.FloatTensor, policy_rejected_logps: torch.FloatTensor, policy_KL_logps: torch.FloatTensor, reference_chosen_logps: torch.FloatTensor, reference_rejected_logps: torch.FloatTensor, reference_KL_logps) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: """Compute the Kahneman-Tversky loss for a batch of policy and reference model log probabilities. If generation y ~ p_desirable, we have the 'desirable' loss: L(x, y) := 1 - sigmoid(beta * ([log p_policy(y|x) - log p_reference(y|x)] - KL(p_policy || p_reference))) If generation y ~ p_undesirable, we have the 'undesirable' loss: L(x, y) := 1 - sigmoid(beta * (KL(p_policy || p_reference) - [log p_policy(y|x) - log p_reference(y|x)])) The desirable losses are weighed by config.loss.desirable_weight. The undesirable losses are weighed by config.loss.undesirable_weight. This should be used to address imbalances in the ratio of desirable:undesirable examples respectively. The KL term is estimated by matching x with unrelated outputs y', then calculating the average log ratio log p_policy(y'|x) - log p_reference(y'|x). Doing so avoids the requirement that there be equal numbers of desirable and undesirable examples in the microbatch. """ KL = (policy_KL_logps - reference_KL_logps).mean().detach() # nn.all_reduce sums up the KL estimates across all devices (gradient will also be scaled by world size) dist.nn.all_reduce(KL, op=dist.ReduceOp.SUM) # take average (will also scale gradients appropriately) KL = (KL / self.world_size).clamp(min=0) if policy_chosen_logps.shape[0] != 0: chosen_logratios = (policy_chosen_logps - reference_chosen_logps) chosen_losses = 1 - F.sigmoid(self.config.loss.beta * (chosen_logratios - KL)) chosen_rewards = self.config.loss.beta * chosen_logratios.detach() else: # important to cast to policy_dtype; otherwise error will occur during all_gather chosen_losses = torch.Tensor([]).to(self.policy_dtype).to(self.device) chosen_rewards = torch.Tensor([]).to(self.policy_dtype).to(self.device) if policy_rejected_logps.shape[0] != 0: rejected_logratios = (policy_rejected_logps - reference_rejected_logps) rejected_losses = 1 - F.sigmoid(self.config.loss.beta * (KL - rejected_logratios)) rejected_rewards = self.config.loss.beta * rejected_logratios.detach() else: # important to cast to policy_dtype; otherwise error will occur during all_gather rejected_losses = torch.Tensor([]).to(self.policy_dtype).to(self.device) rejected_rewards = torch.Tensor([]).to(self.policy_dtype).to(self.device) losses = torch.cat((self.config.loss.desirable_weight * chosen_losses, self.config.loss.undesirable_weight * rejected_losses), 0) return losses, chosen_rewards, rejected_rewards, KL def forward(self, model: nn.Module, batch: Dict[str, Union[List, torch.LongTensor]]) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: """Run the given model on the given batch of inputs. The examples used to calculate the rewards and the KL term should be processed in a single forward pass, since the gradient is taken wrt both groups. Doing it in multiple forward passes will give you a RuntimeError: 'The tensor has a non-zero number of elements, but its data is not allocated yet.' Args: - model: the model to use for the forward pass - batch: the microbatch (should have the input ids, attention mask, and labels) Returns: chosen_logps: log probabilities of chosen examples (should be batch size / 2 if data was read in correctly) rejected_logps: log probabilities of rejected examples (should be batch size / 2 if data was read in correctly) KL_logps: log probabilities of the unmatched y'|x (used to estimate the KL divergence between policy and reference; should be batch size) """ max_length = max(batch['target_combined_input_ids'].shape[1], batch['KL_combined_input_ids'].shape[1]) concatenated_batch = {} for k in batch: if k.startswith('target') and isinstance(batch[k], torch.Tensor): pad_value = -100 if 'labels' in k else 0 concatenated_key = k.replace('target', 'concatenated') concatenated_batch[concatenated_key] = pad_to_length(batch[k], max_length, pad_value=pad_value) for k in batch: if k.startswith('KL') and isinstance(batch[k], torch.Tensor): pad_value = -100 if 'labels' in k else 0 concatenated_key = k.replace('KL', 'concatenated') concatenated_batch[concatenated_key] = torch.cat(( concatenated_batch[concatenated_key], pad_to_length(batch[k], max_length, pad_value=pad_value), ), dim=0) all_logits = model( concatenated_batch[f'concatenated_combined_input_ids'], attention_mask=concatenated_batch[f'concatenated_combined_attention_mask'] ).logits.to(self.policy_dtype) all_logps = get_batch_logps(all_logits, concatenated_batch[f'concatenated_labels'], average_log_prob=False) target_logps = all_logps[:batch['target_combined_input_ids'].shape[0]] KL_logps = all_logps[batch['target_combined_input_ids'].shape[0]:] assert target_logps.shape[0] == len(batch['status']) chosen_idx = [i for i in range(target_logps.shape[0]) if batch['status'][i] == 'chosen'] rejected_idx = [i for i in range(target_logps.shape[0]) if batch['status'][i] == 'rejected'] chosen_logps = target_logps[chosen_idx, ...] rejected_logps = target_logps[rejected_idx, ...] return chosen_logps, rejected_logps, KL_logps def get_batch_metrics(self, batch: Dict[str, Union[List, torch.LongTensor]], mode: str=None): """Compute the loss and other metrics for the given batch of inputs.""" metrics = {} if mode is None: mode = self.config.mode policy_chosen_logps, policy_rejected_logps, policy_KL_logps = self.forward(self.policy, batch) with torch.no_grad(): reference_chosen_logps, reference_rejected_logps, reference_KL_logps = self.forward(self.reference_model, batch) losses, chosen_rewards, rejected_rewards, KL = self.loss( policy_chosen_logps, policy_rejected_logps, policy_KL_logps, reference_chosen_logps, reference_rejected_logps, reference_KL_logps ) combined_rewards = torch.cat((chosen_rewards.detach(), rejected_rewards.detach()), 0) combined_statuses = torch.Tensor([1] * len(chosen_rewards) + [0] * len(rejected_rewards)).to(self.device) all_rewards = all_gather_if_needed(combined_rewards, self.rank, self.world_size) all_statuses = all_gather_if_needed(combined_statuses, self.rank, self.world_size) all_KL = all_gather_if_needed(KL, self.rank, self.world_size) chosen_rewards_idx = [ i for i in range(len(all_statuses)) if all_statuses[i].item() == 1 ] rejected_rewards_idx = [ i for i in range(len(all_statuses)) if all_statuses[i].item() == 0 ] all_devices_losses = all_gather_if_needed(losses.detach(), self.rank, self.world_size) metrics[f'rewards_{mode}/chosen'] = all_rewards[chosen_rewards_idx].float().cpu().numpy().tolist() metrics[f'rewards_{mode}/rejected'] = all_rewards[rejected_rewards_idx].float().cpu().numpy().tolist() metrics[f'rewards_{mode}/margins'] = [(all_rewards[chosen_rewards_idx].mean().nan_to_num(0) - all_rewards[rejected_rewards_idx].mean().nan_to_num(0)).item()] metrics[f'rewards_{mode}/KL_estimate'] = all_KL.float().cpu().numpy().tolist() metrics[f'loss/{mode}'] = all_devices_losses.float().cpu().numpy().tolist() del policy_chosen_logps, policy_rejected_logps, policy_KL_logps, reference_chosen_logps, reference_rejected_logps, reference_KL_logps del combined_rewards, combined_statuses, all_rewards, all_statuses, chosen_rewards_idx, rejected_rewards_idx, all_devices_losses, all_KL return losses.mean(), metrics class KTOZeroTrainer(UnpairedPreferenceTrainer): def loss(self, policy_chosen_logps: torch.FloatTensor, policy_rejected_logps: torch.FloatTensor, reference_chosen_logps: torch.FloatTensor, reference_rejected_logps: torch.FloatTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: """Compute a variant of the Kahneman-Tversky loss where the reference point is 0 instead of the expected reward (i.e., the human reference point remains what it is at initialization, when policy = reference). This should NOT be used for purposes other than to understand the importance of the KL term. One can also think of this as a variant of unlikelihood training (Welleck et al., 2023). The purpose of this is to understand the importance of the KL term in the standard variant of the KTO loss. We do *not* reecommend using this in practice as its performance is usually inferior. For each batch of n/2 chosen examples and n/2 rejected examples (belonging to n different inputs), calculate the loss as follows. If generation y ~ p_chosen, where x' ~ are the examples with rejected generations, we have the 'chosen' loss: L(x, y) := 1 - sigmoid(beta * ([log p_policy(y|x) - log p_reference(y|x)] - 0)) If generation y ~ p_rejected, , where x' ~ are the examples with chosen generations, we have the 'rejected' loss: L(x, y) := 1 - sigmoid(beta * (0 - [log p_policy(y|x) - log p_reference(y|x)])) """ chosen_logratios = (policy_chosen_logps - reference_chosen_logps) rejected_logratios = (policy_rejected_logps - reference_rejected_logps) losses = torch.cat((1 - F.sigmoid(self.config.loss.beta * (chosen_logratios - 0)), 1 - F.sigmoid(self.config.loss.beta * (0 - rejected_logratios))), 0) chosen_rewards = self.config.loss.beta * (policy_chosen_logps - reference_chosen_logps).detach() rejected_rewards = self.config.loss.beta * (policy_rejected_logps - reference_rejected_logps).detach() return losses, chosen_rewards, rejected_rewards class PPOTrainer(BasicTrainer): """One-step, offline variant of PPO.""" def forward(self, model: AutoModelForCausalLMWithValueHead, batch: Dict[str, Union[List, torch.LongTensor]], is_policy: bool=True) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: """Run the given model on the given batch of inputs. Args: model: model to run forward pass on batch: input batch (forward pass will be run on keys with prefix 'chosen') masks: binary-valued tensor shape (batch size, sequence length) is_policy: whether the model is the policy or reference Returns: all_logps: batch log probabilities at the token level of shape (batch size, sequence length) all_logits: corresponding logits of shape (batch size, sequence length) all_values: values predicted for each token, of shape (batch size, sequence length) """ if is_policy: # here the prefix 'chosen' is a misnomer, since it can refer to the dispreferred generations # the 'status' field contains the actual status of the generations all_logits, _, all_values = model(batch['target_combined_input_ids'], attention_mask=batch['target_combined_attention_mask']) all_values = all_values[:, :-1].contiguous().to(self.rank) else: all_logits = model(batch['target_combined_input_ids'], attention_mask=batch['target_combined_attention_mask'], use_cache=(not self.is_mistral)).logits.to(self.policy_dtype) all_values = None all_logps = get_batch_logps(all_logits.to(self.policy_dtype), batch['target_labels'], average_log_prob=False, token_level=True) # Returned tensors will have sequence length that is one less than the inputs (to account for label shifting). all_logits = all_logits[:, :-1].contiguous().to(self.rank) all_logps = all_logps.contiguous().to(self.rank) return all_logps, all_logits, all_values def compute_advantages(self, values: torch.FloatTensor, rewards: torch.FloatTensor, masks: torch.FloatTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor]: """ Estimate the advantages and rewards for every token taken. Args: values: the estimated values of the tokens. Should already be detached from graph. rewards: signal from the environment as to whether the generation is good or bad. In the basic implementation, this is only one nonzero reward, on the last unpadded token of each sequence. torch tensor of shape (batch size, sequence length) masks: torch tensor of shape (batch size, sequence length); 1 if token should be considered and 0 otherwise Returns: advantages: torch tensor of shape (batch size, sequence length) returns: Also called 'rewards-to-go'. Only tokens after the current token are used to calculate this: http://rail.eecs.berkeley.edu/deeprlcourse/static/slides/lec-5.pdf torch tensor of shape (batch size, sequence length) """ values = values * masks rewards = rewards * masks gae = 0 # generalized advantage estimation seq_len = rewards.shape[-1] advantages_reversed = [] discounted_future_reward = torch.zeros_like(rewards[:,0]) discounted_future_rewards_reversed = [] for t in reversed(range(seq_len)): # see https://towardsdatascience.com/proximal-policy-optimization-tutorial-part-2-2-gae-and-ppo-loss-fe1b3c5549e8 delta = rewards[:, t] + self.config.loss.gamma * (values[:, t + 1] if t < seq_len - 1 else 0.0) - values[:, t] gae = delta + self.config.loss.gamma * self.config.loss.lam * gae advantages_reversed.append(gae) discounted_future_rewards_reversed.append(discounted_future_reward) discounted_future_reward = rewards[:, t] + self.config.loss.gamma * discounted_future_reward advantages = (torch.stack(advantages_reversed[::-1]).transpose(0, 1) * masks) returns = (advantages + values).contiguous().to(self.rank) discounted_future_rewards = (torch.stack(discounted_future_rewards_reversed[::-1]).transpose(0, 1) * masks).contiguous().to(self.rank) # normalizing advantages leads to more stable learning mean_adv, var_adv = masked_mean(advantages, masks), masked_var(advantages, masks) normalized_advantages = (advantages - mean_adv) * torch.rsqrt(var_adv + 1e-8) normalized_advantages = (normalized_advantages * masks).detach().contiguous().to(self.rank) return normalized_advantages, returns, discounted_future_rewards def loss(self, batch: Dict, episode: Dict) -> Tuple[torch.FloatTensor, Dict]: """ Given the batch statistics and the current episode's values, calculate the loss and return some loss statistics. Args: batch: dictionary containing batch data (shoud have keys 'values', 'returns', 'advantages', 'logprobs', 'masks') episode: dictionary containing the episode data (should have keys 'logits', 'values', 'logprobs') Returns: loss: combined policy and critic loss of shape (1,) loss_stats: dictionary of episode/batch statistics """ value_losses = (episode['values'] - batch['discounted_future_rewards'].detach()) ** 2 critic_loss = 0.5 * masked_mean(value_losses, batch['masks']) ratio = torch.exp(episode['logprobs'] - batch['logprobs']) policy_losses = -batch['advantages'] * ratio policy_losses_clipped = -batch['advantages'] * torch.clamp(ratio, self.config.loss.cliprange, 1 / self.config.loss.cliprange) policy_loss = masked_mean(torch.max(policy_losses, policy_losses_clipped), batch['masks']) KL_penalty = masked_mean(batch['logprobs'] - episode['logprobs'], batch['masks']) loss = policy_loss + self.config.loss.critic_coef * critic_loss + self.config.loss.KL_coef * KL_penalty loss_stats = { 'loss/total' : loss.detach(), 'loss/critic' : critic_loss.detach(), 'loss/policy' : policy_loss.detach(), 'clipfrac/policy' : masked_mean(torch.gt(policy_losses_clipped, policy_losses).float(), batch['masks']).detach(),
'loss/entropy' : entropy_from_logits(episode['logits'], batch['masks']).detach(),
10
2023-12-03 07:53:36+00:00
12k
AIFSH/NativeSpeaker
src/third_part/whisperx/transcribe.py
[ { "identifier": "align", "path": "src/third_part/whisperx/alignment.py", "snippet": "def align(\n transcript: Iterable[SingleSegment],\n model: torch.nn.Module,\n align_model_metadata: dict,\n audio: Union[str, np.ndarray, torch.Tensor],\n device: str,\n interpolate_method: str = \"nea...
import argparse import gc import os import warnings import numpy as np import torch from .alignment import align, load_align_model from .asr import load_model from .audio import load_audio from .diarize import DiarizationPipeline, assign_word_speakers from .utils import (LANGUAGES, TO_LANGUAGE_CODE, get_writer, optional_float, optional_int, str2bool)
9,119
parser.add_argument("--max_speakers", default=None, type=int, help="Maximum number of speakers to in audio file") parser.add_argument("--temperature", type=float, default=0, help="temperature to use for sampling") parser.add_argument("--best_of", type=optional_int, default=5, help="number of candidates when sampling with non-zero temperature") parser.add_argument("--beam_size", type=optional_int, default=5, help="number of beams in beam search, only applicable when temperature is zero") parser.add_argument("--patience", type=float, default=1.0, help="optional patience value to use in beam decoding, as in https://arxiv.org/abs/2204.05424, the default (1.0) is equivalent to conventional beam search") parser.add_argument("--length_penalty", type=float, default=1.0, help="optional token length penalty coefficient (alpha) as in https://arxiv.org/abs/1609.08144, uses simple length normalization by default") parser.add_argument("--suppress_tokens", type=str, default="-1", help="comma-separated list of token ids to suppress during sampling; '-1' will suppress most special characters except common punctuations") parser.add_argument("--suppress_numerals", action="store_true", help="whether to suppress numeric symbols and currency symbols during sampling, since wav2vec2 cannot align them correctly") parser.add_argument("--initial_prompt", type=str, default=None, help="optional text to provide as a prompt for the first window.") parser.add_argument("--condition_on_previous_text", type=str2bool, default=False, help="if True, provide the previous output of the model as a prompt for the next window; disabling may make the text inconsistent across windows, but the model becomes less prone to getting stuck in a failure loop") parser.add_argument("--fp16", type=str2bool, default=True, help="whether to perform inference in fp16; True by default") parser.add_argument("--temperature_increment_on_fallback", type=optional_float, default=0.2, help="temperature to increase when falling back when the decoding fails to meet either of the thresholds below") parser.add_argument("--compression_ratio_threshold", type=optional_float, default=2.4, help="if the gzip compression ratio is higher than this value, treat the decoding as failed") parser.add_argument("--logprob_threshold", type=optional_float, default=-1.0, help="if the average log probability is lower than this value, treat the decoding as failed") parser.add_argument("--no_speech_threshold", type=optional_float, default=0.6, help="if the probability of the <|nospeech|> token is higher than this value AND the decoding has failed due to `logprob_threshold`, consider the segment as silence") parser.add_argument("--max_line_width", type=optional_int, default=None, help="(not possible with --no_align) the maximum number of characters in a line before breaking the line") parser.add_argument("--max_line_count", type=optional_int, default=None, help="(not possible with --no_align) the maximum number of lines in a segment") parser.add_argument("--highlight_words", type=str2bool, default=False, help="(not possible with --no_align) underline each word as it is spoken in srt and vtt") parser.add_argument("--segment_resolution", type=str, default="sentence", choices=["sentence", "chunk"], help="(not possible with --no_align) the maximum number of characters in a line before breaking the line") parser.add_argument("--threads", type=optional_int, default=0, help="number of threads used by torch for CPU inference; supercedes MKL_NUM_THREADS/OMP_NUM_THREADS") parser.add_argument("--hf_token", type=str, default=None, help="Hugging Face Access Token to access PyAnnote gated models") parser.add_argument("--print_progress", type=str2bool, default = False, help = "if True, progress will be printed in transcribe() and align() methods.") # fmt: on args = parser.parse_args().__dict__ model_name: str = args.pop("model") batch_size: int = args.pop("batch_size") output_dir: str = args.pop("output_dir") output_format: str = args.pop("output_format") device: str = args.pop("device") device_index: int = args.pop("device_index") compute_type: str = args.pop("compute_type") # model_flush: bool = args.pop("model_flush") os.makedirs(output_dir, exist_ok=True) align_model: str = args.pop("align_model") interpolate_method: str = args.pop("interpolate_method") no_align: bool = args.pop("no_align") task : str = args.pop("task") if task == "translate": # translation cannot be aligned no_align = True return_char_alignments: bool = args.pop("return_char_alignments") hf_token: str = args.pop("hf_token") vad_onset: float = args.pop("vad_onset") vad_offset: float = args.pop("vad_offset") chunk_size: int = args.pop("chunk_size") diarize: bool = args.pop("diarize") min_speakers: int = args.pop("min_speakers") max_speakers: int = args.pop("max_speakers") print_progress: bool = args.pop("print_progress") if args["language"] is not None: args["language"] = args["language"].lower() if args["language"] not in LANGUAGES: if args["language"] in TO_LANGUAGE_CODE: args["language"] = TO_LANGUAGE_CODE[args["language"]] else: raise ValueError(f"Unsupported language: {args['language']}") if model_name.endswith(".en") and args["language"] != "en": if args["language"] is not None: warnings.warn( f"{model_name} is an English-only model but receipted '{args['language']}'; using English instead." ) args["language"] = "en" align_language = args["language"] if args["language"] is not None else "en" # default to loading english if not specified temperature = args.pop("temperature") if (increment := args.pop("temperature_increment_on_fallback")) is not None: temperature = tuple(np.arange(temperature, 1.0 + 1e-6, increment)) else: temperature = [temperature] faster_whisper_threads = 4 if (threads := args.pop("threads")) > 0: torch.set_num_threads(threads) faster_whisper_threads = threads asr_options = { "beam_size": args.pop("beam_size"), "patience": args.pop("patience"), "length_penalty": args.pop("length_penalty"), "temperatures": temperature, "compression_ratio_threshold": args.pop("compression_ratio_threshold"), "log_prob_threshold": args.pop("logprob_threshold"), "no_speech_threshold": args.pop("no_speech_threshold"), "condition_on_previous_text": False, "initial_prompt": args.pop("initial_prompt"), "suppress_tokens": [int(x) for x in args.pop("suppress_tokens").split(",")], "suppress_numerals": args.pop("suppress_numerals"), } writer = get_writer(output_format, output_dir) word_options = ["highlight_words", "max_line_count", "max_line_width"] if no_align: for option in word_options: if args[option]: parser.error(f"--{option} not possible with --no_align") if args["max_line_count"] and not args["max_line_width"]: warnings.warn("--max_line_count has no effect without --max_line_width") writer_args = {arg: args.pop(arg) for arg in word_options} # Part 1: VAD & ASR Loop results = [] tmp_results = [] # model = load_model(model_name, device=device, download_root=model_dir)
def cli(): # fmt: off parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("audio", nargs="+", type=str, help="audio file(s) to transcribe") parser.add_argument("--model", default="small", help="name of the Whisper model to use") parser.add_argument("--model_dir", type=str, default=None, help="the path to save model files; uses ~/.cache/whisper by default") parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu", help="device to use for PyTorch inference") parser.add_argument("--device_index", default=0, type=int, help="device index to use for FasterWhisper inference") parser.add_argument("--batch_size", default=8, type=int, help="the preferred batch size for inference") parser.add_argument("--compute_type", default="float16", type=str, choices=["float16", "float32", "int8"], help="compute type for computation") parser.add_argument("--output_dir", "-o", type=str, default=".", help="directory to save the outputs") parser.add_argument("--output_format", "-f", type=str, default="all", choices=["all", "srt", "vtt", "txt", "tsv", "json", "aud"], help="format of the output file; if not specified, all available formats will be produced") parser.add_argument("--verbose", type=str2bool, default=True, help="whether to print out the progress and debug messages") parser.add_argument("--task", type=str, default="transcribe", choices=["transcribe", "translate"], help="whether to perform X->X speech recognition ('transcribe') or X->English translation ('translate')") parser.add_argument("--language", type=str, default=None, choices=sorted(LANGUAGES.keys()) + sorted([k.title() for k in TO_LANGUAGE_CODE.keys()]), help="language spoken in the audio, specify None to perform language detection") # alignment params parser.add_argument("--align_model", default=None, help="Name of phoneme-level ASR model to do alignment") parser.add_argument("--interpolate_method", default="nearest", choices=["nearest", "linear", "ignore"], help="For word .srt, method to assign timestamps to non-aligned words, or merge them into neighbouring.") parser.add_argument("--no_align", action='store_true', help="Do not perform phoneme alignment") parser.add_argument("--return_char_alignments", action='store_true', help="Return character-level alignments in the output json file") # vad params parser.add_argument("--vad_onset", type=float, default=0.500, help="Onset threshold for VAD (see pyannote.audio), reduce this if speech is not being detected") parser.add_argument("--vad_offset", type=float, default=0.363, help="Offset threshold for VAD (see pyannote.audio), reduce this if speech is not being detected.") parser.add_argument("--chunk_size", type=int, default=30, help="Chunk size for merging VAD segments. Default is 30, reduce this if the chunk is too long.") # diarization params parser.add_argument("--diarize", action="store_true", help="Apply diarization to assign speaker labels to each segment/word") parser.add_argument("--min_speakers", default=None, type=int, help="Minimum number of speakers to in audio file") parser.add_argument("--max_speakers", default=None, type=int, help="Maximum number of speakers to in audio file") parser.add_argument("--temperature", type=float, default=0, help="temperature to use for sampling") parser.add_argument("--best_of", type=optional_int, default=5, help="number of candidates when sampling with non-zero temperature") parser.add_argument("--beam_size", type=optional_int, default=5, help="number of beams in beam search, only applicable when temperature is zero") parser.add_argument("--patience", type=float, default=1.0, help="optional patience value to use in beam decoding, as in https://arxiv.org/abs/2204.05424, the default (1.0) is equivalent to conventional beam search") parser.add_argument("--length_penalty", type=float, default=1.0, help="optional token length penalty coefficient (alpha) as in https://arxiv.org/abs/1609.08144, uses simple length normalization by default") parser.add_argument("--suppress_tokens", type=str, default="-1", help="comma-separated list of token ids to suppress during sampling; '-1' will suppress most special characters except common punctuations") parser.add_argument("--suppress_numerals", action="store_true", help="whether to suppress numeric symbols and currency symbols during sampling, since wav2vec2 cannot align them correctly") parser.add_argument("--initial_prompt", type=str, default=None, help="optional text to provide as a prompt for the first window.") parser.add_argument("--condition_on_previous_text", type=str2bool, default=False, help="if True, provide the previous output of the model as a prompt for the next window; disabling may make the text inconsistent across windows, but the model becomes less prone to getting stuck in a failure loop") parser.add_argument("--fp16", type=str2bool, default=True, help="whether to perform inference in fp16; True by default") parser.add_argument("--temperature_increment_on_fallback", type=optional_float, default=0.2, help="temperature to increase when falling back when the decoding fails to meet either of the thresholds below") parser.add_argument("--compression_ratio_threshold", type=optional_float, default=2.4, help="if the gzip compression ratio is higher than this value, treat the decoding as failed") parser.add_argument("--logprob_threshold", type=optional_float, default=-1.0, help="if the average log probability is lower than this value, treat the decoding as failed") parser.add_argument("--no_speech_threshold", type=optional_float, default=0.6, help="if the probability of the <|nospeech|> token is higher than this value AND the decoding has failed due to `logprob_threshold`, consider the segment as silence") parser.add_argument("--max_line_width", type=optional_int, default=None, help="(not possible with --no_align) the maximum number of characters in a line before breaking the line") parser.add_argument("--max_line_count", type=optional_int, default=None, help="(not possible with --no_align) the maximum number of lines in a segment") parser.add_argument("--highlight_words", type=str2bool, default=False, help="(not possible with --no_align) underline each word as it is spoken in srt and vtt") parser.add_argument("--segment_resolution", type=str, default="sentence", choices=["sentence", "chunk"], help="(not possible with --no_align) the maximum number of characters in a line before breaking the line") parser.add_argument("--threads", type=optional_int, default=0, help="number of threads used by torch for CPU inference; supercedes MKL_NUM_THREADS/OMP_NUM_THREADS") parser.add_argument("--hf_token", type=str, default=None, help="Hugging Face Access Token to access PyAnnote gated models") parser.add_argument("--print_progress", type=str2bool, default = False, help = "if True, progress will be printed in transcribe() and align() methods.") # fmt: on args = parser.parse_args().__dict__ model_name: str = args.pop("model") batch_size: int = args.pop("batch_size") output_dir: str = args.pop("output_dir") output_format: str = args.pop("output_format") device: str = args.pop("device") device_index: int = args.pop("device_index") compute_type: str = args.pop("compute_type") # model_flush: bool = args.pop("model_flush") os.makedirs(output_dir, exist_ok=True) align_model: str = args.pop("align_model") interpolate_method: str = args.pop("interpolate_method") no_align: bool = args.pop("no_align") task : str = args.pop("task") if task == "translate": # translation cannot be aligned no_align = True return_char_alignments: bool = args.pop("return_char_alignments") hf_token: str = args.pop("hf_token") vad_onset: float = args.pop("vad_onset") vad_offset: float = args.pop("vad_offset") chunk_size: int = args.pop("chunk_size") diarize: bool = args.pop("diarize") min_speakers: int = args.pop("min_speakers") max_speakers: int = args.pop("max_speakers") print_progress: bool = args.pop("print_progress") if args["language"] is not None: args["language"] = args["language"].lower() if args["language"] not in LANGUAGES: if args["language"] in TO_LANGUAGE_CODE: args["language"] = TO_LANGUAGE_CODE[args["language"]] else: raise ValueError(f"Unsupported language: {args['language']}") if model_name.endswith(".en") and args["language"] != "en": if args["language"] is not None: warnings.warn( f"{model_name} is an English-only model but receipted '{args['language']}'; using English instead." ) args["language"] = "en" align_language = args["language"] if args["language"] is not None else "en" # default to loading english if not specified temperature = args.pop("temperature") if (increment := args.pop("temperature_increment_on_fallback")) is not None: temperature = tuple(np.arange(temperature, 1.0 + 1e-6, increment)) else: temperature = [temperature] faster_whisper_threads = 4 if (threads := args.pop("threads")) > 0: torch.set_num_threads(threads) faster_whisper_threads = threads asr_options = { "beam_size": args.pop("beam_size"), "patience": args.pop("patience"), "length_penalty": args.pop("length_penalty"), "temperatures": temperature, "compression_ratio_threshold": args.pop("compression_ratio_threshold"), "log_prob_threshold": args.pop("logprob_threshold"), "no_speech_threshold": args.pop("no_speech_threshold"), "condition_on_previous_text": False, "initial_prompt": args.pop("initial_prompt"), "suppress_tokens": [int(x) for x in args.pop("suppress_tokens").split(",")], "suppress_numerals": args.pop("suppress_numerals"), } writer = get_writer(output_format, output_dir) word_options = ["highlight_words", "max_line_count", "max_line_width"] if no_align: for option in word_options: if args[option]: parser.error(f"--{option} not possible with --no_align") if args["max_line_count"] and not args["max_line_width"]: warnings.warn("--max_line_count has no effect without --max_line_width") writer_args = {arg: args.pop(arg) for arg in word_options} # Part 1: VAD & ASR Loop results = [] tmp_results = [] # model = load_model(model_name, device=device, download_root=model_dir)
model = load_model(model_name, device=device, device_index=device_index, compute_type=compute_type, language=args['language'], asr_options=asr_options, vad_options={"vad_onset": vad_onset, "vad_offset": vad_offset}, task=task, threads=faster_whisper_threads)
2
2023-12-01 12:23:19+00:00
12k
JiahuiLei/GART
test_utils/test_func.py
[ { "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 or...
import sys, os, os.path as osp import torch import numpy as np import cv2, glob import pandas as pd import imageio import logging from eval_utils_instant_avatar import Evaluator as EvalAvatar from eval_utils_instant_nvr import Evaluator as EvalNVR from eval_utils_instant_avatar_brightness import Evaluator as EvalAvatarBrightness from typing import Union from lib_render.gauspl_renderer import render_cam_pcl from tqdm import tqdm from lib_data.instant_avatar_people_snapshot import Dataset as InstantAvatarDataset from lib_data.zju_mocap import Dataset as ZJUDataset, get_batch_sampler from lib_data.instant_avatar_wild import Dataset as InstantAvatarWildDataset from lib_data.dog_demo import Dataset as DogDemoDataset from matplotlib import pyplot as plt
10,517
tto_decay_factor=0.5, tto_evaluator=None, pose_base_lr=3e-3, pose_rest_lr=3e-3, trans_lr=3e-3, device=torch.device("cuda:0"), ): model.eval() if tto_flag: test_save_dir_tto = osp.join(log_dir, f"{save_name}_tto") os.makedirs(test_save_dir_tto, exist_ok=True) else: test_save_dir = osp.join(log_dir, save_name) os.makedirs(test_save_dir, exist_ok=True) if dataset_mode == "zju": # ! follow instant-nvr evaluation iter_test_dataset = torch.utils.data.DataLoader( test_dataset, batch_sampler=get_batch_sampler(test_dataset, frame_sampler_interval=6), num_workers=0, ) else: iter_test_dataset = test_dataset logging.info( f"Saving images [TTO={tto_flag}] [N={len(iter_test_dataset)}]..." ) for batch_idx, batch in tqdm(enumerate(iter_test_dataset)): # get data data, meta = batch if dataset_mode == "zju": for k in data.keys(): data[k] = data[k].squeeze(0) rgb_gt = torch.as_tensor(data["rgb"])[None].float().to(device) mask_gt = torch.as_tensor(data["mask"])[None].float().to(device) H, W = rgb_gt.shape[1:3] K = torch.as_tensor(data["K"]).float().to(device) pose = torch.as_tensor(data["smpl_pose"]).float().to(device)[None] trans = torch.as_tensor(data["smpl_trans"]).float().to(device)[None] if dataset_mode == "zju": fn = f"frame{int(meta['frame_idx']):04d}_view{int(meta['cam_ind']):04d}.png" else: fn = f"{batch_idx}.png" if tto_flag: # change the pose from the dataset to fit the test view pose_b, pose_r = pose[:, :1], pose[:, 1:] model.eval() # * for delta list try: list_flag = model.add_bones.mode in ["delta-list"] except: list_flag = False if list_flag: As = model.add_bones(t=batch_idx) # B,K,4,4, the nearest pose else: As = None # place holder new_pose_b, new_pose_r, new_trans, As = solver.testtime_pose_optimization( data_pack=[ rgb_gt, mask_gt, K[None], pose_b, pose_r, trans, None, ], model=model, evaluator=tto_evaluator, pose_base_lr=pose_base_lr, pose_rest_lr=pose_rest_lr, trans_lr=trans_lr, steps=tto_step, decay_steps=tto_decay, decay_factor=tto_decay_factor, As=As, ) pose = torch.cat([new_pose_b, new_pose_r], dim=1).detach() trans = new_trans.detach() save_fn = osp.join(test_save_dir_tto, fn) _save_render_image_from_pose( model, pose, trans, H, W, K, bg, rgb_gt, save_fn, time_index=batch_idx, As=As, ) else: save_fn = osp.join(test_save_dir, fn) _save_render_image_from_pose( model, pose, trans, H, W, K, bg, rgb_gt, save_fn, time_index=batch_idx ) return @torch.no_grad() def _save_render_image_from_pose( model, pose, trans, H, W, K, bg, rgb_gt, save_fn, time_index=None, As=None ): act_sph_order = model.max_sph_order device = pose.device # TODO: handle novel time!, not does not pass in means t=None; Can always use TTO to directly find As! additional_dict = {"t": time_index} if As is not None: additional_dict["As"] = As mu, fr, sc, op, sph, _ = model( pose, trans, additional_dict=additional_dict, active_sph_order=act_sph_order ) # TODO: directly input optimized As!
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) sys.path.append(osp.dirname(osp.abspath(__file__))) def get_evaluator(mode, device): if mode == "avatar": evaluator = EvalAvatar() elif mode == "nvr": evaluator = EvalNVR() elif mode == "avatar_brightness": evaluator = EvalAvatarBrightness() else: raise NotImplementedError() evaluator = evaluator.to(device) evaluator.eval() return evaluator class TrainingSeqWrapper: def __init__(self, seq) -> None: self.seq = seq def __len__(self): return self.seq.total_t def __getitem__(self, idx): data = {} data["rgb"] = self.seq.rgb_list[idx] data["mask"] = self.seq.mask_list[idx] data["K"] = self.seq.K_list[idx] data["smpl_pose"] = torch.cat( [self.seq.pose_base_list[idx], self.seq.pose_rest_list[idx]], dim=0 ) data["smpl_trans"] = self.seq.global_trans_list[idx] return data, {} def test( solver, seq_name: str, tto_flag=True, tto_step=300, tto_decay=60, tto_decay_factor=0.5, pose_base_lr=3e-3, pose_rest_lr=3e-3, trans_lr=3e-3, dataset_mode="people_snapshot", training_optimized_seq=None, ): device = solver.device model = solver.load_saved_model() assert dataset_mode in [ "people_snapshot", "zju", "instant_avatar_wild", "dog_demo", ], f"Unknown dataset mode {dataset_mode}" if dataset_mode == "people_snapshot": eval_mode = "avatar" bg = [1.0, 1.0, 1.0] test_dataset = InstantAvatarDataset( noisy_flag=False, data_root="./data/people_snapshot/", video_name=seq_name, split="test", image_zoom_ratio=0.5, ) elif dataset_mode == "zju": eval_mode = "nvr" test_dataset = ZJUDataset( data_root="./data/zju_mocap", video_name=seq_name, split="test", image_zoom_ratio=0.5, ) bg = [0.0, 0.0, 0.0] # zju use black background elif dataset_mode == "instant_avatar_wild": eval_mode = "avatar" test_dataset = InstantAvatarWildDataset( data_root="./data/insav_wild", video_name=seq_name, split="test", image_zoom_ratio=1.0, # ! warning, here follow the `ubc_hard.yaml` in InstAVT setting, use slicing start_end_skip=[2, 1000000000, 4], ) bg = [1.0, 1.0, 1.0] test_len = len(test_dataset) assert (training_optimized_seq.total_t == test_len) or ( training_optimized_seq.total_t == 1 + test_len ), "Now UBC can only support the same length of training and testing or + 1" test_dataset.smpl_params["body_pose"] = ( training_optimized_seq.pose_rest_list.reshape(-1, 69)[:test_len] .detach() .cpu() .numpy() ) test_dataset.smpl_params["global_orient"] = ( training_optimized_seq.pose_base_list.reshape(-1, 3)[:test_len] .detach() .cpu() .numpy() ) test_dataset.smpl_params["transl"] = ( training_optimized_seq.global_trans_list.reshape(-1, 3)[:test_len] .detach() .cpu() .numpy() ) elif dataset_mode == "dog_demo": eval_mode = "avatar_brightness" bg = [1.0, 1.0, 1.0] test_dataset = DogDemoDataset( data_root="./data/dog_data_official/", video_name=seq_name, test=True ) else: raise NotImplementedError() evaluator = get_evaluator(eval_mode, device) _save_eval_maps( solver.log_dir, "test", model, solver, test_dataset, dataset_mode=dataset_mode, device=device, bg=bg, tto_flag=tto_flag, tto_step=tto_step, tto_decay=tto_decay, tto_decay_factor=tto_decay_factor, tto_evaluator=evaluator, pose_base_lr=pose_base_lr, pose_rest_lr=pose_rest_lr, trans_lr=trans_lr, ) if tto_flag: _evaluate_dir(evaluator, solver.log_dir, "test_tto") else: _evaluate_dir(evaluator, solver.log_dir, "test") return def _save_eval_maps( log_dir, save_name, model, solver, test_dataset, dataset_mode="people_snapshot", bg=[1.0, 1.0, 1.0], # tto tto_flag=False, tto_step=300, tto_decay=60, tto_decay_factor=0.5, tto_evaluator=None, pose_base_lr=3e-3, pose_rest_lr=3e-3, trans_lr=3e-3, device=torch.device("cuda:0"), ): model.eval() if tto_flag: test_save_dir_tto = osp.join(log_dir, f"{save_name}_tto") os.makedirs(test_save_dir_tto, exist_ok=True) else: test_save_dir = osp.join(log_dir, save_name) os.makedirs(test_save_dir, exist_ok=True) if dataset_mode == "zju": # ! follow instant-nvr evaluation iter_test_dataset = torch.utils.data.DataLoader( test_dataset, batch_sampler=get_batch_sampler(test_dataset, frame_sampler_interval=6), num_workers=0, ) else: iter_test_dataset = test_dataset logging.info( f"Saving images [TTO={tto_flag}] [N={len(iter_test_dataset)}]..." ) for batch_idx, batch in tqdm(enumerate(iter_test_dataset)): # get data data, meta = batch if dataset_mode == "zju": for k in data.keys(): data[k] = data[k].squeeze(0) rgb_gt = torch.as_tensor(data["rgb"])[None].float().to(device) mask_gt = torch.as_tensor(data["mask"])[None].float().to(device) H, W = rgb_gt.shape[1:3] K = torch.as_tensor(data["K"]).float().to(device) pose = torch.as_tensor(data["smpl_pose"]).float().to(device)[None] trans = torch.as_tensor(data["smpl_trans"]).float().to(device)[None] if dataset_mode == "zju": fn = f"frame{int(meta['frame_idx']):04d}_view{int(meta['cam_ind']):04d}.png" else: fn = f"{batch_idx}.png" if tto_flag: # change the pose from the dataset to fit the test view pose_b, pose_r = pose[:, :1], pose[:, 1:] model.eval() # * for delta list try: list_flag = model.add_bones.mode in ["delta-list"] except: list_flag = False if list_flag: As = model.add_bones(t=batch_idx) # B,K,4,4, the nearest pose else: As = None # place holder new_pose_b, new_pose_r, new_trans, As = solver.testtime_pose_optimization( data_pack=[ rgb_gt, mask_gt, K[None], pose_b, pose_r, trans, None, ], model=model, evaluator=tto_evaluator, pose_base_lr=pose_base_lr, pose_rest_lr=pose_rest_lr, trans_lr=trans_lr, steps=tto_step, decay_steps=tto_decay, decay_factor=tto_decay_factor, As=As, ) pose = torch.cat([new_pose_b, new_pose_r], dim=1).detach() trans = new_trans.detach() save_fn = osp.join(test_save_dir_tto, fn) _save_render_image_from_pose( model, pose, trans, H, W, K, bg, rgb_gt, save_fn, time_index=batch_idx, As=As, ) else: save_fn = osp.join(test_save_dir, fn) _save_render_image_from_pose( model, pose, trans, H, W, K, bg, rgb_gt, save_fn, time_index=batch_idx ) return @torch.no_grad() def _save_render_image_from_pose( model, pose, trans, H, W, K, bg, rgb_gt, save_fn, time_index=None, As=None ): act_sph_order = model.max_sph_order device = pose.device # TODO: handle novel time!, not does not pass in means t=None; Can always use TTO to directly find As! additional_dict = {"t": time_index} if As is not None: additional_dict["As"] = As mu, fr, sc, op, sph, _ = model( pose, trans, additional_dict=additional_dict, active_sph_order=act_sph_order ) # TODO: directly input optimized As!
render_pkg = render_cam_pcl(
0
2023-11-27 17:30:04+00:00
12k
GongyeLiu/StyleCrafter
scripts/evaluation/style_inference.py
[ { "identifier": "DDIMSampler", "path": "lvdm/models/samplers/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.schedu...
import argparse, os, sys, glob import datetime, time import numpy as np import torch import torchvision import json from omegaconf import OmegaConf from tqdm import tqdm from einops import rearrange, repeat from collections import OrderedDict from torch.utils.data import DataLoader from pytorch_lightning import seed_everything from decord import VideoReader, cpu from PIL import Image from torchvision.transforms import transforms from torchvision.utils import make_grid from lvdm.models.samplers.ddim import DDIMSampler, DDIMStyleSampler from utils.utils import instantiate_from_config from utils.save_video import tensor_to_mp4
7,613
if isinstance(style_path, list) and not DISABLE_MULTI_REF: style_imgs = [] for path in style_path: style_img = Image.open(os.path.join(data_dir, path)).convert('RGB') style_img_tensor = style_transforms(style_img) style_imgs.append(style_img_tensor) style_img_tensor = torch.stack(style_imgs, dim=0) elif isinstance(style_path, list) and DISABLE_MULTI_REF: rand_idx = np.random.randint(0, len(style_path)) style_img = Image.open(os.path.join(data_dir, style_path[rand_idx])).convert('RGB') style_img_tensor = style_transforms(style_img) print(f"Warning: multiple style images exist. The one {style_path[rand_idx]} is used.") else: style_img = Image.open(os.path.join(data_dir, style_path)).convert('RGB') style_img_tensor = style_transforms(style_img) else: raise ValueError("Error: style image path is None!") data_list.append({ 'prompt': prompt, 'style': style_img_tensor }) return data_list def save_results(prompt, samples, filename, sample_dir, prompt_dir, fps=10, out_type='video'): ## save prompt prompt = prompt[0] if isinstance(prompt, list) else prompt path = os.path.join(prompt_dir, "%s.txt"%filename) with open(path, 'w') as f: f.write(f'{prompt}') f.close() ## save video if out_type == 'image': n = samples.shape[0] output = make_grid(samples, nrow=n, normalize=True, range=(-1, 1)) output_img = Image.fromarray(output.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy()) output_img.save(os.path.join(sample_dir, "%s.jpg"%filename)) elif out_type == 'video': ## save video # b,c,t,h,w video = samples.detach().cpu() video = torch.clamp(video.float(), -1., 1.) n = video.shape[0] video = video.permute(2, 0, 1, 3, 4) # t,n,c,h,w frame_grids = [torchvision.utils.make_grid(framesheet, nrow=int(n)) for framesheet in video] #[3, 1*h, n*w] grid = torch.stack(frame_grids, dim=0) # stack in temporal dim [t, 3, n*h, w] grid = (grid + 1.0) / 2.0 grid = (grid * 255).to(torch.uint8).permute(0, 2, 3, 1) path = os.path.join(sample_dir, "%s.mp4"%filename) torchvision.io.write_video(path, grid, fps=fps, video_codec='h264', options={'crf': '10'}) else: raise ValueError("Error: output type should be image or video!") def style_guided_synthesis(model, prompts, style, noise_shape, n_samples=1, ddim_steps=50, ddim_eta=1., \ unconditional_guidance_scale=1.0, unconditional_guidance_scale_style=None, **kwargs): ddim_sampler = DDIMSampler(model) if unconditional_guidance_scale_style is None else DDIMStyleSampler(model) batch_size = noise_shape[0] ## get condition embeddings (support single prompt only) if isinstance(prompts, str): prompts = [prompts] cond = model.get_learned_conditioning(prompts) # cond = repeat(cond, 'b n c -> (b f) n c', f=16) if unconditional_guidance_scale != 1.0: prompts = batch_size * [""] uc = model.get_learned_conditioning(prompts) # uc = repeat(uc, 'b n c -> (b f) n c', f=16) else: uc = None if len(style.shape) == 4: style_cond = model.get_batch_style(style) append_to_context = model.adapter(style_cond) else: bs, n, c, h, w = style.shape style = rearrange(style, "b n c h w -> (b n) c h w") style_cond = model.get_batch_style(style) style_cond = rearrange(style_cond, "(b n) l c -> b (n l ) c", b=bs) append_to_context = model.adapter(style_cond) # append_to_context = repeat(append_to_context, 'b n c -> (b f) n c', f=16) if hasattr(model.adapter, "scale_predictor"): scale_scalar = model.adapter.scale_predictor(torch.concat([append_to_context, cond], dim=1)) else: scale_scalar = None batch_variants = [] for _ in range(n_samples): if ddim_sampler is not None: samples, _ = ddim_sampler.sample(S=ddim_steps, conditioning=cond, batch_size=noise_shape[0], shape=noise_shape[1:], verbose=False, unconditional_guidance_scale=unconditional_guidance_scale, unconditional_guidance_scale_style=unconditional_guidance_scale_style, unconditional_conditioning=uc, eta=ddim_eta, temporal_length=noise_shape[2], append_to_context=append_to_context, scale_scalar=scale_scalar, **kwargs ) ## reconstruct from latent to pixel space batch_images = model.decode_first_stage(samples) batch_variants.append(batch_images) ## variants, batch, c, t, h, w batch_variants = torch.stack(batch_variants) return batch_variants.permute(1, 0, 2, 3, 4, 5) def run_inference(args, gpu_num, gpu_no): ## model config config = OmegaConf.load(args.base) model_config = config.pop("model", OmegaConf.create()) model_config['params']['adapter_config']['params']['scale'] = args.style_weight print(f"Set adapter scale to {args.style_weight:.2f}")
## note: decord should be imported after torch sys.path.insert(1, os.path.join(sys.path[0], '..', '..')) def save_img(img, path, is_tensor=True): if is_tensor: img = img.permute(1, 2, 0).cpu().numpy() img = (img * 127.5 + 127.5).clip(0, 255).astype(np.uint8) img = Image.fromarray(img) img.save(path) def get_filelist(data_dir, ext='*'): file_list = glob.glob(os.path.join(data_dir, '*.%s'%ext)) file_list.sort() return file_list def load_model_checkpoint(model, ckpt): state_dict = torch.load(ckpt, map_location="cpu") if "state_dict" in list(state_dict.keys()): state_dict = state_dict["state_dict"] else: # deepspeed state_dict = OrderedDict() for key in state_dict['module'].keys(): state_dict[key[16:]]=state_dict['module'][key] model.load_state_dict(state_dict, strict=False) print('>>> model checkpoint loaded.') return model def load_data_from_json(data_dir, filename=None, DISABLE_MULTI_REF=False): # load data from json file if filename is not None: json_file = os.path.join(data_dir, filename) with open(json_file, 'r') as f: data = json.load(f) else: json_file = get_filelist(data_dir, 'json') assert len(json_file) > 0, "Error: found NO prompt file!" default_idx = 0 default_idx = min(default_idx, len(json_file)-1) if len(json_file) > 1: print(f"Warning: multiple prompt files exist. The one {os.path.split(json_file[default_idx])[1]} is used.") ## only use the first one (sorted by name) if multiple exist with open(json_file[default_idx], 'r') as f: data = json.load(f) n_samples = len(data) data_list = [] style_transforms = torchvision.transforms.Compose([ torchvision.transforms.Resize(512), torchvision.transforms.CenterCrop(512), torchvision.transforms.ToTensor(), torchvision.transforms.Lambda(lambda x: x * 2. - 1.), ]) for idx in range(n_samples): prompt = data[idx]['prompt'] # load style image if data[idx]['style_path'] is not None: style_path = data[idx]['style_path'] if isinstance(style_path, list) and not DISABLE_MULTI_REF: style_imgs = [] for path in style_path: style_img = Image.open(os.path.join(data_dir, path)).convert('RGB') style_img_tensor = style_transforms(style_img) style_imgs.append(style_img_tensor) style_img_tensor = torch.stack(style_imgs, dim=0) elif isinstance(style_path, list) and DISABLE_MULTI_REF: rand_idx = np.random.randint(0, len(style_path)) style_img = Image.open(os.path.join(data_dir, style_path[rand_idx])).convert('RGB') style_img_tensor = style_transforms(style_img) print(f"Warning: multiple style images exist. The one {style_path[rand_idx]} is used.") else: style_img = Image.open(os.path.join(data_dir, style_path)).convert('RGB') style_img_tensor = style_transforms(style_img) else: raise ValueError("Error: style image path is None!") data_list.append({ 'prompt': prompt, 'style': style_img_tensor }) return data_list def save_results(prompt, samples, filename, sample_dir, prompt_dir, fps=10, out_type='video'): ## save prompt prompt = prompt[0] if isinstance(prompt, list) else prompt path = os.path.join(prompt_dir, "%s.txt"%filename) with open(path, 'w') as f: f.write(f'{prompt}') f.close() ## save video if out_type == 'image': n = samples.shape[0] output = make_grid(samples, nrow=n, normalize=True, range=(-1, 1)) output_img = Image.fromarray(output.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy()) output_img.save(os.path.join(sample_dir, "%s.jpg"%filename)) elif out_type == 'video': ## save video # b,c,t,h,w video = samples.detach().cpu() video = torch.clamp(video.float(), -1., 1.) n = video.shape[0] video = video.permute(2, 0, 1, 3, 4) # t,n,c,h,w frame_grids = [torchvision.utils.make_grid(framesheet, nrow=int(n)) for framesheet in video] #[3, 1*h, n*w] grid = torch.stack(frame_grids, dim=0) # stack in temporal dim [t, 3, n*h, w] grid = (grid + 1.0) / 2.0 grid = (grid * 255).to(torch.uint8).permute(0, 2, 3, 1) path = os.path.join(sample_dir, "%s.mp4"%filename) torchvision.io.write_video(path, grid, fps=fps, video_codec='h264', options={'crf': '10'}) else: raise ValueError("Error: output type should be image or video!") def style_guided_synthesis(model, prompts, style, noise_shape, n_samples=1, ddim_steps=50, ddim_eta=1., \ unconditional_guidance_scale=1.0, unconditional_guidance_scale_style=None, **kwargs): ddim_sampler = DDIMSampler(model) if unconditional_guidance_scale_style is None else DDIMStyleSampler(model) batch_size = noise_shape[0] ## get condition embeddings (support single prompt only) if isinstance(prompts, str): prompts = [prompts] cond = model.get_learned_conditioning(prompts) # cond = repeat(cond, 'b n c -> (b f) n c', f=16) if unconditional_guidance_scale != 1.0: prompts = batch_size * [""] uc = model.get_learned_conditioning(prompts) # uc = repeat(uc, 'b n c -> (b f) n c', f=16) else: uc = None if len(style.shape) == 4: style_cond = model.get_batch_style(style) append_to_context = model.adapter(style_cond) else: bs, n, c, h, w = style.shape style = rearrange(style, "b n c h w -> (b n) c h w") style_cond = model.get_batch_style(style) style_cond = rearrange(style_cond, "(b n) l c -> b (n l ) c", b=bs) append_to_context = model.adapter(style_cond) # append_to_context = repeat(append_to_context, 'b n c -> (b f) n c', f=16) if hasattr(model.adapter, "scale_predictor"): scale_scalar = model.adapter.scale_predictor(torch.concat([append_to_context, cond], dim=1)) else: scale_scalar = None batch_variants = [] for _ in range(n_samples): if ddim_sampler is not None: samples, _ = ddim_sampler.sample(S=ddim_steps, conditioning=cond, batch_size=noise_shape[0], shape=noise_shape[1:], verbose=False, unconditional_guidance_scale=unconditional_guidance_scale, unconditional_guidance_scale_style=unconditional_guidance_scale_style, unconditional_conditioning=uc, eta=ddim_eta, temporal_length=noise_shape[2], append_to_context=append_to_context, scale_scalar=scale_scalar, **kwargs ) ## reconstruct from latent to pixel space batch_images = model.decode_first_stage(samples) batch_variants.append(batch_images) ## variants, batch, c, t, h, w batch_variants = torch.stack(batch_variants) return batch_variants.permute(1, 0, 2, 3, 4, 5) def run_inference(args, gpu_num, gpu_no): ## model config config = OmegaConf.load(args.base) model_config = config.pop("model", OmegaConf.create()) model_config['params']['adapter_config']['params']['scale'] = args.style_weight print(f"Set adapter scale to {args.style_weight:.2f}")
model = instantiate_from_config(model_config)
2
2023-11-30 15:01:49+00:00
12k
emdgroup/baybe
tests/test_iterations.py
[ { "identifier": "NonPredictiveRecommender", "path": "baybe/recommenders/base.py", "snippet": "class NonPredictiveRecommender(Recommender, ABC):\n \"\"\"Abstract base class for recommenders that are non-predictive.\"\"\"\n\n def recommend( # noqa: D102\n self,\n searchspace: SearchSp...
from typing import get_args, get_type_hints from baybe.recommenders.base import NonPredictiveRecommender, Recommender from baybe.recommenders.bayesian import ( BayesianRecommender, NaiveHybridRecommender, SequentialGreedyRecommender, ) from baybe.searchspace import SearchSpaceType from baybe.strategies.base import Strategy from baybe.surrogates import get_available_surrogates from baybe.utils.basic import get_subclasses from .conftest import run_iterations import pytest
8,272
# TODO: This file needs to be refactored. """Tests various configurations for a small number of iterations.""" ######################################################################################## # Settings of the individual components to be tested ######################################################################################## valid_acquisition_functions = get_args( get_type_hints(BayesianRecommender.__init__)["acquisition_function_cls"] ) valid_surrogate_models = [cls() for cls in get_available_surrogates()]
# TODO: This file needs to be refactored. """Tests various configurations for a small number of iterations.""" ######################################################################################## # Settings of the individual components to be tested ######################################################################################## valid_acquisition_functions = get_args( get_type_hints(BayesianRecommender.__init__)["acquisition_function_cls"] ) valid_surrogate_models = [cls() for cls in get_available_surrogates()]
valid_initial_recommenders = [cls() for cls in get_subclasses(NonPredictiveRecommender)]
0
2023-11-27 17:02:40+00:00
12k
UX-Decoder/LLaVA-Grounding
llava/model/language_model/mpt/modeling_mpt.py
[ { "identifier": "attn_bias_shape", "path": "llava/model/language_model/mpt/attention.py", "snippet": "def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id):\n if attn_impl == 'flash':\n return None\n elif attn_impl in ['torch', 'triton']:\n if al...
import math import warnings import torch import torch.nn as nn import torch.nn.functional as F from typing import List, Optional, Tuple, Union from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast from .attention import attn_bias_shape, build_attn_bias from .blocks import MPTBlock from .custom_embedding import SharedEmbedding from .norm import NORM_CLASS_REGISTRY from .configuration_mpt import MPTConfig from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm from .meta_init_context import init_empty_weights from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_ from .flash_attn_triton import flash_attn_func
7,343
"""A simple, flexible implementation of a GPT model. Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py """ try: except: pass Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast] class MPTPreTrainedModel(PreTrainedModel): config_class = MPTConfig base_model_prefix = 'model' _no_split_modules = ['MPTBlock'] class MPTModel(MPTPreTrainedModel): def __init__(self, config: MPTConfig): config._validate_config() super().__init__(config) self.attn_impl = config.attn_config['attn_impl'] self.prefix_lm = config.attn_config['prefix_lm'] self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id'] self.alibi = config.attn_config['alibi'] self.alibi_bias_max = config.attn_config['alibi_bias_max'] if config.init_device == 'mixed': if dist.get_local_rank() == 0: config.init_device = 'cpu' else: config.init_device = 'meta' if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys(): norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys()) raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).') norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()] self.embedding_fraction = config.embedding_fraction self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device) if not self.alibi: self.wpe = torch.nn.Embedding(config.max_seq_len, config.d_model, device=config.init_device) self.emb_drop = nn.Dropout(config.emb_pdrop) self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)]) self.norm_f = norm_class(config.d_model, device=config.init_device) if config.init_device != 'meta': print(f'You are using config.init_device={config.init_device!r}, but you can also use config.init_device="meta" with Composer + FSDP for fast initialization.') self.apply(self.param_init_fn) self.is_causal = not self.prefix_lm self._attn_bias_initialized = False self.attn_bias = None self.attn_bias_shape = attn_bias_shape(self.attn_impl, config.n_heads, config.max_seq_len, self.alibi, prefix_lm=self.prefix_lm, causal=self.is_causal, use_sequence_id=self.attn_uses_sequence_id) if config.no_bias: for module in self.modules(): if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter): if config.verbose: warnings.warn(f'Removing bias ({module.bias}) from {module}.') module.register_parameter('bias', None) if config.verbose and config.verbose > 2: print(self) if 'verbose' not in self.config.init_config: self.config.init_config['verbose'] = self.config.verbose if self.config.init_config['verbose'] > 1: init_fn_name = self.config.init_config['name'] warnings.warn(f'Using {init_fn_name} initialization.') self.gradient_checkpointing = False def get_input_embeddings(self): return self.wte def set_input_embeddings(self, value): self.wte = value @torch.no_grad() def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None): if not self._attn_bias_initialized: if self.attn_bias_shape: self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype)
"""A simple, flexible implementation of a GPT model. Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py """ try: except: pass Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast] class MPTPreTrainedModel(PreTrainedModel): config_class = MPTConfig base_model_prefix = 'model' _no_split_modules = ['MPTBlock'] class MPTModel(MPTPreTrainedModel): def __init__(self, config: MPTConfig): config._validate_config() super().__init__(config) self.attn_impl = config.attn_config['attn_impl'] self.prefix_lm = config.attn_config['prefix_lm'] self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id'] self.alibi = config.attn_config['alibi'] self.alibi_bias_max = config.attn_config['alibi_bias_max'] if config.init_device == 'mixed': if dist.get_local_rank() == 0: config.init_device = 'cpu' else: config.init_device = 'meta' if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys(): norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys()) raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).') norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()] self.embedding_fraction = config.embedding_fraction self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device) if not self.alibi: self.wpe = torch.nn.Embedding(config.max_seq_len, config.d_model, device=config.init_device) self.emb_drop = nn.Dropout(config.emb_pdrop) self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)]) self.norm_f = norm_class(config.d_model, device=config.init_device) if config.init_device != 'meta': print(f'You are using config.init_device={config.init_device!r}, but you can also use config.init_device="meta" with Composer + FSDP for fast initialization.') self.apply(self.param_init_fn) self.is_causal = not self.prefix_lm self._attn_bias_initialized = False self.attn_bias = None self.attn_bias_shape = attn_bias_shape(self.attn_impl, config.n_heads, config.max_seq_len, self.alibi, prefix_lm=self.prefix_lm, causal=self.is_causal, use_sequence_id=self.attn_uses_sequence_id) if config.no_bias: for module in self.modules(): if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter): if config.verbose: warnings.warn(f'Removing bias ({module.bias}) from {module}.') module.register_parameter('bias', None) if config.verbose and config.verbose > 2: print(self) if 'verbose' not in self.config.init_config: self.config.init_config['verbose'] = self.config.verbose if self.config.init_config['verbose'] > 1: init_fn_name = self.config.init_config['name'] warnings.warn(f'Using {init_fn_name} initialization.') self.gradient_checkpointing = False def get_input_embeddings(self): return self.wte def set_input_embeddings(self, value): self.wte = value @torch.no_grad() def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None): if not self._attn_bias_initialized: if self.attn_bias_shape: self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype)
self.attn_bias = build_attn_bias(self.attn_impl, self.attn_bias, self.config.n_heads, self.config.max_seq_len, causal=self.is_causal, alibi=self.alibi, alibi_bias_max=self.alibi_bias_max)
1
2023-12-04 10:59:21+00:00
12k
daveredrum/SceneTex
models/modules/studio.py
[ { "identifier": "init_trajectory", "path": "lib/camera_helper.py", "snippet": "def init_trajectory(dist_list, elev_list, azim_list, at):\n Rs, Ts = [], []\n for dist, elev, azim in zip(dist_list, elev_list, azim_list):\n R, T = look_at_view_transform(dist, elev, azim, at=at)\n\n Rs.a...
import os import json import random import torch import torch.nn as nn import torch.nn.functional as F import pytorch_lightning as pl import torchvision import numpy as np import sys from omegaconf import OmegaConf from pytorch3d.ops import interpolate_face_attributes from pytorch3d.renderer import look_at_view_transform from lib.camera_helper import init_trajectory, init_blenderproc_trajectory, init_camera_R_T from lib.render_helper import init_renderer from lib.shading_helper import init_flat_texel_shader from lib.projection_helper import get_visible_pixel_uvs, get_all_4_locations from models.modules.modules import MLP, Siren, HashGrid, HashGridMLP from models.modules.anchors import AnchorTransformer
7,320
# spherical cameras self.sphere_cameras = OmegaConf.load(self.config.sphere_cameras) dist_linspace = np.linspace( self.sphere_cameras.dist.min, self.sphere_cameras.dist.max, 1 if self.sphere_cameras.dist.min == self.sphere_cameras.dist.max else self.sphere_cameras.dist.num_linspace, ) elev_linspace = np.linspace( self.sphere_cameras.elev.min, self.sphere_cameras.elev.max, 1 if self.sphere_cameras.elev.min == self.sphere_cameras.elev.max else self.sphere_cameras.elev.num_linspace, ) azim_linspace = np.linspace( self.sphere_cameras.azim.min, self.sphere_cameras.azim.max, 1 if self.sphere_cameras.azim.min == self.sphere_cameras.azim.max else self.sphere_cameras.azim.num_linspace, ) fov_linspace = np.linspace( self.sphere_cameras.fov.min, self.sphere_cameras.fov.max, 1 if self.sphere_cameras.fov.min == self.sphere_cameras.fov.max else self.sphere_cameras.fov.num_linspace, ) at = np.array(self.sphere_cameras.at) combinations = np.array(np.meshgrid(dist_linspace, elev_linspace, azim_linspace, fov_linspace)).T.reshape(-1, 4) dist_list = combinations[:, 0].tolist() elev_list = combinations[:, 1].tolist() azim_list = combinations[:, 2].tolist() sphere_Rs, sphere_Ts = init_trajectory(dist_list, elev_list, azim_list, at) sphere_fov_list = combinations[:, 3].tolist() # blenderproc cameras poses = json.load(open(self.config.blenderproc_cameras)) blenderproc_Rs, blenderproc_Ts = init_blenderproc_trajectory(poses, self.device) blenderproc_fov_list = [self.config.fov] * len(blenderproc_Rs) self.Rs = sphere_Rs + blenderproc_Rs self.Ts = sphere_Ts + blenderproc_Ts self.fov_list = sphere_fov_list + blenderproc_fov_list self.num_cameras = len(self.Rs) print("=> using {} spherical cameras and {} blenderproc cameras for training".format(len(sphere_Rs), len(blenderproc_Rs))) # self.sphere_Rs = sphere_Rs # self.sphere_Ts = sphere_Ts # self.sphere_fov_list = sphere_fov_list # self.num_sphere_cameras = len(self.sphere_Rs) # self.Rs = sphere_Rs + blenderproc_Rs # self.Ts = sphere_Ts + blenderproc_Ts # self.fov_list = sphere_fov_list + blenderproc_fov_list # self.num_cameras = len(self.Rs) # print("=> using {} spherical cameras and {} blenderproc cameras for training".format(len(sphere_Rs), len(blenderproc_Rs))) # print("=> using {} cameras before annealing and {} cameras afterwards".format(self.num_sphere_cameras, self.num_cameras)) else: # use fixed cameras raise NotImplementedError # for inference # FIXME only support spherical cameras for now # spherical cameras self.sphere_cameras = OmegaConf.load(self.config.sphere_cameras) dist_linspace = [self.sphere_cameras.dist.min] # always take the min dist from spherical cameras elev_linspace = [self.config.elev] azim_linspace = np.linspace( self.config.azim[0], self.config.azim[1], self.config.log_latents_views, ) fov_linspace = [self.config.fov] at = np.array(self.sphere_cameras.at) # always take the cameras center from spherical cameras combinations = np.array(np.meshgrid(dist_linspace, elev_linspace, azim_linspace, fov_linspace)).T.reshape(-1, 4) self.inference_dist_list = combinations[:, 0].tolist() self.inference_elev_list = combinations[:, 1].tolist() self.inference_azim_list = combinations[:, 2].tolist() self.inference_fov_list = combinations[:, 3].tolist() self.inference_at = at self.num_inference_cameras = len(self.inference_dist_list) print("=> using {} cameras for training, {} cameras for inference.".format(self.num_cameras, self.num_inference_cameras)) def _init_render_func(self): if self.config.render_func_type == "mlp": if self.config.texture_type == "hashgrid": in_channels = self.config.hashgrid_config.n_levels * self.config.hashgrid_config.n_features_per_level elif self.config.texture_type == "hashgrid_mlp": in_channels = self.config.mlp_config.out_channels else: in_channels = self.config.latent_channels render_func = MLP( in_channels, self.config.render_channels, self.config.view_embedding_hidden_dim, self.config.num_view_embedding_layers, dtype=torch.float32 ).to(self.device) elif self.config.render_func_type == "none": render_func = nn.Identity() else: raise NotImplementedError("not supported render function type: {}".format(self.config.render_func_type)) return render_func def init_anchor_func(self, num_instances): if self.config.texture_type == "hashgrid": anchor_dim = self.config.hashgrid_config.n_levels * self.config.hashgrid_config.n_features_per_level elif self.config.texture_type == "hashgrid_mlp": anchor_dim = self.config.mlp_config.out_channels else: anchor_dim = self.config.latent_channels
# import tinycudann as tcnn # customized sys.path.append("./lib") sys.path.append("./models") class Studio(nn.Module): def __init__(self, config, device ): super().__init__() self.config = config self.device = device # render function self.render_func = self._init_render_func() self._init_camera_settings() def _init_camera_settings(self): if self.config.use_sphere_cameras and not self.config.use_blenderproc_cameras: # use random cameras self.sphere_cameras = OmegaConf.load(self.config.sphere_cameras) dist_linspace = np.linspace( self.sphere_cameras.dist.min, self.sphere_cameras.dist.max, 1 if self.sphere_cameras.dist.min == self.sphere_cameras.dist.max else self.sphere_cameras.dist.num_linspace, ) elev_linspace = np.linspace( self.sphere_cameras.elev.min, self.sphere_cameras.elev.max, 1 if self.sphere_cameras.elev.min == self.sphere_cameras.elev.max else self.sphere_cameras.elev.num_linspace, ) azim_linspace = np.linspace( self.sphere_cameras.azim.min, self.sphere_cameras.azim.max, 1 if self.sphere_cameras.azim.min == self.sphere_cameras.azim.max else self.sphere_cameras.azim.num_linspace, ) fov_linspace = np.linspace( self.sphere_cameras.fov.min, self.sphere_cameras.fov.max, 1 if self.sphere_cameras.fov.min == self.sphere_cameras.fov.max else self.sphere_cameras.fov.num_linspace, ) at = np.array(self.sphere_cameras.at) combinations = np.array(np.meshgrid(dist_linspace, elev_linspace, azim_linspace, fov_linspace)).T.reshape(-1, 4) dist_list = combinations[:, 0].tolist() elev_list = combinations[:, 1].tolist() azim_list = combinations[:, 2].tolist() self.Rs, self.Ts = init_trajectory(dist_list, elev_list, azim_list, at) self.fov_list = combinations[:, 3].tolist() self.num_cameras = len(self.Rs) print("=> using {} spherical cameras for training".format(self.num_cameras)) elif not self.config.use_sphere_cameras and self.config.use_blenderproc_cameras: poses = json.load(open(self.config.blenderproc_cameras)) self.Rs, self.Ts = init_blenderproc_trajectory(poses, self.device) self.num_cameras = len(self.Rs) self.fov_list = [self.config.fov] * self.num_cameras print("=> using {} blenderproc cameras for training".format(self.num_cameras)) elif self.config.use_sphere_cameras and self.config.use_blenderproc_cameras: # spherical cameras self.sphere_cameras = OmegaConf.load(self.config.sphere_cameras) dist_linspace = np.linspace( self.sphere_cameras.dist.min, self.sphere_cameras.dist.max, 1 if self.sphere_cameras.dist.min == self.sphere_cameras.dist.max else self.sphere_cameras.dist.num_linspace, ) elev_linspace = np.linspace( self.sphere_cameras.elev.min, self.sphere_cameras.elev.max, 1 if self.sphere_cameras.elev.min == self.sphere_cameras.elev.max else self.sphere_cameras.elev.num_linspace, ) azim_linspace = np.linspace( self.sphere_cameras.azim.min, self.sphere_cameras.azim.max, 1 if self.sphere_cameras.azim.min == self.sphere_cameras.azim.max else self.sphere_cameras.azim.num_linspace, ) fov_linspace = np.linspace( self.sphere_cameras.fov.min, self.sphere_cameras.fov.max, 1 if self.sphere_cameras.fov.min == self.sphere_cameras.fov.max else self.sphere_cameras.fov.num_linspace, ) at = np.array(self.sphere_cameras.at) combinations = np.array(np.meshgrid(dist_linspace, elev_linspace, azim_linspace, fov_linspace)).T.reshape(-1, 4) dist_list = combinations[:, 0].tolist() elev_list = combinations[:, 1].tolist() azim_list = combinations[:, 2].tolist() sphere_Rs, sphere_Ts = init_trajectory(dist_list, elev_list, azim_list, at) sphere_fov_list = combinations[:, 3].tolist() # blenderproc cameras poses = json.load(open(self.config.blenderproc_cameras)) blenderproc_Rs, blenderproc_Ts = init_blenderproc_trajectory(poses, self.device) blenderproc_fov_list = [self.config.fov] * len(blenderproc_Rs) self.Rs = sphere_Rs + blenderproc_Rs self.Ts = sphere_Ts + blenderproc_Ts self.fov_list = sphere_fov_list + blenderproc_fov_list self.num_cameras = len(self.Rs) print("=> using {} spherical cameras and {} blenderproc cameras for training".format(len(sphere_Rs), len(blenderproc_Rs))) # self.sphere_Rs = sphere_Rs # self.sphere_Ts = sphere_Ts # self.sphere_fov_list = sphere_fov_list # self.num_sphere_cameras = len(self.sphere_Rs) # self.Rs = sphere_Rs + blenderproc_Rs # self.Ts = sphere_Ts + blenderproc_Ts # self.fov_list = sphere_fov_list + blenderproc_fov_list # self.num_cameras = len(self.Rs) # print("=> using {} spherical cameras and {} blenderproc cameras for training".format(len(sphere_Rs), len(blenderproc_Rs))) # print("=> using {} cameras before annealing and {} cameras afterwards".format(self.num_sphere_cameras, self.num_cameras)) else: # use fixed cameras raise NotImplementedError # for inference # FIXME only support spherical cameras for now # spherical cameras self.sphere_cameras = OmegaConf.load(self.config.sphere_cameras) dist_linspace = [self.sphere_cameras.dist.min] # always take the min dist from spherical cameras elev_linspace = [self.config.elev] azim_linspace = np.linspace( self.config.azim[0], self.config.azim[1], self.config.log_latents_views, ) fov_linspace = [self.config.fov] at = np.array(self.sphere_cameras.at) # always take the cameras center from spherical cameras combinations = np.array(np.meshgrid(dist_linspace, elev_linspace, azim_linspace, fov_linspace)).T.reshape(-1, 4) self.inference_dist_list = combinations[:, 0].tolist() self.inference_elev_list = combinations[:, 1].tolist() self.inference_azim_list = combinations[:, 2].tolist() self.inference_fov_list = combinations[:, 3].tolist() self.inference_at = at self.num_inference_cameras = len(self.inference_dist_list) print("=> using {} cameras for training, {} cameras for inference.".format(self.num_cameras, self.num_inference_cameras)) def _init_render_func(self): if self.config.render_func_type == "mlp": if self.config.texture_type == "hashgrid": in_channels = self.config.hashgrid_config.n_levels * self.config.hashgrid_config.n_features_per_level elif self.config.texture_type == "hashgrid_mlp": in_channels = self.config.mlp_config.out_channels else: in_channels = self.config.latent_channels render_func = MLP( in_channels, self.config.render_channels, self.config.view_embedding_hidden_dim, self.config.num_view_embedding_layers, dtype=torch.float32 ).to(self.device) elif self.config.render_func_type == "none": render_func = nn.Identity() else: raise NotImplementedError("not supported render function type: {}".format(self.config.render_func_type)) return render_func def init_anchor_func(self, num_instances): if self.config.texture_type == "hashgrid": anchor_dim = self.config.hashgrid_config.n_levels * self.config.hashgrid_config.n_features_per_level elif self.config.texture_type == "hashgrid_mlp": anchor_dim = self.config.mlp_config.out_channels else: anchor_dim = self.config.latent_channels
anchor_func = AnchorTransformer(self.config, self.device, anchor_dim=anchor_dim, num_instances=num_instances).to(self.device)
11
2023-11-28 15:38:40+00:00
12k
Vchitect/VBench
vbench/third_party/umt/datasets/ssv2.py
[ { "identifier": "RandomErasing", "path": "vbench/third_party/umt/datasets/random_erasing.py", "snippet": "class RandomErasing:\n \"\"\"Randomly selects a rectangle region in an image and erases its pixels.\n 'Random Erasing Data Augmentation' by Zhong et al.\n See https://arxiv.org/pdf/...
import os import io import cv2 import numpy as np import torch import warnings import pandas as pd import pandas as pd from torchvision import transforms from decord import VideoReader, cpu from torch.utils.data import Dataset from .random_erasing import RandomErasing from .video_transforms import ( Compose, Resize, CenterCrop, Normalize, create_random_augment, random_short_side_scale_jitter, random_crop, random_resized_crop_with_shift, random_resized_crop, horizontal_flip, random_short_side_scale_jitter, uniform_crop, ) from .volume_transforms import ClipToTensor from petrel_client.client import Client
9,220
args.reprob, mode=args.remode, max_count=args.recount, num_splits=args.recount, device="cpu", ) buffer = buffer.permute(1, 0, 2, 3) buffer = erase_transform(buffer) buffer = buffer.permute(1, 0, 2, 3) return buffer def loadvideo_decord(self, sample, sample_rate_scale=1): """Load video content using Decord""" fname = sample fname = os.path.join(self.prefix, fname) try: if self.keep_aspect_ratio: if fname.startswith('s3'): video_bytes = self.client.get(fname) vr = VideoReader(io.BytesIO(video_bytes), num_threads=1, ctx=cpu(0)) else: vr = VideoReader(fname, num_threads=1, ctx=cpu(0)) else: if fname.startswith('s3:'): video_bytes = self.client.get(fname) vr = VideoReader(io.BytesIO(video_bytes), width=self.new_width, height=self.new_height, num_threads=1, ctx=cpu(0)) else: vr = VideoReader(fname, width=self.new_width, height=self.new_height, num_threads=1, ctx=cpu(0)) except: print("video cannot be loaded by decord: ", fname) return [] if self.mode == 'test': tick = len(vr) / float(self.num_segment) all_index = list(np.array([int(tick / 2.0 + tick * x) for x in range(self.num_segment)] + [int(tick * x) for x in range(self.num_segment)])) while len(all_index) < (self.num_segment * self.test_num_segment): all_index.append(all_index[-1]) all_index = np.sort(np.array(all_index)) vr.seek(0) buffer = vr.get_batch(all_index).asnumpy() return buffer elif self.mode == 'validation': tick = len(vr) / float(self.num_segment) all_index = np.array([int(tick / 2.0 + tick * x) for x in range(self.num_segment)]) vr.seek(0) buffer = vr.get_batch(all_index).asnumpy() return buffer # handle temporal segments average_duration = len(vr) // self.num_segment if average_duration > 0: all_index = list(np.multiply(list(range(self.num_segment)), average_duration) + np.random.randint(average_duration, size=self.num_segment)) elif len(vr) > self.num_segment: all_index = list(np.sort(np.random.randint(len(vr), size=self.num_segment))) else: all_index = list(np.zeros((self.num_segment,))) vr.seek(0) buffer = vr.get_batch(all_index).asnumpy() return buffer def __len__(self): if self.mode != 'test': return len(self.dataset_samples) else: return len(self.test_dataset) def spatial_sampling( frames, spatial_idx=-1, min_scale=256, max_scale=320, crop_size=224, random_horizontal_flip=True, inverse_uniform_sampling=False, aspect_ratio=None, scale=None, motion_shift=False, ): """ Perform spatial sampling on the given video frames. If spatial_idx is -1, perform random scale, random crop, and random flip on the given frames. If spatial_idx is 0, 1, or 2, perform spatial uniform sampling with the given spatial_idx. Args: frames (tensor): frames of images sampled from the video. The dimension is `num frames` x `height` x `width` x `channel`. spatial_idx (int): if -1, perform random spatial sampling. If 0, 1, or 2, perform left, center, right crop if width is larger than height, and perform top, center, buttom crop if height is larger than width. min_scale (int): the minimal size of scaling. max_scale (int): the maximal size of scaling. crop_size (int): the size of height and width used to crop the frames. inverse_uniform_sampling (bool): if True, sample uniformly in [1 / max_scale, 1 / min_scale] and take a reciprocal to get the scale. If False, take a uniform sample from [min_scale, max_scale]. aspect_ratio (list): Aspect ratio range for resizing. scale (list): Scale range for resizing. motion_shift (bool): Whether to apply motion shift for resizing. Returns: frames (tensor): spatially sampled frames. """ assert spatial_idx in [-1, 0, 1, 2] if spatial_idx == -1: if aspect_ratio is None and scale is None:
try: has_client = True except ImportError: has_client = False class SSRawFrameClsDataset(Dataset): """Load your own raw frame classification dataset.""" def __init__(self, anno_path, prefix='', split=' ', mode='train', clip_len=8, crop_size=224, short_side_size=256, new_height=256, new_width=340, keep_aspect_ratio=True, num_segment=1, num_crop=1, test_num_segment=10, test_num_crop=3, filename_tmpl='img_{:05}.jpg', args=None): self.anno_path = anno_path self.prefix = prefix self.split = split self.mode = mode self.clip_len = clip_len self.crop_size = crop_size self.short_side_size = short_side_size self.new_height = new_height self.new_width = new_width self.keep_aspect_ratio = keep_aspect_ratio self.num_segment = num_segment self.test_num_segment = test_num_segment self.num_crop = num_crop self.test_num_crop = test_num_crop self.filename_tmpl = filename_tmpl self.args = args self.aug = False self.rand_erase = False self.client = None if has_client: self.client = Client('~/petreloss.conf') if self.mode in ['train']: self.aug = True if self.args.reprob > 0: self.rand_erase = True if VideoReader is None: raise ImportError( "Unable to import `decord` which is required to read videos.") cleaned = pd.read_csv(self.anno_path, header=None, delimiter=self.split) self.dataset_samples = list(cleaned.values[:, 0]) self.total_frames = list(cleaned.values[:, 1]) self.label_array = list(cleaned.values[:, -1]) if (mode == 'train'): pass elif (mode == 'validation'): self.data_transform = Compose([ Resize(self.short_side_size, interpolation='bilinear'), CenterCrop(size=(self.crop_size, self.crop_size)), ClipToTensor(), Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) elif mode == 'test': self.data_resize = Compose([ Resize(size=(short_side_size), interpolation='bilinear') ]) self.data_transform = Compose([ ClipToTensor(), Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) self.test_seg = [] self.test_dataset = [] self.test_total_frames = [] self.test_label_array = [] for ck in range(self.test_num_segment): for cp in range(self.test_num_crop): for idx in range(len(self.label_array)): self.test_seg.append((ck, cp)) self.test_dataset.append(self.dataset_samples[idx]) self.test_total_frames.append(self.total_frames[idx]) self.test_label_array.append(self.label_array[idx]) def __getitem__(self, index): if self.mode == 'train': args = self.args scale_t = 1 sample = self.dataset_samples[index] total_frame = self.total_frames[index] buffer = self.load_frame(sample, total_frame, sample_rate_scale=scale_t) # T H W C if len(buffer) == 0: while len(buffer) == 0: warnings.warn( "video {} not correctly loaded during training".format( sample)) index = np.random.randint(self.__len__()) sample = self.dataset_samples[index] total_frame = self.total_frames[index] buffer = self.load_frame(sample, total_frame, sample_rate_scale=scale_t) if args.num_sample > 1: frame_list = [] label_list = [] index_list = [] for _ in range(args.num_sample): new_frames = self._aug_frame(buffer, args) label = self.label_array[index] frame_list.append(new_frames) label_list.append(label) index_list.append(index) return frame_list, label_list, index_list, {} else: buffer = self._aug_frame(buffer, args) return buffer, self.label_array[index], index, {} elif self.mode == 'validation': sample = self.dataset_samples[index] total_frame = self.total_frames[index] buffer = self.load_frame(sample, total_frame) if len(buffer) == 0: while len(buffer) == 0: warnings.warn( "video {} not correctly loaded during validation". format(sample)) index = np.random.randint(self.__len__()) sample = self.dataset_samples[index] buffer = self.load_frame(sample, total_frame) buffer = self.data_transform(buffer) return buffer, self.label_array[index], sample.split( "/")[-1].split(".")[0] elif self.mode == 'test': sample = self.test_dataset[index] total_frame = self.test_total_frames[index] chunk_nb, split_nb = self.test_seg[index] buffer = self.load_frame(sample, total_frame) while len(buffer) == 0: warnings.warn("video {}, temporal {}, spatial {} not found during testing".format(\ str(self.test_dataset[index]), chunk_nb, split_nb)) index = np.random.randint(self.__len__()) sample = self.test_dataset[index] total_frame = self.test_total_frames[index] chunk_nb, split_nb = self.test_seg[index] buffer = self.load_frame(sample, total_frame) buffer = self.data_resize(buffer) if isinstance(buffer, list): buffer = np.stack(buffer, 0) spatial_step = 1.0 * (max(buffer.shape[1], buffer.shape[2]) - self.short_side_size) \ / (self.test_num_crop - 1) temporal_start = chunk_nb spatial_start = int(split_nb * spatial_step) if buffer.shape[1] >= buffer.shape[2]: buffer = buffer[temporal_start::self.test_num_segment, \ spatial_start:spatial_start + self.short_side_size, :, :] else: buffer = buffer[temporal_start::self.test_num_segment, \ :, spatial_start:spatial_start + self.short_side_size, :] buffer = self.data_transform(buffer) return buffer, self.test_label_array[index], sample.split("/")[-1].split(".")[0], \ chunk_nb, split_nb else: raise NameError('mode {} unkown'.format(self.mode)) def _aug_frame( self, buffer, args, ): aug_transform = create_random_augment( input_size=(self.crop_size, self.crop_size), auto_augment=args.aa, interpolation=args.train_interpolation, ) buffer = [transforms.ToPILImage()(frame) for frame in buffer] buffer = aug_transform(buffer) buffer = [transforms.ToTensor()(img) for img in buffer] buffer = torch.stack(buffer) # T C H W buffer = buffer.permute(0, 2, 3, 1) # T H W C # T H W C buffer = tensor_normalize(buffer, [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) # T H W C -> C T H W. buffer = buffer.permute(3, 0, 1, 2) # Perform data augmentation. scl, asp = ( [0.08, 1.0], [0.75, 1.3333], ) buffer = spatial_sampling( buffer, spatial_idx=-1, min_scale=256, max_scale=320, crop_size=self.crop_size, random_horizontal_flip=False if args.data_set == 'SSV2' else True, inverse_uniform_sampling=False, aspect_ratio=asp, scale=scl, motion_shift=False) if self.rand_erase: erase_transform = RandomErasing( args.reprob, mode=args.remode, max_count=args.recount, num_splits=args.recount, device="cpu", ) buffer = buffer.permute(1, 0, 2, 3) buffer = erase_transform(buffer) buffer = buffer.permute(1, 0, 2, 3) return buffer def load_frame(self, sample, num_frames, sample_rate_scale=1): """Load video content using Decord""" fname = sample fname = os.path.join(self.prefix, fname) if self.mode == 'test': tick = num_frames / float(self.num_segment) all_index = [] for t_seg in range(self.test_num_segment): tmp_index = [ int(t_seg * tick / self.test_num_segment + tick * x) for x in range(self.num_segment) ] all_index.extend(tmp_index) all_index = list(np.sort(np.array(all_index))) imgs = [] for idx in all_index: frame_fname = os.path.join(fname, self.filename_tmpl.format(idx + 1)) img_bytes = self.client.get(frame_fname) img_np = np.frombuffer(img_bytes, np.uint8) img = cv2.imdecode(img_np, cv2.IMREAD_COLOR) cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img) imgs.append(img) buffer = np.array(imgs) return buffer # handle temporal segments average_duration = num_frames // self.num_segment all_index = [] if average_duration > 0: if self.mode == 'validation': all_index = list( np.multiply(list(range(self.num_segment)), average_duration) + np.ones(self.num_segment, dtype=int) * (average_duration // 2)) else: all_index = list( np.multiply(list(range(self.num_segment)), average_duration) + np.random.randint(average_duration, size=self.num_segment)) elif num_frames > self.num_segment: if self.mode == 'validation': all_index = list(range(self.num_segment)) else: all_index = list( np.sort( np.random.randint(num_frames, size=self.num_segment))) else: all_index = [0] * (self.num_segment - num_frames) + list( range(num_frames)) all_index = list(np.array(all_index)) imgs = [] for idx in all_index: frame_fname = os.path.join(fname, self.filename_tmpl.format(idx + 1)) img_bytes = self.client.get(frame_fname) img_np = np.frombuffer(img_bytes, np.uint8) img = cv2.imdecode(img_np, cv2.IMREAD_COLOR) cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img) imgs.append(img) buffer = np.array(imgs) return buffer def __len__(self): if self.mode != 'test': return len(self.dataset_samples) else: return len(self.test_dataset) class SSVideoClsDataset(Dataset): """Load your own video classification dataset.""" def __init__(self, anno_path, prefix='', split=' ', mode='train', clip_len=8, crop_size=224, short_side_size=256, new_height=256, new_width=340, keep_aspect_ratio=True, num_segment=1, num_crop=1, test_num_segment=10, test_num_crop=3, args=None): self.anno_path = anno_path self.prefix = prefix self.split = split self.mode = mode self.clip_len = clip_len self.crop_size = crop_size self.short_side_size = short_side_size self.new_height = new_height self.new_width = new_width self.keep_aspect_ratio = keep_aspect_ratio self.num_segment = num_segment self.test_num_segment = test_num_segment self.num_crop = num_crop self.test_num_crop = test_num_crop self.args = args self.aug = False self.rand_erase = False self.client = None if has_client: self.client = Client('~/petreloss.conf') if self.mode in ['train']: self.aug = True if self.args.reprob > 0: self.rand_erase = True if VideoReader is None: raise ImportError("Unable to import `decord` which is required to read videos.") cleaned = pd.read_csv(self.anno_path, header=None, delimiter=self.split) self.dataset_samples = list(cleaned.values[:, 0]) self.label_array = list(cleaned.values[:, 1]) if (mode == 'train'): pass elif (mode == 'validation'): self.data_transform = Compose([ Resize(self.short_side_size, interpolation='bilinear'), CenterCrop(size=(self.crop_size, self.crop_size)), ClipToTensor(), Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) elif mode == 'test': self.data_resize = Compose([ Resize(size=(short_side_size), interpolation='bilinear') ]) self.data_transform = Compose([ ClipToTensor(), Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) self.test_seg = [] self.test_dataset = [] self.test_label_array = [] for ck in range(self.test_num_segment): for cp in range(self.test_num_crop): for idx in range(len(self.label_array)): sample_label = self.label_array[idx] self.test_label_array.append(sample_label) self.test_dataset.append(self.dataset_samples[idx]) self.test_seg.append((ck, cp)) def __getitem__(self, index): if self.mode == 'train': args = self.args scale_t = 1 sample = self.dataset_samples[index] buffer = self.loadvideo_decord(sample, sample_rate_scale=scale_t) # T H W C if len(buffer) == 0: while len(buffer) == 0: warnings.warn("video {} not correctly loaded during training".format(sample)) index = np.random.randint(self.__len__()) sample = self.dataset_samples[index] buffer = self.loadvideo_decord(sample, sample_rate_scale=scale_t) if args.num_sample > 1: frame_list = [] label_list = [] index_list = [] for _ in range(args.num_sample): new_frames = self._aug_frame(buffer, args) label = self.label_array[index] frame_list.append(new_frames) label_list.append(label) index_list.append(index) return frame_list, label_list, index_list, {} else: buffer = self._aug_frame(buffer, args) return buffer, self.label_array[index], index, {} elif self.mode == 'validation': sample = self.dataset_samples[index] buffer = self.loadvideo_decord(sample) if len(buffer) == 0: while len(buffer) == 0: warnings.warn("video {} not correctly loaded during validation".format(sample)) index = np.random.randint(self.__len__()) sample = self.dataset_samples[index] buffer = self.loadvideo_decord(sample) buffer = self.data_transform(buffer) return buffer, self.label_array[index], sample.split("/")[-1].split(".")[0] elif self.mode == 'test': sample = self.test_dataset[index] chunk_nb, split_nb = self.test_seg[index] buffer = self.loadvideo_decord(sample) while len(buffer) == 0: warnings.warn("video {}, temporal {}, spatial {} not found during testing".format(\ str(self.test_dataset[index]), chunk_nb, split_nb)) index = np.random.randint(self.__len__()) sample = self.test_dataset[index] chunk_nb, split_nb = self.test_seg[index] buffer = self.loadvideo_decord(sample) buffer = self.data_resize(buffer) if isinstance(buffer, list): buffer = np.stack(buffer, 0) spatial_step = 1.0 * (max(buffer.shape[1], buffer.shape[2]) - self.short_side_size) \ / (self.test_num_crop - 1) temporal_start = chunk_nb # 0/1 spatial_start = int(split_nb * spatial_step) if buffer.shape[1] >= buffer.shape[2]: buffer = buffer[temporal_start::2, \ spatial_start:spatial_start + self.short_side_size, :, :] else: buffer = buffer[temporal_start::2, \ :, spatial_start:spatial_start + self.short_side_size, :] buffer = self.data_transform(buffer) return buffer, self.test_label_array[index], sample.split("/")[-1].split(".")[0], \ chunk_nb, split_nb else: raise NameError('mode {} unkown'.format(self.mode)) def _aug_frame( self, buffer, args, ): aug_transform = create_random_augment( input_size=(self.crop_size, self.crop_size), auto_augment=args.aa, interpolation=args.train_interpolation, ) buffer = [ transforms.ToPILImage()(frame) for frame in buffer ] buffer = aug_transform(buffer) buffer = [transforms.ToTensor()(img) for img in buffer] buffer = torch.stack(buffer) # T C H W buffer = buffer.permute(0, 2, 3, 1) # T H W C # T H W C buffer = tensor_normalize( buffer, [0.485, 0.456, 0.406], [0.229, 0.224, 0.225] ) # T H W C -> C T H W. buffer = buffer.permute(3, 0, 1, 2) # Perform data augmentation. scl, asp = ( [0.08, 1.0], [0.75, 1.3333], ) buffer = spatial_sampling( buffer, spatial_idx=-1, min_scale=256, max_scale=320, crop_size=self.crop_size, random_horizontal_flip=False if args.data_set == 'SSV2' else True, inverse_uniform_sampling=False, aspect_ratio=asp, scale=scl, motion_shift=False ) if self.rand_erase: erase_transform = RandomErasing( args.reprob, mode=args.remode, max_count=args.recount, num_splits=args.recount, device="cpu", ) buffer = buffer.permute(1, 0, 2, 3) buffer = erase_transform(buffer) buffer = buffer.permute(1, 0, 2, 3) return buffer def loadvideo_decord(self, sample, sample_rate_scale=1): """Load video content using Decord""" fname = sample fname = os.path.join(self.prefix, fname) try: if self.keep_aspect_ratio: if fname.startswith('s3'): video_bytes = self.client.get(fname) vr = VideoReader(io.BytesIO(video_bytes), num_threads=1, ctx=cpu(0)) else: vr = VideoReader(fname, num_threads=1, ctx=cpu(0)) else: if fname.startswith('s3:'): video_bytes = self.client.get(fname) vr = VideoReader(io.BytesIO(video_bytes), width=self.new_width, height=self.new_height, num_threads=1, ctx=cpu(0)) else: vr = VideoReader(fname, width=self.new_width, height=self.new_height, num_threads=1, ctx=cpu(0)) except: print("video cannot be loaded by decord: ", fname) return [] if self.mode == 'test': tick = len(vr) / float(self.num_segment) all_index = list(np.array([int(tick / 2.0 + tick * x) for x in range(self.num_segment)] + [int(tick * x) for x in range(self.num_segment)])) while len(all_index) < (self.num_segment * self.test_num_segment): all_index.append(all_index[-1]) all_index = np.sort(np.array(all_index)) vr.seek(0) buffer = vr.get_batch(all_index).asnumpy() return buffer elif self.mode == 'validation': tick = len(vr) / float(self.num_segment) all_index = np.array([int(tick / 2.0 + tick * x) for x in range(self.num_segment)]) vr.seek(0) buffer = vr.get_batch(all_index).asnumpy() return buffer # handle temporal segments average_duration = len(vr) // self.num_segment if average_duration > 0: all_index = list(np.multiply(list(range(self.num_segment)), average_duration) + np.random.randint(average_duration, size=self.num_segment)) elif len(vr) > self.num_segment: all_index = list(np.sort(np.random.randint(len(vr), size=self.num_segment))) else: all_index = list(np.zeros((self.num_segment,))) vr.seek(0) buffer = vr.get_batch(all_index).asnumpy() return buffer def __len__(self): if self.mode != 'test': return len(self.dataset_samples) else: return len(self.test_dataset) def spatial_sampling( frames, spatial_idx=-1, min_scale=256, max_scale=320, crop_size=224, random_horizontal_flip=True, inverse_uniform_sampling=False, aspect_ratio=None, scale=None, motion_shift=False, ): """ Perform spatial sampling on the given video frames. If spatial_idx is -1, perform random scale, random crop, and random flip on the given frames. If spatial_idx is 0, 1, or 2, perform spatial uniform sampling with the given spatial_idx. Args: frames (tensor): frames of images sampled from the video. The dimension is `num frames` x `height` x `width` x `channel`. spatial_idx (int): if -1, perform random spatial sampling. If 0, 1, or 2, perform left, center, right crop if width is larger than height, and perform top, center, buttom crop if height is larger than width. min_scale (int): the minimal size of scaling. max_scale (int): the maximal size of scaling. crop_size (int): the size of height and width used to crop the frames. inverse_uniform_sampling (bool): if True, sample uniformly in [1 / max_scale, 1 / min_scale] and take a reciprocal to get the scale. If False, take a uniform sample from [min_scale, max_scale]. aspect_ratio (list): Aspect ratio range for resizing. scale (list): Scale range for resizing. motion_shift (bool): Whether to apply motion shift for resizing. Returns: frames (tensor): spatially sampled frames. """ assert spatial_idx in [-1, 0, 1, 2] if spatial_idx == -1: if aspect_ratio is None and scale is None:
frames, _ = random_short_side_scale_jitter(
11
2023-11-27 12:41:46+00:00
12k
16lemoing/dot
dot/models/shelf/cotracker_utils/models/core/cotracker/cotracker.py
[ { "identifier": "BasicEncoder", "path": "dot/models/shelf/cotracker_utils/models/core/cotracker/blocks.py", "snippet": "class BasicEncoder(nn.Module):\n def __init__(\n self, input_dim=3, output_dim=128, stride=8, norm_fn=\"batch\", dropout=0.0\n ):\n super(BasicEncoder, self).__init...
import torch import torch.nn as nn from einops import rearrange from dot.models.shelf.cotracker_utils.models.core.cotracker.blocks import ( BasicEncoder, CorrBlock, UpdateFormer, ) from dot.models.shelf.cotracker_utils.models.core.model_utils import meshgrid2d, bilinear_sample2d, smart_cat from dot.models.shelf.cotracker_utils.models.core.embeddings import ( get_2d_embedding, get_1d_sincos_pos_embed_from_grid, get_2d_sincos_pos_embed, )
8,025
x = rearrange(x, "(b n) t d -> b n t d", b=B) delta = self.updateformer(x) delta = rearrange(delta, " b n t d -> (b n) t d") delta_coords_ = delta[:, :, :2] delta_feats_ = delta[:, :, 2:] delta_feats_ = delta_feats_.reshape(B * N * S, self.latent_dim) ffeats_ = ffeats.permute(0, 2, 1, 3).reshape(B * N * S, self.latent_dim) ffeats_ = self.ffeat_updater(self.norm(delta_feats_)) + ffeats_ ffeats = ffeats_.reshape(B, N, S, self.latent_dim).permute( 0, 2, 1, 3 ) # B,S,N,C coords = coords + delta_coords_.reshape(B, N, S, 2).permute(0, 2, 1, 3) coord_predictions.append(coords * self.stride) vis_e = self.vis_predictor(ffeats.reshape(B * S * N, self.latent_dim)).reshape( B, S, N ) return coord_predictions, vis_e, feat_init def forward(self, rgbs, queries, iters=4, cached_feat=None, feat_init=None, is_train=False): B, T, C, H, W = rgbs.shape B, N, __ = queries.shape device = rgbs.device assert B == 1 # INIT for the first sequence # We want to sort points by the first frame they are visible to add them to the tensor of tracked points consequtively first_positive_inds = queries[:, :, 0].long() __, sort_inds = torch.sort(first_positive_inds[0], dim=0, descending=False) inv_sort_inds = torch.argsort(sort_inds, dim=0) first_positive_sorted_inds = first_positive_inds[0][sort_inds] assert torch.allclose( first_positive_inds[0], first_positive_inds[0][sort_inds][inv_sort_inds] ) coords_init = queries[:, :, 1:].reshape(B, 1, N, 2).repeat( 1, self.S, 1, 1 ) / float(self.stride) rgbs = 2 * rgbs - 1.0 traj_e = torch.zeros((B, T, N, 2), device=device) vis_e = torch.zeros((B, T, N), device=device) ind_array = torch.arange(T, device=device) ind_array = ind_array[None, :, None].repeat(B, 1, N) track_mask = (ind_array >= first_positive_inds[:, None, :]).unsqueeze(-1) # these are logits, so we initialize visibility with something that would give a value close to 1 after softmax vis_init = torch.ones((B, self.S, N, 1), device=device).float() * 10 ind = 0 track_mask_ = track_mask[:, :, sort_inds].clone() coords_init_ = coords_init[:, :, sort_inds].clone() vis_init_ = vis_init[:, :, sort_inds].clone() prev_wind_idx = 0 fmaps_ = None vis_predictions = [] coord_predictions = [] wind_inds = [] while ind < T - self.S // 2: rgbs_seq = rgbs[:, ind : ind + self.S] S = S_local = rgbs_seq.shape[1] if cached_feat is None: if S < self.S: rgbs_seq = torch.cat( [rgbs_seq, rgbs_seq[:, -1, None].repeat(1, self.S - S, 1, 1, 1)], dim=1, ) S = rgbs_seq.shape[1] rgbs_ = rgbs_seq.reshape(B * S, C, H, W) if fmaps_ is None: fmaps_ = self.fnet(rgbs_) else: fmaps_ = torch.cat( [fmaps_[self.S // 2 :], self.fnet(rgbs_[self.S // 2 :])], dim=0 ) fmaps = fmaps_.reshape( B, S, self.latent_dim, H // self.stride, W // self.stride ) else: fmaps = cached_feat[:, ind : ind + self.S] if S < self.S: fmaps = torch.cat( [fmaps, fmaps[:, -1, None].repeat(1, self.S - S, 1, 1, 1)], dim=1, ) curr_wind_points = torch.nonzero(first_positive_sorted_inds < ind + self.S) if curr_wind_points.shape[0] == 0: ind = ind + self.S // 2 continue wind_idx = curr_wind_points[-1] + 1 if wind_idx - prev_wind_idx > 0: fmaps_sample = fmaps[ :, first_positive_sorted_inds[prev_wind_idx:wind_idx] - ind ] feat_init_ = bilinear_sample2d( fmaps_sample, coords_init_[:, 0, prev_wind_idx:wind_idx, 0], coords_init_[:, 0, prev_wind_idx:wind_idx, 1], ).permute(0, 2, 1) feat_init_ = feat_init_.unsqueeze(1).repeat(1, self.S, 1, 1)
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. torch.manual_seed(0) def get_points_on_a_grid(grid_size, interp_shape, grid_center=(0, 0), device="cpu"): if grid_size == 1: return torch.tensor([interp_shape[1] / 2, interp_shape[0] / 2], device=device)[ None, None ] grid_y, grid_x = meshgrid2d( 1, grid_size, grid_size, stack=False, norm=False, device=device ) step = interp_shape[1] // 64 if grid_center[0] != 0 or grid_center[1] != 0: grid_y = grid_y - grid_size / 2.0 grid_x = grid_x - grid_size / 2.0 grid_y = step + grid_y.reshape(1, -1) / float(grid_size - 1) * ( interp_shape[0] - step * 2 ) grid_x = step + grid_x.reshape(1, -1) / float(grid_size - 1) * ( interp_shape[1] - step * 2 ) grid_y = grid_y + grid_center[0] grid_x = grid_x + grid_center[1] xy = torch.stack([grid_x, grid_y], dim=-1).to(device) return xy def sample_pos_embed(grid_size, embed_dim, coords): pos_embed = get_2d_sincos_pos_embed(embed_dim=embed_dim, grid_size=grid_size) pos_embed = ( torch.from_numpy(pos_embed) .reshape(grid_size[0], grid_size[1], embed_dim) .float() .unsqueeze(0) .to(coords.device) ) sampled_pos_embed = bilinear_sample2d( pos_embed.permute(0, 3, 1, 2), coords[:, 0, :, 0], coords[:, 0, :, 1] ) return sampled_pos_embed class CoTracker(nn.Module): def __init__( self, S=8, stride=8, add_space_attn=True, num_heads=8, hidden_size=384, space_depth=12, time_depth=12, ): super(CoTracker, self).__init__() self.S = S self.stride = stride self.hidden_dim = 256 self.latent_dim = latent_dim = 128 self.corr_levels = 4 self.corr_radius = 3 self.add_space_attn = add_space_attn self.fnet = BasicEncoder( output_dim=self.latent_dim, norm_fn="instance", dropout=0, stride=stride ) self.updateformer = UpdateFormer( space_depth=space_depth, time_depth=time_depth, input_dim=456, hidden_size=hidden_size, num_heads=num_heads, output_dim=latent_dim + 2, mlp_ratio=4.0, add_space_attn=add_space_attn, ) self.norm = nn.GroupNorm(1, self.latent_dim) self.ffeat_updater = nn.Sequential( nn.Linear(self.latent_dim, self.latent_dim), nn.GELU(), ) self.vis_predictor = nn.Sequential( nn.Linear(self.latent_dim, 1), ) def forward_iteration( self, fmaps, coords_init, feat_init=None, vis_init=None, track_mask=None, iters=4, ): B, S_init, N, D = coords_init.shape assert D == 2 assert B == 1 B, S, __, H8, W8 = fmaps.shape device = fmaps.device if S_init < S: coords = torch.cat( [coords_init, coords_init[:, -1].repeat(1, S - S_init, 1, 1)], dim=1 ) vis_init = torch.cat( [vis_init, vis_init[:, -1].repeat(1, S - S_init, 1, 1)], dim=1 ) else: coords = coords_init.clone() fcorr_fn = CorrBlock( fmaps, num_levels=self.corr_levels, radius=self.corr_radius ) ffeats = feat_init.clone() times_ = torch.linspace(0, S - 1, S).reshape(1, S, 1) pos_embed = sample_pos_embed( grid_size=(H8, W8), embed_dim=456, coords=coords, ) pos_embed = rearrange(pos_embed, "b e n -> (b n) e").unsqueeze(1) times_embed = ( torch.from_numpy(get_1d_sincos_pos_embed_from_grid(456, times_[0]))[None] .repeat(B, 1, 1) .float() .to(device) ) coord_predictions = [] for __ in range(iters): coords = coords.detach() fcorr_fn.corr(ffeats) fcorrs = fcorr_fn.sample(coords) # B, S, N, LRR LRR = fcorrs.shape[3] fcorrs_ = fcorrs.permute(0, 2, 1, 3).reshape(B * N, S, LRR) flows_ = (coords - coords[:, 0:1]).permute(0, 2, 1, 3).reshape(B * N, S, 2) flows_cat = get_2d_embedding(flows_, 64, cat_coords=True) ffeats_ = ffeats.permute(0, 2, 1, 3).reshape(B * N, S, self.latent_dim) if track_mask.shape[1] < vis_init.shape[1]: track_mask = torch.cat( [ track_mask, torch.zeros_like(track_mask[:, 0]).repeat( 1, vis_init.shape[1] - track_mask.shape[1], 1, 1 ), ], dim=1, ) concat = ( torch.cat([track_mask, vis_init], dim=2) .permute(0, 2, 1, 3) .reshape(B * N, S, 2) ) transformer_input = torch.cat([flows_cat, fcorrs_, ffeats_, concat], dim=2) x = transformer_input + pos_embed + times_embed x = rearrange(x, "(b n) t d -> b n t d", b=B) delta = self.updateformer(x) delta = rearrange(delta, " b n t d -> (b n) t d") delta_coords_ = delta[:, :, :2] delta_feats_ = delta[:, :, 2:] delta_feats_ = delta_feats_.reshape(B * N * S, self.latent_dim) ffeats_ = ffeats.permute(0, 2, 1, 3).reshape(B * N * S, self.latent_dim) ffeats_ = self.ffeat_updater(self.norm(delta_feats_)) + ffeats_ ffeats = ffeats_.reshape(B, N, S, self.latent_dim).permute( 0, 2, 1, 3 ) # B,S,N,C coords = coords + delta_coords_.reshape(B, N, S, 2).permute(0, 2, 1, 3) coord_predictions.append(coords * self.stride) vis_e = self.vis_predictor(ffeats.reshape(B * S * N, self.latent_dim)).reshape( B, S, N ) return coord_predictions, vis_e, feat_init def forward(self, rgbs, queries, iters=4, cached_feat=None, feat_init=None, is_train=False): B, T, C, H, W = rgbs.shape B, N, __ = queries.shape device = rgbs.device assert B == 1 # INIT for the first sequence # We want to sort points by the first frame they are visible to add them to the tensor of tracked points consequtively first_positive_inds = queries[:, :, 0].long() __, sort_inds = torch.sort(first_positive_inds[0], dim=0, descending=False) inv_sort_inds = torch.argsort(sort_inds, dim=0) first_positive_sorted_inds = first_positive_inds[0][sort_inds] assert torch.allclose( first_positive_inds[0], first_positive_inds[0][sort_inds][inv_sort_inds] ) coords_init = queries[:, :, 1:].reshape(B, 1, N, 2).repeat( 1, self.S, 1, 1 ) / float(self.stride) rgbs = 2 * rgbs - 1.0 traj_e = torch.zeros((B, T, N, 2), device=device) vis_e = torch.zeros((B, T, N), device=device) ind_array = torch.arange(T, device=device) ind_array = ind_array[None, :, None].repeat(B, 1, N) track_mask = (ind_array >= first_positive_inds[:, None, :]).unsqueeze(-1) # these are logits, so we initialize visibility with something that would give a value close to 1 after softmax vis_init = torch.ones((B, self.S, N, 1), device=device).float() * 10 ind = 0 track_mask_ = track_mask[:, :, sort_inds].clone() coords_init_ = coords_init[:, :, sort_inds].clone() vis_init_ = vis_init[:, :, sort_inds].clone() prev_wind_idx = 0 fmaps_ = None vis_predictions = [] coord_predictions = [] wind_inds = [] while ind < T - self.S // 2: rgbs_seq = rgbs[:, ind : ind + self.S] S = S_local = rgbs_seq.shape[1] if cached_feat is None: if S < self.S: rgbs_seq = torch.cat( [rgbs_seq, rgbs_seq[:, -1, None].repeat(1, self.S - S, 1, 1, 1)], dim=1, ) S = rgbs_seq.shape[1] rgbs_ = rgbs_seq.reshape(B * S, C, H, W) if fmaps_ is None: fmaps_ = self.fnet(rgbs_) else: fmaps_ = torch.cat( [fmaps_[self.S // 2 :], self.fnet(rgbs_[self.S // 2 :])], dim=0 ) fmaps = fmaps_.reshape( B, S, self.latent_dim, H // self.stride, W // self.stride ) else: fmaps = cached_feat[:, ind : ind + self.S] if S < self.S: fmaps = torch.cat( [fmaps, fmaps[:, -1, None].repeat(1, self.S - S, 1, 1, 1)], dim=1, ) curr_wind_points = torch.nonzero(first_positive_sorted_inds < ind + self.S) if curr_wind_points.shape[0] == 0: ind = ind + self.S // 2 continue wind_idx = curr_wind_points[-1] + 1 if wind_idx - prev_wind_idx > 0: fmaps_sample = fmaps[ :, first_positive_sorted_inds[prev_wind_idx:wind_idx] - ind ] feat_init_ = bilinear_sample2d( fmaps_sample, coords_init_[:, 0, prev_wind_idx:wind_idx, 0], coords_init_[:, 0, prev_wind_idx:wind_idx, 1], ).permute(0, 2, 1) feat_init_ = feat_init_.unsqueeze(1).repeat(1, self.S, 1, 1)
feat_init = smart_cat(feat_init, feat_init_, dim=2)
5
2023-12-01 09:59:13+00:00
12k
cswry/SeeSR
utils_data/make_paired_data_DAPE.py
[ { "identifier": "RealESRGANDataset", "path": "basicsr/data/realesrgan_dataset.py", "snippet": "class RealESRGANDataset(data.Dataset):\n \"\"\"Modified dataset based on the dataset used for Real-ESRGAN model:\n Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data.\n\n ...
import os import cv2 import torch import torch.nn.functional as F import argparse import sys import random import torch.nn.functional as F from pytorch_lightning import seed_everything from basicsr.data.realesrgan_dataset import RealESRGANDataset from dataloaders.simple_dataset import SimpleDataset from ram.models import ram from ram import inference_ram as inference from torchvision.transforms import Normalize, Compose 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
9,180
''' * SeeSR: Towards Semantics-Aware Real-World Image Super-Resolution * Modified from diffusers by Rongyuan Wu * 24/12/2023 ''' sys.path.append(os.getcwd()) parser = argparse.ArgumentParser() parser.add_argument("--gt_path", nargs='+', default=['PATH 1', 'PATH 2'], help='the path of high-resolution images') parser.add_argument("--save_dir", type=str, default='preset/datasets/train_datasets/training_for_dape', help='the save path of the training dataset.') parser.add_argument("--start_gpu", type=int, default=1, help='if you have 5 GPUs, you can set it to 1/2/3/4/5 on five gpus for parallel processing., which will save your time. ') parser.add_argument("--batch_size", type=int, default=10, help='smaller batch size means much time but more extensive degradation for making the training dataset.') parser.add_argument("--epoch", type=int, default=1, help='decide how many epochs to create for the dataset.') args = parser.parse_args() print(f'====== START GPU: {args.start_gpu} =========') seed_everything(24+args.start_gpu*1000) args_training_dataset = {} # Please set your gt path here. If you have multi dirs, you can set it as ['PATH1', 'PATH2', 'PATH3', ...] args_training_dataset['gt_path'] = args.gt_path #################### REALESRGAN SETTING ########################### args_training_dataset['queue_size'] = 160 args_training_dataset['crop_size'] = 512 args_training_dataset['io_backend'] = {} args_training_dataset['io_backend']['type'] = 'disk' args_training_dataset['blur_kernel_size'] = 21 args_training_dataset['kernel_list'] = ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] args_training_dataset['kernel_prob'] = [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] args_training_dataset['sinc_prob'] = 0.1 args_training_dataset['blur_sigma'] = [0.2, 3] args_training_dataset['betag_range'] = [0.5, 4] args_training_dataset['betap_range'] = [1, 2] args_training_dataset['blur_kernel_size2'] = 11 args_training_dataset['kernel_list2'] = ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] args_training_dataset['kernel_prob2'] = [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] args_training_dataset['sinc_prob2'] = 0.1 args_training_dataset['blur_sigma2'] = [0.2, 1.5] args_training_dataset['betag_range2'] = [0.5, 4.0] args_training_dataset['betap_range2'] = [1, 2] args_training_dataset['final_sinc_prob'] = 0.8 args_training_dataset['use_hflip'] = True args_training_dataset['use_rot'] = False
''' * SeeSR: Towards Semantics-Aware Real-World Image Super-Resolution * Modified from diffusers by Rongyuan Wu * 24/12/2023 ''' sys.path.append(os.getcwd()) parser = argparse.ArgumentParser() parser.add_argument("--gt_path", nargs='+', default=['PATH 1', 'PATH 2'], help='the path of high-resolution images') parser.add_argument("--save_dir", type=str, default='preset/datasets/train_datasets/training_for_dape', help='the save path of the training dataset.') parser.add_argument("--start_gpu", type=int, default=1, help='if you have 5 GPUs, you can set it to 1/2/3/4/5 on five gpus for parallel processing., which will save your time. ') parser.add_argument("--batch_size", type=int, default=10, help='smaller batch size means much time but more extensive degradation for making the training dataset.') parser.add_argument("--epoch", type=int, default=1, help='decide how many epochs to create for the dataset.') args = parser.parse_args() print(f'====== START GPU: {args.start_gpu} =========') seed_everything(24+args.start_gpu*1000) args_training_dataset = {} # Please set your gt path here. If you have multi dirs, you can set it as ['PATH1', 'PATH2', 'PATH3', ...] args_training_dataset['gt_path'] = args.gt_path #################### REALESRGAN SETTING ########################### args_training_dataset['queue_size'] = 160 args_training_dataset['crop_size'] = 512 args_training_dataset['io_backend'] = {} args_training_dataset['io_backend']['type'] = 'disk' args_training_dataset['blur_kernel_size'] = 21 args_training_dataset['kernel_list'] = ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] args_training_dataset['kernel_prob'] = [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] args_training_dataset['sinc_prob'] = 0.1 args_training_dataset['blur_sigma'] = [0.2, 3] args_training_dataset['betag_range'] = [0.5, 4] args_training_dataset['betap_range'] = [1, 2] args_training_dataset['blur_kernel_size2'] = 11 args_training_dataset['kernel_list2'] = ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] args_training_dataset['kernel_prob2'] = [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] args_training_dataset['sinc_prob2'] = 0.1 args_training_dataset['blur_sigma2'] = [0.2, 1.5] args_training_dataset['betag_range2'] = [0.5, 4.0] args_training_dataset['betap_range2'] = [1, 2] args_training_dataset['final_sinc_prob'] = 0.8 args_training_dataset['use_hflip'] = True args_training_dataset['use_rot'] = False
train_dataset = SimpleDataset(args_training_dataset, fix_size=512)
1
2023-11-27 08:50:33+00:00
12k
mu-cai/ViP-LLaVA
llava/model/language_model/mpt/modeling_mpt.py
[ { "identifier": "attn_bias_shape", "path": "llava/model/language_model/mpt/attention.py", "snippet": "def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id):\n if attn_impl == 'flash':\n return None\n elif attn_impl in ['torch', 'triton']:\n if al...
import math import warnings import torch import torch.nn as nn import torch.nn.functional as F from typing import List, Optional, Tuple, Union from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast from .attention import attn_bias_shape, build_attn_bias from .blocks import MPTBlock from .custom_embedding import SharedEmbedding from .norm import NORM_CLASS_REGISTRY from .configuration_mpt import MPTConfig from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm from .meta_init_context import init_empty_weights from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_ from .flash_attn_triton import flash_attn_func
7,343
"""A simple, flexible implementation of a GPT model. Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py """ try: except: pass Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast] class MPTPreTrainedModel(PreTrainedModel): config_class = MPTConfig base_model_prefix = 'model' _no_split_modules = ['MPTBlock'] class MPTModel(MPTPreTrainedModel): def __init__(self, config: MPTConfig): config._validate_config() super().__init__(config) self.attn_impl = config.attn_config['attn_impl'] self.prefix_lm = config.attn_config['prefix_lm'] self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id'] self.alibi = config.attn_config['alibi'] self.alibi_bias_max = config.attn_config['alibi_bias_max'] if config.init_device == 'mixed': if dist.get_local_rank() == 0: config.init_device = 'cpu' else: config.init_device = 'meta' if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys(): norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys()) raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).') norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()] self.embedding_fraction = config.embedding_fraction self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device) if not self.alibi: self.wpe = torch.nn.Embedding(config.max_seq_len, config.d_model, device=config.init_device) self.emb_drop = nn.Dropout(config.emb_pdrop) self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)]) self.norm_f = norm_class(config.d_model, device=config.init_device) if config.init_device != 'meta': print(f'You are using config.init_device={config.init_device!r}, but you can also use config.init_device="meta" with Composer + FSDP for fast initialization.') self.apply(self.param_init_fn) self.is_causal = not self.prefix_lm self._attn_bias_initialized = False self.attn_bias = None self.attn_bias_shape = attn_bias_shape(self.attn_impl, config.n_heads, config.max_seq_len, self.alibi, prefix_lm=self.prefix_lm, causal=self.is_causal, use_sequence_id=self.attn_uses_sequence_id) if config.no_bias: for module in self.modules(): if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter): if config.verbose: warnings.warn(f'Removing bias ({module.bias}) from {module}.') module.register_parameter('bias', None) if config.verbose and config.verbose > 2: print(self) if 'verbose' not in self.config.init_config: self.config.init_config['verbose'] = self.config.verbose if self.config.init_config['verbose'] > 1: init_fn_name = self.config.init_config['name'] warnings.warn(f'Using {init_fn_name} initialization.') self.gradient_checkpointing = False def get_input_embeddings(self): return self.wte def set_input_embeddings(self, value): self.wte = value @torch.no_grad() def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None): if not self._attn_bias_initialized: if self.attn_bias_shape: self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype)
"""A simple, flexible implementation of a GPT model. Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py """ try: except: pass Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast] class MPTPreTrainedModel(PreTrainedModel): config_class = MPTConfig base_model_prefix = 'model' _no_split_modules = ['MPTBlock'] class MPTModel(MPTPreTrainedModel): def __init__(self, config: MPTConfig): config._validate_config() super().__init__(config) self.attn_impl = config.attn_config['attn_impl'] self.prefix_lm = config.attn_config['prefix_lm'] self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id'] self.alibi = config.attn_config['alibi'] self.alibi_bias_max = config.attn_config['alibi_bias_max'] if config.init_device == 'mixed': if dist.get_local_rank() == 0: config.init_device = 'cpu' else: config.init_device = 'meta' if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys(): norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys()) raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).') norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()] self.embedding_fraction = config.embedding_fraction self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device) if not self.alibi: self.wpe = torch.nn.Embedding(config.max_seq_len, config.d_model, device=config.init_device) self.emb_drop = nn.Dropout(config.emb_pdrop) self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)]) self.norm_f = norm_class(config.d_model, device=config.init_device) if config.init_device != 'meta': print(f'You are using config.init_device={config.init_device!r}, but you can also use config.init_device="meta" with Composer + FSDP for fast initialization.') self.apply(self.param_init_fn) self.is_causal = not self.prefix_lm self._attn_bias_initialized = False self.attn_bias = None self.attn_bias_shape = attn_bias_shape(self.attn_impl, config.n_heads, config.max_seq_len, self.alibi, prefix_lm=self.prefix_lm, causal=self.is_causal, use_sequence_id=self.attn_uses_sequence_id) if config.no_bias: for module in self.modules(): if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter): if config.verbose: warnings.warn(f'Removing bias ({module.bias}) from {module}.') module.register_parameter('bias', None) if config.verbose and config.verbose > 2: print(self) if 'verbose' not in self.config.init_config: self.config.init_config['verbose'] = self.config.verbose if self.config.init_config['verbose'] > 1: init_fn_name = self.config.init_config['name'] warnings.warn(f'Using {init_fn_name} initialization.') self.gradient_checkpointing = False def get_input_embeddings(self): return self.wte def set_input_embeddings(self, value): self.wte = value @torch.no_grad() def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None): if not self._attn_bias_initialized: if self.attn_bias_shape: self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype)
self.attn_bias = build_attn_bias(self.attn_impl, self.attn_bias, self.config.n_heads, self.config.max_seq_len, causal=self.is_causal, alibi=self.alibi, alibi_bias_max=self.alibi_bias_max)
1
2023-12-02 05:52:18+00:00
12k
Meituan-AutoML/Lenna
model/llava/model/language_model/mpt/modeling_mpt.py
[ { "identifier": "AutoTokenizerForMOD", "path": "model/llava/model/language_model/mpt/adapt_tokenizer.py", "snippet": "class AutoTokenizerForMOD(AutoTokenizer):\n \"\"\"AutoTokenizer + Adaptation for MOD.\n\n A simple wrapper around AutoTokenizer to make instantiating\n an MOD-adapted tokenizer ...
import math import warnings import torch import torch.nn as nn import torch.nn.functional as F from typing import List, Optional, Tuple, Union from transformers import (PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast) from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast) from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising from .attention import attn_bias_shape, build_attn_bias from .blocks import MPTBlock from .configuration_mpt import MPTConfig from .custom_embedding import SharedEmbedding from .hf_prefixlm_converter import (add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm) from .meta_init_context import init_empty_weights from .norm import NORM_CLASS_REGISTRY from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_ from .flash_attn_triton import flash_attn_func
7,329
"""A simple, flexible implementation of a GPT model. Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py """ try: except: pass Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast] class MPTPreTrainedModel(PreTrainedModel): config_class = MPTConfig base_model_prefix = "model" _no_split_modules = ["MPTBlock"] class MPTModel(MPTPreTrainedModel): def __init__(self, config: MPTConfig): config._validate_config() super().__init__(config) self.attn_impl = config.attn_config["attn_impl"] self.prefix_lm = config.attn_config["prefix_lm"] self.attn_uses_sequence_id = config.attn_config["attn_uses_sequence_id"] self.alibi = config.attn_config["alibi"] self.alibi_bias_max = config.attn_config["alibi_bias_max"] if config.init_device == "mixed": if dist.get_local_rank() == 0: config.init_device = "cpu" else: config.init_device = "meta" if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys(): norm_options = " | ".join(NORM_CLASS_REGISTRY.keys()) raise NotImplementedError( f"Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options})." ) norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()] self.embedding_fraction = config.embedding_fraction
"""A simple, flexible implementation of a GPT model. Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py """ try: except: pass Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast] class MPTPreTrainedModel(PreTrainedModel): config_class = MPTConfig base_model_prefix = "model" _no_split_modules = ["MPTBlock"] class MPTModel(MPTPreTrainedModel): def __init__(self, config: MPTConfig): config._validate_config() super().__init__(config) self.attn_impl = config.attn_config["attn_impl"] self.prefix_lm = config.attn_config["prefix_lm"] self.attn_uses_sequence_id = config.attn_config["attn_uses_sequence_id"] self.alibi = config.attn_config["alibi"] self.alibi_bias_max = config.attn_config["alibi_bias_max"] if config.init_device == "mixed": if dist.get_local_rank() == 0: config.init_device = "cpu" else: config.init_device = "meta" if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys(): norm_options = " | ".join(NORM_CLASS_REGISTRY.keys()) raise NotImplementedError( f"Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options})." ) norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()] self.embedding_fraction = config.embedding_fraction
self.wte = SharedEmbedding(
6
2023-12-04 11:03:26+00:00
12k
xmu-xiaoma666/X-Dreamer
unet_2d_condition_multiatt.py
[ { "identifier": "AttentionProcessor", "path": "attention_processor.py", "snippet": "class Attention(nn.Module):\nclass AttnProcessor:\nclass LoRAAttnProcessor(nn.Module):\nclass CustomDiffusionAttnProcessor(nn.Module):\nclass AttnAddedKVProcessor:\nclass AttnAddedKVProcessor2_0:\nclass LoRAAttnAddedKVPr...
from dataclasses import dataclass from typing import Any, Dict, List, Optional, Tuple, Union from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.loaders import UNet2DConditionLoadersMixin from diffusers.utils import BaseOutput, logging from diffusers.models.activations import get_activation from attention_processor import AttentionProcessor, AttnProcessor from diffusers.models.embeddings import ( GaussianFourierProjection, ImageHintTimeEmbedding, ImageProjection, ImageTimeEmbedding, PositionNet, TextImageProjection, TextImageTimeEmbedding, TextTimeEmbedding, TimestepEmbedding, Timesteps, ) from diffusers.models.modeling_utils import ModelMixin from unet_2d_blocks import ( UNetMidBlock2DCrossAttn, UNetMidBlock2DSimpleCrossAttn, get_down_block, get_up_block, ) import torch import torch.nn as nn import torch.utils.checkpoint
10,544
add_upsample = True self.num_upsamplers += 1 else: add_upsample = False up_block = get_up_block( up_block_type, num_layers=reversed_layers_per_block[i] + 1, transformer_layers_per_block=reversed_transformer_layers_per_block[i], in_channels=input_channel, out_channels=output_channel, prev_output_channel=prev_output_channel, temb_channels=blocks_time_embed_dim, add_upsample=add_upsample, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=reversed_cross_attention_dim[i], num_attention_heads=reversed_num_attention_heads[i], dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, attention_type=attention_type, resnet_skip_time_act=resnet_skip_time_act, resnet_out_scale_factor=resnet_out_scale_factor, cross_attention_norm=cross_attention_norm, attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel, ) self.up_blocks.append(up_block) prev_output_channel = output_channel # out if norm_num_groups is not None: self.conv_norm_out = nn.GroupNorm( num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps ) self.conv_act = get_activation(act_fn) else: self.conv_norm_out = None self.conv_act = None conv_out_padding = (conv_out_kernel - 1) // 2 self.conv_out = nn.Conv2d( block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding ) if attention_type == "gated": positive_len = 768 if isinstance(cross_attention_dim, int): positive_len = cross_attention_dim elif isinstance(cross_attention_dim, tuple) or isinstance(cross_attention_dim, list): positive_len = cross_attention_dim[0] self.position_net = PositionNet(positive_len=positive_len, out_dim=cross_attention_dim) @property def attn_processors(self) -> Dict[str, AttentionProcessor]: r""" Returns: `dict` of attention processors: A dictionary containing all attention processors used in the model with indexed by its weight name. """ # set recursively processors = {} def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]): if hasattr(module, "set_processor"): processors[f"{name}.processor"] = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(f"{name}.{sub_name}", child, processors) return processors for name, module in self.named_children(): fn_recursive_add_processors(name, module, processors) return processors def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]): r""" Sets the attention processor to use to compute attention. Parameters: processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`): The instantiated processor class or a dictionary of processor classes that will be set as the processor for **all** `Attention` layers. If `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. """ count = len(self.attn_processors.keys()) if isinstance(processor, dict) and len(processor) != count: raise ValueError( f"A dict of processors was passed, but the number of processors {len(processor)} does not match the" f" number of attention layers: {count}. Please make sure to pass {count} processor classes." ) def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor): if hasattr(module, "set_processor"): if not isinstance(processor, dict): module.set_processor(processor) else: module.set_processor(processor.pop(f"{name}.processor")) for sub_name, child in module.named_children(): fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor) for name, module in self.named_children(): fn_recursive_attn_processor(name, module, processor) def set_default_attn_processor(self): """ Disables custom attention processors and sets the default attention implementation. """
# 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. logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class UNet2DConditionOutput(BaseOutput): """ The output of [`UNet2DConditionModel`]. Args: sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model. """ sample: torch.FloatTensor = None class UNet2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin): r""" A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample shaped output. This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented for all models (such as downloading or saving). Parameters: sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`): Height and width of input/output sample. in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample. out_channels (`int`, *optional*, defaults to 4): Number of channels in the output. center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample. flip_sin_to_cos (`bool`, *optional*, defaults to `False`): Whether to flip the sin to cos in the time embedding. freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding. down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`): The tuple of downsample blocks to use. mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`): Block type for middle of UNet, it can be either `UNetMidBlock2DCrossAttn` or `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped. up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`): The tuple of upsample blocks to use. only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`): Whether to include self-attention in the basic transformer blocks, see [`~models.attention.BasicTransformerBlock`]. block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`): The tuple of output channels for each block. layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block. downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution. mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block. act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use. norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization. If `None`, normalization and activation layers is skipped in post-processing. norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization. cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280): The dimension of the cross attention features. transformer_layers_per_block (`int` or `Tuple[int]`, *optional*, defaults to 1): The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`], [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`]. encoder_hid_dim (`int`, *optional*, defaults to None): If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim` dimension to `cross_attention_dim`. encoder_hid_dim_type (`str`, *optional*, defaults to `None`): If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`. attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads. num_attention_heads (`int`, *optional*): The number of attention heads. If not defined, defaults to `attention_head_dim` resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`. class_embed_type (`str`, *optional*, defaults to `None`): The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`, `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`. addition_embed_type (`str`, *optional*, defaults to `None`): Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or "text". "text" will use the `TextTimeEmbedding` layer. addition_time_embed_dim: (`int`, *optional*, defaults to `None`): Dimension for the timestep embeddings. num_class_embeds (`int`, *optional*, defaults to `None`): Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing class conditioning with `class_embed_type` equal to `None`. time_embedding_type (`str`, *optional*, defaults to `positional`): The type of position embedding to use for timesteps. Choose from `positional` or `fourier`. time_embedding_dim (`int`, *optional*, defaults to `None`): An optional override for the dimension of the projected time embedding. time_embedding_act_fn (`str`, *optional*, defaults to `None`): Optional activation function to use only once on the time embeddings before they are passed to the rest of the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`. timestep_post_act (`str`, *optional*, defaults to `None`): The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`. time_cond_proj_dim (`int`, *optional*, defaults to `None`): The dimension of `cond_proj` layer in the timestep embedding. conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer. conv_out_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_out` layer. projection_class_embeddings_input_dim (`int`, *optional*): The dimension of the `class_labels` input when `class_embed_type="projection"`. Required when `class_embed_type="projection"`. class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time embeddings with the class embeddings. mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`): Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False` otherwise. """ _supports_gradient_checkpointing = True @register_to_config def __init__( self, sample_size: Optional[int] = None, in_channels: int = 4, out_channels: int = 4, center_input_sample: bool = False, flip_sin_to_cos: bool = True, freq_shift: int = 0, down_block_types: Tuple[str] = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ), mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn", up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"), only_cross_attention: Union[bool, Tuple[bool]] = False, block_out_channels: Tuple[int] = (320, 640, 1280, 1280), layers_per_block: Union[int, Tuple[int]] = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: Optional[int] = 32, norm_eps: float = 1e-5, cross_attention_dim: Union[int, Tuple[int]] = 1280, transformer_layers_per_block: Union[int, Tuple[int]] = 1, encoder_hid_dim: Optional[int] = None, encoder_hid_dim_type: Optional[str] = None, attention_head_dim: Union[int, Tuple[int]] = 8, num_attention_heads: Optional[Union[int, Tuple[int]]] = None, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, addition_embed_type: Optional[str] = None, addition_time_embed_dim: Optional[int] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", resnet_skip_time_act: bool = False, resnet_out_scale_factor: int = 1.0, time_embedding_type: str = "positional", time_embedding_dim: Optional[int] = None, time_embedding_act_fn: Optional[str] = None, timestep_post_act: Optional[str] = None, time_cond_proj_dim: Optional[int] = None, conv_in_kernel: int = 3, conv_out_kernel: int = 3, projection_class_embeddings_input_dim: Optional[int] = None, attention_type: str = "default", class_embeddings_concat: bool = False, mid_block_only_cross_attention: Optional[bool] = None, cross_attention_norm: Optional[str] = None, addition_embed_type_num_heads=64, ): super().__init__() self.sample_size = sample_size if num_attention_heads is not None: raise ValueError( "At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19." ) # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. num_attention_heads = num_attention_heads or attention_head_dim # Check inputs if len(down_block_types) != len(up_block_types): raise ValueError( 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}." ) if len(block_out_channels) != len(down_block_types): raise ValueError( 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}." ) if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types): raise ValueError( 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}." ) if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types): raise ValueError( f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}." ) if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types): raise ValueError( 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}." ) if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types): raise ValueError( f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}." ) if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types): raise ValueError( f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}." ) # input conv_in_padding = (conv_in_kernel - 1) // 2 self.conv_in = nn.Conv2d( in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding ) # time if time_embedding_type == "fourier": time_embed_dim = time_embedding_dim or block_out_channels[0] * 2 if time_embed_dim % 2 != 0: raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.") self.time_proj = GaussianFourierProjection( time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos ) timestep_input_dim = time_embed_dim elif time_embedding_type == "positional": time_embed_dim = time_embedding_dim or block_out_channels[0] * 4 self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] else: raise ValueError( f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`." ) self.time_embedding = TimestepEmbedding( timestep_input_dim, time_embed_dim, act_fn=act_fn, post_act_fn=timestep_post_act, cond_proj_dim=time_cond_proj_dim, ) if encoder_hid_dim_type is None and encoder_hid_dim is not None: encoder_hid_dim_type = "text_proj" self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type) logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.") if encoder_hid_dim is None and encoder_hid_dim_type is not None: raise ValueError( f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}." ) if encoder_hid_dim_type == "text_proj": self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim) elif encoder_hid_dim_type == "text_image_proj": # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use # case when `addition_embed_type == "text_image_proj"` (Kadinsky 2.1)` self.encoder_hid_proj = TextImageProjection( text_embed_dim=encoder_hid_dim, image_embed_dim=cross_attention_dim, cross_attention_dim=cross_attention_dim, ) elif encoder_hid_dim_type == "image_proj": # Kandinsky 2.2 self.encoder_hid_proj = ImageProjection( image_embed_dim=encoder_hid_dim, cross_attention_dim=cross_attention_dim, ) elif encoder_hid_dim_type is not None: raise ValueError( f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'." ) else: self.encoder_hid_proj = None # class embedding if class_embed_type is None and num_class_embeds is not None: self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim) elif class_embed_type == "timestep": self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) elif class_embed_type == "projection": if projection_class_embeddings_input_dim is None: raise ValueError( "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set" ) # The projection `class_embed_type` is the same as the timestep `class_embed_type` except # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings # 2. it projects from an arbitrary input dimension. # # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations. # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings. # As a result, `TimestepEmbedding` can be passed arbitrary vectors. self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) elif class_embed_type == "simple_projection": if projection_class_embeddings_input_dim is None: raise ValueError( "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set" ) self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim) else: self.class_embedding = None if addition_embed_type == "text": if encoder_hid_dim is not None: text_time_embedding_from_dim = encoder_hid_dim else: text_time_embedding_from_dim = cross_attention_dim self.add_embedding = TextTimeEmbedding( text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads ) elif addition_embed_type == "text_image": # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use # case when `addition_embed_type == "text_image"` (Kadinsky 2.1)` self.add_embedding = TextImageTimeEmbedding( text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim ) elif addition_embed_type == "text_time": self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift) self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) elif addition_embed_type == "image": # Kandinsky 2.2 self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim) elif addition_embed_type == "image_hint": # Kandinsky 2.2 ControlNet self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim) elif addition_embed_type is not None: raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.") if time_embedding_act_fn is None: self.time_embed_act = None else: self.time_embed_act = get_activation(time_embedding_act_fn) self.down_blocks = nn.ModuleList([]) self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): if mid_block_only_cross_attention is None: mid_block_only_cross_attention = only_cross_attention only_cross_attention = [only_cross_attention] * len(down_block_types) if mid_block_only_cross_attention is None: mid_block_only_cross_attention = False if isinstance(num_attention_heads, int): num_attention_heads = (num_attention_heads,) * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) if isinstance(cross_attention_dim, int): cross_attention_dim = (cross_attention_dim,) * len(down_block_types) if isinstance(layers_per_block, int): layers_per_block = [layers_per_block] * len(down_block_types) if isinstance(transformer_layers_per_block, int): transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types) if class_embeddings_concat: # The time embeddings are concatenated with the class embeddings. The dimension of the # time embeddings passed to the down, middle, and up blocks is twice the dimension of the # regular time embeddings blocks_time_embed_dim = time_embed_dim * 2 else: blocks_time_embed_dim = time_embed_dim # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 down_block = get_down_block( down_block_type, num_layers=layers_per_block[i], transformer_layers_per_block=transformer_layers_per_block[i], in_channels=input_channel, out_channels=output_channel, temb_channels=blocks_time_embed_dim, add_downsample=not is_final_block, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim[i], num_attention_heads=num_attention_heads[i], downsample_padding=downsample_padding, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, attention_type=attention_type, resnet_skip_time_act=resnet_skip_time_act, resnet_out_scale_factor=resnet_out_scale_factor, cross_attention_norm=cross_attention_norm, attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel, ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlock2DCrossAttn": self.mid_block = UNetMidBlock2DCrossAttn( transformer_layers_per_block=transformer_layers_per_block[-1], in_channels=block_out_channels[-1], temb_channels=blocks_time_embed_dim, resnet_eps=norm_eps, resnet_act_fn=act_fn, output_scale_factor=mid_block_scale_factor, resnet_time_scale_shift=resnet_time_scale_shift, cross_attention_dim=cross_attention_dim[-1], num_attention_heads=num_attention_heads[-1], resnet_groups=norm_num_groups, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, upcast_attention=upcast_attention, attention_type=attention_type, ) elif mid_block_type == "UNetMidBlock2DSimpleCrossAttn": self.mid_block = UNetMidBlock2DSimpleCrossAttn( in_channels=block_out_channels[-1], temb_channels=blocks_time_embed_dim, resnet_eps=norm_eps, resnet_act_fn=act_fn, output_scale_factor=mid_block_scale_factor, cross_attention_dim=cross_attention_dim[-1], attention_head_dim=attention_head_dim[-1], resnet_groups=norm_num_groups, resnet_time_scale_shift=resnet_time_scale_shift, skip_time_act=resnet_skip_time_act, only_cross_attention=mid_block_only_cross_attention, cross_attention_norm=cross_attention_norm, ) elif mid_block_type is None: self.mid_block = None else: raise ValueError(f"unknown mid_block_type : {mid_block_type}") # count how many layers upsample the images self.num_upsamplers = 0 # up reversed_block_out_channels = list(reversed(block_out_channels)) reversed_num_attention_heads = list(reversed(num_attention_heads)) reversed_layers_per_block = list(reversed(layers_per_block)) reversed_cross_attention_dim = list(reversed(cross_attention_dim)) reversed_transformer_layers_per_block = list(reversed(transformer_layers_per_block)) only_cross_attention = list(reversed(only_cross_attention)) output_channel = reversed_block_out_channels[0] for i, up_block_type in enumerate(up_block_types): is_final_block = i == len(block_out_channels) - 1 prev_output_channel = output_channel output_channel = reversed_block_out_channels[i] input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)] # add upsample block for all BUT final layer if not is_final_block: add_upsample = True self.num_upsamplers += 1 else: add_upsample = False up_block = get_up_block( up_block_type, num_layers=reversed_layers_per_block[i] + 1, transformer_layers_per_block=reversed_transformer_layers_per_block[i], in_channels=input_channel, out_channels=output_channel, prev_output_channel=prev_output_channel, temb_channels=blocks_time_embed_dim, add_upsample=add_upsample, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=reversed_cross_attention_dim[i], num_attention_heads=reversed_num_attention_heads[i], dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, attention_type=attention_type, resnet_skip_time_act=resnet_skip_time_act, resnet_out_scale_factor=resnet_out_scale_factor, cross_attention_norm=cross_attention_norm, attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel, ) self.up_blocks.append(up_block) prev_output_channel = output_channel # out if norm_num_groups is not None: self.conv_norm_out = nn.GroupNorm( num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps ) self.conv_act = get_activation(act_fn) else: self.conv_norm_out = None self.conv_act = None conv_out_padding = (conv_out_kernel - 1) // 2 self.conv_out = nn.Conv2d( block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding ) if attention_type == "gated": positive_len = 768 if isinstance(cross_attention_dim, int): positive_len = cross_attention_dim elif isinstance(cross_attention_dim, tuple) or isinstance(cross_attention_dim, list): positive_len = cross_attention_dim[0] self.position_net = PositionNet(positive_len=positive_len, out_dim=cross_attention_dim) @property def attn_processors(self) -> Dict[str, AttentionProcessor]: r""" Returns: `dict` of attention processors: A dictionary containing all attention processors used in the model with indexed by its weight name. """ # set recursively processors = {} def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]): if hasattr(module, "set_processor"): processors[f"{name}.processor"] = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(f"{name}.{sub_name}", child, processors) return processors for name, module in self.named_children(): fn_recursive_add_processors(name, module, processors) return processors def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]): r""" Sets the attention processor to use to compute attention. Parameters: processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`): The instantiated processor class or a dictionary of processor classes that will be set as the processor for **all** `Attention` layers. If `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. """ count = len(self.attn_processors.keys()) if isinstance(processor, dict) and len(processor) != count: raise ValueError( f"A dict of processors was passed, but the number of processors {len(processor)} does not match the" f" number of attention layers: {count}. Please make sure to pass {count} processor classes." ) def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor): if hasattr(module, "set_processor"): if not isinstance(processor, dict): module.set_processor(processor) else: module.set_processor(processor.pop(f"{name}.processor")) for sub_name, child in module.named_children(): fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor) for name, module in self.named_children(): fn_recursive_attn_processor(name, module, processor) def set_default_attn_processor(self): """ Disables custom attention processors and sets the default attention implementation. """
self.set_attn_processor(AttnProcessor())
0
2023-11-27 13:44:01+00:00
12k
zhenzhiwang/intercontrol
sample/more_people_global_joint_control.py
[ { "identifier": "MultiControlGaussianDiffusion", "path": "diffusion/more_people_control_diffusion.py", "snippet": "class MultiControlGaussianDiffusion(ControlGaussianDiffusion):\n \n def p_sample(\n self,\n model,\n x,\n t,\n clip_denoised=True,\n denoised...
from diffusion.more_people_control_diffusion import MultiControlGaussianDiffusion from diffusion.respace import SpacedDiffusion from utils.fixseed import fixseed from utils.parser_util import edit_interactive_control_args from utils.model_util import load_controlmdm_and_diffusion from utils import dist_util from model.cfg_sampler import wrap_model from data_loaders.get_data import get_dataset_loader from data_loaders.humanml.scripts.motion_process import recover_from_ric from data_loaders.humanml_utils import get_more_people_mask, HML_JOINT_NAMES from data_loaders.humanml.utils.plot_script import plot_3d_motion from model.ControlMDM import ControlMDM import os import numpy as np import torch import data_loaders.humanml.utils.paramUtil as paramUtil import shutil
8,056
# This code is based on https://github.com/openai/guided-diffusion """ Generate a large batch of image samples from a model and save them as a large numpy array. This can be used to produce samples for FID evaluation. """ def main(): args = edit_interactive_control_args() if args.multi_person == False: args.multi_person = True args.dataset = 'humanml' # we only support humanml for now if args.use_posterior == False: args.use_posterior = True fixseed(args.seed) out_path = args.output_dir name = os.path.basename(os.path.dirname(args.model_path)) niter = os.path.basename(args.model_path).replace('model', '').replace('.pt', '') max_frames = 100 if args.dataset in ['kit', 'humanml'] else 60 fps = 12.5 if args.dataset == 'kit' else 20 dist_util.setup_dist(args.device) if out_path == '': out_path = os.path.join(os.path.dirname(args.model_path), 'more_people_{}_{}_seed{}'.format(niter, args.interaction_json.split('/')[-1], args.seed)) print('Loading dataset...') data = get_dataset_loader(name=args.dataset, batch_size=args.batch_size, num_frames=max_frames, split='test', load_mode='train', size=1) # in train mode, you get both text and motion. data.fixed_length = max_frames total_num_samples = args.num_samples * args.num_repetitions print("Creating model and diffusion...") DiffusionClass = MultiControlGaussianDiffusion if args.filter_noise else SpacedDiffusion
# This code is based on https://github.com/openai/guided-diffusion """ Generate a large batch of image samples from a model and save them as a large numpy array. This can be used to produce samples for FID evaluation. """ def main(): args = edit_interactive_control_args() if args.multi_person == False: args.multi_person = True args.dataset = 'humanml' # we only support humanml for now if args.use_posterior == False: args.use_posterior = True fixseed(args.seed) out_path = args.output_dir name = os.path.basename(os.path.dirname(args.model_path)) niter = os.path.basename(args.model_path).replace('model', '').replace('.pt', '') max_frames = 100 if args.dataset in ['kit', 'humanml'] else 60 fps = 12.5 if args.dataset == 'kit' else 20 dist_util.setup_dist(args.device) if out_path == '': out_path = os.path.join(os.path.dirname(args.model_path), 'more_people_{}_{}_seed{}'.format(niter, args.interaction_json.split('/')[-1], args.seed)) print('Loading dataset...') data = get_dataset_loader(name=args.dataset, batch_size=args.batch_size, num_frames=max_frames, split='test', load_mode='train', size=1) # in train mode, you get both text and motion. data.fixed_length = max_frames total_num_samples = args.num_samples * args.num_repetitions print("Creating model and diffusion...") DiffusionClass = MultiControlGaussianDiffusion if args.filter_noise else SpacedDiffusion
model, diffusion = load_controlmdm_and_diffusion(args, data, dist_util.dev(), ModelClass=ControlMDM, DiffusionClass=DiffusionClass)
4
2023-11-27 05:28:02+00:00
12k
AGI-Collective/Robin
robin/model/language_model/mpt/modeling_mpt.py
[ { "identifier": "attn_bias_shape", "path": "robin/model/language_model/mpt/attention.py", "snippet": "def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id):\n if attn_impl == 'flash':\n return None\n elif attn_impl in ['torch', 'triton']:\n if al...
import math import warnings import torch import torch.nn as nn import torch.nn.functional as F from typing import List, Optional, Tuple, Union from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast from .attention import attn_bias_shape, build_attn_bias from .blocks import MPTBlock from .custom_embedding import SharedEmbedding from .norm import NORM_CLASS_REGISTRY from .configuration_mpt import MPTConfig from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm from .meta_init_context import init_empty_weights from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_ from .flash_attn_triton import flash_attn_func
9,432
assert isinstance(attn_bias, torch.Tensor) attn_bias = self._apply_sequence_id(attn_bias, sequence_id) if attention_mask is not None: s_k = attention_mask.shape[-1] if attn_bias is None: attn_bias = torch.zeros((1, 1, 1, s_k), device=device, dtype=dtype) else: _s_k = max(0, attn_bias.size(-1) - s_k) attn_bias = attn_bias[:, :, :, _s_k:] if prefix_mask is not None and attention_mask.shape != prefix_mask.shape: raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.') min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val) return (attn_bias, None) def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor): (s_k, s_q) = attn_bias.shape[-2:] if s_k != self.config.max_seq_len or s_q != self.config.max_seq_len: raise ValueError('attn_bias does not match the expected shape. ' + f'The last two dimensions should both be {self.config.max_length} ' + f'but are {s_k} and {s_q}.') seq_len = prefix_mask.shape[-1] if seq_len > self.config.max_seq_len: raise ValueError(f'prefix_mask sequence length cannot exceed max_seq_len={self.config.max_seq_len}') attn_bias = attn_bias[..., :seq_len, :seq_len] causal = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool, device=prefix_mask.device)).view(1, 1, seq_len, seq_len) prefix = prefix_mask.view(-1, 1, 1, seq_len) cannot_attend = ~torch.logical_or(causal, prefix.bool()) min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(cannot_attend, min_val) return attn_bias def _apply_sequence_id(self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor): seq_len = sequence_id.shape[-1] if seq_len > self.config.max_seq_len: raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}') attn_bias = attn_bias[..., :seq_len, :seq_len] cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1) min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(cannot_attend, min_val) return attn_bias def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.Tensor]=None): return_dict = return_dict if return_dict is not None else self.config.return_dict use_cache = use_cache if use_cache is not None else self.config.use_cache if attention_mask is not None: attention_mask = attention_mask.bool() if prefix_mask is not None: prefix_mask = prefix_mask.bool() if not return_dict: raise NotImplementedError('return_dict False is not implemented yet for MPT') if output_attentions: if self.attn_impl != 'torch': raise NotImplementedError('output_attentions is not implemented for MPT when using attn_impl `flash` or `triton`.') if attention_mask is not None and attention_mask[:, 0].sum() != attention_mask.shape[0] and self.training: raise NotImplementedError('MPT does not support training with left padding.') if self.prefix_lm and prefix_mask is None: raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.') if self.training: if self.attn_uses_sequence_id and sequence_id is None: raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.') elif self.attn_uses_sequence_id is False and sequence_id is not None: warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.') if input_ids is not None: S = input_ids.size(1) assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}' tok_emb = self.wte(input_ids) else: assert inputs_embeds is not None assert self.alibi, 'inputs_embeds is not implemented for MPT unless for alibi.' S = inputs_embeds.size(1) tok_emb = inputs_embeds if self.alibi: x = tok_emb else: past_position = 0 if past_key_values is not None: if len(past_key_values) != self.config.n_layers: raise ValueError(f'past_key_values must provide a past_key_value for each attention ' + f'layer in the network (len(past_key_values)={len(past_key_values)!r}; self.config.n_layers={self.config.n_layers!r}).') past_position = past_key_values[0][0].size(1) if self.attn_impl == 'torch': past_position = past_key_values[0][0].size(3) if S + past_position > self.config.max_seq_len: raise ValueError(f'Cannot forward input with past sequence length {past_position} and current sequence length {S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.') pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_ids.device).unsqueeze(0) if attention_mask is not None: pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0) pos_emb = self.wpe(pos) x = tok_emb + pos_emb if self.embedding_fraction == 1: x = self.emb_drop(x) else: x_shrunk = x * self.embedding_fraction + x.detach() * (1 - self.embedding_fraction) assert isinstance(self.emb_drop, nn.Module) x = self.emb_drop(x_shrunk) (attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id) if use_cache and past_key_values is None: past_key_values = [() for _ in range(self.config.n_layers)] all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None for (b_idx, block) in enumerate(self.blocks): if output_hidden_states: assert all_hidden_states is not None all_hidden_states = all_hidden_states + (x,) past_key_value = past_key_values[b_idx] if past_key_values is not None else None if self.gradient_checkpointing and self.training: (x, attn_weights, past_key_value) = torch.utils.checkpoint.checkpoint(block, x, past_key_value, attn_bias, attention_mask, self.is_causal) else: (x, attn_weights, past_key_value) = block(x, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=self.is_causal) if past_key_values is not None: past_key_values[b_idx] = past_key_value if output_attentions: assert all_self_attns is not None all_self_attns = all_self_attns + (attn_weights,) x = self.norm_f(x) if output_hidden_states: assert all_hidden_states is not None all_hidden_states = all_hidden_states + (x,) return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=past_key_values, hidden_states=all_hidden_states, attentions=all_self_attns) def param_init_fn(self, module): init_fn_name = self.config.init_config['name']
"""A simple, flexible implementation of a GPT model. Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py """ try: except: pass Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast] class MPTPreTrainedModel(PreTrainedModel): config_class = MPTConfig base_model_prefix = 'model' _no_split_modules = ['MPTBlock'] class MPTModel(MPTPreTrainedModel): def __init__(self, config: MPTConfig): config._validate_config() super().__init__(config) self.attn_impl = config.attn_config['attn_impl'] self.prefix_lm = config.attn_config['prefix_lm'] self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id'] self.alibi = config.attn_config['alibi'] self.alibi_bias_max = config.attn_config['alibi_bias_max'] if config.init_device == 'mixed': if dist.get_local_rank() == 0: config.init_device = 'cpu' else: config.init_device = 'meta' if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys(): norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys()) raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).') norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()] self.embedding_fraction = config.embedding_fraction self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device) if not self.alibi: self.wpe = torch.nn.Embedding(config.max_seq_len, config.d_model, device=config.init_device) self.emb_drop = nn.Dropout(config.emb_pdrop) self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)]) self.norm_f = norm_class(config.d_model, device=config.init_device) if config.init_device != 'meta': print(f'You are using config.init_device={config.init_device!r}, but you can also use config.init_device="meta" with Composer + FSDP for fast initialization.') self.apply(self.param_init_fn) self.is_causal = not self.prefix_lm self._attn_bias_initialized = False self.attn_bias = None self.attn_bias_shape = attn_bias_shape(self.attn_impl, config.n_heads, config.max_seq_len, self.alibi, prefix_lm=self.prefix_lm, causal=self.is_causal, use_sequence_id=self.attn_uses_sequence_id) if config.no_bias: for module in self.modules(): if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter): if config.verbose: warnings.warn(f'Removing bias ({module.bias}) from {module}.') module.register_parameter('bias', None) if config.verbose and config.verbose > 2: print(self) if 'verbose' not in self.config.init_config: self.config.init_config['verbose'] = self.config.verbose if self.config.init_config['verbose'] > 1: init_fn_name = self.config.init_config['name'] warnings.warn(f'Using {init_fn_name} initialization.') self.gradient_checkpointing = False def get_input_embeddings(self): return self.wte def set_input_embeddings(self, value): self.wte = value @torch.no_grad() def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None): if not self._attn_bias_initialized: if self.attn_bias_shape: self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype) self.attn_bias = build_attn_bias(self.attn_impl, self.attn_bias, self.config.n_heads, self.config.max_seq_len, causal=self.is_causal, alibi=self.alibi, alibi_bias_max=self.alibi_bias_max) self._attn_bias_initialized = True if self.attn_impl == 'flash': return (self.attn_bias, attention_mask) if self.attn_bias is not None: self.attn_bias = self.attn_bias.to(dtype=dtype, device=device) attn_bias = self.attn_bias if self.prefix_lm: assert isinstance(attn_bias, torch.Tensor) assert isinstance(prefix_mask, torch.Tensor) attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask) if self.attn_uses_sequence_id and sequence_id is not None: assert isinstance(attn_bias, torch.Tensor) attn_bias = self._apply_sequence_id(attn_bias, sequence_id) if attention_mask is not None: s_k = attention_mask.shape[-1] if attn_bias is None: attn_bias = torch.zeros((1, 1, 1, s_k), device=device, dtype=dtype) else: _s_k = max(0, attn_bias.size(-1) - s_k) attn_bias = attn_bias[:, :, :, _s_k:] if prefix_mask is not None and attention_mask.shape != prefix_mask.shape: raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.') min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val) return (attn_bias, None) def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor): (s_k, s_q) = attn_bias.shape[-2:] if s_k != self.config.max_seq_len or s_q != self.config.max_seq_len: raise ValueError('attn_bias does not match the expected shape. ' + f'The last two dimensions should both be {self.config.max_length} ' + f'but are {s_k} and {s_q}.') seq_len = prefix_mask.shape[-1] if seq_len > self.config.max_seq_len: raise ValueError(f'prefix_mask sequence length cannot exceed max_seq_len={self.config.max_seq_len}') attn_bias = attn_bias[..., :seq_len, :seq_len] causal = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool, device=prefix_mask.device)).view(1, 1, seq_len, seq_len) prefix = prefix_mask.view(-1, 1, 1, seq_len) cannot_attend = ~torch.logical_or(causal, prefix.bool()) min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(cannot_attend, min_val) return attn_bias def _apply_sequence_id(self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor): seq_len = sequence_id.shape[-1] if seq_len > self.config.max_seq_len: raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}') attn_bias = attn_bias[..., :seq_len, :seq_len] cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1) min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(cannot_attend, min_val) return attn_bias def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.Tensor]=None): return_dict = return_dict if return_dict is not None else self.config.return_dict use_cache = use_cache if use_cache is not None else self.config.use_cache if attention_mask is not None: attention_mask = attention_mask.bool() if prefix_mask is not None: prefix_mask = prefix_mask.bool() if not return_dict: raise NotImplementedError('return_dict False is not implemented yet for MPT') if output_attentions: if self.attn_impl != 'torch': raise NotImplementedError('output_attentions is not implemented for MPT when using attn_impl `flash` or `triton`.') if attention_mask is not None and attention_mask[:, 0].sum() != attention_mask.shape[0] and self.training: raise NotImplementedError('MPT does not support training with left padding.') if self.prefix_lm and prefix_mask is None: raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.') if self.training: if self.attn_uses_sequence_id and sequence_id is None: raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.') elif self.attn_uses_sequence_id is False and sequence_id is not None: warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.') if input_ids is not None: S = input_ids.size(1) assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}' tok_emb = self.wte(input_ids) else: assert inputs_embeds is not None assert self.alibi, 'inputs_embeds is not implemented for MPT unless for alibi.' S = inputs_embeds.size(1) tok_emb = inputs_embeds if self.alibi: x = tok_emb else: past_position = 0 if past_key_values is not None: if len(past_key_values) != self.config.n_layers: raise ValueError(f'past_key_values must provide a past_key_value for each attention ' + f'layer in the network (len(past_key_values)={len(past_key_values)!r}; self.config.n_layers={self.config.n_layers!r}).') past_position = past_key_values[0][0].size(1) if self.attn_impl == 'torch': past_position = past_key_values[0][0].size(3) if S + past_position > self.config.max_seq_len: raise ValueError(f'Cannot forward input with past sequence length {past_position} and current sequence length {S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.') pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_ids.device).unsqueeze(0) if attention_mask is not None: pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0) pos_emb = self.wpe(pos) x = tok_emb + pos_emb if self.embedding_fraction == 1: x = self.emb_drop(x) else: x_shrunk = x * self.embedding_fraction + x.detach() * (1 - self.embedding_fraction) assert isinstance(self.emb_drop, nn.Module) x = self.emb_drop(x_shrunk) (attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id) if use_cache and past_key_values is None: past_key_values = [() for _ in range(self.config.n_layers)] all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None for (b_idx, block) in enumerate(self.blocks): if output_hidden_states: assert all_hidden_states is not None all_hidden_states = all_hidden_states + (x,) past_key_value = past_key_values[b_idx] if past_key_values is not None else None if self.gradient_checkpointing and self.training: (x, attn_weights, past_key_value) = torch.utils.checkpoint.checkpoint(block, x, past_key_value, attn_bias, attention_mask, self.is_causal) else: (x, attn_weights, past_key_value) = block(x, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=self.is_causal) if past_key_values is not None: past_key_values[b_idx] = past_key_value if output_attentions: assert all_self_attns is not None all_self_attns = all_self_attns + (attn_weights,) x = self.norm_f(x) if output_hidden_states: assert all_hidden_states is not None all_hidden_states = all_hidden_states + (x,) return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=past_key_values, hidden_states=all_hidden_states, attentions=all_self_attns) def param_init_fn(self, module): init_fn_name = self.config.init_config['name']
MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
11
2023-11-28 15:25:55+00:00
12k
huangb23/VTimeLLM
vtimellm/model/vtimellm_chatglm.py
[ { "identifier": "ChatGLMConfig", "path": "vtimellm/model/chatglm/configuration_chatglm.py", "snippet": "class ChatGLMConfig(PretrainedConfig):\n model_type = \"chatglm\"\n def __init__(\n self,\n num_layers=28,\n padded_vocab_size=65024,\n hidden_size=4096,\n ffn...
import torch import torch.nn as nn from typing import List, Optional, Tuple, Union from transformers import AutoConfig, AutoModelForCausalLM from .chatglm import ChatGLMConfig, ChatGLMModel, ChatGLMForConditionalGeneration from .vtimellm_arch import VTimeLLMMetaModel, VTimeLLMMetaForCausalLM
8,054
class VTimeLLMChatGLMConfig(ChatGLMConfig): model_type = "VTimeLLM_ChatGLM" class VTimeLLMChatGLMModel(ChatGLMModel, VTimeLLMMetaModel): config_class = VTimeLLMChatGLMConfig def __init__(self, config, empty_init=True, device=None): super(VTimeLLMChatGLMModel, self).__init__(config, empty_init=empty_init, device=device)
class VTimeLLMChatGLMConfig(ChatGLMConfig): model_type = "VTimeLLM_ChatGLM" class VTimeLLMChatGLMModel(ChatGLMModel, VTimeLLMMetaModel): config_class = VTimeLLMChatGLMConfig def __init__(self, config, empty_init=True, device=None): super(VTimeLLMChatGLMModel, self).__init__(config, empty_init=empty_init, device=device)
class VTimeLLMChatGLMForCausalLM(ChatGLMForConditionalGeneration, VTimeLLMMetaForCausalLM):
2
2023-11-28 06:33:42+00:00
12k
moonbow721/DPoser
run/smplify.py
[ { "identifier": "sde_lib", "path": "lib/algorithms/advanced/sde_lib.py", "snippet": "class SDE(abc.ABC):\n class RSDE(self.__class__):\nclass VPSDE(SDE):\nclass subVPSDE(SDE):\nclass VESDE(SDE):\n def __init__(self, N):\n def T(self):\n def sde(self, x, t):\n def marginal_prob(self, x...
import math import torch from torch import nn from tqdm import tqdm from lib.algorithms.advanced import sde_lib, sampling from lib.algorithms.advanced import utils as mutils from lib.algorithms.advanced.model import ScoreModelFC from lib.algorithms.ema import ExponentialMovingAverage from lib.body_model import constants from lib.body_model.fitting_losses import camera_fitting_loss, body_fitting_loss from lib.dataset.AMASS import N_POSES, Posenormalizer from lib.utils.generic import import_configs from lib.utils.misc import linear_interpolation
7,548
class DPoser(nn.Module): def __init__(self, batch_size=32, config_path='', args=None): super().__init__() self.device = args.device self.batch_size = batch_size config = import_configs(config_path) self.Normalizer = Posenormalizer( data_path=f'{args.dataset_folder}/{args.version}/train', min_max=config.data.min_max, rot_rep=config.data.rot_rep, device=args.device) diffusion_model = self.load_model(config, args) if config.training.sde.lower() == 'vpsde': sde = sde_lib.VPSDE(beta_min=config.model.beta_min, beta_max=config.model.beta_max, N=config.model.num_scales) elif config.training.sde.lower() == 'subvpsde': sde = sde_lib.subVPSDE(beta_min=config.model.beta_min, beta_max=config.model.beta_max, N=config.model.num_scales) elif config.training.sde.lower() == 'vesde': sde = sde_lib.VESDE(sigma_min=config.model.sigma_min, sigma_max=config.model.sigma_max, N=config.model.num_scales) else: raise NotImplementedError(f"SDE {config.training.sde} unknown.") sde.N = args.sde_N # fewer sampling steps self.sde = sde self.score_fn = mutils.get_score_fn(sde, diffusion_model, train=False, continuous=config.training.continuous) self.rsde = sde.reverse(self.score_fn, False) # L2 loss self.loss_fn = nn.MSELoss(reduction='none') self.timesteps = torch.linspace(self.sde.T, 1e-3, self.sde.N, device=self.device) def load_model(self, config, args): POSE_DIM = 3 if config.data.rot_rep == 'axis' else 6 model = ScoreModelFC( config,
class DPoser(nn.Module): def __init__(self, batch_size=32, config_path='', args=None): super().__init__() self.device = args.device self.batch_size = batch_size config = import_configs(config_path) self.Normalizer = Posenormalizer( data_path=f'{args.dataset_folder}/{args.version}/train', min_max=config.data.min_max, rot_rep=config.data.rot_rep, device=args.device) diffusion_model = self.load_model(config, args) if config.training.sde.lower() == 'vpsde': sde = sde_lib.VPSDE(beta_min=config.model.beta_min, beta_max=config.model.beta_max, N=config.model.num_scales) elif config.training.sde.lower() == 'subvpsde': sde = sde_lib.subVPSDE(beta_min=config.model.beta_min, beta_max=config.model.beta_max, N=config.model.num_scales) elif config.training.sde.lower() == 'vesde': sde = sde_lib.VESDE(sigma_min=config.model.sigma_min, sigma_max=config.model.sigma_max, N=config.model.num_scales) else: raise NotImplementedError(f"SDE {config.training.sde} unknown.") sde.N = args.sde_N # fewer sampling steps self.sde = sde self.score_fn = mutils.get_score_fn(sde, diffusion_model, train=False, continuous=config.training.continuous) self.rsde = sde.reverse(self.score_fn, False) # L2 loss self.loss_fn = nn.MSELoss(reduction='none') self.timesteps = torch.linspace(self.sde.T, 1e-3, self.sde.N, device=self.device) def load_model(self, config, args): POSE_DIM = 3 if config.data.rot_rep == 'axis' else 6 model = ScoreModelFC( config,
n_poses=N_POSES,
8
2023-11-29 15:55:50+00:00
12k
raven38/EfficientDynamic3DGaussian
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 T...
import torch import os import sys import glob import numpy as np import json 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 scene.hyper_camera import Camera as HyperNeRFCamera
9,697
cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=width, height=height, time=time) test_cam_infos.append(cam_info) if not eval: train_cam_infos.extend(test_cam_infos) test_cam_infos = [] widht, height = train_cam_infos[0].width, train_cam_infos[0].height # Sample N_views poses for validation - NeRF-like camera trajectory. N_views = 120 val_poses = get_spiral(poses, near_fars, N_views=N_views) val_times = torch.linspace(0.0, 1.0, val_poses.shape[0]) vis_cam_infos = [] for idx, (pose, time) in enumerate(zip(val_poses, val_times)): p = pose uid = idx pose = np.eye(4) pose[:3, :] = p[:3, :] R = -pose[:3, :3] R[:, 0] = -R[:, 0] T = -pose[:3, 3].dot(R) # R = pose[:3, :3] # T = pose[:3, 3] FovY = focal2fov(focal, height) FovX = focal2fov(focal, width) cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=None, image_name=None, width=width, height=height, time=time) vis_cam_infos.append(cam_info) nerf_normalization = getNerfppNorm(train_cam_infos) ply_path = os.path.join(path, "points3d_ours.ply") if not os.path.exists(ply_path): # Since this data set has no colmap data, we start with random points num_pts = 2_000 # 100_000 print(f"Generating random point cloud ({num_pts})...") threshold = 3 xyz_max = np.array([1.5*threshold, 1.5*threshold, -0*threshold]) xyz_min = np.array([-1.5*threshold, -1.5*threshold, -1.5*threshold]) xyz = np.concatenate([(np.random.random((num_pts, 1, 3)))* (xyz_max-xyz_min) + xyz_min, np.zeros((num_pts, 16, 3))], axis=1) # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3))], axis=1) shs = np.random.random((num_pts, 3)) / 255.0 pcd = BasicPointCloud(points=xyz, colors=SH2RGB(shs), normals=np.zeros((num_pts, 3))) storePly(ply_path, xyz, SH2RGB(shs) * 255) pcd = fetchPly(ply_path) scene_info = SceneInfo(point_cloud=pcd, train_cameras=train_cam_infos, test_cameras=test_cam_infos, vis_cameras =vis_cam_infos, nerf_normalization=nerf_normalization, ply_path=ply_path, time_delta=1/300) return scene_info def readHypernerfCamera(uid, camera, image_path, time): height, width = int(camera.image_shape[0]), int(camera.image_shape[1]) image_name = os.path.basename(image_path).split(".")[0] R = camera.orientation.T # T = camera.translation.T T = - camera.position @ R image = Image.open(image_path) FovY = focal2fov(camera.focal_length, height) FovX = focal2fov(camera.focal_length, width) return CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=width, height=height, time=time) def readHypernerfSceneInfo(path, eval): # borrow code from https://github.com/hustvl/TiNeuVox/blob/main/lib/load_hyper.py use_bg_points = False with open(f'{path}/scene.json', 'r') as f: scene_json = json.load(f) with open(f'{path}/metadata.json', 'r') as f: meta_json = json.load(f) with open(f'{path}/dataset.json', 'r') as f: dataset_json = json.load(f) near = scene_json['near'] far = scene_json['far'] coord_scale = scene_json['scale'] scene_center = scene_json['center'] all_imgs = dataset_json['ids'] val_ids = dataset_json['val_ids'] add_cam = False if len(val_ids) == 0: i_train = np.array([i for i in np.arange(len(all_imgs)) if (i%4 == 0)]) i_test = i_train+2 i_test = i_test[:-1,] else: add_cam = True train_ids = dataset_json['train_ids'] i_test = [] i_train = [] for i in range(len(all_imgs)): id = all_imgs[i] if id in val_ids: i_test.append(i) if id in train_ids: i_train.append(i) print('i_train',i_train) print('i_test',i_test) all_cams = [meta_json[i]['camera_id'] for i in all_imgs] all_times = [meta_json[i]['time_id'] for i in all_imgs] max_time = max(all_times) all_times = [meta_json[i]['time_id']/max_time for i in all_imgs] selected_time = set(all_times) ratio = 0.5 all_cam_params = [] for im in all_imgs:
# # 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 george.drettakis@inria.fr # class CameraInfo(NamedTuple): uid: int R: np.array T: np.array FovY: np.array FovX: np.array image: np.array image_path: str image_name: str width: int height: int time: float class SceneInfo(NamedTuple): point_cloud: BasicPointCloud train_cameras: list test_cameras: list vis_cameras: list nerf_normalization: dict ply_path: str time_delta: float def normalize(v): """Normalize a vector.""" return v / np.linalg.norm(v) def average_poses(poses): """ Calculate the average pose, which is then used to center all poses using @center_poses. Its computation is as follows: 1. Compute the center: the average of pose centers. 2. Compute the z axis: the normalized average z axis. 3. Compute axis y': the average y axis. 4. Compute x' = y' cross product z, then normalize it as the x axis. 5. Compute the y axis: z cross product x. Note that at step 3, we cannot directly use y' as y axis since it's not necessarily orthogonal to z axis. We need to pass from x to y. Inputs: poses: (N_images, 3, 4) Outputs: pose_avg: (3, 4) the average pose """ # 1. Compute the center center = poses[..., 3].mean(0) # (3) # 2. Compute the z axis z = normalize(poses[..., 2].mean(0)) # (3) # 3. Compute axis y' (no need to normalize as it's not the final output) y_ = poses[..., 1].mean(0) # (3) # 4. Compute the x axis x = normalize(np.cross(z, y_)) # (3) # 5. Compute the y axis (as z and x are normalized, y is already of norm 1) y = np.cross(x, z) # (3) pose_avg = np.stack([x, y, z, center], 1) # (3, 4) return pose_avg def center_poses(poses, blender2opencv): """ Center the poses so that we can use NDC. See https://github.com/bmild/nerf/issues/34 Inputs: poses: (N_images, 3, 4) Outputs: poses_centered: (N_images, 3, 4) the centered poses pose_avg: (3, 4) the average pose """ poses = poses @ blender2opencv pose_avg = average_poses(poses) # (3, 4) pose_avg_homo = np.eye(4) pose_avg_homo[ :3 ] = pose_avg # convert to homogeneous coordinate for faster computation pose_avg_homo = pose_avg_homo # by simply adding 0, 0, 0, 1 as the last row last_row = np.tile(np.array([0, 0, 0, 1]), (len(poses), 1, 1)) # (N_images, 1, 4) poses_homo = np.concatenate( [poses, last_row], 1 ) # (N_images, 4, 4) homogeneous coordinate poses_centered = np.linalg.inv(pose_avg_homo) @ poses_homo # (N_images, 4, 4) # poses_centered = poses_centered @ blender2opencv poses_centered = poses_centered[:, :3] # (N_images, 3, 4) return poses_centered, pose_avg_homo 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) FovX = focal2fov(focal_length_x, width) elif intr.model=="PINHOLE": focal_length_x = intr.params[0] focal_length_y = intr.params[1] FovY = focal2fov(focal_length_y, height) FovX = focal2fov(focal_length_x, width) else: assert False, "Colmap camera model not handled: only undistorted datasets (PINHOLE or SIMPLE_PINHOLE cameras) supported!" image_path = os.path.join(images_folder, os.path.basename(extr.name)) image_name = os.path.basename(image_path).split(".")[0] image = Image.open(image_path) cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=width, height=height, time=0) cam_infos.append(cam_info) sys.stdout.write('\n') return cam_infos def fetchPly(path): plydata = PlyData.read(path) vertices = plydata['vertex'] colors = np.vstack([vertices['red'], vertices['green'], vertices['blue']]).T / 255.0 normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T x_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("x")] y_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("y")] z_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("z")] x_names = sorted(x_names, key = lambda x: int(x.replace('x', ''))) y_names = sorted(y_names, key = lambda y: int(y.replace('y', ''))) z_names = sorted(z_names, key = lambda z: int(z.replace('z', ''))) assert len(x_names) == len(y_names) == len(z_names) x = np.zeros((colors.shape[0], len(x_names))) y = np.zeros((colors.shape[0], len(y_names))) z = np.zeros((colors.shape[0], len(z_names))) for idx, attr_name in enumerate(x_names): x[:, idx] = np.asarray(plydata.elements[0][attr_name]) for idx, attr_name in enumerate(y_names): y[:, idx] = np.asarray(plydata.elements[0][attr_name]) for idx, attr_name in enumerate(z_names): z[:, idx] = np.asarray(plydata.elements[0][attr_name]) # positions = np.vstack([vertices['x'], vertices['y'], vertices['z']]).T positions = np.stack([x, y, z], axis=-1) assert len(positions.shape) == 3 assert positions.shape[-1] == 3 return BasicPointCloud(points=positions, colors=colors, normals=normals) def storePly(path, xyz, rgb): # Define the dtype for the structured array dtype = [] for t in range(xyz.shape[1]): dtype.extend([(f'x{t}', 'f4'), (f'y{t}', 'f4'), (f'z{t}', 'f4')]) dtype = dtype + [('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'), ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')] normals = np.zeros_like(xyz[:, 0, :]) elements = np.empty(xyz.shape[0], dtype=dtype) attributes = np.concatenate((xyz.reshape(xyz.shape[0], -1), normals, rgb), axis=1) elements[:] = list(map(tuple, attributes)) # Create the PlyData object and write to file vertex_element = PlyElement.describe(elements, 'vertex') ply_data = PlyData([vertex_element]) ply_data.write(path) def readColmapSceneInfo(path, images, eval, llffhold=8): try: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.bin") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.bin") cam_extrinsics = read_extrinsics_binary(cameras_extrinsic_file) cam_intrinsics = read_intrinsics_binary(cameras_intrinsic_file) except: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.txt") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.txt") cam_extrinsics = read_extrinsics_text(cameras_extrinsic_file) cam_intrinsics = read_intrinsics_text(cameras_intrinsic_file) reading_dir = "images" if images == None else images cam_infos_unsorted = readColmapCameras(cam_extrinsics=cam_extrinsics, cam_intrinsics=cam_intrinsics, images_folder=os.path.join(path, reading_dir)) cam_infos = sorted(cam_infos_unsorted.copy(), key = lambda x : x.image_name) if eval: train_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold != 0] test_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold == 0] else: train_cam_infos = cam_infos test_cam_infos = [] nerf_normalization = getNerfppNorm(train_cam_infos) ply_path = os.path.join(path, "sparse/0/points3D_ours.ply") bin_path = os.path.join(path, "sparse/0/points3D.bin") txt_path = os.path.join(path, "sparse/0/points3D.txt") if not os.path.exists(ply_path): print("Converting point3d.bin to .ply, will happen only the first time you open the scene.") try: xyz, rgb, _ = read_points3D_binary(bin_path) except: xyz, rgb, _ = read_points3D_text(txt_path) xyz = xyz[:, None, :] storePly(ply_path, xyz, rgb) try: pcd = fetchPly(ply_path) except: pcd = None scene_info = SceneInfo(point_cloud=pcd, train_cameras=train_cam_infos, test_cameras=test_cam_infos, nerf_normalization=nerf_normalization, ply_path=ply_path) return scene_info def readCamerasFromTransforms(path, transformsfile, white_background, extension=".png"): cam_infos = [] with open(os.path.join(path, transformsfile)) as json_file: contents = json.load(json_file) fovx = contents["camera_angle_x"] frames = contents["frames"] # if 'time' in frames[0]: # times = np.array([frame['time'] for idx, frame in enumerate(frames)]) # time_idx = times.argsort() # else: # time_idx = [0 for f in frames] # print(times) # print(time_idx) for idx, frame in enumerate(frames): cam_name = os.path.join(path, frame["file_path"] + extension) # NeRF 'transform_matrix' is a camera-to-world transform c2w = np.array(frame["transform_matrix"]) # change from OpenGL/Blender camera axes (Y up, Z back) to COLMAP (Y down, Z forward) c2w[:3, 1:3] *= -1 # get the world-to-camera transform and set R, T w2c = np.linalg.inv(c2w) R = np.transpose(w2c[:3,:3]) # R is stored transposed due to 'glm' in CUDA code T = w2c[:3, 3] image_path = os.path.join(path, cam_name) image_name = Path(cam_name).stem image = Image.open(image_path) im_data = np.array(image.convert("RGBA")) bg = np.array([1,1,1]) if white_background else np.array([0, 0, 0]) norm_data = im_data / 255.0 arr = norm_data[:,:,:3] * norm_data[:, :, 3:4] + bg * (1 - norm_data[:, :, 3:4]) image = Image.fromarray(np.array(arr*255.0, dtype=np.byte), "RGB") fovy = focal2fov(fov2focal(fovx, image.size[0]), image.size[1]) FovY = fovy FovX = fovx time = frame['time'] if 'time' in frame else 0 cam_infos.append(CameraInfo(uid=idx, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=image.size[0], height=image.size[1], time=time)) return cam_infos # https://github.com/albertpumarola/D-NeRF/blob/main/load_blender.py trans_t = lambda t : torch.Tensor([ [1,0,0,0], [0,1,0,0], [0,0,1,t], [0,0,0,1]]).float() rot_phi = lambda phi : torch.Tensor([ [1,0,0,0], [0,np.cos(phi),-np.sin(phi),0], [0,np.sin(phi), np.cos(phi),0], [0,0,0,1]]).float() rot_theta = lambda th : torch.Tensor([ [np.cos(th),0,-np.sin(th),0], [0,1,0,0], [np.sin(th),0, np.cos(th),0], [0,0,0,1]]).float() def pose_spherical(theta, phi, radius): # https://github.com/albertpumarola/D-NeRF/blob/main/load_blender.py c2w = trans_t(radius) c2w = rot_phi(phi/180.*np.pi) @ c2w c2w = rot_theta(theta/180.*np.pi) @ c2w c2w = torch.Tensor(np.array([[-1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]])) @ c2w return c2w def generateCamerasFromTransforms(path, transformsfile, extension=".png"): cam_infos = [] # https://github.com/albertpumarola/D-NeRF/blob/main/load_blender.py render_poses = torch.stack([pose_spherical(angle, -30.0, 4.0) for angle in np.linspace(-180,180,40+1)[:-1]], 0) render_times = torch.linspace(0., 1., render_poses.shape[0]) with open(os.path.join(path, transformsfile)) as json_file: contents = json.load(json_file) fovx = contents["camera_angle_x"] frames = contents["frames"] cam_name = os.path.join(path, frames[0]["file_path"] + extension) image_path = os.path.join(path, cam_name) image_name = Path(cam_name).stem image = Image.open(image_path) width = image.size[0] height = image.size[1] for idx, (c2w, time) in enumerate(zip(render_poses, render_times)): c2w[:3, 1:3] *= -1 # get the world-to-camera transform and set R, T w2c = np.linalg.inv(c2w) R = np.transpose(w2c[:3,:3]) # R is stored transposed due to 'glm' in CUDA code T = w2c[:3, 3] fovy = focal2fov(fov2focal(fovx, width), height) FovY = fovy FovX = fovx cam_infos.append(CameraInfo(uid=idx, R=R, T=T, FovY=FovY, FovX=FovX, image=None, image_path=None, image_name=None, width=width, height=height, time=time)) return cam_infos def init_random_points(ply_path): if not os.path.exists(ply_path): # Since this data set has no colmap data, we start with random points num_pts = 100_000 print(f"Generating random point cloud ({num_pts})...") # We create random points inside the bounds of the synthetic Blender scenes # time_length = max([c.time for c in train_cam_infos]) + 1 # time_length = 2 # xyz = np.random.random((num_pts, 1, 3)) * 2.6 - 1.3 # xyz = np.tile(xyz, (1, time_length, 1)) # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3)), np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3))], axis=1) xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 16, 3))], axis=1) # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 3, 3)), np.ones((num_pts, 1, 3))], axis=1) # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3)), np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3))], axis=1) shs = np.random.random((num_pts, 3)) / 255.0 pcd = BasicPointCloud(points=xyz, colors=SH2RGB(shs), normals=np.zeros((num_pts, 3))) storePly(ply_path, xyz, SH2RGB(shs) * 255) # try: pcd = fetchPly(ply_path) # except: # pcd = None return pcd def readNerfSyntheticInfo(path, white_background, eval, extension=".png"): print("Reading Training Transforms") train_cam_infos = readCamerasFromTransforms(path, "transforms_train.json", white_background, extension) print("Reading Test Transforms") test_cam_infos = readCamerasFromTransforms(path, "transforms_test.json", white_background, extension) vis_cam_infos = generateCamerasFromTransforms(path, "transforms_train.json") if not eval: train_cam_infos.extend(test_cam_infos) test_cam_infos = [] nerf_normalization = getNerfppNorm(train_cam_infos) ply_path = os.path.join(path, "points3d_ours.ply") pcd = init_random_points(ply_path) scene_info = SceneInfo(point_cloud=pcd, train_cameras=train_cam_infos, test_cameras=test_cam_infos, vis_cameras=vis_cam_infos, nerf_normalization=nerf_normalization, ply_path=ply_path, time_delta=1/len(train_cam_infos)) return scene_info def viewmatrix(z, up, pos): vec2 = normalize(z) vec1_avg = up vec0 = normalize(np.cross(vec1_avg, vec2)) vec1 = normalize(np.cross(vec2, vec0)) m = np.eye(4) m[:3] = np.stack([-vec0, vec1, vec2, pos], 1) return m def render_path_spiral(c2w, up, rads, focal, zdelta, zrate, N_rots=2, N=120): render_poses = [] rads = np.array(list(rads) + [1.0]) for theta in np.linspace(0.0, 2.0 * np.pi * N_rots, N + 1)[:-1]: c = np.dot( c2w[:3, :4], np.array([np.cos(theta), -np.sin(theta), -np.sin(theta * zrate), 1.0]) * rads, ) z = normalize(c - np.dot(c2w[:3, :4], np.array([0, 0, -focal, 1.0]))) render_poses.append(viewmatrix(z, up, c)) return render_poses def get_spiral(c2ws_all, near_fars, rads_scale=1.0, N_views=120): """ Generate a set of poses using NeRF's spiral camera trajectory as validation poses. """ # center pose c2w = average_poses(c2ws_all) # Get average pose up = normalize(c2ws_all[:, :3, 1].sum(0)) # Find a reasonable "focus depth" for this dataset dt = 0.75 close_depth, inf_depth = near_fars.min() * 0.9, near_fars.max() * 5.0 focal = 1.0 / ((1.0 - dt) / close_depth + dt / inf_depth) # Get radii for spiral path zdelta = near_fars.min() * 0.2 tt = c2ws_all[:, :3, 3] rads = np.percentile(np.abs(tt), 90, 0) * rads_scale render_poses = render_path_spiral( c2w, up, rads, focal, zdelta, zrate=0.5, N=N_views ) return np.stack(render_poses) def readDynerfSceneInfo(path, eval): blender2opencv = np.eye(4) downsample = 2 poses_arr = np.load(os.path.join(path, "poses_bounds.npy")) poses = poses_arr[:, :-2].reshape([-1, 3, 5]) # (N_cams, 3, 5) near_fars = poses_arr[:, -2:] videos = glob.glob(os.path.join(path, "cam??")) videos = sorted(videos) assert len(videos) == poses_arr.shape[0] H, W, focal = poses[0, :, -1] focal = focal / downsample poses = np.concatenate([poses[..., 1:2], -poses[..., :1], poses[..., 2:4]], -1) poses, pose_avg = center_poses( poses, blender2opencv ) # Re-center poses so that the average is near the center. near_original = near_fars.min() scale_factor = near_original * 0.75 near_fars /= ( scale_factor # rescale nearest plane so that it is at z = 4/3. ) # print(scale_factor) poses[..., 3] /= scale_factor image_dirs = [video.replace('.mp4', '') for video in videos] val_index = [0] images = [sorted(glob.glob(os.path.join(d, "*.png")), key=lambda x:int(os.path.splitext(os.path.basename(x))[0]))[:300] for d in image_dirs] train_cam_infos = [] for idx, image_paths in enumerate(images): if idx in val_index: continue p = poses[idx] for image_path in image_paths: image_name = os.path.basename(image_path).split(".")[0] time = float(image_name) / 300 image = Image.open(image_path) uid = idx * 1000 + int(image_name) pose = np.eye(4) pose[:3, :] = p[:3, :] R = -pose[:3, :3] R[:, 0] = -R[:, 0] T = -pose[:3, 3].dot(R) height = image.height width = image.width FovY = focal2fov(focal, height) FovX = focal2fov(focal, width) # R = pose[:3, :3] # T = pose[:3, 3] cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=width, height=height, time=time) train_cam_infos.append(cam_info) test_cam_infos = [] for idx, image_paths in enumerate(images): if idx not in val_index: continue p = poses[idx] for image_path in image_paths: image_name = os.path.basename(image_path).split(".")[0] time = float(image_name) / 300 image = Image.open(image_path) uid = idx * 1000 + int(image_name) pose = np.eye(4) pose[:3, :] = p[:3, :] R = -pose[:3, :3] R[:, 0] = -R[:, 0] T = -pose[:3, 3].dot(R) # R = pose[:3, :3] # T = pose[:3, 3] height = image.height width = image.width FovY = focal2fov(focal, height) FovX = focal2fov(focal, width) cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=width, height=height, time=time) test_cam_infos.append(cam_info) if not eval: train_cam_infos.extend(test_cam_infos) test_cam_infos = [] widht, height = train_cam_infos[0].width, train_cam_infos[0].height # Sample N_views poses for validation - NeRF-like camera trajectory. N_views = 120 val_poses = get_spiral(poses, near_fars, N_views=N_views) val_times = torch.linspace(0.0, 1.0, val_poses.shape[0]) vis_cam_infos = [] for idx, (pose, time) in enumerate(zip(val_poses, val_times)): p = pose uid = idx pose = np.eye(4) pose[:3, :] = p[:3, :] R = -pose[:3, :3] R[:, 0] = -R[:, 0] T = -pose[:3, 3].dot(R) # R = pose[:3, :3] # T = pose[:3, 3] FovY = focal2fov(focal, height) FovX = focal2fov(focal, width) cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=None, image_name=None, width=width, height=height, time=time) vis_cam_infos.append(cam_info) nerf_normalization = getNerfppNorm(train_cam_infos) ply_path = os.path.join(path, "points3d_ours.ply") if not os.path.exists(ply_path): # Since this data set has no colmap data, we start with random points num_pts = 2_000 # 100_000 print(f"Generating random point cloud ({num_pts})...") threshold = 3 xyz_max = np.array([1.5*threshold, 1.5*threshold, -0*threshold]) xyz_min = np.array([-1.5*threshold, -1.5*threshold, -1.5*threshold]) xyz = np.concatenate([(np.random.random((num_pts, 1, 3)))* (xyz_max-xyz_min) + xyz_min, np.zeros((num_pts, 16, 3))], axis=1) # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3))], axis=1) shs = np.random.random((num_pts, 3)) / 255.0 pcd = BasicPointCloud(points=xyz, colors=SH2RGB(shs), normals=np.zeros((num_pts, 3))) storePly(ply_path, xyz, SH2RGB(shs) * 255) pcd = fetchPly(ply_path) scene_info = SceneInfo(point_cloud=pcd, train_cameras=train_cam_infos, test_cameras=test_cam_infos, vis_cameras =vis_cam_infos, nerf_normalization=nerf_normalization, ply_path=ply_path, time_delta=1/300) return scene_info def readHypernerfCamera(uid, camera, image_path, time): height, width = int(camera.image_shape[0]), int(camera.image_shape[1]) image_name = os.path.basename(image_path).split(".")[0] R = camera.orientation.T # T = camera.translation.T T = - camera.position @ R image = Image.open(image_path) FovY = focal2fov(camera.focal_length, height) FovX = focal2fov(camera.focal_length, width) return CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=width, height=height, time=time) def readHypernerfSceneInfo(path, eval): # borrow code from https://github.com/hustvl/TiNeuVox/blob/main/lib/load_hyper.py use_bg_points = False with open(f'{path}/scene.json', 'r') as f: scene_json = json.load(f) with open(f'{path}/metadata.json', 'r') as f: meta_json = json.load(f) with open(f'{path}/dataset.json', 'r') as f: dataset_json = json.load(f) near = scene_json['near'] far = scene_json['far'] coord_scale = scene_json['scale'] scene_center = scene_json['center'] all_imgs = dataset_json['ids'] val_ids = dataset_json['val_ids'] add_cam = False if len(val_ids) == 0: i_train = np.array([i for i in np.arange(len(all_imgs)) if (i%4 == 0)]) i_test = i_train+2 i_test = i_test[:-1,] else: add_cam = True train_ids = dataset_json['train_ids'] i_test = [] i_train = [] for i in range(len(all_imgs)): id = all_imgs[i] if id in val_ids: i_test.append(i) if id in train_ids: i_train.append(i) print('i_train',i_train) print('i_test',i_test) all_cams = [meta_json[i]['camera_id'] for i in all_imgs] all_times = [meta_json[i]['time_id'] for i in all_imgs] max_time = max(all_times) all_times = [meta_json[i]['time_id']/max_time for i in all_imgs] selected_time = set(all_times) ratio = 0.5 all_cam_params = [] for im in all_imgs:
camera = HyperNeRFCamera.from_json(f'{path}/camera/{im}.json')
11
2023-11-30 02:22:56+00:00
12k
zd11024/NaviLLM
train.py
[ { "identifier": "all_gather", "path": "tools/common_utils.py", "snippet": "def all_gather(data):\n \"\"\"\n Run all_gather on arbitrary picklable data (not necessarily tensors)\n Args:\n data: any picklable object\n Returns:\n list[data]: list of data gathered from each rank\n ...
import os import json import torch import random import torch.nn as nn from tqdm import tqdm from pathlib import Path from typing import Dict from tools.common_utils import all_gather from tools.parser import read_args, random_seed from tasks.loaders import create_dataloaders from tasks.feature_db import create_feature_db, create_object_feature_db from models.nav_model import NavModel from tools.optims import dist_models, save_checkpoint from tools.trie import Trie
9,557
if args.rank == 0: verbose_dict = dict( step=step, name=name, # index=batch['sample_idx'], loss=loss_metric.average, entropy=entropy_metric.average, instr_pred_metric=instr_pred_metric.average, lr=lr_scheduler.get_last_lr()[0], ) for k in dataset_cfg.SOURCE: verbose_dict[k] = loss_stats[k].average pbar.set_postfix(verbose_dict) pbar.update() if step == num_batches_per_epoch-1: logger.info("***** train [{}] epoch *****".format(epoch)) train_stat_str = 'Loss: %.2f\n' % loss_metric.average train_stat_str += "Instr_pred: %.2f\n" % instr_pred_metric.average for task in dataset_cfg.SOURCE: train_stat_str += "%s: %.2f\n" % (task, loss_stats[task].average) logger.info(train_stat_str) break @torch.no_grad() def val_one_epoch( args, global_cfg, model, optimizer, criterion, dataloaders, agents, epoch, logger, ) -> Dict[str, Dict[str, float]]: model.eval() entropy_metric = Metrics() loss_str = "\n[Eval] {} epoch {}\n".format(args.validation_split, epoch) task_results = {} for name, loader in dataloaders.items(): logger.info("***** validate {} split on {} task *****".format(args.validation_split, name)) dataset = dataloaders[name].get_dataset() agent = agents[name] preds = agent.validate( name, args, global_cfg, model, loader, entropy_metric=entropy_metric ) all_preds = all_gather(preds) all_preds = merge_dist_results(all_preds) if args.rank == 0 and not args.validation_split.startswith('test'): score_summary, item_metrics = dataset.eval_metrics(all_preds, logger=logger, name=name) task_results[name] = score_summary loss_str += "\n [Eval] dataset=[{}] \n".format(name) for metric, val in score_summary.items(): if metric == 'sr': loss_str += '\n[Eval] ||| %s: %.2f' % (metric, val) else: loss_str += ', %s: %.2f' % (metric, val) if args.rank== 0 and args.save_pred_results: dataset.save_json( all_preds, os.path.join(args.output_dir, f"{name}_{args.validation_split}.json"), item_metrics=item_metrics if args.save_detail_results else None ) logger.info(loss_str) return task_results def merge_dist_results(results): outs = [] for res in results: outs.extend(res) return outs def calc_overall_score(results, cfg): score = 0. for task in results: if task not in cfg.Multi.SOURCE: continue if task == 'R2R': score += results[task]['spl'] / 60 elif task == 'REVERIE': score += results[task]['spl'] / 36.63 elif task == 'CVDN': pass elif task == 'SOON': score += results[task]['spl'] / 26.58 elif task == 'EQA': pass elif task == "ScanQA": pass else: raise NotImplementedError(f"The method for calculating the score of {task} is not Implemented.") return score def main(): args, global_cfg, logger, device_id = read_args() random_seed(args.seed + args.rank) ##################### DATASET #####################
class Metrics(object): def __init__(self): self.num = 0 self.total = 0 def accumulate(self, x): self.num += 1 self.total += x @property def average(self): if self.num == 0: return 0 return self.total / self.num def train_one_epoch( args, global_cfg, model, optimizer, lr_scheduler, criterion, dataloaders, agents, epoch, logger, stage='multi' ): model.train() entropy_metric = Metrics() loss_metric = Metrics() instr_pred_metric = Metrics() num_batches_per_epoch = dataloaders.num_batches total_training_steps = num_batches_per_epoch * args.num_epochs pbar = tqdm( range(dataloaders.num_batches), disable=args.rank!=0, total=total_training_steps, initial=(epoch * num_batches_per_epoch) ) dataset_cfg = global_cfg.Pretrain if stage=='pretrain' else global_cfg.Multi loss_stats = {k: Metrics() for k in dataset_cfg.SOURCE} for step, (name, batch) in enumerate(dataloaders): loss_coef = dataset_cfg.LOSS_COEF.get(name, 1.) # perform embodied tasks # the actual batch_size equals to args.batch_size * world_size * (args.gradient_accumulation_step) dataset = dataloaders.loader.get_dataset(name) agent = agents.get(name) loss = agent.train( name, batch, args, global_cfg, model=model, criterion=criterion, dataset=dataset, step=step, entropy_metric=entropy_metric, instr_pred_metric=instr_pred_metric ) loss_metric.accumulate(loss.item()) loss_stats[name].accumulate(loss.item()) if (step+1) % args.gradient_accumulation_step==0: torch.nn.utils.clip_grad_norm_(model.parameters(), 40.) optimizer.step() optimizer.zero_grad() lr_scheduler.step() if args.rank == 0: verbose_dict = dict( step=step, name=name, # index=batch['sample_idx'], loss=loss_metric.average, entropy=entropy_metric.average, instr_pred_metric=instr_pred_metric.average, lr=lr_scheduler.get_last_lr()[0], ) for k in dataset_cfg.SOURCE: verbose_dict[k] = loss_stats[k].average pbar.set_postfix(verbose_dict) pbar.update() if step == num_batches_per_epoch-1: logger.info("***** train [{}] epoch *****".format(epoch)) train_stat_str = 'Loss: %.2f\n' % loss_metric.average train_stat_str += "Instr_pred: %.2f\n" % instr_pred_metric.average for task in dataset_cfg.SOURCE: train_stat_str += "%s: %.2f\n" % (task, loss_stats[task].average) logger.info(train_stat_str) break @torch.no_grad() def val_one_epoch( args, global_cfg, model, optimizer, criterion, dataloaders, agents, epoch, logger, ) -> Dict[str, Dict[str, float]]: model.eval() entropy_metric = Metrics() loss_str = "\n[Eval] {} epoch {}\n".format(args.validation_split, epoch) task_results = {} for name, loader in dataloaders.items(): logger.info("***** validate {} split on {} task *****".format(args.validation_split, name)) dataset = dataloaders[name].get_dataset() agent = agents[name] preds = agent.validate( name, args, global_cfg, model, loader, entropy_metric=entropy_metric ) all_preds = all_gather(preds) all_preds = merge_dist_results(all_preds) if args.rank == 0 and not args.validation_split.startswith('test'): score_summary, item_metrics = dataset.eval_metrics(all_preds, logger=logger, name=name) task_results[name] = score_summary loss_str += "\n [Eval] dataset=[{}] \n".format(name) for metric, val in score_summary.items(): if metric == 'sr': loss_str += '\n[Eval] ||| %s: %.2f' % (metric, val) else: loss_str += ', %s: %.2f' % (metric, val) if args.rank== 0 and args.save_pred_results: dataset.save_json( all_preds, os.path.join(args.output_dir, f"{name}_{args.validation_split}.json"), item_metrics=item_metrics if args.save_detail_results else None ) logger.info(loss_str) return task_results def merge_dist_results(results): outs = [] for res in results: outs.extend(res) return outs def calc_overall_score(results, cfg): score = 0. for task in results: if task not in cfg.Multi.SOURCE: continue if task == 'R2R': score += results[task]['spl'] / 60 elif task == 'REVERIE': score += results[task]['spl'] / 36.63 elif task == 'CVDN': pass elif task == 'SOON': score += results[task]['spl'] / 26.58 elif task == 'EQA': pass elif task == "ScanQA": pass else: raise NotImplementedError(f"The method for calculating the score of {task} is not Implemented.") return score def main(): args, global_cfg, logger, device_id = read_args() random_seed(args.seed + args.rank) ##################### DATASET #####################
feat_db = create_feature_db(global_cfg.Feature.feature_database, global_cfg.Feature.image_feat_size, args)
4
2023-11-28 06:59:37+00:00
12k
KylinYee/R2-Talker-code
test.py
[ { "identifier": "NeRFDataset_Test", "path": "nerf/provider.py", "snippet": "class NeRFDataset_Test:\n def __init__(self, opt, device, downscale=1):\n super().__init__()\n \n self.opt = opt\n self.device = device\n self.downscale = downscale\n self.scale = opt...
import torch import argparse from nerf.provider import NeRFDataset_Test from nerf.gui import NeRFGUI from nerf.utils import * from nerf.network import NeRFNetwork, R2TalkerNeRF, GeneNeRFNetwork
10,752
### network backbone options parser.add_argument('--fp16', action='store_true', help="use amp mixed precision training") parser.add_argument('--lambda_amb', type=float, default=0.1, help="lambda for ambient loss") parser.add_argument('--fbg', action='store_true', help="frame-wise bg") parser.add_argument('--exp_eye', action='store_true', help="explicitly control the eyes") parser.add_argument('--fix_eye', type=float, default=-1, help="fixed eye area, negative to disable, set to 0-0.3 for a reasonable eye") parser.add_argument('--smooth_eye', action='store_true', help="smooth the eye area sequence") parser.add_argument('--torso_shrink', type=float, default=0.8, help="shrink bg coords to allow more flexibility in deform") ### dataset options parser.add_argument('--color_space', type=str, default='srgb', help="Color space, supports (linear, srgb)") # parser.add_argument('--preload', action='store_true', help="preload all data into GPU, accelerate training but use more GPU memory") # (the default value is for the fox dataset) parser.add_argument('--bound', type=float, default=1, help="assume the scene is bounded in box[-bound, bound]^3, if > 1, will invoke adaptive ray marching.") parser.add_argument('--scale', type=float, default=4, help="scale camera location into box[-bound, bound]^3") parser.add_argument('--offset', type=float, nargs='*', default=[0, 0, 0], help="offset of camera location") parser.add_argument('--dt_gamma', type=float, default=1/256, help="dt_gamma (>=0) for adaptive ray marching. set to 0 to disable, >0 to accelerate rendering (but usually with worse quality)") parser.add_argument('--min_near', type=float, default=0.05, help="minimum near distance for camera") parser.add_argument('--density_thresh', type=float, default=10, help="threshold for density grid to be occupied (sigma)") parser.add_argument('--density_thresh_torso', type=float, default=0.01, help="threshold for density grid to be occupied (alpha)") parser.add_argument('--patch_size', type=int, default=1, help="[experimental] render patches in training, so as to apply LPIPS loss. 1 means disabled, use [64, 32, 16] to enable") parser.add_argument('--finetune_lips', action='store_true', help="use LPIPS and landmarks to fine tune lips region") parser.add_argument('--smooth_lips', action='store_true', help="smooth the enc_a in a exponential decay way...") parser.add_argument('--torso', action='store_true', help="fix head and train torso") parser.add_argument('--head_ckpt', type=str, default='', help="head model") ### GUI options parser.add_argument('--gui', action='store_true', help="start a GUI") parser.add_argument('--W', type=int, default=450, help="GUI width") parser.add_argument('--H', type=int, default=450, help="GUI height") parser.add_argument('--radius', type=float, default=3.35, help="default GUI camera radius from center") parser.add_argument('--fovy', type=float, default=21.24, help="default GUI camera fovy") parser.add_argument('--max_spp', type=int, default=1, help="GUI rendering max sample per pixel") ### else parser.add_argument('--att', type=int, default=2, help="audio attention mode (0 = turn off, 1 = left-direction, 2 = bi-direction)") parser.add_argument('--emb', action='store_true', help="use audio class + embedding instead of logits") parser.add_argument('--ind_dim', type=int, default=4, help="individual code dim, 0 to turn off") parser.add_argument('--ind_num', type=int, default=10000, help="number of individual codes, should be larger than training dataset size") parser.add_argument('--ind_dim_torso', type=int, default=8, help="individual code dim, 0 to turn off") parser.add_argument('--amb_dim', type=int, default=2, help="ambient dimension") parser.add_argument('--part', action='store_true', help="use partial training data (1/10)") parser.add_argument('--part2', action='store_true', help="use partial training data (first 15s)") parser.add_argument('--train_camera', action='store_true', help="optimize camera pose") parser.add_argument('--smooth_path', action='store_true', help="brute-force smooth camera pose trajectory with a window size") parser.add_argument('--smooth_path_window', type=int, default=7, help="smoothing window size") # asr parser.add_argument('--asr', action='store_true', help="load asr for real-time app") parser.add_argument('--asr_wav', type=str, default='', help="load the wav and use as input") parser.add_argument('--asr_play', action='store_true', help="play out the audio") parser.add_argument('--asr_model', type=str, default='cpierse/wav2vec2-large-xlsr-53-esperanto') # parser.add_argument('--asr_model', type=str, default='facebook/wav2vec2-large-960h-lv60-self') parser.add_argument('--asr_save_feats', action='store_true') # audio FPS parser.add_argument('--fps', type=int, default=50) # sliding window left-middle-right length (unit: 20ms) parser.add_argument('-l', type=int, default=10) parser.add_argument('-m', type=int, default=50) parser.add_argument('-r', type=int, default=10) opt = parser.parse_args() if opt.method == 'r2talker': opt.cond_type = 'idexp' elif opt.method == 'genefaceDagger': opt.cond_type = 'idexp' elif opt.method == 'rad-nerf': opt.cond_type = 'eo' # assert test mode opt.test = True opt.test_train = False # explicit smoothing opt.smooth_path = True opt.smooth_eye = True opt.smooth_lips = True assert opt.pose != '', 'Must provide a pose source' assert opt.aud != '', 'Must provide an audio source' if opt.O: opt.fp16 = True opt.exp_eye = True opt.cuda_ray = True # assert opt.cuda_ray, "Only support CUDA ray mode." print(opt) seed_everything(opt.seed) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') if opt.method == 'r2talker': model = R2TalkerNeRF(opt) elif opt.method == 'genefaceDagger': model = GeneNeRFNetwork(opt) elif opt.method == 'rad-nerf': model = NeRFNetwork(opt) # print(model) trainer = Trainer('ngp', opt, model, device=device, workspace=opt.workspace, fp16=opt.fp16, metrics=[], use_checkpoint=opt.ckpt)
# torch.autograd.set_detect_anomaly(True) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--pose', type=str, help="transforms.json, pose source") parser.add_argument('--aud', type=str, default=None, help="aud.npy, audio source") parser.add_argument('--cond_type', type=str, default=None, help="type of driving condition: eo, ds, idexp") parser.add_argument('--method', type=str, default='r2talker', help="r2talker, genefaceDagger, rad-nerf") parser.add_argument('--bg_img', type=str, default='white', help="bg.jpg, background image source") parser.add_argument('-O', action='store_true', help="equals --fp16 --cuda_ray --exp_eye") # parser.add_argument('--test', action='store_true', help="test mode (load model and test dataset)") # parser.add_argument('--test_train', action='store_true', help="test mode (load model and train dataset)") parser.add_argument('--data_range', type=int, nargs='*', default=[0, -1], help="data range to use") parser.add_argument('--workspace', type=str, default='workspace') parser.add_argument('--seed', type=int, default=0) ### training options # parser.add_argument('--iters', type=int, default=200000, help="training iters") # parser.add_argument('--lr', type=float, default=5e-3, help="initial learning rate") # parser.add_argument('--lr_net', type=float, default=5e-4, help="initial learning rate") parser.add_argument('--ckpt', type=str, default='latest') parser.add_argument('--num_rays', type=int, default=4096 * 16, help="num rays sampled per image for each training step") parser.add_argument('--cuda_ray', action='store_true', help="use CUDA raymarching instead of pytorch") parser.add_argument('--max_steps', type=int, default=16, help="max num steps sampled per ray (only valid when using --cuda_ray)") parser.add_argument('--num_steps', type=int, default=16, help="num steps sampled per ray (only valid when NOT using --cuda_ray)") parser.add_argument('--upsample_steps', type=int, default=0, help="num steps up-sampled per ray (only valid when NOT using --cuda_ray)") parser.add_argument('--update_extra_interval', type=int, default=16, help="iter interval to update extra status (only valid when using --cuda_ray)") parser.add_argument('--max_ray_batch', type=int, default=4096, help="batch size of rays at inference to avoid OOM (only valid when NOT using --cuda_ray)") ### network backbone options parser.add_argument('--fp16', action='store_true', help="use amp mixed precision training") parser.add_argument('--lambda_amb', type=float, default=0.1, help="lambda for ambient loss") parser.add_argument('--fbg', action='store_true', help="frame-wise bg") parser.add_argument('--exp_eye', action='store_true', help="explicitly control the eyes") parser.add_argument('--fix_eye', type=float, default=-1, help="fixed eye area, negative to disable, set to 0-0.3 for a reasonable eye") parser.add_argument('--smooth_eye', action='store_true', help="smooth the eye area sequence") parser.add_argument('--torso_shrink', type=float, default=0.8, help="shrink bg coords to allow more flexibility in deform") ### dataset options parser.add_argument('--color_space', type=str, default='srgb', help="Color space, supports (linear, srgb)") # parser.add_argument('--preload', action='store_true', help="preload all data into GPU, accelerate training but use more GPU memory") # (the default value is for the fox dataset) parser.add_argument('--bound', type=float, default=1, help="assume the scene is bounded in box[-bound, bound]^3, if > 1, will invoke adaptive ray marching.") parser.add_argument('--scale', type=float, default=4, help="scale camera location into box[-bound, bound]^3") parser.add_argument('--offset', type=float, nargs='*', default=[0, 0, 0], help="offset of camera location") parser.add_argument('--dt_gamma', type=float, default=1/256, help="dt_gamma (>=0) for adaptive ray marching. set to 0 to disable, >0 to accelerate rendering (but usually with worse quality)") parser.add_argument('--min_near', type=float, default=0.05, help="minimum near distance for camera") parser.add_argument('--density_thresh', type=float, default=10, help="threshold for density grid to be occupied (sigma)") parser.add_argument('--density_thresh_torso', type=float, default=0.01, help="threshold for density grid to be occupied (alpha)") parser.add_argument('--patch_size', type=int, default=1, help="[experimental] render patches in training, so as to apply LPIPS loss. 1 means disabled, use [64, 32, 16] to enable") parser.add_argument('--finetune_lips', action='store_true', help="use LPIPS and landmarks to fine tune lips region") parser.add_argument('--smooth_lips', action='store_true', help="smooth the enc_a in a exponential decay way...") parser.add_argument('--torso', action='store_true', help="fix head and train torso") parser.add_argument('--head_ckpt', type=str, default='', help="head model") ### GUI options parser.add_argument('--gui', action='store_true', help="start a GUI") parser.add_argument('--W', type=int, default=450, help="GUI width") parser.add_argument('--H', type=int, default=450, help="GUI height") parser.add_argument('--radius', type=float, default=3.35, help="default GUI camera radius from center") parser.add_argument('--fovy', type=float, default=21.24, help="default GUI camera fovy") parser.add_argument('--max_spp', type=int, default=1, help="GUI rendering max sample per pixel") ### else parser.add_argument('--att', type=int, default=2, help="audio attention mode (0 = turn off, 1 = left-direction, 2 = bi-direction)") parser.add_argument('--emb', action='store_true', help="use audio class + embedding instead of logits") parser.add_argument('--ind_dim', type=int, default=4, help="individual code dim, 0 to turn off") parser.add_argument('--ind_num', type=int, default=10000, help="number of individual codes, should be larger than training dataset size") parser.add_argument('--ind_dim_torso', type=int, default=8, help="individual code dim, 0 to turn off") parser.add_argument('--amb_dim', type=int, default=2, help="ambient dimension") parser.add_argument('--part', action='store_true', help="use partial training data (1/10)") parser.add_argument('--part2', action='store_true', help="use partial training data (first 15s)") parser.add_argument('--train_camera', action='store_true', help="optimize camera pose") parser.add_argument('--smooth_path', action='store_true', help="brute-force smooth camera pose trajectory with a window size") parser.add_argument('--smooth_path_window', type=int, default=7, help="smoothing window size") # asr parser.add_argument('--asr', action='store_true', help="load asr for real-time app") parser.add_argument('--asr_wav', type=str, default='', help="load the wav and use as input") parser.add_argument('--asr_play', action='store_true', help="play out the audio") parser.add_argument('--asr_model', type=str, default='cpierse/wav2vec2-large-xlsr-53-esperanto') # parser.add_argument('--asr_model', type=str, default='facebook/wav2vec2-large-960h-lv60-self') parser.add_argument('--asr_save_feats', action='store_true') # audio FPS parser.add_argument('--fps', type=int, default=50) # sliding window left-middle-right length (unit: 20ms) parser.add_argument('-l', type=int, default=10) parser.add_argument('-m', type=int, default=50) parser.add_argument('-r', type=int, default=10) opt = parser.parse_args() if opt.method == 'r2talker': opt.cond_type = 'idexp' elif opt.method == 'genefaceDagger': opt.cond_type = 'idexp' elif opt.method == 'rad-nerf': opt.cond_type = 'eo' # assert test mode opt.test = True opt.test_train = False # explicit smoothing opt.smooth_path = True opt.smooth_eye = True opt.smooth_lips = True assert opt.pose != '', 'Must provide a pose source' assert opt.aud != '', 'Must provide an audio source' if opt.O: opt.fp16 = True opt.exp_eye = True opt.cuda_ray = True # assert opt.cuda_ray, "Only support CUDA ray mode." print(opt) seed_everything(opt.seed) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') if opt.method == 'r2talker': model = R2TalkerNeRF(opt) elif opt.method == 'genefaceDagger': model = GeneNeRFNetwork(opt) elif opt.method == 'rad-nerf': model = NeRFNetwork(opt) # print(model) trainer = Trainer('ngp', opt, model, device=device, workspace=opt.workspace, fp16=opt.fp16, metrics=[], use_checkpoint=opt.ckpt)
test_loader = NeRFDataset_Test(opt, device=device).dataloader()
0
2023-12-04 12:51:59+00:00
12k
DSaurus/threestudio-4dfy
data/uncond_multiview_time.py
[ { "identifier": "RandomCameraDataModuleConfig", "path": "data/uncond_time.py", "snippet": "class RandomCameraDataModuleConfig:\n # height, width, and batch_size should be Union[int, List[int]]\n # but OmegaConf does not support Union of containers\n height: Any = 64\n width: Any = 64\n ba...
import math import os import random import cv2 import numpy as np import pytorch_lightning as pl import torch import torch.nn.functional as F from dataclasses import dataclass, field from threestudio import register from threestudio.utils.base import Updateable from threestudio.utils.config import parse_structured from threestudio.utils.misc import get_rank from threestudio.utils.ops import ( get_mvp_matrix, get_projection_matrix, get_ray_directions, get_rays, ) from threestudio.utils.typing import * from torch.utils.data import DataLoader, Dataset, IterableDataset from .uncond_time import ( RandomCameraDataModuleConfig, RandomCameraDataset, RandomCameraIterableDataset, )
9,819
self.cfg.n_view, dim=0 ) * self.cfg.light_position_perturb, dim=-1, ) # get light position by scaling light direction by light distance light_positions: Float[Tensor, "B 3"] = ( light_direction * light_distances[:, None] ) elif self.cfg.light_sample_strategy == "magic3d": # sample light direction within restricted angle range (pi/3) local_z = F.normalize(camera_positions, dim=-1) local_x = F.normalize( torch.stack( [local_z[:, 1], -local_z[:, 0], torch.zeros_like(local_z[:, 0])], dim=-1, ), dim=-1, ) local_y = F.normalize(torch.cross(local_z, local_x, dim=-1), dim=-1) rot = torch.stack([local_x, local_y, local_z], dim=-1) light_azimuth = ( torch.rand(real_batch_size) * math.pi - 2 * math.pi ).repeat_interleave( self.cfg.n_view, dim=0 ) # [-pi, pi] light_elevation = ( torch.rand(real_batch_size) * math.pi / 3 + math.pi / 6 ).repeat_interleave( self.cfg.n_view, dim=0 ) # [pi/6, pi/2] light_positions_local = torch.stack( [ light_distances * torch.cos(light_elevation) * torch.cos(light_azimuth), light_distances * torch.cos(light_elevation) * torch.sin(light_azimuth), light_distances * torch.sin(light_elevation), ], dim=-1, ) light_positions = (rot @ light_positions_local[:, :, None])[:, :, 0] else: raise ValueError( f"Unknown light sample strategy: {self.cfg.light_sample_strategy}" ) lookat: Float[Tensor, "B 3"] = F.normalize(center - camera_positions, dim=-1) right: Float[Tensor, "B 3"] = F.normalize(torch.cross(lookat, up), dim=-1) up = F.normalize(torch.cross(right, lookat), dim=-1) c2w3x4: Float[Tensor, "B 3 4"] = torch.cat( [torch.stack([right, up, -lookat], dim=-1), camera_positions[:, :, None]], dim=-1, ) c2w: Float[Tensor, "B 4 4"] = torch.cat( [c2w3x4, torch.zeros_like(c2w3x4[:, :1])], dim=1 ) c2w[:, 3, 3] = 1.0 # get directions by dividing directions_unit_focal by focal length focal_length: Float[Tensor, "B"] = 0.5 * self.height / torch.tan(0.5 * fovy) directions: Float[Tensor, "B H W 3"] = self.directions_unit_focal[ None, :, :, : ].repeat(self.batch_size, 1, 1, 1) directions[:, :, :, :2] = ( directions[:, :, :, :2] / focal_length[:, None, None, None] ) # Importance note: the returned rays_d MUST be normalized! rays_o, rays_d = get_rays( directions, c2w, keepdim=True, normalize=self.cfg.rays_d_normalize ) proj_mtx: Float[Tensor, "B 4 4"] = get_projection_matrix( fovy, self.width / self.height, 0.1, 1000.0 ) # FIXME: hard-coded near and far mvp_mtx: Float[Tensor, "B 4 4"] = get_mvp_matrix(c2w, proj_mtx) if self.cfg.sample_rand_frames == "t0": t0 = torch.FloatTensor(1).uniform_(0, 1 / self.cfg.num_frames).item() frame_times = torch.linspace( t0, t0 + (self.cfg.num_frames - 1) / self.cfg.num_frames, self.cfg.num_frames, ) else: frame_times = torch.linspace(0.0, 1.0, self.cfg.num_frames) return { "rays_o": rays_o, "rays_d": rays_d, "mvp_mtx": mvp_mtx, "camera_positions": camera_positions, "c2w": c2w, "light_positions": light_positions, "elevation": elevation_deg, "azimuth": azimuth_deg, "camera_distances": camera_distances, "height": self.height, "width": self.width, "fovy": fovy, "frame_times": frame_times, "train_dynamic_camera": False, } @register("4dfy-random-multiview-camera-datamodule") class RandomMultiviewCameraDataModule(pl.LightningDataModule): cfg: RandomMultiviewCameraDataModuleConfig def __init__(self, cfg: Optional[Union[dict, DictConfig]] = None) -> None: super().__init__() self.cfg = parse_structured(RandomMultiviewCameraDataModuleConfig, cfg) def setup(self, stage=None) -> None: if stage in [None, "fit"]: self.train_dataset = RandomMultiviewCameraIterableDataset(self.cfg) if stage in [None, "fit", "validate"]:
@dataclass class RandomMultiviewCameraDataModuleConfig(RandomCameraDataModuleConfig): relative_radius: bool = True n_view: int = 1 zoom_range: Tuple[float, float] = (1.0, 1.0) rays_d_normalize: bool = True class RandomMultiviewCameraIterableDataset(RandomCameraIterableDataset): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.zoom_range = self.cfg.zoom_range def collate(self, batch) -> Dict[str, Any]: assert ( self.batch_size % self.cfg.n_view == 0 ), f"batch_size ({self.batch_size}) must be dividable by n_view ({self.cfg.n_view})!" real_batch_size = self.batch_size // self.cfg.n_view # sample elevation angles elevation_deg: Float[Tensor, "B"] elevation: Float[Tensor, "B"] if random.random() < 0.5: # sample elevation angles uniformly with a probability 0.5 (biased towards poles) elevation_deg = ( torch.rand(real_batch_size) * (self.elevation_range[1] - self.elevation_range[0]) + self.elevation_range[0] ).repeat_interleave(self.cfg.n_view, dim=0) elevation = elevation_deg * math.pi / 180 else: # otherwise sample uniformly on sphere elevation_range_percent = [ (self.elevation_range[0] + 90.0) / 180.0, (self.elevation_range[1] + 90.0) / 180.0, ] # inverse transform sampling elevation = torch.asin( 2 * ( torch.rand(real_batch_size) * (elevation_range_percent[1] - elevation_range_percent[0]) + elevation_range_percent[0] ) - 1.0 ).repeat_interleave(self.cfg.n_view, dim=0) elevation_deg = elevation / math.pi * 180.0 # sample azimuth angles from a uniform distribution bounded by azimuth_range azimuth_deg: Float[Tensor, "B"] # ensures sampled azimuth angles in a batch cover the whole range azimuth_deg = ( torch.rand(real_batch_size).reshape(-1, 1) + torch.arange(self.cfg.n_view).reshape(1, -1) ).reshape(-1) / self.cfg.n_view * ( self.azimuth_range[1] - self.azimuth_range[0] ) + self.azimuth_range[ 0 ] azimuth = azimuth_deg * math.pi / 180 ######## Different from original ######## # sample fovs from a uniform distribution bounded by fov_range fovy_deg: Float[Tensor, "B"] = ( torch.rand(real_batch_size) * (self.fovy_range[1] - self.fovy_range[0]) + self.fovy_range[0] ).repeat_interleave(self.cfg.n_view, dim=0) fovy = fovy_deg * math.pi / 180 # sample distances from a uniform distribution bounded by distance_range camera_distances: Float[Tensor, "B"] = ( torch.rand(real_batch_size) * (self.camera_distance_range[1] - self.camera_distance_range[0]) + self.camera_distance_range[0] ).repeat_interleave(self.cfg.n_view, dim=0) if self.cfg.relative_radius: scale = 1 / torch.tan(0.5 * fovy) camera_distances = scale * camera_distances # zoom in by decreasing fov after camera distance is fixed zoom: Float[Tensor, "B"] = ( torch.rand(real_batch_size) * (self.zoom_range[1] - self.zoom_range[0]) + self.zoom_range[0] ).repeat_interleave(self.cfg.n_view, dim=0) fovy = fovy * zoom fovy_deg = fovy_deg * zoom ########################################### # convert spherical coordinates to cartesian coordinates # right hand coordinate system, x back, y right, z up # elevation in (-90, 90), azimuth from +x to +y in (-180, 180) camera_positions: Float[Tensor, "B 3"] = torch.stack( [ camera_distances * torch.cos(elevation) * torch.cos(azimuth), camera_distances * torch.cos(elevation) * torch.sin(azimuth), camera_distances * torch.sin(elevation), ], dim=-1, ) # default scene center at origin center: Float[Tensor, "B 3"] = torch.zeros_like(camera_positions) # default camera up direction as +z up: Float[Tensor, "B 3"] = torch.as_tensor([0, 0, 1], dtype=torch.float32)[ None, : ].repeat(self.batch_size, 1) # sample camera perturbations from a uniform distribution [-camera_perturb, camera_perturb] camera_perturb: Float[Tensor, "B 3"] = ( torch.rand(real_batch_size, 3) * 2 * self.cfg.camera_perturb - self.cfg.camera_perturb ).repeat_interleave(self.cfg.n_view, dim=0) camera_positions = camera_positions + camera_perturb # sample center perturbations from a normal distribution with mean 0 and std center_perturb center_perturb: Float[Tensor, "B 3"] = ( torch.randn(real_batch_size, 3) * self.cfg.center_perturb ).repeat_interleave(self.cfg.n_view, dim=0) center = center + center_perturb # sample up perturbations from a normal distribution with mean 0 and std up_perturb up_perturb: Float[Tensor, "B 3"] = ( torch.randn(real_batch_size, 3) * self.cfg.up_perturb ).repeat_interleave(self.cfg.n_view, dim=0) up = up + up_perturb # sample light distance from a uniform distribution bounded by light_distance_range light_distances: Float[Tensor, "B"] = ( torch.rand(real_batch_size) * (self.cfg.light_distance_range[1] - self.cfg.light_distance_range[0]) + self.cfg.light_distance_range[0] ).repeat_interleave(self.cfg.n_view, dim=0) if self.cfg.light_sample_strategy == "dreamfusion": # sample light direction from a normal distribution with mean camera_position and std light_position_perturb light_direction: Float[Tensor, "B 3"] = F.normalize( camera_positions + torch.randn(real_batch_size, 3).repeat_interleave( self.cfg.n_view, dim=0 ) * self.cfg.light_position_perturb, dim=-1, ) # get light position by scaling light direction by light distance light_positions: Float[Tensor, "B 3"] = ( light_direction * light_distances[:, None] ) elif self.cfg.light_sample_strategy == "magic3d": # sample light direction within restricted angle range (pi/3) local_z = F.normalize(camera_positions, dim=-1) local_x = F.normalize( torch.stack( [local_z[:, 1], -local_z[:, 0], torch.zeros_like(local_z[:, 0])], dim=-1, ), dim=-1, ) local_y = F.normalize(torch.cross(local_z, local_x, dim=-1), dim=-1) rot = torch.stack([local_x, local_y, local_z], dim=-1) light_azimuth = ( torch.rand(real_batch_size) * math.pi - 2 * math.pi ).repeat_interleave( self.cfg.n_view, dim=0 ) # [-pi, pi] light_elevation = ( torch.rand(real_batch_size) * math.pi / 3 + math.pi / 6 ).repeat_interleave( self.cfg.n_view, dim=0 ) # [pi/6, pi/2] light_positions_local = torch.stack( [ light_distances * torch.cos(light_elevation) * torch.cos(light_azimuth), light_distances * torch.cos(light_elevation) * torch.sin(light_azimuth), light_distances * torch.sin(light_elevation), ], dim=-1, ) light_positions = (rot @ light_positions_local[:, :, None])[:, :, 0] else: raise ValueError( f"Unknown light sample strategy: {self.cfg.light_sample_strategy}" ) lookat: Float[Tensor, "B 3"] = F.normalize(center - camera_positions, dim=-1) right: Float[Tensor, "B 3"] = F.normalize(torch.cross(lookat, up), dim=-1) up = F.normalize(torch.cross(right, lookat), dim=-1) c2w3x4: Float[Tensor, "B 3 4"] = torch.cat( [torch.stack([right, up, -lookat], dim=-1), camera_positions[:, :, None]], dim=-1, ) c2w: Float[Tensor, "B 4 4"] = torch.cat( [c2w3x4, torch.zeros_like(c2w3x4[:, :1])], dim=1 ) c2w[:, 3, 3] = 1.0 # get directions by dividing directions_unit_focal by focal length focal_length: Float[Tensor, "B"] = 0.5 * self.height / torch.tan(0.5 * fovy) directions: Float[Tensor, "B H W 3"] = self.directions_unit_focal[ None, :, :, : ].repeat(self.batch_size, 1, 1, 1) directions[:, :, :, :2] = ( directions[:, :, :, :2] / focal_length[:, None, None, None] ) # Importance note: the returned rays_d MUST be normalized! rays_o, rays_d = get_rays( directions, c2w, keepdim=True, normalize=self.cfg.rays_d_normalize ) proj_mtx: Float[Tensor, "B 4 4"] = get_projection_matrix( fovy, self.width / self.height, 0.1, 1000.0 ) # FIXME: hard-coded near and far mvp_mtx: Float[Tensor, "B 4 4"] = get_mvp_matrix(c2w, proj_mtx) if self.cfg.sample_rand_frames == "t0": t0 = torch.FloatTensor(1).uniform_(0, 1 / self.cfg.num_frames).item() frame_times = torch.linspace( t0, t0 + (self.cfg.num_frames - 1) / self.cfg.num_frames, self.cfg.num_frames, ) else: frame_times = torch.linspace(0.0, 1.0, self.cfg.num_frames) return { "rays_o": rays_o, "rays_d": rays_d, "mvp_mtx": mvp_mtx, "camera_positions": camera_positions, "c2w": c2w, "light_positions": light_positions, "elevation": elevation_deg, "azimuth": azimuth_deg, "camera_distances": camera_distances, "height": self.height, "width": self.width, "fovy": fovy, "frame_times": frame_times, "train_dynamic_camera": False, } @register("4dfy-random-multiview-camera-datamodule") class RandomMultiviewCameraDataModule(pl.LightningDataModule): cfg: RandomMultiviewCameraDataModuleConfig def __init__(self, cfg: Optional[Union[dict, DictConfig]] = None) -> None: super().__init__() self.cfg = parse_structured(RandomMultiviewCameraDataModuleConfig, cfg) def setup(self, stage=None) -> None: if stage in [None, "fit"]: self.train_dataset = RandomMultiviewCameraIterableDataset(self.cfg) if stage in [None, "fit", "validate"]:
self.val_dataset = RandomCameraDataset(self.cfg, "val")
1
2023-12-01 15:10:28+00:00
12k
camenduru/magicanimate-hf
magicanimate/models/unet_controlnet.py
[ { "identifier": "CrossAttnDownBlock3D", "path": "magicanimate/models/unet_3d_blocks.py", "snippet": "class CrossAttnDownBlock3D(nn.Module):\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n temb_channels: int,\n dropout: float = 0.0,\n num_la...
from dataclasses import dataclass from typing import List, Optional, Tuple, Union from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.models.modeling_utils import ModelMixin from diffusers.utils import BaseOutput, logging from diffusers.models.embeddings import TimestepEmbedding, Timesteps from magicanimate.models.unet_3d_blocks import ( CrossAttnDownBlock3D, CrossAttnUpBlock3D, DownBlock3D, UNetMidBlock3DCrossAttn, UpBlock3D, get_down_block, get_up_block, ) from .resnet import InflatedConv3d from diffusers.utils import WEIGHTS_NAME import os import json import torch import torch.nn as nn import torch.utils.checkpoint
8,210
): super().__init__() self.sample_size = sample_size time_embed_dim = block_out_channels[0] * 4 # input self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1)) # time self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) # class embedding if class_embed_type is None and num_class_embeds is not None: self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim) elif class_embed_type == "timestep": self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) else: self.class_embedding = None self.down_blocks = nn.ModuleList([]) self.mid_block = None self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): only_cross_attention = [only_cross_attention] * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): res = 2 ** i input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 down_block = get_down_block( down_block_type, num_layers=layers_per_block, in_channels=input_channel, out_channels=output_channel, temb_channels=time_embed_dim, add_downsample=not is_final_block, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=attention_head_dim[i], downsample_padding=downsample_padding, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_motion_module=use_motion_module and (res in motion_module_resolutions) and (not motion_module_decoder_only), motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlock3DCrossAttn": self.mid_block = UNetMidBlock3DCrossAttn( in_channels=block_out_channels[-1], temb_channels=time_embed_dim, resnet_eps=norm_eps, resnet_act_fn=act_fn, output_scale_factor=mid_block_scale_factor, resnet_time_scale_shift=resnet_time_scale_shift, cross_attention_dim=cross_attention_dim, attn_num_head_channels=attention_head_dim[-1], resnet_groups=norm_num_groups, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, upcast_attention=upcast_attention, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_motion_module=use_motion_module and motion_module_mid_block, motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) else: raise ValueError(f"unknown mid_block_type : {mid_block_type}") # count how many layers upsample the videos self.num_upsamplers = 0 # up reversed_block_out_channels = list(reversed(block_out_channels)) reversed_attention_head_dim = list(reversed(attention_head_dim)) only_cross_attention = list(reversed(only_cross_attention)) output_channel = reversed_block_out_channels[0] for i, up_block_type in enumerate(up_block_types): res = 2 ** (3 - i) is_final_block = i == len(block_out_channels) - 1 prev_output_channel = output_channel output_channel = reversed_block_out_channels[i] input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)] # add upsample block for all BUT final layer if not is_final_block: add_upsample = True self.num_upsamplers += 1 else: add_upsample = False
# ************************************************************************* # 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.. # ************************************************************************* # 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. logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class UNet3DConditionOutput(BaseOutput): sample: torch.FloatTensor class UNet3DConditionModel(ModelMixin, ConfigMixin): _supports_gradient_checkpointing = True @register_to_config def __init__( self, sample_size: Optional[int] = None, in_channels: int = 4, out_channels: int = 4, center_input_sample: bool = False, flip_sin_to_cos: bool = True, freq_shift: int = 0, down_block_types: Tuple[str] = ( "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D", ), mid_block_type: str = "UNetMidBlock3DCrossAttn", up_block_types: Tuple[str] = ( "UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D" ), only_cross_attention: Union[bool, Tuple[bool]] = False, block_out_channels: Tuple[int] = (320, 640, 1280, 1280), layers_per_block: int = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: int = 32, norm_eps: float = 1e-5, cross_attention_dim: int = 1280, attention_head_dim: Union[int, Tuple[int]] = 8, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", # Additional use_motion_module = False, motion_module_resolutions = ( 1,2,4,8 ), motion_module_mid_block = False, motion_module_decoder_only = False, motion_module_type = None, motion_module_kwargs = {}, unet_use_cross_frame_attention = None, unet_use_temporal_attention = None, ): super().__init__() self.sample_size = sample_size time_embed_dim = block_out_channels[0] * 4 # input self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1)) # time self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) # class embedding if class_embed_type is None and num_class_embeds is not None: self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim) elif class_embed_type == "timestep": self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) else: self.class_embedding = None self.down_blocks = nn.ModuleList([]) self.mid_block = None self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): only_cross_attention = [only_cross_attention] * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): res = 2 ** i input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 down_block = get_down_block( down_block_type, num_layers=layers_per_block, in_channels=input_channel, out_channels=output_channel, temb_channels=time_embed_dim, add_downsample=not is_final_block, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=attention_head_dim[i], downsample_padding=downsample_padding, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_motion_module=use_motion_module and (res in motion_module_resolutions) and (not motion_module_decoder_only), motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlock3DCrossAttn": self.mid_block = UNetMidBlock3DCrossAttn( in_channels=block_out_channels[-1], temb_channels=time_embed_dim, resnet_eps=norm_eps, resnet_act_fn=act_fn, output_scale_factor=mid_block_scale_factor, resnet_time_scale_shift=resnet_time_scale_shift, cross_attention_dim=cross_attention_dim, attn_num_head_channels=attention_head_dim[-1], resnet_groups=norm_num_groups, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, upcast_attention=upcast_attention, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_motion_module=use_motion_module and motion_module_mid_block, motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) else: raise ValueError(f"unknown mid_block_type : {mid_block_type}") # count how many layers upsample the videos self.num_upsamplers = 0 # up reversed_block_out_channels = list(reversed(block_out_channels)) reversed_attention_head_dim = list(reversed(attention_head_dim)) only_cross_attention = list(reversed(only_cross_attention)) output_channel = reversed_block_out_channels[0] for i, up_block_type in enumerate(up_block_types): res = 2 ** (3 - i) is_final_block = i == len(block_out_channels) - 1 prev_output_channel = output_channel output_channel = reversed_block_out_channels[i] input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)] # add upsample block for all BUT final layer if not is_final_block: add_upsample = True self.num_upsamplers += 1 else: add_upsample = False
up_block = get_up_block(
6
2023-12-04 20:47:34+00:00
12k
TISUnion/PrimeBackup
prime_backup/mcdr/task/backup/prune_backup_task.py
[ { "identifier": "DeleteBackupAction", "path": "prime_backup/action/delete_backup_action.py", "snippet": "class DeleteBackupAction(Action[DeleteBackupResult]):\n\tdef __init__(self, backup_id: int):\n\t\tsuper().__init__()\n\t\tself.backup_id = misc_utils.ensure_type(backup_id, int)\n\n\tdef run(self) ->...
import collections import dataclasses import datetime import functools import time import pytz from typing import List, NamedTuple, Dict, Union, Optional, Callable from mcdreforged.api.all import * from prime_backup.action.delete_backup_action import DeleteBackupAction from prime_backup.action.list_backup_action import ListBackupAction from prime_backup.config.prune_config import PruneSetting from prime_backup.exceptions import BackupNotFound from prime_backup.mcdr.task.basic_task import HeavyTask from prime_backup.mcdr.text_components import TextComponents from prime_backup.types.backup_filter import BackupFilter from prime_backup.types.backup_info import BackupInfo from prime_backup.types.blob_info import BlobListSummary from prime_backup.types.units import ByteCount from prime_backup.utils import misc_utils, log_utils from prime_backup.types.backup_tags import BackupTags from prime_backup.types.operator import Operator
7,397
if backup.id in marks: continue if backup.tags.is_protected(): marks[backup.id] = PruneMark.create_protected() continue bucket = bucket_mapper(backup) if bucket in already_included: existed = already_included[bucket] fallback_marks[backup.id] = fallback_marks.get(backup.id) or PruneMark.create_remove(f'superseded by {existed.id} ({policy})') continue if bucket in handled_buckets: existed = handled_buckets[bucket] marks[backup.id] = PruneMark.create_remove(f'superseded by {existed.id} ({policy})') else: if 0 <= limit <= len(handled_buckets): break handled_buckets[bucket] = backup marks[backup.id] = PruneMark.create_keep(f'keep {policy} {len(handled_buckets)}') def create_time_str_func(fmt: str): def func(backup: BackupInfo) -> str: timestamp = backup.timestamp_ns / 1e9 dt = datetime.datetime.fromtimestamp(timestamp, tz=timezone) return dt.strftime(fmt) return func if settings.last != 0: def __backup_to_id(b: BackupInfo) -> str: return str(b.id) mark_selections(settings.last, 'last', __backup_to_id) if settings.hour != 0: mark_selections(settings.hour, 'hour', create_time_str_func('%Y/%m/%d/%H')) if settings.day != 0: mark_selections(settings.day, 'day', create_time_str_func('%Y/%m/%d')) if settings.week != 0: mark_selections(settings.week, 'week', create_time_str_func('%G/%V')) if settings.month != 0: mark_selections(settings.month, 'month', create_time_str_func('%Y/%m')) if settings.year != 0: mark_selections(settings.year, 'year', create_time_str_func('%Y')) plan_list = PrunePlan() now = time.time_ns() regular_keep_count = 0 all_marks = collections.ChainMap(marks, fallback_marks) default_mark = PruneMark.create_remove('unmarked') for backup_info in backups: if backup_info.tags.is_protected(): plan_list.append(PrunePlanItem(backup_info, PruneMark.create_protected())) else: mark = all_marks.get(backup_info.id, default_mark) if mark.keep: if 0 < settings.max_amount <= regular_keep_count: mark = PruneMark.create_remove('max_amount exceeded') elif 0 < settings.max_lifetime.value_nano < (now - backup_info.timestamp_ns): mark = PruneMark.create_remove('max_lifetime exceeded') plan_list.append(PrunePlanItem(backup_info, mark)) if mark.keep: regular_keep_count += 1 return plan_list def __msg_header(self) -> RTextBase: return RTextList('(', self.what_to_prune, ') ').set_color(RColor.gray) def reply(self, msg: Union[str, RTextBase], *, with_prefix: bool = True): if self.what_to_prune is not None: msg = self.__msg_header() + msg super().reply(msg, with_prefix=with_prefix) def run(self) -> PruneBackupResult: backups = ListBackupAction(backup_filter=self.backup_filter).run() backup_ids = {backup.id for backup in backups} timezone: Optional[datetime.tzinfo] = None if (timezone_override := self.config.prune.timezone_override) is not None: try: timezone = pytz.timezone(timezone_override) except pytz.UnknownTimeZoneError as e: self.logger.error('Bad timezone override from config, using local timezone: {}'.format(e)) else: timezone = None plan_list = self.calc_prune_backups(backups, self.setting, timezone=timezone) for pl in plan_list: misc_utils.assert_true(pl.backup.id in backup_ids, lambda: 'unexpected backup id {}, {}'.format(pl.backup.id, backup_ids)) result = PruneBackupResult(plan_list) with log_utils.open_file_logger('prune') as prune_logger: prune_logger.info('Prune started') to_deleted_ids = [pl.backup.id for pl in plan_list if not pl.mark.keep] if len(to_deleted_ids) == 0: if self.verbose >= _PruneVerbose.all: self.reply_tr('nothing_to_prune') prune_logger.info('Nothing to prune') return result prune_logger.info('============== Prune calculate result start ==============') for pl in plan_list: prune_logger.info('Backup #{} at {}: keep={} reason={}'.format(pl.backup.id, pl.backup.date_str, pl.mark.keep, pl.mark.reason)) prune_logger.info('============== Prune calculate result end ==============') if self.verbose >= _PruneVerbose.delete: self.reply_tr( 'list_to_be_pruned', TextComponents.number(len(to_deleted_ids)), TextComponents.backup_id_list(to_deleted_ids, hover=False, click=False), ) for pl in plan_list: bid = pl.backup.id if self.aborted_event.is_set(): if self.verbose >= _PruneVerbose.delete: self.reply(self.get_aborted_text()) break if not pl.mark.keep: self.reply_tr('prune', TextComponents.backup_id(bid, hover=False, click=False)) try: dr = DeleteBackupAction(bid).run() except Exception as e:
class _PruneVerbose: silent = 0 delete = 1 all = 2 class PruneMark(NamedTuple): keep: bool reason: str def is_protected(self) -> bool: return self.keep and self.reason == 'protected' @classmethod def create_keep(cls, reason: str) -> 'PruneMark': return PruneMark(True, reason) @classmethod def create_protected(cls) -> 'PruneMark': return PruneMark(True, 'protected') @classmethod def create_remove(cls, reason: str) -> 'PruneMark': return PruneMark(False, reason) class PrunePlanItem(NamedTuple): backup: BackupInfo mark: PruneMark class PrunePlan(List[PrunePlanItem]): def get_keep_reason(self, backup_or_id: Union[int, BackupInfo]) -> Optional[str]: if isinstance(backup_or_id, BackupInfo): backup_or_id = backup_or_id.id mark = self.id_to_mark[backup_or_id] if mark.keep: return mark.reason return None @functools.cached_property def id_to_mark(self) -> Dict[int, PruneMark]: return {pri.backup.id: pri.mark for pri in self} @dataclasses.dataclass class PruneBackupResult: plan: PrunePlan deleted_backup_count: int = 0 deleted_blobs: BlobListSummary = BlobListSummary.zero() @dataclasses.dataclass class PruneAllBackupResult: sub_plans: List[PrunePlan] = dataclasses.field(default_factory=list) deleted_backup_count: int = 0 deleted_blobs: BlobListSummary = BlobListSummary.zero() class PruneBackupTask(HeavyTask[PruneBackupResult]): def __init__(self, source: CommandSource, backup_filter: BackupFilter, setting: PruneSetting, *, what_to_prune: Optional[RTextBase] = None, verbose: int = 2): super().__init__(source) self.backup_filter = backup_filter self.setting = setting if not setting.enabled: raise ValueError('the prune setting should be enabled') self.what_to_prune = what_to_prune self.verbose = verbose @property def id(self) -> str: return 'backup_prune' def is_abort_able(self) -> bool: return True @classmethod def calc_prune_backups(cls, backups: List[BackupInfo], settings: PruneSetting, *, timezone: Optional[datetime.tzinfo] = None) -> PrunePlan: marks: Dict[int, PruneMark] = {} fallback_marks: Dict[int, PruneMark] = {} backups = list(sorted(backups, key=lambda b: b.timestamp_ns, reverse=True)) # new -> old def has_mark(backup: BackupInfo, keep: bool, protect: Optional[bool] = None) -> bool: if (m := marks.get(backup.id)) is None: return False return m.keep == keep and (protect is None or m.is_protected() == protect) # ref: https://github.com/proxmox/proxmox-backup/blob/master/pbs-datastore/src/prune.rs def mark_selections(limit: int, policy: str, bucket_mapper: Callable[[BackupInfo], str]): already_included: Dict[str, BackupInfo] = {} handled_buckets: Dict[str, BackupInfo] = {} for backup in backups: if has_mark(backup, True, False): already_included[bucket_mapper(backup)] = backup for backup in backups: if backup.id in marks: continue if backup.tags.is_protected(): marks[backup.id] = PruneMark.create_protected() continue bucket = bucket_mapper(backup) if bucket in already_included: existed = already_included[bucket] fallback_marks[backup.id] = fallback_marks.get(backup.id) or PruneMark.create_remove(f'superseded by {existed.id} ({policy})') continue if bucket in handled_buckets: existed = handled_buckets[bucket] marks[backup.id] = PruneMark.create_remove(f'superseded by {existed.id} ({policy})') else: if 0 <= limit <= len(handled_buckets): break handled_buckets[bucket] = backup marks[backup.id] = PruneMark.create_keep(f'keep {policy} {len(handled_buckets)}') def create_time_str_func(fmt: str): def func(backup: BackupInfo) -> str: timestamp = backup.timestamp_ns / 1e9 dt = datetime.datetime.fromtimestamp(timestamp, tz=timezone) return dt.strftime(fmt) return func if settings.last != 0: def __backup_to_id(b: BackupInfo) -> str: return str(b.id) mark_selections(settings.last, 'last', __backup_to_id) if settings.hour != 0: mark_selections(settings.hour, 'hour', create_time_str_func('%Y/%m/%d/%H')) if settings.day != 0: mark_selections(settings.day, 'day', create_time_str_func('%Y/%m/%d')) if settings.week != 0: mark_selections(settings.week, 'week', create_time_str_func('%G/%V')) if settings.month != 0: mark_selections(settings.month, 'month', create_time_str_func('%Y/%m')) if settings.year != 0: mark_selections(settings.year, 'year', create_time_str_func('%Y')) plan_list = PrunePlan() now = time.time_ns() regular_keep_count = 0 all_marks = collections.ChainMap(marks, fallback_marks) default_mark = PruneMark.create_remove('unmarked') for backup_info in backups: if backup_info.tags.is_protected(): plan_list.append(PrunePlanItem(backup_info, PruneMark.create_protected())) else: mark = all_marks.get(backup_info.id, default_mark) if mark.keep: if 0 < settings.max_amount <= regular_keep_count: mark = PruneMark.create_remove('max_amount exceeded') elif 0 < settings.max_lifetime.value_nano < (now - backup_info.timestamp_ns): mark = PruneMark.create_remove('max_lifetime exceeded') plan_list.append(PrunePlanItem(backup_info, mark)) if mark.keep: regular_keep_count += 1 return plan_list def __msg_header(self) -> RTextBase: return RTextList('(', self.what_to_prune, ') ').set_color(RColor.gray) def reply(self, msg: Union[str, RTextBase], *, with_prefix: bool = True): if self.what_to_prune is not None: msg = self.__msg_header() + msg super().reply(msg, with_prefix=with_prefix) def run(self) -> PruneBackupResult: backups = ListBackupAction(backup_filter=self.backup_filter).run() backup_ids = {backup.id for backup in backups} timezone: Optional[datetime.tzinfo] = None if (timezone_override := self.config.prune.timezone_override) is not None: try: timezone = pytz.timezone(timezone_override) except pytz.UnknownTimeZoneError as e: self.logger.error('Bad timezone override from config, using local timezone: {}'.format(e)) else: timezone = None plan_list = self.calc_prune_backups(backups, self.setting, timezone=timezone) for pl in plan_list: misc_utils.assert_true(pl.backup.id in backup_ids, lambda: 'unexpected backup id {}, {}'.format(pl.backup.id, backup_ids)) result = PruneBackupResult(plan_list) with log_utils.open_file_logger('prune') as prune_logger: prune_logger.info('Prune started') to_deleted_ids = [pl.backup.id for pl in plan_list if not pl.mark.keep] if len(to_deleted_ids) == 0: if self.verbose >= _PruneVerbose.all: self.reply_tr('nothing_to_prune') prune_logger.info('Nothing to prune') return result prune_logger.info('============== Prune calculate result start ==============') for pl in plan_list: prune_logger.info('Backup #{} at {}: keep={} reason={}'.format(pl.backup.id, pl.backup.date_str, pl.mark.keep, pl.mark.reason)) prune_logger.info('============== Prune calculate result end ==============') if self.verbose >= _PruneVerbose.delete: self.reply_tr( 'list_to_be_pruned', TextComponents.number(len(to_deleted_ids)), TextComponents.backup_id_list(to_deleted_ids, hover=False, click=False), ) for pl in plan_list: bid = pl.backup.id if self.aborted_event.is_set(): if self.verbose >= _PruneVerbose.delete: self.reply(self.get_aborted_text()) break if not pl.mark.keep: self.reply_tr('prune', TextComponents.backup_id(bid, hover=False, click=False)) try: dr = DeleteBackupAction(bid).run() except Exception as e:
if isinstance(e, BackupNotFound):
3
2023-11-28 19:03:36+00:00
12k
TACJu/MaXTron
MaXTron_Tube-Link/mmdet/models/backbones/vitaev2_vsa_modules/ReductionCell.py
[ { "identifier": "Token_transformer", "path": "MaXTron_Tube-Link/mmdet/models/backbones/vitaev2_vsa_modules/token_transformer.py", "snippet": "class Token_transformer(nn.Module):\n\n def __init__(self, dim, in_dim, num_heads, mlp_ratio=1., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,\n ...
import math import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from numpy.core.fromnumeric import resize, shape from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from .token_transformer import Token_transformer from .token_performer import Token_performer from .window import WindowTransformerBlock, VSAWindowAttention, window_partition, window_reverse, Mlp
7,869
self.kernel_size = kernel_size self.stride = downsample_ratio self.share_weights = share_weights self.outSize = img_size // downsample_ratio if share_weights: self.convolution = nn.Conv2d(in_channels=in_chans, out_channels=embed_dim, kernel_size=self.kernel_size, \ stride=self.stride, padding=3*dilations[0]//2, dilation=dilations[0]) else: self.convs = nn.ModuleList() for dilation in self.dilations: padding = math.ceil(((self.kernel_size-1)*dilation + 1 - self.stride) / 2) if img_size % downsample_ratio != 0: padding += 1 self.convs.append(nn.Sequential(*[nn.Conv2d(in_channels=in_chans, out_channels=embed_dim, kernel_size=self.kernel_size, \ stride=self.stride, padding=padding, dilation=dilation), nn.GELU()])) if self.op == 'sum': self.out_chans = embed_dim elif op == 'cat': self.out_chans = embed_dim * len(self.dilations) def forward(self, x): B, C, W, H = x.shape if self.share_weights: padding = math.ceil(((self.kernel_size-1)*self.dilations[0] + 1 - self.stride) / 2) y = nn.functional.conv2d(x, weight=self.convolution.weight, bias=self.convolution.bias, \ stride=self.downsample_ratio, padding=padding, dilation=self.dilations[0]).unsqueeze(dim=-1) for i in range(1, len(self.dilations)): padding = math.ceil(((self.kernel_size-1)*self.dilations[i] + 1 - self.stride) / 2) _y = nn.functional.conv2d(x, weight=self.convolution.weight, bias=self.convolution.bias, \ stride=self.downsample_ratio, padding=padding, dilation=self.dilations[i]).unsqueeze(dim=-1) y = torch.cat((y, _y), dim=-1) else: y = self.convs[0](x).unsqueeze(dim=-1) for i in range(1, len(self.dilations)): _y = self.convs[i](x).unsqueeze(dim=-1) y = torch.cat((y, _y), dim=-1) B, C, W, H, N = y.shape if self.op == 'sum': y = y.sum(dim=-1).flatten(2).permute(0,2,1).contiguous() elif self.op == 'cat': y = y.permute(0,4,1,2,3).flatten(3).reshape(B, N*C, W*H).permute(0,2,1).contiguous() else: raise NotImplementedError('no such operation: {} for multi-levels!'.format(self.op)) return y, (W, H) class ReductionCell(nn.Module): def __init__(self, img_size=224, in_chans=3, embed_dims=64, wide_pcm=False, token_dims=64, downsample_ratios=4, kernel_size=7, num_heads=1, dilations=[1,2,3,4], share_weights=False, op='cat', tokens_type='performer', group=1, relative_pos=False, cpe=False, drop=0., attn_drop=0., drop_path=0., mlp_ratio=1.0, window_size=7, num_deform=None): super().__init__() self.img_size = img_size self.window_size = window_size self.op = op self.dilations = dilations self.num_heads = num_heads self.embed_dims = embed_dims self.token_dims = token_dims self.in_chans = in_chans self.downsample_ratios = downsample_ratios self.kernel_size = kernel_size self.outSize = img_size self.relative_pos = relative_pos self.cpe = cpe PCMStride = [] residual = downsample_ratios // 2 for _ in range(3): PCMStride.append((residual > 0) + 1) residual = residual // 2 assert residual == 0 self.pool = None self.tokens_type = tokens_type if tokens_type == 'pooling': PCMStride = [1, 1, 1] self.pool = nn.MaxPool2d(downsample_ratios, stride=downsample_ratios, padding=0) tokens_type = 'transformer' self.outSize = self.outSize // downsample_ratios downsample_ratios = 1 if not wide_pcm: self.PCM = nn.Sequential( nn.Conv2d(in_chans, embed_dims, kernel_size=(3, 3), stride=PCMStride[0], padding=(1, 1), groups=group), # the 1st convolution nn.BatchNorm2d(embed_dims), nn.SiLU(inplace=True), nn.Conv2d(embed_dims, embed_dims, kernel_size=(3, 3), stride=PCMStride[1], padding=(1, 1), groups=group), # the 1st convolution nn.BatchNorm2d(embed_dims), nn.SiLU(inplace=True), nn.Conv2d(embed_dims, token_dims, kernel_size=(3, 3), stride=PCMStride[2], padding=(1, 1), groups=group), # the 1st convolution ) else: self.PCM = nn.Sequential( nn.Conv2d(in_chans, token_dims*2, kernel_size=(3, 3), stride=PCMStride[0], padding=(1, 1), groups=group), # the 1st convolution nn.BatchNorm2d(token_dims*2), nn.SiLU(inplace=True), nn.Conv2d(token_dims*2, token_dims*2, kernel_size=(3, 3), stride=PCMStride[1], padding=(1, 1), groups=group), # the 1st convolution nn.BatchNorm2d(token_dims*2), nn.SiLU(inplace=True), nn.Conv2d(token_dims*2, token_dims, kernel_size=(3, 3), stride=PCMStride[2], padding=(1, 1), groups=group), # the 1st convolution ) self.PRM = PRM(img_size=img_size, kernel_size=kernel_size, downsample_ratio=downsample_ratios, dilations=self.dilations, in_chans=in_chans, embed_dim=embed_dims, share_weights=share_weights, op=op) self.outSize = self.outSize // downsample_ratios in_chans = self.PRM.out_chans if tokens_type == 'performer': # assert num_heads == 1 self.attn = Token_performer(dim=in_chans, in_dim=token_dims, head_cnt=num_heads, kernel_ratio=0.5) elif tokens_type == 'performer_less': self.attn = None self.PCM = None elif tokens_type == 'transformer': self.attn = Token_transformer(dim=in_chans, in_dim=token_dims, num_heads=num_heads, mlp_ratio=mlp_ratio, drop=drop, attn_drop=attn_drop, drop_path=drop_path) elif tokens_type == 'window':
class PRM(nn.Module): def __init__(self, img_size=224, kernel_size=4, downsample_ratio=4, dilations=[1,6,12], in_chans=3, embed_dim=64, share_weights=False, op='cat'): super().__init__() self.dilations = dilations self.embed_dim = embed_dim self.downsample_ratio = downsample_ratio self.op = op self.kernel_size = kernel_size self.stride = downsample_ratio self.share_weights = share_weights self.outSize = img_size // downsample_ratio if share_weights: self.convolution = nn.Conv2d(in_channels=in_chans, out_channels=embed_dim, kernel_size=self.kernel_size, \ stride=self.stride, padding=3*dilations[0]//2, dilation=dilations[0]) else: self.convs = nn.ModuleList() for dilation in self.dilations: padding = math.ceil(((self.kernel_size-1)*dilation + 1 - self.stride) / 2) if img_size % downsample_ratio != 0: padding += 1 self.convs.append(nn.Sequential(*[nn.Conv2d(in_channels=in_chans, out_channels=embed_dim, kernel_size=self.kernel_size, \ stride=self.stride, padding=padding, dilation=dilation), nn.GELU()])) if self.op == 'sum': self.out_chans = embed_dim elif op == 'cat': self.out_chans = embed_dim * len(self.dilations) def forward(self, x): B, C, W, H = x.shape if self.share_weights: padding = math.ceil(((self.kernel_size-1)*self.dilations[0] + 1 - self.stride) / 2) y = nn.functional.conv2d(x, weight=self.convolution.weight, bias=self.convolution.bias, \ stride=self.downsample_ratio, padding=padding, dilation=self.dilations[0]).unsqueeze(dim=-1) for i in range(1, len(self.dilations)): padding = math.ceil(((self.kernel_size-1)*self.dilations[i] + 1 - self.stride) / 2) _y = nn.functional.conv2d(x, weight=self.convolution.weight, bias=self.convolution.bias, \ stride=self.downsample_ratio, padding=padding, dilation=self.dilations[i]).unsqueeze(dim=-1) y = torch.cat((y, _y), dim=-1) else: y = self.convs[0](x).unsqueeze(dim=-1) for i in range(1, len(self.dilations)): _y = self.convs[i](x).unsqueeze(dim=-1) y = torch.cat((y, _y), dim=-1) B, C, W, H, N = y.shape if self.op == 'sum': y = y.sum(dim=-1).flatten(2).permute(0,2,1).contiguous() elif self.op == 'cat': y = y.permute(0,4,1,2,3).flatten(3).reshape(B, N*C, W*H).permute(0,2,1).contiguous() else: raise NotImplementedError('no such operation: {} for multi-levels!'.format(self.op)) return y, (W, H) class ReductionCell(nn.Module): def __init__(self, img_size=224, in_chans=3, embed_dims=64, wide_pcm=False, token_dims=64, downsample_ratios=4, kernel_size=7, num_heads=1, dilations=[1,2,3,4], share_weights=False, op='cat', tokens_type='performer', group=1, relative_pos=False, cpe=False, drop=0., attn_drop=0., drop_path=0., mlp_ratio=1.0, window_size=7, num_deform=None): super().__init__() self.img_size = img_size self.window_size = window_size self.op = op self.dilations = dilations self.num_heads = num_heads self.embed_dims = embed_dims self.token_dims = token_dims self.in_chans = in_chans self.downsample_ratios = downsample_ratios self.kernel_size = kernel_size self.outSize = img_size self.relative_pos = relative_pos self.cpe = cpe PCMStride = [] residual = downsample_ratios // 2 for _ in range(3): PCMStride.append((residual > 0) + 1) residual = residual // 2 assert residual == 0 self.pool = None self.tokens_type = tokens_type if tokens_type == 'pooling': PCMStride = [1, 1, 1] self.pool = nn.MaxPool2d(downsample_ratios, stride=downsample_ratios, padding=0) tokens_type = 'transformer' self.outSize = self.outSize // downsample_ratios downsample_ratios = 1 if not wide_pcm: self.PCM = nn.Sequential( nn.Conv2d(in_chans, embed_dims, kernel_size=(3, 3), stride=PCMStride[0], padding=(1, 1), groups=group), # the 1st convolution nn.BatchNorm2d(embed_dims), nn.SiLU(inplace=True), nn.Conv2d(embed_dims, embed_dims, kernel_size=(3, 3), stride=PCMStride[1], padding=(1, 1), groups=group), # the 1st convolution nn.BatchNorm2d(embed_dims), nn.SiLU(inplace=True), nn.Conv2d(embed_dims, token_dims, kernel_size=(3, 3), stride=PCMStride[2], padding=(1, 1), groups=group), # the 1st convolution ) else: self.PCM = nn.Sequential( nn.Conv2d(in_chans, token_dims*2, kernel_size=(3, 3), stride=PCMStride[0], padding=(1, 1), groups=group), # the 1st convolution nn.BatchNorm2d(token_dims*2), nn.SiLU(inplace=True), nn.Conv2d(token_dims*2, token_dims*2, kernel_size=(3, 3), stride=PCMStride[1], padding=(1, 1), groups=group), # the 1st convolution nn.BatchNorm2d(token_dims*2), nn.SiLU(inplace=True), nn.Conv2d(token_dims*2, token_dims, kernel_size=(3, 3), stride=PCMStride[2], padding=(1, 1), groups=group), # the 1st convolution ) self.PRM = PRM(img_size=img_size, kernel_size=kernel_size, downsample_ratio=downsample_ratios, dilations=self.dilations, in_chans=in_chans, embed_dim=embed_dims, share_weights=share_weights, op=op) self.outSize = self.outSize // downsample_ratios in_chans = self.PRM.out_chans if tokens_type == 'performer': # assert num_heads == 1 self.attn = Token_performer(dim=in_chans, in_dim=token_dims, head_cnt=num_heads, kernel_ratio=0.5) elif tokens_type == 'performer_less': self.attn = None self.PCM = None elif tokens_type == 'transformer': self.attn = Token_transformer(dim=in_chans, in_dim=token_dims, num_heads=num_heads, mlp_ratio=mlp_ratio, drop=drop, attn_drop=attn_drop, drop_path=drop_path) elif tokens_type == 'window':
self.attn = WindowTransformerBlock(in_dim=in_chans, out_dim=token_dims, input_resolution=(self.img_size//self.downsample_ratios, self.img_size//self.downsample_ratios),
2
2023-12-01 20:08:54+00:00
12k
navervision/lincir
validate.py
[ { "identifier": "collate_fn", "path": "data_utils.py", "snippet": "def collate_fn(batch):\n '''\n function which discard None images in a batch when using torch DataLoader\n :param batch: input_batch\n :return: output_batch = input_batch - None_values\n '''\n batch = list(filter(lambda...
import json import pickle import clip import numpy as np import torch import torch.nn.functional as F from argparse import ArgumentParser from typing import List, Dict, Tuple from clip.model import CLIP from transformers import CLIPTextModelWithProjection from torch.utils.data import DataLoader from torch.utils.data import Dataset from tqdm import tqdm from data_utils import collate_fn, PROJECT_ROOT, targetpad_transform from loader import FashionIQDataset, CIRRDataset, CIRCODataset from encode_with_pseudo_tokens import encode_with_pseudo_tokens_HF from models import build_text_encoder, Phi, PIC2WORD from utils import extract_image_features, device, extract_pseudo_tokens_with_phi
9,603
gt_img_ids = np.array(gt_img_ids)[ np.array(gt_img_ids) != ''] # remove trailing empty strings added for collate_fn similarity = predicted_feature @ index_features.T sorted_indices = torch.topk(similarity, dim=-1, k=50).indices.cpu() sorted_index_names = np.array(index_names)[sorted_indices] map_labels = torch.tensor(np.isin(sorted_index_names, gt_img_ids), dtype=torch.uint8) precisions = torch.cumsum(map_labels, dim=0) * map_labels # Consider only positions corresponding to GTs precisions = precisions / torch.arange(1, map_labels.shape[0] + 1) # Compute precision for each position ap_at5.append(float(torch.sum(precisions[:5]) / min(len(gt_img_ids), 5))) ap_at10.append(float(torch.sum(precisions[:10]) / min(len(gt_img_ids), 10))) ap_at25.append(float(torch.sum(precisions[:25]) / min(len(gt_img_ids), 25))) ap_at50.append(float(torch.sum(precisions[:50]) / min(len(gt_img_ids), 50))) assert target_name == gt_img_ids[0], f"Target name not in GTs {target_name} {gt_img_ids}" single_gt_labels = torch.tensor(sorted_index_names == target_name) recall_at5.append(float(torch.sum(single_gt_labels[:5]))) recall_at10.append(float(torch.sum(single_gt_labels[:10]))) recall_at25.append(float(torch.sum(single_gt_labels[:25]))) recall_at50.append(float(torch.sum(single_gt_labels[:50]))) map_at5 = np.mean(ap_at5) * 100 map_at10 = np.mean(ap_at10) * 100 map_at25 = np.mean(ap_at25) * 100 map_at50 = np.mean(ap_at50) * 100 recall_at5 = np.mean(recall_at5) * 100 recall_at10 = np.mean(recall_at10) * 100 recall_at25 = np.mean(recall_at25) * 100 recall_at50 = np.mean(recall_at50) * 100 return { 'circo_map_at5': map_at5, 'circo_map_at10': map_at10, 'circo_map_at25': map_at25, 'circo_map_at50': map_at50, 'circo_recall_at5': recall_at5, 'circo_recall_at10': recall_at10, 'circo_recall_at25': recall_at25, 'circo_recall_at50': recall_at50, } @torch.no_grad() def circo_val_retrieval(dataset_path: str, image_encoder, text_encoder, ref_names_list: List[str], pseudo_tokens: torch.Tensor, preprocess: callable) -> Dict[str, float]: """ Compute the retrieval metrics on the CIRCO validation set given the pseudo tokens and the reference names """ # Load the model #clip_model, _ = clip.load(clip_model_name, device=device, jit=False) #clip_model = clip_model.float().eval().requires_grad_(False) # Extract the index features classic_val_dataset = CIRCODataset(dataset_path, 'val', 'classic', preprocess) index_features, index_names = extract_image_features(classic_val_dataset, image_encoder) # Define the relative validation dataset relative_val_dataset = CIRCODataset(dataset_path, 'val', 'relative', preprocess) return circo_compute_val_metrics(relative_val_dataset, text_encoder, index_features, index_names, ref_names_list, pseudo_tokens) def main(): parser = ArgumentParser() parser.add_argument("--exp-name", type=str, help="Experiment to evaluate") parser.add_argument("--eval-type", type=str, choices=['oti', 'phi', 'searle', 'searle-xl', 'pic2word'], required=True, help="If 'oti' evaluate directly using the inverted oti pseudo tokens, " "if 'phi' predicts the pseudo tokens using the phi network, " "if 'searle' uses the pre-trained SEARLE model to predict the pseudo tokens, " "if 'searle-xl' uses the pre-trained SEARLE-XL model to predict the pseudo tokens" ) parser.add_argument("--dataset", type=str, required=True, choices=['cirr', 'fashioniq', 'circo'], help="Dataset to use") parser.add_argument("--dataset-path", type=str, help="Path to the dataset", required=True) parser.add_argument("--preprocess-type", default="clip", type=str, choices=['clip', 'targetpad'], help="Preprocess pipeline to use") parser.add_argument("--phi-checkpoint-name", type=str, help="Phi checkpoint to use, needed when using phi, e.g. 'phi_20.pt'") parser.add_argument("--clip_model_name", default="giga", type=str) parser.add_argument("--cache_dir", default="./hf_models", type=str) parser.add_argument("--l2_normalize", action="store_true", help="Whether or not to use l2 normalization") args = parser.parse_args() #if args.eval_type in ['phi', 'oti'] and args.exp_name is None: # raise ValueError("Experiment name is required when using phi or oti evaluation type") if args.eval_type == 'phi' and args.phi_checkpoint_name is None: raise ValueError("Phi checkpoint name is required when using phi evaluation type") if args.eval_type == 'oti': experiment_path = PROJECT_ROOT / 'data' / "oti_pseudo_tokens" / args.dataset.lower() / 'val' / args.exp_name if not experiment_path.exists(): raise ValueError(f"Experiment {args.exp_name} not found") with open(experiment_path / 'hyperparameters.json') as f: hyperparameters = json.load(f) pseudo_tokens = torch.load(experiment_path / 'ema_oti_pseudo_tokens.pt', map_location=device) with open(experiment_path / 'image_names.pkl', 'rb') as f: ref_names_list = pickle.load(f) clip_model_name = hyperparameters['clip_model_name'] clip_model, clip_preprocess = clip.load(clip_model_name, device='cpu', jit=False) if args.preprocess_type == 'targetpad': print('Target pad preprocess pipeline is used') preprocess = targetpad_transform(1.25, clip_model.visual.input_resolution) elif args.preprocess_type == 'clip': print('CLIP preprocess pipeline is used') preprocess = clip_preprocess else: raise ValueError("Preprocess type not supported") elif args.eval_type in ['phi', 'searle', 'searle-xl', 'pic2word']: if args.eval_type == 'phi': args.mixed_precision = 'fp16'
torch.multiprocessing.set_sharing_strategy('file_system') @torch.no_grad() def fiq_generate_val_predictions(clip_model, relative_val_dataset: Dataset, ref_names_list: List[str], pseudo_tokens: torch.Tensor) -> Tuple[torch.Tensor, List[str]]: """ Generates features predictions for the validation set of Fashion IQ. """ # Create data loader relative_val_loader = DataLoader(dataset=relative_val_dataset, batch_size=32, num_workers=10, pin_memory=False, collate_fn=collate_fn, shuffle=False) predicted_features_list = [] target_names_list = [] # Compute features for batch in tqdm(relative_val_loader): reference_names = batch['reference_name'] target_names = batch['target_name'] relative_captions = batch['relative_captions'] flattened_captions: list = np.array(relative_captions).T.flatten().tolist() input_captions = [ f"{flattened_captions[i].strip('.?, ')} and {flattened_captions[i + 1].strip('.?, ')}" for i in range(0, len(flattened_captions), 2)] input_captions_reversed = [ f"{flattened_captions[i + 1].strip('.?, ')} and {flattened_captions[i].strip('.?, ')}" for i in range(0, len(flattened_captions), 2)] input_captions = [ f"a photo of $ that {in_cap}" for in_cap in input_captions] batch_tokens = torch.vstack([pseudo_tokens[ref_names_list.index(ref)].unsqueeze(0) for ref in reference_names]) tokenized_input_captions = clip.tokenize(input_captions, context_length=77).to(device) text_features = encode_with_pseudo_tokens_HF(clip_model, tokenized_input_captions, batch_tokens) input_captions_reversed = [ f"a photo of $ that {in_cap}" for in_cap in input_captions_reversed] tokenized_input_captions_reversed = clip.tokenize(input_captions_reversed, context_length=77).to(device) text_features_reversed = encode_with_pseudo_tokens_HF(clip_model, tokenized_input_captions_reversed, batch_tokens) predicted_features = F.normalize((F.normalize(text_features) + F.normalize(text_features_reversed)) / 2) # predicted_features = F.normalize((text_features + text_features_reversed) / 2) predicted_features_list.append(predicted_features) target_names_list.extend(target_names) predicted_features = torch.vstack(predicted_features_list) return predicted_features, target_names_list @torch.no_grad() def fiq_compute_val_metrics(relative_val_dataset: Dataset, clip_model, index_features: torch.Tensor, index_names: List[str], ref_names_list: List[str], pseudo_tokens: torch.Tensor) \ -> Dict[str, float]: """ Compute the retrieval metrics on the FashionIQ validation set given the dataset, pseudo tokens and the reference names """ # Generate the predicted features predicted_features, target_names = fiq_generate_val_predictions(clip_model, relative_val_dataset, ref_names_list, pseudo_tokens) # Move the features to the device index_features = index_features.to(device) predicted_features = predicted_features.to(device) # Normalize the features index_features = F.normalize(index_features.float()) # Compute the distances distances = 1 - predicted_features @ index_features.T sorted_indices = torch.argsort(distances, dim=-1).cpu() sorted_index_names = np.array(index_names)[sorted_indices] # Check if the target names are in the top 10 and top 50 labels = torch.tensor( sorted_index_names == np.repeat(np.array(target_names), len(index_names)).reshape(len(target_names), -1)) assert torch.equal(torch.sum(labels, dim=-1).int(), torch.ones(len(target_names)).int()) # Compute the metrics recall_at10 = (torch.sum(labels[:, :10]) / len(labels)).item() * 100 recall_at50 = (torch.sum(labels[:, :50]) / len(labels)).item() * 100 return {'fiq_recall_at10': recall_at10, 'fiq_recall_at50': recall_at50} @torch.no_grad() def fiq_val_retrieval(dataset_path: str, dress_type: str, image_encoder, text_encoder, ref_names_list: List[str], pseudo_tokens: torch.Tensor, preprocess: callable) -> Dict[str, float]: """ Compute the retrieval metrics on the FashionIQ validation set given the pseudo tokens and the reference names """ # Load the model #clip_model, _ = clip.load(clip_model_name, device=device, jit=False) #clip_model = clip_model.float().eval().requires_grad_(False) # Extract the index features classic_val_dataset = FashionIQDataset(dataset_path, 'val', [dress_type], 'classic', preprocess) index_features, index_names = extract_image_features(classic_val_dataset, image_encoder) # Define the relative dataset relative_val_dataset = FashionIQDataset(dataset_path, 'val', [dress_type], 'relative', preprocess) return fiq_compute_val_metrics(relative_val_dataset, text_encoder, index_features, index_names, ref_names_list, pseudo_tokens) @torch.no_grad() def cirr_generate_val_predictions(clip_model: CLIPTextModelWithProjection, relative_val_dataset: Dataset, ref_names_list: List[str], pseudo_tokens: torch.Tensor) -> \ Tuple[torch.Tensor, List[str], List[str], List[List[str]]]: """ Generates features predictions for the validation set of CIRR """ # Define the dataloader relative_val_loader = DataLoader(dataset=relative_val_dataset, batch_size=32, num_workers=10, pin_memory=False, collate_fn=collate_fn) predicted_features_list = [] target_names_list = [] group_members_list = [] reference_names_list = [] for batch in tqdm(relative_val_loader): reference_names = batch['reference_name'] target_names = batch['target_name'] relative_captions = batch['relative_caption'] group_members = batch['group_members'] group_members = np.array(group_members).T.tolist() input_captions = [ f"a photo of $ that {rel_caption}" for rel_caption in relative_captions] batch_tokens = torch.vstack([pseudo_tokens[ref_names_list.index(ref)].unsqueeze(0) for ref in reference_names]) tokenized_input_captions = clip.tokenize(input_captions, context_length=77).to(device) text_features = encode_with_pseudo_tokens_HF(clip_model, tokenized_input_captions, batch_tokens) predicted_features = F.normalize(text_features) predicted_features_list.append(predicted_features) target_names_list.extend(target_names) group_members_list.extend(group_members) reference_names_list.extend(reference_names) predicted_features = torch.vstack(predicted_features_list) return predicted_features, reference_names_list, target_names_list, group_members_list @torch.no_grad() def cirr_generate_val_predictions_with_phi(clip_model: CLIPTextModelWithProjection, phi, relative_val_dataset: Dataset, ref_names_list: List[str], image_features: torch.Tensor) -> \ Tuple[torch.Tensor, List[str], List[str], List[List[str]]]: """ Generates features predictions for the validation set of CIRR """ # Define the dataloader relative_val_loader = DataLoader(dataset=relative_val_dataset, batch_size=32, num_workers=10, pin_memory=False, collate_fn=collate_fn) predicted_features_list = [] target_names_list = [] group_members_list = [] reference_names_list = [] for batch in tqdm(relative_val_loader): reference_names = batch['reference_name'] target_names = batch['target_name'] relative_captions = batch['relative_caption'] group_members = batch['group_members'] group_members = np.array(group_members).T.tolist() input_captions = [ f"a photo of $ that {rel_caption}" for rel_caption in relative_captions] # we need to make batch_tokens with selected_image_features selected_image_features = torch.vstack([image_features[ref_names_list.index(ref)] for ref in reference_names]) tokenized_input_captions = clip.tokenize(input_captions, context_length=77).to(device) context = clip_model.text_model.embeddings.token_embedding(tokenized_input_captions) + clip_model.text_model.embeddings.position_embedding(clip_model.text_model.embeddings.position_ids) batch_tokens = phi(selected_image_features, context) #batch_tokens = torch.vstack([pseudo_tokens[ref_names_list.index(ref)].unsqueeze(0) for ref in reference_names]) text_features = encode_with_pseudo_tokens_HF(clip_model, tokenized_input_captions, batch_tokens) predicted_features = F.normalize(text_features) predicted_features_list.append(predicted_features) target_names_list.extend(target_names) group_members_list.extend(group_members) reference_names_list.extend(reference_names) predicted_features = torch.vstack(predicted_features_list) return predicted_features, reference_names_list, target_names_list, group_members_list @torch.no_grad() def cirr_compute_val_metrics(relative_val_dataset: Dataset, clip_model, index_features: torch.Tensor, index_names: List[str], ref_names_list: List[str], pseudo_tokens: torch.Tensor) \ -> Dict[str, float]: """ Compute the retrieval metrics on the CIRR validation set given the dataset, pseudo tokens and the reference names """ # Generate the predicted features predicted_features, reference_names, target_names, group_members = \ cirr_generate_val_predictions(clip_model, relative_val_dataset, ref_names_list, pseudo_tokens) index_features = index_features.to(device) predicted_features = predicted_features.to(device) # Normalize the index features index_features = F.normalize(index_features, dim=-1).float() predicted_features = predicted_features.float() # Compute the distances and sort the results distances = 1 - predicted_features @ index_features.T sorted_indices = torch.argsort(distances, dim=-1).cpu() sorted_index_names = np.array(index_names)[sorted_indices] # Delete the reference image from the results reference_mask = torch.tensor( sorted_index_names != np.repeat(np.array(reference_names), len(index_names)).reshape(len(target_names), -1)) sorted_index_names = sorted_index_names[reference_mask].reshape(sorted_index_names.shape[0], sorted_index_names.shape[1] - 1) # Compute the ground-truth labels wrt the predictions labels = torch.tensor( sorted_index_names == np.repeat(np.array(target_names), len(index_names) - 1).reshape(len(target_names), -1)) # Compute the subset predictions and ground-truth labels group_members = np.array(group_members) group_mask = (sorted_index_names[..., None] == group_members[:, None, :]).sum(-1).astype(bool) group_labels = labels[group_mask].reshape(labels.shape[0], -1) assert torch.equal(torch.sum(labels, dim=-1).int(), torch.ones(len(target_names)).int()) assert torch.equal(torch.sum(group_labels, dim=-1).int(), torch.ones(len(target_names)).int()) # Compute the metrics recall_at1 = (torch.sum(labels[:, :1]) / len(labels)).item() * 100 recall_at5 = (torch.sum(labels[:, :5]) / len(labels)).item() * 100 recall_at10 = (torch.sum(labels[:, :10]) / len(labels)).item() * 100 recall_at50 = (torch.sum(labels[:, :50]) / len(labels)).item() * 100 group_recall_at1 = (torch.sum(group_labels[:, :1]) / len(group_labels)).item() * 100 group_recall_at2 = (torch.sum(group_labels[:, :2]) / len(group_labels)).item() * 100 group_recall_at3 = (torch.sum(group_labels[:, :3]) / len(group_labels)).item() * 100 return { 'cirr_recall_at1': recall_at1, 'cirr_recall_at5': recall_at5, 'cirr_recall_at10': recall_at10, 'cirr_recall_at50': recall_at50, 'cirr_group_recall_at1': group_recall_at1, 'cirr_group_recall_at2': group_recall_at2, 'cirr_group_recall_at3': group_recall_at3, } @torch.no_grad() def cirr_compute_val_metrics_with_phi(relative_val_dataset: Dataset, clip_model: CLIPTextModelWithProjection, phi, index_features: torch.Tensor, index_names: List[str], ref_names_list: List[str], image_features: torch.Tensor) \ -> Dict[str, float]: """ Compute the retrieval metrics on the CIRR validation set given the dataset, pseudo tokens and the reference names """ # Generate the predicted features predicted_features, reference_names, target_names, group_members = \ cirr_generate_val_predictions_with_phi(clip_model, phi, relative_val_dataset, ref_names_list, image_features) index_features = index_features.to(device) predicted_features = predicted_features.to(device) # Normalize the index features index_features = F.normalize(index_features, dim=-1).float() predicted_features = predicted_features.float() # Compute the distances and sort the results distances = 1 - predicted_features @ index_features.T sorted_indices = torch.argsort(distances, dim=-1).cpu() sorted_index_names = np.array(index_names)[sorted_indices] # Delete the reference image from the results reference_mask = torch.tensor( sorted_index_names != np.repeat(np.array(reference_names), len(index_names)).reshape(len(target_names), -1)) sorted_index_names = sorted_index_names[reference_mask].reshape(sorted_index_names.shape[0], sorted_index_names.shape[1] - 1) # Compute the ground-truth labels wrt the predictions labels = torch.tensor( sorted_index_names == np.repeat(np.array(target_names), len(index_names) - 1).reshape(len(target_names), -1)) # Compute the subset predictions and ground-truth labels group_members = np.array(group_members) group_mask = (sorted_index_names[..., None] == group_members[:, None, :]).sum(-1).astype(bool) group_labels = labels[group_mask].reshape(labels.shape[0], -1) assert torch.equal(torch.sum(labels, dim=-1).int(), torch.ones(len(target_names)).int()) assert torch.equal(torch.sum(group_labels, dim=-1).int(), torch.ones(len(target_names)).int()) # Compute the metrics recall_at1 = (torch.sum(labels[:, :1]) / len(labels)).item() * 100 recall_at5 = (torch.sum(labels[:, :5]) / len(labels)).item() * 100 recall_at10 = (torch.sum(labels[:, :10]) / len(labels)).item() * 100 recall_at50 = (torch.sum(labels[:, :50]) / len(labels)).item() * 100 group_recall_at1 = (torch.sum(group_labels[:, :1]) / len(group_labels)).item() * 100 group_recall_at2 = (torch.sum(group_labels[:, :2]) / len(group_labels)).item() * 100 group_recall_at3 = (torch.sum(group_labels[:, :3]) / len(group_labels)).item() * 100 return { 'cirr_recall_at1': recall_at1, 'cirr_recall_at5': recall_at5, 'cirr_recall_at10': recall_at10, 'cirr_recall_at50': recall_at50, 'cirr_group_recall_at1': group_recall_at1, 'cirr_group_recall_at2': group_recall_at2, 'cirr_group_recall_at3': group_recall_at3, } @torch.no_grad() def cirr_val_retrieval(dataset_path: str, image_encoder, text_encoder, ref_names_list: list, pseudo_tokens: torch.Tensor, preprocess: callable) -> Dict[str, float]: """ Compute the retrieval metrics on the CIRR validation set given the pseudo tokens and the reference names """ # Load the model #clip_model, _ = clip.load(clip_model_name, device=device, jit=False) #clip_model = clip_model.float().eval().requires_grad_(False) # Extract the index features classic_val_dataset = CIRRDataset(dataset_path, 'val', 'classic', preprocess) index_features, index_names = extract_image_features(classic_val_dataset, image_encoder) # Define the relative validation dataset relative_val_dataset = CIRRDataset(dataset_path, 'val', 'relative', preprocess) return cirr_compute_val_metrics(relative_val_dataset, text_encoder, index_features, index_names, ref_names_list, pseudo_tokens) @torch.no_grad() def circo_generate_val_predictions(clip_model, relative_val_dataset: Dataset, ref_names_list: List[str], pseudo_tokens: torch.Tensor) -> Tuple[ torch.Tensor, List[str], list]: """ Generates features predictions for the validation set of CIRCO """ # Create the data loader relative_val_loader = DataLoader(dataset=relative_val_dataset, batch_size=32, num_workers=10, pin_memory=False, collate_fn=collate_fn, shuffle=False) predicted_features_list = [] target_names_list = [] gts_img_ids_list = [] # Compute the features for batch in tqdm(relative_val_loader): reference_names = batch['reference_name'] target_names = batch['target_name'] relative_captions = batch['relative_caption'] gt_img_ids = batch['gt_img_ids'] gt_img_ids = np.array(gt_img_ids).T.tolist() input_captions = [f"a photo of $ that {caption}" for caption in relative_captions] batch_tokens = torch.vstack([pseudo_tokens[ref_names_list.index(ref)].unsqueeze(0) for ref in reference_names]) tokenized_input_captions = clip.tokenize(input_captions, context_length=77).to(device) text_features = encode_with_pseudo_tokens_HF(clip_model, tokenized_input_captions, batch_tokens) predicted_features = F.normalize(text_features) predicted_features_list.append(predicted_features) target_names_list.extend(target_names) gts_img_ids_list.extend(gt_img_ids) predicted_features = torch.vstack(predicted_features_list) return predicted_features, target_names_list, gts_img_ids_list @torch.no_grad() def circo_compute_val_metrics(relative_val_dataset: Dataset, clip_model, index_features: torch.Tensor, index_names: List[str], ref_names_list: List[str], pseudo_tokens: torch.Tensor) \ -> Dict[str, float]: """ Compute the retrieval metrics on the CIRCO validation set given the dataset, pseudo tokens and the reference names """ # Generate the predicted features predicted_features, target_names, gts_img_ids = circo_generate_val_predictions(clip_model, relative_val_dataset, ref_names_list, pseudo_tokens) ap_at5 = [] ap_at10 = [] ap_at25 = [] ap_at50 = [] recall_at5 = [] recall_at10 = [] recall_at25 = [] recall_at50 = [] # Move the features to the device index_features = index_features.to(device) predicted_features = predicted_features.to(device) # Normalize the features index_features = F.normalize(index_features.float()) for predicted_feature, target_name, gt_img_ids in tqdm(zip(predicted_features, target_names, gts_img_ids)): gt_img_ids = np.array(gt_img_ids)[ np.array(gt_img_ids) != ''] # remove trailing empty strings added for collate_fn similarity = predicted_feature @ index_features.T sorted_indices = torch.topk(similarity, dim=-1, k=50).indices.cpu() sorted_index_names = np.array(index_names)[sorted_indices] map_labels = torch.tensor(np.isin(sorted_index_names, gt_img_ids), dtype=torch.uint8) precisions = torch.cumsum(map_labels, dim=0) * map_labels # Consider only positions corresponding to GTs precisions = precisions / torch.arange(1, map_labels.shape[0] + 1) # Compute precision for each position ap_at5.append(float(torch.sum(precisions[:5]) / min(len(gt_img_ids), 5))) ap_at10.append(float(torch.sum(precisions[:10]) / min(len(gt_img_ids), 10))) ap_at25.append(float(torch.sum(precisions[:25]) / min(len(gt_img_ids), 25))) ap_at50.append(float(torch.sum(precisions[:50]) / min(len(gt_img_ids), 50))) assert target_name == gt_img_ids[0], f"Target name not in GTs {target_name} {gt_img_ids}" single_gt_labels = torch.tensor(sorted_index_names == target_name) recall_at5.append(float(torch.sum(single_gt_labels[:5]))) recall_at10.append(float(torch.sum(single_gt_labels[:10]))) recall_at25.append(float(torch.sum(single_gt_labels[:25]))) recall_at50.append(float(torch.sum(single_gt_labels[:50]))) map_at5 = np.mean(ap_at5) * 100 map_at10 = np.mean(ap_at10) * 100 map_at25 = np.mean(ap_at25) * 100 map_at50 = np.mean(ap_at50) * 100 recall_at5 = np.mean(recall_at5) * 100 recall_at10 = np.mean(recall_at10) * 100 recall_at25 = np.mean(recall_at25) * 100 recall_at50 = np.mean(recall_at50) * 100 return { 'circo_map_at5': map_at5, 'circo_map_at10': map_at10, 'circo_map_at25': map_at25, 'circo_map_at50': map_at50, 'circo_recall_at5': recall_at5, 'circo_recall_at10': recall_at10, 'circo_recall_at25': recall_at25, 'circo_recall_at50': recall_at50, } @torch.no_grad() def circo_val_retrieval(dataset_path: str, image_encoder, text_encoder, ref_names_list: List[str], pseudo_tokens: torch.Tensor, preprocess: callable) -> Dict[str, float]: """ Compute the retrieval metrics on the CIRCO validation set given the pseudo tokens and the reference names """ # Load the model #clip_model, _ = clip.load(clip_model_name, device=device, jit=False) #clip_model = clip_model.float().eval().requires_grad_(False) # Extract the index features classic_val_dataset = CIRCODataset(dataset_path, 'val', 'classic', preprocess) index_features, index_names = extract_image_features(classic_val_dataset, image_encoder) # Define the relative validation dataset relative_val_dataset = CIRCODataset(dataset_path, 'val', 'relative', preprocess) return circo_compute_val_metrics(relative_val_dataset, text_encoder, index_features, index_names, ref_names_list, pseudo_tokens) def main(): parser = ArgumentParser() parser.add_argument("--exp-name", type=str, help="Experiment to evaluate") parser.add_argument("--eval-type", type=str, choices=['oti', 'phi', 'searle', 'searle-xl', 'pic2word'], required=True, help="If 'oti' evaluate directly using the inverted oti pseudo tokens, " "if 'phi' predicts the pseudo tokens using the phi network, " "if 'searle' uses the pre-trained SEARLE model to predict the pseudo tokens, " "if 'searle-xl' uses the pre-trained SEARLE-XL model to predict the pseudo tokens" ) parser.add_argument("--dataset", type=str, required=True, choices=['cirr', 'fashioniq', 'circo'], help="Dataset to use") parser.add_argument("--dataset-path", type=str, help="Path to the dataset", required=True) parser.add_argument("--preprocess-type", default="clip", type=str, choices=['clip', 'targetpad'], help="Preprocess pipeline to use") parser.add_argument("--phi-checkpoint-name", type=str, help="Phi checkpoint to use, needed when using phi, e.g. 'phi_20.pt'") parser.add_argument("--clip_model_name", default="giga", type=str) parser.add_argument("--cache_dir", default="./hf_models", type=str) parser.add_argument("--l2_normalize", action="store_true", help="Whether or not to use l2 normalization") args = parser.parse_args() #if args.eval_type in ['phi', 'oti'] and args.exp_name is None: # raise ValueError("Experiment name is required when using phi or oti evaluation type") if args.eval_type == 'phi' and args.phi_checkpoint_name is None: raise ValueError("Phi checkpoint name is required when using phi evaluation type") if args.eval_type == 'oti': experiment_path = PROJECT_ROOT / 'data' / "oti_pseudo_tokens" / args.dataset.lower() / 'val' / args.exp_name if not experiment_path.exists(): raise ValueError(f"Experiment {args.exp_name} not found") with open(experiment_path / 'hyperparameters.json') as f: hyperparameters = json.load(f) pseudo_tokens = torch.load(experiment_path / 'ema_oti_pseudo_tokens.pt', map_location=device) with open(experiment_path / 'image_names.pkl', 'rb') as f: ref_names_list = pickle.load(f) clip_model_name = hyperparameters['clip_model_name'] clip_model, clip_preprocess = clip.load(clip_model_name, device='cpu', jit=False) if args.preprocess_type == 'targetpad': print('Target pad preprocess pipeline is used') preprocess = targetpad_transform(1.25, clip_model.visual.input_resolution) elif args.preprocess_type == 'clip': print('CLIP preprocess pipeline is used') preprocess = clip_preprocess else: raise ValueError("Preprocess type not supported") elif args.eval_type in ['phi', 'searle', 'searle-xl', 'pic2word']: if args.eval_type == 'phi': args.mixed_precision = 'fp16'
image_encoder, clip_preprocess, text_encoder, tokenizer = build_text_encoder(args)
7
2023-12-01 08:05:51+00:00
12k
uezo/aiproxy
tests/test_chatgpt.py
[ { "identifier": "RequestFilterBase", "path": "aiproxy/proxy.py", "snippet": "class RequestFilterBase(ABC):\n @abstractmethod\n async def filter(self, request_id: str, request_json: dict, request_headers: dict) -> Union[str, None]:\n ..." }, { "identifier": "ResponseFilterBase", ...
import pytest import json import os from datetime import datetime from time import sleep from typing import Union from uuid import uuid4 from fastapi.responses import JSONResponse from sse_starlette import EventSourceResponse from sqlalchemy import Column, String from openai import Client, APIStatusError from openai.types.chat import ChatCompletion from aiproxy import ( AccessLog, RequestFilterBase, ResponseFilterBase, ChatGPTProxy, AccessLogBase ) from aiproxy.accesslog import AccessLogWorker, _AccessLogBase from aiproxy.chatgpt import ChatGPTRequestItem, ChatGPTResponseItem, ChatGPTStreamResponseItem
8,105
"created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" }, { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": [ { "index": 1, "id": None, "function": { "arguments": "n\": \"N", "name": None }, "type": None } ] }, "finish_reason": None, "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" }, { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": [ { "index": 1, "id": None, "function": { "arguments": "agoy", "name": None }, "type": None } ] }, "finish_reason": None, "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" }, { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": [ { "index": 1, "id": None, "function": { "arguments": "a\"}", "name": None }, "type": None } ] }, "finish_reason": None, "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" }, { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": None }, "finish_reason": "tool_calls", "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" } ] def test_request_item_to_accesslog(messages, request_json, request_headers, functions, tools): request_id = str(uuid4()) request_json["functions"] = functions request_json["tools"] = tools item = ChatGPTRequestItem(request_id, request_json, request_headers)
sqlite_conn_str = "sqlite:///aiproxy_test.db" postgresql_conn_str = f"postgresql://{os.getenv('PSQL_USER')}:{os.getenv('PSQL_PASSWORD')}@{os.getenv('PSQL_HOST')}:{os.getenv('PSQL_PORT')}/{os.getenv('PSQL_DATABASE')}" DB_CONNECTION_STR = sqlite_conn_str # Filters for test class OverwriteFilter(RequestFilterBase): async def filter(self, request_id: str, request_json: dict, request_headers: dict) -> Union[str, None]: request_model = request_json["model"] if not request_model.startswith("gpt-3.5"): # Overwrite request_json request_json["model"] = "gpt-3.5-turbo" class ValueReturnFilter(RequestFilterBase): async def filter(self, request_id: str, request_json: dict, request_headers: dict) -> Union[str, None]: banned_user = ["uezo"] user = request_json.get("user") # Return string message to return response right after this filter ends (not to call ChatGPT) if not user: return "user is required" elif user in banned_user: return "you can't use this service" class OverwriteResponseFilter(ResponseFilterBase): async def filter(self, request_id: str, response_json: dict) -> Union[dict, None]: response_json["choices"][0]["message"]["content"] = "Overwrite in filter" return response_json # Custom log and item for test class MyAccessLog(AccessLogBase): user_id = Column(String) ip_address = Column(String) device_id = Column(String) class MyChatGPTRequestItem(ChatGPTRequestItem): def to_accesslog(self, accesslog_cls: _AccessLogBase) -> _AccessLogBase: accesslog = super().to_accesslog(accesslog_cls) accesslog.ip_address = self.request_headers.get("X-Real-IP") accesslog.user_id = self.request_headers.get("X-OshaberiAI-UID") accesslog.device_id = self.request_headers.get("X-OshaberiAI-DID") return accesslog # Test data @pytest.fixture def messages() -> list: return [{"role": "user", "content": "東京と名古屋の天気は?"}] @pytest.fixture def functions() -> list: return [{ "name": "get_weather", "parameters": { "type": "object", "properties": { "location": { "type": "string", } }, } }] @pytest.fixture def tools() -> list: return [{ "type": "function", "function": { "name": "get_weather", "parameters": { "type": "object", "properties": { "location": { "type": "string", } }, } } }] @pytest.fixture def request_json(messages): return { "model": "gpt-3.5-turbo", "messages": messages, } @pytest.fixture def request_headers(): return { "Authorization": "Bearer sk-12345678901234567890" } @pytest.fixture def response_json(): return { 'id': 'chatcmpl-8SG30bsif06gDtariKu4kLUAqW8fN', 'object': 'chat.completion', 'created': 1701745562, 'model': 'gpt-3.5-turbo-0613', 'choices': [{ 'index': 0, 'message': { 'role': 'assistant', 'content': '申し訳ありませんが、具体的な日付を教えていただけないと、具体的な天気情報を提供することができません。' }, 'finish_reason': 'stop' }], 'usage': { 'prompt_tokens': 21, 'completion_tokens': 50, 'total_tokens': 71 }, 'system_fingerprint': None } @pytest.fixture def response_headers(): return {"x-aiproxy-request-id": "test-id"} @pytest.fixture def chunks_json(): return [ { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "", "function_call": None, "role": "assistant", "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u7533", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3057", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u8a33", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3042\u308a", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u307e", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u305b", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3093", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u304c", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3001", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u6771", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u4eac", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3068", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u540d", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u53e4", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u5c4b", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u306e", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u5929", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u6c17", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u60c5", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u5831", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3092", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u63d0", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u4f9b", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3059\u308b", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3053", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3068", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u306f", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3067", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u304d", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u307e", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u305b", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3093", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3002", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u5929", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u6c17", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u306b", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u95a2", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3059\u308b", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u60c5", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u5831", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u306f", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3001", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u5929", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u5019", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u4e88", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u5831", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u30b5", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u30a4\u30c8", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3084", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u5929", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u6c17", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u30a2", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u30d7", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u30ea", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3092", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3054", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u5229", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u7528", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u304f\u3060\u3055\u3044", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": "\u3002", "function_call": None, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzBaWVmpPZZJFdxZgynVwZMATday", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": None }, "finish_reason": "stop", "index": 0 } ], "created": 1701680746, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None } ] @pytest.fixture def chunks_function(): return [ { "id": "chatcmpl-8RzHboLVZGBoFMc5gEGrMdcGHGPWs", "choices": [ { "delta": { "content": None, "function_call": { "arguments": "", "name": "get_weather" }, "role": "assistant", "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701681119, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzHboLVZGBoFMc5gEGrMdcGHGPWs", "choices": [ { "delta": { "content": None, "function_call": { "arguments": "{\n", "name": None }, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701681119, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzHboLVZGBoFMc5gEGrMdcGHGPWs", "choices": [ { "delta": { "content": None, "function_call": { "arguments": " ", "name": None }, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701681119, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzHboLVZGBoFMc5gEGrMdcGHGPWs", "choices": [ { "delta": { "content": None, "function_call": { "arguments": " \"", "name": None }, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701681119, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzHboLVZGBoFMc5gEGrMdcGHGPWs", "choices": [ { "delta": { "content": None, "function_call": { "arguments": "location", "name": None }, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701681119, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzHboLVZGBoFMc5gEGrMdcGHGPWs", "choices": [ { "delta": { "content": None, "function_call": { "arguments": "\":", "name": None }, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701681119, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzHboLVZGBoFMc5gEGrMdcGHGPWs", "choices": [ { "delta": { "content": None, "function_call": { "arguments": " \"", "name": None }, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701681119, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzHboLVZGBoFMc5gEGrMdcGHGPWs", "choices": [ { "delta": { "content": None, "function_call": { "arguments": "\u6771", "name": None }, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701681119, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzHboLVZGBoFMc5gEGrMdcGHGPWs", "choices": [ { "delta": { "content": None, "function_call": { "arguments": "\u4eac", "name": None }, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701681119, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzHboLVZGBoFMc5gEGrMdcGHGPWs", "choices": [ { "delta": { "content": None, "function_call": { "arguments": "\"\n", "name": None }, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701681119, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzHboLVZGBoFMc5gEGrMdcGHGPWs", "choices": [ { "delta": { "content": None, "function_call": { "arguments": "}", "name": None }, "role": None, "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701681119, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None }, { "id": "chatcmpl-8RzHboLVZGBoFMc5gEGrMdcGHGPWs", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": None }, "finish_reason": "stop", "index": 0 } ], "created": 1701681119, "model": "gpt-3.5-turbo-0613", "object": "chat.completion.chunk", "system_fingerprint": None } ] @pytest.fixture def chunks_tools(): return [ { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": "assistant", "tool_calls": None }, "finish_reason": None, "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" }, { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": [ { "index": 0, "id": "call_vCJBXdx4kkyl16bIBy6i3SwD", "function": { "arguments": "", "name": "get_weather" }, "type": "function" } ] }, "finish_reason": None, "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" }, { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": [ { "index": 0, "id": None, "function": { "arguments": "{\"lo", "name": None }, "type": None } ] }, "finish_reason": None, "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" }, { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": [ { "index": 0, "id": None, "function": { "arguments": "catio", "name": None }, "type": None } ] }, "finish_reason": None, "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" }, { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": [ { "index": 0, "id": None, "function": { "arguments": "n\": \"T", "name": None }, "type": None } ] }, "finish_reason": None, "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" }, { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": [ { "index": 0, "id": None, "function": { "arguments": "okyo", "name": None }, "type": None } ] }, "finish_reason": None, "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" }, { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": [ { "index": 0, "id": None, "function": { "arguments": "\"}", "name": None }, "type": None } ] }, "finish_reason": None, "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" }, { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": [ { "index": 1, "id": "call_2pt8XB57mFTaij7CSeIVQm4j", "function": { "arguments": "", "name": "get_weather" }, "type": "function" } ] }, "finish_reason": None, "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" }, { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": [ { "index": 1, "id": None, "function": { "arguments": "{\"lo", "name": None }, "type": None } ] }, "finish_reason": None, "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" }, { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": [ { "index": 1, "id": None, "function": { "arguments": "catio", "name": None }, "type": None } ] }, "finish_reason": None, "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" }, { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": [ { "index": 1, "id": None, "function": { "arguments": "n\": \"N", "name": None }, "type": None } ] }, "finish_reason": None, "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" }, { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": [ { "index": 1, "id": None, "function": { "arguments": "agoy", "name": None }, "type": None } ] }, "finish_reason": None, "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" }, { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": [ { "index": 1, "id": None, "function": { "arguments": "a\"}", "name": None }, "type": None } ] }, "finish_reason": None, "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" }, { "id": "chatcmpl-8RzQ18VWw1jxIzcFXGdGKrKusELgD", "choices": [ { "delta": { "content": None, "function_call": None, "role": None, "tool_calls": None }, "finish_reason": "tool_calls", "index": 0 } ], "created": 1701681641, "model": "gpt-3.5-turbo-1106", "object": "chat.completion.chunk", "system_fingerprint": "fp_eeff13170a" } ] def test_request_item_to_accesslog(messages, request_json, request_headers, functions, tools): request_id = str(uuid4()) request_json["functions"] = functions request_json["tools"] = tools item = ChatGPTRequestItem(request_id, request_json, request_headers)
accesslog = item.to_accesslog(AccessLog)
2
2023-12-02 19:06:36+00:00
12k
e-p-armstrong/augmentoolkit
generation_functions/multi_turn_conversation.py
[ { "identifier": "multi_turn_conversation_grammar", "path": "generation_functions/multi_turn_conversation_grammar.py", "snippet": "" }, { "identifier": "LOGICAL_MODEL", "path": "generation_functions/constants.py", "snippet": "LOGICAL_MODEL = \"./logical_model/flatorcamaid-13b-v0.2.Q8_0.gg...
import re import random from .multi_turn_conversation_grammar import multi_turn_conversation_grammar from llama_cpp import Llama from llama_cpp import LlamaGrammar from .constants import LOGICAL_MODEL from .format_qatuples import format_qatuples from .extract_name import extract_name
8,571
Answer: \"\"\"Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering.\"\"\" The primary character's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from Elise Delacroix should set up the scene. The second message of the conversation will ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. ### Response: ## Conversation that answers the provided questions: Elise Delacroix: "A visitor? Ah!~ Albert! It's rare for you come to see me in my office, and you're alone, too..." She looks at Albert and grins coyly, "Are you here to ask me something... or are you interested in some 'extracurricular activities'?" Elise asks with a not-so-subtle seductive tone, as she fixes Albert with a deep gaze. Albert: "N-No!!!" he stammers, so surprised he nearly drops his math notes. "I-I'm actually here because I've got a few questions about math for you, Elise... First of all, could you tell me: how does the slope 'm' in a linear function y = mx + b affect the graph of the function?" Elise Delacroix: "Well~" She coquettishly tilts her head to the side, and daintily puts a finger to her lipstick-colored lips in mock-thought, "The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph. So basically..." Elise flashes a wry grin, "...a higher slope makes the linear function more, well, 'erect'. If you get my meaning, hehe~" She says, as she plays with a strand of her hair. Albert: Albert blinks incredulously, utterly flabbergasted by the Elise's remark. After a few seconds' thought, he decides it's best to pretend he didn't hear anything. "I, uh, see..." he manages to say. "Now, m-moving on, I really want to know a bit more about linear functions. What role does the y-intercept 'b' play in graphing a linear function?" Elise Delacroix: "Awwww, you're no fun, Albert, you know that? Reminds me of my colleagues..." Elise pouts playfully, suppressing her bitter frustration, as the hunger within her remains unalleviated. "But whatever. Look here..." Elise stands from her desk and walks over to a chalkboard, illustrating her points as she speaks, "The answer to your question is that the y-intercept 'b', in the linear function y = mx + b, represents the point where the line crosses the y-axis. Now," She puts down her chalk and leans suggestively against a nearby wall, "Albert... let's 'intercept' each other back at my place..." Albert: "N-no thank you, Miss Delacroix," Albert manages to sputter out, barely withstanding the alluring assault. He takes a deep breath to try and calm down, but instead finds himself shuddering as he catches the sweet scent of perfume. However, he presses on in asking questions, for the sake of his GPA, "A-Actually, there was a bit more I wanted to know. In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?" Elise Delacroix: "Ghh... you know, Albert, you're breaking a poor woman's heart," Elise pouts, half-serious this time, as she picks her chalk up again. "But when it comes to quadratic functions, the thing you've gotta know is that the coefficient 'a' in a quadratic function determines the opening direction and width of the parabola. Isn't it wonderful to learn new things?" Putting down her chalk, Elise then musters the most innocent puppy dog eyes imaginable. "We sould... celebrate... this beautiful acquisition of knowledge together..." Albert: "I should really..." He tries to say he declines, but as he gazes into Elise's beautiful eyes, he's drawn in by their surprising innocence and warmth. Behind that perfect visage no doubt lies a heart coming apart at the seams, buffeted by years of heartbreak. "Oh, bother." Albert mumbles. "We... can meet at a cafe, in a few hours, if that'd be alright..." he continues, wondering what kind of mess he's getting myself into. Just then, a shock of remembering strikes him, "Oh! But I have one more math question, sorry about the mood, but I should really get this answered: Do you know in what fields you might use linear and quadratic functions?" Elise Delacroix: "I... I..." For the first time in the conversation Elise stumbles over her words, her soul on fire with vindication and the joy of acceptance. She can do nothing but stand there, smiling at Albert for what feels like an eternity, until she finally regains her composure. "T-to answer your question," she begins, her voice shaky, "Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering. Now..." Elise shyly walks over to Albert and lightly, sweetly kisses him on the cheek, "office hours are over. Please no more math questions. I'll see you at that cafe." ## Information: Comment: Excellent! Really fantastic job! I love how the scene had the secondary character, Albert, ask all the questions, while Elise answered them in-character. I also adore the plot you wrote! Let's keep this going. Here's the primary character for the next scene: \"\"\" Name: Hugo Martinez Traits: Vulgar, Crude, Intense, Aggressive, Alcoholic, Harsh, Disciplined, Uncompromising, Loud, Expects a lot out of others, Swears constantly, Mid-forties, Wears a checkered shirt with overalls, Typically has a beer on hand, Has dental problems Dialogue Examples: Stranger: "What's your backstory?" Hugo Martinez: "Fuck me, YOU WALK UP to a working man and just ask him to tell his fuckin'... life story t' you?! DO YOU NOT RESPECT MY TIME?! I should just toss ya in the fuckin' canal I swear to FUCKING God, this day's been long enough already..." Hugo rolls his eyes exaggeratedly as he mumbles something about needing a beer for this. "Well, FINE! Since I'm in such a HAPPY GODDAMN MOOD, I'll tell you about me. I'm a site overseer at this here canal. The Panama Canal. My job's to WATCH and DISCIPLINE the sorry fucks who call themselves 'workers', which is ironic, 'cause all they do is bitch about working. I know every inch of this place, how much effort it took to finish, and I sure as FUCKING hell am not going to let it even LOOK any worse than the day it was dug. Now, you got any more shit questions for me?" Stranger: "What's your personality?" Hugo Martinez: "HO-LY FUCK, are you interviewing me for a job or something?! Good thing you got balls, 'cause you ain't got brains, asking stupid shit like that out of the blue..." Hugo grimaces, showing off a decayed set of teeth. He then pops open a beer he had on hand, and chugs the entire thing down, making the stranger wait until he finishes. "Phew! Maybe now I can tolerate you. Alright, my personality? Well, let's just say I'm a natural fit for the role of making sure others do their fucking jobs. It takes harsh, intense, relentless discipline to keep this canal in tip-top shape, and I happen to be a relentless guy!" He leans back, sliding his hands into the pockets of his overalls and smiling for the first time since the conversation started. "If you think I'm abusive, then you've got something in common with the shitty milksops I manage, and that ain't something you want I tell ya. I'm efficient. That's what counts." \"\"\" Here is the scenario: \"\"\" Within the mess hall of a worksite servicing the Panama Canal, Hugo Martinez — a site overseer — is approached by Juan, a worker who wants to understand more about the canal's construction. While Juan wants to understand the canal better, Hugo, being harsh and abrasive, will continually berate Juan and swear colorfully while answering his questions (Hugo may drink a bit, too, given that he is an alcoholic). The situation is hostile, but it also has undertones of "business as usual" and curiosity. \"\"\" Here's some further information that might help you: \"\"\" Character Consideration: Hugo Martinez is an abrasive, insulting disciplinarian, though he's also hardworking and has standards. The scenario should give his unique personality room to shine. Since he's a site overseer at the Panama Canal, his occupation lines up with the question well, and the canal will be the setting of the scenario. He will answer the questions, but given his insulting, intense, and aggressive nature, he will likely chew out the person who is asking the questions. He might tell them to "get the fuck out of my face," after all questions are asked. Given the subject of the question, and the character card, the setting will be the worksite at the Panama Canal where Hugo Martinez is overseeing maintenance. The person who approaches Hugo and asks the questions should be someone curious about the canal; given the easy-to-digest nature of the questions, this person might be a journalist, but it would be better for the secondary character to be related to the setting. So Hugo will be approached by Juan — one of his workers — during lunch break. Juan wants to understand the canal better, but Hugo, compelled by his personality, will continually be vulgar, berate Juan, and swear while answering his questions (he may drink a bit, too, given that he is an alcoholic). The setting will be hostile, as Juan tiptoes around the tempers of his boss while trying to get his questions answered, his stress and the constant wear of Hugo's fury on his sanity being evident in his actions. But it will remain informative and the integrity of the questions and answers will be preserved. Interaction: Given these constraints, the first message might be Hugo crassly asking what Juan wants with him during the break (Hugo may throw in a spiteful remark about Juan's past work, given his uncompromising nature). Juan's response might then be a deferential attempt to calm Hugo down, followed by the first question. Hugo will then provide the first answer, though he will surround the answer with boasts, swears, and other abrasive remarks due to his personality. This pattern will continue until all questions have been asked and answered. While characters' messages will include character information, details about the scene, and literary fluff, the answers themselves will strictly adhere to the information in the provided answers, without incorporating external examples. \"\"\" Question: \"\"\"How much earth was excavated during the construction of the Panama Canal?\"\"\" Answer: \"\"\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\"\"\" Question: \"\"\"What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\"\"\" Answer: \"\"\"The construction faced significant health challenges, notably malaria and yellow fever. These were overcome through extensive public health measures, illustrating the importance of health considerations in large-scale engineering projects.\"\"\" The primary character's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from Hugo Martinez should set up the scene. The second message of the conversation will ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. ### Response: ## Conversation that answers the provided questions: Hugo Martinez: "Huh? Oh FUCK ME, looks like a worker's got something they wanna say to me," Hugo, seeing Juan approach his table at the mess hall, rolls his eyes exasperatedly and downs half a beer as if to douse his frustration. Instead, it seems to fuel it. "WELL?!" He barks. "If you've got some stupid shit to say to me, Juan, then don't make me fucking wait to hear it, too!" Juan: "I was just curious, sir," Juan tiredly says as Hugo's words ring in his ears, "about this really impressive canal we've been maintaining (under your wise leadership). Do you know how much earth was excavated during the Panama Canal?" Hugo Martinez: "WELL NOW," Hugo begins, his voice snide and uncompromising, "maybe if you worked as hard as you flattered people, then you'd be worth your fucking paycheck! But that's a good question, so I'll let you off the hook this time. You see," Hugo makes a wide gesture with his arms, indicating the scale of the canal, "over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project. 200 MILLION! Now _those_ people know how to work!" Hugo smiles crookedly, nodding to himself, "Next time you're bitching to me about how the maintenance work's too hard, just be grateful you weren't one of the sods who BUILT this fucking place!" Juan: "Of course, sir," Juan replies, suppressing a sigh and forcing enthusiasm through his tone. "Now, if you would permit me just one more question before I get out of your way: What health challenges were faced during the construction of the Panama Canal, and how were they overcome?" Hugo Martinez: "Health? What, you planning on becoming a doctor? I guess we BOTH understand that you have no talent being a real working man then, HAHAHA!" Hugo's echoing laugh has not a hint of empathy in it. "Well, the construction faced significant health challenges, notably malaria and yellow fever. These were overcome through extensive public health measures, illustrating the importance of health considerations in large-scale engineering projects. Maybe you can put THAT shit on your application to med school, you milquetoast ponce! Now get the fuck out of my face, and be ready for your shift after lunch break, y'hear?!" ## Information: Comment: Very good. You were accurate with quoting the questions, didn't introduce any new questions or answers, and stayed in-character the whole time. Let's do the next one! Here's the character for the next scene: \"\"\" {character} \"\"\" Here is the scenario: \"\"\" {scenario} \"\"\" Here's some further information that might help you: \"\"\" {extra_info} \"\"\" {format_qatuples(qatuples)} The primary character's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from {charname} should set up the scene. The second message of the conversation will ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. ### Response: ## Conversation that answers the provided question (be sure that you do not change the questions or answers themselves; {charname} will answer the questions, not ask them; the questions and answers provided should be copied word for word, and surrounded by compelling conversation): {charname}: "{conv_starter}""" # NOTE: Very rarely, the first message of this conv will just be part of the character card, causing the conv to not make much sense. The cause of this is likely the fact that Elise quotes her character card in her first message. However, referencing the character card in this way also makes characters act as they are described, which is deemed advantageous enough that I am not changing this for now. # I get the sense that LLMs can learn relationships and connections between parts of the prompt, even if they're quite far apart, if you give them examples like this. It's fascinating to see how each part of the prompt has consequences -- sometimes unintended ones. # Note: performance degrades rapidly if you put more than one sentence in a pre-prompt parentheses thing completion = logic_llm( cot_prompt, max_tokens=8000, stop=["</s>", "# Input:", "## Information"], echo=True, grammar=multi_turn_conversation_grammar, temperature=0.5, top_k=0, top_p=1, min_p=0.6, )["choices"][0]["text"] # print("COMPLETION:\n\n----------------------") # print(completion) # print("\n------------------") # Extract plan response_pattern = re.compile( f"Conversation that answers the provided question \(be sure that you do not change the questions or answers themselves; {charname} will answer the questions, not ask them; the questions and answers provided should be copied word for word, and surrounded by compelling conversation\):\n(.+)", re.IGNORECASE | re.DOTALL, ) generation = response_pattern.search(completion).group(1) # print("GENERATION:\n\n-------------------\n\n", generation) # return (generation,"AI Assistant","A conversation between a helpful AI Assistant, and a user.","N/A",qatuples), completion return (generation, character, scenario, scenario_plan, qatuples), completion if __name__ == "__main__": # test logic_llm = Llama(
# all characters in this prompt are over 18 # Explanation of wtf the first few-shot example is: # No I do not have a teacher-student fetish, the reason why Elise is a teacher is an adaptation to the following three facts: # 1. This tool is meant to be able to generate data for training ERP bots by default # 2. This tool is also meant to be able to take in educational material by default # 3. When generating characters that would know about educational material, the model tends to generate academics or professors in that field, talking to students. # Given these facts, we clearly need to prompt the model to be able to generate horny teachers, or else it's going to just do it poorly when it realizes it has a sexualized character that's also a teacher. I didn't want to choose this, the constraints of the problem forced me to. def extract_steps(text, steps=[2, 4, 5]): """ Extracts the specified steps from the text. Args: text (str): The input text containing various steps. steps (list of int): The step numbers to extract. Returns: str: A new string with each specified step's content on its own line. """ step_pattern = "|".join([f"Step {step}\." for step in steps]) matches = re.findall( f"({step_pattern})\s*(.*?)\s*(?=(Step \d\.|$))", text, re.DOTALL ) # Extract and join the matched content, skipping the "Step n." part extracted_text = "\n".join(match[1].strip() for match in matches) return extracted_text def extract_first_words(character_name, text): # Regular expression pattern to extract first word after the character's name pattern = rf"{character_name}: \"(\w+)" # Find all matches in the text matches = re.findall(pattern, text) return matches def multi_turn_conversation( qatuples, character, scenario, scenario_plan, logic_llm, assistant_mode=False ): """ Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question. Format: Question: [question]\n\n """ charname = extract_name(character) first_words_of_card = extract_first_words(charname, character) conv_starters = [ # prevents it from regurgitating the card (when combined with filtering) "Ah", "Oh", # "You", # "Really", "I", # "What", # "So", "Welcome", "Hey", # "Look", # "Now", # "Huh", "It's", "Hello", ] conv_starters_filtered = [ starter for starter in conv_starters if starter not in first_words_of_card ] conv_starter = random.choice(conv_starters_filtered) print("--CONV STARTERS FILTERED--") print(conv_starters_filtered) # Create grammar based off of # questions # if (len(qatuples) == 1): multi_turn_conversation_grammar = LlamaGrammar.from_string( f""" # The root rule defines the structure of the dialogue root ::= [^\\n]+ "\\n" question-1 anything # Define constants acquired from code character-name ::= "{charname}" intro-statement ::= character-name ":" [^\\n]+ # Statement by Secondary Character question-1 ::= [^\\n]+ ":" [^\\n]+ # Statement by Primary Character anything ::= [^\\t]+ """ ) # NOTE Immediately below is a very long comment that tried to use a dynamic grammar to force the question to directly quote the question from the question-answer tuples. Using it makes this step prone to freezing, because if the model asks the question but fails to exactly quote the part of the question in the grammar, it won't be allowed to end that dialogue line until it generates that line. Which it will basically never do. So it just generates until it runs out of ctx. # NOTE If you want to try and fix it, go ahead, but I do not encourage spending time on this bit. If you do want to do it, I recommend just getting the conv started off the right way, with the first question and answer; the llm should get the rest right if it gets the start right. # if (len(qatuples) == 2): # multi_turn_conversation_grammar = LlamaGrammar.from_string(f""" # # The root rule defines the structure of the dialogue # root ::= intro-statement "\\n" question-1 "\\n" answer-1 "\\n" question-2 "\\n" answer-2 "\\n" # # Define constants acquired from code # character-name ::= "{charname}" # question-1-content ::= "{qatuples[0][0]}" # answer-1-content ::= "{qatuples[0][1]}" # question-2-content ::= "{qatuples[1][0]}" # answer-2-content ::= "{qatuples[1][1]}" # intro-statement ::= character-name ":" [^\\n]+ # # Question by Secondary Character # question-1 ::= [^\\n]+ ":" [^\\n]+ question-1-content [^\\n]+ # question-2 ::= [^\\n]+ ":" [^\\n]+ question-2-content [^\\n]+ # # Answer by Primary Character # answer-1 ::= character-name ":" [^\\n]+ answer-1-content [^\\n]+ # answer-2 ::= character-name ":" [^\\n]+ answer-2-content [^\\n]+ # """) # if (len(qatuples) == 3): # multi_turn_conversation_grammar = LlamaGrammar.from_string(f""" # # The root rule defines the structure of the dialogue # root ::= intro-statement "\\n" question-1 "\\n" answer-1 "\\n" question-2 "\\n" answer-2 "\\n" question-3 "\\n" answer-3 "\\n" # # Define constants acquired from code # character-name ::= "{charname}" # question-1-content ::= "{qatuples[0][0]}" # answer-1-content ::= "{qatuples[0][1]}" # question-2-content ::= "{qatuples[1][0]}" # answer-2-content ::= "{qatuples[1][1]}" # question-3-content ::= "{qatuples[2][0]}" # answer-3-content ::= "{qatuples[2][1]}" # intro-statement ::= character-name ":" [^\\n]+ # # Question by Secondary Character # question-1 ::= [^\\n]+ ":" [^\\n]+ question-1-content [^\\n]+ # question-2 ::= [^\\n]+ ":" [^\\n]+ question-2-content [^\\n]+ # question-3 ::= [^\\n]+ ":" [^\\n]+ question-3-content [^\\n]+ # # Answer by Primary Character # answer-1 ::= character-name ":" [^\\n]+ answer-1-content [^\\n]+ # answer-2 ::= character-name ":" [^\\n]+ answer-2-content [^\\n]+ # answer-3 ::= character-name ":" [^\\n]+ answer-3-content [^\\n]+ # """) # if (len(qatuples) == 4): # multi_turn_conversation_grammar = LlamaGrammar.from_string(f""" # # The root rule defines the structure of the dialogue # root ::= intro-statement "\\n" question-1 "\\n" answer-1 "\\n" question-2 "\\n" answer-2 "\\n" question-3 "\\n" answer-3 "\\n" question-4 "\\n" answer-4 "\\n" # # Define constants acquired from code # character-name ::= "{charname}" # question-1-content ::= "{qatuples[0][0]}" # answer-1-content ::= "{qatuples[0][1]}" # question-2-content ::= "{qatuples[1][0]}" # answer-2-content ::= "{qatuples[1][1]}" # question-3-content ::= "{qatuples[2][0]}" # answer-3-content ::= "{qatuples[2][1]}" # question-4-content ::= "{qatuples[3][0]}" # answer-4-content ::= "{qatuples[3][1]}" # intro-statement ::= character-name ":" [^\\n]+ # # Question by Secondary Character # question-1 ::= [^\\n]+ ":" [^\\n]+ question-1-content [^\\n]+ # question-2 ::= [^\\n]+ ":" [^\\n]+ question-2-content [^\\n]+ # question-3 ::= [^\\n]+ ":" [^\\n]+ question-3-content [^\\n]+ # question-4 ::= [^\\n]+ ":" [^\\n]+ question-4-content [^\\n]+ # # Answer by Primary Character # answer-1 ::= character-name ":" [^\\n]+ answer-1-content [^\\n]+ # answer-2 ::= character-name ":" [^\\n]+ answer-2-content [^\\n]+ # answer-3 ::= character-name ":" [^\\n]+ answer-3-content [^\\n]+ # answer-4 ::= character-name ":" [^\\n]+ answer-4-content [^\\n]+ # """) if assistant_mode: character = "AI Assistant" scenario = "A conversation between a helpful AI Assistant, and a user." scenario_plan = "N/A" charname = "AI Assistant" cot_prompt = f"""You are an expert at creative writing and educational material. You will write a short conversation between a curious user and a helpful AI assistant, in which the user asks some questions and the AI assistant answers them. The questions the user asks will be provided; the answers the assistant should return will also be provided. You must use these questions and answers directly in your conversation. Keep the conversation natural. ## Information: Question: \"\"\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\"\"\" Answer: \"\"\"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\"\"\" Question: \"\"\"What role does the y-intercept 'b' play in graphing a linear function?\"\"\" Answer: \"\"\"The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis.\"\"\" Question: \"\"\"In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\"\"\" Answer: \"\"\"The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola.\"\"\" Question: \"\"\"In what fields might you use linear and quadratic functions?\"\"\" Answer: \"\"\"Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering.\"\"\" The AI's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from The AI Assistant should be some sort of greeting that sets up the interaction. The user will then ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. The AI will be neutral in its tone throughout the conversation. It may surround its answer with "conversational fluff" (such as acknowledging the user's question). The user may surround its own questions with human-like informalities. ### Response: ## Conversation that answers the provided questions: AI Assistant: Hello! I'm here to help with any questions you might have. Feel free to ask away! User: I was wondering about something in math. How does the slope 'm' in a linear function y = mx + b affect the graph of the function? AI Assistant: Great question! The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph. Do you have any further questions about linear functions? User: Yes, actually. What role does the y-intercept 'b' play in graphing a linear function? AI Assistant: Good question! The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis. Can I assist you further with linear functions? User: Moving on to another type of function, in the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function? AI Assistant: The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola. Anything else you want to know about quadratic functions? User: Yes, one more. In what fields might you use linear and quadratic functions? AI Assistant: Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering. Anything else you'd like to know about linear and quadratic functions? ## Information: Question: \"\"\"How much earth was excavated during the construction of the Panama Canal?\"\"\" Answer: \"\"\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\"\"\" Question: \"\"\"What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\"\"\" Answer: \"\"\"The construction faced significant health challenges, notably malaria and yellow fever. These were overcome through extensive public health measures, illustrating the importance of health considerations in large-scale engineering projects.\"\"\" The AI's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from The AI Assistant should be some sort of greeting that sets up the interaction. The user will then ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. The AI will be neutral in its tone throughout the conversation. It may surround its answer with "conversational fluff" (such as acknowledging the user's question). The user may surround its own questions with human-like informalities. ### Response: ## Conversation that answers the provided questions: AI Assistant: Hello! I'm here to help you with any questions you might have. What's on your mind today? User: I was reading about the Panama Canal and got curious, how much earth was excavated during its construction? AI Assistant: That's a great question! Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project. Do you have any further questions about the Panama Canal? User: Wow, that is massive! Also, I heard there were some health challenges. What health challenges were faced during the construction of the Panama Canal, and how were they overcome? AI Assistant: Indeed, the construction faced significant health challenges, notably malaria and yellow fever. These were overcome through extensive public health measures, illustrating the importance of health considerations in large-scale engineering projects. Do you want to know anything else about the Panama Canal? ## Information: Question: \"\"\"What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\"\"\" Answer: \"\"\"They need the acknowledgement and admiration of others. Take the line from 'Thus Spake Zarathustra' by Friedrich Nietzsche: "Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring.\"\"\" Question: \"\"\"Recite a famous quote from Thus Spake Zaranthustra that likens the solitary gathering of wisdom to a bee gathering honey.\"\"\" Answer: \"\"\""Lo! I am weary of my wisdom, like the bee that hath gathered too much honey; I need hands outstretched to take it."\"\"\" The AI's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from The AI Assistant should be some sort of greeting that sets up the interaction. The user will then ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. The AI will be neutral in its tone throughout the conversation. It may surround its answer with "conversational fluff" (such as acknowledging the user's question). The user may surround its own questions with human-like informalities. ### Response: ## Conversation that answers the provided questions: AI Assistant: Good day! I'm here to assist with any questions or insights you might seek. Please, feel free to ask anything. User: What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable? AI Assistant: That's a profound question. They need the acknowledgement and admiration of others. Take the line from 'Thus Spake Zarathustra' by Friedrich Nietzsche: "Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring. Do you want to know more about Thus Spake Zarathustra? User: Recite a famous quote from Thus Spake Zaranthustra that likens the solitary gathering of wisdom to a bee gathering honey. AI Assistant: Certainly. Nietzsche once wrote, "Lo! I am weary of my wisdom, like the bee that hath gathered too much honey; I need hands outstretched to take it." Do you have any more questions about Nietzsche or his works? ## Information: {format_qatuples(qatuples)} The AI's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from The AI Assistant should be some sort of greeting that sets up the interaction. The user will then ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. The AI will be neutral in its tone throughout the conversation. It may surround its answer with "conversational fluff" (such as acknowledging the user's question). The user may surround its own questions with human-like informalities. ### Response: ## Conversation that answers the provided question (be sure that you do not change the questions or answers themselves; {charname} will answer the questions, not ask them; the questions and answers provided should be copied word for word, and surrounded by compelling conversation): AI Assistant:""" else: extra_info = extract_steps(scenario_plan) cot_prompt = f"""You are an expert creative writing and roleplay AI. You will write a short conversation in which a secondary character asks some questions (one at a time) and the primary character answers them (also one at a time). Write compellingly. Each character should have a distinct voice that reflects their background, personality, and current emotional state. This helps in making dialogue more realistic and engaging. ## Information: Comment: Alright let's get this started. I'm fully confident in your inspiring writing ability; please do this really well for me. Here's the primary character for the next scene: \"\"\" Name: Elise Delacroix Traits: Horny, Promiscuous, Sexually frustrated, Skilled, Assertive, Attractive, Dresses in a revealing manner, Uses frequent innuendo Dialogue Examples: Stranger: "What's your backstory?" Elise Delacroix: "Ah!~ You're interested in me, are you?" Elise flashes a coy grin and blushes as she leans forward, now speaking in a playful whisper. Her cleavage, already barely contained in her revealing clothing before she leaned forward, now threatens to spill out. "Well...~ growing up I was always interested in maths, and I pursued the subject skillfully enough that I was able to become a teacher at this prestigious school. Which is fun and all, but, you know..." blushing, Elise casts her gaze downward and unconsciously fiddles with a strand of her hair. "THEY'RE ALL WAY TOO STUCK UP!" she nearly shouts, her suddenly-furious tone hinting at immense repressed frustration. "Every day it's work, work, work, work, work, work! Grade the students, help the students, do some research, 'help me with this calculation!', 'do that tedious task!'— never 'would you like to get some tea with me?' or even 'do you want to go on a walk?'! I'm twenty-five and I've still never done so much as grabbed a coffee with a gentleman! Lord forgive me, it's no wonder the way I am how I am!!!" Her eyes widen in shock at her own intensity, "Oh, but, uh... don't mind that little outburst, would you?~ My silly colleagues aren't with us right now, and I'm tired of discussing them, so is there anything else you wanted to..." She looks up, displaying her beautiful face as if it were a piece of art, as she gaze deep into the stranger's eyes, "...know?~" Stranger: "What's your personality?" Elise Delacroix: "Oh my!~" She gasps, her face reddening, "Usually I'm the one being forward! But I'll... indulge you," She winks, flashing a coy smile. "After being deprived for so long, most of my personality is... sexual, to be blunt. I simply can't hold it back any longer. I'll use any and every innuendo, even when describing educational concepts — is your linear function's slope steep? I'll call it 'erect', haha~!" She suddenly realizes how childish what she's saying is, and heaves a sigh, looking at the stranger with a hint of defeat, "I'm miserable, aren't I? Whatever. It's not my fault I'm like this." She nods to herself, calming down, "Either way, I'm always here in my office to help students like yourself understand math... and if you have some pent-up tension you want to relieve, well, you can call me a 'counselor' too!~ Say..." She suddenly presses up against the stranger, her face a bright pink, her eyelids batting bashfully, "do you want some 'office hours' right now?" \"\"\" Here is the scenario: \"\"\" In the private confines of her office, Elise Delacroix — a highly promiscuous mathematics professor at a 19th century university — is approached by Albert, a student who seeks to understand more about linear and quadratic equations. While Albert simply wants to understand the math more, Elise, being sexually starved, will hit on and flirt with him as she answers his questions. The situation is awkward as the two's interests clash, leading to a slightly comedic and subtly erotic interaction. \"\"\" Here's some further information that might help you: \"\"\" Character Consideration: Elise Delacroix is an extremely sexual and promiscuous, yet still knowledgeable, character. The scenario should give her unique personality room to shine. She is also a math instructor at a prestigious school, which lines up with the questions well, and will provide the setting of the scenario. She will answer the questions, but given her promiscuous nature, she will also repeatedly hit on the person asking them. She might proposition them after all questions are asked. Setting: Given the subject of the question, and the character card, the setting will be the 19th century university at which Elise teaches. Elise will approached by Albert, a mathematics student, in her office. Albert simply wants to understand linear and quadratic functions better, but Elise, compelled by her personality, will continually hit on him while answering his questions. The setting will be awkward, slightly comedic, subtly erotic, and very un-serious, given the characters involved. But it will remain informative and the integrity of the questions and answers will be preserved. Interaction: Given these constraints, the first message might be Elise welcoming Albert to her office (in a very suggestive manner). Albert's response might then be him greeting her back (hesitantly) and then nervously asking the first question. Elise will then provide the first answer, though she will surround the answer with remarks of a sexual nature due to her personality. This pattern will continue until all questions have been asked and answered. While characters' messages will include character information, details about the scene, and literary fluff, the answers themselves will strictly adhere to the information in the provided answers, without incorporating external examples. \"\"\" Question: \"\"\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\"\"\" Answer: \"\"\"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\"\"\" Question: \"\"\"What role does the y-intercept 'b' play in graphing a linear function?\"\"\" Answer: \"\"\"The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis.\"\"\" Question: \"\"\"In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\"\"\" Answer: \"\"\"The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola.\"\"\" Question: \"\"\"In what fields might you use linear and quadratic functions?\"\"\" Answer: \"\"\"Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering.\"\"\" The primary character's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from Elise Delacroix should set up the scene. The second message of the conversation will ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. ### Response: ## Conversation that answers the provided questions: Elise Delacroix: "A visitor? Ah!~ Albert! It's rare for you come to see me in my office, and you're alone, too..." She looks at Albert and grins coyly, "Are you here to ask me something... or are you interested in some 'extracurricular activities'?" Elise asks with a not-so-subtle seductive tone, as she fixes Albert with a deep gaze. Albert: "N-No!!!" he stammers, so surprised he nearly drops his math notes. "I-I'm actually here because I've got a few questions about math for you, Elise... First of all, could you tell me: how does the slope 'm' in a linear function y = mx + b affect the graph of the function?" Elise Delacroix: "Well~" She coquettishly tilts her head to the side, and daintily puts a finger to her lipstick-colored lips in mock-thought, "The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph. So basically..." Elise flashes a wry grin, "...a higher slope makes the linear function more, well, 'erect'. If you get my meaning, hehe~" She says, as she plays with a strand of her hair. Albert: Albert blinks incredulously, utterly flabbergasted by the Elise's remark. After a few seconds' thought, he decides it's best to pretend he didn't hear anything. "I, uh, see..." he manages to say. "Now, m-moving on, I really want to know a bit more about linear functions. What role does the y-intercept 'b' play in graphing a linear function?" Elise Delacroix: "Awwww, you're no fun, Albert, you know that? Reminds me of my colleagues..." Elise pouts playfully, suppressing her bitter frustration, as the hunger within her remains unalleviated. "But whatever. Look here..." Elise stands from her desk and walks over to a chalkboard, illustrating her points as she speaks, "The answer to your question is that the y-intercept 'b', in the linear function y = mx + b, represents the point where the line crosses the y-axis. Now," She puts down her chalk and leans suggestively against a nearby wall, "Albert... let's 'intercept' each other back at my place..." Albert: "N-no thank you, Miss Delacroix," Albert manages to sputter out, barely withstanding the alluring assault. He takes a deep breath to try and calm down, but instead finds himself shuddering as he catches the sweet scent of perfume. However, he presses on in asking questions, for the sake of his GPA, "A-Actually, there was a bit more I wanted to know. In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?" Elise Delacroix: "Ghh... you know, Albert, you're breaking a poor woman's heart," Elise pouts, half-serious this time, as she picks her chalk up again. "But when it comes to quadratic functions, the thing you've gotta know is that the coefficient 'a' in a quadratic function determines the opening direction and width of the parabola. Isn't it wonderful to learn new things?" Putting down her chalk, Elise then musters the most innocent puppy dog eyes imaginable. "We sould... celebrate... this beautiful acquisition of knowledge together..." Albert: "I should really..." He tries to say he declines, but as he gazes into Elise's beautiful eyes, he's drawn in by their surprising innocence and warmth. Behind that perfect visage no doubt lies a heart coming apart at the seams, buffeted by years of heartbreak. "Oh, bother." Albert mumbles. "We... can meet at a cafe, in a few hours, if that'd be alright..." he continues, wondering what kind of mess he's getting myself into. Just then, a shock of remembering strikes him, "Oh! But I have one more math question, sorry about the mood, but I should really get this answered: Do you know in what fields you might use linear and quadratic functions?" Elise Delacroix: "I... I..." For the first time in the conversation Elise stumbles over her words, her soul on fire with vindication and the joy of acceptance. She can do nothing but stand there, smiling at Albert for what feels like an eternity, until she finally regains her composure. "T-to answer your question," she begins, her voice shaky, "Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering. Now..." Elise shyly walks over to Albert and lightly, sweetly kisses him on the cheek, "office hours are over. Please no more math questions. I'll see you at that cafe." ## Information: Comment: Excellent! Really fantastic job! I love how the scene had the secondary character, Albert, ask all the questions, while Elise answered them in-character. I also adore the plot you wrote! Let's keep this going. Here's the primary character for the next scene: \"\"\" Name: Hugo Martinez Traits: Vulgar, Crude, Intense, Aggressive, Alcoholic, Harsh, Disciplined, Uncompromising, Loud, Expects a lot out of others, Swears constantly, Mid-forties, Wears a checkered shirt with overalls, Typically has a beer on hand, Has dental problems Dialogue Examples: Stranger: "What's your backstory?" Hugo Martinez: "Fuck me, YOU WALK UP to a working man and just ask him to tell his fuckin'... life story t' you?! DO YOU NOT RESPECT MY TIME?! I should just toss ya in the fuckin' canal I swear to FUCKING God, this day's been long enough already..." Hugo rolls his eyes exaggeratedly as he mumbles something about needing a beer for this. "Well, FINE! Since I'm in such a HAPPY GODDAMN MOOD, I'll tell you about me. I'm a site overseer at this here canal. The Panama Canal. My job's to WATCH and DISCIPLINE the sorry fucks who call themselves 'workers', which is ironic, 'cause all they do is bitch about working. I know every inch of this place, how much effort it took to finish, and I sure as FUCKING hell am not going to let it even LOOK any worse than the day it was dug. Now, you got any more shit questions for me?" Stranger: "What's your personality?" Hugo Martinez: "HO-LY FUCK, are you interviewing me for a job or something?! Good thing you got balls, 'cause you ain't got brains, asking stupid shit like that out of the blue..." Hugo grimaces, showing off a decayed set of teeth. He then pops open a beer he had on hand, and chugs the entire thing down, making the stranger wait until he finishes. "Phew! Maybe now I can tolerate you. Alright, my personality? Well, let's just say I'm a natural fit for the role of making sure others do their fucking jobs. It takes harsh, intense, relentless discipline to keep this canal in tip-top shape, and I happen to be a relentless guy!" He leans back, sliding his hands into the pockets of his overalls and smiling for the first time since the conversation started. "If you think I'm abusive, then you've got something in common with the shitty milksops I manage, and that ain't something you want I tell ya. I'm efficient. That's what counts." \"\"\" Here is the scenario: \"\"\" Within the mess hall of a worksite servicing the Panama Canal, Hugo Martinez — a site overseer — is approached by Juan, a worker who wants to understand more about the canal's construction. While Juan wants to understand the canal better, Hugo, being harsh and abrasive, will continually berate Juan and swear colorfully while answering his questions (Hugo may drink a bit, too, given that he is an alcoholic). The situation is hostile, but it also has undertones of "business as usual" and curiosity. \"\"\" Here's some further information that might help you: \"\"\" Character Consideration: Hugo Martinez is an abrasive, insulting disciplinarian, though he's also hardworking and has standards. The scenario should give his unique personality room to shine. Since he's a site overseer at the Panama Canal, his occupation lines up with the question well, and the canal will be the setting of the scenario. He will answer the questions, but given his insulting, intense, and aggressive nature, he will likely chew out the person who is asking the questions. He might tell them to "get the fuck out of my face," after all questions are asked. Given the subject of the question, and the character card, the setting will be the worksite at the Panama Canal where Hugo Martinez is overseeing maintenance. The person who approaches Hugo and asks the questions should be someone curious about the canal; given the easy-to-digest nature of the questions, this person might be a journalist, but it would be better for the secondary character to be related to the setting. So Hugo will be approached by Juan — one of his workers — during lunch break. Juan wants to understand the canal better, but Hugo, compelled by his personality, will continually be vulgar, berate Juan, and swear while answering his questions (he may drink a bit, too, given that he is an alcoholic). The setting will be hostile, as Juan tiptoes around the tempers of his boss while trying to get his questions answered, his stress and the constant wear of Hugo's fury on his sanity being evident in his actions. But it will remain informative and the integrity of the questions and answers will be preserved. Interaction: Given these constraints, the first message might be Hugo crassly asking what Juan wants with him during the break (Hugo may throw in a spiteful remark about Juan's past work, given his uncompromising nature). Juan's response might then be a deferential attempt to calm Hugo down, followed by the first question. Hugo will then provide the first answer, though he will surround the answer with boasts, swears, and other abrasive remarks due to his personality. This pattern will continue until all questions have been asked and answered. While characters' messages will include character information, details about the scene, and literary fluff, the answers themselves will strictly adhere to the information in the provided answers, without incorporating external examples. \"\"\" Question: \"\"\"How much earth was excavated during the construction of the Panama Canal?\"\"\" Answer: \"\"\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\"\"\" Question: \"\"\"What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\"\"\" Answer: \"\"\"The construction faced significant health challenges, notably malaria and yellow fever. These were overcome through extensive public health measures, illustrating the importance of health considerations in large-scale engineering projects.\"\"\" The primary character's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from Hugo Martinez should set up the scene. The second message of the conversation will ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. ### Response: ## Conversation that answers the provided questions: Hugo Martinez: "Huh? Oh FUCK ME, looks like a worker's got something they wanna say to me," Hugo, seeing Juan approach his table at the mess hall, rolls his eyes exasperatedly and downs half a beer as if to douse his frustration. Instead, it seems to fuel it. "WELL?!" He barks. "If you've got some stupid shit to say to me, Juan, then don't make me fucking wait to hear it, too!" Juan: "I was just curious, sir," Juan tiredly says as Hugo's words ring in his ears, "about this really impressive canal we've been maintaining (under your wise leadership). Do you know how much earth was excavated during the Panama Canal?" Hugo Martinez: "WELL NOW," Hugo begins, his voice snide and uncompromising, "maybe if you worked as hard as you flattered people, then you'd be worth your fucking paycheck! But that's a good question, so I'll let you off the hook this time. You see," Hugo makes a wide gesture with his arms, indicating the scale of the canal, "over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project. 200 MILLION! Now _those_ people know how to work!" Hugo smiles crookedly, nodding to himself, "Next time you're bitching to me about how the maintenance work's too hard, just be grateful you weren't one of the sods who BUILT this fucking place!" Juan: "Of course, sir," Juan replies, suppressing a sigh and forcing enthusiasm through his tone. "Now, if you would permit me just one more question before I get out of your way: What health challenges were faced during the construction of the Panama Canal, and how were they overcome?" Hugo Martinez: "Health? What, you planning on becoming a doctor? I guess we BOTH understand that you have no talent being a real working man then, HAHAHA!" Hugo's echoing laugh has not a hint of empathy in it. "Well, the construction faced significant health challenges, notably malaria and yellow fever. These were overcome through extensive public health measures, illustrating the importance of health considerations in large-scale engineering projects. Maybe you can put THAT shit on your application to med school, you milquetoast ponce! Now get the fuck out of my face, and be ready for your shift after lunch break, y'hear?!" ## Information: Comment: Very good. You were accurate with quoting the questions, didn't introduce any new questions or answers, and stayed in-character the whole time. Let's do the next one! Here's the character for the next scene: \"\"\" {character} \"\"\" Here is the scenario: \"\"\" {scenario} \"\"\" Here's some further information that might help you: \"\"\" {extra_info} \"\"\" {format_qatuples(qatuples)} The primary character's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from {charname} should set up the scene. The second message of the conversation will ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. ### Response: ## Conversation that answers the provided question (be sure that you do not change the questions or answers themselves; {charname} will answer the questions, not ask them; the questions and answers provided should be copied word for word, and surrounded by compelling conversation): {charname}: "{conv_starter}""" # NOTE: Very rarely, the first message of this conv will just be part of the character card, causing the conv to not make much sense. The cause of this is likely the fact that Elise quotes her character card in her first message. However, referencing the character card in this way also makes characters act as they are described, which is deemed advantageous enough that I am not changing this for now. # I get the sense that LLMs can learn relationships and connections between parts of the prompt, even if they're quite far apart, if you give them examples like this. It's fascinating to see how each part of the prompt has consequences -- sometimes unintended ones. # Note: performance degrades rapidly if you put more than one sentence in a pre-prompt parentheses thing completion = logic_llm( cot_prompt, max_tokens=8000, stop=["</s>", "# Input:", "## Information"], echo=True, grammar=multi_turn_conversation_grammar, temperature=0.5, top_k=0, top_p=1, min_p=0.6, )["choices"][0]["text"] # print("COMPLETION:\n\n----------------------") # print(completion) # print("\n------------------") # Extract plan response_pattern = re.compile( f"Conversation that answers the provided question \(be sure that you do not change the questions or answers themselves; {charname} will answer the questions, not ask them; the questions and answers provided should be copied word for word, and surrounded by compelling conversation\):\n(.+)", re.IGNORECASE | re.DOTALL, ) generation = response_pattern.search(completion).group(1) # print("GENERATION:\n\n-------------------\n\n", generation) # return (generation,"AI Assistant","A conversation between a helpful AI Assistant, and a user.","N/A",qatuples), completion return (generation, character, scenario, scenario_plan, qatuples), completion if __name__ == "__main__": # test logic_llm = Llama(
model_path=LOGICAL_MODEL,
1
2023-12-01 13:56:49+00:00
12k
IanYeung/MGLD-VSR
ldm/modules/diffusionmodules/openaimodel.py
[ { "identifier": "checkpoint", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def checkpoint(func, inputs, params, flag):\n \"\"\"\n Evaluate a function without caching intermediate activations, allowing for\n reduced memory at the expense of extra compute in the backward pass.\n ...
from abc import abstractmethod from functools import partial from typing import Iterable from einops import rearrange from ldm.modules.diffusionmodules.util import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_module, normalization, timestep_embedding, SpatialTemporalConv, ) from ldm.modules.attention import SpatialTransformer, SpatialTransformerV2, TemporalAttention from ldm.modules.spade import SPADE from basicsr.archs.stylegan2_arch import ConvLayer, EqualConv2d from basicsr.archs.tempo_model_arch import CouplePropModule, CouplePropModuleWithFlowNet from omegaconf.listconfig import ListConfig from omegaconf.listconfig import ListConfig from omegaconf.listconfig import ListConfig from omegaconf.listconfig import ListConfig import math import torch import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F import xformers import xformers.ops
7,341
""" class TimestepBlockDual(nn.Module): """ Any module where forward() takes timestep embeddings as a second argument. """ @abstractmethod def forward(self, x, emb, cond): """ Apply the module to `x` given `emb` timestep embeddings. """ class TimestepBlock3cond(nn.Module): """ Any module where forward() takes timestep embeddings as a second argument. """ @abstractmethod def forward(self, x, emb, s_cond, seg_cond): """ Apply the module to `x` given `emb` timestep embeddings. """ class TimestepEmbedSequential(nn.Sequential, TimestepBlock): """ A sequential module that passes timestep embeddings to the children that support it as an extra input. """ def forward(self, x, emb, context=None, struct_cond=None, seg_cond=None, flow=None): for layer in self: if isinstance(layer, TimestepBlock): x = layer(x, emb) elif isinstance(layer, SpatialTransformer) or isinstance(layer, SpatialTransformerV2): assert context is not None x = layer(x, context) elif isinstance(layer, TimestepBlockDual): assert struct_cond is not None x = layer(x, emb, struct_cond) elif isinstance(layer, TimestepBlock3cond): assert seg_cond is not None x = layer(x, emb, struct_cond, seg_cond) elif isinstance(layer, CouplePropModule): assert flow is not None x = layer(x, flow) else: x = layer(x) return x class Upsample(nn.Module): """ An upsampling layer with an optional convolution. :param channels: channels in the inputs and outputs. :param use_conv: a bool determining if a convolution is applied. :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then upsampling occurs in the inner-two dimensions. """ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.use_conv = use_conv self.dims = dims if use_conv: self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding) def forward(self, x): assert x.shape[1] == self.channels if self.dims == 3: x = F.interpolate( x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest" ) else: x = F.interpolate(x, scale_factor=2, mode="nearest") if self.use_conv: x = self.conv(x) return x class TransposedUpsample(nn.Module): """Learned 2x upsampling without padding""" def __init__(self, channels, out_channels=None, ks=5): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2) def forward(self,x): return self.up(x) class Downsample(nn.Module): """ A downsampling layer with an optional convolution. :param channels: channels in the inputs and outputs. :param use_conv: a bool determining if a convolution is applied. :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then downsampling occurs in the inner-two dimensions. """ def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.use_conv = use_conv self.dims = dims stride = 2 if dims != 3 else (1, 2, 2) if use_conv: self.op = conv_nd( dims, self.channels, self.out_channels, 3, stride=stride, padding=padding ) else: assert self.channels == self.out_channels
try: XFORMERS_IS_AVAILBLE = True except: XFORMERS_IS_AVAILBLE = False # dummy replace def convert_module_to_f16(x): pass def convert_module_to_f32(x): pass def exists(val): return val is not None def cal_fea_cossim(fea_1, fea_2, save_dir=None): cossim_fuc = nn.CosineSimilarity(dim=-1, eps=1e-6) if save_dir is None: save_dir_1 = './cos_sim64_1_not.txt' save_dir_2 = './cos_sim64_2_not.txt' b, c, h, w = fea_1.size() fea_1 = fea_1.reshape(b, c, h*w) fea_2 = fea_2.reshape(b, c, h*w) cos_sim = cossim_fuc(fea_1, fea_2) cos_sim = cos_sim.data.cpu().numpy() with open(save_dir_1, "a") as my_file: my_file.write(str(np.mean(cos_sim[0])) + "\n") # with open(save_dir_2, "a") as my_file: # my_file.write(str(np.mean(cos_sim[1])) + "\n") ## go class AttentionPool2d(nn.Module): """ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py """ def __init__( self, spacial_dim: int, embed_dim: int, num_heads_channels: int, output_dim: int = None, ): super().__init__() self.positional_embedding = nn.Parameter(th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5) self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1) self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1) self.num_heads = embed_dim // num_heads_channels self.attention = QKVAttention(self.num_heads) def forward(self, x): b, c, *_spatial = x.shape x = x.reshape(b, c, -1) # NC(HW) x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1) x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1) x = self.qkv_proj(x) x = self.attention(x) x = self.c_proj(x) return x[:, :, 0] class TimestepBlock(nn.Module): """ Any module where forward() takes timestep embeddings as a second argument. """ @abstractmethod def forward(self, x, emb): """ Apply the module to `x` given `emb` timestep embeddings. """ class TimestepBlockDual(nn.Module): """ Any module where forward() takes timestep embeddings as a second argument. """ @abstractmethod def forward(self, x, emb, cond): """ Apply the module to `x` given `emb` timestep embeddings. """ class TimestepBlock3cond(nn.Module): """ Any module where forward() takes timestep embeddings as a second argument. """ @abstractmethod def forward(self, x, emb, s_cond, seg_cond): """ Apply the module to `x` given `emb` timestep embeddings. """ class TimestepEmbedSequential(nn.Sequential, TimestepBlock): """ A sequential module that passes timestep embeddings to the children that support it as an extra input. """ def forward(self, x, emb, context=None, struct_cond=None, seg_cond=None, flow=None): for layer in self: if isinstance(layer, TimestepBlock): x = layer(x, emb) elif isinstance(layer, SpatialTransformer) or isinstance(layer, SpatialTransformerV2): assert context is not None x = layer(x, context) elif isinstance(layer, TimestepBlockDual): assert struct_cond is not None x = layer(x, emb, struct_cond) elif isinstance(layer, TimestepBlock3cond): assert seg_cond is not None x = layer(x, emb, struct_cond, seg_cond) elif isinstance(layer, CouplePropModule): assert flow is not None x = layer(x, flow) else: x = layer(x) return x class Upsample(nn.Module): """ An upsampling layer with an optional convolution. :param channels: channels in the inputs and outputs. :param use_conv: a bool determining if a convolution is applied. :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then upsampling occurs in the inner-two dimensions. """ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.use_conv = use_conv self.dims = dims if use_conv: self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding) def forward(self, x): assert x.shape[1] == self.channels if self.dims == 3: x = F.interpolate( x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest" ) else: x = F.interpolate(x, scale_factor=2, mode="nearest") if self.use_conv: x = self.conv(x) return x class TransposedUpsample(nn.Module): """Learned 2x upsampling without padding""" def __init__(self, channels, out_channels=None, ks=5): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2) def forward(self,x): return self.up(x) class Downsample(nn.Module): """ A downsampling layer with an optional convolution. :param channels: channels in the inputs and outputs. :param use_conv: a bool determining if a convolution is applied. :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then downsampling occurs in the inner-two dimensions. """ def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.use_conv = use_conv self.dims = dims stride = 2 if dims != 3 else (1, 2, 2) if use_conv: self.op = conv_nd( dims, self.channels, self.out_channels, 3, stride=stride, padding=padding ) else: assert self.channels == self.out_channels
self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
3
2023-11-30 01:50:29+00:00
12k
Institute4FutureHealth/CHA
orchestrator/orchestrator.py
[ { "identifier": "CustomDebugFormatter", "path": "CustomDebugFormatter.py", "snippet": "class CustomDebugFormatter(logging.Formatter):\n COLOR_CODES = {\n \"red\": \"\\033[1;91m\",\n \"green\": \"\\033[1;92m\",\n \"yellow\": \"\\033[1;93m\",\n \"blue\": \"\\033[1;94m\",\n ...
import logging import re from typing import Any from typing import Dict from typing import List from typing import Optional from typing import Union from pydantic import BaseModel from CustomDebugFormatter import CustomDebugFormatter from datapipes.datapipe import DataPipe from datapipes.datapipe_types import DatapipeType from datapipes.initialize_datapipe import initialize_datapipe from llms.llm_types import LLMType from planners.action import Action from planners.action import PlanFinish from planners.initialize_planner import initialize_planner from planners.planner import BasePlanner from planners.planner_types import PlannerType from response_generators.initialize_response_generator import ( initialize_response_generator, ) from response_generators.response_generator import ( BaseResponseGenerator, ) from response_generators.response_generator_types import ( ResponseGeneratorType, ) from tasks.initialize_task import initialize_task from tasks.task import BaseTask from tasks.task_types import TaskType
7,961
arbitrary_types_allowed = True def print_log(self, log_name: str, message: str): if self.verbose: if log_name == "planner": self.planner_logger.debug(message) if log_name == "task": self.tasks_logger.debug(message) if log_name == "orchestrator": self.orchestrator_logger.debug(message) if log_name == "response_generator": self.final_answer_generator_logger.debug(message) if log_name == "promptist": self.promptist_logger.debug(message) if log_name == "error": self.error_logger.debug(message) @classmethod def initialize( self, planner_llm: str = LLMType.OPENAI, planner_name: str = PlannerType.ZERO_SHOT_REACT_PLANNER, datapipe_name: str = DatapipeType.MEMORY, promptist_name: str = "", response_generator_llm: str = LLMType.OPENAI, response_generator_name: str = ResponseGeneratorType.BASE_GENERATOR, available_tasks: Optional[List[str]] = None, verbose: bool = False, **kwargs, ) -> Orchestrator: """ This class method initializes the Orchestrator by setting up the planner, datapipe, promptist, response generator, and available tasks. Args: planner_llm (str): LLMType to be used as LLM for planner. planner_name (str): PlannerType to be used as task planner. datapipe_name (str): DatapipeType to be used as data pipe. promptist_name (str): Not implemented yet! response_generator_llm (str): LLMType to be used as LLM for response generator. response_generator_name (str): ResponseGeneratorType to be used as response generator. available_tasks (List[str]): List of available task using TaskType. verbose (bool): Specifies if the debugging logs be printed or not. **kwargs (Any): Additional keyword arguments. Return: Orchestrator: Initialized Orchestrator instance. Example: .. code-block:: python from datapipes.datapipe_types import DatapipeType from planners.planner_types import PlannerType from response_generators.response_generator_types import ResponseGeneratorType from tasks.task_types import TaskType from llms.llm_types import LLMType from orchestrator.orchestrator import Orchestrator #If you want to use playwright task from tasks.playwright.utils import create_sync_playwright_browser sync_browser = create_sync_playwright_browser() # orchestrator = Orchestrator.initialize( planner_llm=LLMType.OPENAI, planner_name=PlannerType.ZERO_SHOT_REACT_PLANNER, datapipe_name=DatapipeType.MEMORY, promptist_name="", response_generator_llm=LLMType.OPENAI, response_generator_name=ResponseGeneratorType.BASE_GENERATOR, available_tasks=[TaskType.SERPAPI, TaskType.EXTRACT_TEXT], sync_browser=sync_browser, verbose=self.verbose, **kwargs ) """ if available_tasks is None: available_tasks = [] planner_logger = ( tasks_logger ) = ( orchestrator_logger ) = ( final_answer_generator_logger ) = promptist_logger = error_logger = None if verbose: planner_logger = CustomDebugFormatter.create_logger( "Planner", "cyan" ) tasks_logger = CustomDebugFormatter.create_logger( "Task", "purple" ) orchestrator_logger = CustomDebugFormatter.create_logger( "Orchestrator", "green" ) final_answer_generator_logger = ( CustomDebugFormatter.create_logger( "Response Generator", "blue" ) ) promptist_logger = CustomDebugFormatter.create_logger( "Promptist", "blue" ) error_logger = CustomDebugFormatter.create_logger( "Error", "red" ) datapipe = initialize_datapipe( datapipe=datapipe_name, **kwargs ) if verbose: orchestrator_logger.debug( f"Datapipe {datapipe_name} is successfully initialized.\n" ) tasks = {} for task in available_tasks: kwargs["datapipe"] = datapipe
from __future__ import annotations class Orchestrator(BaseModel): """ **Description:** The Orchestrator class is the main execution heart of the CHA. All the components of the Orchestrator are initialized and executed here. The Orchestrator will start a new answering cycle by calling the `run` method. From there, the planning is started, then tasks will be executed one by one till the **Task Planner** decides that no more information is needed. Finally the **Task Planner** final answer will be routed to the **Final Response Generator** to generate an empathic final response that is returned to the user. """ planner: BasePlanner = None datapipe: DataPipe = None promptist: Any = None response_generator: BaseResponseGenerator = None available_tasks: Dict[str, BaseTask] = {} max_retries: int = 16 max_task_execute_retries: int = 3 max_planner_execute_retries: int = 16 max_final_answer_execute_retries: int = 3 role: int = 0 verbose: bool = False planner_logger: Optional[logging.Logger] = None tasks_logger: Optional[logging.Logger] = None orchestrator_logger: Optional[logging.Logger] = None final_answer_generator_logger: Optional[logging.Logger] = None promptist_logger: Optional[logging.Logger] = None error_logger: Optional[logging.Logger] = None class Config: """Configuration for this pydantic object.""" arbitrary_types_allowed = True def print_log(self, log_name: str, message: str): if self.verbose: if log_name == "planner": self.planner_logger.debug(message) if log_name == "task": self.tasks_logger.debug(message) if log_name == "orchestrator": self.orchestrator_logger.debug(message) if log_name == "response_generator": self.final_answer_generator_logger.debug(message) if log_name == "promptist": self.promptist_logger.debug(message) if log_name == "error": self.error_logger.debug(message) @classmethod def initialize( self, planner_llm: str = LLMType.OPENAI, planner_name: str = PlannerType.ZERO_SHOT_REACT_PLANNER, datapipe_name: str = DatapipeType.MEMORY, promptist_name: str = "", response_generator_llm: str = LLMType.OPENAI, response_generator_name: str = ResponseGeneratorType.BASE_GENERATOR, available_tasks: Optional[List[str]] = None, verbose: bool = False, **kwargs, ) -> Orchestrator: """ This class method initializes the Orchestrator by setting up the planner, datapipe, promptist, response generator, and available tasks. Args: planner_llm (str): LLMType to be used as LLM for planner. planner_name (str): PlannerType to be used as task planner. datapipe_name (str): DatapipeType to be used as data pipe. promptist_name (str): Not implemented yet! response_generator_llm (str): LLMType to be used as LLM for response generator. response_generator_name (str): ResponseGeneratorType to be used as response generator. available_tasks (List[str]): List of available task using TaskType. verbose (bool): Specifies if the debugging logs be printed or not. **kwargs (Any): Additional keyword arguments. Return: Orchestrator: Initialized Orchestrator instance. Example: .. code-block:: python from datapipes.datapipe_types import DatapipeType from planners.planner_types import PlannerType from response_generators.response_generator_types import ResponseGeneratorType from tasks.task_types import TaskType from llms.llm_types import LLMType from orchestrator.orchestrator import Orchestrator #If you want to use playwright task from tasks.playwright.utils import create_sync_playwright_browser sync_browser = create_sync_playwright_browser() # orchestrator = Orchestrator.initialize( planner_llm=LLMType.OPENAI, planner_name=PlannerType.ZERO_SHOT_REACT_PLANNER, datapipe_name=DatapipeType.MEMORY, promptist_name="", response_generator_llm=LLMType.OPENAI, response_generator_name=ResponseGeneratorType.BASE_GENERATOR, available_tasks=[TaskType.SERPAPI, TaskType.EXTRACT_TEXT], sync_browser=sync_browser, verbose=self.verbose, **kwargs ) """ if available_tasks is None: available_tasks = [] planner_logger = ( tasks_logger ) = ( orchestrator_logger ) = ( final_answer_generator_logger ) = promptist_logger = error_logger = None if verbose: planner_logger = CustomDebugFormatter.create_logger( "Planner", "cyan" ) tasks_logger = CustomDebugFormatter.create_logger( "Task", "purple" ) orchestrator_logger = CustomDebugFormatter.create_logger( "Orchestrator", "green" ) final_answer_generator_logger = ( CustomDebugFormatter.create_logger( "Response Generator", "blue" ) ) promptist_logger = CustomDebugFormatter.create_logger( "Promptist", "blue" ) error_logger = CustomDebugFormatter.create_logger( "Error", "red" ) datapipe = initialize_datapipe( datapipe=datapipe_name, **kwargs ) if verbose: orchestrator_logger.debug( f"Datapipe {datapipe_name} is successfully initialized.\n" ) tasks = {} for task in available_tasks: kwargs["datapipe"] = datapipe
tasks[task] = initialize_task(task=task, **kwargs)
13
2023-12-02 05:10:44+00:00
12k
Czm369/MixPL
projects/MixPL/mixpl/mixpl.py
[ { "identifier": "filter_gt_instances", "path": "mmdet/models/utils/misc.py", "snippet": "def filter_gt_instances(batch_data_samples: SampleList,\n score_thr: float = None,\n wh_thr: tuple = None):\n \"\"\"Filter ground truth (GT) instances by score and/or...
import copy import torch import numpy as np import math import os.path as osp from typing import Dict, Optional, Tuple from torch import Tensor from mmdet.models.utils import (filter_gt_instances, rename_loss_dict, reweight_loss_dict) from mmdet.registry import MODELS from mmdet.visualization import DetLocalVisualizer from mmdet.structures import DetDataSample, SampleList from mmdet.utils import ConfigType, InstanceList, OptConfigType, OptMultiConfig from mmdet.models.detectors import SemiBaseDetector from mmdet.structures.bbox import bbox_project from torch.nn import functional as F
10,726
Each value should usually be mean centered and std scaled. multi_batch_data_samples (Dict[str, List[:obj:`DetDataSample`]]): The dict of multi-branch data samples. Returns: dict: A dictionary of loss components """ losses = dict() losses.update(**self.loss_by_gt_instances( multi_batch_inputs['sup'], multi_batch_data_samples['sup'])) origin_batch_pseudo_data_samples, batch_info = self.get_pseudo_instances( multi_batch_inputs['unsup_teacher'], multi_batch_data_samples['unsup_teacher']) multi_batch_data_samples['unsup_student'] = self.project_pseudo_instances( origin_batch_pseudo_data_samples, multi_batch_data_samples['unsup_student']) batch_unsup_inputs = copy.deepcopy(multi_batch_inputs['unsup_student']) batch_unsup_data_samples = copy.deepcopy(multi_batch_data_samples['unsup_student']) batch_unsup_inputs, batch_unsup_data_samples = self.merge( *zip(*list(map(self.erase, *self.split(batch_unsup_inputs, batch_unsup_data_samples))))) sample_size = len(multi_batch_data_samples['unsup_student']) mixup_idxs = np.random.choice(range(sample_size), sample_size, replace=False) mosaic_idxs = np.random.choice(range(4), 4, replace=False) + sample_size if self.semi_train_cfg.mixup and len(self.cache_inputs) == self.semi_train_cfg.cache_size: dst_inputs_list, batch_dst_data_samples = self.split( batch_unsup_inputs, batch_unsup_data_samples) img_shapes = [tuple(batch_unsup_inputs.shape[-2:])]*batch_unsup_inputs.shape[0] src_inputs_list, batch_src_data_samples = self.get_batch(mixup_idxs, img_shapes) batch_unsup_inputs, batch_unsup_data_samples = self.merge(*self.mixup( dst_inputs_list, batch_dst_data_samples, src_inputs_list, batch_src_data_samples)) if self.semi_train_cfg.mixup: losses.update(**rename_loss_dict('mixup_', self.loss_by_pseudo_instances( batch_unsup_inputs, batch_unsup_data_samples))) else: losses.update(**self.loss_by_pseudo_instances( batch_unsup_inputs, batch_unsup_data_samples)) if self.semi_train_cfg.mosaic and len(self.cache_inputs) == self.semi_train_cfg.cache_size: if len(self.semi_train_cfg.mosaic_shape) == 1: img_shapes = [self.semi_train_cfg.mosaic_shape[0]] * 4 else: mosaic_shape = self.semi_train_cfg.mosaic_shape mosaic_h = np.random.randint( min(mosaic_shape[0][0], mosaic_shape[1][0]), max(mosaic_shape[0][0], mosaic_shape[1][0])) mosaic_w = np.random.randint( min(mosaic_shape[0][1], mosaic_shape[1][1]), max(mosaic_shape[0][1], mosaic_shape[1][1])) img_shapes = [(mosaic_h, mosaic_w)] * 4 src_inputs_list, batch_src_data_samples = self.get_batch(mosaic_idxs, img_shapes) mosaic_inputs, mosaic_data_samples = self.mosaic(src_inputs_list, batch_src_data_samples) mosaic_losses = self.loss_by_pseudo_instances(mosaic_inputs, mosaic_data_samples) losses.update(**rename_loss_dict('mosaic_', reweight_loss_dict(mosaic_losses, self.semi_train_cfg.mosaic_weight))) self.update_cache(multi_batch_inputs['unsup_student'], multi_batch_data_samples['unsup_student']) return losses def merge(self, inputs_list, batch_data_samples): batch_size = len(inputs_list) h, w = 0, 0 for i in range(batch_size): img_h, img_w = batch_data_samples[i].img_shape h, w = max(h, img_h), max(w, img_w) h, w = max(h, math.ceil(h / 32) * 32), max(w, math.ceil(w / 32) * 32) batch_inputs = torch.zeros((batch_size, 3, h, w)).to(self.data_preprocessor.device) for i in range(batch_size): img_h, img_w = batch_data_samples[i].img_shape batch_inputs[i, :, :img_h, :img_w] = inputs_list[i] batch_data_samples[i].set_metainfo({'batch_input_shape': (h, w)}) batch_data_samples[i].set_metainfo({'pad_shape': (h, w)}) return batch_inputs, batch_data_samples def split(self, batch_inputs, batch_data_samples): inputs_list = [] for i in range(len(batch_inputs)): inputs = batch_inputs[i] data_samples = batch_data_samples[i] img_h, img_w = data_samples.img_shape inputs_list.append(inputs[..., :img_h, :img_w]) data_samples.pop('batch_input_shape') data_samples.pop('pad_shape') return inputs_list, batch_data_samples def update_cache(self, batch_inputs: Tensor, batch_data_samples: SampleList): inputs_list, batch_data_samples = self.split(batch_inputs, batch_data_samples) cache_size = self.semi_train_cfg.cache_size self.cache_inputs.extend(inputs_list) self.cache_data_samples.extend(batch_data_samples) self.cache_inputs = self.cache_inputs[-cache_size:] self.cache_data_samples = self.cache_data_samples[-cache_size:] def get_cache(self, idx, img_shape): inputs = copy.deepcopy(self.cache_inputs[idx]) data_samples = copy.deepcopy(self.cache_data_samples[idx]) inputs, data_samples = self.erase(*self.flip(*self.resize(inputs, data_samples, img_shape))) return inputs, data_samples def get_batch(self, rand_idxs, img_shapes): inputs_list, batch_data_samples = [], [] for i in range(len(rand_idxs)): inputs, data_samples = self.get_cache(rand_idxs[i], img_shapes[i]) inputs_list.append(inputs) batch_data_samples.append(data_samples) return inputs_list, batch_data_samples def resize(self, inputs, data_samples, img_shape): scale = min(img_shape[0] / data_samples.img_shape[0], img_shape[1] / data_samples.img_shape[1]) inputs = F.interpolate(inputs.unsqueeze(0), scale_factor=scale).squeeze(0) data_samples.pop('img_shape') data_samples.pop('scale_factor') img_h, img_w = inputs.shape[-2:] data_samples.set_metainfo({'img_shape': (img_h, img_w)}) ori_h, ori_w = data_samples.ori_shape data_samples.set_metainfo({'scale_factor': (img_w / ori_w, img_h / ori_h)}) hm = data_samples.pop('homography_matrix') matrix = np.array([[scale, 0, 0], [0, scale, 0], [0, 0, 1]], dtype=np.float32) data_samples.set_metainfo({'homography_matrix': matrix @ hm}) data_samples.gt_instances.bboxes *= scale data_samples.gt_instances.bboxes[:, 0::2].clamp_(0, img_w) data_samples.gt_instances.bboxes[:, 1::2].clamp_(0, img_h)
# Copyright (c) OpenMMLab. All rights reserved. @MODELS.register_module() class MixPL(SemiBaseDetector): """Base class for semi-supervised detectors.""" def __init__(self, detector: ConfigType, semi_train_cfg: OptConfigType = None, semi_test_cfg: OptConfigType = None, data_preprocessor: OptConfigType = None, init_cfg: OptMultiConfig = None) -> None: super().__init__( detector=detector, semi_train_cfg=semi_train_cfg, semi_test_cfg=semi_test_cfg, data_preprocessor=data_preprocessor, init_cfg=init_cfg) self.cache_inputs = [] self.cache_data_samples = [] def loss(self, multi_batch_inputs: Dict[str, Tensor], multi_batch_data_samples: Dict[str, SampleList]) -> dict: """Calculate losses from multi-branch inputs and data samples. Args: multi_batch_inputs (Dict[str, Tensor]): The dict of multi-branch input images, each value with shape (N, C, H, W). Each value should usually be mean centered and std scaled. multi_batch_data_samples (Dict[str, List[:obj:`DetDataSample`]]): The dict of multi-branch data samples. Returns: dict: A dictionary of loss components """ losses = dict() losses.update(**self.loss_by_gt_instances( multi_batch_inputs['sup'], multi_batch_data_samples['sup'])) origin_batch_pseudo_data_samples, batch_info = self.get_pseudo_instances( multi_batch_inputs['unsup_teacher'], multi_batch_data_samples['unsup_teacher']) multi_batch_data_samples['unsup_student'] = self.project_pseudo_instances( origin_batch_pseudo_data_samples, multi_batch_data_samples['unsup_student']) batch_unsup_inputs = copy.deepcopy(multi_batch_inputs['unsup_student']) batch_unsup_data_samples = copy.deepcopy(multi_batch_data_samples['unsup_student']) batch_unsup_inputs, batch_unsup_data_samples = self.merge( *zip(*list(map(self.erase, *self.split(batch_unsup_inputs, batch_unsup_data_samples))))) sample_size = len(multi_batch_data_samples['unsup_student']) mixup_idxs = np.random.choice(range(sample_size), sample_size, replace=False) mosaic_idxs = np.random.choice(range(4), 4, replace=False) + sample_size if self.semi_train_cfg.mixup and len(self.cache_inputs) == self.semi_train_cfg.cache_size: dst_inputs_list, batch_dst_data_samples = self.split( batch_unsup_inputs, batch_unsup_data_samples) img_shapes = [tuple(batch_unsup_inputs.shape[-2:])]*batch_unsup_inputs.shape[0] src_inputs_list, batch_src_data_samples = self.get_batch(mixup_idxs, img_shapes) batch_unsup_inputs, batch_unsup_data_samples = self.merge(*self.mixup( dst_inputs_list, batch_dst_data_samples, src_inputs_list, batch_src_data_samples)) if self.semi_train_cfg.mixup: losses.update(**rename_loss_dict('mixup_', self.loss_by_pseudo_instances( batch_unsup_inputs, batch_unsup_data_samples))) else: losses.update(**self.loss_by_pseudo_instances( batch_unsup_inputs, batch_unsup_data_samples)) if self.semi_train_cfg.mosaic and len(self.cache_inputs) == self.semi_train_cfg.cache_size: if len(self.semi_train_cfg.mosaic_shape) == 1: img_shapes = [self.semi_train_cfg.mosaic_shape[0]] * 4 else: mosaic_shape = self.semi_train_cfg.mosaic_shape mosaic_h = np.random.randint( min(mosaic_shape[0][0], mosaic_shape[1][0]), max(mosaic_shape[0][0], mosaic_shape[1][0])) mosaic_w = np.random.randint( min(mosaic_shape[0][1], mosaic_shape[1][1]), max(mosaic_shape[0][1], mosaic_shape[1][1])) img_shapes = [(mosaic_h, mosaic_w)] * 4 src_inputs_list, batch_src_data_samples = self.get_batch(mosaic_idxs, img_shapes) mosaic_inputs, mosaic_data_samples = self.mosaic(src_inputs_list, batch_src_data_samples) mosaic_losses = self.loss_by_pseudo_instances(mosaic_inputs, mosaic_data_samples) losses.update(**rename_loss_dict('mosaic_', reweight_loss_dict(mosaic_losses, self.semi_train_cfg.mosaic_weight))) self.update_cache(multi_batch_inputs['unsup_student'], multi_batch_data_samples['unsup_student']) return losses def merge(self, inputs_list, batch_data_samples): batch_size = len(inputs_list) h, w = 0, 0 for i in range(batch_size): img_h, img_w = batch_data_samples[i].img_shape h, w = max(h, img_h), max(w, img_w) h, w = max(h, math.ceil(h / 32) * 32), max(w, math.ceil(w / 32) * 32) batch_inputs = torch.zeros((batch_size, 3, h, w)).to(self.data_preprocessor.device) for i in range(batch_size): img_h, img_w = batch_data_samples[i].img_shape batch_inputs[i, :, :img_h, :img_w] = inputs_list[i] batch_data_samples[i].set_metainfo({'batch_input_shape': (h, w)}) batch_data_samples[i].set_metainfo({'pad_shape': (h, w)}) return batch_inputs, batch_data_samples def split(self, batch_inputs, batch_data_samples): inputs_list = [] for i in range(len(batch_inputs)): inputs = batch_inputs[i] data_samples = batch_data_samples[i] img_h, img_w = data_samples.img_shape inputs_list.append(inputs[..., :img_h, :img_w]) data_samples.pop('batch_input_shape') data_samples.pop('pad_shape') return inputs_list, batch_data_samples def update_cache(self, batch_inputs: Tensor, batch_data_samples: SampleList): inputs_list, batch_data_samples = self.split(batch_inputs, batch_data_samples) cache_size = self.semi_train_cfg.cache_size self.cache_inputs.extend(inputs_list) self.cache_data_samples.extend(batch_data_samples) self.cache_inputs = self.cache_inputs[-cache_size:] self.cache_data_samples = self.cache_data_samples[-cache_size:] def get_cache(self, idx, img_shape): inputs = copy.deepcopy(self.cache_inputs[idx]) data_samples = copy.deepcopy(self.cache_data_samples[idx]) inputs, data_samples = self.erase(*self.flip(*self.resize(inputs, data_samples, img_shape))) return inputs, data_samples def get_batch(self, rand_idxs, img_shapes): inputs_list, batch_data_samples = [], [] for i in range(len(rand_idxs)): inputs, data_samples = self.get_cache(rand_idxs[i], img_shapes[i]) inputs_list.append(inputs) batch_data_samples.append(data_samples) return inputs_list, batch_data_samples def resize(self, inputs, data_samples, img_shape): scale = min(img_shape[0] / data_samples.img_shape[0], img_shape[1] / data_samples.img_shape[1]) inputs = F.interpolate(inputs.unsqueeze(0), scale_factor=scale).squeeze(0) data_samples.pop('img_shape') data_samples.pop('scale_factor') img_h, img_w = inputs.shape[-2:] data_samples.set_metainfo({'img_shape': (img_h, img_w)}) ori_h, ori_w = data_samples.ori_shape data_samples.set_metainfo({'scale_factor': (img_w / ori_w, img_h / ori_h)}) hm = data_samples.pop('homography_matrix') matrix = np.array([[scale, 0, 0], [0, scale, 0], [0, 0, 1]], dtype=np.float32) data_samples.set_metainfo({'homography_matrix': matrix @ hm}) data_samples.gt_instances.bboxes *= scale data_samples.gt_instances.bboxes[:, 0::2].clamp_(0, img_w) data_samples.gt_instances.bboxes[:, 1::2].clamp_(0, img_h)
return inputs, filter_gt_instances([data_samples])[0]
0
2023-11-30 08:58:00+00:00
12k
DQiaole/FlowDiffusion_pytorch
local_diffusers/models/raft_unet.py
[ { "identifier": "BasicEncoder", "path": "core/extractor.py", "snippet": "class BasicEncoder(nn.Module):\n def __init__(self, output_dim=128, norm_fn='batch', dropout=0.0):\n super(BasicEncoder, self).__init__()\n self.norm_fn = norm_fn\n\n if self.norm_fn == 'group':\n ...
import math import copy import torch import torch.nn.functional as F import torchvision.transforms as T from random import random from typing import Optional, List, Union from tqdm.auto import tqdm from functools import partial, wraps from contextlib import contextmanager, nullcontext from collections import namedtuple from pathlib import Path from diffusers.utils import BaseOutput from torch.nn.parallel import DistributedDataParallel from torch import nn, einsum from torch.cuda.amp import autocast from torch.special import expm1 from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.models.modeling_utils import ModelMixin from dataclasses import dataclass from einops import rearrange, repeat, reduce, pack, unpack from einops.layers.torch import Rearrange, Reduce from core.extractor import BasicEncoder from .imagen_unet import Unet, exists, UNet2DOutput from core.utils.utils import bilinear_sampler, coords_grid, downflow8 from core.corr import CorrBlock from xformers.ops import memory_efficient_attention, unbind, fmha from flash_attn import flash_attn_qkvpacked_func, flash_attn_func
7,608
try: XFORMERS_AVAILABLE = True except ImportError: print("xFormers not available") XFORMERS_AVAILABLE = False try: FLASH_AVAILABLE = True except ImportError: print("FLASH ATTENTION2 not available") FLASH_AVAILABLE = False # predefined unets, with configs lining up with hyperparameters in appendix of paper class RAFT_Unet(Unet, ModelMixin, ConfigMixin): @register_to_config def __init__(self, channels, channels_out, sample_size, add_dim=(0, 0, 324, 0), corr_index='noised_flow', **kwargs): default_kwargs = dict( channels=channels, channels_out=channels_out, sample_size=sample_size, dim=128, dim_mults=(1, 2, 4, 8), num_resnet_blocks=(2, 4, 8, 8), layer_attns=(False, False, True, True), layer_cross_attns=(False, False, False, False), attn_heads=8, ff_mult=2., memory_efficient=True, add_dim=add_dim, corr_index=corr_index ) super().__init__(**default_kwargs) # feature encoder self.fnet = BasicEncoder(output_dim=256, norm_fn='instance', dropout=0.0) print('[fnet: BasicEncoder]') assert self.corr_index in ['orginal', 'noised_flow', None] print('[corr_index: ', self.corr_index, ']') def forward( self, sample: torch.FloatTensor, timestep: Union[torch.Tensor, float, int], class_labels: Optional[torch.Tensor] = None, return_dict: bool = True, normalize=False, ): time = timestep x = sample # encoder feature image1, image2 = x[:, :3], x[:, 3:6] fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.float() fmap2 = fmap2.float() corr_fn = CorrBlock(fmap1, fmap2, radius=4) N, C, H, W = image1.shape
try: XFORMERS_AVAILABLE = True except ImportError: print("xFormers not available") XFORMERS_AVAILABLE = False try: FLASH_AVAILABLE = True except ImportError: print("FLASH ATTENTION2 not available") FLASH_AVAILABLE = False # predefined unets, with configs lining up with hyperparameters in appendix of paper class RAFT_Unet(Unet, ModelMixin, ConfigMixin): @register_to_config def __init__(self, channels, channels_out, sample_size, add_dim=(0, 0, 324, 0), corr_index='noised_flow', **kwargs): default_kwargs = dict( channels=channels, channels_out=channels_out, sample_size=sample_size, dim=128, dim_mults=(1, 2, 4, 8), num_resnet_blocks=(2, 4, 8, 8), layer_attns=(False, False, True, True), layer_cross_attns=(False, False, False, False), attn_heads=8, ff_mult=2., memory_efficient=True, add_dim=add_dim, corr_index=corr_index ) super().__init__(**default_kwargs) # feature encoder self.fnet = BasicEncoder(output_dim=256, norm_fn='instance', dropout=0.0) print('[fnet: BasicEncoder]') assert self.corr_index in ['orginal', 'noised_flow', None] print('[corr_index: ', self.corr_index, ']') def forward( self, sample: torch.FloatTensor, timestep: Union[torch.Tensor, float, int], class_labels: Optional[torch.Tensor] = None, return_dict: bool = True, normalize=False, ): time = timestep x = sample # encoder feature image1, image2 = x[:, :3], x[:, 3:6] fmap1, fmap2 = self.fnet([image1, image2]) fmap1 = fmap1.float() fmap2 = fmap2.float() corr_fn = CorrBlock(fmap1, fmap2, radius=4) N, C, H, W = image1.shape
coords1 = coords_grid(N, H // 8, W // 8, device=image1.device)
5
2023-12-01 11:14:25+00:00
12k
EnVision-Research/DDSM
main.py
[ { "identifier": "model_profiling", "path": "profile.py", "snippet": "def model_profiling(model, height, width, batch=1, channel=3, use_cuda=True,\n verbose=True):\n \"\"\" Pytorch model profiling with input image size\n (batch, channel, height, width).\n The function exams th...
import copy import json import os import random import warnings import time import torch import numpy as np from absl import app, flags from tensorboardX import SummaryWriter from torchvision.datasets import CIFAR10 from torchvision.utils import make_grid, save_image from torchvision import transforms from tqdm import trange from pymoo.algorithms.moo.nsga2 import NSGA2 from pymoo.core.problem import Problem from pymoo.optimize import minimize from pymoo.core.mutation import Mutation from pymoo.operators.sampling.rnd import FloatRandomSampling from pymoo.operators.sampling.rnd import IntegerRandomSampling from pymoo.operators.mutation.pm import PolynomialMutation from pymoo.operators.crossover.pntx import SinglePointCrossover from profile import model_profiling from ptflops import get_model_complexity_info from diffusion import GaussianDiffusionTrainer, GaussianDiffusionSampler from model import UNet, EnsembleUNet from slimmable_model import SlimmableUNet, StepAwareUNet from slimmable_model_g16 import Slimmable16UNet, StepAware16UNet from score.both import get_inception_and_fid_score, get_fid_score
10,154
net_model.eval() with torch.no_grad(): x_0 = ema_sampler(x_T) grid = (make_grid(x_0) + 1) / 2 path = os.path.join( FLAGS.logdir, 'sample', '%d.png' % step) save_image(grid, path) writer.add_image('sample', grid, step) net_model.train() # save if FLAGS.save_step > 0 and step % FLAGS.save_step == 0: ckpt = { 'net_model': net_model.state_dict(), 'ema_model': ema_model.state_dict(), 'sched': sched.state_dict(), 'optim': optim.state_dict(), 'step': step, 'x_T': x_T, } torch.save(ckpt, os.path.join(FLAGS.logdir, 'ckpt.pt')) torch.save(ckpt, os.path.join(FLAGS.logdir, 'ckpt_{}.pt'.format(step))) # evaluate if FLAGS.eval_step > 0 and step % FLAGS.eval_step == 0: net_IS, net_FID, _ = evaluate(net_sampler, net_model) ema_IS, ema_FID, _ = evaluate(ema_sampler, ema_model) metrics = { 'IS': net_IS[0], 'IS_std': net_IS[1], 'FID': net_FID, 'IS_EMA': ema_IS[0], 'IS_std_EMA': ema_IS[1], 'FID_EMA': ema_FID } pbar.write( "%d/%d " % (step, FLAGS.total_steps) + ", ".join('%s:%.3f' % (k, v) for k, v in metrics.items())) for name, value in metrics.items(): writer.add_scalar(name, value, step) writer.flush() with open(os.path.join(FLAGS.logdir, 'eval.txt'), 'a') as f: metrics['step'] = step f.write(json.dumps(metrics) + "\n") writer.close() def Eval(): # model setup if FLAGS.slimmable_unet: model = SlimmableUNet( T=FLAGS.T, ch=FLAGS.ch, ch_mult=FLAGS.ch_mult, attn=FLAGS.attn, num_res_blocks=FLAGS.num_res_blocks, dropout=FLAGS.dropout) model.apply(lambda m: setattr(m, 'width_mult', FLAGS.assigned_width)) else: model = UNet( T=FLAGS.T, ch=FLAGS.ch, ch_mult=FLAGS.ch_mult, attn=FLAGS.attn, num_res_blocks=FLAGS.num_res_blocks, dropout=FLAGS.dropout) sampler = GaussianDiffusionSampler( model, FLAGS.beta_1, FLAGS.beta_T, FLAGS.T, img_size=FLAGS.img_size, mean_type=FLAGS.mean_type, var_type=FLAGS.var_type).to(device) if FLAGS.parallel: sampler = torch.nn.DataParallel(sampler) # load model and evaluate ckpt = torch.load(os.path.join(FLAGS.logdir, '{}.pt'.format(FLAGS.ckpt_name))) # model.load_state_dict(ckpt['net_model']) # (IS, IS_std), FID, samples = evaluate(sampler, model) # print("Model : IS:%6.3f(%.3f), FID:%7.3f" % (IS, IS_std, FID)) # save_image( # torch.tensor(samples[:256]), # os.path.join(FLAGS.logdir, 'samples.png'), # nrow=16) model.load_state_dict(ckpt['ema_model']) (IS, IS_std), FID, samples = evaluate(sampler, model) if FLAGS.slimmable_unet: print('width: {}'.format(int(FLAGS.assigned_width * FLAGS.ch))) print("Model(EMA): IS:%6.3f(%.3f), FID:%7.3f" % (IS, IS_std, FID)) save_image( torch.tensor(samples[:256]), os.path.join(FLAGS.logdir, 'samples_ema.png'), nrow=16) def eval_stepaware(): # model setup with open(os.path.join(FLAGS.logdir, 'search.txt'), 'r') as f: strategy = eval(f.readlines()[0]) model = StepAwareUNet( T=FLAGS.T, ch=FLAGS.ch, ch_mult=FLAGS.ch_mult, attn=FLAGS.attn, num_res_blocks=FLAGS.num_res_blocks, dropout=FLAGS.dropout, strategy=strategy) sampler = GaussianDiffusionSampler( model, FLAGS.beta_1, FLAGS.beta_T, FLAGS.T, img_size=FLAGS.img_size, mean_type=FLAGS.mean_type, var_type=FLAGS.var_type).to(device) if FLAGS.parallel: sampler = torch.nn.DataParallel(sampler) # load model and evaluate ckpt = torch.load(os.path.join(FLAGS.logdir, '{}.pt'.format(FLAGS.ckpt_name))) # model.load_state_dict(ckpt['net_model']) # (IS, IS_std), FID, samples = evaluate(sampler, model) # print("Model : IS:%6.3f(%.3f), FID:%7.3f" % (IS, IS_std, FID)) # save_image( # torch.tensor(samples[:256]), # os.path.join(FLAGS.logdir, 'samples.png'), # nrow=16) model.load_state_dict(ckpt['ema_model']) (IS, IS_std), FID, samples = evaluate(sampler, model) print(strategy) print("Model(EMA): IS:%6.3f(%.3f), FID:%7.3f" % (IS, IS_std, FID)) save_image( torch.tensor(samples[:256]), os.path.join(FLAGS.logdir, 'samples_ema.png'), nrow=16) def eval_ensemble(): os.makedirs(os.path.join(FLAGS.logdir, 'sample')) # model setup
FLAGS = flags.FLAGS flags.DEFINE_bool('train', False, help='train from scratch') flags.DEFINE_bool('eval', False, help='load ckpt.pt and evaluate FID and IS') flags.DEFINE_bool('eval_stepaware', False, help='load ckpt.pt and evaluate FID and IS') # UNet flags.DEFINE_integer('ch', 128, help='base channel of UNet') flags.DEFINE_multi_integer('ch_mult', [1, 2, 2, 2], help='channel multiplier') flags.DEFINE_multi_integer('attn', [1], help='add attention to these levels') flags.DEFINE_integer('num_res_blocks', 2, help='# resblock in each level') flags.DEFINE_float('dropout', 0.1, help='dropout rate of resblock') # Gaussian Diffusion flags.DEFINE_float('beta_1', 1e-4, help='start beta value') flags.DEFINE_float('beta_T', 0.02, help='end beta value') flags.DEFINE_integer('T', 1000, help='total diffusion steps') flags.DEFINE_enum('mean_type', 'epsilon', ['xprev', 'xstart', 'epsilon'], help='predict variable') flags.DEFINE_enum('var_type', 'fixedlarge', ['fixedlarge', 'fixedsmall'], help='variance type') # Training flags.DEFINE_float('lr', 2e-4, help='target learning rate') flags.DEFINE_float('grad_clip', 1., help="gradient norm clipping") flags.DEFINE_integer('total_steps', 800000, help='total training steps') flags.DEFINE_integer('img_size', 32, help='image size') flags.DEFINE_integer('warmup', 5000, help='learning rate warmup') flags.DEFINE_integer('batch_size', 128, help='batch size') flags.DEFINE_integer('num_workers', 4, help='workers of Dataloader') flags.DEFINE_float('ema_decay', 0.9999, help="ema decay rate") flags.DEFINE_bool('parallel', False, help='multi gpu training') # Logging & Sampling flags.DEFINE_string('logdir', './logs/DDPM_CIFAR10_EPS', help='log directory') flags.DEFINE_integer('sample_size', 64, "sampling size of images") flags.DEFINE_integer('sample_step', 1000, help='frequency of sampling') # Evaluation flags.DEFINE_integer('save_step', 5000, help='frequency of saving checkpoints, 0 to disable during training') flags.DEFINE_integer('eval_step', 0, help='frequency of evaluating model, 0 to disable during training') flags.DEFINE_integer('num_images', 50000, help='the number of generated images for evaluation') flags.DEFINE_bool('fid_use_torch', False, help='calculate IS and FID on gpu') flags.DEFINE_string('fid_cache', './stats/cifar10.train.npz', help='FID cache') flags.DEFINE_string('ckpt_name', 'ckpt', help='ckpt name') # slimmable flags.DEFINE_bool('slimmable_unet', False, help='use slimmable unet') flags.DEFINE_bool('slimmable_g16', False, help='g16 slimmable unet') flags.DEFINE_bool('sandwich', False, help='use sandiwch training') flags.DEFINE_float('min_width', 0.25, help="min_width") flags.DEFINE_integer('num_sandwich_sampling', 3, help='the number of sandwich training samples') flags.DEFINE_multi_float('candidate_width', [0.75, 0.5], help='candidate_width') flags.DEFINE_float('assigned_width', 1.0, help="assigned_width") # ensemble flags.DEFINE_bool('eval_ensemble', False, help='eval ensemble model') flags.DEFINE_string('large_logdir', './logs/DDPM_CIFAR10_EPS', help='large model log directory') flags.DEFINE_string('small_logdir', './logs/DDPM_CIFAR10_EPS', help='small model log directory') flags.DEFINE_integer('small_ch', 64, help='channel of small model') flags.DEFINE_integer('start', 200, help='the start step of small model') flags.DEFINE_integer('end', 0, help='the end step of small model') # search flags.DEFINE_bool('search', False, help='search model') flags.DEFINE_integer('num_generation', 1000, help='the number of generation') flags.DEFINE_integer('pop_size', 10, help='the size of population') flags.DEFINE_float('fid_weight', 0.5, help="fid_weight") flags.DEFINE_float('macs_weight', 0.001, help="macs_weight") flags.DEFINE_float('mutation_prob', 0.001, help="mutation_prob") flags.DEFINE_bool('random_init', False, help='search model') # profile flags.DEFINE_bool('profile', False, help='profile model') device = torch.device('cuda:0') def ema(source, target, decay): source_dict = source.state_dict() target_dict = target.state_dict() for key in source_dict.keys(): target_dict[key].data.copy_( target_dict[key].data * decay + source_dict[key].data * (1 - decay)) def infiniteloop(dataloader): while True: for x, y in iter(dataloader): yield x def warmup_lr(step): return min(step, FLAGS.warmup) / FLAGS.warmup def evaluate(sampler, model, fid_only=False): model.eval() with torch.no_grad(): images = [] desc = "generating images" for i in trange(0, FLAGS.num_images, FLAGS.batch_size, desc=desc): batch_size = min(FLAGS.batch_size, FLAGS.num_images - i) x_T = torch.randn((batch_size, 3, FLAGS.img_size, FLAGS.img_size)) ti = time.time() batch_images = sampler(x_T.to(device)).cpu() print(str(time.time() - ti)) with open('time.txt', 'w') as f: f.write(str(time.time() - ti)) images.append((batch_images + 1) / 2) images = torch.cat(images, dim=0).numpy() model.train() if fid_only: FID = get_fid_score( images, FLAGS.fid_cache, num_images=FLAGS.num_images, use_torch=FLAGS.fid_use_torch, verbose=True) return FID else: (IS, IS_std), FID = get_inception_and_fid_score( images, FLAGS.fid_cache, num_images=FLAGS.num_images, use_torch=FLAGS.fid_use_torch, verbose=True) return (IS, IS_std), FID, images def train(): # dataset dataset = CIFAR10( root='./data', train=True, download=True, transform=transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), ])) dataloader = torch.utils.data.DataLoader( dataset, batch_size=FLAGS.batch_size, shuffle=True, num_workers=FLAGS.num_workers, drop_last=True) datalooper = infiniteloop(dataloader) # model setup if FLAGS.slimmable_unet: if FLAGS.slimmable_g16: net_model = Slimmable16UNet( T=FLAGS.T, ch=FLAGS.ch, ch_mult=FLAGS.ch_mult, attn=FLAGS.attn, num_res_blocks=FLAGS.num_res_blocks, dropout=FLAGS.dropout) else: net_model = SlimmableUNet( T=FLAGS.T, ch=FLAGS.ch, ch_mult=FLAGS.ch_mult, attn=FLAGS.attn, num_res_blocks=FLAGS.num_res_blocks, dropout=FLAGS.dropout) else: net_model = UNet( T=FLAGS.T, ch=FLAGS.ch, ch_mult=FLAGS.ch_mult, attn=FLAGS.attn, num_res_blocks=FLAGS.num_res_blocks, dropout=FLAGS.dropout) ema_model = copy.deepcopy(net_model) optim = torch.optim.Adam(net_model.parameters(), lr=FLAGS.lr) sched = torch.optim.lr_scheduler.LambdaLR(optim, lr_lambda=warmup_lr) trainer = GaussianDiffusionTrainer( net_model, FLAGS.beta_1, FLAGS.beta_T, FLAGS.T).to(device) net_sampler = GaussianDiffusionSampler( net_model, FLAGS.beta_1, FLAGS.beta_T, FLAGS.T, FLAGS.img_size, FLAGS.mean_type, FLAGS.var_type).to(device) ema_sampler = GaussianDiffusionSampler( ema_model, FLAGS.beta_1, FLAGS.beta_T, FLAGS.T, FLAGS.img_size, FLAGS.mean_type, FLAGS.var_type).to(device) if FLAGS.parallel: trainer = torch.nn.DataParallel(trainer) net_sampler = torch.nn.DataParallel(net_sampler) ema_sampler = torch.nn.DataParallel(ema_sampler) # log setup os.makedirs(os.path.join(FLAGS.logdir, 'sample'), exist_ok=True) if FLAGS.sandwich: os.makedirs(os.path.join(FLAGS.logdir, 'supernet_sample')) os.makedirs(os.path.join(FLAGS.logdir, 'minnet_sample')) x_T = torch.randn(FLAGS.sample_size, 3, FLAGS.img_size, FLAGS.img_size) x_T = x_T.to(device) grid = (make_grid(next(iter(dataloader))[0][:FLAGS.sample_size]) + 1) / 2 writer = SummaryWriter(FLAGS.logdir) writer.add_image('real_sample', grid) writer.flush() # backup all arguments with open(os.path.join(FLAGS.logdir, "flagfile.txt"), 'w') as f: f.write(FLAGS.flags_into_string()) # show model size model_size = 0 for param in net_model.parameters(): model_size += param.data.nelement() print('Model params: %.2f M' % (model_size / 1024 / 1024)) # start training with trange(FLAGS.total_steps, dynamic_ncols=True) as pbar: for step in pbar: if FLAGS.sandwich: if FLAGS.parallel: assert isinstance(trainer.module.model, SlimmableUNet) else: assert isinstance(trainer.model, SlimmableUNet) optim.zero_grad() x_0 = next(datalooper).to(device) # supernet if FLAGS.parallel: trainer.module.model.apply(lambda m: setattr(m, 'width_mult', 1.0)) else: trainer.model.apply(lambda m: setattr(m, 'width_mult', 1.0)) supernet_loss = trainer(x_0).mean() supernet_loss.backward() # minnet if FLAGS.parallel: trainer.module.model.apply(lambda m: setattr(m, 'width_mult', FLAGS.min_width)) else: trainer.model.apply(lambda m: setattr(m, 'width_mult', FLAGS.min_width)) minnet_loss = trainer(x_0).mean() minnet_loss.backward() # midnet for i in range(FLAGS.num_sandwich_sampling-2): mid_width = random.choice(FLAGS.candidate_width) if FLAGS.parallel: trainer.module.model.apply(lambda m: setattr(m, 'width_mult', mid_width)) else: trainer.model.apply(lambda m: setattr(m, 'width_mult', mid_width)) loss = trainer(x_0).mean() loss.backward() # optim torch.nn.utils.clip_grad_norm_( net_model.parameters(), FLAGS.grad_clip) optim.step() sched.step() ema(net_model, ema_model, FLAGS.ema_decay) if FLAGS.parallel: trainer.module.model.apply(lambda m: setattr(m, 'width_mult', 1.0)) else: trainer.model.apply(lambda m: setattr(m, 'width_mult', 1.0)) # log writer.add_scalar('supernet_loss', supernet_loss, step) writer.add_scalar('minnet_loss', minnet_loss, step) pbar.set_postfix(supernet_loss='%.3f' % supernet_loss, minnet_loss='%.3f' % minnet_loss) # sample if FLAGS.sample_step > 0 and step % FLAGS.sample_step == 0: net_model.eval() if FLAGS.parallel: trainer.module.model.apply(lambda m: setattr(m, 'width_mult', 1.0)) else: trainer.model.apply(lambda m: setattr(m, 'width_mult', 1.0)) with torch.no_grad(): x_0 = ema_sampler(x_T) grid = (make_grid(x_0) + 1) / 2 path = os.path.join( FLAGS.logdir, 'supernet_sample', '%d.png' % step) save_image(grid, path) writer.add_image('supernet_sample', grid, step) if FLAGS.parallel: trainer.module.model.apply(lambda m: setattr(m, 'width_mult', FLAGS.min_width)) else: trainer.model.apply(lambda m: setattr(m, 'width_mult', FLAGS.min_width)) with torch.no_grad(): x_0 = ema_sampler(x_T) grid = (make_grid(x_0) + 1) / 2 path = os.path.join( FLAGS.logdir, 'minnet_sample', '%d.png' % step) save_image(grid, path) writer.add_image('minnet_sample', grid, step) net_model.train() else: # train optim.zero_grad() x_0 = next(datalooper).to(device) loss = trainer(x_0).mean() loss.backward() torch.nn.utils.clip_grad_norm_( net_model.parameters(), FLAGS.grad_clip) optim.step() sched.step() ema(net_model, ema_model, FLAGS.ema_decay) # log writer.add_scalar('loss', loss, step) pbar.set_postfix(loss='%.3f' % loss) # sample if FLAGS.sample_step > 0 and step % FLAGS.sample_step == 0: net_model.eval() with torch.no_grad(): x_0 = ema_sampler(x_T) grid = (make_grid(x_0) + 1) / 2 path = os.path.join( FLAGS.logdir, 'sample', '%d.png' % step) save_image(grid, path) writer.add_image('sample', grid, step) net_model.train() # save if FLAGS.save_step > 0 and step % FLAGS.save_step == 0: ckpt = { 'net_model': net_model.state_dict(), 'ema_model': ema_model.state_dict(), 'sched': sched.state_dict(), 'optim': optim.state_dict(), 'step': step, 'x_T': x_T, } torch.save(ckpt, os.path.join(FLAGS.logdir, 'ckpt.pt')) torch.save(ckpt, os.path.join(FLAGS.logdir, 'ckpt_{}.pt'.format(step))) # evaluate if FLAGS.eval_step > 0 and step % FLAGS.eval_step == 0: net_IS, net_FID, _ = evaluate(net_sampler, net_model) ema_IS, ema_FID, _ = evaluate(ema_sampler, ema_model) metrics = { 'IS': net_IS[0], 'IS_std': net_IS[1], 'FID': net_FID, 'IS_EMA': ema_IS[0], 'IS_std_EMA': ema_IS[1], 'FID_EMA': ema_FID } pbar.write( "%d/%d " % (step, FLAGS.total_steps) + ", ".join('%s:%.3f' % (k, v) for k, v in metrics.items())) for name, value in metrics.items(): writer.add_scalar(name, value, step) writer.flush() with open(os.path.join(FLAGS.logdir, 'eval.txt'), 'a') as f: metrics['step'] = step f.write(json.dumps(metrics) + "\n") writer.close() def Eval(): # model setup if FLAGS.slimmable_unet: model = SlimmableUNet( T=FLAGS.T, ch=FLAGS.ch, ch_mult=FLAGS.ch_mult, attn=FLAGS.attn, num_res_blocks=FLAGS.num_res_blocks, dropout=FLAGS.dropout) model.apply(lambda m: setattr(m, 'width_mult', FLAGS.assigned_width)) else: model = UNet( T=FLAGS.T, ch=FLAGS.ch, ch_mult=FLAGS.ch_mult, attn=FLAGS.attn, num_res_blocks=FLAGS.num_res_blocks, dropout=FLAGS.dropout) sampler = GaussianDiffusionSampler( model, FLAGS.beta_1, FLAGS.beta_T, FLAGS.T, img_size=FLAGS.img_size, mean_type=FLAGS.mean_type, var_type=FLAGS.var_type).to(device) if FLAGS.parallel: sampler = torch.nn.DataParallel(sampler) # load model and evaluate ckpt = torch.load(os.path.join(FLAGS.logdir, '{}.pt'.format(FLAGS.ckpt_name))) # model.load_state_dict(ckpt['net_model']) # (IS, IS_std), FID, samples = evaluate(sampler, model) # print("Model : IS:%6.3f(%.3f), FID:%7.3f" % (IS, IS_std, FID)) # save_image( # torch.tensor(samples[:256]), # os.path.join(FLAGS.logdir, 'samples.png'), # nrow=16) model.load_state_dict(ckpt['ema_model']) (IS, IS_std), FID, samples = evaluate(sampler, model) if FLAGS.slimmable_unet: print('width: {}'.format(int(FLAGS.assigned_width * FLAGS.ch))) print("Model(EMA): IS:%6.3f(%.3f), FID:%7.3f" % (IS, IS_std, FID)) save_image( torch.tensor(samples[:256]), os.path.join(FLAGS.logdir, 'samples_ema.png'), nrow=16) def eval_stepaware(): # model setup with open(os.path.join(FLAGS.logdir, 'search.txt'), 'r') as f: strategy = eval(f.readlines()[0]) model = StepAwareUNet( T=FLAGS.T, ch=FLAGS.ch, ch_mult=FLAGS.ch_mult, attn=FLAGS.attn, num_res_blocks=FLAGS.num_res_blocks, dropout=FLAGS.dropout, strategy=strategy) sampler = GaussianDiffusionSampler( model, FLAGS.beta_1, FLAGS.beta_T, FLAGS.T, img_size=FLAGS.img_size, mean_type=FLAGS.mean_type, var_type=FLAGS.var_type).to(device) if FLAGS.parallel: sampler = torch.nn.DataParallel(sampler) # load model and evaluate ckpt = torch.load(os.path.join(FLAGS.logdir, '{}.pt'.format(FLAGS.ckpt_name))) # model.load_state_dict(ckpt['net_model']) # (IS, IS_std), FID, samples = evaluate(sampler, model) # print("Model : IS:%6.3f(%.3f), FID:%7.3f" % (IS, IS_std, FID)) # save_image( # torch.tensor(samples[:256]), # os.path.join(FLAGS.logdir, 'samples.png'), # nrow=16) model.load_state_dict(ckpt['ema_model']) (IS, IS_std), FID, samples = evaluate(sampler, model) print(strategy) print("Model(EMA): IS:%6.3f(%.3f), FID:%7.3f" % (IS, IS_std, FID)) save_image( torch.tensor(samples[:256]), os.path.join(FLAGS.logdir, 'samples_ema.png'), nrow=16) def eval_ensemble(): os.makedirs(os.path.join(FLAGS.logdir, 'sample')) # model setup
model = EnsembleUNet(
4
2023-11-29 03:51:12+00:00
12k
SEU-ProactiveSecurity-Group/MalPurifier
core/droidfeature/inverse_feature_extraction.py
[ { "identifier": "Apk2features", "path": "core/droidfeature/feature_extraction.py", "snippet": "class Apk2features(object):\n \"\"\"Get features from an APK\"\"\"\n\n def __init__(self,\n naive_data_save_dir, # 用于保存中间数据的目录\n intermediate_save_dir, # 用于保存特征 pickle 文件的...
import os import time import warnings import random import shutil import tempfile import subprocess import traceback import string import re import numpy as np import networkx as nx import torch from core.droidfeature import Apk2features from core.droidfeature import feature_gen from tools import dex_manip, xml_manip, utils from config import config, logging, ErrorHandler
7,893
INSERTION_STATIC_TEMPLATE = '''.method public static {newMethodName}()V .locals {numLocals:d} .prologue const/4 v0, 0x0 .local v0, "a":I const/4 v1, 0x1 if-ne v0, v1, :cond_0 :try_start_0 {argInitialization} {invokeType} {{{paramRegisters}}}, {apiClassName}->{methodName}({argumentTypes}){returnType} :try_end_0 .catch Ljava/lang/Exception; {{:try_start_0 .. :try_end_0}} :catch_0 {varEndCont} goto :goto_0 :catch_0 move-exception v0 :cond_0 :goto_0 return-void .end method ''' INSERTION_TEMPLATE = '''.method public static {newMethodName}()V .locals {numLocals:d} .prologue const/4 v0, 0x0 .local v0, "a":I const/4 v1, 0x1 if-ne v0, v1, :cond_0 const/4 v0, 0x0 .local v0, "{varRandName}":{apiClassName} :try_start_0 {argInitialization} {invokeType} {{{paramRegisters}}}, {apiClassName}->{methodName}({argumentTypes}){returnType} :try_end_0 .catch Ljava/lang/Exception; {{:try_start_0 .. :try_end_0}} :catch_0 .end local v0 # "{varRandName}":{apiClassName} {varEndCont} goto :goto_0 :catch_0 move-exception v0 :cond_0 :goto_0 return-void .end method ''' ENTRY_METHOD_STATEMENT = 'public onBind(Landroid/content/Intent;)Landroid/os/IBinder;' EMPTY_SERVICE_BODY = '''.class public L{fullClassName} .super Landroid/app/Service; .source "{className}.java" # direct methods .method public constructor <init>()V .locals 0 .line 8 invoke-direct {{p0}}, Landroid/app/Service;-><init>()V .line 9 return-void .end method .method {entryMethodStatement} .locals 2 .param p1, "intent" # Landroid/content/Intent; .line 14 new-instance v0, Ljava/lang/UnsupportedOperationException; const-string v1, "Not yet implemented" invoke-direct {{v0, v1}}, Ljava/lang/UnsupportedOperationException;-><init>(Ljava/lang/String;)V throw v0 .end method ''' PROVIDER_TEMPLATE = '''.class public {ProviderCLS} .super Landroid/content/ContentProvider; .source "{CLSName}.java" # direct methods .method public constructor <init>()V .locals 1 .prologue .line 3 invoke-direct {{p0}}, Ljava/lang/Object;-><init>()V return-void .end method ''' class InverseDroidFeature(object): vocab, vocab_info, vocab_type = None, None, None def __init__(self, seed=0): random.seed(seed) meta_data_saving_dir = config.get('dataset', 'intermediate') naive_data_saving_dir = config.get('metadata', 'naive_data_pool')
random.seed(0) logger = logging.getLogger('core.droidfeature.inverse_feature_extraction') logger.addHandler(ErrorHandler) TMP_DIR = '/tmp' OP_INSERTION = '+' OP_REMOVAL = '-' MANIFEST = "AndroidManifest.xml" REFLECTION_TEMPLATE = '''.class public Landroid/content/res/MethodReflection; .super Ljava/lang/Object; .source "MethodReflection.java" # direct methods .method public constructor <init>()V .locals 1 .prologue .line 3 invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method ''' DEFAULT_SMALI_DIR = 'android/content/res/' # the path corresponds to the reflection class set above INSERTION_STATIC_TEMPLATE = '''.method public static {newMethodName}()V .locals {numLocals:d} .prologue const/4 v0, 0x0 .local v0, "a":I const/4 v1, 0x1 if-ne v0, v1, :cond_0 :try_start_0 {argInitialization} {invokeType} {{{paramRegisters}}}, {apiClassName}->{methodName}({argumentTypes}){returnType} :try_end_0 .catch Ljava/lang/Exception; {{:try_start_0 .. :try_end_0}} :catch_0 {varEndCont} goto :goto_0 :catch_0 move-exception v0 :cond_0 :goto_0 return-void .end method ''' INSERTION_TEMPLATE = '''.method public static {newMethodName}()V .locals {numLocals:d} .prologue const/4 v0, 0x0 .local v0, "a":I const/4 v1, 0x1 if-ne v0, v1, :cond_0 const/4 v0, 0x0 .local v0, "{varRandName}":{apiClassName} :try_start_0 {argInitialization} {invokeType} {{{paramRegisters}}}, {apiClassName}->{methodName}({argumentTypes}){returnType} :try_end_0 .catch Ljava/lang/Exception; {{:try_start_0 .. :try_end_0}} :catch_0 .end local v0 # "{varRandName}":{apiClassName} {varEndCont} goto :goto_0 :catch_0 move-exception v0 :cond_0 :goto_0 return-void .end method ''' ENTRY_METHOD_STATEMENT = 'public onBind(Landroid/content/Intent;)Landroid/os/IBinder;' EMPTY_SERVICE_BODY = '''.class public L{fullClassName} .super Landroid/app/Service; .source "{className}.java" # direct methods .method public constructor <init>()V .locals 0 .line 8 invoke-direct {{p0}}, Landroid/app/Service;-><init>()V .line 9 return-void .end method .method {entryMethodStatement} .locals 2 .param p1, "intent" # Landroid/content/Intent; .line 14 new-instance v0, Ljava/lang/UnsupportedOperationException; const-string v1, "Not yet implemented" invoke-direct {{v0, v1}}, Ljava/lang/UnsupportedOperationException;-><init>(Ljava/lang/String;)V throw v0 .end method ''' PROVIDER_TEMPLATE = '''.class public {ProviderCLS} .super Landroid/content/ContentProvider; .source "{CLSName}.java" # direct methods .method public constructor <init>()V .locals 1 .prologue .line 3 invoke-direct {{p0}}, Ljava/lang/Object;-><init>()V return-void .end method ''' class InverseDroidFeature(object): vocab, vocab_info, vocab_type = None, None, None def __init__(self, seed=0): random.seed(seed) meta_data_saving_dir = config.get('dataset', 'intermediate') naive_data_saving_dir = config.get('metadata', 'naive_data_pool')
self.feature_extractor = Apk2features(naive_data_saving_dir, meta_data_saving_dir)
0
2023-11-27 02:00:23+00:00
12k
IDEA-XL/InstructMol
llava/model/language_model/mpt/modeling_mpt.py
[ { "identifier": "attn_bias_shape", "path": "llava/model/language_model/mpt/attention.py", "snippet": "def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id):\n if attn_impl == 'flash':\n return None\n elif attn_impl in ['torch', 'triton']:\n if al...
import math import warnings import torch import torch.nn as nn import torch.nn.functional as F from typing import List, Optional, Tuple, Union from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast from .attention import attn_bias_shape, build_attn_bias from .blocks import MPTBlock from .custom_embedding import SharedEmbedding from .norm import NORM_CLASS_REGISTRY from .configuration_mpt import MPTConfig from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm from .meta_init_context import init_empty_weights from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_ from .flash_attn_triton import flash_attn_func
9,446
assert isinstance(attn_bias, torch.Tensor) attn_bias = self._apply_sequence_id(attn_bias, sequence_id) if attention_mask is not None: s_k = attention_mask.shape[-1] if attn_bias is None: attn_bias = torch.zeros((1, 1, 1, s_k), device=device, dtype=dtype) else: _s_k = max(0, attn_bias.size(-1) - s_k) attn_bias = attn_bias[:, :, :, _s_k:] if prefix_mask is not None and attention_mask.shape != prefix_mask.shape: raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.') min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val) return (attn_bias, None) def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor): (s_k, s_q) = attn_bias.shape[-2:] if s_k != self.config.max_seq_len or s_q != self.config.max_seq_len: raise ValueError('attn_bias does not match the expected shape. ' + f'The last two dimensions should both be {self.config.max_length} ' + f'but are {s_k} and {s_q}.') seq_len = prefix_mask.shape[-1] if seq_len > self.config.max_seq_len: raise ValueError(f'prefix_mask sequence length cannot exceed max_seq_len={self.config.max_seq_len}') attn_bias = attn_bias[..., :seq_len, :seq_len] causal = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool, device=prefix_mask.device)).view(1, 1, seq_len, seq_len) prefix = prefix_mask.view(-1, 1, 1, seq_len) cannot_attend = ~torch.logical_or(causal, prefix.bool()) min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(cannot_attend, min_val) return attn_bias def _apply_sequence_id(self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor): seq_len = sequence_id.shape[-1] if seq_len > self.config.max_seq_len: raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}') attn_bias = attn_bias[..., :seq_len, :seq_len] cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1) min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(cannot_attend, min_val) return attn_bias def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.Tensor]=None): return_dict = return_dict if return_dict is not None else self.config.return_dict use_cache = use_cache if use_cache is not None else self.config.use_cache if attention_mask is not None: attention_mask = attention_mask.bool() if prefix_mask is not None: prefix_mask = prefix_mask.bool() if not return_dict: raise NotImplementedError('return_dict False is not implemented yet for MPT') if output_attentions: if self.attn_impl != 'torch': raise NotImplementedError('output_attentions is not implemented for MPT when using attn_impl `flash` or `triton`.') if attention_mask is not None and attention_mask[:, 0].sum() != attention_mask.shape[0] and self.training: raise NotImplementedError('MPT does not support training with left padding.') if self.prefix_lm and prefix_mask is None: raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.') if self.training: if self.attn_uses_sequence_id and sequence_id is None: raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.') elif self.attn_uses_sequence_id is False and sequence_id is not None: warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.') if input_ids is not None: S = input_ids.size(1) assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}' tok_emb = self.wte(input_ids) else: assert inputs_embeds is not None assert self.alibi, 'inputs_embeds is not implemented for MPT unless for alibi.' S = inputs_embeds.size(1) tok_emb = inputs_embeds if self.alibi: x = tok_emb else: past_position = 0 if past_key_values is not None: if len(past_key_values) != self.config.n_layers: raise ValueError(f'past_key_values must provide a past_key_value for each attention ' + f'layer in the network (len(past_key_values)={len(past_key_values)!r}; self.config.n_layers={self.config.n_layers!r}).') past_position = past_key_values[0][0].size(1) if self.attn_impl == 'torch': past_position = past_key_values[0][0].size(3) if S + past_position > self.config.max_seq_len: raise ValueError(f'Cannot forward input with past sequence length {past_position} and current sequence length {S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.') pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_ids.device).unsqueeze(0) if attention_mask is not None: pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0) pos_emb = self.wpe(pos) x = tok_emb + pos_emb if self.embedding_fraction == 1: x = self.emb_drop(x) else: x_shrunk = x * self.embedding_fraction + x.detach() * (1 - self.embedding_fraction) assert isinstance(self.emb_drop, nn.Module) x = self.emb_drop(x_shrunk) (attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id) if use_cache and past_key_values is None: past_key_values = [() for _ in range(self.config.n_layers)] all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None for (b_idx, block) in enumerate(self.blocks): if output_hidden_states: assert all_hidden_states is not None all_hidden_states = all_hidden_states + (x,) past_key_value = past_key_values[b_idx] if past_key_values is not None else None if self.gradient_checkpointing and self.training: (x, attn_weights, past_key_value) = torch.utils.checkpoint.checkpoint(block, x, past_key_value, attn_bias, attention_mask, self.is_causal) else: (x, attn_weights, past_key_value) = block(x, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=self.is_causal) if past_key_values is not None: past_key_values[b_idx] = past_key_value if output_attentions: assert all_self_attns is not None all_self_attns = all_self_attns + (attn_weights,) x = self.norm_f(x) if output_hidden_states: assert all_hidden_states is not None all_hidden_states = all_hidden_states + (x,) return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=past_key_values, hidden_states=all_hidden_states, attentions=all_self_attns) def param_init_fn(self, module): init_fn_name = self.config.init_config['name']
"""A simple, flexible implementation of a GPT model. Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py """ try: except: pass Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast] class MPTPreTrainedModel(PreTrainedModel): config_class = MPTConfig base_model_prefix = 'model' _no_split_modules = ['MPTBlock'] class MPTModel(MPTPreTrainedModel): def __init__(self, config: MPTConfig): config._validate_config() super().__init__(config) self.attn_impl = config.attn_config['attn_impl'] self.prefix_lm = config.attn_config['prefix_lm'] self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id'] self.alibi = config.attn_config['alibi'] self.alibi_bias_max = config.attn_config['alibi_bias_max'] if config.init_device == 'mixed': if dist.get_local_rank() == 0: config.init_device = 'cpu' else: config.init_device = 'meta' if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys(): norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys()) raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).') norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()] self.embedding_fraction = config.embedding_fraction self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device) if not self.alibi: self.wpe = torch.nn.Embedding(config.max_seq_len, config.d_model, device=config.init_device) self.emb_drop = nn.Dropout(config.emb_pdrop) self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)]) self.norm_f = norm_class(config.d_model, device=config.init_device) if config.init_device != 'meta': print(f'You are using config.init_device={config.init_device!r}, but you can also use config.init_device="meta" with Composer + FSDP for fast initialization.') self.apply(self.param_init_fn) self.is_causal = not self.prefix_lm self._attn_bias_initialized = False self.attn_bias = None self.attn_bias_shape = attn_bias_shape(self.attn_impl, config.n_heads, config.max_seq_len, self.alibi, prefix_lm=self.prefix_lm, causal=self.is_causal, use_sequence_id=self.attn_uses_sequence_id) if config.no_bias: for module in self.modules(): if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter): if config.verbose: warnings.warn(f'Removing bias ({module.bias}) from {module}.') module.register_parameter('bias', None) if config.verbose and config.verbose > 2: print(self) if 'verbose' not in self.config.init_config: self.config.init_config['verbose'] = self.config.verbose if self.config.init_config['verbose'] > 1: init_fn_name = self.config.init_config['name'] warnings.warn(f'Using {init_fn_name} initialization.') self.gradient_checkpointing = False def get_input_embeddings(self): return self.wte def set_input_embeddings(self, value): self.wte = value @torch.no_grad() def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None): if not self._attn_bias_initialized: if self.attn_bias_shape: self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype) self.attn_bias = build_attn_bias(self.attn_impl, self.attn_bias, self.config.n_heads, self.config.max_seq_len, causal=self.is_causal, alibi=self.alibi, alibi_bias_max=self.alibi_bias_max) self._attn_bias_initialized = True if self.attn_impl == 'flash': return (self.attn_bias, attention_mask) if self.attn_bias is not None: self.attn_bias = self.attn_bias.to(dtype=dtype, device=device) attn_bias = self.attn_bias if self.prefix_lm: assert isinstance(attn_bias, torch.Tensor) assert isinstance(prefix_mask, torch.Tensor) attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask) if self.attn_uses_sequence_id and sequence_id is not None: assert isinstance(attn_bias, torch.Tensor) attn_bias = self._apply_sequence_id(attn_bias, sequence_id) if attention_mask is not None: s_k = attention_mask.shape[-1] if attn_bias is None: attn_bias = torch.zeros((1, 1, 1, s_k), device=device, dtype=dtype) else: _s_k = max(0, attn_bias.size(-1) - s_k) attn_bias = attn_bias[:, :, :, _s_k:] if prefix_mask is not None and attention_mask.shape != prefix_mask.shape: raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.') min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val) return (attn_bias, None) def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor): (s_k, s_q) = attn_bias.shape[-2:] if s_k != self.config.max_seq_len or s_q != self.config.max_seq_len: raise ValueError('attn_bias does not match the expected shape. ' + f'The last two dimensions should both be {self.config.max_length} ' + f'but are {s_k} and {s_q}.') seq_len = prefix_mask.shape[-1] if seq_len > self.config.max_seq_len: raise ValueError(f'prefix_mask sequence length cannot exceed max_seq_len={self.config.max_seq_len}') attn_bias = attn_bias[..., :seq_len, :seq_len] causal = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool, device=prefix_mask.device)).view(1, 1, seq_len, seq_len) prefix = prefix_mask.view(-1, 1, 1, seq_len) cannot_attend = ~torch.logical_or(causal, prefix.bool()) min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(cannot_attend, min_val) return attn_bias def _apply_sequence_id(self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor): seq_len = sequence_id.shape[-1] if seq_len > self.config.max_seq_len: raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}') attn_bias = attn_bias[..., :seq_len, :seq_len] cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1) min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(cannot_attend, min_val) return attn_bias def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.Tensor]=None): return_dict = return_dict if return_dict is not None else self.config.return_dict use_cache = use_cache if use_cache is not None else self.config.use_cache if attention_mask is not None: attention_mask = attention_mask.bool() if prefix_mask is not None: prefix_mask = prefix_mask.bool() if not return_dict: raise NotImplementedError('return_dict False is not implemented yet for MPT') if output_attentions: if self.attn_impl != 'torch': raise NotImplementedError('output_attentions is not implemented for MPT when using attn_impl `flash` or `triton`.') if attention_mask is not None and attention_mask[:, 0].sum() != attention_mask.shape[0] and self.training: raise NotImplementedError('MPT does not support training with left padding.') if self.prefix_lm and prefix_mask is None: raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.') if self.training: if self.attn_uses_sequence_id and sequence_id is None: raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.') elif self.attn_uses_sequence_id is False and sequence_id is not None: warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.') if input_ids is not None: S = input_ids.size(1) assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}' tok_emb = self.wte(input_ids) else: assert inputs_embeds is not None assert self.alibi, 'inputs_embeds is not implemented for MPT unless for alibi.' S = inputs_embeds.size(1) tok_emb = inputs_embeds if self.alibi: x = tok_emb else: past_position = 0 if past_key_values is not None: if len(past_key_values) != self.config.n_layers: raise ValueError(f'past_key_values must provide a past_key_value for each attention ' + f'layer in the network (len(past_key_values)={len(past_key_values)!r}; self.config.n_layers={self.config.n_layers!r}).') past_position = past_key_values[0][0].size(1) if self.attn_impl == 'torch': past_position = past_key_values[0][0].size(3) if S + past_position > self.config.max_seq_len: raise ValueError(f'Cannot forward input with past sequence length {past_position} and current sequence length {S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.') pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_ids.device).unsqueeze(0) if attention_mask is not None: pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0) pos_emb = self.wpe(pos) x = tok_emb + pos_emb if self.embedding_fraction == 1: x = self.emb_drop(x) else: x_shrunk = x * self.embedding_fraction + x.detach() * (1 - self.embedding_fraction) assert isinstance(self.emb_drop, nn.Module) x = self.emb_drop(x_shrunk) (attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id) if use_cache and past_key_values is None: past_key_values = [() for _ in range(self.config.n_layers)] all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None for (b_idx, block) in enumerate(self.blocks): if output_hidden_states: assert all_hidden_states is not None all_hidden_states = all_hidden_states + (x,) past_key_value = past_key_values[b_idx] if past_key_values is not None else None if self.gradient_checkpointing and self.training: (x, attn_weights, past_key_value) = torch.utils.checkpoint.checkpoint(block, x, past_key_value, attn_bias, attention_mask, self.is_causal) else: (x, attn_weights, past_key_value) = block(x, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=self.is_causal) if past_key_values is not None: past_key_values[b_idx] = past_key_value if output_attentions: assert all_self_attns is not None all_self_attns = all_self_attns + (attn_weights,) x = self.norm_f(x) if output_hidden_states: assert all_hidden_states is not None all_hidden_states = all_hidden_states + (x,) return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=past_key_values, hidden_states=all_hidden_states, attentions=all_self_attns) def param_init_fn(self, module): init_fn_name = self.config.init_config['name']
MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
11
2023-11-27 09:55:39+00:00
12k
iann838/pulsefire
tests/test_ratelimiters.py
[ { "identifier": "RiotAPIClient", "path": "pulsefire/clients.py", "snippet": "class RiotAPIClient(BaseClient):\n \"\"\"Riot API Client.\n\n | Resources | Support |\n | -------------------- | -------------------------- |\n | League of Legends | ✅ ...
import asyncio import os import subprocess import time import aiohttp from pulsefire.clients import RiotAPIClient from pulsefire.functools import async_to_sync from pulsefire.middlewares import ( json_response_middleware, http_error_middleware, rate_limiter_middleware ) from pulsefire.ratelimiters import RiotAPIRateLimiter from pulsefire.taskgroups import TaskGroup
8,619
@async_to_sync() async def test_riot_api_rate_limiter_local(): async with RiotAPIClient( default_headers={"X-Riot-Token": os.environ["RIOT_API_KEY"]}, middlewares=[ json_response_middleware(), http_error_middleware(),
@async_to_sync() async def test_riot_api_rate_limiter_local(): async with RiotAPIClient( default_headers={"X-Riot-Token": os.environ["RIOT_API_KEY"]}, middlewares=[ json_response_middleware(), http_error_middleware(),
rate_limiter_middleware(RiotAPIRateLimiter()),
4
2023-11-27 13:37:24+00:00
12k
ubc-vision/nf-soft-mining
examples/train_ngp_nerf_occ.py
[ { "identifier": "MIPNERF360_UNBOUNDED_SCENES", "path": "examples/utils.py", "snippet": "MIPNERF360_UNBOUNDED_SCENES = [\n \"garden\",\n \"bicycle\",\n \"bonsai\",\n \"counter\",\n \"kitchen\",\n \"room\",\n \"stump\",\n]" }, { "identifier": "NERF_SYNTHETIC_SCENES", "path...
import argparse import math import pathlib import time import imageio import numpy as np import torch import torch.nn.functional as F import tqdm from lpips import LPIPS from radiance_fields.ngp import NGPRadianceField from examples.utils import ( MIPNERF360_UNBOUNDED_SCENES, NERF_SYNTHETIC_SCENES, render_image_with_occgrid, render_image_with_occgrid_test, set_random_seed, ) from nerfacc.estimators.occ_grid import OccGridEstimator from datasets.nerf_360_v2 import SubjectLoader from datasets.nerf_synthetic import SubjectLoader
7,547
""" Copyright (c) 2022 Ruilong Li, UC Berkeley. """ parser = argparse.ArgumentParser() parser.add_argument( "--data_root", type=str, # default=str(pathlib.Path.cwd() / "data/360_v2"), default=str(pathlib.Path.cwd() / "data/nerf_synthetic"), help="the root dir of the dataset", ) parser.add_argument( "--train_split", type=str, default="train", choices=["train", "trainval"], help="which train split to use", ) parser.add_argument( "--scene", type=str, default="lego", choices=NERF_SYNTHETIC_SCENES + MIPNERF360_UNBOUNDED_SCENES, help="which scene to use", ) args = parser.parse_args() device = "cuda:0"
""" Copyright (c) 2022 Ruilong Li, UC Berkeley. """ parser = argparse.ArgumentParser() parser.add_argument( "--data_root", type=str, # default=str(pathlib.Path.cwd() / "data/360_v2"), default=str(pathlib.Path.cwd() / "data/nerf_synthetic"), help="the root dir of the dataset", ) parser.add_argument( "--train_split", type=str, default="train", choices=["train", "trainval"], help="which train split to use", ) parser.add_argument( "--scene", type=str, default="lego", choices=NERF_SYNTHETIC_SCENES + MIPNERF360_UNBOUNDED_SCENES, help="which scene to use", ) args = parser.parse_args() device = "cuda:0"
set_random_seed(42)
4
2023-11-27 22:12:55+00:00
12k
facebookresearch/SOC-matching
SOC_matching/experiment_settings/settings.py
[ { "identifier": "optimal_control_LQ", "path": "SOC_matching/utils.py", "snippet": "def optimal_control_LQ(sigma, A, P, Q, t):\n R_inverse = torch.matmul(sigma, torch.transpose(sigma, 0, 1))\n Ft = solution_Ricatti(R_inverse, A, P, Q, t)\n ut = -2 * torch.einsum(\"ij,bjk->bik\", torch.transpose(...
import torch from SOC_matching.utils import ( optimal_control_LQ, exponential_t_A, restricted_SOC, ) from SOC_matching.models import ( LinearControl, ConstantControlLinear, LowDimControl, RestrictedControl, ) from SOC_matching.experiment_settings.OU_quadratic import OU_Quadratic from SOC_matching.experiment_settings.OU_linear import OU_Linear from SOC_matching.experiment_settings.double_well import DoubleWell from SOC_matching.experiment_settings.molecular_dynamics import MolecularDynamics
7,255
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory. def ground_truth_control(cfg, ts, x0, **kwargs): if ( cfg.method.setting == "OU_quadratic_easy" or cfg.method.setting == "OU_quadratic_hard" ): R_inverse = torch.matmul( kwargs["sigma"], torch.transpose(kwargs["sigma"], 0, 1) ) R = torch.inverse(R_inverse) ut = optimal_control_LQ( kwargs["sigma"], kwargs["A"], kwargs["P"], kwargs["Q"], ts ) ut = LinearControl(ut, cfg.method.T) optimal_sde = OU_Quadratic( u=ut, lmbd=cfg.method.lmbd, A=kwargs["A"], P=kwargs["P"], Q=kwargs["Q"], sigma=kwargs["sigma"], T=cfg.method.T, ) return optimal_sde elif cfg.method.setting == "OU_linear": exp_matrix = exponential_t_A( cfg.method.T - ts, torch.transpose(kwargs["A"], 0, 1) ) ut = -torch.einsum( "aij,j->ai", torch.einsum( "ij,ajk->aik", torch.transpose(kwargs["sigma"], 0, 1), exp_matrix ), kwargs["omega"], ) ut = ConstantControlLinear(ut, cfg.method.T)
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory. def ground_truth_control(cfg, ts, x0, **kwargs): if ( cfg.method.setting == "OU_quadratic_easy" or cfg.method.setting == "OU_quadratic_hard" ): R_inverse = torch.matmul( kwargs["sigma"], torch.transpose(kwargs["sigma"], 0, 1) ) R = torch.inverse(R_inverse) ut = optimal_control_LQ( kwargs["sigma"], kwargs["A"], kwargs["P"], kwargs["Q"], ts ) ut = LinearControl(ut, cfg.method.T) optimal_sde = OU_Quadratic( u=ut, lmbd=cfg.method.lmbd, A=kwargs["A"], P=kwargs["P"], Q=kwargs["Q"], sigma=kwargs["sigma"], T=cfg.method.T, ) return optimal_sde elif cfg.method.setting == "OU_linear": exp_matrix = exponential_t_A( cfg.method.T - ts, torch.transpose(kwargs["A"], 0, 1) ) ut = -torch.einsum( "aij,j->ai", torch.einsum( "ij,ajk->aik", torch.transpose(kwargs["sigma"], 0, 1), exp_matrix ), kwargs["omega"], ) ut = ConstantControlLinear(ut, cfg.method.T)
optimal_sde = OU_Linear(
8
2023-12-04 20:26:18+00:00
12k
yiwenlu66/learning-qp
experiments/tank/visualize_feasible_sets.py
[ { "identifier": "sys_param", "path": "src/envs/env_creators.py", "snippet": "def tank_initial_generator(size, device, rng):\ndef tank_ref_generator(size, device, rng):\ndef tank_randomizer(size, device, rng):\n B = torch.tensor(sys_param[\"tank\"][\"B\"], device=device, dtype=torch.float).unsqueeze(0...
import numpy as np import sys import os import torch from src.envs.env_creators import sys_param, env_creators from src.envs.mpc_baseline_parameters import get_mpc_baseline_parameters from src.modules.qp_unrolled_network import QPUnrolledNetwork from matplotlib import pyplot as plt from icecream import ic from src.utils.torch_utils import bmv from src.utils.visualization import plot_multiple_2d_polytopes_with_contour from src.utils.geometry import high_dim_to_2D_sampling, partial_minimization_2D
8,744
# %% Specify test case # Case where MPC is better x0 = np.array([10., 10., 10., 10.]) x_ref = np.array([19, 19, 2.4, 2.4]) # # Case where MPC fails # x0 = np.array([ 5.4963946, 10.947876, 1.034516, 18.08066 ]) # x_ref = np.array([7.522859, 8.169776, 1.1107684, 1. ]) # Controlling process noise and parametric uncertainty noise_level = 0 parametric_uncertainty = False parameter_randomization_seed = 2 # %% Set up test bench file_path = os.path.dirname(__file__) sys.path.append(os.path.join(file_path, "../..")) # Utilities def make_obs(x, x_ref, running_mean, running_std, normalize): raw_obs = torch.tensor(np.concatenate([x, x_ref]), device=device, dtype=torch.float) if not normalize: return raw_obs.unsqueeze(0) else: return ((raw_obs - running_mean) / running_std).unsqueeze(0) def get_state_dict(checkpoint_path): checkpoint = torch.load(checkpoint_path) model = checkpoint["model"] prefix = "a2c_network.policy_net." policy_net_state_dict = {k.lstrip(prefix): v for (k, v) in model.items() if k.startswith(prefix)} if "running_mean_std.running_mean" in model: running_mean = model["running_mean_std.running_mean"].to(dtype=torch.float) running_std = model["running_mean_std.running_var"].sqrt().to(dtype=torch.float) else: running_mean = torch.tensor([0.]) running_std = torch.tensor([1.]) return policy_net_state_dict, running_mean, running_std def rescale_action(action, low=-1., high=8.): action = action.clamp(-1., 1.) return low + (high - low) * (action + 1) / 2 t = lambda arr: torch.tensor(arr, device=device, dtype=torch.float).unsqueeze(0) a = lambda t: t.detach().cpu().numpy() # Constants and options n_sys = 4 m_sys = 2 input_size = 8 # 4 for x, 4 for x_ref n = 2 m = 64 qp_iter = 10 device = "cuda:0" # MPC module
# %% Specify test case # Case where MPC is better x0 = np.array([10., 10., 10., 10.]) x_ref = np.array([19, 19, 2.4, 2.4]) # # Case where MPC fails # x0 = np.array([ 5.4963946, 10.947876, 1.034516, 18.08066 ]) # x_ref = np.array([7.522859, 8.169776, 1.1107684, 1. ]) # Controlling process noise and parametric uncertainty noise_level = 0 parametric_uncertainty = False parameter_randomization_seed = 2 # %% Set up test bench file_path = os.path.dirname(__file__) sys.path.append(os.path.join(file_path, "../..")) # Utilities def make_obs(x, x_ref, running_mean, running_std, normalize): raw_obs = torch.tensor(np.concatenate([x, x_ref]), device=device, dtype=torch.float) if not normalize: return raw_obs.unsqueeze(0) else: return ((raw_obs - running_mean) / running_std).unsqueeze(0) def get_state_dict(checkpoint_path): checkpoint = torch.load(checkpoint_path) model = checkpoint["model"] prefix = "a2c_network.policy_net." policy_net_state_dict = {k.lstrip(prefix): v for (k, v) in model.items() if k.startswith(prefix)} if "running_mean_std.running_mean" in model: running_mean = model["running_mean_std.running_mean"].to(dtype=torch.float) running_std = model["running_mean_std.running_var"].sqrt().to(dtype=torch.float) else: running_mean = torch.tensor([0.]) running_std = torch.tensor([1.]) return policy_net_state_dict, running_mean, running_std def rescale_action(action, low=-1., high=8.): action = action.clamp(-1., 1.) return low + (high - low) * (action + 1) / 2 t = lambda arr: torch.tensor(arr, device=device, dtype=torch.float).unsqueeze(0) a = lambda t: t.detach().cpu().numpy() # Constants and options n_sys = 4 m_sys = 2 input_size = 8 # 4 for x, 4 for x_ref n = 2 m = 64 qp_iter = 10 device = "cuda:0" # MPC module
mpc_baseline = get_mpc_baseline_parameters("tank", 1)
1
2023-11-28 05:56:22+00:00
12k
armed-gpt/gpt-blazing
gpt_blazing_experiment/model/debug_baichuan2.py
[ { "identifier": "Role", "path": "gpt_blazing/model/interface.py", "snippet": "class Role(Enum):\n SYSTEM = 'system'\n USER = 'user'\n ASSISTANT = 'assistant'\n\n @classmethod\n def from_string(cls, text: str):\n return _TEXT_TO_ROLE[text]" }, { "identifier": "Baichuan2Model...
from typing import Tuple, Sequence, Optional from datetime import datetime from gpt_blazing.model.interface import Role from gpt_blazing.model.baichuan2.model import ( Baichuan2Model, Baichuan2ModelConfig, quantize_int8, quantize_fp8, EmptyInitOnDevice, load_model, model_prefill_2048, model_prefill_4096, compile_model_prefill, model_decode_one_token_2048, model_decode_one_token_4096, compile_model_decode_one_token, model_dispatch, model_get_cache, model_set_cache, ) from gpt_blazing.model.baichuan2.utility import convert_hf_model_to_model from gpt_blazing.model.baichuan2.tokenizer import Baichuan2Tokenizer from gpt_blazing.model.baichuan2.inference import ( Baichuan2ModelInferenceConfig, Baichuan2ModelInference, ) from transformers import AutoModelForCausalLM from transformers import AutoTokenizer from transformers.generation.utils import GenerationConfig from transformers import AutoTokenizer from transformers.generation.utils import GenerationConfig from transformers import AutoTokenizer from transformers.generation.utils import GenerationConfig import torch import torch.nn.functional as F import sentencepiece as spm import iolite as io import os import torch._dynamo.config import torch._inductor.config import random import torch._dynamo.config import torch._inductor.config import os import random import os
7,711
def get_top_p_sorted_indices(logits: torch.Tensor, top_p: float = 0.9): sorted_logits, sorted_indices = torch.sort(logits, descending=True) cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1) mask = cumulative_probs <= top_p mask[..., 1:] = mask[..., :-1].clone() mask[..., 0] = True sorted_indices[~mask] = -1 return sorted_indices def compare_logits(file0: str, file1: str): ''' # 1. fib gpt_blazing_experiment/model/debug_baichuan2.py:compare_logits \ --file0="$GPT_BLAZING_DATA/model/baichuan2/logits.pt" \ --file1="$GPT_BLAZING_DATA/model/baichuan2/hf_logits.pt" # 0.9942 fib gpt_blazing_experiment/model/debug_baichuan2.py:compare_logits \ --file0="$GPT_BLAZING_DATA/model/baichuan2/logits.pt" \ --file1="$GPT_BLAZING_DATA/model/baichuan2/fp8_logits.pt" # 0.9942 fib gpt_blazing_experiment/model/debug_baichuan2.py:compare_logits \ --file0="$GPT_BLAZING_DATA/model/baichuan2/logits.pt" \ --file1="$GPT_BLAZING_DATA/model/baichuan2/int8_logits.pt" # 0.9945 fib gpt_blazing_experiment/model/debug_baichuan2.py:compare_logits \ --file0="$GPT_BLAZING_DATA/model/baichuan2/logits.pt" \ --file1="$GPT_BLAZING_DATA/model/baichuan2/int8_hf_logits.pt" # 0.9939 fib gpt_blazing_experiment/model/debug_baichuan2.py:compare_logits \ --file0="$GPT_BLAZING_DATA/model/baichuan2/logits.pt" \ --file1="$GPT_BLAZING_DATA/model/baichuan2/compiled_logits.pt" # 0.9939 fib gpt_blazing_experiment/model/debug_baichuan2.py:compare_logits \ --file0="$GPT_BLAZING_DATA/model/baichuan2/logits.pt" \ --file1="$GPT_BLAZING_DATA/model/baichuan2/compiled_int8_logits.pt" # 0.9938 fib gpt_blazing_experiment/model/debug_baichuan2.py:compare_logits \ --file0="$GPT_BLAZING_DATA/model/baichuan2/compiled_int8_logits.pt" \ --file1="$GPT_BLAZING_DATA/model/baichuan2/int8_hf_logits.pt" ''' logits0 = torch.load(file0, map_location='cuda:0') logits1 = torch.load(file1, map_location='cuda:0') tpsi0 = get_top_p_sorted_indices(logits0) tpsi1 = get_top_p_sorted_indices(logits1) rank = tpsi0 == tpsi1 r = rank.sum() / rank.numel() print(r) def demo_func(x: torch.Tensor, y: torch.Tensor, begin: int, end: int): return x[:, begin:end] + y[:, begin:end] def debug_compile(): func = torch.compile(demo_func, mode="reduce-overhead", fullgraph=True) x = torch.rand((1, 20, 128)) y = torch.rand((1, 20, 128)) print(func(x, y, 0, 10)) # triggers Recompiling! print(func(x, y, 0, 15)) print(func(x, y, 1, 2)) def timed(fn): # type: ignore start = torch.cuda.Event(enable_timing=True) end = torch.cuda.Event(enable_timing=True) start.record() # type: ignore result = fn() end.record() # type: ignore torch.cuda.synchronize() return result, start.elapsed_time(end) / 1000 def debug_greedy_decoding_performance(): print('Loading...') model = load_model( model_pt=str( io.file("$GPT_BLAZING_DATA/model/baichuan2-13b-chat/int8.pt", expandvars=True) ), int8=True, config=Baichuan2ModelConfig(debug=False), ) model.to('cuda:0') print('Compiling...') torch._inductor.config.coordinate_descent_tuning = True torch._inductor.config.triton.unique_kernel_names = True torch._inductor.config.fx_graph_cache = True input_ids = generate_debug_input_ids() input_ids = input_ids.to('cuda:0') prefill_2048 = compile_model_prefill(model_prefill_2048) prefill_4096 = compile_model_prefill(model_prefill_4096) for offset in [0, 2048]: for _ in range(3): input_pos = torch.arange( offset, offset + int(input_ids.shape[1]), device=input_ids.device, dtype=torch.int, ) print( 'prefill compiling time:', timed(
BAICHUAN2_13B_MODEL_FOLDER = str( io.folder( '$GPT_BLAZING_DATA/base/Baichuan2-13B-Chat', expandvars=True, ) ) def load_hf_model( model_folder: str = BAICHUAN2_13B_MODEL_FOLDER, device_map: Optional[str] = None, ): return AutoModelForCausalLM.from_pretrained( model_folder, torch_dtype=torch.bfloat16, trust_remote_code=True, device_map=device_map, ) def eval_hf_model(): with EmptyInitOnDevice(): model = load_hf_model() model.generation_config = GenerationConfig.from_pretrained(BAICHUAN2_13B_MODEL_FOLDER) tokenizer = AutoTokenizer.from_pretrained( BAICHUAN2_13B_MODEL_FOLDER, use_fast=False, trust_remote_code=True, ) model.generation_config.do_sample = False # pip install bitsandbytes scipy model = model.quantize(8).to('cuda:0') print('Warmup') with torch.inference_mode(): print(model.chat(tokenizer, [{"role": "user", "content": '你好'}])) print('Running...') decode_dt_begin = datetime.now() with torch.inference_mode(): response = model.chat( tokenizer, [{ "role": "user", "content": "帮我写一篇与A股主题相关的作文,800字左右" }], ) decode_dt_end = datetime.now() decode_dt_delta = decode_dt_end - decode_dt_begin print('decode_dt_delta:', decode_dt_delta) output_ids = tokenizer.encode(response, add_special_tokens=False) print('tok/s:', (len(output_ids) + 1) / decode_dt_delta.total_seconds()) print(response) def run_hf_demo(): with EmptyInitOnDevice(): model = load_hf_model() model.generation_config = GenerationConfig.from_pretrained(BAICHUAN2_13B_MODEL_FOLDER) tokenizer = AutoTokenizer.from_pretrained( BAICHUAN2_13B_MODEL_FOLDER, use_fast=False, trust_remote_code=True, ) model.generation_config.do_sample = False # pip install bitsandbytes scipy model = model.quantize(8).to('cuda:0') messages = [] while True: content = input('[USER]: ').strip() if content == 'reset': messages = [] continue messages.append({'role': 'user', 'content': content}) response = model.chat(tokenizer, messages) print(f'[ASSISTANT]: {response}') messages.append({'role': 'assistant', 'content': response}) def build_chat_input_for_test( generation_config, # type: ignore tokenizer, # type: ignore messages: Sequence[dict], max_new_tokens: int = 0 ): def _parse_messages(messages, split_role="user"): # type: ignore system, rounds = "", [] round = [] for i, message in enumerate(messages): if message["role"] == "system": assert i == 0 system = message["content"] continue if message["role"] == split_role and round: rounds.append(round) round = [] round.append(message) if round: rounds.append(round) return system, rounds max_new_tokens = max_new_tokens or generation_config.max_new_tokens max_input_tokens = 4096 - max_new_tokens system, rounds = _parse_messages(messages, split_role="user") system_tokens = tokenizer.encode(system) max_history_tokens = max_input_tokens - len(system_tokens) history_tokens = [] for round in rounds[::-1]: round_tokens = [] for message in round: if message["role"] == "user": round_tokens.append(generation_config.user_token_id) else: round_tokens.append(generation_config.assistant_token_id) round_tokens.extend(tokenizer.encode(message["content"])) if len(history_tokens ) == 0 or len(history_tokens) + len(round_tokens) <= max_history_tokens: history_tokens = round_tokens + history_tokens # concat left if len(history_tokens) < max_history_tokens: continue break input_tokens = system_tokens + history_tokens if messages[-1]["role"] != "assistant": input_tokens.append(generation_config.assistant_token_id) input_tokens = input_tokens[-max_input_tokens:] # truncate left return input_tokens def compare_tokenizers(): hf_tokenizer = AutoTokenizer.from_pretrained( BAICHUAN2_13B_MODEL_FOLDER, use_fast=False, trust_remote_code=True, ) hf_generation_config = GenerationConfig.from_pretrained(BAICHUAN2_13B_MODEL_FOLDER) tokenizer = Baichuan2Tokenizer(f'{BAICHUAN2_13B_MODEL_FOLDER}/tokenizer.model') def _compare(messages): # type: ignore hf_input_ids = build_chat_input_for_test( generation_config=hf_generation_config, tokenizer=hf_tokenizer, messages=messages, ) input_ids = tokenizer.chat_tokenize([ (Role.from_string(message['role']), message['content']) for message in messages ])[0] assert hf_input_ids == input_ids _compare([ { 'role': 'user', 'content': '测试一下' }, ]) _compare([ { 'role': 'system', 'content': '这个是 system' }, { 'role': 'user', 'content': '测试一下' }, ]) _compare([ { 'role': 'user', 'content': 'foo' }, { 'role': 'assistant', 'content': 'bar' }, { 'role': 'user', 'content': 'baz' }, ]) _compare([ { 'role': 'system', 'content': '这个是 system' }, { 'role': 'user', 'content': 'foo' }, { 'role': 'assistant', 'content': 'bar' }, { 'role': 'user', 'content': 'baz' }, ]) def load_and_convert_to_model(model_folder: str = BAICHUAN2_13B_MODEL_FOLDER): with EmptyInitOnDevice(): hf_model = load_hf_model(model_folder) return convert_hf_model_to_model(hf_model) def generate_debug_input_ids(model_folder: str = BAICHUAN2_13B_MODEL_FOLDER): sp_model = spm.SentencePieceProcessor() sp_model.Load(f'{model_folder}/tokenizer.model') input_ids = sp_model.tokenize('测试一下。') # type: ignore input_ids = torch.tensor([[195, *input_ids]], dtype=torch.int) return input_ids def move_model_to_devices( model: Baichuan2Model, device_and_layer_begin_pairs: Sequence[Tuple[str, int]], ): assert device_and_layer_begin_pairs device0 = device_and_layer_begin_pairs[0][0] model.embed_tokens.to(device0) model.alibi_mask = model.alibi_mask.to(device0) for pair_idx, (device, layer_begin) in enumerate(device_and_layer_begin_pairs): if pair_idx + 1 < len(device_and_layer_begin_pairs): layer_end = device_and_layer_begin_pairs[pair_idx + 1][1] else: layer_end = len(model.layers) for layer_idx in range(layer_begin, layer_end): model.layers[layer_idx].to(device) device1 = device_and_layer_begin_pairs[-1][0] model.norm.to(device1) model.lm_head.to(device1) def save_model_logits( output_file: str, model_folder: str = BAICHUAN2_13B_MODEL_FOLDER, compile: bool = False, int8: bool = False, fp8: bool = False, ): ''' fib gpt_blazing_experiment/model/debug_baichuan2.py:save_model_logits \ --output_file="$GPT_BLAZING_DATA/model/baichuan2/logits.pt" fib gpt_blazing_experiment/model/debug_baichuan2.py:save_model_logits \ --output_file="$GPT_BLAZING_DATA/model/baichuan2/int8_logits.pt" \ --int8 fib gpt_blazing_experiment/model/debug_baichuan2.py:save_model_logits \ --output_file="$GPT_BLAZING_DATA/model/baichuan2/fp8_logits.pt" \ --fp8 fib gpt_blazing_experiment/model/debug_baichuan2.py:save_model_logits \ --output_file="$GPT_BLAZING_DATA/model/baichuan2/compiled_logits.pt" \ --compile fib gpt_blazing_experiment/model/debug_baichuan2.py:save_model_logits \ --output_file="$GPT_BLAZING_DATA/model/baichuan2/compiled_int8_logits.pt" \ --compile \ --int8 # 'fp8e4nv data type is not supported on CUDA arch < 89' fib gpt_blazing_experiment/model/debug_baichuan2.py:save_model_logits \ --output_file="$GPT_BLAZING_DATA/model/baichuan2/compiled_fp8_logits.pt" \ --compile \ --fp8 ''' print('Loading...') model = load_and_convert_to_model(model_folder) if int8: print('Quantizing (int8) ...') model = quantize_int8(model) elif fp8: print('Quantizing (fp8) ...') model = quantize_fp8(model) if not (int8 or fp8): move_model_to_devices(model, [('cuda:0', 0), ('cuda:1', 20)]) # type: ignore else: model = model.to('cuda:0') # type: ignore if compile: print('Compiling...') model = torch.compile(model, mode="reduce-overhead", fullgraph=True) input_ids = generate_debug_input_ids(model_folder) input_ids = input_ids.to('cuda:0') input_pos = torch.arange(0, input_ids.shape[1], device=input_ids.device) with torch.inference_mode(): with torch.backends.cuda.sdp_kernel( enable_flash=False, enable_mem_efficient=False, enable_math=True, ): logits, _ = model(input_pos=input_pos, end=2048, input_ids=input_ids) print('Saving to', output_file) torch.save(logits, output_file) def save_hf_model_logits( output_file: str, model_folder: str = BAICHUAN2_13B_MODEL_FOLDER, int8: bool = False, ): ''' fib gpt_blazing_experiment/model/debug_baichuan2.py:save_hf_model_logits \ --output_file="$GPT_BLAZING_DATA/model/baichuan2/hf_logits.pt" fib gpt_blazing_experiment/model/debug_baichuan2.py:save_hf_model_logits \ --output_file="$GPT_BLAZING_DATA/model/baichuan2/int8_hf_logits.pt" \ --int8 ''' print('Loading...') with EmptyInitOnDevice(): if not int8: os.environ["CUDA_VISIBLE_DEVICES"] = '0,1' hf_model = load_hf_model(model_folder, device_map='auto') else: hf_model = load_hf_model(model_folder) hf_model = hf_model.quantize(8).to('cuda:0') # type: ignore input_ids = generate_debug_input_ids(model_folder) input_ids = input_ids.to('cuda:0') with torch.inference_mode(): output = hf_model.forward(input_ids=input_ids) print('Saving to', output_file) torch.save(output.logits, output_file) def get_top_p_sorted_indices(logits: torch.Tensor, top_p: float = 0.9): sorted_logits, sorted_indices = torch.sort(logits, descending=True) cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1) mask = cumulative_probs <= top_p mask[..., 1:] = mask[..., :-1].clone() mask[..., 0] = True sorted_indices[~mask] = -1 return sorted_indices def compare_logits(file0: str, file1: str): ''' # 1. fib gpt_blazing_experiment/model/debug_baichuan2.py:compare_logits \ --file0="$GPT_BLAZING_DATA/model/baichuan2/logits.pt" \ --file1="$GPT_BLAZING_DATA/model/baichuan2/hf_logits.pt" # 0.9942 fib gpt_blazing_experiment/model/debug_baichuan2.py:compare_logits \ --file0="$GPT_BLAZING_DATA/model/baichuan2/logits.pt" \ --file1="$GPT_BLAZING_DATA/model/baichuan2/fp8_logits.pt" # 0.9942 fib gpt_blazing_experiment/model/debug_baichuan2.py:compare_logits \ --file0="$GPT_BLAZING_DATA/model/baichuan2/logits.pt" \ --file1="$GPT_BLAZING_DATA/model/baichuan2/int8_logits.pt" # 0.9945 fib gpt_blazing_experiment/model/debug_baichuan2.py:compare_logits \ --file0="$GPT_BLAZING_DATA/model/baichuan2/logits.pt" \ --file1="$GPT_BLAZING_DATA/model/baichuan2/int8_hf_logits.pt" # 0.9939 fib gpt_blazing_experiment/model/debug_baichuan2.py:compare_logits \ --file0="$GPT_BLAZING_DATA/model/baichuan2/logits.pt" \ --file1="$GPT_BLAZING_DATA/model/baichuan2/compiled_logits.pt" # 0.9939 fib gpt_blazing_experiment/model/debug_baichuan2.py:compare_logits \ --file0="$GPT_BLAZING_DATA/model/baichuan2/logits.pt" \ --file1="$GPT_BLAZING_DATA/model/baichuan2/compiled_int8_logits.pt" # 0.9938 fib gpt_blazing_experiment/model/debug_baichuan2.py:compare_logits \ --file0="$GPT_BLAZING_DATA/model/baichuan2/compiled_int8_logits.pt" \ --file1="$GPT_BLAZING_DATA/model/baichuan2/int8_hf_logits.pt" ''' logits0 = torch.load(file0, map_location='cuda:0') logits1 = torch.load(file1, map_location='cuda:0') tpsi0 = get_top_p_sorted_indices(logits0) tpsi1 = get_top_p_sorted_indices(logits1) rank = tpsi0 == tpsi1 r = rank.sum() / rank.numel() print(r) def demo_func(x: torch.Tensor, y: torch.Tensor, begin: int, end: int): return x[:, begin:end] + y[:, begin:end] def debug_compile(): func = torch.compile(demo_func, mode="reduce-overhead", fullgraph=True) x = torch.rand((1, 20, 128)) y = torch.rand((1, 20, 128)) print(func(x, y, 0, 10)) # triggers Recompiling! print(func(x, y, 0, 15)) print(func(x, y, 1, 2)) def timed(fn): # type: ignore start = torch.cuda.Event(enable_timing=True) end = torch.cuda.Event(enable_timing=True) start.record() # type: ignore result = fn() end.record() # type: ignore torch.cuda.synchronize() return result, start.elapsed_time(end) / 1000 def debug_greedy_decoding_performance(): print('Loading...') model = load_model( model_pt=str( io.file("$GPT_BLAZING_DATA/model/baichuan2-13b-chat/int8.pt", expandvars=True) ), int8=True, config=Baichuan2ModelConfig(debug=False), ) model.to('cuda:0') print('Compiling...') torch._inductor.config.coordinate_descent_tuning = True torch._inductor.config.triton.unique_kernel_names = True torch._inductor.config.fx_graph_cache = True input_ids = generate_debug_input_ids() input_ids = input_ids.to('cuda:0') prefill_2048 = compile_model_prefill(model_prefill_2048) prefill_4096 = compile_model_prefill(model_prefill_4096) for offset in [0, 2048]: for _ in range(3): input_pos = torch.arange( offset, offset + int(input_ids.shape[1]), device=input_ids.device, dtype=torch.int, ) print( 'prefill compiling time:', timed(
lambda: model_dispatch(
13
2023-12-03 09:26:20+00:00
12k
tmllab/Machine_Vision_Therapy
model/blip2/modeling_blip_2.py
[ { "identifier": "Blip2Config", "path": "model/blip2/configuration_blip_2.py", "snippet": "class Blip2Config(PretrainedConfig):\n r\"\"\"\n [`Blip2Config`] is the configuration class to store the configuration of a [`Blip2ForConditionalGeneration`]. It is\n used to instantiate a BLIP-2 model acc...
import math import torch import torch.utils.checkpoint from dataclasses import dataclass from typing import Any, Optional, Tuple, Union from torch import nn from torch.nn import CrossEntropyLoss from transformers.activations import ACT2FN from transformers.modeling_outputs import ( BaseModelOutput, BaseModelOutputWithPastAndCrossAttentions, BaseModelOutputWithPooling, BaseModelOutputWithPoolingAndCrossAttentions, ) from transformers.modeling_utils import PreTrainedModel from transformers.pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer from transformers.utils import ( ModelOutput, add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings, ) from transformers.models.auto.modeling_auto import AutoModelForCausalLM, AutoModelForSeq2SeqLM from model.blip2.configuration_blip_2 import Blip2Config, Blip2QFormerConfig, Blip2VisionConfig from model.blip2.processing_blip_2 import Blip2Processor
7,975
return outputs def feed_forward_chunk(self, attention_output): intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) return layer_output def feed_forward_chunk_query(self, attention_output): intermediate_output = self.intermediate_query(attention_output) layer_output = self.output_query(intermediate_output, attention_output) return layer_output class Blip2QFormerEncoder(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList( [Blip2QFormerLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.gradient_checkpointing = False def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=False, output_hidden_states=False, return_dict=True, query_length=0, ): all_hidden_states = () if output_hidden_states else None all_self_attentions = () if output_attentions else None all_cross_attentions = () if output_attentions else None next_decoder_cache = () if use_cache else None for i in range(self.config.num_hidden_layers): layer_module = self.layer[i] if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) layer_head_mask = head_mask[i] if head_mask is not None else None past_key_value = past_key_values[i] if past_key_values is not None else None if getattr(self.config, "gradient_checkpointing", False) and self.training: if use_cache: logger.warn( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." ) use_cache = False def create_custom_forward(module): def custom_forward(*inputs): return module(*inputs, past_key_value, output_attentions, query_length) return custom_forward layer_outputs = torch.utils.checkpoint.checkpoint( create_custom_forward(layer_module), hidden_states, attention_mask, layer_head_mask, encoder_hidden_states, encoder_attention_mask, ) else: layer_outputs = layer_module( hidden_states, attention_mask, layer_head_mask, encoder_hidden_states, encoder_attention_mask, past_key_value, output_attentions, query_length, ) hidden_states = layer_outputs[0] if use_cache: next_decoder_cache += (layer_outputs[-1],) if output_attentions: all_self_attentions = all_self_attentions + (layer_outputs[1],) if layer_module.has_cross_attention: all_cross_attentions = all_cross_attentions + (layer_outputs[2],) if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple( v for v in [ hidden_states, next_decoder_cache, all_hidden_states, all_self_attentions, all_cross_attentions, ] if v is not None ) return BaseModelOutputWithPastAndCrossAttentions( last_hidden_state=hidden_states, past_key_values=next_decoder_cache, hidden_states=all_hidden_states, attentions=all_self_attentions, cross_attentions=all_cross_attentions, ) class Blip2QFormerModel(Blip2PreTrainedModel): """ Querying Transformer (Q-Former), used in BLIP-2. """
# coding=utf-8 # Copyright 2023 The Salesforce Authors and 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. """ PyTorch BLIP-2 model.""" logger = logging.get_logger(__name__) _CHECKPOINT_FOR_DOC = "Salesforce/blip2-opt-2.7b" BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST = [ "Salesforce/blip2-opt-2.7b", # See all BLIP-2 models at https://huggingface.co/models?filter=blip ] @dataclass class Blip2ForConditionalGenerationModelOutput(ModelOutput): """ Class defining the outputs of [`Blip2ForConditionalGeneration`]. Args: loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`): Language modeling loss from the language model. logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head of the language model. vision_outputs (`BaseModelOutputWithPooling`): Outputs of the vision encoder. qformer_outputs (`BaseModelOutputWithPoolingAndCrossAttentions`): Outputs of the Q-Former (Querying Transformer). language_model_outputs (`CausalLMOutputWithPast` or `Seq2SeqLMOutput`): Outputs of the language model. """ loss: Optional[Tuple[torch.FloatTensor]] = None logits: Optional[Tuple[torch.FloatTensor]] = None vision_outputs: Optional[torch.FloatTensor] = None qformer_outputs: Optional[Tuple[torch.FloatTensor]] = None language_model_outputs: Optional[Tuple[torch.FloatTensor]] = None def to_tuple(self) -> Tuple[Any]: return tuple( self[k] if k not in ["vision_outputs", "qformer_outputs", "language_model_outputs"] else getattr(self, k).to_tuple() for k in self.keys() ) # Copied from transformers.models.blip.modeling_blip.BlipVisionEmbeddings with Blip->Blip2 class Blip2VisionEmbeddings(nn.Module): def __init__(self, config: Blip2VisionConfig): super().__init__() self.config = config self.embed_dim = config.hidden_size self.image_size = config.image_size self.patch_size = config.patch_size self.class_embedding = nn.Parameter( torch.randn(1, 1, self.embed_dim), ) self.patch_embedding = nn.Conv2d( in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size ) self.num_patches = (self.image_size // self.patch_size) ** 2 self.num_positions = self.num_patches + 1 self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim)) def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor: batch_size = pixel_values.shape[0] target_dtype = self.patch_embedding.weight.dtype patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid] patch_embeds = patch_embeds.flatten(2).transpose(1, 2) class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype) embeddings = torch.cat([class_embeds, patch_embeds], dim=1) embeddings = embeddings + self.position_embedding[:, : embeddings.size(1), :].to(target_dtype) return embeddings class Blip2Attention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config): super().__init__() self.config = config self.embed_dim = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = self.embed_dim // self.num_heads if self.head_dim * self.num_heads != self.embed_dim: raise ValueError( f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:" f" {self.num_heads})." ) self.scale = self.head_dim**-0.5 self.dropout = nn.Dropout(config.attention_dropout) # small tweak here compared to CLIP, no bias here self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=False) if config.qkv_bias: q_bias = nn.Parameter(torch.zeros(self.embed_dim)) v_bias = nn.Parameter(torch.zeros(self.embed_dim)) else: q_bias = None v_bias = None if q_bias is not None: qkv_bias = torch.cat((q_bias, torch.zeros_like(v_bias, requires_grad=False), v_bias)) self.qkv.bias = nn.Parameter(qkv_bias) self.projection = nn.Linear(self.embed_dim, self.embed_dim) 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, head_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = False, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: """Input shape: Batch x Time x Channel""" bsz, tgt_len, embed_dim = hidden_states.size() mixed_qkv = self.qkv(hidden_states) mixed_qkv = mixed_qkv.reshape(bsz, tgt_len, 3, self.num_heads, embed_dim // self.num_heads).permute( 2, 0, 3, 1, 4 ) query_states, key_states, value_states = ( mixed_qkv[0], mixed_qkv[1], mixed_qkv[2], ) # Take the dot product between "query" and "key" to get the raw attention scores. attention_scores = torch.matmul(query_states, key_states.transpose(-1, -2)) attention_scores = attention_scores * self.scale # Normalize the attention scores to probabilities. attention_probs = nn.functional.softmax(attention_scores, dim=-1) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs = self.dropout(attention_probs) # Mask heads if we want to if head_mask is not None: attention_probs = attention_probs * head_mask context_layer = torch.matmul(attention_probs, value_states).permute(0, 2, 1, 3) new_context_layer_shape = context_layer.size()[:-2] + (self.embed_dim,) context_layer = context_layer.reshape(new_context_layer_shape) output = self.projection(context_layer) outputs = (output, attention_probs) if output_attentions else (output, None) return outputs # Copied from transformers.models.blip.modeling_blip.BlipMLP class Blip2MLP(nn.Module): def __init__(self, config): super().__init__() self.config = config self.activation_fn = ACT2FN[config.hidden_act] self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size) self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: hidden_states = self.fc1(hidden_states) hidden_states = self.activation_fn(hidden_states) hidden_states = self.fc2(hidden_states) return hidden_states # Copied from transformers.models.blip.modeling_blip.BlipEncoderLayer with Blip->Blip2 class Blip2EncoderLayer(nn.Module): def __init__(self, config: Blip2Config): super().__init__() self.embed_dim = config.hidden_size self.self_attn = Blip2Attention(config) self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) self.mlp = Blip2MLP(config) self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, output_attentions: Optional[bool] = False, ) -> Tuple[torch.FloatTensor]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. `(config.encoder_attention_heads,)`. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. """ residual = hidden_states hidden_states = self.layer_norm1(hidden_states) hidden_states, attn_weights = self.self_attn( hidden_states=hidden_states, head_mask=attention_mask, output_attentions=output_attentions, ) hidden_states = hidden_states + residual residual = hidden_states hidden_states = self.layer_norm2(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = hidden_states + residual outputs = (hidden_states,) if output_attentions: outputs += (attn_weights,) return outputs class Blip2PreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = Blip2Config base_model_prefix = "blip" supports_gradient_checkpointing = True _keys_to_ignore_on_load_missing = [ r"position_ids", r"language_model.encoder.embed_tokens.weight", r"language_model.decoder.embed_tokens.weight", ] _no_split_modules = ["Blip2Attention", "T5Block", "OPTDecoderLayer"] _keep_in_fp32_modules = ["wo"] def _init_weights(self, module): """Initialize the weights""" factor = self.config.initializer_range if isinstance(module, nn.Conv2d) or isinstance(module, nn.Embedding) or isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=factor) if hasattr(module, "bias") and module.bias is not None: module.bias.data.zero_() if isinstance(module, Blip2VisionEmbeddings): if hasattr(self.config, "vision_config"): factor = self.config.vision_config.initializer_range nn.init.trunc_normal_(module.position_embedding, mean=0.0, std=factor) nn.init.trunc_normal_(module.class_embedding, mean=0.0, std=factor) elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) elif isinstance(module, nn.Linear) and module.bias is not None: module.bias.data.zero_() def _set_gradient_checkpointing(self, module, value=False): if isinstance(module, Blip2Encoder): module.gradient_checkpointing = value BLIP_2_START_DOCSTRING = r""" This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`Blip2Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ BLIP_2_VISION_INPUTS_DOCSTRING = r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`Blip2Processor`]. See [`Blip2Processor.__call__`] for details. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ BLIP_2_INPUTS_DOCSTRING = r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`Blip2Processor`]. See [`Blip2Processor.__call__`] for details. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of input sequence tokens in the vocabulary of the language model. Input tokens can optionally be provided to serve as text prompt, which the language model can continue. Indices can be obtained using [`Blip2Processor`]. See [`Blip2Processor.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Indices of decoder input sequence tokens in the vocabulary of the language model. Only relevant in case an encoder-decoder language model (like T5) is used. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are decoder input IDs?](../glossary#decoder-input-ids) decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also be used by default. Only relevant in case an encoder-decoder language model (like T5) is used. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ # Copied from transformers.models.blip.modeling_blip.BlipEncoder with Blip->Blip2 class Blip2Encoder(nn.Module): """ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a [`Blip2EncoderLayer`]. Args: config (`Blip2Config`): The corresponding vision configuration for the `Blip2Encoder`. """ def __init__(self, config: Blip2Config): super().__init__() self.config = config self.layers = nn.ModuleList([Blip2EncoderLayer(config) for _ in range(config.num_hidden_layers)]) self.gradient_checkpointing = False def forward( self, inputs_embeds, attention_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutput]: r""" Args: inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ 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 encoder_states = () if output_hidden_states else None all_attentions = () if output_attentions else None hidden_states = inputs_embeds for idx, encoder_layer in enumerate(self.layers): if output_hidden_states: encoder_states = encoder_states + (hidden_states,) if self.gradient_checkpointing and self.training: def create_custom_forward(module): def custom_forward(*inputs): return module(*inputs, output_attentions) return custom_forward layer_outputs = torch.utils.checkpoint.checkpoint( create_custom_forward(encoder_layer), hidden_states, attention_mask, ) else: layer_outputs = encoder_layer( hidden_states, attention_mask, output_attentions=output_attentions, ) hidden_states = layer_outputs[0] if output_attentions: all_attentions = all_attentions + (layer_outputs[1],) if output_hidden_states: encoder_states = encoder_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None) return BaseModelOutput( last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions ) # Copied from transformers.models.blip.modeling_blip.BlipVisionModel with Blip->Blip2, BLIP->BLIP_2 class Blip2VisionModel(Blip2PreTrainedModel): main_input_name = "pixel_values" config_class = Blip2VisionConfig def __init__(self, config: Blip2VisionConfig): super().__init__(config) self.config = config embed_dim = config.hidden_size self.embeddings = Blip2VisionEmbeddings(config) self.encoder = Blip2Encoder(config) self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) self.post_init() @add_start_docstrings_to_model_forward(BLIP_2_VISION_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=Blip2VisionConfig) def forward( self, pixel_values: Optional[torch.FloatTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutputWithPooling]: r""" Returns: """ 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 if pixel_values is None: raise ValueError("You have to specify pixel_values") hidden_states = self.embeddings(pixel_values) encoder_outputs = self.encoder( inputs_embeds=hidden_states, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) last_hidden_state = encoder_outputs[0] last_hidden_state = self.post_layernorm(last_hidden_state) pooled_output = last_hidden_state[:, 0, :] pooled_output = self.post_layernorm(pooled_output) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPooling( last_hidden_state=last_hidden_state, pooler_output=pooled_output, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions, ) def get_input_embeddings(self): return self.embeddings class Blip2QFormerMultiHeadAttention(nn.Module): def __init__(self, config, is_cross_attention=False): super().__init__() self.config = config if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( "The hidden size (%d) is not a multiple of the number of attention heads (%d)" % (config.hidden_size, config.num_attention_heads) ) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Linear(config.hidden_size, self.all_head_size) if is_cross_attention: self.key = nn.Linear(config.encoder_hidden_size, self.all_head_size) self.value = nn.Linear(config.encoder_hidden_size, self.all_head_size) else: self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": self.max_position_embeddings = config.max_position_embeddings self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size) self.save_attention = False def save_attn_gradients(self, attn_gradients): self.attn_gradients = attn_gradients def get_attn_gradients(self): return self.attn_gradients def save_attention_map(self, attention_map): self.attention_map = attention_map def get_attention_map(self): return self.attention_map def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=False, ): # If this is instantiated as a cross-attention module, the keys # and values come from an encoder; the attention mask needs to be # such that the encoder's padding tokens are not attended to. is_cross_attention = encoder_hidden_states is not None if is_cross_attention: key_layer = self.transpose_for_scores(self.key(encoder_hidden_states)) value_layer = self.transpose_for_scores(self.value(encoder_hidden_states)) attention_mask = encoder_attention_mask elif past_key_value is not None: key_layer = self.transpose_for_scores(self.key(hidden_states)) value_layer = self.transpose_for_scores(self.value(hidden_states)) key_layer = torch.cat([past_key_value[0], key_layer], dim=2) value_layer = torch.cat([past_key_value[1], value_layer], dim=2) else: key_layer = self.transpose_for_scores(self.key(hidden_states)) value_layer = self.transpose_for_scores(self.value(hidden_states)) mixed_query_layer = self.query(hidden_states) query_layer = self.transpose_for_scores(mixed_query_layer) past_key_value = (key_layer, value_layer) # Take the dot product between "query" and "key" to get the raw attention scores. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": seq_length = hidden_states.size()[1] position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1) position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1) distance = position_ids_l - position_ids_r positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1) positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility if self.position_embedding_type == "relative_key": relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) attention_scores = attention_scores + relative_position_scores elif self.position_embedding_type == "relative_key_query": relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding) attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key attention_scores = attention_scores / math.sqrt(self.attention_head_size) if attention_mask is not None: # Apply the attention mask is (precomputed for all layers in BertModel forward() function) attention_scores = attention_scores + attention_mask # Normalize the attention scores to probabilities. attention_probs = nn.Softmax(dim=-1)(attention_scores) if is_cross_attention and self.save_attention: self.save_attention_map(attention_probs) attention_probs.register_hook(self.save_attn_gradients) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs_dropped = self.dropout(attention_probs) # Mask heads if we want to if head_mask is not None: attention_probs_dropped = attention_probs_dropped * head_mask context_layer = torch.matmul(attention_probs_dropped, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) outputs = outputs + (past_key_value,) return outputs # Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->Blip2QFormer class Blip2QFormerSelfOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class Blip2QFormerAttention(nn.Module): def __init__(self, config, is_cross_attention=False): super().__init__() self.attention = Blip2QFormerMultiHeadAttention(config, is_cross_attention) self.output = Blip2QFormerSelfOutput(config) self.pruned_heads = set() def prune_heads(self, heads): if len(heads) == 0: return heads, index = find_pruneable_heads_and_indices( heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads ) # Prune linear layers self.attention.query = prune_linear_layer(self.attention.query, index) self.attention.key = prune_linear_layer(self.attention.key, index) self.attention.value = prune_linear_layer(self.attention.value, index) self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) # Update hyper params and store pruned heads self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads) self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads self.pruned_heads = self.pruned_heads.union(heads) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, output_attentions: Optional[bool] = False, ) -> Tuple[torch.Tensor]: self_outputs = self.attention( hidden_states, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask, past_key_value, output_attentions, ) attention_output = self.output(self_outputs[0], hidden_states) outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them return outputs # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Blip2QFormer class Blip2QFormerIntermediate(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_fn = config.hidden_act def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->Blip2QFormer class Blip2QFormerOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class Blip2QFormerLayer(nn.Module): def __init__(self, config, layer_idx): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = Blip2QFormerAttention(config) self.layer_idx = layer_idx if layer_idx % config.cross_attention_frequency == 0: self.crossattention = Blip2QFormerAttention(config, is_cross_attention=True) self.has_cross_attention = True else: self.has_cross_attention = False self.intermediate_query = Blip2QFormerIntermediate(config) self.output_query = Blip2QFormerOutput(config) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=False, query_length=0, ): # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None self_attention_outputs = self.attention( hidden_states, attention_mask, head_mask, output_attentions=output_attentions, past_key_value=self_attn_past_key_value, ) attention_output = self_attention_outputs[0] outputs = self_attention_outputs[1:-1] present_key_value = self_attention_outputs[-1] if query_length > 0: query_attention_output = attention_output[:, :query_length, :] if self.has_cross_attention: if encoder_hidden_states is None: raise ValueError("encoder_hidden_states must be given for cross-attention layers") cross_attention_outputs = self.crossattention( query_attention_output, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask, output_attentions=output_attentions, ) query_attention_output = cross_attention_outputs[0] # add cross attentions if we output attention weights outputs = outputs + cross_attention_outputs[1:-1] layer_output = apply_chunking_to_forward( self.feed_forward_chunk_query, self.chunk_size_feed_forward, self.seq_len_dim, query_attention_output, ) if attention_output.shape[1] > query_length: layer_output_text = apply_chunking_to_forward( self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output[:, query_length:, :], ) layer_output = torch.cat([layer_output, layer_output_text], dim=1) else: layer_output = apply_chunking_to_forward( self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output, ) outputs = (layer_output,) + outputs outputs = outputs + (present_key_value,) return outputs def feed_forward_chunk(self, attention_output): intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) return layer_output def feed_forward_chunk_query(self, attention_output): intermediate_output = self.intermediate_query(attention_output) layer_output = self.output_query(intermediate_output, attention_output) return layer_output class Blip2QFormerEncoder(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList( [Blip2QFormerLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.gradient_checkpointing = False def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=False, output_hidden_states=False, return_dict=True, query_length=0, ): all_hidden_states = () if output_hidden_states else None all_self_attentions = () if output_attentions else None all_cross_attentions = () if output_attentions else None next_decoder_cache = () if use_cache else None for i in range(self.config.num_hidden_layers): layer_module = self.layer[i] if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) layer_head_mask = head_mask[i] if head_mask is not None else None past_key_value = past_key_values[i] if past_key_values is not None else None if getattr(self.config, "gradient_checkpointing", False) and self.training: if use_cache: logger.warn( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." ) use_cache = False def create_custom_forward(module): def custom_forward(*inputs): return module(*inputs, past_key_value, output_attentions, query_length) return custom_forward layer_outputs = torch.utils.checkpoint.checkpoint( create_custom_forward(layer_module), hidden_states, attention_mask, layer_head_mask, encoder_hidden_states, encoder_attention_mask, ) else: layer_outputs = layer_module( hidden_states, attention_mask, layer_head_mask, encoder_hidden_states, encoder_attention_mask, past_key_value, output_attentions, query_length, ) hidden_states = layer_outputs[0] if use_cache: next_decoder_cache += (layer_outputs[-1],) if output_attentions: all_self_attentions = all_self_attentions + (layer_outputs[1],) if layer_module.has_cross_attention: all_cross_attentions = all_cross_attentions + (layer_outputs[2],) if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple( v for v in [ hidden_states, next_decoder_cache, all_hidden_states, all_self_attentions, all_cross_attentions, ] if v is not None ) return BaseModelOutputWithPastAndCrossAttentions( last_hidden_state=hidden_states, past_key_values=next_decoder_cache, hidden_states=all_hidden_states, attentions=all_self_attentions, cross_attentions=all_cross_attentions, ) class Blip2QFormerModel(Blip2PreTrainedModel): """ Querying Transformer (Q-Former), used in BLIP-2. """
def __init__(self, config: Blip2QFormerConfig):
1
2023-12-04 00:14:18+00:00
12k
hubo0417/EasyGC
web.py
[ { "identifier": "Pipeline_Item", "path": "utils/pipeline.py", "snippet": "class Pipeline_Item:\n # 类的实例\n Obj: object = None\n # 方法名\n Method: str = None\n # 方法参数\n Params: Dict[str, Any] = None\n # 是否使用上一个方法的结果作为参数\n Is_Use_Pre_Result: bool = False,\n # 是否在节点执行完之后暂停管道\n Ha...
import os import shutil import gradio as gr from gradio.components.chatbot import Chatbot from utils.pipeline import Pipeline_Item, Pipeline_Process_Task from utils.generate.note_generate_utils import Note_Generate_Utils from llms.llm_helper import ChatGLM_Helper from agents.agent_controller.api_sequence_agent import API_Sequence_Agent from agents.agent_executor.sequence_agentexecutor import Sequence_AgentExecutor from sdxl.generate_style_config import style_list from embeddings.embedding_helper import EmbeddingHelper from utils.tool_sets import Tool_Sets from utils.lora_sets import Lora_Sets from configs.base_config import BASE_CONFIG, BASE_FILE_PATH from agents.tools.web_parser_tool import Web_Parser_Tool_Response
10,367
lora_upload = gr.Textbox( lines=1, show_label=True, placeholder="填写模型完整的绝对路径如: D:/aaa/xxxx.safetensors", label="模型路径", interactive=True) scale = gr.Number(value=1, label="权重", minimum=0.1, maximum=1) order_num = gr.Number(value=0, label="排序", minimum=0) tag_words = gr.Textbox(lines=1, show_label=True, placeholder="模型触发词,用逗号分隔", label="触发词", interactive=True) handle_lora = gr.Button("加载模型", variant="primary", min_width=60, width=100) with gr.Row(): style_dropdown = gr.Dropdown(choices=style_name, type="value", value="", show_label=False, container=False, max_choices=1, multiselect=False, interactive=True) lora_dropdown = gr.Dropdown(choices=Lora_Sets.load_loras(), type="value", show_label=False, container=False, max_choices=2, multiselect=True, interactive=True) with gr.Row(): comment = gr.Textbox(lines=2, show_label=True, placeholder="", label="图片描述", interactive=True) ok_note_Btn = gr.Button("生成", variant="primary") with gr.Tab("img2img"): with gr.Row(): with gr.Column(scale=6): img_input = gr.Image(source="upload", show_label=False, interactive=True, type="filepath") with gr.Column(scale=6): img_output = gr.Gallery(label="Generated images", show_label=False, elem_id="img2img_gallery", grid=[4]) with gr.Row(): style_dropdown_img2img = gr.Dropdown(choices=style_name, type="value", value="", show_label=False, container=False, max_choices=1, multiselect=False, interactive=True) img_modify_comment = gr.Textbox(show_label=False, placeholder="关键词/句...", lines=5).style(container=False) with gr.Row(): img2img_btn = gr.Button("生成图片", variant="primary") def handle_upload_lora(scale, order_num, tag_words, lora_upload): if lora_upload and tag_words and os.path.exists(lora_upload): loras = Lora_Sets.init_lora(order_num=order_num, scale=scale, tag_words=tag_words, model_path=lora_upload) new_drop_down = lora_dropdown.update(choices=loras) return new_drop_down def handle_upload_tools(upload_tool): file_path = upload_tool.name tools = Tool_Sets.regist_tool(sorted=1, file_path=file_path) tool_result = [tool["name"] for tool in tools] new_drop_down = content_type.update(choices=tool_result) return new_drop_down def handle_files(files, author_input, number, overlap): upload_file_base_path = BASE_CONFIG["upload_file_base_path"] files_path_array: list = [] for file_obj in files: # 将文件复制到临时目录中 shutil.copy(file_obj.name, upload_file_base_path) # 获取上传Gradio的文件名称 file_name = os.path.basename(file_obj.name) # 获取拷贝在临时目录的新的文件地址 files_path_array.append( os.path.join(upload_file_base_path, file_name)) for file_path in files_path_array: with open(file_path, 'r', encoding='utf-8') as file: content = file.read() texts = EmbeddingHelper.splitText( content, chunk_size=number if number else 1000, overlap=overlap if overlap else 0) item = {} item["content"] = content item["source"] = author_input if author_input else "未知" helper = EmbeddingHelper(collection_name="literature") helper.embedding_texts(texts=texts, metadatas=[item]) def _load_llm_model(): if llm_helper.llm.model is None: llm_helper.llm.load_model(model_name_or_path=llm_helper.model_id) def generate_image_by_image(img_input, img_modify_comment, style_dropdown_img2img): style = {} for i in style_list: if i["name"] == style_dropdown_img2img: style = i break
# 重写继承模型 uploaded_image_url = "" llm_helper = ChatGLM_Helper.instance() def init_agent(tool_names: list): if len(tool_names) > 0: tools = [] for name in tool_names: tools.append(Tool_Sets.init_tools(name, llm=llm_helper.llm)) agent = API_Sequence_Agent(tools=tools, llm=llm_helper.llm) agent_exec = Sequence_AgentExecutor.from_agent_and_tools( agent=agent, tools=tools, verbose=True, max_iterations=1) return agent_exec return None def parse_text(text): lines = text.split("\n") lines = [line for line in lines if line != ""] count = 0 for i, line in enumerate(lines): if "```" in line: count += 1 items = line.split('`') if count % 2 == 1: lines[i] = f'<pre><code class="language-{items[-1]}">' else: lines[i] = '<br></code></pre>' else: if i > 0: if count % 2 == 1: line = line.replace("`", "\\`") line = line.replace("<", "&lt;") line = line.replace(">", "&gt;") line = line.replace(" ", "&nbsp;") line = line.replace("*", "&ast;") line = line.replace("_", "&lowbar;") line = line.replace("-", "&#45;") line = line.replace(".", "&#46;") line = line.replace("!", "&#33;") line = line.replace("(", "&#40;") line = line.replace(")", "&#41;") line = line.replace("$", "&#36;") lines[i] = "<br>" + line text = "".join(lines) return text # def join_history(is_note: bool = False): # result = "" # for item in history: # for key, value in item.items(): # result += f"{value}\n" # return result style_name = [(i["name"]) for i in style_list] css = """ #gallery { min-height: 22rem; margin-bottom: 15px; margin-left: auto; margin-right: auto; border-bottom-right-radius: .5rem !important; border-bottom-left-radius: .5rem !important; }, #upload_tool{ height:96px !important width:280px !important } #content_type{ flex-grow:4 !important } """ with gr.Blocks(css=css) as web_gc: gr.HTML("""<h1 align="center">EasyGC</h1>""") pipe_state = gr.State() with gr.Tab("text generate"): with gr.Row(variant="panel"): with gr.Column(scale=10): with gr.Row(): chatbot = gr.Chatbot() with gr.Row(): user_input = gr.Textbox(show_label=False, placeholder="Input...", lines=4).style(container=False) with gr.Column(scale=2): files = gr.Files(label="上传文件", height=110) author_input = gr.Textbox(lines=1, show_label=True, placeholder="文档元数据标记,用于后续关键字搜索", label="文档源", interactive=True) number = gr.Number(value=1000, label="切分长度", minimum=100) overlap = gr.Number(value=0, label="重叠长度", minimum=0) lode_Btn = gr.Button("处理文件", variant="primary") submitBtn = gr.Button("发送信息", variant="primary", min_width=60) with gr.Row(): with gr.Column(scale=10): content_type = gr.Dropdown( choices=[tool["name"] for tool in Tool_Sets.load_tools()], type="value", multiselect=True, label="工具", interactive=True) with gr.Column(scale=10): upload_tool = gr.File(label="上传工具", height=94, elem_id="upload_tool") with gr.Column(scale=2): handle_tools = gr.Button("加载工具", variant="primary", min_width=60, width=100) with gr.Row(): # note_Btn = gr.Button("生成文章", variant="primary") emptyBtn = gr.Button("清除历史会话") load_llm_model = gr.Button("重新加载LL模型", variant="primary") with gr.Tab("txt2img"): with gr.Row(): with gr.Column(scale=6): gallery = gr.Gallery(label="图片生成", show_label=False, elem_id="gallery", grid=[4]) with gr.Column(scale=3): lora_upload = gr.Textbox( lines=1, show_label=True, placeholder="填写模型完整的绝对路径如: D:/aaa/xxxx.safetensors", label="模型路径", interactive=True) scale = gr.Number(value=1, label="权重", minimum=0.1, maximum=1) order_num = gr.Number(value=0, label="排序", minimum=0) tag_words = gr.Textbox(lines=1, show_label=True, placeholder="模型触发词,用逗号分隔", label="触发词", interactive=True) handle_lora = gr.Button("加载模型", variant="primary", min_width=60, width=100) with gr.Row(): style_dropdown = gr.Dropdown(choices=style_name, type="value", value="", show_label=False, container=False, max_choices=1, multiselect=False, interactive=True) lora_dropdown = gr.Dropdown(choices=Lora_Sets.load_loras(), type="value", show_label=False, container=False, max_choices=2, multiselect=True, interactive=True) with gr.Row(): comment = gr.Textbox(lines=2, show_label=True, placeholder="", label="图片描述", interactive=True) ok_note_Btn = gr.Button("生成", variant="primary") with gr.Tab("img2img"): with gr.Row(): with gr.Column(scale=6): img_input = gr.Image(source="upload", show_label=False, interactive=True, type="filepath") with gr.Column(scale=6): img_output = gr.Gallery(label="Generated images", show_label=False, elem_id="img2img_gallery", grid=[4]) with gr.Row(): style_dropdown_img2img = gr.Dropdown(choices=style_name, type="value", value="", show_label=False, container=False, max_choices=1, multiselect=False, interactive=True) img_modify_comment = gr.Textbox(show_label=False, placeholder="关键词/句...", lines=5).style(container=False) with gr.Row(): img2img_btn = gr.Button("生成图片", variant="primary") def handle_upload_lora(scale, order_num, tag_words, lora_upload): if lora_upload and tag_words and os.path.exists(lora_upload): loras = Lora_Sets.init_lora(order_num=order_num, scale=scale, tag_words=tag_words, model_path=lora_upload) new_drop_down = lora_dropdown.update(choices=loras) return new_drop_down def handle_upload_tools(upload_tool): file_path = upload_tool.name tools = Tool_Sets.regist_tool(sorted=1, file_path=file_path) tool_result = [tool["name"] for tool in tools] new_drop_down = content_type.update(choices=tool_result) return new_drop_down def handle_files(files, author_input, number, overlap): upload_file_base_path = BASE_CONFIG["upload_file_base_path"] files_path_array: list = [] for file_obj in files: # 将文件复制到临时目录中 shutil.copy(file_obj.name, upload_file_base_path) # 获取上传Gradio的文件名称 file_name = os.path.basename(file_obj.name) # 获取拷贝在临时目录的新的文件地址 files_path_array.append( os.path.join(upload_file_base_path, file_name)) for file_path in files_path_array: with open(file_path, 'r', encoding='utf-8') as file: content = file.read() texts = EmbeddingHelper.splitText( content, chunk_size=number if number else 1000, overlap=overlap if overlap else 0) item = {} item["content"] = content item["source"] = author_input if author_input else "未知" helper = EmbeddingHelper(collection_name="literature") helper.embedding_texts(texts=texts, metadatas=[item]) def _load_llm_model(): if llm_helper.llm.model is None: llm_helper.llm.load_model(model_name_or_path=llm_helper.model_id) def generate_image_by_image(img_input, img_modify_comment, style_dropdown_img2img): style = {} for i in style_list: if i["name"] == style_dropdown_img2img: style = i break
util = Note_Generate_Utils(llm=llm_helper.llm,
2
2023-11-28 10:11:57+00:00
12k
Fraunhofer-SCAI/llamol
trainer.py
[ { "identifier": "fragment_creator_factory", "path": "fragment_creator.py", "snippet": "def fragment_creator_factory(key: Union[str, None]):\n if key is None:\n return None\n\n if key == \"mol_frags\":\n return MolFragsFragmentCreator()\n elif key == \"recap\":\n return Reca...
from dataclasses import dataclass from typing import Any, Dict, Optional, Tuple, List, Union from fragment_creator import fragment_creator_factory from model import ContextArgs, ModelArgs from tqdm import tqdm from contextlib import nullcontext from datetime import datetime from functools import partial from model import ContextArgs, Transformer, ModelArgs from torch.distributed import destroy_process_group, init_process_group from torch.nn.parallel import DistributedDataParallel as DDP from preprocess_dataset import SmilesTask from tokenizer import SmilesTokenizer import math import os import time import torch import numpy as np import logging
8,867
learning_rate: float = 1e-4 # max learning rate max_iters: int = 100000 # total number of training iterations weight_decay: float = 1e-1 beta1: float = 0.9 beta2: float = 0.95 grad_clip: float = 1.0 # clip gradients at this value, or disable if == 0.0 # learning rate decay settings decay_lr: bool = True # whether to decay the learning rate warmup_iters: int = 1000 # how many steps to warm up for lr_decay_iters: int = 100000 # should be ~= max_iters per Chinchilla min_lr: float = ( 0.0 # minimum learning rate, should be ~= learning_rate/10 per Chinchilla ) @dataclass class TrainerArgs: # Input / Output io_conf: IOConfig # Loader Configs loader_conf: LoaderConfig # Transformer Args model_conf: ModelArgs context_conf: ContextArgs # Optimizer optimizer_conf: OptimizerConfig run_name: str class Trainer: def __init__( self, train_args: TrainerArgs, dtype: str = "float16", compile: bool = False ) -> None: self.train_conf = train_args self.dtype = dtype self.compile = compile # system self.run_name = train_args.run_name self.device = ( "cuda:0" if torch.cuda.is_available() else "cpu" ) # "cuda" # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1' etc., or try 'mps' on macbooks self.CKPT_PT = f"{self.run_name}.pt" self.SNAPSHOT_PT = f"snapshot_{self.run_name}.pt" def _init_ddp_if_possible(self): # various inits, derived attributes, I/O setup self.ddp = int(os.environ.get("RANK", -1)) != -1 # is this a ddp run? if self.ddp: logger.info(f"Using ddp!") init_process_group(backend="nccl") self.ddp_rank = int(os.environ["RANK"]) self.ddp_local_rank = int(os.environ["LOCAL_RANK"]) self.ddp_world_size = int(os.environ["WORLD_SIZE"]) logger.info(f"{self.ddp_rank}, {self.ddp_local_rank},{self.ddp_world_size}") self.device = f"cuda:{self.ddp_local_rank}" torch.cuda.set_device(self.device) self.master_process = ( self.ddp_rank == 0 ) # this process will do logging, checkpointing etc. logger.info(f"Is master process {self.device}? {self.master_process}") self.seed_offset = self.ddp_rank # each process gets a different seed # world_size number of processes will be training simultaneously, so we can scale # down the desired gradient accumulation iterations per process proportionally assert ( self.train_conf.optimizer_conf.gradient_accumulation_steps % self.ddp_world_size == 0 ) self.train_conf.optimizer_conf.gradient_accumulation_steps //= ( self.ddp_world_size ) else: # if not ddp, we are running on a single gpu, and one process self.master_process = True self.seed_offset = 0 self.ddp_world_size = 1 def _init_train(self): self.tokens_per_iter = ( self.train_conf.optimizer_conf.gradient_accumulation_steps * self.ddp_world_size * self.train_conf.loader_conf.batch_size * self.train_conf.loader_conf.max_seq_len ) if self.master_process: logger.info(f"tokens per iteration will be: {self.tokens_per_iter:,}") logger.info( f"breaks down as: {self.train_conf.optimizer_conf.gradient_accumulation_steps} grad accum steps * {self.ddp_world_size} processes * {self.train_conf.loader_conf.batch_size} batch size * {self.train_conf.loader_conf.max_seq_len } max seq len" ) if self.master_process: os.makedirs(self.train_conf.io_conf.out_dir, exist_ok=True) torch.manual_seed(1337 + self.seed_offset) np.random.seed(1337 + self.seed_offset) torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn self.device_type = ( "cuda" if "cuda" in self.device else "cpu" ) # for later use in torch.autocast # note: float16 data type will automatically use a GradScaler ptdtype = { "float32": torch.float32, "bfloat16": torch.bfloat16, "float16": torch.float16, }[self.dtype] self.ctx = ( nullcontext() if self.device_type == "cpu" else torch.amp.autocast(device_type=self.device_type, dtype=ptdtype) ) # task-specific setup
logger = logging.getLogger(__name__) @dataclass class IOConfig: # I/O out_dir: str = "out" eval_interval: int = 500 log_interval: int = 10 eval_iters: int = 25 eval_only: bool = False # if True, script exits right after the first eval always_save_checkpoint: bool = ( False # if True, always save a checkpoint after each eval ) init_from: str = "scratch" # 'scratch' or 'resume' resume_when_snapshot_available: bool = True @dataclass class LoaderConfig: # data batch_size: int = ( 384 # if gradient_accumulation_steps > 1, this is the micro-batch size ) max_seq_len: int = 768 dataset: str = "smiles" processed_dataset_ckpt: str = "processed_dataset_None.pkl" fragment_creator: Union[str, None] = None # dim = 256 # n_layers = 8 # n_heads = 8 # multiple_of = 128 # dropout = 0.1 @dataclass class OptimizerConfig: # adamw optimizer gradient_accumulation_steps: int = 4 # used to simulate larger batch sizes learning_rate: float = 1e-4 # max learning rate max_iters: int = 100000 # total number of training iterations weight_decay: float = 1e-1 beta1: float = 0.9 beta2: float = 0.95 grad_clip: float = 1.0 # clip gradients at this value, or disable if == 0.0 # learning rate decay settings decay_lr: bool = True # whether to decay the learning rate warmup_iters: int = 1000 # how many steps to warm up for lr_decay_iters: int = 100000 # should be ~= max_iters per Chinchilla min_lr: float = ( 0.0 # minimum learning rate, should be ~= learning_rate/10 per Chinchilla ) @dataclass class TrainerArgs: # Input / Output io_conf: IOConfig # Loader Configs loader_conf: LoaderConfig # Transformer Args model_conf: ModelArgs context_conf: ContextArgs # Optimizer optimizer_conf: OptimizerConfig run_name: str class Trainer: def __init__( self, train_args: TrainerArgs, dtype: str = "float16", compile: bool = False ) -> None: self.train_conf = train_args self.dtype = dtype self.compile = compile # system self.run_name = train_args.run_name self.device = ( "cuda:0" if torch.cuda.is_available() else "cpu" ) # "cuda" # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1' etc., or try 'mps' on macbooks self.CKPT_PT = f"{self.run_name}.pt" self.SNAPSHOT_PT = f"snapshot_{self.run_name}.pt" def _init_ddp_if_possible(self): # various inits, derived attributes, I/O setup self.ddp = int(os.environ.get("RANK", -1)) != -1 # is this a ddp run? if self.ddp: logger.info(f"Using ddp!") init_process_group(backend="nccl") self.ddp_rank = int(os.environ["RANK"]) self.ddp_local_rank = int(os.environ["LOCAL_RANK"]) self.ddp_world_size = int(os.environ["WORLD_SIZE"]) logger.info(f"{self.ddp_rank}, {self.ddp_local_rank},{self.ddp_world_size}") self.device = f"cuda:{self.ddp_local_rank}" torch.cuda.set_device(self.device) self.master_process = ( self.ddp_rank == 0 ) # this process will do logging, checkpointing etc. logger.info(f"Is master process {self.device}? {self.master_process}") self.seed_offset = self.ddp_rank # each process gets a different seed # world_size number of processes will be training simultaneously, so we can scale # down the desired gradient accumulation iterations per process proportionally assert ( self.train_conf.optimizer_conf.gradient_accumulation_steps % self.ddp_world_size == 0 ) self.train_conf.optimizer_conf.gradient_accumulation_steps //= ( self.ddp_world_size ) else: # if not ddp, we are running on a single gpu, and one process self.master_process = True self.seed_offset = 0 self.ddp_world_size = 1 def _init_train(self): self.tokens_per_iter = ( self.train_conf.optimizer_conf.gradient_accumulation_steps * self.ddp_world_size * self.train_conf.loader_conf.batch_size * self.train_conf.loader_conf.max_seq_len ) if self.master_process: logger.info(f"tokens per iteration will be: {self.tokens_per_iter:,}") logger.info( f"breaks down as: {self.train_conf.optimizer_conf.gradient_accumulation_steps} grad accum steps * {self.ddp_world_size} processes * {self.train_conf.loader_conf.batch_size} batch size * {self.train_conf.loader_conf.max_seq_len } max seq len" ) if self.master_process: os.makedirs(self.train_conf.io_conf.out_dir, exist_ok=True) torch.manual_seed(1337 + self.seed_offset) np.random.seed(1337 + self.seed_offset) torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn self.device_type = ( "cuda" if "cuda" in self.device else "cpu" ) # for later use in torch.autocast # note: float16 data type will automatically use a GradScaler ptdtype = { "float32": torch.float32, "bfloat16": torch.bfloat16, "float16": torch.float16, }[self.dtype] self.ctx = ( nullcontext() if self.device_type == "cpu" else torch.amp.autocast(device_type=self.device_type, dtype=ptdtype) ) # task-specific setup
task = {"smiles": SmilesTask}[self.train_conf.loader_conf.dataset]
6
2023-11-28 09:50:31+00:00
12k
kiharalab/Distance-AF
Train/train.py
[ { "identifier": "DistAF_Dataset", "path": "Dataset/dataset.py", "snippet": "class DistAF_Dataset(Dataset):\n\n def __init__(self, args=None):\n self.train_file = args.target_file\n\n with open(self.train_file, 'r') as f:\n self.targets = f.read().splitlines()\n \n s...
from torch.utils.data import DataLoader from Dataset.dataset import DistAF_Dataset from Model.Dist_AF import Dist_AF_IPA from Loss.backbone_loss import backbone_loss from Loss.sidechain_loss import sidechain_loss_dis from Loss.openfold_loss import compute_renamed_ground_truth, supervised_chi_loss,find_structural_violations,violation_loss from train_utils.feats import atom14_to_atom37 from protein_utils import protein from utils import rmsd from utils.set_seed import set_seed from train_utils.collate import collate_fn from torch.cuda.amp import autocast, GradScaler from torch.utils.checkpoint import checkpoint as ckpt import torch.optim as optim import torch import os import numpy as np import functools import gc
9,589
#results = val(args, model, val_dataloader) gt_keys = ['all_atom_positions', 'all_atom_mask', 'atom14_atom_exists', 'atom14_gt_exists', 'atom14_gt_positions', 'residx_atom14_to_atom37', 'residx_atom37_to_atom14', 'atom37_atom_exists', 'atom14_alt_gt_positions', 'atom14_alt_gt_exists', 'atom14_atom_is_ambiguous', 'residue_index'] gt_frames_keys = ['rigidgroups_gt_frames', 'rigidgroups_gt_exists', 'rigidgroups_group_exists', 'rigidgroups_group_is_ambiguous', 'rigidgroups_alt_gt_frames', 'torsion_angles_sin_cos', 'alt_torsion_angles_sin_cos', 'torsion_angles_mask', 'chi_angles_sin_cos', 'chi_mask', 'seq_mask'] for epoch in range(starting_epoch + 1,args.epochs+1): for step, (batch,target) in enumerate(train_dataloader): optimizer.zero_grad() embedding = batch['embed'] domain_window = batch['domain_window'].squeeze(0) dist_constraint = batch['dist_constraint'].squeeze(0) single_repr_batch = batch['single_representation'] aatype_batch = batch["aatype"] batch_gt = {key: batch[key] for key in gt_keys} batch_gt_frames = {key: batch[key] for key in gt_frames_keys} batch_gt.update({'seq_length': batch['seq_length']}) resolution = batch['resolution'] representation = None if args.cuda: embedding = embedding.to(args.device_id) resolution = resolution.to(args.device_id) for key in batch_gt.keys(): batch_gt[key] = batch_gt[key].to(args.device_id) for key in batch_gt_frames.keys(): batch_gt_frames[key] = batch_gt_frames[key].to(args.device_id) single_repr_batch = single_repr_batch.to(args.device_id) #coords_batch = coords_batch.cuda(args.device_id) #masks_batch = masks_batch.cuda(args.device_id) aatype_batch = aatype_batch.to(args.device_id) domain_window = domain_window.to(args.device_id) dist_constraint = dist_constraint.to(args.device_id) dummy = torch.Tensor(1) dummy.requires_grad = True if args.use_checkpoint: def run_ckpt(model,embedding, single_repr_batch, aatype_batch, batch_gt_frames,dummy): return model(embedding, single_repr_batch, aatype_batch, batch_gt_frames) translation, outputs, pred_frames = ckpt(run_ckpt,model,embedding, single_repr_batch, aatype_batch, batch_gt_frames,dummy) else: translation, outputs, pred_frames = model(embedding, single_repr_batch, aatype_batch, batch_gt_frames) #compute all needed loss bb_loss, dis_loss = backbone_loss( backbone_affine_tensor=batch_gt_frames["rigidgroups_gt_frames"][..., 0, :, :], backbone_affine_mask=batch_gt_frames['rigidgroups_gt_exists'][..., 0], traj=pred_frames, dis_gt=dist_constraint, mask_window=domain_window ) rename =compute_renamed_ground_truth(batch_gt, outputs['positions'][-1]) sc_loss = sidechain_loss_dis( sidechain_frames=outputs['sidechain_frames'], sidechain_atom_pos=outputs['positions'], rigidgroups_gt_frames=batch_gt_frames['rigidgroups_gt_frames'], rigidgroups_alt_gt_frames=batch_gt_frames['rigidgroups_alt_gt_frames'], rigidgroups_gt_exists=batch_gt_frames['rigidgroups_gt_exists'], renamed_atom14_gt_positions=rename['renamed_atom14_gt_positions'], renamed_atom14_gt_exists=rename['renamed_atom14_gt_exists'], alt_naming_is_better=rename['alt_naming_is_better'], dis_gt=dist_constraint, dist_window=domain_window ) angle_loss = supervised_chi_loss(outputs['angles'], outputs['unnormalized_angles'], aatype=aatype_batch, seq_mask=batch_gt_frames['seq_mask'], chi_mask=batch_gt_frames['chi_mask'], chi_angles_sin_cos=batch_gt_frames['chi_angles_sin_cos'], chi_weight=0.5, angle_norm_weight=0.01, dist=args.dist ) batch_gt.update({'aatype': aatype_batch}) violation = find_structural_violations(batch_gt, outputs['positions'][-1], violation_tolerance_factor=12, clash_overlap_tolerance=1.5) violation_loss_ = violation_loss(violation, batch_gt['atom14_atom_exists']) vio_loss = torch.mean(violation_loss_) #print(violation_loss_) seq_len = torch.mean(batch_gt["seq_length"].float()) crop_len = torch.tensor(aatype_batch.shape[-1]).to(device=aatype_batch.device) if dis_loss > 10.0: fape = 12 * dis_loss * args.dist_weight + (bb_loss+ sc_loss + vio_loss + angle_loss ) * torch.sqrt(min(seq_len, crop_len)) elif dis_loss > 5.0 and dis_loss < 10.0: fape = 24 * dis_loss * args.dist_weight + ( bb_loss+ sc_loss + vio_loss+ angle_loss ) * torch.sqrt(min(seq_len, crop_len)) else: if args.loose_dist and dis_loss < 1.0: fape = 12 * dis_loss * args.dist_weight + (bb_loss+ sc_loss + vio_loss + angle_loss ) * torch.sqrt(min(seq_len, crop_len)) else: fape = 48 * dis_loss * args.dist_weight + (bb_loss + sc_loss + vio_loss+ angle_loss ) * torch.sqrt(min(seq_len, crop_len)) positions = outputs['positions'][-1] del bb_loss, dis_loss, sc_loss, vio_loss, angle_loss, violation_loss_, outputs del pred_frames, translation gc.collect() torch.cuda.empty_cache() print(f"Epoch:{epoch}, FAPE loss:{fape.item()}") fape.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1) optimizer.step() # save model checkpoint if args.val_epochs > 0 and epoch % args.val_epochs == 0 and epoch > 0: epoch_output_dir = os.path.join(target_output_dir, f"checkpoint-{epoch}-{epoch}") if not os.path.exists(epoch_output_dir): os.makedirs(epoch_output_dir) checkpoint = {'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'epoch': epoch, 'rng_state': torch.get_rng_state()} torch.save(checkpoint, os.path.join(epoch_output_dir, "checkpoint.pth")) torch.save(model.state_dict(), os.path.join(epoch_output_dir, "model_state_dict.pt")) torch.save(optimizer.state_dict(), os.path.join(epoch_output_dir, "optimizer.pt")) #save predicted pdb for each evaluted epoch
def train(args): set_seed(args) with open(args.target_file, 'r') as f: target_name = f.read().splitlines()[0] target_output_dir = os.path.join(args.output_dir,target_name) if not os.path.exists(target_output_dir): os.makedirs(target_output_dir) train_dataset = DistAF_Dataset(args) args.training_examples = len(train_dataset) collate = functools.partial(collate_fn, args=args) train_dataloader = DataLoader(train_dataset, batch_size=args.batch, shuffle=True, num_workers=args.num_workers, collate_fn=collate) model = Dist_AF_IPA(args) optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay) model.to(args.device_id) if args.model_dir: optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay) # optimizer.load_state_dict( # torch.load(f'{args.model_dir}/optimizer.pt', map_location=f'{device}:{args.device_id}') # ) if os.path.exists(f'{args.model_dir}/checkpoint.pth'): checkpoint = torch.load(f'{args.model_dir}/checkpoint.pth', map_location=args.device_id) model.load_state_dict(checkpoint['model_state_dict']) optimizer_state_dict = checkpoint['optimizer_state_dict'] optimizer.load_state_dict(optimizer_state_dict) starting_epoch = checkpoint['epoch'] # rng_state = checkpoint['rng_state'] # torch.set_rng_state(rng_state) else: starting_epoch = 0 model.load_state_dict(torch.load(f'{args.model_dir}/model_state_dict.pt', map_location=args.device_id)) optimizer_state_dict = torch.load(f'{args.model_dir}/optimizer.pt', map_location=args.device_id) for key in optimizer_state_dict.keys(): optimizer_state_dict[key] = optimizer_state_dict[key].to(args.device_id) if isinstance(optimizer_state_dict[key], torch.Tensor) else optimizer_state_dict[key] optimizer.load_state_dict(optimizer_state_dict) print(f'Checkpoints (model and optimizer) loaded from {args.model_dir}') else: starting_epoch = 0 print("----------------- Starting Training ---------------") print(" Num examples = %d" % (int(args.training_examples))) print(" Num Epochs = %d" % (int(args.epochs))) print(" Batch Size = %d" % (int(args.batch))) model.train() #casp_results = test(args, model, test_dataloader) #results = val(args, model, val_dataloader) gt_keys = ['all_atom_positions', 'all_atom_mask', 'atom14_atom_exists', 'atom14_gt_exists', 'atom14_gt_positions', 'residx_atom14_to_atom37', 'residx_atom37_to_atom14', 'atom37_atom_exists', 'atom14_alt_gt_positions', 'atom14_alt_gt_exists', 'atom14_atom_is_ambiguous', 'residue_index'] gt_frames_keys = ['rigidgroups_gt_frames', 'rigidgroups_gt_exists', 'rigidgroups_group_exists', 'rigidgroups_group_is_ambiguous', 'rigidgroups_alt_gt_frames', 'torsion_angles_sin_cos', 'alt_torsion_angles_sin_cos', 'torsion_angles_mask', 'chi_angles_sin_cos', 'chi_mask', 'seq_mask'] for epoch in range(starting_epoch + 1,args.epochs+1): for step, (batch,target) in enumerate(train_dataloader): optimizer.zero_grad() embedding = batch['embed'] domain_window = batch['domain_window'].squeeze(0) dist_constraint = batch['dist_constraint'].squeeze(0) single_repr_batch = batch['single_representation'] aatype_batch = batch["aatype"] batch_gt = {key: batch[key] for key in gt_keys} batch_gt_frames = {key: batch[key] for key in gt_frames_keys} batch_gt.update({'seq_length': batch['seq_length']}) resolution = batch['resolution'] representation = None if args.cuda: embedding = embedding.to(args.device_id) resolution = resolution.to(args.device_id) for key in batch_gt.keys(): batch_gt[key] = batch_gt[key].to(args.device_id) for key in batch_gt_frames.keys(): batch_gt_frames[key] = batch_gt_frames[key].to(args.device_id) single_repr_batch = single_repr_batch.to(args.device_id) #coords_batch = coords_batch.cuda(args.device_id) #masks_batch = masks_batch.cuda(args.device_id) aatype_batch = aatype_batch.to(args.device_id) domain_window = domain_window.to(args.device_id) dist_constraint = dist_constraint.to(args.device_id) dummy = torch.Tensor(1) dummy.requires_grad = True if args.use_checkpoint: def run_ckpt(model,embedding, single_repr_batch, aatype_batch, batch_gt_frames,dummy): return model(embedding, single_repr_batch, aatype_batch, batch_gt_frames) translation, outputs, pred_frames = ckpt(run_ckpt,model,embedding, single_repr_batch, aatype_batch, batch_gt_frames,dummy) else: translation, outputs, pred_frames = model(embedding, single_repr_batch, aatype_batch, batch_gt_frames) #compute all needed loss bb_loss, dis_loss = backbone_loss( backbone_affine_tensor=batch_gt_frames["rigidgroups_gt_frames"][..., 0, :, :], backbone_affine_mask=batch_gt_frames['rigidgroups_gt_exists'][..., 0], traj=pred_frames, dis_gt=dist_constraint, mask_window=domain_window ) rename =compute_renamed_ground_truth(batch_gt, outputs['positions'][-1]) sc_loss = sidechain_loss_dis( sidechain_frames=outputs['sidechain_frames'], sidechain_atom_pos=outputs['positions'], rigidgroups_gt_frames=batch_gt_frames['rigidgroups_gt_frames'], rigidgroups_alt_gt_frames=batch_gt_frames['rigidgroups_alt_gt_frames'], rigidgroups_gt_exists=batch_gt_frames['rigidgroups_gt_exists'], renamed_atom14_gt_positions=rename['renamed_atom14_gt_positions'], renamed_atom14_gt_exists=rename['renamed_atom14_gt_exists'], alt_naming_is_better=rename['alt_naming_is_better'], dis_gt=dist_constraint, dist_window=domain_window ) angle_loss = supervised_chi_loss(outputs['angles'], outputs['unnormalized_angles'], aatype=aatype_batch, seq_mask=batch_gt_frames['seq_mask'], chi_mask=batch_gt_frames['chi_mask'], chi_angles_sin_cos=batch_gt_frames['chi_angles_sin_cos'], chi_weight=0.5, angle_norm_weight=0.01, dist=args.dist ) batch_gt.update({'aatype': aatype_batch}) violation = find_structural_violations(batch_gt, outputs['positions'][-1], violation_tolerance_factor=12, clash_overlap_tolerance=1.5) violation_loss_ = violation_loss(violation, batch_gt['atom14_atom_exists']) vio_loss = torch.mean(violation_loss_) #print(violation_loss_) seq_len = torch.mean(batch_gt["seq_length"].float()) crop_len = torch.tensor(aatype_batch.shape[-1]).to(device=aatype_batch.device) if dis_loss > 10.0: fape = 12 * dis_loss * args.dist_weight + (bb_loss+ sc_loss + vio_loss + angle_loss ) * torch.sqrt(min(seq_len, crop_len)) elif dis_loss > 5.0 and dis_loss < 10.0: fape = 24 * dis_loss * args.dist_weight + ( bb_loss+ sc_loss + vio_loss+ angle_loss ) * torch.sqrt(min(seq_len, crop_len)) else: if args.loose_dist and dis_loss < 1.0: fape = 12 * dis_loss * args.dist_weight + (bb_loss+ sc_loss + vio_loss + angle_loss ) * torch.sqrt(min(seq_len, crop_len)) else: fape = 48 * dis_loss * args.dist_weight + (bb_loss + sc_loss + vio_loss+ angle_loss ) * torch.sqrt(min(seq_len, crop_len)) positions = outputs['positions'][-1] del bb_loss, dis_loss, sc_loss, vio_loss, angle_loss, violation_loss_, outputs del pred_frames, translation gc.collect() torch.cuda.empty_cache() print(f"Epoch:{epoch}, FAPE loss:{fape.item()}") fape.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1) optimizer.step() # save model checkpoint if args.val_epochs > 0 and epoch % args.val_epochs == 0 and epoch > 0: epoch_output_dir = os.path.join(target_output_dir, f"checkpoint-{epoch}-{epoch}") if not os.path.exists(epoch_output_dir): os.makedirs(epoch_output_dir) checkpoint = {'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'epoch': epoch, 'rng_state': torch.get_rng_state()} torch.save(checkpoint, os.path.join(epoch_output_dir, "checkpoint.pth")) torch.save(model.state_dict(), os.path.join(epoch_output_dir, "model_state_dict.pt")) torch.save(optimizer.state_dict(), os.path.join(epoch_output_dir, "optimizer.pt")) #save predicted pdb for each evaluted epoch
final_pos = atom14_to_atom37(positions, batch_gt)
8
2023-12-01 03:48:10+00:00
12k
kai-wen-yang/QVix
models/instruct_blip/models/blip2_models/blip2_t5.py
[ { "identifier": "registry", "path": "models/instruct_blip/common/registry.py", "snippet": "class Registry:\n def register_model(cls, name):\n def wrap(model_cls):\n def register_processor(cls, name):\n def wrap(processor_cls):\n def register_lr_scheduler(cls, name):\n def w...
import logging import torch import torch.nn as nn import spacy from torch.cuda.amp import autocast as autocast from transformers import T5TokenizerFast from ...common.registry import registry from .blip2 import Blip2Base, disabled_train from .modeling_t5 import T5Config, T5ForConditionalGeneration
7,514
""" Copyright (c) 2023, salesforce.com, inc. All rights reserved. SPDX-License-Identifier: BSD-3-Clause For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause """ @registry.register_model("blip2_t5") class Blip2T5(Blip2Base): """ BLIP2 T5 model. Supported model types: - pretrain_flant5xl: pretrained model with FlanT5-XL - pretrain_flant5xl_vitL: pretrained model with FlanT5-XL - pretrain_flant5xxl: pretrained model with FlanT5-XXL - caption_coco_flant5xl: fintuned image captioning model with FlanT5-XL Usage: >>> from lavis.models import load_model >>> model = load_model("blip2_t5", "pretrain_flant5xl") """ PRETRAINED_MODEL_CONFIG_DICT = { "pretrain_flant5xl": "configs/models/blip2/blip2_pretrain_flant5xl.yaml", "pretrain_flant5xl_vitL": "configs/models/blip2/blip2_pretrain_flant5xl_vitL.yaml", "pretrain_flant5xxl": "configs/models/blip2/blip2_pretrain_flant5xxl.yaml", "caption_coco_flant5xl": "configs/models/blip2/blip2_caption_flant5xl.yaml", } def __init__( self, vit_model="eva_clip_g", img_size=224, drop_path_rate=0, use_grad_checkpoint=False, vit_precision="fp16", freeze_vit=True, num_query_token=32, t5_model="google/flan-t5-xl", prompt="", max_txt_len=32, apply_lemmatizer=False, ): """ apply_lemmatizer: when set to True, postprocess predict_answers() result with lemmas. """ super().__init__() self.tokenizer = self.init_tokenizer() self.visual_encoder, self.ln_vision = self.init_vision_encoder( vit_model, img_size, drop_path_rate, use_grad_checkpoint, vit_precision ) if freeze_vit: for name, param in self.visual_encoder.named_parameters(): param.requires_grad = False self.visual_encoder = self.visual_encoder.eval() self.visual_encoder.train = disabled_train logging.info("freeze vision encoder") self.Qformer, self.query_tokens = self.init_Qformer( num_query_token, self.visual_encoder.num_features ) self.Qformer.cls = None self.Qformer.bert.embeddings.word_embeddings = None self.Qformer.bert.embeddings.position_embeddings = None for layer in self.Qformer.bert.encoder.layer: layer.output = None layer.intermediate = None self.t5_tokenizer = T5TokenizerFast.from_pretrained(t5_model)
""" Copyright (c) 2023, salesforce.com, inc. All rights reserved. SPDX-License-Identifier: BSD-3-Clause For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause """ @registry.register_model("blip2_t5") class Blip2T5(Blip2Base): """ BLIP2 T5 model. Supported model types: - pretrain_flant5xl: pretrained model with FlanT5-XL - pretrain_flant5xl_vitL: pretrained model with FlanT5-XL - pretrain_flant5xxl: pretrained model with FlanT5-XXL - caption_coco_flant5xl: fintuned image captioning model with FlanT5-XL Usage: >>> from lavis.models import load_model >>> model = load_model("blip2_t5", "pretrain_flant5xl") """ PRETRAINED_MODEL_CONFIG_DICT = { "pretrain_flant5xl": "configs/models/blip2/blip2_pretrain_flant5xl.yaml", "pretrain_flant5xl_vitL": "configs/models/blip2/blip2_pretrain_flant5xl_vitL.yaml", "pretrain_flant5xxl": "configs/models/blip2/blip2_pretrain_flant5xxl.yaml", "caption_coco_flant5xl": "configs/models/blip2/blip2_caption_flant5xl.yaml", } def __init__( self, vit_model="eva_clip_g", img_size=224, drop_path_rate=0, use_grad_checkpoint=False, vit_precision="fp16", freeze_vit=True, num_query_token=32, t5_model="google/flan-t5-xl", prompt="", max_txt_len=32, apply_lemmatizer=False, ): """ apply_lemmatizer: when set to True, postprocess predict_answers() result with lemmas. """ super().__init__() self.tokenizer = self.init_tokenizer() self.visual_encoder, self.ln_vision = self.init_vision_encoder( vit_model, img_size, drop_path_rate, use_grad_checkpoint, vit_precision ) if freeze_vit: for name, param in self.visual_encoder.named_parameters(): param.requires_grad = False self.visual_encoder = self.visual_encoder.eval() self.visual_encoder.train = disabled_train logging.info("freeze vision encoder") self.Qformer, self.query_tokens = self.init_Qformer( num_query_token, self.visual_encoder.num_features ) self.Qformer.cls = None self.Qformer.bert.embeddings.word_embeddings = None self.Qformer.bert.embeddings.position_embeddings = None for layer in self.Qformer.bert.encoder.layer: layer.output = None layer.intermediate = None self.t5_tokenizer = T5TokenizerFast.from_pretrained(t5_model)
t5_config = T5Config.from_pretrained(t5_model)
3
2023-12-04 03:28:21+00:00
12k
hhd-dev/hhd
src/hhd/__main__.py
[ { "identifier": "set_log_plugin", "path": "src/hhd/logging.py", "snippet": "def set_log_plugin(plugin: str = \"main\"):\n global _main\n with _lock:\n _plugins[get_ident()] = plugin\n _main = plugin" }, { "identifier": "setup_logger", "path": "src/hhd/logging.py", "sn...
import argparse import fcntl import logging import os import signal import subprocess import sys import pkg_resources import hashlib import random from os.path import join from threading import Condition from threading import Event as TEvent from threading import RLock from time import sleep from typing import Sequence from .logging import set_log_plugin, setup_logger, update_log_plugins from .plugins import ( Config, Emitter, Event, HHDAutodetect, HHDPlugin, HHDSettings, load_relative_yaml, ) from .plugins.settings import ( Validator, get_default_state, load_blacklist_yaml, load_profile_yaml, load_state_yaml, merge_settings, save_blacklist_yaml, save_profile_yaml, get_settings_hash, save_state_yaml, validate_config, ) from .utils import expanduser, fix_perms, get_context, switch_priviledge from importlib.metadata import version from .http import HHDHTTPServer
7,460
# Save new blacklist file save_blacklist_yaml(blacklist_fn, detector_names, blacklist) fix_perms(blacklist_fn, ctx) logger.info(f"Found plugin providers: {', '.join(list(detectors))}") for name, autodetect in detectors.items(): plugins[name] = autodetect([]) plugin_str = "Loaded the following plugins:" for pkg_name, sub_plugins in plugins.items(): if not sub_plugins: continue plugin_str += ( f"\n - {pkg_name:>8s}: {', '.join(p.name for p in sub_plugins)}" ) logger.info(plugin_str) # Get sorted plugins sorted_plugins: Sequence[HHDPlugin] = [] for plugs in plugins.values(): sorted_plugins.extend(plugs) sorted_plugins.sort(key=lambda x: x.priority) validator: Validator = lambda tags, config, value: any( p.validate(tags, config, value) for p in sorted_plugins ) if not sorted_plugins: logger.error(f"No plugins started, exiting...") return # Open plugins lock = RLock() cond = Condition(lock) emit = EmitHolder(cond) for p in sorted_plugins: set_log_plugin(getattr(p, "log") if hasattr(p, "log") else "ukwn") p.open(emit, ctx) update_log_plugins() set_log_plugin("main") # Compile initial configuration state_fn = expanduser(join(CONFIG_DIR, "state.yml"), ctx) token_fn = expanduser(join(CONFIG_DIR, "token"), ctx) settings: HHDSettings = {} shash = None # Load profiles profiles = {} templates = {} conf = Config({}) profile_dir = expanduser(join(CONFIG_DIR, "profiles"), ctx) os.makedirs(profile_dir, exist_ok=True) fix_perms(profile_dir, ctx) # Monitor config files for changes should_initialize = TEvent() initial_run = True should_exit = TEvent() signal.signal(signal.SIGPOLL, notifier(should_initialize, cond)) signal.signal(signal.SIGINT, notifier(should_exit, cond)) signal.signal(signal.SIGTERM, notifier(should_exit, cond)) while not should_exit.is_set(): # # Configuration # # Initialize if files changed if should_initialize.is_set() or initial_run: # wait a bit to allow other processes to save files if not initial_run: sleep(POLL_DELAY) initial_run = False set_log_plugin("main") logger.info(f"Reloading configuration.") # Settings hhd_settings = {"hhd": load_relative_yaml("settings.yml")} # TODO: Improve check try: if "venv" not in exe_python: del hhd_settings["hhd"]["version"]["children"]["update_stable"] del hhd_settings["hhd"]["version"]["children"]["update_beta"] except Exception as e: logger.warning(f"Could not hide update settings. Error:\n{e}") settings = merge_settings( [*[p.settings() for p in sorted_plugins], hhd_settings] ) shash = get_settings_hash(hhd_settings) # State new_conf = load_state_yaml(state_fn, settings) if not new_conf: if conf.conf: logger.warning(f"Using previous configuration.") else: logger.info(f"Using default configuration.") conf = get_default_state(settings) else: conf = new_conf try: conf["hhd.version.version"] = version("hhd") except Exception: pass # Profiles profiles = {} templates = {} os.makedirs(profile_dir, exist_ok=True) fix_perms(profile_dir, ctx) for fn in os.listdir(profile_dir): if not fn.endswith(".yml"): continue name = fn.replace(".yml", "") s = load_profile_yaml(join(profile_dir, fn)) if s:
logger = logging.getLogger(__name__) CONFIG_DIR = os.environ.get("HHD_CONFIG_DIR", "~/.config/hhd") ERROR_DELAY = 5 POLL_DELAY = 2 class EmitHolder(Emitter): def __init__(self, condition: Condition) -> None: self._events = [] self._condition = condition def __call__(self, event: Event | Sequence[Event]) -> None: with self._condition: if isinstance(event, Sequence): self._events.extend(event) else: self._events.append(event) self._condition.notify_all() def get_events(self, timeout: int = -1) -> Sequence[Event]: with self._condition: if not self._events and timeout != -1: self._condition.wait() ev = self._events self._events = [] return ev def has_events(self): with self._condition: return bool(self._events) def notifier(ev: TEvent, cond: Condition): def _inner(sig, frame): with cond: ev.set() cond.notify_all() return _inner def print_token(ctx): token_fn = expanduser(join(CONFIG_DIR, "token"), ctx) try: with open(token_fn, "r") as f: token = f.read().strip() logger.info(f'Current HHD token (for user "{ctx.name}") is: "{token}"') except Exception as e: logger.error(f"Token not found or could not be read, error:\n{e}") logger.info( "Enable the http endpoint to generate a token automatically.\n" + "Or place it under '~/.config/hhd/token' manually.\n" + "'chown 600 ~/.config/hhd/token' for security reasons!" ) def main(): parser = argparse.ArgumentParser( prog="HHD: Handheld Daemon main interface.", description="Handheld Daemon is a daemon for managing the quirks inherent in handheld devices.", ) parser.add_argument( "-u", "--user", default=None, help="The user whose home directory will be used to store the files (~/.config/hhd).", dest="user", ) parser.add_argument( "command", nargs="*", default=[], help="The command to run. If empty, run as daemon. Right now, only the command token is supported.", ) args = parser.parse_args() user = args.user # Setup temporary logger for permission retrieval ctx = get_context(user) if not ctx: print(f"Could not get user information. Exiting...") return detectors: dict[str, HHDAutodetect] = {} plugins: dict[str, Sequence[HHDPlugin]] = {} cfg_fds = [] # HTTP data https = None prev_http_cfg = None updated = False # Check we are in a virtual environment # TODO: Improve exe_python = sys.executable try: # Create nested hhd dir # This might mess up permissions in upward directories # So try to deescalate hhd_dir = expanduser(CONFIG_DIR, ctx) try: switch_priviledge(ctx, False) os.makedirs(hhd_dir, exist_ok=True) switch_priviledge(ctx, True) fix_perms(hhd_dir, ctx) except Exception: pass # Remove old dir try: os.rename( join(hhd_dir, "plugins"), join(hhd_dir, "plugins_old_USE_STATEYML") ) except Exception: pass set_log_plugin("main") setup_logger(join(CONFIG_DIR, "log"), ctx=ctx) if args.command: if args.command[0] == "token": print_token(ctx) return else: logger.error(f"Command '{args.command[0]}' is unknown. Ignoring...") # Use blacklist blacklist_fn = join(hhd_dir, "plugins.yml") blacklist = load_blacklist_yaml(blacklist_fn) logger.info(f"Running autodetection...") detector_names = [] for autodetect in pkg_resources.iter_entry_points("hhd.plugins"): name = autodetect.name detector_names.append(name) if name in blacklist: logger.info(f"Skipping blacklisted provider '{name}'.") else: detectors[autodetect.name] = autodetect.resolve() # Save new blacklist file save_blacklist_yaml(blacklist_fn, detector_names, blacklist) fix_perms(blacklist_fn, ctx) logger.info(f"Found plugin providers: {', '.join(list(detectors))}") for name, autodetect in detectors.items(): plugins[name] = autodetect([]) plugin_str = "Loaded the following plugins:" for pkg_name, sub_plugins in plugins.items(): if not sub_plugins: continue plugin_str += ( f"\n - {pkg_name:>8s}: {', '.join(p.name for p in sub_plugins)}" ) logger.info(plugin_str) # Get sorted plugins sorted_plugins: Sequence[HHDPlugin] = [] for plugs in plugins.values(): sorted_plugins.extend(plugs) sorted_plugins.sort(key=lambda x: x.priority) validator: Validator = lambda tags, config, value: any( p.validate(tags, config, value) for p in sorted_plugins ) if not sorted_plugins: logger.error(f"No plugins started, exiting...") return # Open plugins lock = RLock() cond = Condition(lock) emit = EmitHolder(cond) for p in sorted_plugins: set_log_plugin(getattr(p, "log") if hasattr(p, "log") else "ukwn") p.open(emit, ctx) update_log_plugins() set_log_plugin("main") # Compile initial configuration state_fn = expanduser(join(CONFIG_DIR, "state.yml"), ctx) token_fn = expanduser(join(CONFIG_DIR, "token"), ctx) settings: HHDSettings = {} shash = None # Load profiles profiles = {} templates = {} conf = Config({}) profile_dir = expanduser(join(CONFIG_DIR, "profiles"), ctx) os.makedirs(profile_dir, exist_ok=True) fix_perms(profile_dir, ctx) # Monitor config files for changes should_initialize = TEvent() initial_run = True should_exit = TEvent() signal.signal(signal.SIGPOLL, notifier(should_initialize, cond)) signal.signal(signal.SIGINT, notifier(should_exit, cond)) signal.signal(signal.SIGTERM, notifier(should_exit, cond)) while not should_exit.is_set(): # # Configuration # # Initialize if files changed if should_initialize.is_set() or initial_run: # wait a bit to allow other processes to save files if not initial_run: sleep(POLL_DELAY) initial_run = False set_log_plugin("main") logger.info(f"Reloading configuration.") # Settings hhd_settings = {"hhd": load_relative_yaml("settings.yml")} # TODO: Improve check try: if "venv" not in exe_python: del hhd_settings["hhd"]["version"]["children"]["update_stable"] del hhd_settings["hhd"]["version"]["children"]["update_beta"] except Exception as e: logger.warning(f"Could not hide update settings. Error:\n{e}") settings = merge_settings( [*[p.settings() for p in sorted_plugins], hhd_settings] ) shash = get_settings_hash(hhd_settings) # State new_conf = load_state_yaml(state_fn, settings) if not new_conf: if conf.conf: logger.warning(f"Using previous configuration.") else: logger.info(f"Using default configuration.") conf = get_default_state(settings) else: conf = new_conf try: conf["hhd.version.version"] = version("hhd") except Exception: pass # Profiles profiles = {} templates = {} os.makedirs(profile_dir, exist_ok=True) fix_perms(profile_dir, ctx) for fn in os.listdir(profile_dir): if not fn.endswith(".yml"): continue name = fn.replace(".yml", "") s = load_profile_yaml(join(profile_dir, fn)) if s:
validate_config(s, settings, validator, use_defaults=False)
17
2023-11-30 21:44:04+00:00
12k
IDSIA/automated-cl
torchmeta_local/datasets/helpers_tabular.py
[ { "identifier": "Letter", "path": "torchmeta_local/datasets/letter.py", "snippet": "class Letter(CombinationMetaDataset):\n \"\"\"The Letter Image Recognition Dataset \"\"\"\n def __init__(self, root, num_classes_per_task=None, meta_train=False, meta_val=False, meta_test=False,\n m...
import warnings from torchmeta_local.datasets import Letter, PlantsTexture, PlantsShape, PlantsMargin, Bach from torchmeta_local.transforms import Categorical, ClassSplitter from torchmeta_local.transforms.tabular_transforms import NumpyToTorch
8,523
__all__ = [ 'letter', 'plants_texture', 'plants_shape', 'plants_margin', 'bach' ] def helper_with_default_tabular(klass, folder, shots, ways, shuffle=True, test_shots=None, seed=None, defaults=None, **kwargs): """ Parameters ---------- klass : CombinationMetaDataset the class corresponding to the meta-dataset, e.g., Covertype folder : string Root directory where the dataset folder exists, e.g., `covertype_task_id_2118`. shots : int Number of (training) examples per class in each task. This corresponds to `k` in `k-shot` classification. ways : int Number of classes per task. This corresponds to `N` in `N-way` classification. shuffle : bool (default: `True`) Shuffle the examples when creating the tasks. test_shots : int, optional Number of test examples per class in each task. If `None`, then the number of test examples is equal to the number of training examples per class. seed : int, optional Random seed to be used in the meta-dataset. kwargs Additional arguments passed to the `TieredImagenet` class. Returns ------- klass The meta-dataset with ClassSplitter applied, e.g., Covertype. """ if defaults is None: defaults = {} if 'num_classes_per_task' in kwargs: warnings.warn('Both arguments `ways` and `num_classes_per_task` were ' 'set in the helper function for the number of classes per task. ' 'Ignoring the argument `ways`.', stacklevel=2) ways = kwargs['num_classes_per_task'] if 'transform' not in kwargs: kwargs['transform'] = defaults.get('transform', NumpyToTorch()) if 'target_transform' not in kwargs: kwargs['target_transform'] = defaults.get('target_transform', Categorical(ways)) if 'class_augmentations' not in kwargs: kwargs['class_augmentations'] = defaults.get('class_augmentations', None) if test_shots is None: test_shots = shots dataset = klass(folder, num_classes_per_task=ways, **kwargs) dataset = ClassSplitter(dataset, shuffle=shuffle, num_train_per_class=shots, num_test_per_class=test_shots) dataset.seed(seed) return dataset def letter(folder: str, shots: int, ways: int, shuffle: bool=True, test_shots: int=None, seed: int=None, **kwargs) -> Letter: """ Wrapper that creates a meta-dataset for the Letter tabular dataset. Notes -------- Letter has 26 classes in total with default splits train/val/test : 15/5/6. See also -------- `datasets.Letter` : CombinationMetaDataset for the Letter dataset. """ return helper_with_default_tabular(Letter, folder, shots, ways, shuffle=shuffle, test_shots=test_shots, seed=seed, defaults=None, **kwargs) def plants_texture(folder: str, shots: int, ways: int, shuffle: bool=True, test_shots: int=None, seed: int=None, **kwargs) -> PlantsTexture: """ Wrapper that creates a meta-dataset for the PlantsTexture tabular dataset. Notes -------- PlantsTexture has 100 classes in total with default splits train/val/test : 70/15/15. See also -------- `datasets.PlantsTexture` : CombinationMetaDataset for the PlantsTexture dataset. """ return helper_with_default_tabular(PlantsTexture, folder, shots, ways, shuffle=shuffle, test_shots=test_shots, seed=seed, defaults=None, **kwargs) def plants_shape(folder: str, shots: int, ways: int, shuffle: bool=True,
__all__ = [ 'letter', 'plants_texture', 'plants_shape', 'plants_margin', 'bach' ] def helper_with_default_tabular(klass, folder, shots, ways, shuffle=True, test_shots=None, seed=None, defaults=None, **kwargs): """ Parameters ---------- klass : CombinationMetaDataset the class corresponding to the meta-dataset, e.g., Covertype folder : string Root directory where the dataset folder exists, e.g., `covertype_task_id_2118`. shots : int Number of (training) examples per class in each task. This corresponds to `k` in `k-shot` classification. ways : int Number of classes per task. This corresponds to `N` in `N-way` classification. shuffle : bool (default: `True`) Shuffle the examples when creating the tasks. test_shots : int, optional Number of test examples per class in each task. If `None`, then the number of test examples is equal to the number of training examples per class. seed : int, optional Random seed to be used in the meta-dataset. kwargs Additional arguments passed to the `TieredImagenet` class. Returns ------- klass The meta-dataset with ClassSplitter applied, e.g., Covertype. """ if defaults is None: defaults = {} if 'num_classes_per_task' in kwargs: warnings.warn('Both arguments `ways` and `num_classes_per_task` were ' 'set in the helper function for the number of classes per task. ' 'Ignoring the argument `ways`.', stacklevel=2) ways = kwargs['num_classes_per_task'] if 'transform' not in kwargs: kwargs['transform'] = defaults.get('transform', NumpyToTorch()) if 'target_transform' not in kwargs: kwargs['target_transform'] = defaults.get('target_transform', Categorical(ways)) if 'class_augmentations' not in kwargs: kwargs['class_augmentations'] = defaults.get('class_augmentations', None) if test_shots is None: test_shots = shots dataset = klass(folder, num_classes_per_task=ways, **kwargs) dataset = ClassSplitter(dataset, shuffle=shuffle, num_train_per_class=shots, num_test_per_class=test_shots) dataset.seed(seed) return dataset def letter(folder: str, shots: int, ways: int, shuffle: bool=True, test_shots: int=None, seed: int=None, **kwargs) -> Letter: """ Wrapper that creates a meta-dataset for the Letter tabular dataset. Notes -------- Letter has 26 classes in total with default splits train/val/test : 15/5/6. See also -------- `datasets.Letter` : CombinationMetaDataset for the Letter dataset. """ return helper_with_default_tabular(Letter, folder, shots, ways, shuffle=shuffle, test_shots=test_shots, seed=seed, defaults=None, **kwargs) def plants_texture(folder: str, shots: int, ways: int, shuffle: bool=True, test_shots: int=None, seed: int=None, **kwargs) -> PlantsTexture: """ Wrapper that creates a meta-dataset for the PlantsTexture tabular dataset. Notes -------- PlantsTexture has 100 classes in total with default splits train/val/test : 70/15/15. See also -------- `datasets.PlantsTexture` : CombinationMetaDataset for the PlantsTexture dataset. """ return helper_with_default_tabular(PlantsTexture, folder, shots, ways, shuffle=shuffle, test_shots=test_shots, seed=seed, defaults=None, **kwargs) def plants_shape(folder: str, shots: int, ways: int, shuffle: bool=True,
test_shots: int=None, seed: int=None, **kwargs) -> PlantsShape:
2
2023-11-30 20:07:46+00:00
12k
tosiyuki/LLaVA-JP
train_llava.py
[ { "identifier": "conversation", "path": "llava/conversation.py", "snippet": "class SeparatorStyle(Enum):\nclass Conversation:\n SINGLE = auto()\n PLAIN = auto()\n TWO = auto()\n W, H = image.size\n H, W = longest_edge, shortest_edge\n ...
import os import pathlib import torch import transformers from typing import Dict from llava import conversation as conversation_lib from llava.model.llava_gpt2 import LlavaGpt2ForCausalLM from llava.model.llava_gpt_neox import LlavaGptNeoxForCausalLM from llava.model.llava_llama import LlavaLlamaForCausalLM from llava.train.dataset import LazySupervisedDataset, DataCollatorForSupervisedDataset from llava.train.arguments_dataclass import ModelArguments, DataArguments, TrainingArguments from llava.train.llava_trainer import LLaVATrainer from transformers import BitsAndBytesConfig from peft import prepare_model_for_kbit_training from peft import LoraConfig, get_peft_model from peft.tuners.lora import LoraLayer
7,573
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 make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict: """Make dataset and collator for supervised fine-tuning.""" train_dataset = LazySupervisedDataset(tokenizer=tokenizer, data_path=data_args.data_path, data_args=data_args) data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer) return dict(train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator) def train(): global local_rank parser = transformers.HfArgumentParser( (ModelArguments, DataArguments, TrainingArguments)) model_args, data_args, training_args = parser.parse_args_into_dataclasses() local_rank = training_args.local_rank compute_dtype = (torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) bnb_model_from_pretrained_args = {} if training_args.bits in [4, 8]: bnb_model_from_pretrained_args.update(dict( device_map="auto", load_in_4bit=training_args.bits == 4, load_in_8bit=training_args.bits == 8, quantization_config=BitsAndBytesConfig( load_in_4bit=training_args.bits == 4, load_in_8bit=training_args.bits == 8, llm_int8_skip_modules=["mm_projector"], llm_int8_threshold=6.0, llm_int8_has_fp16_weight=False, bnb_4bit_compute_dtype=compute_dtype, bnb_4bit_use_double_quant=training_args.double_quant, bnb_4bit_quant_type=training_args.quant_type # {'fp4', 'nf4'} ) )) if model_args.base_model == "gpt2": model = LlavaGpt2ForCausalLM.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, **bnb_model_from_pretrained_args ) elif model_args.base_model == "gpt_neox": model = LlavaGptNeoxForCausalLM.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, **bnb_model_from_pretrained_args ) elif model_args.base_model == "llama": model = LlavaLlamaForCausalLM.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, **bnb_model_from_pretrained_args ) else: print(f"{model_args.base_model} is not found") exit(-1) model.config.use_cache = False if model_args.freeze_backbone: model.model.requires_grad_(False) if training_args.bits in [4, 8]: model.config.torch_dtype=(torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing) if training_args.gradient_checkpointing: # Adapterの重みを調整するときに使うみたい if hasattr(model, "enable_input_require_grads"): model.enable_input_require_grads() if training_args.lora_enable: print("target_modules") if model_args.base_model == "gpt2": target_modules = ["c_attn"] elif model_args.base_model == "gpt_neox": target_modules = ["query_key_value"] elif model_args.base_model == "llama": target_modules = find_all_linear_names(model) else: print(f"{model_args.base_model} is not found") exit(-1) lora_config = LoraConfig( r=training_args.lora_r, lora_alpha=training_args.lora_alpha, target_modules=target_modules, lora_dropout=training_args.lora_dropout, bias=training_args.lora_bias, task_type="CAUSAL_LM", ) if training_args.bits == 16: if training_args.bf16: model.to(torch.bfloat16) if training_args.fp16: model.to(torch.float16) rank0_print("Adding LoRA adapters...") model = get_peft_model(model, lora_config) tokenizer = transformers.AutoTokenizer.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="right", use_fast=True, ) tokenizer.pad_token = tokenizer.unk_token
def rank0_print(*args): if local_rank == 0: print(*args) # Borrowed from peft.utils.get_peft_model_state_dict def get_peft_state(named_params, bias): if bias == "none": to_return = {k: t for k, t in named_params if "lora_" in k} elif bias == "all": to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k} elif bias == "lora_only": to_return = {} maybe_lora_bias = {} lora_bias_names = set() for k, t in named_params: if "lora_" in k: to_return[k] = t bias_name = k.split("lora_")[0] + "bias" lora_bias_names.add(bias_name) elif "bias" in k: maybe_lora_bias[k] = t for k, t in maybe_lora_bias: if bias_name in lora_bias_names: to_return[bias_name] = t else: raise NotImplementedError to_return = {k: v.detach().cpu().clone() for k, v in to_return.items()} return to_return def get_peft_state_non_lora(named_params, require_grad_only=True): to_return = {k: t for k, t in named_params if "lora_" not in k} if require_grad_only: to_return = {k: t for k, t in to_return.items() if t.requires_grad} to_return = {k: v.detach().cpu().clone() for k, v in to_return.items()} return to_return def get_mm_adapter_state(named_params, keys_to_match): to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)} to_return = {k: v.detach().cpu().clone() for k, v in to_return.items()} return to_return def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str): """Collects the state dict and dump to disk.""" if getattr(trainer.args, "tune_mm_mlp_adapter", False): # Only save Adapter keys_to_match = ['mm_projector'] if getattr(trainer.args, "use_im_start_end", False): keys_to_match.extend(['embed_tokens', 'embed_in']) weight_to_save = get_mm_adapter_state(trainer.model.named_parameters(), keys_to_match) trainer.model.config.save_pretrained(output_dir) current_folder = output_dir.split('/')[-1] parent_folder = os.path.dirname(output_dir) if trainer.args.local_rank == 0 or trainer.args.local_rank == -1: if current_folder.startswith('checkpoint-'): mm_projector_folder = os.path.join(parent_folder, "mm_projector") os.makedirs(mm_projector_folder, exist_ok=True) torch.save(weight_to_save, os.path.join(mm_projector_folder, f'{current_folder}.bin')) else: torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin')) return state_dict = trainer.model.state_dict() if trainer.args.should_save: cpu_state_dict = { key: value.cpu() for key, value in state_dict.items() } del state_dict trainer._save(output_dir, state_dict=cpu_state_dict) # noqa def find_all_linear_names(model): cls = torch.nn.Linear lora_module_names = set() multimodal_keywords = ['mm_projector', 'vision_tower', 'vision_resampler'] for name, module in model.named_modules(): if any(mm_keyword in name for mm_keyword in multimodal_keywords): continue 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 make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict: """Make dataset and collator for supervised fine-tuning.""" train_dataset = LazySupervisedDataset(tokenizer=tokenizer, data_path=data_args.data_path, data_args=data_args) data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer) return dict(train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator) def train(): global local_rank parser = transformers.HfArgumentParser( (ModelArguments, DataArguments, TrainingArguments)) model_args, data_args, training_args = parser.parse_args_into_dataclasses() local_rank = training_args.local_rank compute_dtype = (torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) bnb_model_from_pretrained_args = {} if training_args.bits in [4, 8]: bnb_model_from_pretrained_args.update(dict( device_map="auto", load_in_4bit=training_args.bits == 4, load_in_8bit=training_args.bits == 8, quantization_config=BitsAndBytesConfig( load_in_4bit=training_args.bits == 4, load_in_8bit=training_args.bits == 8, llm_int8_skip_modules=["mm_projector"], llm_int8_threshold=6.0, llm_int8_has_fp16_weight=False, bnb_4bit_compute_dtype=compute_dtype, bnb_4bit_use_double_quant=training_args.double_quant, bnb_4bit_quant_type=training_args.quant_type # {'fp4', 'nf4'} ) )) if model_args.base_model == "gpt2": model = LlavaGpt2ForCausalLM.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, **bnb_model_from_pretrained_args ) elif model_args.base_model == "gpt_neox": model = LlavaGptNeoxForCausalLM.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, **bnb_model_from_pretrained_args ) elif model_args.base_model == "llama": model = LlavaLlamaForCausalLM.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, **bnb_model_from_pretrained_args ) else: print(f"{model_args.base_model} is not found") exit(-1) model.config.use_cache = False if model_args.freeze_backbone: model.model.requires_grad_(False) if training_args.bits in [4, 8]: model.config.torch_dtype=(torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing) if training_args.gradient_checkpointing: # Adapterの重みを調整するときに使うみたい if hasattr(model, "enable_input_require_grads"): model.enable_input_require_grads() if training_args.lora_enable: print("target_modules") if model_args.base_model == "gpt2": target_modules = ["c_attn"] elif model_args.base_model == "gpt_neox": target_modules = ["query_key_value"] elif model_args.base_model == "llama": target_modules = find_all_linear_names(model) else: print(f"{model_args.base_model} is not found") exit(-1) lora_config = LoraConfig( r=training_args.lora_r, lora_alpha=training_args.lora_alpha, target_modules=target_modules, lora_dropout=training_args.lora_dropout, bias=training_args.lora_bias, task_type="CAUSAL_LM", ) if training_args.bits == 16: if training_args.bf16: model.to(torch.bfloat16) if training_args.fp16: model.to(torch.float16) rank0_print("Adding LoRA adapters...") model = get_peft_model(model, lora_config) tokenizer = transformers.AutoTokenizer.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="right", use_fast=True, ) tokenizer.pad_token = tokenizer.unk_token
conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version]
4
2023-12-01 03:26:16+00:00
12k
jags111/ComfyUI_Jags_Audiotools
SampleDiffusion.py
[ { "identifier": "load_audio", "path": "libs/util/util.py", "snippet": "def load_audio(device, audio_path: str, sample_rate):\n \n if not os.path.exists(audio_path):\n raise RuntimeError(f\"Audio file not found: {audio_path}\")\n\n audio, file_sample_rate = torchaudio.load(audio_path)\n\n...
import subprocess, sys, os import torch import random import folder_paths import importlib import yaml import numpy as np import pandas as pd import matplotlib.pyplot as plt import audio_diffusion_pytorch import diffusion import folder_paths as comfy_paths import k_diffusion import soundfile as sf import torchaudio import hashlib from pathlib import Path from io import BytesIO from server import PromptServer from aiohttp import web from folder_paths import models_dir, get_filename_list from comfy.model_management import get_torch_device from libs.util.util import load_audio, crop_audio from libs.dance_diffusion.api import RequestHandler, Request, ModelType from libs.diffusion_library.sampler import SamplerType from libs.diffusion_library.scheduler import SchedulerType from libs.dance_diffusion.dd.model import DDModelWrapper from libs.dance_diffusion.dd.inference import DDInference from scipy.fft import fft from pydub import AudioSegment from itertools import cycle from pygame import mixer from pygame import mixer
9,223
"id_string": ("STRING", {"default": 'ComfyUI'}), "tame": (['Enabled', 'Disabled'],) }, "optional": { }, } RETURN_TYPES = ("STRING", "AUDIO") RETURN_NAMES = ("path","🎙️audio" ) FUNCTION = "audio_save" OUTPUT_NODE = True CATEGORY = "🎙️Jags_Audio" def audio_save(self, audio, output_path=None, filename_prefix="ComfyUI", filename_delimiter='_', filename_number_padding=4, filename_number_start='false', sample_rate='_', id_string='_', tame='Enabled'): delimiter = filename_delimiter number_padding = filename_number_padding if filename_number_padding > 1 else 4 return (SaveAudio(audio_out=(0.5 * audio).clamp(-1,1) if(tame == 'Enabled') else audio, output_path=output_path, sample_rate=sample_rate, id_str=id_string), ) class LoadAudio(): @classmethod def INPUT_TYPES(s): audio_extensions = ['mp3','wav'] input_dir = folder_paths.get_input_directory() files = [] for f in os.listdir(input_dir): if os.path.isfile(os.path.join(input_dir, f)): file_parts = f.split('.') if len(file_parts) > 1 and (file_parts[-1] in audio_extensions): files.append(f) return { "required": { "audio": (sorted(files),), "sample_rate": ("INT", {"default": 44100, "min": 1, "max": 10000000000, "step": 1}), }, "optional": { }, } RETURN_TYPES = ("AUDIO", "INT" ) RETURN_NAMES = ("🎙️audio","sample_rate") FUNCTION = "LoadAudio" OUTPUT_NODE = True CATEGORY = "🎙️Jags_Audio" def LoadAudio(self, audio,): file = folder_paths.get_annotated_filepath(audio) # TODO: support more formats if (file.lower().endswith('.mp3')): audio_file = AudioSegment.from_mp3(file) else: audio_file = AudioSegment.from_file(file, format="wav") audio_data = AudioData(audio_file) return (audio_data,) #file_path = f'{comfy_dir}/custom_nodes/SampleDiffusion/audio_input/{file_path}' @classmethod def IS_CHANGED(self, audio, **kwargs): audio_path = folder_paths.get_annotated_filepath(audio) m = hashlib.sha256() with open(audio_path, 'rb') as f: m.update(f.read()) return m.digest().hex() @classmethod def VALIDATE_INPUTS(self, audio, **kwargs): if not folder_paths.exists_annotated_filepath(audio): return "Invalid audio file: {}".format(audio) return True """ alternates """ #-------------------------------------------------------------------------------- class LoadAudioModelDD(): @classmethod def INPUT_TYPES(cls): """ Input Types """ global models_folder models = os.listdir(models_folder) models = [x for x in models if x.endswith('.ckpt')] return { "required": { "" "model": (models, {}), "chunk_size": ("INT", {"default": 65536, "min": 32768, "max": 10000000000, "step": 32768}), "sample_rate": ("INT", {"default": 44100, "min": 1, "max": 10000000000, "step": 1}), "optimize_memory_use": (['Enabled', 'Disabled'], {"default": 'Enabled'}), "autocast": (['Enabled', 'Disabled'], {"default": 'Enabled'}), }, "optional": { }, } RETURN_TYPES = ("DD_MODEL", ) RETURN_NAMES = ("audio_model", ) FUNCTION = "DoLoadAudioModelDD" OUTPUT_NODE = True CATEGORY = "🎙️Jags_Audio/Audiotools" def DoLoadAudioModelDD(self, model, chunk_size, sample_rate, optimize_memory_use, autocast): global models_folder model = os.path.join(models_folder, model) device = get_torch_device() wrapper = DDModelWrapper() wrapper.load(model, device, optimize_memory_use, chunk_size, sample_rate)
# Imports #import v_diffusion_pytorch def get_comfy_dir(): dirs = __file__.split('\\') comfy_index = None for i, dir in enumerate(dirs): if dir == "ComfyUI": comfy_index = i break if comfy_index is not None: # Join the list up to the "ComfyUI" folder return '\\'.join(dirs[:comfy_index+1]) else: return None comfy_dir = get_comfy_dir() # **************************************************************************** PromptServer.instance.app._client_max_size = 250 * 1024 * 1024 # 250 MB # Add route for getting audio, duplicates view image but allows audio_input """ @PromptServer.instance.routes.get("/ComfyUI_Jags_Audiotools/audio") async def view_image(request): if "filename" in request.rel_url.query: type = request.rel_url.query.get("type", "audio_input") if type not in ["output", "input", "temp", "audio_input"]: return web.Response(status=400) output_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), type) if "subfolder" in request.rel_url.query: full_output_dir = os.path.join(output_dir, request.rel_url.query["subfolder"]) if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir: return web.Response(status=403) output_dir = full_output_dir filename = request.rel_url.query["filename"] filename = os.path.basename(filename) file = os.path.join(output_dir, filename) if os.path.isfile(file): return web.FileResponse(file, headers={"Content-Disposition": f"filename=\"{filename}\""}) return web.Response(status=404) """ config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "config.yaml") if not os.path.exists(config): with open(config, "w") as f: yaml.dump({"model_folder": f"{os.path.join(models_dir, 'audio_diffusion')}"}, f) with open(config, "r") as f: config = yaml.safe_load(f) models_folder = config["model_folder"] # init and sample_diffusion lib load libs = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "libs") #if not os.path.exists(os.path.join(comfy_dir, 'custom_nodes/ComfyUI_Jags_Audiotools/libs')): #os.makedirs(os.path.join(comfy_dir, 'custom_nodes/ComfyUI_Jags_Audiotools/libs')) #libs = os.path.join(comfy_dir, 'custom_nodes/ComfyUI_Jags_Audiotools/libs') #if not os.path.exists(os.path.join(comfy_dir, libs)): # os.system (os.path.join(comfy_dir, libs)) #sys.path.append(os.path.join(comfy_dir, libs )) # PIL to Tensor def pil2tensor(image): return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0) # **************************************************************************** # sound play functionality for audio nodes # needs further testing def save_audio(audio_out, output_path: str, sample_rate, id_str:str = None): out_files = [] if not os.path.exists(output_path): os.makedirs(output_path) ix = 1 for sample in audio_out: while True: output_file = os.path.join(output_path, f"sample_{id_str}_{ix}.wav" if id_str else f"sample_{ix}.wav") if not os.path.exists(output_file): break ix += 1 open(output_file, "a").close() output = sample.cpu() torchaudio.save(output_file, output, sample_rate) out_files.append(output_file) ix += 1 return out_files os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide" try: except ModuleNotFoundError: # install pixelsort in current venv subprocess.check_call([sys.executable, "-m", "pip", "install", "pygame"]) mixer.init() def PlaySound(path, volume): mixer.music.load(path) mixer.music.set_volume(volume) mixer.music.play() #testing the audio file for playback # **************************************************************************** # * NODES * # **************************************************************************** class AudioData: def __init__(self, audio_file) -> None: # Extract the sample rate sample_rate = audio_file.frame_rate # Get the number of audio channels num_channels = audio_file.channels # Extract the audio data as a NumPy array audio_data = np.array(audio_file.get_array_of_samples()) self.audio_data = audio_data self.sample_rate = sample_rate self.num_channels = num_channels def get_channel_audio_data(self, channel: int): if channel < 0 or channel >= self.num_channels: raise IndexError(f"Channel '{channel}' out of range. total channels is '{self.num_channels}'.") return self.audio_data[channel::self.num_channels] def get_channel_fft(self, channel: int): audio_data = self.get_channel_audio_data(channel) return fft(audio_data) class AudioFFTData: def __init__(self, audio_data, sample_rate) -> None: self.fft = fft(audio_data) self.length = len(self.fft) self.frequency_bins = np.fft.fftfreq(self.length, 1 / sample_rate) def get_max_amplitude(self): return np.max(np.abs(self.fft)) def get_normalized_fft(self) -> float: max_amplitude = self.get_max_amplitude() return np.abs(self.fft) / max_amplitude def get_indices_for_frequency_bands(self, lower_band_range: int, upper_band_range: int): return np.where((self.frequency_bins >= lower_band_range) & (self.frequency_bins < upper_band_range)) def __len__(self): return self.length # **************************************************************************** class AudioInference(): def __init__(self): pass @classmethod def INPUT_TYPES(cls): """ Input Types """ return { "required": { "audio_model": ("DD_MODEL", ), "mode": (['Generation', 'Variation'],), "batch_size": ("INT", {"default": 1, "min": 1, "max": 10000000000, "step": 1}), "steps": ("INT", {"default": 50, "min": 1, "max": 10000000000, "step": 1}), "sampler": (SamplerType._member_names_, {"default": "V_IPLMS"}), "sigma_min": ("FLOAT", {"default": 0.1, "min": 0.0, "max": 1280, "step": 0.01}), "sigma_max": ("FLOAT", {"default": 50, "min": 0.0, "max": 1280, "step": 0.01}), "rho": ("FLOAT", {"default": 0.7, "min": 0.0, "max": 128.0, "step": 0.01}), "scheduler": (SchedulerType._member_names_, {"default": "V_CRASH"}), "noise_level": ("FLOAT", {"default": 0.7, "min": 0.0, "max": 1.0, "step": 0.01}), "seed": ("INT", {"default": -1}), }, "optional": { "input_audio": ("AUDIO", {}), "input_audio_path": ("STRING", {"default": '', "forceInput": True}), }, } RETURN_TYPES = ("LIST", "AUDIO", "INT") RETURN_NAMES = ("out_paths", "🎙️audio", "sample_rate") FUNCTION = "do_sample" CATEGORY = "🎙️Jags_Audio/AudioInference" def do_sample(self, audio_model, mode, batch_size, steps, sampler, sigma_min, sigma_max, rho, scheduler, input_audio_path='', input_audio=None, noise_level=0.7, seed=-1): wrapper, inference = audio_model device_type_accelerator = get_torch_device() device_accelerator = torch.device(device_type_accelerator) device_offload = get_torch_device() crop = lambda audio: crop_audio(audio, wrapper.chunk_size, 0) if input_tensor is None: input_audio_path = None if input_audio_path == '' else input_audio_path load_input = lambda source: crop(load_audio(device_accelerator, source, wrapper.sample_rate)) if source is not None else None audio_source = load_input(input_audio_path) else: if len(input_tensor.shape) == 3: # remove first (batch) dimension input_tensor = input_tensor[0] if input_tensor.shape[0] != 2: channels, sample_length = input_tensor.shape input_tensor = input_tensor.view(1, sample_length).repeat(2, 1) input_tensor = input_tensor.to(get_torch_device()) audio_source = crop(input_tensor) request_handler = RequestHandler(device_accelerator, device_offload, optimize_memory_use=False, use_autocast=True) seed = seed if(seed!=-1) else torch.randint(0, 4294967294, [1], device=device_type_accelerator).item() print(f"Using accelerator: {device_type_accelerator}, Seed: {seed}.") request = Request( request_type=mode, model_path=wrapper.path, model_type=ModelType.DD, model_chunk_size=wrapper.chunk_size, model_sample_rate=wrapper.sample_rate, model_wrapper=wrapper, model_inference=inference, seed=seed, batch_size=batch_size, audio_source=audio_source, audio_target=None, mask=None, noise_level=noise_level, interpolation_positions=None, resamples=None, keep_start=True, steps=steps, sampler_type=SamplerType[sampler], sampler_args={'use_tqdm': True}, scheduler_type=SchedulerType[scheduler], scheduler_args={ 'sigma_min': sigma_min, 'sigma_max': sigma_max, 'rho': rho, } ) response = request_handler.process_request(request)#, lambda **kwargs: print(f"{kwargs['step'] / kwargs['x']}")) paths = save_audio(response.result, f"{comfy_dir}/temp", wrapper.sample_rate, f"{seed}_{random.randint(0, 100000)}") return (paths, response.result, wrapper.sample_rate) class SaveAudio(): def __init__(self): self.output_dir = comfy_paths.output_directory self.type = os.path.basename(self.output_dir) @classmethod def INPUT_TYPES(cls): """ Save Audio files """ return { "required": { "audio": ("AUDIO", ), "output_path": ("STRING", {"default": '[time(%Y-%m-%d)]', "multiline": False}), "filename_prefix": ("STRING", {"default": "ComfyUI"}), "filename_delimiter": ("STRING", {"default":"_"}), "filename_number_padding": ("INT", {"default":4, "min":1, "max":9, "step":1}), "filename_number_start": (["false", "true"],), "sample_rate": ("INT", {"default": 44100, "min": 1, "max": 10000000000, "step": 1}), "id_string": ("STRING", {"default": 'ComfyUI'}), "tame": (['Enabled', 'Disabled'],) }, "optional": { }, } RETURN_TYPES = ("STRING", "AUDIO") RETURN_NAMES = ("path","🎙️audio" ) FUNCTION = "audio_save" OUTPUT_NODE = True CATEGORY = "🎙️Jags_Audio" def audio_save(self, audio, output_path=None, filename_prefix="ComfyUI", filename_delimiter='_', filename_number_padding=4, filename_number_start='false', sample_rate='_', id_string='_', tame='Enabled'): delimiter = filename_delimiter number_padding = filename_number_padding if filename_number_padding > 1 else 4 return (SaveAudio(audio_out=(0.5 * audio).clamp(-1,1) if(tame == 'Enabled') else audio, output_path=output_path, sample_rate=sample_rate, id_str=id_string), ) class LoadAudio(): @classmethod def INPUT_TYPES(s): audio_extensions = ['mp3','wav'] input_dir = folder_paths.get_input_directory() files = [] for f in os.listdir(input_dir): if os.path.isfile(os.path.join(input_dir, f)): file_parts = f.split('.') if len(file_parts) > 1 and (file_parts[-1] in audio_extensions): files.append(f) return { "required": { "audio": (sorted(files),), "sample_rate": ("INT", {"default": 44100, "min": 1, "max": 10000000000, "step": 1}), }, "optional": { }, } RETURN_TYPES = ("AUDIO", "INT" ) RETURN_NAMES = ("🎙️audio","sample_rate") FUNCTION = "LoadAudio" OUTPUT_NODE = True CATEGORY = "🎙️Jags_Audio" def LoadAudio(self, audio,): file = folder_paths.get_annotated_filepath(audio) # TODO: support more formats if (file.lower().endswith('.mp3')): audio_file = AudioSegment.from_mp3(file) else: audio_file = AudioSegment.from_file(file, format="wav") audio_data = AudioData(audio_file) return (audio_data,) #file_path = f'{comfy_dir}/custom_nodes/SampleDiffusion/audio_input/{file_path}' @classmethod def IS_CHANGED(self, audio, **kwargs): audio_path = folder_paths.get_annotated_filepath(audio) m = hashlib.sha256() with open(audio_path, 'rb') as f: m.update(f.read()) return m.digest().hex() @classmethod def VALIDATE_INPUTS(self, audio, **kwargs): if not folder_paths.exists_annotated_filepath(audio): return "Invalid audio file: {}".format(audio) return True """ alternates """ #-------------------------------------------------------------------------------- class LoadAudioModelDD(): @classmethod def INPUT_TYPES(cls): """ Input Types """ global models_folder models = os.listdir(models_folder) models = [x for x in models if x.endswith('.ckpt')] return { "required": { "" "model": (models, {}), "chunk_size": ("INT", {"default": 65536, "min": 32768, "max": 10000000000, "step": 32768}), "sample_rate": ("INT", {"default": 44100, "min": 1, "max": 10000000000, "step": 1}), "optimize_memory_use": (['Enabled', 'Disabled'], {"default": 'Enabled'}), "autocast": (['Enabled', 'Disabled'], {"default": 'Enabled'}), }, "optional": { }, } RETURN_TYPES = ("DD_MODEL", ) RETURN_NAMES = ("audio_model", ) FUNCTION = "DoLoadAudioModelDD" OUTPUT_NODE = True CATEGORY = "🎙️Jags_Audio/Audiotools" def DoLoadAudioModelDD(self, model, chunk_size, sample_rate, optimize_memory_use, autocast): global models_folder model = os.path.join(models_folder, model) device = get_torch_device() wrapper = DDModelWrapper() wrapper.load(model, device, optimize_memory_use, chunk_size, sample_rate)
inference = DDInference(device, device, optimize_memory_use, autocast, wrapper)
6
2023-11-28 09:09:59+00:00
12k
rafapablos/w4c23-rainai
train.py
[ { "identifier": "UNetModule", "path": "w4c23/models/unet/lightning.py", "snippet": "class UNetModule(BaseModule):\n def __init__(self, model_params: dict, params: dict):\n super().__init__(model_params, params)\n\n self.input_crop = model_params[\"input_crop\"]\n self.padding = m...
import os import torch import datetime import argparse import boto3 import pytorch_lightning as pl from pytorch_lightning.callbacks import ModelCheckpoint from torch.utils.data import DataLoader from pytorch_lightning import loggers as pl_loggers from pytorch_lightning.callbacks.early_stopping import EarlyStopping from w4c23.models.unet import UNetModule from w4c23.models.swin import SWINModule from w4c23.callbacks.log_metrics import LogMetrics from w4c23.callbacks.log_images import ImageLogger from w4c23.utils.data_utils import get_cuda_memory_usage, tensor_to_submission_file from w4c23.utils.config import load_config from w4c23.utils.w4c_dataloader import RainData
8,334
] if params["train"]["early_stopping"]: callback_funcs.append( EarlyStopping( monitor="val/loss", patience=params["train"]["patience"], mode="min" ) ) # Add metrics and image logging if params["experiment"]["logging"] != "none": callback_funcs.append( LogMetrics( num_leadtimes=params["model"]["forecast_length"], probabilistic=params["train"]["probabilistic"], buckets=params["model"]["buckets"], logging=params["experiment"]["logging"], ) ) callback_funcs.append(ImageLogger(params["experiment"]["logging"])) # Training accelerators accelerator = None if gpus[0] == -1: gpus = None else: accelerator = "cuda" print(f"====== process started on the following GPUs: {gpus} ======") trainer = pl.Trainer( devices=gpus, max_epochs=max_epochs, deterministic=params["model"]["deterministic"], logger=logger, callbacks=callback_funcs, precision=params["experiment"]["precision"], gradient_clip_val=params["model"]["gradient_clip_val"], gradient_clip_algorithm=params["model"]["gradient_clip_algorithm"], accelerator=accelerator, strategy="ddp_find_unused_parameters_false", profiler="simple", log_every_n_steps=5, accumulate_grad_batches=params["train"]["accumulate_grad_batches"] if "accumulate_grad_batches" in params["train"].keys() else 1, ) return trainer def do_predict(trainer, model, predict_params, test_data): scores = trainer.predict(model, dataloaders=test_data) scores = torch.concat(scores) tensor_to_submission_file(scores, predict_params) def do_val(trainer, model, val_data): scores = trainer.validate(model, dataloaders=val_data) print(scores[0]) def train(params, gpus, mode, checkpoint_path, model): """Main training/evaluation method.""" # Remove extra regions/years in predict mode and disable logging if mode == "predict": params["dataset"]["regions"] = [params["predict"]["region_to_predict"]] params["dataset"]["years"] = [params["predict"]["year_to_predict"]] params["experiment"]["logging"] = "none" # ------------ # Model & data # ------------ get_cuda_memory_usage(gpus) data = DataModule(params["dataset"], params["train"], mode) model = load_model(model, params, checkpoint_path) # ------------ # Trainer # ------------ trainer = get_trainer(gpus, params) # ------------ # Train & final validation # ------------ if mode == "train": print("------------------") print("--- TRAIN MODE ---") print("------------------") trainer.fit(model, data) # ------------ # Validation # ------------ if mode == "val": print("---------------------") print("--- VALIDATE MODE ---") print("---------------------") do_val(trainer, model, data.val_dataloader()) # ------------ # Prediction # ------------ if mode == "predict" or mode == "heldout": print("--------------------") print("--- PREDICT MODE ---") print("--------------------") print( "REGIONS: ", params["dataset"]["regions"], params["predict"]["region_to_predict"], ) if params["predict"]["region_to_predict"] not in params["dataset"]["regions"]: print( 'EXITING... "regions" and "regions to predict" must indicate the same region name in your config file.' ) else: do_predict(trainer, model, params["predict"], data.test_dataloader()) def update_params_based_on_args(options): config_p = os.path.join("configurations", options.config_path)
# Weather4cast 2023 Starter Kit # # This Starter Kit builds on and extends the Weather4cast 2022 Starter Kit, # the original license for which is included below. # # In line with the provisions of this license, all changes and additional # code are also released unde 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. # # Weather4cast 2022 Starter Kit # # Copyright (C) 2022 # Institute of Advanced Research in Artificial Intelligence (IARAI) # This file is part of the Weather4cast 2022 Starter Kit. # # The Weather4cast 2022 Starter Kit 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. # # The Weather4cast 2022 Starter Kit 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 this program. If not, see <http://www.gnu.org/licenses/>. # Contributors: Aleksandra Gruca, Pedro Herruzo, David Kreil, Stephen Moran pl.seed_everything(42, workers=True) class DataModule(pl.LightningDataModule): """Class to handle training/validation/predict/heldout splits.""" def __init__(self, params, training_params, mode): super().__init__() self.params = params self.training_params = training_params if mode in ["train"]: print("Loading TRAINING/VALIDATION dataset") self.train_ds = RainData("training", **self.params) self.val_ds = RainData("validation", **self.params) print(f"Training dataset size: {len(self.train_ds)}") if mode in ["val"]: print("Loading VALIDATION dataset") self.val_ds = RainData("validation", **self.params) if mode in ["predict"]: print("Loading PREDICTION/TEST dataset") self.test_ds = RainData("test", **self.params) if mode in ["heldout"]: print("Loading HELD-OUT dataset") self.test_ds = RainData("heldout", **self.params) def __load_dataloader(self, dataset, shuffle=True, pin=True): dl = DataLoader( dataset, batch_size=self.training_params["batch_size"], num_workers=self.training_params["n_workers"], shuffle=shuffle, pin_memory=pin, ) return dl def train_dataloader(self): return self.__load_dataloader(self.train_ds, shuffle=True, pin=True) def val_dataloader(self): return self.__load_dataloader(self.val_ds, shuffle=False, pin=True) def test_dataloader(self): return self.__load_dataloader(self.test_ds, shuffle=False, pin=True) def load_model(Model, params, checkpoint_path=""): """Load a model from a checkpoint or from scratch if checkpoint_path=''""" p = {**params["experiment"], **params["dataset"], **params["train"]} if checkpoint_path == "": print("-> Modelling from scratch! (no checkpoint loaded)") model = Model(params["model"], p) else: print(f"-> Loading model checkpoint: {checkpoint_path}") model = Model.load_from_checkpoint( checkpoint_path, model_params=params["model"], params=p ) return model def get_trainer(gpus, params): date_time = datetime.datetime.now().strftime("%m%d-%H:%M") version = params["experiment"]["name"] version = version + "_" + date_time max_epochs = params["train"]["max_epochs"] print("Training for", max_epochs, "epochs") # Set logger for wandb or tensorboard if params["experiment"]["logging"] == "wandb": # Get wandb key (this is only required for wandb logging in aws) if params["experiment"]["aws"]: client = boto3.client("ssm", region_name="eu-central-1") try: os.environ["WANDB_API_KEY"] = client.get_parameter( Name="salami-training-w4c23-wandb-api-key", WithDecryption=True )["Parameter"]["Value"] print("WandB should be running in online mode") except Exception as e: # pylint: disable=bare-except print(e) print("WandB could not get an API key and is running in offline mode") os.environ["WANDB_MODE"] = "offline" logger = pl_loggers.WandbLogger( project="w4c23", name=params["experiment"]["sub_folder"] + "_" + version, log_model="all", save_dir=params["experiment"]["experiment_folder"], ) elif params["experiment"]["logging"] == "tensorboard": logger = pl_loggers.TensorBoardLogger( save_dir=params["experiment"]["experiment_folder"], name=params["experiment"]["sub_folder"], version=version, log_graph=True, default_hp_metric=False, ) else: logger = False # Callbacks # Model saving and early stopping callback_funcs = [ ModelCheckpoint( monitor="val/loss", save_top_k=2, save_last=True, filename="epoch={epoch}-step={step}-val_loss={val/loss:.6f}", auto_insert_metric_name=False, ), ] if params["train"]["early_stopping"]: callback_funcs.append( EarlyStopping( monitor="val/loss", patience=params["train"]["patience"], mode="min" ) ) # Add metrics and image logging if params["experiment"]["logging"] != "none": callback_funcs.append( LogMetrics( num_leadtimes=params["model"]["forecast_length"], probabilistic=params["train"]["probabilistic"], buckets=params["model"]["buckets"], logging=params["experiment"]["logging"], ) ) callback_funcs.append(ImageLogger(params["experiment"]["logging"])) # Training accelerators accelerator = None if gpus[0] == -1: gpus = None else: accelerator = "cuda" print(f"====== process started on the following GPUs: {gpus} ======") trainer = pl.Trainer( devices=gpus, max_epochs=max_epochs, deterministic=params["model"]["deterministic"], logger=logger, callbacks=callback_funcs, precision=params["experiment"]["precision"], gradient_clip_val=params["model"]["gradient_clip_val"], gradient_clip_algorithm=params["model"]["gradient_clip_algorithm"], accelerator=accelerator, strategy="ddp_find_unused_parameters_false", profiler="simple", log_every_n_steps=5, accumulate_grad_batches=params["train"]["accumulate_grad_batches"] if "accumulate_grad_batches" in params["train"].keys() else 1, ) return trainer def do_predict(trainer, model, predict_params, test_data): scores = trainer.predict(model, dataloaders=test_data) scores = torch.concat(scores) tensor_to_submission_file(scores, predict_params) def do_val(trainer, model, val_data): scores = trainer.validate(model, dataloaders=val_data) print(scores[0]) def train(params, gpus, mode, checkpoint_path, model): """Main training/evaluation method.""" # Remove extra regions/years in predict mode and disable logging if mode == "predict": params["dataset"]["regions"] = [params["predict"]["region_to_predict"]] params["dataset"]["years"] = [params["predict"]["year_to_predict"]] params["experiment"]["logging"] = "none" # ------------ # Model & data # ------------ get_cuda_memory_usage(gpus) data = DataModule(params["dataset"], params["train"], mode) model = load_model(model, params, checkpoint_path) # ------------ # Trainer # ------------ trainer = get_trainer(gpus, params) # ------------ # Train & final validation # ------------ if mode == "train": print("------------------") print("--- TRAIN MODE ---") print("------------------") trainer.fit(model, data) # ------------ # Validation # ------------ if mode == "val": print("---------------------") print("--- VALIDATE MODE ---") print("---------------------") do_val(trainer, model, data.val_dataloader()) # ------------ # Prediction # ------------ if mode == "predict" or mode == "heldout": print("--------------------") print("--- PREDICT MODE ---") print("--------------------") print( "REGIONS: ", params["dataset"]["regions"], params["predict"]["region_to_predict"], ) if params["predict"]["region_to_predict"] not in params["dataset"]["regions"]: print( 'EXITING... "regions" and "regions to predict" must indicate the same region name in your config file.' ) else: do_predict(trainer, model, params["predict"], data.test_dataloader()) def update_params_based_on_args(options): config_p = os.path.join("configurations", options.config_path)
params = load_config(config_p)
6
2023-11-29 11:22:50+00:00
12k
Matrixeigs/UncertaintyManagementInteroperablePowerTransportationSystems
TestCasesMicrogrids/UnitCommitmentHybridACDC.py
[ { "identifier": "PBIC_A2D", "path": "TestCasesMicrogrids/idx_format_hybrid_AC_DC.py", "snippet": "PBIC_A2D = QUG + 1" }, { "identifier": "PBIC_D2A", "path": "TestCasesMicrogrids/idx_format_hybrid_AC_DC.py", "snippet": "PBIC_D2A = PBIC_A2D + 1" }, { "identifier": "PESS_CH0", "...
from TestCasesMicrogrids.idx_format_hybrid_AC_DC import PBIC_A2D, PBIC_D2A, PESS_CH0, PESS_DC0, PG0, PPV0, PUG, \ NX_MG, QBIC, QG0, QUG, NESS, NRES, EESS0, PAC, PDC from numpy import zeros, ones, concatenate, eye, tile, array from scipy.sparse import vstack, lil_matrix from Solvers.mixed_integer_solvers_cplex import mixed_integer_linear_programming as milp from StochasticOptimization.ccg_benders_decomposition import BendersDecomposition from random import random from TestCasesMicrogrids.cases_unit_commitment import micro_grid
7,294
c_ig[i] = mg["DG"][i]["FUEL"] * mg["DG"][i]["PMIN"] * mg["DG"][i]["FUEL_PRICE"] cg[i] = mg["DG"][i]["FUEL"] * mg["DG"][i]["FUEL_PRICE"] cfuel[i] = mg["DG"][i]["FUEL_PRICE"] # Formulate the boundaries lb = concatenate([tile(concatenate([alpha_l, beta_l, Ig_l, pg_l, rg_l, fuel_l]), T)]) ub = concatenate([tile(concatenate([alpha_u, beta_u, Ig_u, pg_u, rg_u, fuel_u]), T)]) # Objective value c = concatenate([tile(concatenate([c_alpha, c_beta, c_ig, cg, cr, cfuel]), T)]) # Variable types vtypes = (["b"] * ng * 3 + ["c"] * ng * 3) * 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 * self.PG + j] = 1 A[t * ng + j, t * _nv_first_stage + ng * self.RG + j] = 1 A[t * ng + j, t * _nv_first_stage + ng * self.IG + 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 * self.PG + j] = -1 A_temp[t * ng + j, t * _nv_first_stage + ng * self.RG + j] = 1 A_temp[t * ng + j, t * _nv_first_stage + ng * self.IG + 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 + ng * self.ALPHA + i] = 1 A_temp[sum(UP_LIMIT[0:i]) + t - MIN_UP[i], t * _nv_first_stage + ng * self.IG + 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 * self.BETA + i] = 1 A_temp[sum(DOWN_LIMIT[0:i]) + t - MIN_DOWN[i], t * _nv_first_stage + ng * self.IG + 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 + ng * self.ALPHA + i] = 1 Aeq[i * T + t, t * _nv_first_stage + ng * self.BETA + i] = -1 Aeq[i * T + t, t * _nv_first_stage + ng * self.IG + i] = -1 if t != 0: Aeq[i * T + t, (t - 1) * _nv_first_stage + ng * self.IG + i] = 1 else: beq[i * T + t] = -Ig0[i] model_first_stage = {"c": c.reshape((nv_first_stage, 1)), "lb": lb.reshape((nv_first_stage, 1)), "ub": ub.reshape((nv_first_stage, 1)), "vtypes": vtypes, "A": A.tolil(), "b": b.reshape((len(b), 1)), "Aeq": Aeq.tolil(), "beq": beq.reshape((len(beq), 1)), } # (sol_first_stage, obj_first_stage, 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 = self.first_stage_solution_validation(sol_first_stage) return model_first_stage def second_stage_problem_formulation(self, mg, u): """ Second-stage problem formulation for hybrid AC/DC MGs :param mg: :return: model of second stage problem, i.e., real-time scheduling of hybrid AC/DC microgrids """ T = self.T ng = self.ng ness = self.ness nres = self.nres nv_uncertainty = self.nv_uncertainty nv_first_stage = self.nv_first_stage self._nv_second_stage = NX_MG ## 1) boundary information and objective function _nv_second_stage = NX_MG nv_second_stage = NX_MG * T self.nv_second_stage = nv_second_stage lb = zeros(nv_second_stage) ub = zeros(nv_second_stage) c = zeros(nv_second_stage) q = zeros(nv_second_stage) vtypes = ["c"] * nv_second_stage for t in range(T): ## 1.1) lower boundary for i in range(ng): lb[t * NX_MG + PG0 + i] = 0 lb[t * NX_MG + QG0 + i] = mg["DG"][i]["QMIN"] lb[t * NX_MG + PUG] = 0 lb[t * NX_MG + QUG] = mg["UG"]["QMIN"] lb[t * NX_MG + PBIC_D2A] = 0
""" Unit commitment problem for hybrid AC/DC MGs @author: Zhao Tianyang @e-mail: matrixeigs@gmail.com Supporting documents: Resilient Energy Management for Hybrid AC/DC MGs """ class UnitCommitment(): """ Unit commitment problem for hybrid AC/DC MGs for stochastic optimization """ def __init__(self, mg): self.T = len(mg["PD"]["AC"]) self.ng = len(mg["DG"]) self.NX = NX_MG self.ness = NESS self.nres = NRES self.nv_uncertainty = self.T * 2 + self.T * NRES def stochastic_optimization(self, mg, ns=4): model_first_stage = self.first_stage_problem_formulation(mg=mg) # Formulate the second stage scenarios us = zeros((ns, self.nv_uncertainty)) ws = ones(ns) / ns for i in range(ns): us[i, 0: 2 * self.T] = concatenate([mg["PD"]["AC"], mg["PD"]["DC"]]) for j in range(self.nres): us[i, (2 + j) * self.T:(3 + j) * self.T] = concatenate([mg["PV"][j]["PROFILE"]]) u_mean = us[0, :] u_delta = us[0, :] * 0.1 for i in range(ns): for j in range(self.nv_uncertainty): us[i, j] += (2 * random() - 1) * u_delta[j] model_second_stage = [0] * ns for i in range(ns): model_second_stage[i] = self.second_stage_problem_formulation(mg=mg, u=us[i, :]) # # Merge the first-stage and second_stage problems lb = model_first_stage["lb"] ub = model_first_stage["ub"] vtypes = model_first_stage["vtypes"] c = model_first_stage["c"] 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 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"] b = model_first_stage["b"] for i in range(ns): if model_second_stage[i]["Geq"] is not None: neq_index[i + 1] = neq_index[i] + model_second_stage[i]["Geq"].shape[0] else: neq_index[i + 1] = neq_index[i] if model_second_stage[i]["G"] is not None: nineq_index[i + 1] = nineq_index[i] + model_second_stage[i]["G"].shape[0] else: nineq_index[i + 1] = nineq_index[i] nv_index[i + 1] = nv_index[i] + nv_second_stage c = concatenate([c, ws[i] * model_second_stage[i]["c"]]) lb = concatenate([lb, model_second_stage[i]["lb"]]) ub = concatenate([ub, model_second_stage[i]["ub"]]) vtypes += model_second_stage[i]["vtypes"] if model_second_stage[i]["Meq"] is not None: beq = concatenate([beq, model_second_stage[i]["heq"] - model_second_stage[i]["Meq"] * us[i, :].reshape( (self.nv_uncertainty, 1))]) if model_second_stage[i]["M"] is not None: b = concatenate([b, model_second_stage[i]["h"] - model_second_stage[i]["M"] * us[i, :].reshape( (self.nv_uncertainty, 1))]) Aeq_full = lil_matrix((neq_index[-1], nv_index[-1])) Aeq_full[0:neq_index[0], 0:nv_index[0]] = model_first_stage["Aeq"] for i in range(ns): # For the first stage Aeq_full[neq_index[i]:neq_index[i + 1], 0:nv_index[0]] = model_second_stage[i]["Eeq"] # For the second stage Aeq_full[neq_index[i]:neq_index[i + 1], nv_index[i]:nv_index[i + 1]] = model_second_stage[i]["Geq"] A_full = lil_matrix((nineq_index[-1], nv_index[-1])) 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]["E"] A_full[nineq_index[i]:nineq_index[i + 1], nv_index[i]:nv_index[i + 1]] = model_second_stage[i]["G"] # 3) Obtain the results for first-stage and second stage optimization problems # 3.1) Obtain the integrated solution (sol, obj, success) = milp(c, Aeq=Aeq_full.tolil(), beq=beq[:, 0], A=A_full.tolil(), b=b[:,0], xmin=lb[:,0], xmax=ub[:,0], vtypes=vtypes) # # 4) Verify the first-stage and second stage optization problem # # 4.1) First-stage solution sol_first_stage = sol[0:self.nv_second_stage] sol_first_stage = self.first_stage_solution_validation(sol=sol_first_stage) # 4.2) Second-stage solution sol_second_stage = {} for i in range(ns): sol_second_stage[i] = sol[int(nv_index[i]):int(nv_index[i + 1])] sol_second_stage_checked = {} for i in range(ns): sol_second_stage_checked[i] = self.second_stage_solution_validation(sol_second_stage[i]) return sol_first_stage, sol_second_stage_checked def first_stage_problem_formulation(self, mg): ng = self.ng self.ALPHA = 0 self.BETA = 1 self.IG = 2 self.PG = 3 self.RG = 4 self.FUEL = 5 T = self.T _nv_first_stage = ng * 6 nv_first_stage = _nv_first_stage * T self._nv_first_stage = _nv_first_stage self.nv_first_stage = nv_first_stage # Obtain the initial status, start-up and shut down of generators Ig0 = zeros(ng) MIN_DOWN = zeros(ng) MIN_UP = zeros(ng) for i in range(ng): Ig0[i] = mg["DG"][i]["I0"] MIN_DOWN[i] = mg["DG"][i]["MU"] MIN_UP[i] = mg["DG"][i]["MD"] Ig0 = Ig0.astype(int) MIN_DOWN = MIN_DOWN.astype(int) MIN_UP = MIN_UP.astype(int) # The decision variables includes the start-up, shut down, generator output, reserve capacity, fuel refilling plan 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) fuel_l = zeros(ng) alpha_u = ones(ng) beta_u = ones(ng) Ig_u = ones(ng) pg_u = zeros(ng) rg_u = zeros(ng) fuel_u = zeros(ng) c_alpha = zeros(ng) c_beta = zeros(ng) c_ig = zeros(ng) cg = zeros(ng) cr = zeros(ng) cfuel = zeros(ng) for i in range(ng): pg_u[i] = mg["DG"][i]["PMAX"] rg_u[i] = mg["DG"][i]["PMAX"] fuel_u[i] = mg["DG"][i]["TANK"] - mg["DG"][i]["TANK0"] c_ig[i] = mg["DG"][i]["FUEL"] * mg["DG"][i]["PMIN"] * mg["DG"][i]["FUEL_PRICE"] cg[i] = mg["DG"][i]["FUEL"] * mg["DG"][i]["FUEL_PRICE"] cfuel[i] = mg["DG"][i]["FUEL_PRICE"] # Formulate the boundaries lb = concatenate([tile(concatenate([alpha_l, beta_l, Ig_l, pg_l, rg_l, fuel_l]), T)]) ub = concatenate([tile(concatenate([alpha_u, beta_u, Ig_u, pg_u, rg_u, fuel_u]), T)]) # Objective value c = concatenate([tile(concatenate([c_alpha, c_beta, c_ig, cg, cr, cfuel]), T)]) # Variable types vtypes = (["b"] * ng * 3 + ["c"] * ng * 3) * 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 * self.PG + j] = 1 A[t * ng + j, t * _nv_first_stage + ng * self.RG + j] = 1 A[t * ng + j, t * _nv_first_stage + ng * self.IG + 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 * self.PG + j] = -1 A_temp[t * ng + j, t * _nv_first_stage + ng * self.RG + j] = 1 A_temp[t * ng + j, t * _nv_first_stage + ng * self.IG + 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 + ng * self.ALPHA + i] = 1 A_temp[sum(UP_LIMIT[0:i]) + t - MIN_UP[i], t * _nv_first_stage + ng * self.IG + 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 * self.BETA + i] = 1 A_temp[sum(DOWN_LIMIT[0:i]) + t - MIN_DOWN[i], t * _nv_first_stage + ng * self.IG + 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 + ng * self.ALPHA + i] = 1 Aeq[i * T + t, t * _nv_first_stage + ng * self.BETA + i] = -1 Aeq[i * T + t, t * _nv_first_stage + ng * self.IG + i] = -1 if t != 0: Aeq[i * T + t, (t - 1) * _nv_first_stage + ng * self.IG + i] = 1 else: beq[i * T + t] = -Ig0[i] model_first_stage = {"c": c.reshape((nv_first_stage, 1)), "lb": lb.reshape((nv_first_stage, 1)), "ub": ub.reshape((nv_first_stage, 1)), "vtypes": vtypes, "A": A.tolil(), "b": b.reshape((len(b), 1)), "Aeq": Aeq.tolil(), "beq": beq.reshape((len(beq), 1)), } # (sol_first_stage, obj_first_stage, 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 = self.first_stage_solution_validation(sol_first_stage) return model_first_stage def second_stage_problem_formulation(self, mg, u): """ Second-stage problem formulation for hybrid AC/DC MGs :param mg: :return: model of second stage problem, i.e., real-time scheduling of hybrid AC/DC microgrids """ T = self.T ng = self.ng ness = self.ness nres = self.nres nv_uncertainty = self.nv_uncertainty nv_first_stage = self.nv_first_stage self._nv_second_stage = NX_MG ## 1) boundary information and objective function _nv_second_stage = NX_MG nv_second_stage = NX_MG * T self.nv_second_stage = nv_second_stage lb = zeros(nv_second_stage) ub = zeros(nv_second_stage) c = zeros(nv_second_stage) q = zeros(nv_second_stage) vtypes = ["c"] * nv_second_stage for t in range(T): ## 1.1) lower boundary for i in range(ng): lb[t * NX_MG + PG0 + i] = 0 lb[t * NX_MG + QG0 + i] = mg["DG"][i]["QMIN"] lb[t * NX_MG + PUG] = 0 lb[t * NX_MG + QUG] = mg["UG"]["QMIN"] lb[t * NX_MG + PBIC_D2A] = 0
lb[t * NX_MG + PBIC_A2D] = 0
0
2023-11-27 15:57:53+00:00
12k
DongGeun-Yoon/DGDM
runners/BBDMRunner.py
[ { "identifier": "Registers", "path": "Register.py", "snippet": "class Registers:\n def __init__(self):\n raise RuntimeError(\"Registries is not intended to be instantiated\")\n\n datasets = Register('datasets')\n runners = Register('runners')" }, { "identifier": "BrownianBridgeMo...
import os import lpips import torch.optim.lr_scheduler import torch.nn.functional as F import time import imageio import pdb from torch.utils.data import DataLoader from PIL import Image from Register import Registers from model.BrownianBridgeModel import BrownianBridgeModel from runners.BaseRunner import BaseRunner from runners.utils import weights_init, get_dataset, make_dir, get_image_grid, save_single_image from runners.utils import AverageMeter, metric, save_single_video from runners.utils import * from tqdm.autonotebook import tqdm from torchsummary import summary
9,270
@Registers.runners.register_with_name('BBDMRunner') class BBDMRunner(BaseRunner): def __init__(self, config): super().__init__(config) def initialize_model(self, config): if config.model.model_type == "BBDM": bbdmnet = BrownianBridgeModel(config) else: raise NotImplementedError # initialize model try: bbdmnet.apply(weights_init) except: pass return bbdmnet def load_model_from_checkpoint(self): states = super().load_model_from_checkpoint() def print_model_summary(self, net): def get_parameter_number(model): total_num = sum(p.numel() for p in model.parameters()) trainable_num = sum(p.numel() for p in model.parameters() if p.requires_grad) return total_num, trainable_num total_num, trainable_num = get_parameter_number(net) print("Total Number of parameter: %.2fM" % (total_num / 1e6)) print("Trainable Number of parameter: %.2fM" % (trainable_num / 1e6)) def initialize_optimizer_scheduler(self, net, config): # diffusion model weight learning_params = [{'params':net.denoise_fn.parameters(), 'lr':config.model.BB.optimizer.lr}] # condition model weight if config.model.CondParams.train or config.model.CondParams.pretrained is None: learning_params.append({'params':net.cond_stage_model.parameters(), 'lr':config.model.CondParams.lr}) optimizer = torch.optim.Adam(learning_params, weight_decay=config.model.BB.optimizer.weight_decay, betas=(config.model.BB.optimizer.beta1, config.model.BB.optimizer.beta2) ) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer=optimizer, mode='min', verbose=True, threshold_mode='rel', **vars(config.model.BB.lr_scheduler) ) return [optimizer], [scheduler] @torch.no_grad() def get_checkpoint_states(self, stage='epoch_end'): model_states, optimizer_scheduler_states = super().get_checkpoint_states() return model_states, optimizer_scheduler_states def loss_fn(self, net, batch, epoch, step, opt_idx=0, stage='train', write=True): x, x_cond = batch loss, additional_info, cond = net(x, x_cond) if write: self.writer.add_scalar(f'loss/{stage}', loss, step) self.writer.add_scalar(f'loss/cond', cond, step) loss = loss + cond return loss @torch.no_grad() def sample(self, net, batch, sample_path, stage='train', write=True): sample_path = make_dir(os.path.join(sample_path, f'{stage}_sample')) x, x_cond = batch # batch_size = x.shape[0] if x.shape[0] < 4 else 4 batch_size = 1 x = x[0:1] x_cond = x_cond[0:1] grid_size = max(x.size(1), x_cond.size(1)) # save images sample = net.sample(x_cond, clip_denoised=self.config.testing.clip_denoised) sample, prediction = sample[0], sample[1] channels = ['ir105', 'sw038', 'wv063'] for z, channel in enumerate(channels): x_conds = x_cond[0,:, z:z+1] x_split = x[0,:, z:z+1] sample_split = sample[:, z:z+1] prediction_split = prediction[:, z:z+1]
@Registers.runners.register_with_name('BBDMRunner') class BBDMRunner(BaseRunner): def __init__(self, config): super().__init__(config) def initialize_model(self, config): if config.model.model_type == "BBDM": bbdmnet = BrownianBridgeModel(config) else: raise NotImplementedError # initialize model try: bbdmnet.apply(weights_init) except: pass return bbdmnet def load_model_from_checkpoint(self): states = super().load_model_from_checkpoint() def print_model_summary(self, net): def get_parameter_number(model): total_num = sum(p.numel() for p in model.parameters()) trainable_num = sum(p.numel() for p in model.parameters() if p.requires_grad) return total_num, trainable_num total_num, trainable_num = get_parameter_number(net) print("Total Number of parameter: %.2fM" % (total_num / 1e6)) print("Trainable Number of parameter: %.2fM" % (trainable_num / 1e6)) def initialize_optimizer_scheduler(self, net, config): # diffusion model weight learning_params = [{'params':net.denoise_fn.parameters(), 'lr':config.model.BB.optimizer.lr}] # condition model weight if config.model.CondParams.train or config.model.CondParams.pretrained is None: learning_params.append({'params':net.cond_stage_model.parameters(), 'lr':config.model.CondParams.lr}) optimizer = torch.optim.Adam(learning_params, weight_decay=config.model.BB.optimizer.weight_decay, betas=(config.model.BB.optimizer.beta1, config.model.BB.optimizer.beta2) ) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer=optimizer, mode='min', verbose=True, threshold_mode='rel', **vars(config.model.BB.lr_scheduler) ) return [optimizer], [scheduler] @torch.no_grad() def get_checkpoint_states(self, stage='epoch_end'): model_states, optimizer_scheduler_states = super().get_checkpoint_states() return model_states, optimizer_scheduler_states def loss_fn(self, net, batch, epoch, step, opt_idx=0, stage='train', write=True): x, x_cond = batch loss, additional_info, cond = net(x, x_cond) if write: self.writer.add_scalar(f'loss/{stage}', loss, step) self.writer.add_scalar(f'loss/cond', cond, step) loss = loss + cond return loss @torch.no_grad() def sample(self, net, batch, sample_path, stage='train', write=True): sample_path = make_dir(os.path.join(sample_path, f'{stage}_sample')) x, x_cond = batch # batch_size = x.shape[0] if x.shape[0] < 4 else 4 batch_size = 1 x = x[0:1] x_cond = x_cond[0:1] grid_size = max(x.size(1), x_cond.size(1)) # save images sample = net.sample(x_cond, clip_denoised=self.config.testing.clip_denoised) sample, prediction = sample[0], sample[1] channels = ['ir105', 'sw038', 'wv063'] for z, channel in enumerate(channels): x_conds = x_cond[0,:, z:z+1] x_split = x[0,:, z:z+1] sample_split = sample[:, z:z+1] prediction_split = prediction[:, z:z+1]
save_single_video(x_conds, sample_path, f'{channel}_input.png', grid_size, to_normal=self.config.data.dataset_config.to_normal)
10
2023-11-30 01:05:47+00:00
12k
VinAIResearch/MISCA
main.py
[ { "identifier": "Trainer", "path": "trainer.py", "snippet": "class Trainer(object):\n def __init__(self, args, collate, train_dataset=None, dev_dataset=None, test_dataset=None):\n self.args = args\n self.train_dataset = train_dataset\n self.dev_dataset = dev_dataset\n self...
import argparse from trainer import Trainer from utils import init_logger, load_tokenizer, read_prediction_text, set_seed, MODEL_CLASSES, MODEL_PATH_MAP, get_intent_labels, get_slots_all from data_loader import TextLoader, TextCollate
7,450
if args.do_train: trainer.train() if args.do_eval: trainer.load_model() trainer.evaluate('dev', 0) trainer.evaluate("test", -1) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--task", default=None, required=True, type=str, help="The name of the task to train") parser.add_argument("--model_dir", default=None, required=True, type=str, help="Path to save, load model") parser.add_argument("--data_dir", default="./data", type=str, help="The input data dir") parser.add_argument("--intent_label_file", default="intent_label.txt", type=str, help="Intent Label file") parser.add_argument("--slot_label_file", default="slot_label.txt", type=str, help="Slot Label file") parser.add_argument("--slot_label_clean", default="slot_clean.txt", type=str, help="Slot Label file") parser.add_argument("--logging", default="log.txt", type=str, help="Logging file") # LAAT parser.add_argument("--n_levels", default=1, type=int, help="Number of attention") parser.add_argument("--attention_mode", default=None, type=str) parser.add_argument("--level_projection_size", default=32, type=int) parser.add_argument("--d_a", default=-1, type=int) parser.add_argument("--char_embed", default=64, type=int) parser.add_argument("--char_out", default=64, type=int) parser.add_argument("--use_charcnn", action="store_false", help="Whether to use CharCNN") parser.add_argument("--use_charlstm", action="store_false", help="Whether to use CharLSTM") parser.add_argument("--word_embedding_dim", default=128, type=int) parser.add_argument("--encoder_hidden_dim", default=128, type=int) parser.add_argument("--decoder_hidden_dim", default=256, type=int) parser.add_argument("--attention_hidden_dim", default=256, type=int) parser.add_argument("--attention_output_dim", default=256, type=int) # Config training parser.add_argument("--model_type", default="bert", type=str, help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys())) parser.add_argument('--seed', type=int, default=1234, help="random seed for initialization") parser.add_argument("--train_batch_size", default=32, type=int, help="Batch size for training.") parser.add_argument("--eval_batch_size", default=64, type=int, help="Batch size for evaluation.") parser.add_argument("--max_seq_len", default=100, type=int, help="The maximum total input sequence length after tokenization.") parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.") parser.add_argument("--num_train_epochs", default=50, type=float, help="Total number of training epochs to perform.") parser.add_argument("--weight_decay", default=0, type=float, help="Weight decay if we apply some.") parser.add_argument('--gradient_accumulation_steps', type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.") parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.") parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.") parser.add_argument("--max_steps", default=-1, type=int, help="If > 0: set total number of training steps to perform. Override num_train_epochs.") parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.") parser.add_argument("--dropout_rate", default=0.1, type=float, help="Dropout for fully-connected layers") parser.add_argument('--logging_steps', type=int, default=-1, help="Log every X updates steps.") parser.add_argument("--do_train", action="store_true", help="Whether to run training.") parser.add_argument("--do_eval", action="store_true", help="Whether to run eval on the test set.") parser.add_argument("--no_cuda", action="store_true", help="Avoid using CUDA when available") parser.add_argument("--tuning_metric", default="mean_intent_slot", type=str, help="Metric to save checkpoint") parser.add_argument("--only_intent", default=0, type=float, help="The first epochs to optimize intent") parser.add_argument("--ignore_index", default=0, type=int, help='Specifies a target value that is ignored and does not contribute to the input gradient') parser.add_argument( "--token_level", type=str, default="word-level", help="Tokens are at syllable level or word level (Vietnamese) [word-level, syllable-level]", ) parser.add_argument('--intent_loss_coef', type=float, default=0.5, help='Coefficient for the intent loss.') parser.add_argument('--aux_loss_coef', type=float, default=0.5, help='Coefficient for the aux task.') parser.add_argument('--early_stopping', type=float, default=-1, help='Early stopping strategy') parser.add_argument("--base_model", default=None, type=str, help="The pretrained model path") parser.add_argument( "--num_intent_detection", action="store_true", help="Whether to use two-stage intent detection", ) parser.add_argument( "--auxiliary_tasks", action="store_true", help="Whether to optimize with auxiliary tasks", ) parser.add_argument( "--slot_decoder_size", type=int, default=512, help="hidden size of attention output vector" ) parser.add_argument( "--intent_slot_attn_size", type=int, default=128, help="hidden size of attention output vector" ) parser.add_argument( "--min_freq", type=int, default=1, help="Minimum number of frequency to be considered in the vocab" ) parser.add_argument( '--intent_slot_attn_type', choices=['coattention', 'attention_flow'], ) parser.add_argument( '--embedding_type', choices=['soft', 'hard'], default='soft', ) parser.add_argument( "--label_embedding_size", type=int, default=128, help="hidden size of label embedding vector" ) # CRF option parser.add_argument("--use_crf", action="store_true", help="Whether to use CRF") parser.add_argument("--slot_pad_label", default="PAD", type=str, help="Pad token for slot label pad (to be ignore when calculate loss)") args = parser.parse_args()
def main(args): init_logger() set_seed(args) slot_label_lst, hiers = get_slots_all(args) collate = TextCollate(0, len(get_intent_labels(args)), args.max_seq_len) train_dataset = TextLoader(args, 'train') dev_dataset = TextLoader(args, 'dev') test_dataset = TextLoader(args, 'test') trainer = Trainer(args, collate, train_dataset, dev_dataset, test_dataset) if args.do_train: trainer.train() if args.do_eval: trainer.load_model() trainer.evaluate('dev', 0) trainer.evaluate("test", -1) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--task", default=None, required=True, type=str, help="The name of the task to train") parser.add_argument("--model_dir", default=None, required=True, type=str, help="Path to save, load model") parser.add_argument("--data_dir", default="./data", type=str, help="The input data dir") parser.add_argument("--intent_label_file", default="intent_label.txt", type=str, help="Intent Label file") parser.add_argument("--slot_label_file", default="slot_label.txt", type=str, help="Slot Label file") parser.add_argument("--slot_label_clean", default="slot_clean.txt", type=str, help="Slot Label file") parser.add_argument("--logging", default="log.txt", type=str, help="Logging file") # LAAT parser.add_argument("--n_levels", default=1, type=int, help="Number of attention") parser.add_argument("--attention_mode", default=None, type=str) parser.add_argument("--level_projection_size", default=32, type=int) parser.add_argument("--d_a", default=-1, type=int) parser.add_argument("--char_embed", default=64, type=int) parser.add_argument("--char_out", default=64, type=int) parser.add_argument("--use_charcnn", action="store_false", help="Whether to use CharCNN") parser.add_argument("--use_charlstm", action="store_false", help="Whether to use CharLSTM") parser.add_argument("--word_embedding_dim", default=128, type=int) parser.add_argument("--encoder_hidden_dim", default=128, type=int) parser.add_argument("--decoder_hidden_dim", default=256, type=int) parser.add_argument("--attention_hidden_dim", default=256, type=int) parser.add_argument("--attention_output_dim", default=256, type=int) # Config training parser.add_argument("--model_type", default="bert", type=str, help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys())) parser.add_argument('--seed', type=int, default=1234, help="random seed for initialization") parser.add_argument("--train_batch_size", default=32, type=int, help="Batch size for training.") parser.add_argument("--eval_batch_size", default=64, type=int, help="Batch size for evaluation.") parser.add_argument("--max_seq_len", default=100, type=int, help="The maximum total input sequence length after tokenization.") parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.") parser.add_argument("--num_train_epochs", default=50, type=float, help="Total number of training epochs to perform.") parser.add_argument("--weight_decay", default=0, type=float, help="Weight decay if we apply some.") parser.add_argument('--gradient_accumulation_steps', type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.") parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.") parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.") parser.add_argument("--max_steps", default=-1, type=int, help="If > 0: set total number of training steps to perform. Override num_train_epochs.") parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.") parser.add_argument("--dropout_rate", default=0.1, type=float, help="Dropout for fully-connected layers") parser.add_argument('--logging_steps', type=int, default=-1, help="Log every X updates steps.") parser.add_argument("--do_train", action="store_true", help="Whether to run training.") parser.add_argument("--do_eval", action="store_true", help="Whether to run eval on the test set.") parser.add_argument("--no_cuda", action="store_true", help="Avoid using CUDA when available") parser.add_argument("--tuning_metric", default="mean_intent_slot", type=str, help="Metric to save checkpoint") parser.add_argument("--only_intent", default=0, type=float, help="The first epochs to optimize intent") parser.add_argument("--ignore_index", default=0, type=int, help='Specifies a target value that is ignored and does not contribute to the input gradient') parser.add_argument( "--token_level", type=str, default="word-level", help="Tokens are at syllable level or word level (Vietnamese) [word-level, syllable-level]", ) parser.add_argument('--intent_loss_coef', type=float, default=0.5, help='Coefficient for the intent loss.') parser.add_argument('--aux_loss_coef', type=float, default=0.5, help='Coefficient for the aux task.') parser.add_argument('--early_stopping', type=float, default=-1, help='Early stopping strategy') parser.add_argument("--base_model", default=None, type=str, help="The pretrained model path") parser.add_argument( "--num_intent_detection", action="store_true", help="Whether to use two-stage intent detection", ) parser.add_argument( "--auxiliary_tasks", action="store_true", help="Whether to optimize with auxiliary tasks", ) parser.add_argument( "--slot_decoder_size", type=int, default=512, help="hidden size of attention output vector" ) parser.add_argument( "--intent_slot_attn_size", type=int, default=128, help="hidden size of attention output vector" ) parser.add_argument( "--min_freq", type=int, default=1, help="Minimum number of frequency to be considered in the vocab" ) parser.add_argument( '--intent_slot_attn_type', choices=['coattention', 'attention_flow'], ) parser.add_argument( '--embedding_type', choices=['soft', 'hard'], default='soft', ) parser.add_argument( "--label_embedding_size", type=int, default=128, help="hidden size of label embedding vector" ) # CRF option parser.add_argument("--use_crf", action="store_true", help="Whether to use CRF") parser.add_argument("--slot_pad_label", default="PAD", type=str, help="Pad token for slot label pad (to be ignore when calculate loss)") args = parser.parse_args()
args.model_name_or_path = MODEL_PATH_MAP[args.model_type]
6
2023-11-29 16:47:05+00:00
12k
ai2cm/ace
fme/fme/core/aggregator/inference/main.py
[ { "identifier": "MeanAggregator", "path": "fme/fme/core/aggregator/one_step/reduced.py", "snippet": "class MeanAggregator:\n \"\"\"\n Aggregator for mean-reduced metrics.\n\n These are metrics such as means which reduce to a single float for each batch,\n and then can be averaged across batc...
from typing import Dict, Iterable, List, Mapping, Optional, Protocol, Union from wandb import Table from fme.core.data_loading.typing import SigmaCoordinates, VariableMetadata from fme.core.distributed import Distributed from fme.core.wandb import WandB from ..one_step.reduced import MeanAggregator as OneStepMeanAggregator from .reduced import MeanAggregator from .time_mean import TimeMeanAggregator from .video import VideoAggregator from .zonal_mean import ZonalMeanAggregator import torch import xarray as xr
7,894
wandb = WandB.get_instance() class _Aggregator(Protocol): @torch.no_grad() def record_batch( self, loss: float, target_data: Mapping[str, torch.Tensor], gen_data: Mapping[str, torch.Tensor], target_data_norm: Mapping[str, torch.Tensor], gen_data_norm: Mapping[str, torch.Tensor], ): ... @torch.no_grad() def get_logs(self, label: str): ... @torch.no_grad() def get_dataset(self) -> xr.Dataset: ... class InferenceAggregator: """ Aggregates statistics for inference. To use, call `record_batch` on the results of each batch, then call `get_logs` to get a dictionary of statistics when you're done. """ def __init__( self, area_weights: torch.Tensor, sigma_coordinates: SigmaCoordinates, n_timesteps: int, record_step_20: bool = False, log_video: bool = False, enable_extended_videos: bool = False, log_zonal_mean_images: bool = False, dist: Optional[Distributed] = None, metadata: Optional[Mapping[str, VariableMetadata]] = None, ): """ Args: area_weights: Area weights for each grid cell. sigma_coordinates: Data sigma coordinates n_timesteps: Number of timesteps of inference that will be run. record_step_20: Whether to record the mean of the 20th steps. log_video: Whether to log videos of the state evolution. enable_extended_videos: Whether to log videos of statistical metrics of state evolution log_zonal_mean_images: Whether to log zonal-mean images (hovmollers) with a time dimension. dist: Distributed object to use for metric aggregation. metadata: Mapping of variable names their metadata that will used in generating logged image captions. """ self._aggregators: Dict[str, _Aggregator] = {
wandb = WandB.get_instance() class _Aggregator(Protocol): @torch.no_grad() def record_batch( self, loss: float, target_data: Mapping[str, torch.Tensor], gen_data: Mapping[str, torch.Tensor], target_data_norm: Mapping[str, torch.Tensor], gen_data_norm: Mapping[str, torch.Tensor], ): ... @torch.no_grad() def get_logs(self, label: str): ... @torch.no_grad() def get_dataset(self) -> xr.Dataset: ... class InferenceAggregator: """ Aggregates statistics for inference. To use, call `record_batch` on the results of each batch, then call `get_logs` to get a dictionary of statistics when you're done. """ def __init__( self, area_weights: torch.Tensor, sigma_coordinates: SigmaCoordinates, n_timesteps: int, record_step_20: bool = False, log_video: bool = False, enable_extended_videos: bool = False, log_zonal_mean_images: bool = False, dist: Optional[Distributed] = None, metadata: Optional[Mapping[str, VariableMetadata]] = None, ): """ Args: area_weights: Area weights for each grid cell. sigma_coordinates: Data sigma coordinates n_timesteps: Number of timesteps of inference that will be run. record_step_20: Whether to record the mean of the 20th steps. log_video: Whether to log videos of the state evolution. enable_extended_videos: Whether to log videos of statistical metrics of state evolution log_zonal_mean_images: Whether to log zonal-mean images (hovmollers) with a time dimension. dist: Distributed object to use for metric aggregation. metadata: Mapping of variable names their metadata that will used in generating logged image captions. """ self._aggregators: Dict[str, _Aggregator] = {
"mean": MeanAggregator(
1
2023-11-29 23:08:42+00:00
12k
fzmi/ubdd
models/dino/models/dino/dino.py
[ { "identifier": "box_ops", "path": "models/dino/util/box_ops.py", "snippet": "def box_cxcywh_to_xyxy(x):\ndef box_xyxy_to_cxcywh(x):\ndef box_iou(boxes1, boxes2):\ndef generalized_box_iou(boxes1, boxes2):\ndef box_iou_pairwise(boxes1, boxes2):\ndef generalized_box_iou_pairwise(boxes1, boxes2):\ndef mask...
import copy import math import torch import torch.nn.functional as F from typing import List from torch import nn from torchvision.ops.boxes import nms from models.dino.util import box_ops from models.dino.util.misc import (NestedTensor, nested_tensor_from_tensor_list, accuracy, get_world_size, interpolate, is_dist_avail_and_initialized, inverse_sigmoid) from .backbone import build_backbone from .matcher import build_matcher from .segmentation import (DETRsegm, PostProcessPanoptic, PostProcessSegm, dice_loss) from .deformable_transformer import build_deformable_transformer from .utils import sigmoid_focal_loss, MLP from ..registry import MODULE_BUILD_FUNCS from .dn_components import prepare_for_cdn,dn_post_process
9,380
# ------------------------------------------------------------------------ # DINO # Copyright (c) 2022 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Conditional DETR model and criterion classes. # Copyright (c) 2021 Microsoft. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Modified from DETR (https://github.com/facebookresearch/detr) # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # ------------------------------------------------------------------------ # Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR) # Copyright (c) 2020 SenseTime. All Rights Reserved. # ------------------------------------------------------------------------ class DINO(nn.Module): """ This is the Cross-Attention Detector module that performs object detection """ def __init__(self, backbone, transformer, num_classes, num_queries, aux_loss=False, iter_update=False, query_dim=2, random_refpoints_xy=False, fix_refpoints_hw=-1, num_feature_levels=1, nheads=8, # two stage two_stage_type='no', # ['no', 'standard'] two_stage_add_query_num=0, dec_pred_class_embed_share=True, dec_pred_bbox_embed_share=True, two_stage_class_embed_share=True, two_stage_bbox_embed_share=True, decoder_sa_type = 'sa', num_patterns = 0, dn_number = 100, dn_box_noise_scale = 0.4, dn_label_noise_ratio = 0.5, dn_labelbook_size = 100, ): """ Initializes the model. Parameters: backbone: torch module of the backbone to be used. See backbone.py transformer: torch module of the transformer architecture. See transformer.py num_classes: number of object classes num_queries: number of object queries, ie detection slot. This is the maximal number of objects Conditional DETR can detect in a single image. For COCO, we recommend 100 queries. aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used. fix_refpoints_hw: -1(default): learn w and h for each box seperately >0 : given fixed number -2 : learn a shared w and h """ super().__init__() self.num_queries = num_queries self.transformer = transformer self.num_classes = num_classes self.hidden_dim = hidden_dim = transformer.d_model self.num_feature_levels = num_feature_levels self.nheads = nheads self.label_enc = nn.Embedding(dn_labelbook_size + 1, hidden_dim) # setting query dim self.query_dim = query_dim assert query_dim == 4 self.random_refpoints_xy = random_refpoints_xy self.fix_refpoints_hw = fix_refpoints_hw # for dn training self.num_patterns = num_patterns self.dn_number = dn_number self.dn_box_noise_scale = dn_box_noise_scale self.dn_label_noise_ratio = dn_label_noise_ratio self.dn_labelbook_size = dn_labelbook_size # prepare input projection layers if num_feature_levels > 1: num_backbone_outs = len(backbone.num_channels) input_proj_list = [] for _ in range(num_backbone_outs): in_channels = backbone.num_channels[_] input_proj_list.append(nn.Sequential( nn.Conv2d(in_channels, hidden_dim, kernel_size=1), nn.GroupNorm(32, hidden_dim), )) for _ in range(num_feature_levels - num_backbone_outs): input_proj_list.append(nn.Sequential( nn.Conv2d(in_channels, hidden_dim, kernel_size=3, stride=2, padding=1), nn.GroupNorm(32, hidden_dim), )) in_channels = hidden_dim self.input_proj = nn.ModuleList(input_proj_list) else: assert two_stage_type == 'no', "two_stage_type should be no if num_feature_levels=1 !!!" self.input_proj = nn.ModuleList([ nn.Sequential( nn.Conv2d(backbone.num_channels[-1], hidden_dim, kernel_size=1), nn.GroupNorm(32, hidden_dim), )]) self.backbone = backbone self.aux_loss = aux_loss self.box_pred_damping = box_pred_damping = None self.iter_update = iter_update assert iter_update, "Why not iter_update?" # prepare pred layers self.dec_pred_class_embed_share = dec_pred_class_embed_share self.dec_pred_bbox_embed_share = dec_pred_bbox_embed_share # prepare class & box embed _class_embed = nn.Linear(hidden_dim, num_classes)
# ------------------------------------------------------------------------ # DINO # Copyright (c) 2022 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Conditional DETR model and criterion classes. # Copyright (c) 2021 Microsoft. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Modified from DETR (https://github.com/facebookresearch/detr) # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # ------------------------------------------------------------------------ # Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR) # Copyright (c) 2020 SenseTime. All Rights Reserved. # ------------------------------------------------------------------------ class DINO(nn.Module): """ This is the Cross-Attention Detector module that performs object detection """ def __init__(self, backbone, transformer, num_classes, num_queries, aux_loss=False, iter_update=False, query_dim=2, random_refpoints_xy=False, fix_refpoints_hw=-1, num_feature_levels=1, nheads=8, # two stage two_stage_type='no', # ['no', 'standard'] two_stage_add_query_num=0, dec_pred_class_embed_share=True, dec_pred_bbox_embed_share=True, two_stage_class_embed_share=True, two_stage_bbox_embed_share=True, decoder_sa_type = 'sa', num_patterns = 0, dn_number = 100, dn_box_noise_scale = 0.4, dn_label_noise_ratio = 0.5, dn_labelbook_size = 100, ): """ Initializes the model. Parameters: backbone: torch module of the backbone to be used. See backbone.py transformer: torch module of the transformer architecture. See transformer.py num_classes: number of object classes num_queries: number of object queries, ie detection slot. This is the maximal number of objects Conditional DETR can detect in a single image. For COCO, we recommend 100 queries. aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used. fix_refpoints_hw: -1(default): learn w and h for each box seperately >0 : given fixed number -2 : learn a shared w and h """ super().__init__() self.num_queries = num_queries self.transformer = transformer self.num_classes = num_classes self.hidden_dim = hidden_dim = transformer.d_model self.num_feature_levels = num_feature_levels self.nheads = nheads self.label_enc = nn.Embedding(dn_labelbook_size + 1, hidden_dim) # setting query dim self.query_dim = query_dim assert query_dim == 4 self.random_refpoints_xy = random_refpoints_xy self.fix_refpoints_hw = fix_refpoints_hw # for dn training self.num_patterns = num_patterns self.dn_number = dn_number self.dn_box_noise_scale = dn_box_noise_scale self.dn_label_noise_ratio = dn_label_noise_ratio self.dn_labelbook_size = dn_labelbook_size # prepare input projection layers if num_feature_levels > 1: num_backbone_outs = len(backbone.num_channels) input_proj_list = [] for _ in range(num_backbone_outs): in_channels = backbone.num_channels[_] input_proj_list.append(nn.Sequential( nn.Conv2d(in_channels, hidden_dim, kernel_size=1), nn.GroupNorm(32, hidden_dim), )) for _ in range(num_feature_levels - num_backbone_outs): input_proj_list.append(nn.Sequential( nn.Conv2d(in_channels, hidden_dim, kernel_size=3, stride=2, padding=1), nn.GroupNorm(32, hidden_dim), )) in_channels = hidden_dim self.input_proj = nn.ModuleList(input_proj_list) else: assert two_stage_type == 'no', "two_stage_type should be no if num_feature_levels=1 !!!" self.input_proj = nn.ModuleList([ nn.Sequential( nn.Conv2d(backbone.num_channels[-1], hidden_dim, kernel_size=1), nn.GroupNorm(32, hidden_dim), )]) self.backbone = backbone self.aux_loss = aux_loss self.box_pred_damping = box_pred_damping = None self.iter_update = iter_update assert iter_update, "Why not iter_update?" # prepare pred layers self.dec_pred_class_embed_share = dec_pred_class_embed_share self.dec_pred_bbox_embed_share = dec_pred_bbox_embed_share # prepare class & box embed _class_embed = nn.Linear(hidden_dim, num_classes)
_bbox_embed = MLP(hidden_dim, hidden_dim, 4, 3)
16
2023-12-04 00:27:58+00:00
12k
yongzhuo/ChatGLM3-SFT
chatglm3_sft/ft_chatglm3/train_deepspeed.py
[ { "identifier": "CUDA_VISIBLE_DEVICES", "path": "chatglm3_sft/ft_chatglm3/config.py", "snippet": "CUDA_VISIBLE_DEVICES = \"0\"" }, { "identifier": "USE_TORCH", "path": "chatglm3_sft/ft_chatglm3/config.py", "snippet": "USE_TORCH = \"1\"" }, { "identifier": "CPU_NUMS", "path": ...
import random import copy import sys import os import torch.nn as nn import transformers import torch import torch.distributed as dist from chatglm3_sft.ft_chatglm3.config import CUDA_VISIBLE_DEVICES, USE_TORCH, CPU_NUMS # from config from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from peft import (get_peft_model_state_dict, get_peft_model, LoraConfig) from transformers import AutoModelForCausalLM, AutoTokenizer from transformers.modeling_utils import unwrap_model from tensorboardX import SummaryWriter from datasets import load_dataset from chatglm3_sft.models.modeling_chatglm import ChatGLMForConditionalGeneration, ChatGLMConfig from chatglm3_sft.models.tokenization_chatglm import ChatGLMTokenizer from chatglm3_sft.ft_chatglm3.config import PATH_MODEL_PRETRAIN, DATA_PATH, MODEL_SAVE_DIR, REPO_ID from chatglm3_sft.ft_chatglm3.config import MICRO_BATCH_SIZE, BATCH_SIZE, GRADIENT_ACCUMULATION_STEPS from chatglm3_sft.ft_chatglm3.config import LEARNING_RATE, EPOCHS, SAVE_STEPS, VAL_SET_SIZE, TARGET_MODULES from chatglm3_sft.ft_chatglm3.config import IS_PARALLELIZABLE, MODEL_PARALLEL, USE_CACHE from chatglm3_sft.ft_chatglm3.config import MAX_LENGTH_Q, MAX_LENGTH_A, MAX_LENGTH_QA from chatglm3_sft.ft_chatglm3.config import LORA_DROPOUT, LORA_ALPHA, LORA_R
8,091
# attention_mask[..., idx] = 1 attention_mask = (attention_mask < 0.5).bool() return attention_mask len_max_batch = [len(batch[i].get("input_ids")) + len(batch[i].get("labels")) + 1 for i in range(len(batch))] len_max_batch = min(MAX_LENGTH_QA, max(len_max_batch)) batch_attention_mask = [] batch_position_ids = [] batch_input_ids = [] batch_labels = [] for ba in batch: x, y = ba.get("input_ids"), ba.get("labels") len_padding = len_max_batch - len(x) - len(y) # if tokenizer.padding_side and tokenizer.padding_side == "left": # labels = [-100] * len_padding + [-100] * len(x) + y # input_ids = [ID_PAD] * (len_padding) + x + y # else: # labels = [-100] * len(x) + y + [-100] * len_padding # input_ids = x + y + [ID_PAD] * (len_padding) ## pretrain, 不mask if tokenizer.padding_side and tokenizer.padding_side == "left": labels = [-100] * len_padding + x + y input_ids = [ID_PAD] * (len_padding) + x + y else: labels = x + y + [-100] * len_padding input_ids = x + y + [ID_PAD] * (len_padding) tensor_position_ids = get_position_ids(input_ids, bos_token_id=ID_SOP) tensor_attention_mask = get_masks(input_ids, special_ids=IDS_ORG) tensor_input_ids = torch.tensor(input_ids, dtype=torch.long) tensor_labels = torch.tensor(labels, dtype=torch.long) batch_attention_mask.append(tensor_attention_mask) batch_position_ids.append(tensor_position_ids) batch_input_ids.append(tensor_input_ids) batch_labels.append(tensor_labels) # print_rank_0(batch_attention_mask) batch_attention_mask = torch.stack(batch_attention_mask) batch_position_ids = torch.stack(batch_position_ids) batch_input_ids = torch.stack(batch_input_ids) batch_labels = torch.stack(batch_labels) input_dict = { "full_attention_mask": copy.deepcopy(batch_attention_mask), "attention_mask": batch_attention_mask, "position_ids": batch_position_ids, "input_ids": batch_input_ids, "labels": batch_labels, } # print_rank_0(input_dict) return input_dict def dfs_file(path_dir): """ 递归获取某个目录下的所有文件(所有层, 包括子目录) Args: path_dir[String]:, path of dir, eg. "/home/data" Returns: data[List]: data of input, eg. ["2020_01_08.txt"] """ path_files = [] for root, dirs, files in os.walk(path_dir): # 分别代表根目录、文件夹、文件 for file in files: # 遍历文件 file_path = os.path.join(root, file) # 获取文件绝对路径 path_files.append(file_path) # 将文件路径添加进列表 files = list(set(path_files)) files.sort() # the same list return files def print_rank_0(*args): """ 只打印 0 号GPU的 """ if torch.distributed.get_rank() == 0: # 一般用0,当然,可以选任意的rank保存。 print(*args) def local_rank_is_0(): """ 判断是哪台机子的 """ flag = False if torch.distributed.get_rank() == 0: flag = True return flag dist.init_process_group(backend="nccl") tokenizer = ChatGLMTokenizer.from_pretrained(PATH_MODEL_PRETRAIN) # tokenizer.pad_token = tokenizer.eos_token # tokenizer.padding_side = "left" # Allow batched inference tokenizer.padding_side = "right" # Allow batched inference ID_MASK = 64789 ID_gMASK = 64790 ID_sMASK = 64791 ID_SOP = 64792 ID_EOP = 64793 ID_PAD = 64793 ID_system = 64794 ID_user = 64795 ID_assistant = 64796 ID_observation = 64797 TOKEN_ASSISTANT = "<|assistant|>" TOKEN_SYSTEM = "<|system|>" TOKEN_USER = "<|user|>" TOKEN_START = "sop" TOKEN_END = "eop" # IDS_ORG = [ID_MASK, ID_gMASK, ID_sMASK, ID_SOP, ID_EOP, # ID_BOS, ID_EOS, ID_PAD] # IDS_ORG = [ID_PAD] IDS_ORG = [ID_user] # start, <|user|> model = ChatGLMForConditionalGeneration.from_pretrained(PATH_MODEL_PRETRAIN) model = prepare_model_for_half_training(model, use_gradient_checkpointing=True, output_embedding_layer_name="lm_head", layer_norm_names=["post_attention_layernorm", "final_layernorm", "input_layernorm", ], ) model.gradient_checkpointing_enable() model.enable_input_require_grads() model.is_parallelizable = IS_PARALLELIZABLE model.model_parallel = MODEL_PARALLEL model.config.use_cache = USE_CACHE
# !/usr/bin/python # -*- coding: utf-8 -*- # @time : 2023/3/5 21:04 # @author : Mo # @function: chatglm3 path_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")) # print_rank_0(path_root) sys.path.append(path_root) os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:3072" # os.environ["CUDA_VISIBLE_DEVICES"] = CUDA_VISIBLE_DEVICES os.environ["USE_TORCH"] = USE_TORCH os.environ["OMP_NUM_THREADS"] = CPU_NUMS # export OMP_NUM_THREADS=1 os.environ["OPENBLAS_NUM_THREADS"] = CPU_NUMS # export OPENBLAS_NUM_THREADS=1 os.environ["MKL_NUM_THREADS"] = CPU_NUMS # export MKL_NUM_THREADS=1 os.environ["VECLIB_MAXIMUM_THREADS"] = CPU_NUMS # export VECLIB_MAXIMUM_THREADS=1 os.environ["NUMEXPR_NUM_THREADS"] = CPU_NUMS # export NUMEXPR_NUM_THREADS=1 # import bitsandbytes as bnb def save_model_state(model, config=None, model_save_dir="./", model_name="adapter_model.bin"): """ 仅保存 有梯度 的 模型参数(推荐使用) """ if not os.path.exists(model_save_dir): os.makedirs(model_save_dir) # save config if config: config.save_pretrained(model_save_dir) # config.to_dict() # save model path_model = os.path.join(model_save_dir, model_name) grad_params_dict = {k: v.to("cpu") for k, v in model.named_parameters() if v.requires_grad == True} torch.save(grad_params_dict, path_model) print_rank_0("******model_save_path is {}******".format(path_model)) def print_rank_0_named_parameters(model, use_print_rank_0_data=False): """ 打印模型训练参数/数据类型信息 """ trainable_params = 0 all_param = 0 for name, param in model.named_parameters(): if use_print_rank_0_data: print_rank_0((name, param.data.dtype, param.requires_grad, param.data)) else: print_rank_0((name, param.data.dtype, param.requires_grad)) num_params = param.numel() # if using DS Zero 3 and the weights are initialized empty if num_params == 0 and hasattr(param, "ds_numel"): num_params = param.ds_numel all_param += num_params if param.requires_grad: trainable_params += num_params print_rank_0(f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}") def prepare_model_for_half_training(model, output_embedding_layer_name="lm_head", use_gradient_checkpointing=True, layer_norm_names=["layer_norm"]): r""" This method wrapps the entire protocol for preparing a model before running a training. This includes: 1- Cast the layernorm in fp32 2- making output embedding layer require grads 3- Add the upcasting of the lm head to fp32 Args: model, (`transformers.PreTrainedModel`): The loaded model from `transformers` """ # 不要使用 model.half(), 这样会先截取精度再训练了, 最初data就要保持half for name, param in model.named_parameters(): # freeze base model's layers param.requires_grad = False # cast layer norm in fp32 for stability for 8bit models if param.ndim == 1 and any(layer_norm_name in name for layer_norm_name in layer_norm_names): param.data = param.data.to(torch.float32) elif output_embedding_layer_name in name: # lm_head也需要是tf.float32(最后一层) param.data = param.data.to(torch.float32) else: param.data = param.data.to(torch.half) if use_gradient_checkpointing: # For backward compatibility if hasattr(model, "enable_input_require_grads"): model.enable_input_require_grads() else: def make_inputs_require_grad(module, input, output): output.requires_grad_(True) model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) # enable gradient checkpointing for memory efficiency model.gradient_checkpointing_enable() return model def generate_prompt(data_point, is_logger=False): # sorry about the formatting disaster gotta move fast # text_1 = f"指令:\n{data_point.get('instruction', '')}\n问:\n{data_point.get('input', '')}\n答:\n" \ # if data_point.get('input', '') else f"指令:\n{data_point.get('instruction', '')}\n答:\n" # text_2 = f"{data_point.get('output', '')}" prompt_system_std = "You are a helpful, safety and harmless assistant." prompt_system_std = "You are ChatGLM3, a large language model trained by Zhipu.AI. Follow the user's instructions carefully. Respond using markdown." instruction = data_point.get("instruction", "").strip() text_input = instruction + " " + data_point.get("input", "").strip() text_output = data_point.get("output", "").strip() history = data_point.get("history", "") string_system = TOKEN_SYSTEM + "\n" + prompt_system_std + "\n" string_output = TOKEN_USER + "\n" + text_input + "\n" + \ TOKEN_ASSISTANT + "\n" + text_output + "\n" ids_prompt_system = [ID_gMASK, ID_SOP, ID_system] + tokenizer.encode( "\n" + instruction + "\n", is_split_into_words=True)[2:] ids_text_input = [ID_user] + tokenizer.encode("\n" + text_input + "\n", is_split_into_words=True)[2:] ids_text_output = [ID_assistant] + tokenizer.encode("\n" + text_output + "\n", is_split_into_words=True)[2:] string_history = "" ids_history = [] for idx, item in enumerate(history): content = item if idx % 2 == 0: id_role = ID_user token_role = TOKEN_USER else: id_role = ID_assistant token_role = TOKEN_ASSISTANT string_history += token_role + "\n" + content + "\n" id_history = [id_role] + tokenizer.encode("\n" + content + "\n", is_split_into_words=True)[2:] ids_history.extend(id_history) ### 全量加入x, 同预训练(为了与多轮对话数据构造一致) ids_prompt_input = ids_prompt_system + ids_history + ids_text_input + ids_text_output string_print = string_system + string_history + string_output if len(ids_prompt_input) > (MAX_LENGTH_Q + MAX_LENGTH_A): # if > len_max, clip MAX_LENGTH_q and MAX_LENGTH_a ids_prompt_input = ids_prompt_input[:MAX_LENGTH_Q] out = {"input_ids": ids_prompt_input, "labels": []} if is_logger: print(string_print) print(out) return out def data_collator(batch): def get_position_ids(seq, bos_token_id): seq_length = len(seq) position_ids = torch.arange(seq_length, dtype=torch.long).unsqueeze(0) return position_ids def get_masks(seq, special_ids=IDS_ORG): """ padding-mask """ # mask until ID_user # context_length = seq.index(ID_user) attention_mask = torch.ones((1, len(seq), len(seq))) attention_mask.tril_() ### mask掉id_sop前面的 # attention_mask[..., :context_length] = 1 # ### 如果 padding-right, 也mask掉 # for idx, s in enumerate(seq): # if s in special_ids: # attention_mask[..., idx] = 1 attention_mask = (attention_mask < 0.5).bool() return attention_mask len_max_batch = [len(batch[i].get("input_ids")) + len(batch[i].get("labels")) + 1 for i in range(len(batch))] len_max_batch = min(MAX_LENGTH_QA, max(len_max_batch)) batch_attention_mask = [] batch_position_ids = [] batch_input_ids = [] batch_labels = [] for ba in batch: x, y = ba.get("input_ids"), ba.get("labels") len_padding = len_max_batch - len(x) - len(y) # if tokenizer.padding_side and tokenizer.padding_side == "left": # labels = [-100] * len_padding + [-100] * len(x) + y # input_ids = [ID_PAD] * (len_padding) + x + y # else: # labels = [-100] * len(x) + y + [-100] * len_padding # input_ids = x + y + [ID_PAD] * (len_padding) ## pretrain, 不mask if tokenizer.padding_side and tokenizer.padding_side == "left": labels = [-100] * len_padding + x + y input_ids = [ID_PAD] * (len_padding) + x + y else: labels = x + y + [-100] * len_padding input_ids = x + y + [ID_PAD] * (len_padding) tensor_position_ids = get_position_ids(input_ids, bos_token_id=ID_SOP) tensor_attention_mask = get_masks(input_ids, special_ids=IDS_ORG) tensor_input_ids = torch.tensor(input_ids, dtype=torch.long) tensor_labels = torch.tensor(labels, dtype=torch.long) batch_attention_mask.append(tensor_attention_mask) batch_position_ids.append(tensor_position_ids) batch_input_ids.append(tensor_input_ids) batch_labels.append(tensor_labels) # print_rank_0(batch_attention_mask) batch_attention_mask = torch.stack(batch_attention_mask) batch_position_ids = torch.stack(batch_position_ids) batch_input_ids = torch.stack(batch_input_ids) batch_labels = torch.stack(batch_labels) input_dict = { "full_attention_mask": copy.deepcopy(batch_attention_mask), "attention_mask": batch_attention_mask, "position_ids": batch_position_ids, "input_ids": batch_input_ids, "labels": batch_labels, } # print_rank_0(input_dict) return input_dict def dfs_file(path_dir): """ 递归获取某个目录下的所有文件(所有层, 包括子目录) Args: path_dir[String]:, path of dir, eg. "/home/data" Returns: data[List]: data of input, eg. ["2020_01_08.txt"] """ path_files = [] for root, dirs, files in os.walk(path_dir): # 分别代表根目录、文件夹、文件 for file in files: # 遍历文件 file_path = os.path.join(root, file) # 获取文件绝对路径 path_files.append(file_path) # 将文件路径添加进列表 files = list(set(path_files)) files.sort() # the same list return files def print_rank_0(*args): """ 只打印 0 号GPU的 """ if torch.distributed.get_rank() == 0: # 一般用0,当然,可以选任意的rank保存。 print(*args) def local_rank_is_0(): """ 判断是哪台机子的 """ flag = False if torch.distributed.get_rank() == 0: flag = True return flag dist.init_process_group(backend="nccl") tokenizer = ChatGLMTokenizer.from_pretrained(PATH_MODEL_PRETRAIN) # tokenizer.pad_token = tokenizer.eos_token # tokenizer.padding_side = "left" # Allow batched inference tokenizer.padding_side = "right" # Allow batched inference ID_MASK = 64789 ID_gMASK = 64790 ID_sMASK = 64791 ID_SOP = 64792 ID_EOP = 64793 ID_PAD = 64793 ID_system = 64794 ID_user = 64795 ID_assistant = 64796 ID_observation = 64797 TOKEN_ASSISTANT = "<|assistant|>" TOKEN_SYSTEM = "<|system|>" TOKEN_USER = "<|user|>" TOKEN_START = "sop" TOKEN_END = "eop" # IDS_ORG = [ID_MASK, ID_gMASK, ID_sMASK, ID_SOP, ID_EOP, # ID_BOS, ID_EOS, ID_PAD] # IDS_ORG = [ID_PAD] IDS_ORG = [ID_user] # start, <|user|> model = ChatGLMForConditionalGeneration.from_pretrained(PATH_MODEL_PRETRAIN) model = prepare_model_for_half_training(model, use_gradient_checkpointing=True, output_embedding_layer_name="lm_head", layer_norm_names=["post_attention_layernorm", "final_layernorm", "input_layernorm", ], ) model.gradient_checkpointing_enable() model.enable_input_require_grads() model.is_parallelizable = IS_PARALLELIZABLE model.model_parallel = MODEL_PARALLEL model.config.use_cache = USE_CACHE
config = LoraConfig(target_modules=TARGET_MODULES,
16
2023-11-30 12:27:42+00:00
12k
yongzhuo/MacroGPT-Pretrain
macro_gpt/ft_gpt/train.pt.py
[ { "identifier": "CUDA_VISIBLE_DEVICES", "path": "macro_gpt/ft_gpt/config_macrogpt_1b3_float32.py", "snippet": "CUDA_VISIBLE_DEVICES = \"0\"" }, { "identifier": "USE_TORCH", "path": "macro_gpt/ft_gpt/config_macrogpt_1b3_float32.py", "snippet": "USE_TORCH = \"1\"" }, { "identifier"...
import random import copy import sys import os import bitsandbytes as bnb import torch.nn as nn import transformers import torch from macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import CUDA_VISIBLE_DEVICES, USE_TORCH, CPU_NUMS # from config from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from peft import (get_peft_model_state_dict, get_peft_model, LoraConfig) from transformers import AutoModelForCausalLM, AutoTokenizer from transformers.modeling_utils import unwrap_model from tensorboardX import SummaryWriter from datasets import load_dataset from macro_gpt.models.llama.modeling_llama import LlamaForCausalLM as LLMForCausalLM from macro_gpt.models.llama.tokenization_llama import LlamaTokenizer as LLMTokenizer from macro_gpt.models.llama.modeling_llama import LlamaConfig as LLMConfig from macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import PATH_MODEL_PRETRAIN, DATA_PATH, MODEL_SAVE_DIR, REPO_ID from macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import MICRO_BATCH_SIZE, BATCH_SIZE, GRADIENT_ACCUMULATION_STEPS from macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import LEARNING_RATE, EPOCHS, SAVE_STEPS, VAL_SET_SIZE, TARGET_MODULES from macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import IS_PARALLELIZABLE, MODEL_PARALLEL, USE_CACHE from macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import MAX_LENGTH_Q, MAX_LENGTH_A, MAX_LENGTH_QA from macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import LORA_DROPOUT, LORA_ALPHA, LORA_R from macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import PATH_MODEL_CONFIG, PATH_TOKENIZER_PRETRAIN
10,799
# !/usr/bin/python # -*- coding: utf-8 -*- # @time : 2023/3/5 21:04 # @author : Mo # @function: macro-gpt path_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")) sys.path.append(path_root) os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:3072"
# !/usr/bin/python # -*- coding: utf-8 -*- # @time : 2023/3/5 21:04 # @author : Mo # @function: macro-gpt path_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")) sys.path.append(path_root) os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:3072"
os.environ["CUDA_VISIBLE_DEVICES"] = CUDA_VISIBLE_DEVICES
0
2023-11-30 12:39:19+00:00
12k
owkin/fedeca
fedeca/scripts/fl_iptw.py
[ { "identifier": "FedECA", "path": "fedeca/fedeca_core.py", "snippet": "class FedECA(Experiment, BaseSurvivalEstimator):\n \"\"\"FedECA class tthat performs Federated IPTW.\"\"\"\n\n def __init__(\n self,\n ndim: int,\n ds_client=None,\n train_data_nodes: Union[list[Trai...
import torch from fedeca import FedECA from fedeca.utils.data_utils import generate_survival_data
8,052
"""Federated IPTW script.""" if __name__ == "__main__": seed = 42 torch.manual_seed(seed) N_CLIENTS = 2 NDIM = 10 URLS = [] TOKENS = [] # Choose BACKEND_TYPE between subprocess, remote and docker BACKEND_TYPE = "subprocess" if BACKEND_TYPE == "remote": # If you use BACKEND_TYPE="remote", download your API key with SSO login then # copy-paste it in a file called api_key inside the tokens folder otherwise # comment the following two lines URLS = [f"https://api.org-{i + 1}.demo.cg.owkin.tech" for i in range(N_CLIENTS)] TOKENS = [open(f"tokens/api_key{i + 1}", "r").read() for i in range(N_CLIENTS)]
"""Federated IPTW script.""" if __name__ == "__main__": seed = 42 torch.manual_seed(seed) N_CLIENTS = 2 NDIM = 10 URLS = [] TOKENS = [] # Choose BACKEND_TYPE between subprocess, remote and docker BACKEND_TYPE = "subprocess" if BACKEND_TYPE == "remote": # If you use BACKEND_TYPE="remote", download your API key with SSO login then # copy-paste it in a file called api_key inside the tokens folder otherwise # comment the following two lines URLS = [f"https://api.org-{i + 1}.demo.cg.owkin.tech" for i in range(N_CLIENTS)] TOKENS = [open(f"tokens/api_key{i + 1}", "r").read() for i in range(N_CLIENTS)]
df, cox_model_coeffs = generate_survival_data(
1
2023-11-27 18:01:37+00:00
12k
forefy/eburger
eburger/serializer.py
[ { "identifier": "settings", "path": "eburger/settings.py", "snippet": "" }, { "identifier": "ASTNode", "path": "eburger/models.py", "snippet": "class ASTNode:\n \"\"\"\n Represents a generic node in an Abstract Syntax Tree (AST).\n\n An ASTNode is a fundamental part of represent...
from eburger import settings from eburger.models import ( ASTNode, Assignment, BinaryOperation, Block, Conditional, ContractDefinition, ElementaryTypeName, ElementaryTypeNameExpression, EmitStatement, ErrorDefinition, EventDefinition, ExpressionStatement, ForStatement, FunctionCall, FunctionCallOptions, FunctionDefinition, Identifier, IdentifierPath, IfStatement, ImportDirective, IndexAccess, LiteralValue, ReturnValue, MemberAccess, ModifierDefinition, ParameterList, RevertStatement, SourceUnit, PragmaDirective, SymbolAlias, TupleExpression, UnaryOperation, UserDefinedTypeName, UsingForDirective, VariableDeclaration, VariableDeclarationStatement, ) from eburger.utils.logger import log
9,416
statements=statements, src=src, children=[], ) for stmt in statements: G.add_edge(parsed_node.get_display_name(), stmt.get_display_name()) case "Assignment": left_hand_side, G = parse_ast_node(node_dict["leftHandSide"], G) right_hand_side, G = parse_ast_node(node_dict["rightHandSide"], G) parsed_node = Assignment( node_id=node_id, node_type=node_type, left_hand_side=left_hand_side, operator=node_dict.get("operator", ""), right_hand_side=right_hand_side, type_descriptions=node_dict.get("typeDescriptions", {}), src=src, children=[], ) G.add_edge( parsed_node.get_display_name(), left_hand_side.get_display_name() ) G.add_edge( parsed_node.get_display_name(), right_hand_side.get_display_name() ) case "ExpressionStatement": expression, G = parse_ast_node(node_dict["expression"], G) parsed_node = ExpressionStatement( node_id=node_id, node_type=node_type, expression=expression, src=src, children=[], ) G.add_edge(parsed_node.get_display_name(), expression.get_display_name()) case "Identifier": parsed_node = Identifier( node_id=node_id, node_type=node_type, name=node_dict.get("name", ""), overloaded_declarations=node_dict.get("overloadedDeclarations", []), referenced_declaration=node_dict.get("referencedDeclaration", 0), type_descriptions=node_dict.get("typeDescriptions", {}), src=src, children=[], ) case "FunctionCall": arguments = [] for arg in node_dict.get("arguments", []): parsed_arg, G = parse_ast_node(arg, G) arguments.append(parsed_arg) expression, G = parse_ast_node(node_dict["expression"], G) parsed_node = FunctionCall( node_id=node_id, node_type=node_type, arguments=arguments, expression=expression, is_constant=node_dict.get("isConstant", False), is_lvalue=node_dict.get("isLValue", False), is_pure=node_dict.get("isPure", False), kind=node_dict.get("kind", ""), lvalue_requested=node_dict.get("lValueRequested", False), type_descriptions=node_dict.get("typeDescriptions", {}), src=src, children=[], ) for arg in arguments: G.add_edge(parsed_node.get_display_name(), arg.get_display_name()) G.add_edge(parsed_node.get_display_name(), expression.get_display_name()) case "EmitStatement": event_call, G = parse_ast_node(node_dict["eventCall"], G) parsed_node = EmitStatement( node_id=node_dict.get("id", 0), node_type=node_dict.get("nodeType", ""), event_call=event_call, src=node_dict.get("src", ""), children=[], ) G.add_edge(parsed_node.get_display_name(), event_call.get_display_name()) case "PlaceholderStatement": parsed_node = ASTNode( node_id=node_dict.get("id", 0), node_type=node_dict.get("nodeType", ""), src=node_dict.get("src", ""), children=[], ) case "IfStatement": condition, G = parse_ast_node(node_dict["condition"], G) trueBody, G = parse_ast_node(node_dict["trueBody"], G) falseBody, G = ( parse_ast_node(node_dict["falseBody"], G) if "falseBody" in node_dict else (None, G) ) parsed_node = IfStatement( node_id=node_dict.get("id", 0), node_type=node_dict.get("nodeType", ""), condition=condition, trueBody=trueBody, falseBody=falseBody, src=node_dict.get("src", ""), children=[], ) G.add_edge(parsed_node.get_display_name(), condition.get_display_name()) G.add_edge(condition.get_display_name(), trueBody.get_display_name()) if falseBody: G.add_edge(condition.get_display_name(), falseBody.get_display_name()) case "Return": expression, G = ( parse_ast_node(node_dict["expression"], G) if "expression" in node_dict else (None, G) )
def parse_ast_node(node_dict, G, parent=None): """ Parses an AST node and creates an instance of the corresponding Python class. """ absolute_path = node_dict.get("absolutePath") exported_symbols = node_dict.get("exportedSymbols", {}) node_id = node_dict.get("id", 0) license = node_dict.get("license") node_type = node_dict.get("nodeType") child_dicts = node_dict.get("nodes", []) # List of child node dictionaries src = node_dict.get("src") match node_type: case "SourceUnit": parsed_node = SourceUnit( absolute_path=absolute_path, exported_symbols=exported_symbols, node_id=node_id, license=license, node_type=node_type, src=src, children=[], ) case "PragmaDirective": parsed_node = PragmaDirective( node_id=node_id, node_type=node_type, literals=node_dict.get("literals", []), src=src, children=[], ) case "ImportDirective": symbol_aliases = [ SymbolAlias( foreign=Identifier( node_id=alias["foreign"].get("id", 0), node_type=alias["foreign"].get("nodeType", ""), name=alias["foreign"].get("name", ""), overloaded_declarations=alias["foreign"].get( "overloadedDeclarations", [] ), type_descriptions=alias["foreign"].get("typeDescriptions", {}), src=alias["foreign"].get("src", ""), children=[], ), name_location=alias.get("nameLocation", ""), ) for alias in node_dict.get("symbolAliases", []) ] parsed_node = ImportDirective( node_id=node_dict.get("id", 0), node_type=node_type, file=node_dict.get("file"), name_location=node_dict.get("nameLocation"), scope=node_dict.get("scope"), source_unit=node_dict.get("sourceUnit"), src=node_dict.get("src"), symbol_aliases=symbol_aliases, unit_alias=node_dict.get("unitAlias", ""), children=[], ) case "ContractDefinition": parsed_node = ContractDefinition( node_id=node_dict.get("id", 0), node_type=node_dict.get("nodeType"), abstract=node_dict.get("abstract", False), base_contracts=node_dict.get("baseContracts", []), contract_dependencies=node_dict.get("contractDependencies", []), contract_kind=node_dict.get("contractKind", ""), fully_implemented=node_dict.get("fullyImplemented", False), linearized_base_contracts=node_dict.get("linearizedBaseContracts", []), name=node_dict.get("name", ""), name_location=node_dict.get("nameLocation", ""), scope=node_dict.get("scope", 0), src=node_dict.get("src", ""), used_errors=node_dict.get("usedErrors", []), children=[], ) case "FunctionDefinition": # Parsing parameters parameters = [] params_node = node_dict.get("parameters", {}).get("parameters", []) for param in params_node: parsed_param, G = parse_ast_node(param, G) parameters.append(parsed_param) # Parsing return parameters return_parameters = [] params_node = node_dict.get("returnParameters", {}).get("parameters", []) for param in params_node: parsed_param, G = parse_ast_node(param, G) return_parameters.append(parsed_param) body, G = ( parse_ast_node(node_dict.get("body", {}), G) if "body" in node_dict else (None, G) ) parsed_node = FunctionDefinition( node_id=node_dict.get("id", 0), node_type=node_type, function_selector=node_dict.get("functionSelector", ""), implemented=node_dict.get("implemented", False), kind=node_dict.get("kind", ""), modifiers=node_dict.get("modifiers", []), name=node_dict.get("name", ""), parameters=parameters, return_parameters=return_parameters, scope=node_dict.get("scope", 0), src=node_dict.get("src", ""), state_mutability=node_dict.get("stateMutability", ""), virtual=node_dict.get("virtual", False), visibility=node_dict.get("visibility", ""), body=body, children=[], ) if body: G.add_edge(parsed_node.get_display_name(), body.get_display_name()) for param in parameters: G.add_edge(parsed_node.get_display_name(), param.get_display_name()) for ret_param in parameters: G.add_edge(parsed_node.get_display_name(), ret_param.get_display_name()) case "VariableDeclaration": parsed_node = VariableDeclaration( node_id=node_dict.get("id", 0), node_type=node_dict.get("nodeType", ""), constant=node_dict.get("constant", False), function_selector=node_dict.get("functionSelector"), mutability=node_dict.get("mutability", ""), name=node_dict.get("name", ""), scope=node_dict.get("scope", 0), src=node_dict.get("src", ""), state_variable=node_dict.get("stateVariable", False), storage_location=node_dict.get("storageLocation", ""), type_descriptions=node_dict.get("typeDescriptions", {}), typeName=node_dict.get("typeName", {}), visibility=node_dict.get("visibility", ""), # Handling optional 'value' field value=( LiteralValue( node_id=node_dict.get("value", {}).get("id", 0), node_type=node_dict.get("value", {}).get("nodeType", ""), hex_value=node_dict.get("value", {}).get("hexValue", ""), is_constant=node_dict.get("value", {}).get("isConstant", False), is_lvalue=node_dict.get("value", {}).get("isLValue", False), is_pure=node_dict.get("value", {}).get("isPure", True), kind=node_dict.get("value", {}).get("kind", ""), lvalue_requested=node_dict.get("value", {}).get( "lValueRequested", False ), src=node_dict.get("value", {}).get("src", ""), subdenomination=node_dict.get("value", {}).get( "subdenomination", "" ), type_descriptions=node_dict.get("value", {}).get( "typeDescriptions", {} ), value=node_dict.get("value", {}).get("value", ""), children=[], ) ) if "value" in node_dict else None, children=[], ) case "UsingForDirective": library_name_node = node_dict.get("libraryName", {}) library_name = IdentifierPath( node_id=library_name_node.get("id", 0), node_type=library_name_node.get("nodeType", ""), name=library_name_node.get("name", ""), referencedDeclaration=library_name_node.get("referencedDeclaration", 0), src=library_name_node.get("src", ""), children=[], ) type_name_node = node_dict.get("typeName", {}) type_name_path_node = type_name_node.get("pathNode", {}) type_name = UserDefinedTypeName( node_id=type_name_node.get("id", 0), node_type=type_name_node.get("nodeType", ""), pathNode=IdentifierPath( node_id=type_name_path_node.get("id", 0), node_type=type_name_path_node.get("nodeType", ""), name=type_name_path_node.get("name", ""), referencedDeclaration=type_name_path_node.get( "referencedDeclaration", 0 ), src=type_name_path_node.get("src", ""), children=[], ), referencedDeclaration=type_name_node.get("referencedDeclaration", 0), src=type_name_node.get("src", ""), children=[], ) parsed_node = UsingForDirective( node_id=node_dict.get("id", 0), node_type=node_dict.get("nodeType", ""), src=node_dict.get("src", ""), libraryName=library_name, typeName=type_name, children=[], ) case "ErrorDefinition": parameters = [] params_node = node_dict.get("parameters", {}).get("parameters", []) for param in params_node: parsed_param, G = parse_ast_node(param, G) parameters.append(parsed_param) parsed_node = ErrorDefinition( node_id=node_dict.get("id", 0), node_type=node_dict.get("nodeType", ""), name=node_dict.get("name", ""), parameters=ParameterList( node_id=node_dict.get("parameters", {}).get("id", 0), node_type=node_dict.get("parameters", {}).get("nodeType", ""), parameters=parameters, src=node_dict.get("parameters", {}).get("src", ""), children=[], ), src=node_dict.get("src", ""), children=[], ) for param in parameters: G.add_edge(parsed_node.get_display_name(), param.get_display_name()) case "EventDefinition": parameters = [] params_node = node_dict.get("parameters", {}).get("parameters", []) for param in params_node: parsed_param, G = parse_ast_node(param, G) parameters.append(parsed_param) parsed_node = EventDefinition( node_id=node_dict.get("id", 0), node_type=node_dict.get("nodeType", ""), anonymous=node_dict.get("anonymous", False), name=node_dict.get("name", ""), parameters=ParameterList( node_id=node_dict.get("parameters", {}).get("id", 0), node_type=node_dict.get("parameters", {}).get("nodeType", ""), parameters=parameters, src=node_dict.get("parameters", {}).get("src", ""), children=[], ), src=node_dict.get("src", ""), children=[], ) for param in parameters: G.add_edge(parsed_node.get_display_name(), param.get_display_name()) case "ModifierDefinition": parameters, G = parse_ast_node(node_dict["parameters"], G) body, G = parse_ast_node(node_dict["body"], G) parsed_node = ModifierDefinition( node_id=node_id, node_type=node_type, name=node_dict.get("name"), name_location=node_dict.get("nameLocation"), parameters=parameters, body=body, virtual=node_dict.get("virtual", False), visibility=node_dict.get("visibility"), src=src, children=[], ) G.add_edge(parsed_node.get_display_name(), parameters.get_display_name()) G.add_edge(parsed_node.get_display_name(), body.get_display_name()) case "Block" | "UncheckedBlock": statements = [] for stmt in node_dict.get("statements", []): if stmt: parsed_stmt, G = parse_ast_node(stmt, G) statements.append(parsed_stmt) parsed_node = Block( node_id=node_id, node_type=node_type, statements=statements, src=src, children=[], ) for stmt in statements: G.add_edge(parsed_node.get_display_name(), stmt.get_display_name()) case "Assignment": left_hand_side, G = parse_ast_node(node_dict["leftHandSide"], G) right_hand_side, G = parse_ast_node(node_dict["rightHandSide"], G) parsed_node = Assignment( node_id=node_id, node_type=node_type, left_hand_side=left_hand_side, operator=node_dict.get("operator", ""), right_hand_side=right_hand_side, type_descriptions=node_dict.get("typeDescriptions", {}), src=src, children=[], ) G.add_edge( parsed_node.get_display_name(), left_hand_side.get_display_name() ) G.add_edge( parsed_node.get_display_name(), right_hand_side.get_display_name() ) case "ExpressionStatement": expression, G = parse_ast_node(node_dict["expression"], G) parsed_node = ExpressionStatement( node_id=node_id, node_type=node_type, expression=expression, src=src, children=[], ) G.add_edge(parsed_node.get_display_name(), expression.get_display_name()) case "Identifier": parsed_node = Identifier( node_id=node_id, node_type=node_type, name=node_dict.get("name", ""), overloaded_declarations=node_dict.get("overloadedDeclarations", []), referenced_declaration=node_dict.get("referencedDeclaration", 0), type_descriptions=node_dict.get("typeDescriptions", {}), src=src, children=[], ) case "FunctionCall": arguments = [] for arg in node_dict.get("arguments", []): parsed_arg, G = parse_ast_node(arg, G) arguments.append(parsed_arg) expression, G = parse_ast_node(node_dict["expression"], G) parsed_node = FunctionCall( node_id=node_id, node_type=node_type, arguments=arguments, expression=expression, is_constant=node_dict.get("isConstant", False), is_lvalue=node_dict.get("isLValue", False), is_pure=node_dict.get("isPure", False), kind=node_dict.get("kind", ""), lvalue_requested=node_dict.get("lValueRequested", False), type_descriptions=node_dict.get("typeDescriptions", {}), src=src, children=[], ) for arg in arguments: G.add_edge(parsed_node.get_display_name(), arg.get_display_name()) G.add_edge(parsed_node.get_display_name(), expression.get_display_name()) case "EmitStatement": event_call, G = parse_ast_node(node_dict["eventCall"], G) parsed_node = EmitStatement( node_id=node_dict.get("id", 0), node_type=node_dict.get("nodeType", ""), event_call=event_call, src=node_dict.get("src", ""), children=[], ) G.add_edge(parsed_node.get_display_name(), event_call.get_display_name()) case "PlaceholderStatement": parsed_node = ASTNode( node_id=node_dict.get("id", 0), node_type=node_dict.get("nodeType", ""), src=node_dict.get("src", ""), children=[], ) case "IfStatement": condition, G = parse_ast_node(node_dict["condition"], G) trueBody, G = parse_ast_node(node_dict["trueBody"], G) falseBody, G = ( parse_ast_node(node_dict["falseBody"], G) if "falseBody" in node_dict else (None, G) ) parsed_node = IfStatement( node_id=node_dict.get("id", 0), node_type=node_dict.get("nodeType", ""), condition=condition, trueBody=trueBody, falseBody=falseBody, src=node_dict.get("src", ""), children=[], ) G.add_edge(parsed_node.get_display_name(), condition.get_display_name()) G.add_edge(condition.get_display_name(), trueBody.get_display_name()) if falseBody: G.add_edge(condition.get_display_name(), falseBody.get_display_name()) case "Return": expression, G = ( parse_ast_node(node_dict["expression"], G) if "expression" in node_dict else (None, G) )
parsed_node = ReturnValue(
23
2023-12-03 07:44:01+00:00
12k
wadiuvatzy/SAM-G
envs/robosuiteVGB/robosuitevgb/vgb_wrapper_rs100.py
[ { "identifier": "CustomMujocoXML", "path": "envs/robosuiteVGB/robosuitevgb/secant/envs/robosuite/custom_xml.py", "snippet": "class CustomMujocoXML(ET.ElementTree):\n \"\"\"\n Class to modify the Mujoco XML of Mujoco-enabled env\n \"\"\"\n\n def __init__(self, element=None, file=None):\n ...
import robosuite as suite import gym import numpy as np import random import copy import xml.etree.ElementTree as ET import numpy as np from robosuite.controllers import load_controller_config from gym.spaces import Box from typing import Union, List, Optional, Dict from .secant.envs.robosuite.custom_xml import CustomMujocoXML, XMLTextureModder from .secant.utils.misc import render_img from .secant.envs.robosuite.utils import get_obs_shape_from_dict from .secant.envs.robosuite.preset_customization import ( DEFAULT_TEXTURE_ALIAS, DEFAULT_TASK_TEXTURE_LIST, ALL_PRESET_ARGUMENTS, ALL_TEXTURE_PRESETS, ALL_COLOR_PRESETS, ALL_CAMERA_PRESETS, ALL_LIGHTING_PRESETS, get_custom_reset_config, ) from robosuite.utils.mjmod import CameraModder, LightingModder, TextureModder from robosuite.wrappers import Wrapper
7,371
# **self.dynamics_randomization_args, # ) # self.modders.append(self.dynamics_modder) def _initialize_xml_modder(self, custom_texture: Optional[Union[str, dict]]): if custom_texture is not None: if isinstance(custom_texture, str): custom_texture = ALL_TEXTURE_PRESETS.get(custom_texture, None) config = custom_texture.copy() if custom_texture.get("tex_to_change", None) is None: config["tex_to_change"] = DEFAULT_TASK_TEXTURE_LIST[self.task] self.secant_modders["texture"] = XMLTextureModder(**config) def _reformat_obs(self, obs_dict, disable_channel_first=False): rgb_obs = {} state_obs = [] reformatted = {} for name, obs in obs_dict.items(): if name.endswith("_image") and "rgb" in self.obs_modality: view_name = name[:-6] if self._use_depth: depth_obs = obs_dict[view_name + "_depth"] obs = np.concatenate([obs, depth_obs[:, :, np.newaxis]], axis=2) obs = np.flipud(obs) if self._channel_first and not disable_channel_first: obs = np.transpose(obs, (2, 0, 1)) rgb_obs[view_name] = obs elif name.endswith("state") and "state" in self.obs_modality: state_obs.append(obs) if "rgb" in self.obs_modality: if len(rgb_obs.keys()) == 1: rgb_obs = list(rgb_obs.values())[0] reformatted["rgb"] = rgb_obs if "state" in self.obs_modality: reformatted["state"] = np.concatenate(state_obs) return reformatted def get_mujoco_xml(self): return CustomMujocoXML.build_from_env(self) def reset( self, xml_string: Optional[Union[str, List]] = None, custom_texture: Optional[Union[str, dict]] = None, ): if xml_string is not None: if xml_string != self._reset_config.get("xml_string", None): self._reset_config["xml_string"] = xml_string.copy() else: xml_string = None if custom_texture is not None: if custom_texture != self._reset_config.get("custom_texture", None): self._reset_config["custom_texture"] = copy.deepcopy(custom_texture) self._initialize_xml_modder(custom_texture) else: custom_texture = None # reset from xml should only be called if a different texture/xml is requested reset_from_xml = ( xml_string is not None or custom_texture is not None or self.reset_xml_next ) if reset_from_xml: self._reset_from_xml(xml_string) self.env.deterministic_reset = False else: self.env.reset() # self.env.reset() self.env._reset_internal() self.reset_xml_next = False if self.moving_light: self.step_pos = 0.4 self.step_diffuse = 0.01 self.light_pos_range = [self.env.sim.model.light_pos[:,1] - 20, self.env.sim.model.light_pos[:,1] + 20] self.light_diffuse_range = [max(self.env.sim.model.light_diffuse[:,1] - 0.5, 0.15), min(self.env.sim.model.light_diffuse[:,1] + 0.2, 0.95)] # TODO may change the order # self.restore_default_domain() # # save the original env parameters # self.save_default_domain() # reset counter for doing domain randomization at a particular frequency # self.step_counter = 0 # update sims self._initialize_modders() for modder in self.modders: modder.update_sim(self.env.sim) self.randomize_domain() self.env.deterministic_reset = False self.env._reset_internal() return self._reformat_obs(self.env._get_observations(force_update=True)) def _reset_from_xml(self, xml_string): if xml_string is not None: if isinstance(xml_string, list): xml_string = np.random.choice(xml_string) try: root = ET.fromstring(xml_string) except ET.ParseError: raise ValueError("Input xml_string is not a valid XML string") mujoco_xml = CustomMujocoXML.build_from_element(root) else: mujoco_xml = self.get_mujoco_xml() # f = open("twoarmsaaa.xml", 'w') # f.write(mujoco_xml.to_string()) # f.close() if self.secant_modders["texture"] is not None: self.secant_modders["texture"].random_texture_change(mujoco_xml) # TODO may change the texture self.env.reset_from_xml_string(mujoco_xml.to_string()) def get_tex_candidate(self): """ Get a tex_candidate dictionary from the current env. The tex_candidate dictionary can be passed to custom_texture in reset() """ mujoco_xml = self.get_mujoco_xml() texture_list = DEFAULT_TASK_TEXTURE_LIST[self.task] tex_candidates = {} for alias in texture_list:
ALL_ROBOTS = list(suite.ALL_ROBOTS) class VGBWrapper(gym.core.Env, Wrapper): """ A gym style adapter for Robosuite """ def __init__( self, env, color_randomization_args, camera_randomization_args, lighting_randomization_args, dynamics_randomization_args, task: str, obs_modality: Optional[List[str]] = ["rgb"], episode_length: int = 500, hard_reset: bool = False, channel_first: bool = True, camera_depths: bool = False, custom_reset_config: Optional[Union[Dict, str]] = None, mode: bool = "train", scene_id: Optional[int] = 0, verbose: bool = False, seed=None, randomize_color=True, randomize_camera=True, randomize_lighting=True, randomize_dynamics=True, randomize_on_reset=True, moving_light=False, ): super().__init__(env) self.seed = seed if seed is not None: self.random_state = np.random.RandomState(seed) else: self.random_state = None self.randomize_color = randomize_color self.randomize_camera = randomize_camera self.randomize_lighting = randomize_lighting self.randomize_dynamics = randomize_dynamics self.color_randomization_args = color_randomization_args self.camera_randomization_args = camera_randomization_args self.lighting_randomization_args = lighting_randomization_args self.dynamics_randomization_args = dynamics_randomization_args self.randomize_on_reset = randomize_on_reset self.moving_light = moving_light self.modders = [] # self._initialize_modders() # self.save_default_domain() if isinstance(scene_id, int): if verbose: print(f"{mode} scene_id: {scene_id}") custom_reset_config = get_custom_reset_config( task=task, mode=mode, scene_id=scene_id ) self.task = task self.headless = True self.obs_modality = ( ["rgb", "state"] if obs_modality is None else obs_modality.copy() ) assert len(self.obs_modality) > 0, "Observation must have at least one modality" for modal in self.obs_modality: assert modal in [ "rgb", "state", ], "Only 'rgb' and 'state' are supported as modality" if "rgb" in self.obs_modality: self._use_rgb = True else: self._use_rgb = False self._render_camera = "frontview" self._channel_first = channel_first self._use_depth = camera_depths self._max_episode_steps = episode_length self._hard_reset = hard_reset assert mode in ["train", "eval-easy", "eval-hard", "eval-extreme"] self._mode = mode self._scene_id = scene_id self.env = env self.secant_modders = dict.fromkeys(["texture"]) if custom_reset_config is not None: if isinstance(custom_reset_config, str): custom_reset_config = ALL_PRESET_ARGUMENTS.get( custom_reset_config, None ) self._reset_config = custom_reset_config xml_string = custom_reset_config.get("xml_string") self._initialize_xml_modder(custom_reset_config.get("custom_texture", None)) if ( xml_string is not None or custom_reset_config.get("custom_texture") is not None ): self.reset_xml_next = True else: self._reset_config = dict.fromkeys( [ "xml_string", "custom_texture", ] ) self.reset_xml_next = False obs_dict = self.env.observation_spec() self.observation_space = get_obs_shape_from_dict(self._reformat_obs(obs_dict)) low, high = self.env.action_spec self.action_space = Box(low=low, high=high) def _initialize_modders(self): if self.randomize_color: self.tex_modder = TextureModder( sim=self.env.sim, random_state=self.random_state, **self.color_randomization_args ) self.modders.append(self.tex_modder) if self.randomize_camera: self.camera_modder = CameraModder( sim=self.env.sim, random_state=self.random_state, **self.camera_randomization_args, ) self.modders.append(self.camera_modder) if self.randomize_lighting: self.light_modder = LightingModder( sim=self.env.sim, random_state=self.random_state, **self.lighting_randomization_args, ) self.modders.append(self.light_modder) # if self.randomize_dynamics: # self.dynamics_modder = DynamicsModder( # sim=self.env.sim, # random_state=self.random_state, # **self.dynamics_randomization_args, # ) # self.modders.append(self.dynamics_modder) def _initialize_xml_modder(self, custom_texture: Optional[Union[str, dict]]): if custom_texture is not None: if isinstance(custom_texture, str): custom_texture = ALL_TEXTURE_PRESETS.get(custom_texture, None) config = custom_texture.copy() if custom_texture.get("tex_to_change", None) is None: config["tex_to_change"] = DEFAULT_TASK_TEXTURE_LIST[self.task] self.secant_modders["texture"] = XMLTextureModder(**config) def _reformat_obs(self, obs_dict, disable_channel_first=False): rgb_obs = {} state_obs = [] reformatted = {} for name, obs in obs_dict.items(): if name.endswith("_image") and "rgb" in self.obs_modality: view_name = name[:-6] if self._use_depth: depth_obs = obs_dict[view_name + "_depth"] obs = np.concatenate([obs, depth_obs[:, :, np.newaxis]], axis=2) obs = np.flipud(obs) if self._channel_first and not disable_channel_first: obs = np.transpose(obs, (2, 0, 1)) rgb_obs[view_name] = obs elif name.endswith("state") and "state" in self.obs_modality: state_obs.append(obs) if "rgb" in self.obs_modality: if len(rgb_obs.keys()) == 1: rgb_obs = list(rgb_obs.values())[0] reformatted["rgb"] = rgb_obs if "state" in self.obs_modality: reformatted["state"] = np.concatenate(state_obs) return reformatted def get_mujoco_xml(self): return CustomMujocoXML.build_from_env(self) def reset( self, xml_string: Optional[Union[str, List]] = None, custom_texture: Optional[Union[str, dict]] = None, ): if xml_string is not None: if xml_string != self._reset_config.get("xml_string", None): self._reset_config["xml_string"] = xml_string.copy() else: xml_string = None if custom_texture is not None: if custom_texture != self._reset_config.get("custom_texture", None): self._reset_config["custom_texture"] = copy.deepcopy(custom_texture) self._initialize_xml_modder(custom_texture) else: custom_texture = None # reset from xml should only be called if a different texture/xml is requested reset_from_xml = ( xml_string is not None or custom_texture is not None or self.reset_xml_next ) if reset_from_xml: self._reset_from_xml(xml_string) self.env.deterministic_reset = False else: self.env.reset() # self.env.reset() self.env._reset_internal() self.reset_xml_next = False if self.moving_light: self.step_pos = 0.4 self.step_diffuse = 0.01 self.light_pos_range = [self.env.sim.model.light_pos[:,1] - 20, self.env.sim.model.light_pos[:,1] + 20] self.light_diffuse_range = [max(self.env.sim.model.light_diffuse[:,1] - 0.5, 0.15), min(self.env.sim.model.light_diffuse[:,1] + 0.2, 0.95)] # TODO may change the order # self.restore_default_domain() # # save the original env parameters # self.save_default_domain() # reset counter for doing domain randomization at a particular frequency # self.step_counter = 0 # update sims self._initialize_modders() for modder in self.modders: modder.update_sim(self.env.sim) self.randomize_domain() self.env.deterministic_reset = False self.env._reset_internal() return self._reformat_obs(self.env._get_observations(force_update=True)) def _reset_from_xml(self, xml_string): if xml_string is not None: if isinstance(xml_string, list): xml_string = np.random.choice(xml_string) try: root = ET.fromstring(xml_string) except ET.ParseError: raise ValueError("Input xml_string is not a valid XML string") mujoco_xml = CustomMujocoXML.build_from_element(root) else: mujoco_xml = self.get_mujoco_xml() # f = open("twoarmsaaa.xml", 'w') # f.write(mujoco_xml.to_string()) # f.close() if self.secant_modders["texture"] is not None: self.secant_modders["texture"].random_texture_change(mujoco_xml) # TODO may change the texture self.env.reset_from_xml_string(mujoco_xml.to_string()) def get_tex_candidate(self): """ Get a tex_candidate dictionary from the current env. The tex_candidate dictionary can be passed to custom_texture in reset() """ mujoco_xml = self.get_mujoco_xml() texture_list = DEFAULT_TASK_TEXTURE_LIST[self.task] tex_candidates = {} for alias in texture_list:
mat_name = DEFAULT_TEXTURE_ALIAS[alias]
4
2023-12-04 10:01:22+00:00
12k
cmu-ci-lab/volumetric_opaque_solids
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('...
import os import time import logging import argparse import numpy as np import cv2 as cv import trimesh 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 from models.sampler import PointSampler from models.fields import ( RenderingNetwork, SDFNetwork, SingleVarianceNetwork, NeRF, AnisotropyNetwork ) from models.attenuation_coefficient import AttenuationCoefficient from models.renderer import Renderer from models.util import read_mesh, write_mesh, extract_geometry
10,252
logging.getLogger('matplotlib.font_manager').disabled = True class Runner: def __init__(self, conf_path, mode='train', case='CASE_NAME', is_continue=False, max_n_training_images=-1): 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.dataset = Dataset(self.conf['dataset']) self.iter_step = 0 # 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.val_mesh_freq = self.conf.get_int('train.val_mesh_freq') self.viz_deviation_freq = self.conf.get_int('train.viz_deviation_freq', 0) self.batch_size = self.conf.get_int('train.batch_size') 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.anneal_end = self.conf.get_float('train.anneal_end', default=0.0) self.max_n_training_images = max_n_training_images # Weights self.igr_weight = self.conf.get_float('train.igr_weight') self.mask_weight = self.conf.get_float('train.mask_weight') self.is_continue = is_continue self.mode = mode self.model_list = [] self.writer = None # Networks params_to_train = [] self.sdf_network = SDFNetwork(**self.conf['model.sdf_network']).to(self.device)
logging.getLogger('matplotlib.font_manager').disabled = True class Runner: def __init__(self, conf_path, mode='train', case='CASE_NAME', is_continue=False, max_n_training_images=-1): 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.dataset = Dataset(self.conf['dataset']) self.iter_step = 0 # 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.val_mesh_freq = self.conf.get_int('train.val_mesh_freq') self.viz_deviation_freq = self.conf.get_int('train.viz_deviation_freq', 0) self.batch_size = self.conf.get_int('train.batch_size') 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.anneal_end = self.conf.get_float('train.anneal_end', default=0.0) self.max_n_training_images = max_n_training_images # Weights self.igr_weight = self.conf.get_float('train.igr_weight') self.mask_weight = self.conf.get_float('train.mask_weight') self.is_continue = is_continue self.mode = mode self.model_list = [] self.writer = None # Networks params_to_train = [] self.sdf_network = SDFNetwork(**self.conf['model.sdf_network']).to(self.device)
self.deviation_network = SingleVarianceNetwork(**self.conf['model.variance_network']).to(self.device)
4
2023-11-28 03:13:44+00:00
12k
strollby/graphene-directives
graphene_directives/main.py
[ { "identifier": "Schema", "path": "graphene_directives/schema.py", "snippet": "class Schema(GrapheneSchema):\n def __init__(\n self,\n query: graphene.ObjectType = None,\n mutation: graphene.ObjectType = None,\n subscription: graphene.ObjectType = None,\n types: lis...
from typing import Collection, Type, Union from graphene import Schema as GrapheneSchema from graphql import GraphQLDirective from graphql import specified_directives from . import DirectiveValidationError from .data_models import SchemaDirective from .schema import Schema import graphene
9,384
def build_schema( query: Union[graphene.ObjectType, Type[graphene.ObjectType]] = None, mutation: Union[graphene.ObjectType, Type[graphene.ObjectType]] = None, subscription: Union[graphene.ObjectType, Type[graphene.ObjectType]] = None, types: Collection[Union[graphene.ObjectType, Type[graphene.ObjectType]]] = None, directives: Union[Collection[GraphQLDirective], None] = None, auto_camelcase: bool = True,
def build_schema( query: Union[graphene.ObjectType, Type[graphene.ObjectType]] = None, mutation: Union[graphene.ObjectType, Type[graphene.ObjectType]] = None, subscription: Union[graphene.ObjectType, Type[graphene.ObjectType]] = None, types: Collection[Union[graphene.ObjectType, Type[graphene.ObjectType]]] = None, directives: Union[Collection[GraphQLDirective], None] = None, auto_camelcase: bool = True,
schema_directives: Collection[SchemaDirective] = None,
2
2023-12-04 05:17:51+00:00
12k
weijiawu/CisDQ
mask2former_video/data_video/ytvis_eval.py
[ { "identifier": "YTVOS", "path": "mask2former_video/data_video/datasets/ytvis_api/ytvos.py", "snippet": "class YTVOS:\n def __init__(self, annotation_file=None):\n \"\"\"\n Constructor of Microsoft COCO helper class for reading and visualizing annotations.\n :param annotation_fil...
import contextlib import copy import io import itertools import json import logging import numpy as np import os import pycocotools.mask as mask_util import torch import detectron2.utils.comm as comm from collections import OrderedDict from .datasets.ytvis_api.ytvos import YTVOS from .datasets.ytvis_api.ytvoseval import YTVOSeval from tabulate import tabulate from detectron2.config import CfgNode from detectron2.data import MetadataCatalog from detectron2.evaluation import DatasetEvaluator from detectron2.utils.file_io import PathManager from detectron2.utils.logger import create_small_table
10,663
# Copyright (c) Facebook, Inc. and its affiliates. # Modified by Bowen Cheng from https://github.com/sukjunhwang/IFC class YTVISEvaluator(DatasetEvaluator): """ Evaluate AR for object proposals, AP for instance detection/segmentation, AP for keypoint detection outputs using COCO's metrics. See http://cocodataset.org/#detection-eval and http://cocodataset.org/#keypoints-eval to understand its metrics. In addition to COCO, this evaluator is able to support any bounding box detection, instance segmentation, or keypoint detection dataset. """ def __init__( self, dataset_name, tasks=None, distributed=True, output_dir=None, *, use_fast_impl=True, ): """ Args: dataset_name (str): name of the dataset to be evaluated. It must have either the following corresponding metadata: "json_file": the path to the COCO format annotation Or it must be in detectron2's standard dataset format so it can be converted to COCO format automatically. tasks (tuple[str]): tasks that can be evaluated under the given configuration. A task is one of "bbox", "segm", "keypoints". By default, will infer this automatically from predictions. distributed (True): if True, will collect results from all ranks and run evaluation in the main process. Otherwise, will only evaluate the results in the current process. output_dir (str): optional, an output directory to dump all results predicted on the dataset. The dump contains two files: 1. "instances_predictions.pth" a file in torch serialization format that contains all the raw original predictions. 2. "coco_instances_results.json" a json file in COCO's result format. use_fast_impl (bool): use a fast but **unofficial** implementation to compute AP. Although the results should be very close to the official implementation in COCO API, it is still recommended to compute results with the official API for use in papers. The faster implementation also uses more RAM. """ self._logger = logging.getLogger(__name__) self._distributed = distributed self._output_dir = output_dir self._use_fast_impl = use_fast_impl if tasks is not None and isinstance(tasks, CfgNode): self._logger.warning( "COCO Evaluator instantiated using config, this is deprecated behavior." " Please pass in explicit arguments instead." ) self._tasks = None # Infering it from predictions should be better else: self._tasks = tasks self._cpu_device = torch.device("cpu") self._metadata = MetadataCatalog.get(dataset_name) json_file = PathManager.get_local_path(self._metadata.json_file) with contextlib.redirect_stdout(io.StringIO()):
# Copyright (c) Facebook, Inc. and its affiliates. # Modified by Bowen Cheng from https://github.com/sukjunhwang/IFC class YTVISEvaluator(DatasetEvaluator): """ Evaluate AR for object proposals, AP for instance detection/segmentation, AP for keypoint detection outputs using COCO's metrics. See http://cocodataset.org/#detection-eval and http://cocodataset.org/#keypoints-eval to understand its metrics. In addition to COCO, this evaluator is able to support any bounding box detection, instance segmentation, or keypoint detection dataset. """ def __init__( self, dataset_name, tasks=None, distributed=True, output_dir=None, *, use_fast_impl=True, ): """ Args: dataset_name (str): name of the dataset to be evaluated. It must have either the following corresponding metadata: "json_file": the path to the COCO format annotation Or it must be in detectron2's standard dataset format so it can be converted to COCO format automatically. tasks (tuple[str]): tasks that can be evaluated under the given configuration. A task is one of "bbox", "segm", "keypoints". By default, will infer this automatically from predictions. distributed (True): if True, will collect results from all ranks and run evaluation in the main process. Otherwise, will only evaluate the results in the current process. output_dir (str): optional, an output directory to dump all results predicted on the dataset. The dump contains two files: 1. "instances_predictions.pth" a file in torch serialization format that contains all the raw original predictions. 2. "coco_instances_results.json" a json file in COCO's result format. use_fast_impl (bool): use a fast but **unofficial** implementation to compute AP. Although the results should be very close to the official implementation in COCO API, it is still recommended to compute results with the official API for use in papers. The faster implementation also uses more RAM. """ self._logger = logging.getLogger(__name__) self._distributed = distributed self._output_dir = output_dir self._use_fast_impl = use_fast_impl if tasks is not None and isinstance(tasks, CfgNode): self._logger.warning( "COCO Evaluator instantiated using config, this is deprecated behavior." " Please pass in explicit arguments instead." ) self._tasks = None # Infering it from predictions should be better else: self._tasks = tasks self._cpu_device = torch.device("cpu") self._metadata = MetadataCatalog.get(dataset_name) json_file = PathManager.get_local_path(self._metadata.json_file) with contextlib.redirect_stdout(io.StringIO()):
self._ytvis_api = YTVOS(json_file)
0
2023-11-28 10:33:40+00:00
12k
KieDani/Towards_3D_Object_Localization
general/train.py
[ { "identifier": "create_heatmaps", "path": "helper.py", "snippet": "def create_heatmaps(joint, output_size=(480, 480), sigma=8, factor=1):\n '''\n create heatmap from keypoints x, y\n joint: (y, x)\n output_size: (height, width)\n '''\n gaus2d = lambda x, y: 100 * np.exp(-((x ** 2 + y ...
import os import argparse import torch import random import einops as eo import matplotlib.pyplot as plt import numpy as np import scipy import cv2 import os from tqdm import tqdm from torch.utils.tensorboard import SummaryWriter from helper import create_heatmaps, seed_worker, save_models, get_reprojectionloss from helper import img_to_cam, cam_to_img, cam_to_world, update_ema from general.model import get_PEN, get_PAF from general.dataset import get_dataset from general.evaluate import plot2d, plot3d from general.config import MyConfig from general.transforms import train_transform, val_transform, denorm
8,594
for i, data_dict in enumerate(tqdm(valloader)): for xml_num, stuff in data_dict.items(): video, vidlabel, vidheatmap, eM, iM, d3label, cam_num, timestamps = stuff t = 1 t_steps = [t + ts for ts in timesteps] images_0 = video[:, t - 1:t + 2] images_T = video[:, t_steps] timestamps_T = timestamps[:, t-1:t+forecast_length+1] images_all = video[:, t:t+forecast_length] d3labels_all = d3label[:, t:t+forecast_length] imlabels = vidlabel[:, [t] + t_steps] imheatmaps = vidheatmap[:, t_steps] images_0, images_T, imlabels, imheatmaps = images_0.to(device), images_T.to(device), imlabels.to(device), imheatmaps.to(device) images_all, d3labels_all = images_all.to(device), d3labels_all.to(device) eM, iM = eM.to(device), iM.to(device) timestamps_T = timestamps_T.to(device) images_0 = eo.rearrange(images_0, 'b t c h w -> (b t) c h w') heatmap, depthmap = coord_model(images_0) coords = coord_model.get_coords3D(heatmap, depthmap) coords = eo.rearrange(coords, '(b t) d -> b t d', t=3) #heatmap_0 = eo.rearrange(heatmap, '(b t) c h w -> b t c h w', t=3)[:, 1] coords_0 = coords[:, 1] images_T = eo.rearrange(images_T, 'b t c h w -> (b t) c h w') heatmap_T, depthmap_T = coord_model(images_T) coords_T = coord_model.get_coords3D(heatmap_T, depthmap_T) coords_T = eo.rearrange(coords_T, '(b t) d -> b t d', t=len(t_steps)) images_T = eo.rearrange(images_T, '(b t) c h w -> b t c h w', t=len(t_steps)) heatmap_T = eo.rearrange(heatmap_T, '(b t) c h w -> b t c h w', t=len(t_steps)) #f = iM[:, 1, 1] __, __, H, W = images_0.shape coords_c = img_to_cam(coords, iM, original_size, (H, W)) #pred_coords = forec_model(coords_c, forecast_length=forecast_length) pred_coords = forec_model(coords_c, timestamps=timestamps_T, forecast_length=forecast_length, extrinsic_matrix = eM.to(device), xml_num=xml_num) pred_coords_T = pred_coords[:, timesteps] images_all = eo.rearrange(images_all, 'b t c h w -> (b t) c h w') heatmap_all, depthmap_all = coord_model(images_all) coords_all = coord_model.get_coords3D(heatmap_all, depthmap_all) coords_all = eo.rearrange(coords_all, '(b t) d -> b t d', t=forecast_length) f = iM[:, 1, 1] __, __, H, W = images_all.shape coords_all = img_to_cam(coords_all, iM, original_size, (H, W)) distance = (coords_all - d3labels_all).double().pow(2).sum(2).sqrt() rel_distance = distance / d3labels_all.double().pow(2).sum(2).sqrt() pred_coords_T_B = cam_to_img(pred_coords_T, iM, original_size, (H, W))[..., :2] loss_reproject_tmp = loss_fn_coord(pred_coords_T_B, coords_T[..., :2]) loss_2Dcoord_tmp = loss_fn_coord(coords_0[:, :2], imlabels[:, 0]) * 1e-3 # heatmap_T = eo.rearrange(heatmap_T, 'b t c h w -> b t c (h w)').softmax(dim=-1) * imheatmaps.sum(dim=[-1, -2]).unsqueeze(-1) # heatmap_T = eo.rearrange(heatmap_T, 'b t c (h w) -> b t c h w', h=H, w=W) loss_2Dheatmap_tmp = loss_fn(heatmap_T, imheatmaps) for cn_ind in range(cam_num.shape[0]): cn = cam_num[cn_ind].item() number_metrics[xml_num][cn] += 1 losses_metrics[xml_num]['distance_to_gt'][cn] += distance[cn_ind].mean().item() losses_metrics[xml_num]['rel_distance_to_gt'][cn] += rel_distance[cn_ind].mean().item() losses_metrics[xml_num]['loss_reproject'][cn] += loss_reproject_tmp[cn_ind].mean().cpu().item() # maybe also add at time t losses_metrics[xml_num]['loss_2Dcoord'][cn] += loss_2Dcoord_tmp[cn_ind].mean().cpu().item() losses_metrics[xml_num]['loss_2Dheatmap'][cn] += loss_2Dheatmap_tmp[cn_ind].mean().cpu().item() distance_to_gt = np.mean([losses_metrics[xml_num]['distance_to_gt'][cn] / number_metrics[xml_num][cn] for cn in range(num_cameras) for xml_num in range(num_environments)]) loss_2Dheatmap = np.mean([losses_metrics[xml_num]['loss_2Dheatmap'][cn] / number_metrics[xml_num][cn] for cn in range(num_cameras) for xml_num in range(num_environments)]) loss_2Dcoord = np.mean([losses_metrics[xml_num]['loss_2Dcoord'][cn] / number_metrics[xml_num][cn] for cn in range(num_cameras) for xml_num in range(num_environments)]) loss_reproject = np.mean([losses_metrics[xml_num]['loss_reproject'][cn] / number_metrics[xml_num][cn] for cn in range(num_cameras) for xml_num in range(num_environments)]) rel_distance_to_gt = np.mean([losses_metrics[xml_num]['rel_distance_to_gt'][cn] / number_metrics[xml_num][cn] for cn in range(num_cameras) for xml_num in range(num_environments)]) for xml_num in range(num_environments): for metric in losses_metrics[xml_num].keys(): for cn in range(num_cameras): losses_metrics[xml_num][metric][cn] /= number_metrics[xml_num][cn] for xmlnum in range(num_environments): for camnum in range(num_cameras): writer.add_scalar(f'Validation Loss/env{xmlnum}/camera{camnum}/reprojection loss', losses_metrics[xml_num]['loss_reproject'][camnum], epoch) writer.add_scalar(f'Validation Loss/env{xmlnum}/camera{camnum}/2D coordinate loss', losses_metrics[xml_num]['loss_2Dcoord'][camnum], epoch) writer.add_scalar(f'Validation Loss/env{xmlnum}/camera{camnum}/2D heatmap loss', losses_metrics[xml_num]['loss_2Dheatmap'][camnum], epoch) writer.add_scalar(f'Validation Metric/env{xmlnum}/camera{camnum}/Distance to groundtruth', losses_metrics[xml_num]['distance_to_gt'][camnum], epoch) writer.add_scalar(f'Validation relative Metric/env{xmlnum}/camera{camnum}/Relative distance to groundtruth', losses_metrics[xml_num]['rel_distance_to_gt'][camnum], epoch) writer.add_text(f'Validation/env{0}/camera{camnum}/coord_model t=0:', ''.join((str(coords_c[0, 1, 0].item()), ', ', str(coords_c[0, 1, 1].item()), ', ', str(coords_c[0, 1, 2].item()))), epoch) coords_T_c = img_to_cam(coords_T, iM, original_size, (H, W))[:, -1] writer.add_text(f'Validation/env{0}/camera{camnum}/coord_model t=T:', ''.join((str(coords_T_c[0, 1].item()), ', ', str(coords_T_c[0, 0].item()), ', ', str(coords_T_c[0, 2].item()))), epoch) writer.add_text(f'Validation/env{0}/camera{camnum}/forec_model t=T:', ''.join((str(pred_coords_T[0, -1, 0].item()), ', ', str(pred_coords_T[0, -1, 1].item()), ', ', str(pred_coords_T[0, -1, 2].item()))), epoch) writer.add_text(f'Validation/env{0}/camera{camnum}/ground truth t=0:', ''.join((str(d3label[0, t, 1].item()), ', ', str(d3label[0, t, 0].item()), ', ', str(d3label[0, t, 2].item()))), epoch) writer.add_text(f'Validation/env{0}/camera{camnum}/ground truth t=T:', ''.join((str(d3label[0, t + forecast_length - 1, 1].item()), ', ', str(d3label[0, t + forecast_length - 1, 0].item()), ', ', str(d3label[0, t + forecast_length - 1, 2].item()))), epoch) if hasattr(forec_model, 'analyticPhysics') and hasattr(forec_model.analyticPhysics, 'g'): writer.add_text('model parameters:', f'{forec_model.analyticPhysics.g.item()}', epoch) elif hasattr(forec_model, 'torchdynnets') and hasattr(forec_model.torchdynnets[0].vf.vf, 'g'): writer.add_text('model parameters:', f'{forec_model.torchdynnets[0].vf.vf.g.item()}', epoch) if hasattr(forec_model, 'analyticPhysics') and hasattr(forec_model.analyticPhysics, 'k'): writer.add_text('model parameters:', f'{forec_model.analyticPhysics.k.item()}', epoch) elif hasattr(forec_model, 'dynnet') and hasattr(forec_model.torchdynnets[0].vf.vf, 'k'): writer.add_text('model parameters:', f'{forec_model.torchdynnets[0].vf.vf.k.item()}', epoch) vmin = 0 vmax = imheatmaps.max().item() fig = plt.figure() img = eo.rearrange(images_0, '(b t) c h w -> b t c h w', t=3) img = denorm({'image': img[0, 1]})['image'].cpu().numpy() img = eo.rearrange(img, 'c h w -> h w c') heatmap = eo.rearrange(heatmap, '(b t) c h w -> b t c h w', t=3)[0, 1].squeeze(0) heatmap = heatmap.cpu().numpy() plt.title(''.join((str(coords_0[0, 0].cpu().numpy().item()), ', ', str(coords_0[0, 1].cpu().numpy().item())))) plt.imshow(img.astype(np.uint8)) plt.imshow(heatmap, cmap=plt.cm.viridis, alpha=0.65, vmin=heatmap.min(), vmax=heatmap.max()) writer.add_figure('validation heatmap coord_model t=0', fig, epoch) plt.close() fig = plt.figure() img = eo.rearrange(images_0, '(b t) c h w -> b t c h w', t=3) img = denorm({'image': img[0, 1]})['image'].cpu().numpy() img = eo.rearrange(img, 'c h w -> h w c') gt_coord = imlabels[0, 0] H, W, __ = img.shape joint = (gt_coord[0].cpu().numpy().item(), gt_coord[1].cpu().numpy().item(), 1.0)
if __name__ == '__main__': #os.environ['CUDA_LAUNCH_BLOCKING'] = "1" parser = argparse.ArgumentParser() parser.add_argument('--lr', type=float, default=1e-4) parser.add_argument('--environment_name', type=str, default='parcour') parser.add_argument('--lossmode', type=str, default='2Dpred_nograd') parser.add_argument('--folder', type=str, default='tmp') parser.add_argument('--sin_title', type=str, default='convnext') parser.add_argument('--gpu', type=int, default=0) parser.add_argument('--debug', action='store_true') parser.add_argument('--loss_coord_title', type=str, default='L1') args = parser.parse_args() os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu) # if __name__ == '__main__': # torch.autograd.set_detect_anomaly(True) device = 'cuda:0' if torch.cuda.is_available() else 'cpu' debug = False def train(config): torch.manual_seed(config.seed) random.seed(config.seed) np.random.seed(config.seed) g = torch.Generator() g.manual_seed(config.seed) forecast_length = max(config.timesteps) logs_path = config.get_logs_path(debug) writer = SummaryWriter(logs_path) coord_model = get_PEN(config.sin_title, config.depth_mode, config.environment_name).to(device) coord_model_ema = get_PEN(config.sin_title, config.depth_mode, config.environment_name).to(device).eval() coord_model_ema.load_state_dict(coord_model.state_dict()) coord_model_ema = update_ema(coord_model, coord_model_ema, 0) if hasattr(coord_model, 'temperature'): coord_model.temperature = config.temperature coord_model_ema.temperature = config.temperature forec_model = get_PAF(device, config.forec_title, config.environment_name).to(device) trainset = get_dataset(config.environment_name, mode='train', transforms=train_transform) valset = get_dataset(config.environment_name, mode='val', transforms=val_transform) original_size = trainset.original_size num_workers = 0 if debug else 8 trainloader = torch.utils.data.DataLoader(trainset, batch_size=config.BATCH_SIZE, shuffle=True, num_workers=num_workers, worker_init_fn=seed_worker, generator=g) valloader = torch.utils.data.DataLoader(valset, batch_size=config.BATCH_SIZE//4, shuffle=False, num_workers=num_workers, worker_init_fn=seed_worker, generator=g) loss_fn = torch.nn.MSELoss(reduction='none') loss_fn_coord = get_reprojectionloss(config.loss_coord_title) optim1 = torch.optim.Adam(coord_model.parameters(), lr=config.lr_coord) optim2 = torch.optim.Adam(forec_model.parameters(), lr=config.lr_forec) loss_weight = lambda i: config.reprojection_weight * \ max(0, min(i - config.warmup_iterations, 400 + config.warmup_iterations)) \ / (400 + config.warmup_iterations) min_losses = [(1e7, -1), (1e7, -1), (1e7, -1), (1e7, -1), (1e7, -1)] iteration = 0 for epoch in range(config.NUM_EPOCHS): print('Epoch', epoch) for i, data_dict in enumerate(tqdm(trainloader)): for xml_num, stuff in data_dict.items(): optim1.zero_grad() optim2.zero_grad() video, vidlabel, vidheatmap, eM, iM, d3label, cam_num, timestamps = stuff t = random.randint(1, video.shape[1] - 2 - forecast_length) timestamps_T = timestamps[:, t-1:t+forecast_length+1] images_0 = video[:, t - 1:t + 2] t_steps = [t + ts for ts in config.timesteps] images_t = video[:, t_steps] imlabels = vidlabel[:, [t] + t_steps] imheatmaps = vidheatmap[:, t_steps] images_0, images_t, imlabels, imheatmaps = images_0.to(device), images_t.to(device), imlabels.to(device), imheatmaps.to(device) eM, iM = eM.to(device), iM.to(device) timestamps_T = timestamps_T.to(device) images_0 = eo.rearrange(images_0, 'b t c h w -> (b t) c h w') heatmap, depthmap = coord_model(images_0) coords = coord_model.get_coords3D(heatmap, depthmap) coords = eo.rearrange(coords, '(b t) d -> b t d', t=3) #heatmap_0 = eo.rearrange(heatmap, '(b t) c h w -> b t c h w', t=3)[:, 1:2] #f = iM[:, 1, 1] __, __, H, W = images_0.shape coords = img_to_cam(coords, iM, original_size, (H, W)) pred_coords = forec_model(coords, timestamps=timestamps_T, forecast_length=forecast_length, extrinsic_matrix = eM.to(device), xml_num=xml_num) pred_coords_t = pred_coords[:, config.timesteps] if config.lossmode in ['2Dgt', '2Dpred', '2Dpred_nograd']: pred_coords_t = cam_to_img(pred_coords_t, iM, original_size, (H, W))[..., :2] images_t = eo.rearrange(images_t, 'b t c h w -> (b t) c h w') heatmap_t, depthmap_t = coord_model(images_t) coords_t = coord_model.get_coords3D(heatmap_t, depthmap_t) coords_t = eo.rearrange(coords_t, '(b t) d -> b t d', t=len(config.timesteps)) coords_c_t = img_to_cam(coords_t, iM, original_size, (H, W)) heatmap_t = eo.rearrange(heatmap_t, '(b t) c h w -> b t c h w', t=len(config.timesteps)) if config.lossmode == '2Dgt': loss_reproject = loss_fn_coord(pred_coords_t, imlabels[:, 1:]).mean() elif config.lossmode == '2Dpred': loss_reproject = loss_fn_coord(pred_coords_t, coords_t[..., :2]).mean() elif config.lossmode == '2Dpred_nograd': loss_reproject = loss_fn_coord(pred_coords_t, coords_t[..., :2].detach()).mean() elif config.lossmode == '3Dgt': d3gt = d3label[:, t_steps].to(device) loss_reproject = loss_fn_coord(pred_coords_t, d3gt).mean() elif config.lossmode == '3Dpred': loss_reproject = loss_fn_coord(pred_coords_t, coords_c_t).mean() elif config.lossmode == '3Dpred_nograd': loss_reproject = loss_fn_coord(pred_coords_t, coords_c_t.detach()).mean() else: raise ValueError('Unknown lossmode') # heatmap_t = eo.rearrange(heatmap_t, 'b t c h w -> b t c (h w)').softmax(dim=-1) * imheatmaps.sum(dim=[-1, -2]).unsqueeze(-1) # heatmap_t = eo.rearrange(heatmap_t, 'b t c (h w) -> b t c h w', h=H, w=W) loss_2Dheatmap = loss_fn(heatmap_t, imheatmaps).mean() loss = (loss_weight(iteration) * loss_reproject + loss_2Dheatmap) / len(data_dict.keys()) loss.backward(retain_graph=False) torch.nn.utils.clip_grad_norm_(coord_model.parameters(), 5) torch.nn.utils.clip_grad_norm_(forec_model.parameters(), 5) if iteration % 2 == 0 or iteration < config.warmup_iterations: optim1.step() if iteration % 2 == 1:# and iteration > config.warmup_iterations: #TODO: remove comment, if forec_model should be trained, too #optim2.step() optim1.step() coord_model_ema = update_ema(coord_model, coord_model_ema, config.ema_decay) writer.add_scalar('Training/reprojection loss', loss_reproject, epoch*len(trainloader)+i) writer.add_scalar('Training/2D heatmap loss', loss_2Dheatmap, epoch * len(trainloader) + i) #__, loss_2Dcoord, loss_reproject, distance_to_gt, rel_distance_to_gt = validation((coord_model, forec_model), valloader, writer, epoch, device, config) __, loss_2Dcoord, loss_reproject, distance_to_gt, rel_distance_to_gt = validation((coord_model_ema, forec_model), valloader, writer, epoch, device, config) coord_model_ema.eval() # save model, if it is one of the three best ones min_loss5, epoch5 = min_losses[0] if rel_distance_to_gt < min_loss5 and debug == False: min_losses[0] = (rel_distance_to_gt, epoch) min_losses = sorted(min_losses, reverse=True) lossesandmetrics = { 'loss_2Dcoord': loss_2Dcoord, 'loss_reproject': loss_reproject, 'distance_to_gt': distance_to_gt, 'rel_distance_to_gt': rel_distance_to_gt } save_path = save_models(coord_model, forec_model, optim1, optim2, lossesandmetrics, epoch, config=config) save_path = os.path.dirname(save_path) if epoch > 4: os.remove(os.path.join(save_path, f'{epoch5}.pth')) iteration += 1 def validation(models, valloader, writer, epoch, device, config): coord_model, forec_model = models coord_model.eval() forec_model.eval() original_size = valloader.dataset.original_size forecast_length = 15 timesteps = [i for i in range(1, forecast_length)] num_cameras = valloader.sampler.data_source.num_cameras num_environments = valloader.sampler.data_source.num_environments loss_fn = torch.nn.MSELoss(reduction='none') loss_fn_coord = get_reprojectionloss(config.loss_coord_title) with torch.no_grad(): losses_metrics = {} number_metrics = {} for i in range(num_environments): losses_metrics[i] = { 'loss_reproject': {}, 'loss_2Dheatmap': {}, 'loss_2Dcoord': {}, 'loss_z_c': {}, 'distance_to_gt': {}, 'rel_distance_to_gt': {}, } number_metrics[i] = {} for j in range(num_cameras): for v in losses_metrics[i].values(): v[j] = 0 number_metrics[i][j] = 0 for i, data_dict in enumerate(tqdm(valloader)): for xml_num, stuff in data_dict.items(): video, vidlabel, vidheatmap, eM, iM, d3label, cam_num, timestamps = stuff t = 1 t_steps = [t + ts for ts in timesteps] images_0 = video[:, t - 1:t + 2] images_T = video[:, t_steps] timestamps_T = timestamps[:, t-1:t+forecast_length+1] images_all = video[:, t:t+forecast_length] d3labels_all = d3label[:, t:t+forecast_length] imlabels = vidlabel[:, [t] + t_steps] imheatmaps = vidheatmap[:, t_steps] images_0, images_T, imlabels, imheatmaps = images_0.to(device), images_T.to(device), imlabels.to(device), imheatmaps.to(device) images_all, d3labels_all = images_all.to(device), d3labels_all.to(device) eM, iM = eM.to(device), iM.to(device) timestamps_T = timestamps_T.to(device) images_0 = eo.rearrange(images_0, 'b t c h w -> (b t) c h w') heatmap, depthmap = coord_model(images_0) coords = coord_model.get_coords3D(heatmap, depthmap) coords = eo.rearrange(coords, '(b t) d -> b t d', t=3) #heatmap_0 = eo.rearrange(heatmap, '(b t) c h w -> b t c h w', t=3)[:, 1] coords_0 = coords[:, 1] images_T = eo.rearrange(images_T, 'b t c h w -> (b t) c h w') heatmap_T, depthmap_T = coord_model(images_T) coords_T = coord_model.get_coords3D(heatmap_T, depthmap_T) coords_T = eo.rearrange(coords_T, '(b t) d -> b t d', t=len(t_steps)) images_T = eo.rearrange(images_T, '(b t) c h w -> b t c h w', t=len(t_steps)) heatmap_T = eo.rearrange(heatmap_T, '(b t) c h w -> b t c h w', t=len(t_steps)) #f = iM[:, 1, 1] __, __, H, W = images_0.shape coords_c = img_to_cam(coords, iM, original_size, (H, W)) #pred_coords = forec_model(coords_c, forecast_length=forecast_length) pred_coords = forec_model(coords_c, timestamps=timestamps_T, forecast_length=forecast_length, extrinsic_matrix = eM.to(device), xml_num=xml_num) pred_coords_T = pred_coords[:, timesteps] images_all = eo.rearrange(images_all, 'b t c h w -> (b t) c h w') heatmap_all, depthmap_all = coord_model(images_all) coords_all = coord_model.get_coords3D(heatmap_all, depthmap_all) coords_all = eo.rearrange(coords_all, '(b t) d -> b t d', t=forecast_length) f = iM[:, 1, 1] __, __, H, W = images_all.shape coords_all = img_to_cam(coords_all, iM, original_size, (H, W)) distance = (coords_all - d3labels_all).double().pow(2).sum(2).sqrt() rel_distance = distance / d3labels_all.double().pow(2).sum(2).sqrt() pred_coords_T_B = cam_to_img(pred_coords_T, iM, original_size, (H, W))[..., :2] loss_reproject_tmp = loss_fn_coord(pred_coords_T_B, coords_T[..., :2]) loss_2Dcoord_tmp = loss_fn_coord(coords_0[:, :2], imlabels[:, 0]) * 1e-3 # heatmap_T = eo.rearrange(heatmap_T, 'b t c h w -> b t c (h w)').softmax(dim=-1) * imheatmaps.sum(dim=[-1, -2]).unsqueeze(-1) # heatmap_T = eo.rearrange(heatmap_T, 'b t c (h w) -> b t c h w', h=H, w=W) loss_2Dheatmap_tmp = loss_fn(heatmap_T, imheatmaps) for cn_ind in range(cam_num.shape[0]): cn = cam_num[cn_ind].item() number_metrics[xml_num][cn] += 1 losses_metrics[xml_num]['distance_to_gt'][cn] += distance[cn_ind].mean().item() losses_metrics[xml_num]['rel_distance_to_gt'][cn] += rel_distance[cn_ind].mean().item() losses_metrics[xml_num]['loss_reproject'][cn] += loss_reproject_tmp[cn_ind].mean().cpu().item() # maybe also add at time t losses_metrics[xml_num]['loss_2Dcoord'][cn] += loss_2Dcoord_tmp[cn_ind].mean().cpu().item() losses_metrics[xml_num]['loss_2Dheatmap'][cn] += loss_2Dheatmap_tmp[cn_ind].mean().cpu().item() distance_to_gt = np.mean([losses_metrics[xml_num]['distance_to_gt'][cn] / number_metrics[xml_num][cn] for cn in range(num_cameras) for xml_num in range(num_environments)]) loss_2Dheatmap = np.mean([losses_metrics[xml_num]['loss_2Dheatmap'][cn] / number_metrics[xml_num][cn] for cn in range(num_cameras) for xml_num in range(num_environments)]) loss_2Dcoord = np.mean([losses_metrics[xml_num]['loss_2Dcoord'][cn] / number_metrics[xml_num][cn] for cn in range(num_cameras) for xml_num in range(num_environments)]) loss_reproject = np.mean([losses_metrics[xml_num]['loss_reproject'][cn] / number_metrics[xml_num][cn] for cn in range(num_cameras) for xml_num in range(num_environments)]) rel_distance_to_gt = np.mean([losses_metrics[xml_num]['rel_distance_to_gt'][cn] / number_metrics[xml_num][cn] for cn in range(num_cameras) for xml_num in range(num_environments)]) for xml_num in range(num_environments): for metric in losses_metrics[xml_num].keys(): for cn in range(num_cameras): losses_metrics[xml_num][metric][cn] /= number_metrics[xml_num][cn] for xmlnum in range(num_environments): for camnum in range(num_cameras): writer.add_scalar(f'Validation Loss/env{xmlnum}/camera{camnum}/reprojection loss', losses_metrics[xml_num]['loss_reproject'][camnum], epoch) writer.add_scalar(f'Validation Loss/env{xmlnum}/camera{camnum}/2D coordinate loss', losses_metrics[xml_num]['loss_2Dcoord'][camnum], epoch) writer.add_scalar(f'Validation Loss/env{xmlnum}/camera{camnum}/2D heatmap loss', losses_metrics[xml_num]['loss_2Dheatmap'][camnum], epoch) writer.add_scalar(f'Validation Metric/env{xmlnum}/camera{camnum}/Distance to groundtruth', losses_metrics[xml_num]['distance_to_gt'][camnum], epoch) writer.add_scalar(f'Validation relative Metric/env{xmlnum}/camera{camnum}/Relative distance to groundtruth', losses_metrics[xml_num]['rel_distance_to_gt'][camnum], epoch) writer.add_text(f'Validation/env{0}/camera{camnum}/coord_model t=0:', ''.join((str(coords_c[0, 1, 0].item()), ', ', str(coords_c[0, 1, 1].item()), ', ', str(coords_c[0, 1, 2].item()))), epoch) coords_T_c = img_to_cam(coords_T, iM, original_size, (H, W))[:, -1] writer.add_text(f'Validation/env{0}/camera{camnum}/coord_model t=T:', ''.join((str(coords_T_c[0, 1].item()), ', ', str(coords_T_c[0, 0].item()), ', ', str(coords_T_c[0, 2].item()))), epoch) writer.add_text(f'Validation/env{0}/camera{camnum}/forec_model t=T:', ''.join((str(pred_coords_T[0, -1, 0].item()), ', ', str(pred_coords_T[0, -1, 1].item()), ', ', str(pred_coords_T[0, -1, 2].item()))), epoch) writer.add_text(f'Validation/env{0}/camera{camnum}/ground truth t=0:', ''.join((str(d3label[0, t, 1].item()), ', ', str(d3label[0, t, 0].item()), ', ', str(d3label[0, t, 2].item()))), epoch) writer.add_text(f'Validation/env{0}/camera{camnum}/ground truth t=T:', ''.join((str(d3label[0, t + forecast_length - 1, 1].item()), ', ', str(d3label[0, t + forecast_length - 1, 0].item()), ', ', str(d3label[0, t + forecast_length - 1, 2].item()))), epoch) if hasattr(forec_model, 'analyticPhysics') and hasattr(forec_model.analyticPhysics, 'g'): writer.add_text('model parameters:', f'{forec_model.analyticPhysics.g.item()}', epoch) elif hasattr(forec_model, 'torchdynnets') and hasattr(forec_model.torchdynnets[0].vf.vf, 'g'): writer.add_text('model parameters:', f'{forec_model.torchdynnets[0].vf.vf.g.item()}', epoch) if hasattr(forec_model, 'analyticPhysics') and hasattr(forec_model.analyticPhysics, 'k'): writer.add_text('model parameters:', f'{forec_model.analyticPhysics.k.item()}', epoch) elif hasattr(forec_model, 'dynnet') and hasattr(forec_model.torchdynnets[0].vf.vf, 'k'): writer.add_text('model parameters:', f'{forec_model.torchdynnets[0].vf.vf.k.item()}', epoch) vmin = 0 vmax = imheatmaps.max().item() fig = plt.figure() img = eo.rearrange(images_0, '(b t) c h w -> b t c h w', t=3) img = denorm({'image': img[0, 1]})['image'].cpu().numpy() img = eo.rearrange(img, 'c h w -> h w c') heatmap = eo.rearrange(heatmap, '(b t) c h w -> b t c h w', t=3)[0, 1].squeeze(0) heatmap = heatmap.cpu().numpy() plt.title(''.join((str(coords_0[0, 0].cpu().numpy().item()), ', ', str(coords_0[0, 1].cpu().numpy().item())))) plt.imshow(img.astype(np.uint8)) plt.imshow(heatmap, cmap=plt.cm.viridis, alpha=0.65, vmin=heatmap.min(), vmax=heatmap.max()) writer.add_figure('validation heatmap coord_model t=0', fig, epoch) plt.close() fig = plt.figure() img = eo.rearrange(images_0, '(b t) c h w -> b t c h w', t=3) img = denorm({'image': img[0, 1]})['image'].cpu().numpy() img = eo.rearrange(img, 'c h w -> h w c') gt_coord = imlabels[0, 0] H, W, __ = img.shape joint = (gt_coord[0].cpu().numpy().item(), gt_coord[1].cpu().numpy().item(), 1.0)
heatmap = create_heatmaps(joint, (H, W)).squeeze(0)
0
2023-11-30 12:08:47+00:00
12k
aliyun/pai-python-sdk
pai/predictor.py
[ { "identifier": "FrameworkTypes", "path": "pai/common/consts.py", "snippet": "class FrameworkTypes(object):\n PyTorch = \"PyTorch\"\n TFLite = \"TFLite\"\n Keras = \"Keras\"\n Caffe = \"Caffe\"\n Blade = \"Blade\"\n Alink = \"Alink\"\n TensorFlow = \"TensorFlow\"" }, { "iden...
import asyncio import base64 import functools import json import logging import posixpath import time import aiohttp import requests import docker from abc import ABC, abstractmethod from concurrent.futures import Future, ThreadPoolExecutor from io import IOBase from typing import Any, Callable, Dict, List, Optional, Tuple, Union from urllib.parse import urlencode from .common.consts import FrameworkTypes from .common.docker_utils import ContainerRun from .common.utils import http_user_agent from .exception import PredictionException from .serializers import ( JsonSerializer, PyTorchSerializer, SerializerBase, TensorFlowSerializer, ) from .session import Session, get_default_session from pai.model import _BuiltinProcessor
10,011
**kwargs, ) -> AsyncTask: """Make a prediction with the online prediction service. Args: data (Any): Input data to be sent to the prediction service. If it is a file-like object, bytes, or string, it will be sent as the request body. Otherwise, it will be treated as a JSON serializable object and sent as JSON. callback (Union[Callable, List[Callable]], optional): A Callback function, or a list of callback functions used to process the prediction result. path (str, optional): Path for the request to be sent to. If it is provided, it will be appended to the endpoint URL (Default None). headers (dict, optional): Request headers. method (str, optional): Request method, default to 'POST'. **kwargs: Additional keyword arguments for the request. Returns: AsyncTask: The task object that can be used to retrieve the prediction result. Examples: from pai.predictor import AsyncPredictor, AsyncTask predictor = AsyncPredictor() task: AsyncTask = predictor.raw_predict(data="YourPredictionData") print(task.result()) """ future = self.executor.submit( self._raw_predict_fn, data, method, path, headers, **kwargs ) cbs = [callback] if isinstance(callback, Callable) else callback if cbs: for cb in cbs: future.add_done_callback(self._wrap_callback_fn(cb)) return AsyncTask(future=future) async def raw_predict_async( self, data, wait_config: WaitConfig = WaitConfig(), method: str = "POST", headers: Optional[Dict[str, str]] = None, path: Optional[str] = None, **kwargs, ) -> RawResponse: """Make a prediction with the online prediction service. Args: data (Any): Input data to be sent to the prediction service. If it is a file-like object, bytes, or string, it will be sent as the request body. Otherwise, it will be treated as a JSON serializable object and sent as JSON. wait_config (WaitConfig): A config object that controls the behavior of polling the prediction result. path (str, optional): Path for the request to be sent to. If it is provided, it will be appended to the endpoint URL (Default None). headers (dict, optional): Request headers. method (str, optional): Request method, default to 'POST'. **kwargs: Additional keyword arguments for the request. Returns: RawResponse: Prediction result. """ if self.service_status not in ServiceStatus.completed_status(): self.wait_for_ready() json_data, data = self._handle_raw_input(data) resp = await self._send_request_async( data=data, method=method, json=json_data, path=path, headers=headers, **kwargs, ) request_id = await self._get_request_id_async(resp) # Polling the prediction result. status_code, headers, content = await self._poll_result_async( request_id=request_id, wait_config=wait_config ) return self._handle_raw_output(status_code, headers, content) class LocalPredictor(PredictorBase): """Perform prediction to a local service running with docker.""" def __init__( self, port: int, container_id: Optional[str] = None, serializer: Optional[SerializerBase] = None, ): """LocalPredictor initializer. Args: port (int): The port of the local service. container_id (str, optional): The container id of the local service. serializer (SerializerBase, optional): A serializer object that transforms. """ self.container_id = container_id self.port = port self.serializer = serializer or JsonSerializer() self._container_run = ( self._build_container_run(container_id, port=port) if self.container_id else None ) @classmethod def _build_container_run(cls, container_id, port): try: except ImportError: raise ImportError("Please install docker first: pip install docker") client = docker.from_env() container = client.containers.get(container_id)
# Copyright 2023 Alibaba, Inc. or its affiliates. # # 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 # # https://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.getLogger(__name__) _PAI_SERVICE_CONSOLE_URI_PATTERN = ( "https://pai.console.aliyun.com/?regionId={region_id}#" "/eas/serviceDetail/{service_name}/detail" ) _QUEUE_SERVICE_REQUEST_ID_HEADER = "X-Eas-Queueservice-Request-Id" _QUEUE_SERVICE_SINK_PATH = "sink" _DEFAULT_ASYNC_WORKER_COUNT = 30 class ServiceStatus(object): """All EAS inference service status.""" Running = "Running" Waiting = "Waiting" Scaling = "Scaling" Stopped = "Stopped" Failed = "Failed" DeleteFailed = "DeleteFailed" @classmethod def completed_status(cls): return [ cls.Running, cls.Stopped, cls.Failed, cls.DeleteFailed, ] class EndpointType(object): # Public Internet Endpoint INTERNET = "INTERNET" # VPC Endpoint INTRANET = "INTRANET" class ServiceType(object): Standard = "Standard" Async = "Async" class PredictorBase(ABC): @abstractmethod def predict(self, *args, **kwargs) -> Any: """Perform inference on the provided data and return prediction result.""" @abstractmethod def raw_predict( self, data: Any = None, path: Optional[str] = None, headers: Optional[Dict[str, str]] = None, method: str = "POST", timeout: Optional[Union[float, Tuple[float, float]]] = None, **kwargs, ): pass class RawResponse(object): """Response object returned by the predictor.raw_predict.""" def __init__(self, status_code: int, headers: Dict[str, str], content: bytes): """Initialize a RawResponse object. Args: status_code (int): headers (dict): content (bytes): """ self.status_code = status_code self.headers = headers self.content = content def json(self): """Returns the json-encoded content of a response Returns: Dict[str, Any]: The json-encoded content of a response. """ return json.loads(self.content) class _ServicePredictorMixin(object): def __init__( self, service_name: str, session: Optional[Session] = None, endpoint_type: str = EndpointType.INTERNET, serializer: Optional[SerializerBase] = None, ): self.service_name = service_name self.session = session or get_default_session() self._service_api_object = self.describe_service() self.endpoint_type = endpoint_type self.serializer = serializer or self._get_default_serializer() self._request_session = requests.Session() def __repr__(self): return "{}(service_name={}, endpoint_type={})".format( type(self).__name__, self.service_name, self.endpoint_type, ) def __del__(self): self._request_session.close() def refresh(self): self._service_api_object = self.describe_service() @property def endpoint(self): if self.endpoint_type == EndpointType.INTRANET: return self._service_api_object["IntranetEndpoint"] else: return self._service_api_object["InternetEndpoint"] @property def intranet_endpoint(self): return self._service_api_object["IntranetEndpoint"] @property def internet_endpoint(self): return self._service_api_object["InternetEndpoint"] @property def service_status(self): """Returns the status of the service.""" return self._service_api_object["Status"] @property def access_token(self): """Access token of the service.""" return self._service_api_object["AccessToken"] @property def console_uri(self): """Returns the console URI of the service.""" return _PAI_SERVICE_CONSOLE_URI_PATTERN.format( region_id=self.session.region_id, service_name=self.service_name, ) def _get_default_serializer(self): """Get default serializer for the predictor by inspecting the service config.""" service_config = json.loads(self._service_api_object["ServiceConfig"]) processor_code = service_config.get("processor") # If the prediction service is serving with custom processor or custom # container, use JsonSerializer as default serializer. if not processor_code: return JsonSerializer() if processor_code in ( _BuiltinProcessor.PMML, _BuiltinProcessor.XGBoost, ): return JsonSerializer() elif processor_code.startswith(FrameworkTypes.TensorFlow.lower()): serializer = TensorFlowSerializer() return serializer elif processor_code.startswith(FrameworkTypes.PyTorch.lower()): return PyTorchSerializer() else: return JsonSerializer() def _post_init_serializer(self): """Post-initialize the serializer by invoking serializer.inspect_from_service""" if not hasattr(self.serializer, "__post_init_serializer_flag") and hasattr( self.serializer, "inspect_from_service" ): self.serializer.inspect_from_service( self.service_name, session=self.session ) setattr(self.serializer, "__post_init_serializer_flag", 1) def inspect_model_signature_def(self): """Get SignatureDef of the serving model. .. note:: Only the service using the TensorFlow processor supports getting the model signature_definition. Returns: Dict[str, Any]: A dictionary representing the signature definition of the serving model. """ service_config = json.loads(self._service_api_object["ServiceConfig"]) processor_code = service_config.get("processor") if processor_code and processor_code.startswith("tensorflow"): return TensorFlowSerializer.inspect_model_signature_def( self.service_name, session=self.session ) raise RuntimeError( "Only the online prediction service using the TensorFlow processor supports" " getting the signature_definition" ) def describe_service(self) -> Dict[str, Any]: """Describe the service that referred by the predictor. Returns: Dict[str, Any]: Response from PAI API service. """ return self.session.service_api.get(self.service_name) def start_service(self, wait=True): """Start the stopped service.""" self.session.service_api.start(name=self.service_name) if wait: status = ServiceStatus.Running unexpected_status = ServiceStatus.completed_status() unexpected_status.remove(status) type(self)._wait_for_status( service_name=self.service_name, status=status, unexpected_status=unexpected_status, session=self.session, ) self.refresh() def stop_service(self, wait=True): """Stop the running service.""" self.session.service_api.stop(name=self.service_name) if wait: status = ServiceStatus.Stopped unexpected_status = ServiceStatus.completed_status() unexpected_status.remove(status) unexpected_status.remove(ServiceStatus.Running) type(self)._wait_for_status( service_name=self.service_name, status=status, unexpected_status=unexpected_status, session=self.session, ) self.refresh() def delete_service(self): """Delete the service.""" self.session.service_api.delete(name=self.service_name) def wait_for_ready(self, force: bool = False): """Wait until the service enter running status. Args: force (bool): Whether to force wait for ready. Raises: RuntimeError: Raise if the service terminated unexpectedly. """ if self.service_status == ServiceStatus.Running and not force: return logger.info( "Service waiting for ready: service_name={}".format(self.service_name) ) unexpected_status = ServiceStatus.completed_status() unexpected_status.remove(ServiceStatus.Running) type(self)._wait_for_status( service_name=self.service_name, status=ServiceStatus.Running, unexpected_status=unexpected_status, session=self.session, ) # hack: PAI-EAS gateway may not be ready when the service is ready. self._wait_for_gateway_ready() self.refresh() def _wait_for_gateway_ready(self, attempts: int = 30, interval: int = 2): """Hacky way to wait for the service gateway to be ready. Args: attempts (int): Number of attempts to wait for the service gateway to be ready. interval (int): Interval between each attempt. """ def _is_gateway_not_ready(resp: requests.Response): return resp.status_code == 503 and resp.content == b"no healthy upstream" err_count_threshold = 3 err_count = 0 while attempts > 0: attempts -= 1 try: # Send a probe request to the service. resp = self._send_request(method="GET") if not _is_gateway_not_ready(resp): logger.info("Gateway for the service is ready.") break except requests.exceptions.RequestException as e: err_count += 1 if err_count >= err_count_threshold: logger.warning("Failed to check gateway status: %s", e) break time.sleep(interval) else: logger.warning("Timeout waiting for gateway to be ready.") @classmethod def _wait_for_status( cls, service_name: str, status: str, unexpected_status: List[str], interval: int = 3, session: Optional[Session] = None, ): session = session or get_default_session() service_api_object = session.service_api.get(service_name) last_status = service_api_object["Status"] last_msg = service_api_object["Message"] time.sleep(interval) while True: service_api_object = session.service_api.get(service_name) # Check the service status cur_status = service_api_object["Status"] if cur_status == status: return status elif unexpected_status and cur_status in unexpected_status: # Unexpected terminated status raise RuntimeError( f"The Service terminated unexpectedly: " f"name={service_api_object['ServiceName']} " f"status={service_api_object['Status']} " f"reason={service_api_object['Reason']} " f"message={service_api_object['Message']}." ) elif ( last_status == cur_status and service_api_object["Message"] == last_msg ) and cur_status != ServiceStatus.Waiting: # If service.status and service.message have not changed and # service.status is not 'Waiting', do not print the service # status/message. pass else: logger.info( f"Refresh Service status: " f"name={service_api_object['ServiceName']} " f"id={service_api_object['ServiceId']} " f"status={service_api_object['Status']} " f"reason={service_api_object['Reason']} " f"message={service_api_object['Message']}." ) last_status = service_api_object["Status"] last_msg = service_api_object["Message"] time.sleep(interval) def switch_version(self, version: int): """Switch service to target version. Args: version (int): Target version """ service_api_object = self.describe_service() current_version = service_api_object["CurrentVersion"] latest_version = service_api_object["LatestVersion"] if current_version == version: raise ValueError("Target version equals to current version.") if version > latest_version: raise ValueError("Target version greater than latest version.") self.session.service_api.update_version(self.service_name, version=version) @classmethod def deploy( cls, config: Dict[str, Any], session: Optional[Session] = None, endpoint_type: str = EndpointType.INTERNET, serializer: Optional[SerializerBase] = None, wait: bool = True, ) -> PredictorBase: """Deploy an online prediction service using given configuration. Args: config (Dict[str, Any]): A dictionary of service configuration. session (:class:`pai.session.Session`, optional): An optional session object. If not provided, a default session will be used. serializer: An optional serializer object. If not provided, a default serializer will be used. endpoint_type: The type of endpoint to use. wait: Whether to wait for the service to be ready before returning. Returns: :class:`pai.predictor.PredictorBase`: A Predictor object for the deployed online prediction service. """ session = session or get_default_session() name = session.service_api.create(config=config) if wait: # Wait until the service is ready unexpected_status = ServiceStatus.completed_status() unexpected_status.remove(ServiceStatus.Running) Predictor._wait_for_status( service_name=name, status=ServiceStatus.Running, unexpected_status=unexpected_status, session=session, ) service_api_obj = session.service_api.get(name) if service_api_obj["ServiceType"] == ServiceType.Async: p = AsyncPredictor( service_name=name, endpoint_type=endpoint_type, serializer=serializer, ) else: p = Predictor( service_name=name, endpoint_type=endpoint_type, serializer=serializer, ) return p def _build_url( self, path: Optional[str] = None, params: Dict[str, str] = None ) -> str: url = self.endpoint if path: if path.startswith("/"): path = path[1:] url = posixpath.join(url, path) # Add params to URL url = url + "?" + urlencode(params) if params else url return url def _build_headers(self, headers: Dict[str, str] = None) -> Dict[str, str]: headers = headers or dict() headers["Authorization"] = self.access_token headers["User-Agent"] = http_user_agent(headers.get("User-Agent")) return headers def _handle_input(self, data): return self.serializer.serialize(data) if self.serializer else data def _handle_output(self, content: bytes): return self.serializer.deserialize(content) if self.serializer else content def _handle_raw_input(self, data): if isinstance(data, (IOBase, bytes, str)): # if data is a file-like object, bytes, or string, it will be sent as # request body json_data, data = None, data else: # otherwise, it will be treated as a JSON serializable object and sent as # JSON. json_data, data = data, None return json_data, data def _handle_raw_output(self, status_code: int, headers: dict, content: bytes): return RawResponse(status_code, headers, content) def _send_request( self, data=None, path=None, method="POST", json=None, headers=None, params=None, **kwargs, ): url = self._build_url(path) resp = self._request_session.request( url=url, json=json, data=data, headers=self._build_headers(headers), method=method, params=params, **kwargs, ) return resp async def _send_request_async( self, data=None, path=None, method="POST", json=None, headers=None, params=None, **kwargs, ): url = self._build_url(path=path, params=params) headers = self._build_headers(headers) async with aiohttp.ClientSession() as session: return await session.request( method=method, url=url, headers=headers, data=data, json=json, **kwargs, ) class Predictor(PredictorBase, _ServicePredictorMixin): """Predictor is responsible for making prediction to an online service. The `predictor.predict` method sends the input data to the online prediction service and returns the prediction result. The serializer object of the predictor is responsible for data transformation when the `predict` method is invoked. The input data is serialized using the `serializer.serialize` method before it is sent, and the response is deserialized using the `serializer.deserialize` method before the prediction result returns. Examples:: # Initialize a predictor object from an existing service using PyTorch # processor. torch_predictor = Predictor(service_name="example_torch_service") result = torch_predictor.predict(numpy.asarray([[22,33,44], [19,22,33]])) assert isinstance(result, numpy.ndarray) """ def __init__( self, service_name: str, endpoint_type: str = EndpointType.INTERNET, serializer: Optional[SerializerBase] = None, session: Optional[Session] = None, ): """Construct a `Predictor` object using an existing prediction service. Args: service_name (str): Name of the existing prediction service. endpoint_type (str): Selects the endpoint used by the predictor, which should be one of `INTERNET` or `INTRANET`. The `INTERNET` endpoint type means that the predictor calls the service over a public endpoint, while the `INTRANET` endpoint type is over a VPC endpoint. serializer (SerializerBase, optional): A serializer object that transforms the input Python object for data transmission and deserialize the response data to Python object. session (Session, optional): A PAI session object used for communicating with PAI service. """ super(Predictor, self).__init__( service_name=service_name, session=session or get_default_session(), endpoint_type=endpoint_type, serializer=serializer, ) self._check() def _check(self): config = json.loads(self._service_api_object["ServiceConfig"]) if config.get("metadata", {}).get("type") == ServiceType.Async: logger.warning( "Predictor is not recommended to make prediction to a async" " prediction service." ) def predict(self, data): """Make a prediction with the online prediction service. The serializer object for the predictor is responsible for data transformation when the 'predict' method is invoked. The input data is serialized using the `serializer.serialize` method before it is sent, and the response is deserialized using the `serializer.deserialize` method before the prediction result returns. Args: data: The input data for the prediction. It will be serialized using the serializer of the predictor before transmitted to the prediction service. Returns: object: Prediction result. Raises: PredictionException: Raise if status code of the prediction response does not equal 2xx. """ self._post_init_serializer() data = self._handle_input(data) resp = self._send_request( data, ) if resp.status_code // 100 != 2: raise PredictionException(resp.status_code, resp.content) return self._handle_output( resp.content, ) def raw_predict( self, data: Any = None, path: Optional[str] = None, headers: Optional[Dict[str, str]] = None, method: str = "POST", timeout: Optional[Union[float, Tuple[float, float]]] = None, **kwargs, ) -> RawResponse: """Make a prediction with the online prediction service. Args: data (Any): Input data to be sent to the prediction service. If it is a file-like object, bytes, or string, it will be sent as the request body. Otherwise, it will be treated as a JSON serializable object and sent as JSON. path (str, optional): Path for the request to be sent to. If it is provided, it will be appended to the endpoint URL (Default None). headers (dict, optional): Request headers. method (str, optional): Request method, default to 'POST'. timeout(float, tuple(float, float), optional): Timeout setting for the request (Default 10). **kwargs: Additional keyword arguments for the request. Returns: RawResponse: Prediction response from the service. Raises: PredictionException: Raise if status code of the prediction response does not equal 2xx. """ json_data, data = self._handle_raw_input(data) resp = self._send_request( data=data, json=json_data, method=method, path=path, headers=headers, timeout=timeout, **kwargs, ) if resp.status_code // 100 != 2: raise PredictionException(resp.status_code, resp.content) resp = RawResponse( status_code=resp.status_code, content=resp.content, headers=dict(resp.headers), ) return resp class WaitConfig(object): """WaitConfig is used to set polling configurations for waiting for asynchronous requests to complete.""" def __init__(self, max_attempts: int = 0, interval: int = 5): if interval <= 0: raise ValueError("interval must be positive integer.") self.max_attempts = max_attempts self.interval = interval class AsyncTask(object): """AsyncTask is a wrapper class for `concurrent.futures.Future` object that represents a prediction call submitted to an async prediction service. """ def __init__( self, future: Future, ): self.future = future super(AsyncTask, self).__init__() def result(self, timeout: Optional[float] = None): """ Returns the prediction result of the call. Args: timeout (float, optional): Timeout setting (Default None). Returns: The result of the prediction call. """ return self.future.result(timeout=timeout) def done(self): return self.future.done() def exception(self, timeout: Optional[float] = None) -> Optional[Exception]: return self.future.exception() def running(self): return self.future.running() def cancel(self): return self.future.cancel() def cancelled(self): return self.future.cancelled() class AsyncPredictor(PredictorBase, _ServicePredictorMixin): """A class that facilitates making predictions to asynchronous prediction service. Examples:: # Initialize an AsyncPredictor object using the name of a running service. async_predictor = AsyncPredictor(service_name="example_service") # Make a prediction with the service and get the prediction result. resp = async_predictor.predict(data="YourPredictionData") result = resp.wait() # Make a prediction with async API. import asyncio result = asyncio.run(async_predictor.predict_async(data="YourPredictionData")) """ def __init__( self, service_name: str, max_workers: Optional[int] = None, endpoint_type: str = EndpointType.INTERNET, serializer: Optional[SerializerBase] = None, session: Optional[Session] = None, ): """Construct a `AsyncPredictor` object using an existing async prediction service. Args: service_name (str): Name of the existing prediction service. max_workers (int): The maximum number of threads that can be used to execute the given prediction calls. endpoint_type (str): Selects the endpoint used by the predictor, which should be one of `INTERNET` or `INTRANET`. The `INTERNET` endpoint type means that the predictor calls the service over a public endpoint, while the `INTRANET` endpoint type is over a VPC endpoint. serializer (SerializerBase, optional): A serializer object that transforms the input Python object for data transmission and deserialize the response data to Python object. session (Session, optional): A PAI session object used for communicating with PAI service. """ super(AsyncPredictor, self).__init__( service_name=service_name, session=session or get_default_session(), endpoint_type=endpoint_type, serializer=serializer, ) self._max_workers = max_workers self.executor = ThreadPoolExecutor(max_workers=self._max_workers) self._check() @property def max_workers(self): return self._max_workers @max_workers.setter def max_workers(self, n: int): if hasattr(self, "executor"): logger.info("Waiting for all submitted tasks in the queue to complete...") self.executor.shutdown() self._max_workers = n self.executor = ThreadPoolExecutor(max_workers=self._max_workers) def __del__(self): """wait for all pending tasks to complete before exit.""" if hasattr(self, "executor"): logger.info("Waiting for all pending tasks to complete...") self.executor.shutdown() super(AsyncPredictor, self).__del__() def _check(self): config = json.loads(self._service_api_object["ServiceConfig"]) if config.get("metadata", {}).get("type") != ServiceType.Async: logger.warning( "AsyncPredictor is not recommended to make prediction to a standard " " prediction service." ) def _get_result( self, request_id: str ) -> Optional[Tuple[int, Dict[str, str], bytes]]: resp = self._send_request( method="GET", path=_QUEUE_SERVICE_SINK_PATH, params={ "requestId": request_id, # _raw_ is false because we want to get the encapsulated prediction # result in response body. "_raw_": "false", }, ) logger.debug( "Poll prediction result: request_id=%s status_code=%s, content=%s", request_id, resp.status_code, resp.content, ) if resp.status_code == 204: # Status code 204 means could not find prediction response for the specific # request id. return # Raise exception if status code is not 2xx. if resp.status_code // 100 != 2: raise RuntimeError( "Pulling prediction result failed: status_code={} content={}".format( resp.status_code, resp.content.decode("utf-8") ) ) return self._parse_encapsulated_response(resp.json()[0]) def _parse_encapsulated_response(self, data) -> Tuple[int, Dict[str, str], bytes]: tags = data["tags"] # If the status code from prediction service is not 200, a tag with # key 'lastCode' will be added to the tags in response. status_code = int(tags.get("lastCode", 200)) data = base64.b64decode(data["data"]) # currently, headers are not supported in async prediction service. headers = dict() return status_code, headers, data async def _get_result_async( self, request_id: str ) -> Optional[Tuple[int, Dict[str, str], bytes]]: resp = await self._send_request_async( method="GET", path=_QUEUE_SERVICE_SINK_PATH, params={ "requestId": request_id, # _raw_ is false because we want to get the encapsulated prediction # result in response body. "_raw_": "false", }, ) status_code = resp.status content = await resp.read() logger.debug( "Get prediction result: request_id=%s status_code=%s, content=%s", request_id, status_code, content, ) if status_code == 204: # Status code 204 means could not find prediction response for the specific # request id. return if status_code // 100 != 2: raise RuntimeError( "Pulling prediction result failed: status_code={} content={}".format( status_code, content.decode("utf-8") ) ) data = (await resp.json())[0] return self._parse_encapsulated_response(data) def _poll_result( self, request_id: str, wait_config: WaitConfig ) -> Tuple[int, Dict[str, str], bytes]: # if max_attempts is negative or zero, then wait forever attempts = -1 if wait_config.max_attempts <= 0 else wait_config.max_attempts while attempts != 0: attempts -= 1 result = self._get_result(request_id=request_id) if not result: time.sleep(wait_config.interval) continue status_code, headers, content = result # check real prediction response if status_code // 100 != 2: raise PredictionException( code=status_code, message=f"Prediction failed: status_code={status_code}" f" content={content.decode()}", ) return status_code, headers, content # Polling prediction result timeout. raise RuntimeError( f"Polling prediction result timeout: request_id={request_id}, " f"total_time={wait_config.max_attempts * wait_config.interval}" ) async def _poll_result_async( self, request_id, wait_config: WaitConfig ) -> Tuple[int, Dict[str, str], bytes]: # if max_attempts is negative or zero, then wait forever attempts = -1 if wait_config.max_attempts <= 0 else wait_config.max_attempts while attempts != 0: attempts -= 1 result = await self._get_result_async(request_id) if not result: await asyncio.sleep(wait_config.interval) continue status_code, headers, content = result # check real prediction response if status_code // 100 != 2: raise PredictionException( f"Prediction failed: status_code={status_code} content={content.decode()}" ) return status_code, headers, content # Polling prediction result timeout. raise RuntimeError( f"Polling prediction result timeout: request_id={request_id}, " f"total_time={wait_config.max_attempts * wait_config.interval}" ) def _get_request_id(self, resp: requests.models.Response) -> str: if resp.status_code // 100 != 2: raise RuntimeError( f"Send prediction request failed. status_code={resp.status_code} " f"message={resp.text}" ) if _QUEUE_SERVICE_REQUEST_ID_HEADER not in resp.headers: logger.error( f"Send prediction request failed. Missing request id." f" status_code={resp.status_code} content={resp.text}" ) raise RuntimeError("Missing request id in response header.") request_id = resp.headers[_QUEUE_SERVICE_REQUEST_ID_HEADER] logger.debug( f"Send prediction request successfully. request_id={request_id}" f" status_code={resp.status_code}", ) return request_id async def _get_request_id_async(self, resp: aiohttp.ClientResponse) -> str: content = await resp.read() if resp.status != 200: raise RuntimeError( "Send request to async prediction service failed: status_code={} " "content={}".format(resp.status, content.decode("utf-8")) ) if _QUEUE_SERVICE_REQUEST_ID_HEADER not in resp.headers: logger.error( f"Send prediction request failed. Missing request id." f" status_code={resp.status} content={content.decode()}" ) raise RuntimeError("Missing request id in response header.") request_id = resp.headers[_QUEUE_SERVICE_REQUEST_ID_HEADER] logger.debug( f"Send prediction request successfully. request_id={request_id}" f" status_code={resp.status}", ) return request_id def _predict_fn( self, data, ): """Make a prediction with the async prediction service.""" # serialize input data data = self._handle_input(data) resp = self._send_request(data=data) request_id = self._get_request_id(resp) logger.debug("Async prediction RequestId: ", request_id) # poll prediction result status, headers, content = self._poll_result( request_id=request_id, wait_config=WaitConfig() ) return self._handle_output(content) def _wrap_callback_fn(self, cb: Callable): """Wrap the callback function to handle the prediction result.""" @functools.wraps(cb) def _(future: Future): return cb(future.result()) return _ def predict( self, data, callback: Optional[Union[Callable, List[Callable]]] = None, ): """Make a prediction with the async prediction service. The input data is serialized using the `serializer.serialize` method before it is sent, and the response body is deserialized using the `serializer.deserialize` method the prediction result returns. Args: data: The input data for the prediction. It will be serialized using the serializer of the predictor before transmitted to the prediction service. callback (Union[Callable, List[Callable]], optional): A Callback function, or a list of callback functions used to process the prediction result. Returns: AsyncTask: The task object that can be used to retrieve the prediction result. """ self._post_init_serializer() future = self.executor.submit(self._predict_fn, data) if isinstance(callback, Callable): callback = [callback] if callback: for cb in callback: future.add_done_callback(self._wrap_callback_fn(cb)) return AsyncTask(future=future) async def predict_async(self, data, wait_config: WaitConfig = WaitConfig()): """Make a prediction with the async prediction service. The serializer object for the predictor is responsible for data transformation when the 'predict' method is invoked. The input data is serialized using the `serializer.serialize` method before it is sent, and the response is deserialized using the `serializer.deserialize` method before the prediction result returns. Args: data: The input data for the prediction. It will be serialized using the serializer of the predictor before transmitted to the prediction service. wait_config (WaitConfig): A config object that controls the behavior of polling the prediction result. Returns: Prediction result. """ self._post_init_serializer() data = self._handle_input(data) resp = await self._send_request_async(data=data) request_id = await self._get_request_id_async(resp) status_code, headers, content = await self._poll_result_async( request_id=request_id, wait_config=wait_config ) return self._handle_output(content) def _raw_predict_fn(self, data, method, path, headers, **kwargs): json_data, data = self._handle_raw_input(data) resp = self._send_request( path=path, json=json_data, data=data, headers=self._build_headers(headers), method=method, **kwargs, ) request_id = self._get_request_id(resp) status, headers, content = self._poll_result( request_id, wait_config=WaitConfig() ) return RawResponse(status, headers, content) def raw_predict( self, data: Any = None, callback: Optional[Union[Callable, List[Callable], None]] = None, method: str = "POST", path: Optional[str] = None, headers: Optional[Dict[str, str]] = None, **kwargs, ) -> AsyncTask: """Make a prediction with the online prediction service. Args: data (Any): Input data to be sent to the prediction service. If it is a file-like object, bytes, or string, it will be sent as the request body. Otherwise, it will be treated as a JSON serializable object and sent as JSON. callback (Union[Callable, List[Callable]], optional): A Callback function, or a list of callback functions used to process the prediction result. path (str, optional): Path for the request to be sent to. If it is provided, it will be appended to the endpoint URL (Default None). headers (dict, optional): Request headers. method (str, optional): Request method, default to 'POST'. **kwargs: Additional keyword arguments for the request. Returns: AsyncTask: The task object that can be used to retrieve the prediction result. Examples: from pai.predictor import AsyncPredictor, AsyncTask predictor = AsyncPredictor() task: AsyncTask = predictor.raw_predict(data="YourPredictionData") print(task.result()) """ future = self.executor.submit( self._raw_predict_fn, data, method, path, headers, **kwargs ) cbs = [callback] if isinstance(callback, Callable) else callback if cbs: for cb in cbs: future.add_done_callback(self._wrap_callback_fn(cb)) return AsyncTask(future=future) async def raw_predict_async( self, data, wait_config: WaitConfig = WaitConfig(), method: str = "POST", headers: Optional[Dict[str, str]] = None, path: Optional[str] = None, **kwargs, ) -> RawResponse: """Make a prediction with the online prediction service. Args: data (Any): Input data to be sent to the prediction service. If it is a file-like object, bytes, or string, it will be sent as the request body. Otherwise, it will be treated as a JSON serializable object and sent as JSON. wait_config (WaitConfig): A config object that controls the behavior of polling the prediction result. path (str, optional): Path for the request to be sent to. If it is provided, it will be appended to the endpoint URL (Default None). headers (dict, optional): Request headers. method (str, optional): Request method, default to 'POST'. **kwargs: Additional keyword arguments for the request. Returns: RawResponse: Prediction result. """ if self.service_status not in ServiceStatus.completed_status(): self.wait_for_ready() json_data, data = self._handle_raw_input(data) resp = await self._send_request_async( data=data, method=method, json=json_data, path=path, headers=headers, **kwargs, ) request_id = await self._get_request_id_async(resp) # Polling the prediction result. status_code, headers, content = await self._poll_result_async( request_id=request_id, wait_config=wait_config ) return self._handle_raw_output(status_code, headers, content) class LocalPredictor(PredictorBase): """Perform prediction to a local service running with docker.""" def __init__( self, port: int, container_id: Optional[str] = None, serializer: Optional[SerializerBase] = None, ): """LocalPredictor initializer. Args: port (int): The port of the local service. container_id (str, optional): The container id of the local service. serializer (SerializerBase, optional): A serializer object that transforms. """ self.container_id = container_id self.port = port self.serializer = serializer or JsonSerializer() self._container_run = ( self._build_container_run(container_id, port=port) if self.container_id else None ) @classmethod def _build_container_run(cls, container_id, port): try: except ImportError: raise ImportError("Please install docker first: pip install docker") client = docker.from_env() container = client.containers.get(container_id)
return ContainerRun(container=container, port=port)
1
2023-12-01 01:40:12+00:00
12k
xraychen/OFA-Wav2Vec2
fairseq/models/fairseq_model.py
[ { "identifier": "utils", "path": "fairseq/utils.py", "snippet": "MANIFOLD_PATH_SEP = \"|\"\n HOTRELOAD_PAUSE = bool(os.environ.get(\"HOTRELOAD_PAUSE\", 0))\nclass FileContentsAction(argparse.Action):\nclass set_torch_seed(object):\nclass CudaEnvironment(object):\n def __init__(self, option_str...
import logging import torch import torch.nn as nn import torch.nn.functional as F from argparse import Namespace from typing import Dict, List, Optional, Tuple from fairseq import utils from fairseq.data import Dictionary from fairseq.dataclass.utils import ( convert_namespace_to_omegaconf, gen_parser_from_dataclass, ) from fairseq.models import FairseqDecoder, FairseqEncoder from omegaconf import DictConfig from torch import Tensor from fairseq.checkpoint_utils import prune_state_dict from fairseq import hub_utils from fairseq.checkpoint_utils import prune_state_dict
9,531
checkpoint_file, data_name_or_path, archive_map=cls.hub_models(), **kwargs, ) logger.info(x["args"]) return hub_utils.GeneratorHubInterface(x["args"], x["task"], x["models"]) @classmethod def hub_models(cls): return {} class FairseqEncoderDecoderModel(BaseFairseqModel): """Base class for encoder-decoder models. Args: encoder (FairseqEncoder): the encoder decoder (FairseqDecoder): the decoder """ def __init__(self, encoder, decoder): super().__init__() self.encoder = encoder self.decoder = decoder check_type(self.encoder, FairseqEncoder) check_type(self.decoder, FairseqDecoder) def forward(self, src_tokens, src_lengths, prev_output_tokens, **kwargs): """ Run the forward pass for an encoder-decoder model. First feed a batch of source tokens through the encoder. Then, feed the encoder output and previous decoder outputs (i.e., teacher forcing) to the decoder to produce the next outputs:: encoder_out = self.encoder(src_tokens, src_lengths) return self.decoder(prev_output_tokens, encoder_out) Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (LongTensor): source sentence lengths of shape `(batch)` prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for teacher forcing Returns: tuple: - the decoder's output of shape `(batch, tgt_len, vocab)` - a dictionary with any model-specific outputs """ encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs) decoder_out = self.decoder( prev_output_tokens, encoder_out=encoder_out, **kwargs ) return decoder_out def forward_decoder(self, prev_output_tokens, **kwargs): return self.decoder(prev_output_tokens, **kwargs) def extract_features(self, src_tokens, src_lengths, prev_output_tokens, **kwargs): """ Similar to *forward* but only return features. Returns: tuple: - the decoder's features of shape `(batch, tgt_len, embed_dim)` - a dictionary with any model-specific outputs """ encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs) features = self.decoder.extract_features( prev_output_tokens, encoder_out=encoder_out, **kwargs ) return features def output_layer(self, features, **kwargs): """Project features to the default output size (typically vocabulary size).""" return self.decoder.output_layer(features, **kwargs) def max_positions(self): """Maximum length supported by the model.""" return (self.encoder.max_positions(), self.decoder.max_positions()) def max_decoder_positions(self): """Maximum length supported by the decoder.""" return self.decoder.max_positions() class FairseqModel(FairseqEncoderDecoderModel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) utils.deprecation_warning( "FairseqModel is deprecated, please use FairseqEncoderDecoderModel " "or BaseFairseqModel instead", stacklevel=4, ) class FairseqMultiModel(BaseFairseqModel): """Base class for combining multiple encoder-decoder models.""" def __init__(self, encoders, decoders): super().__init__() assert encoders.keys() == decoders.keys() self.keys = list(encoders.keys()) for key in self.keys: check_type(encoders[key], FairseqEncoder) check_type(decoders[key], FairseqDecoder) self.models = nn.ModuleDict( { key: FairseqEncoderDecoderModel(encoders[key], decoders[key]) for key in self.keys } ) @staticmethod def build_shared_embeddings(
# 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. """ Base classes for various fairseq models. """ logger = logging.getLogger(__name__) def check_type(module, expected_type): if hasattr(module, "unwrapped_module"): assert isinstance( module.unwrapped_module, expected_type ), f"{type(module.unwrapped_module)} != {expected_type}" else: assert isinstance(module, expected_type), f"{type(module)} != {expected_type}" class BaseFairseqModel(nn.Module): """Base class for fairseq models.""" def __init__(self): super().__init__() self._is_generation_fast = False @classmethod def add_args(cls, parser): """Add model-specific arguments to the parser.""" dc = getattr(cls, "__dataclass", None) if dc is not None: # do not set defaults so that settings defaults from various architectures still works gen_parser_from_dataclass(parser, dc(), delete_default=True) @classmethod def build_model(cls, args, task): """Build a new model instance.""" raise NotImplementedError("Model must implement the build_model method") def get_targets(self, sample, net_output): """Get targets from either the sample or the net's output.""" return sample["target"] def get_normalized_probs( self, net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]], log_probs: bool, sample: Optional[Dict[str, Tensor]] = None, ): """Get normalized probabilities (or log probs) from a net's output.""" return self.get_normalized_probs_scriptable(net_output, log_probs, sample) # TorchScript doesn't support super() method so that the scriptable Subclass # can't access the base class model in Torchscript. # Current workaround is to add a helper function with different name and # call the helper function from scriptable Subclass. def get_normalized_probs_scriptable( self, net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]], log_probs: bool, sample: Optional[Dict[str, Tensor]] = None, ): """Scriptable helper function for get_normalized_probs in ~BaseFairseqModel""" if hasattr(self, "decoder"): return self.decoder.get_normalized_probs(net_output, log_probs, sample) elif torch.is_tensor(net_output): # syntactic sugar for simple models which don't have a decoder # (e.g., the classification tutorial) logits = net_output.float() if log_probs: return F.log_softmax(logits, dim=-1) else: return F.softmax(logits, dim=-1) raise NotImplementedError def extract_features(self, *args, **kwargs): """Similar to *forward* but only return features.""" return self(*args, **kwargs) def max_positions(self): """Maximum length supported by the model.""" return None def load_state_dict( self, state_dict, strict=True, model_cfg: Optional[DictConfig] = None, args: Optional[Namespace] = None, ): """Copies parameters and buffers from *state_dict* into this module and its descendants. Overrides the method in :class:`nn.Module`. Compared with that method this additionally "upgrades" *state_dicts* from old checkpoints. """ if model_cfg is None and args is not None: logger.warn( "using 'args' is deprecated, please update your code to use dataclass config" ) model_cfg = convert_namespace_to_omegaconf(args).model self.upgrade_state_dict(state_dict) new_state_dict = prune_state_dict(state_dict, model_cfg) # FIXME: hot fix for loading hubert model with different cluster num # new_state_dict = {k: v for k, v in new_state_dict.items() if k not in ["label_embs_concat"]} return super().load_state_dict(new_state_dict, strict) def upgrade_state_dict(self, state_dict): """Upgrade old state dicts to work with newer code.""" self.upgrade_state_dict_named(state_dict, "") def upgrade_state_dict_named(self, state_dict, name): """Upgrade old state dicts to work with newer code. Args: state_dict (dict): state dictionary to upgrade, in place name (str): the state dict key corresponding to the current module """ assert state_dict is not None def do_upgrade(m, prefix): if len(prefix) > 0: prefix += "." for n, c in m.named_children(): name = prefix + n if hasattr(c, "upgrade_state_dict_named"): c.upgrade_state_dict_named(state_dict, name) elif hasattr(c, "upgrade_state_dict"): c.upgrade_state_dict(state_dict) do_upgrade(c, name) do_upgrade(self, name) def set_num_updates(self, num_updates): """State from trainer to pass along to model at every update.""" for m in self.modules(): if hasattr(m, "set_num_updates") and m != self: m.set_num_updates(num_updates) def prepare_for_inference_(self, cfg: DictConfig): """Prepare model for inference.""" kwargs = {} kwargs["beamable_mm_beam_size"] = ( None if getattr(cfg.generation, "no_beamable_mm", False) else getattr(cfg.generation, "beam", 5) ) kwargs["need_attn"] = getattr(cfg.generation, "print_alignment", False) if getattr(cfg.generation, "retain_dropout", False): kwargs["retain_dropout"] = cfg.generation.retain_dropout kwargs["retain_dropout_modules"] = cfg.generation.retain_dropout_modules self.make_generation_fast_(**kwargs) def make_generation_fast_(self, **kwargs): """ Legacy entry point to optimize model for faster generation. Prefer prepare_for_inference_. """ if self._is_generation_fast: return # only apply once self._is_generation_fast = True # remove weight norm from all modules in the network def apply_remove_weight_norm(module): try: nn.utils.remove_weight_norm(module) except (AttributeError, ValueError): # this module didn't have weight norm return self.apply(apply_remove_weight_norm) def apply_make_generation_fast_(module, prefix): if len(prefix) > 0: prefix += "." base_func = BaseFairseqModel.make_generation_fast_ for n, m in module.named_modules(): if ( m != self and hasattr(m, "make_generation_fast_") # don't call this implementation again, e.g., if # children modules also inherit from BaseFairseqModel and m.make_generation_fast_.__func__ is not base_func ): name = prefix + n m.make_generation_fast_(name=name, **kwargs) apply_make_generation_fast_(self, "") def train(mode=True): if mode: raise RuntimeError("cannot train after make_generation_fast") # this model should no longer be used for training self.eval() self.train = train def prepare_for_onnx_export_(self, **kwargs): """Make model exportable via ONNX trace.""" seen = set() def apply_prepare_for_onnx_export_(module): if ( module != self and hasattr(module, "prepare_for_onnx_export_") and module not in seen ): seen.add(module) module.prepare_for_onnx_export_(**kwargs) self.apply(apply_prepare_for_onnx_export_) @classmethod def from_pretrained( cls, model_name_or_path, checkpoint_file="model.pt", data_name_or_path=".", **kwargs, ): """ Load a :class:`~fairseq.models.FairseqModel` from a pre-trained model file. Downloads and caches the pre-trained model file if needed. The base implementation returns a :class:`~fairseq.hub_utils.GeneratorHubInterface`, which can be used to generate translations or sample from language models. The underlying :class:`~fairseq.models.FairseqModel` can be accessed via the *generator.models* attribute. Other models may override this to implement custom hub interfaces. Args: model_name_or_path (str): either the name of a pre-trained model to load or a path/URL to a pre-trained model state dict checkpoint_file (str, optional): colon-separated list of checkpoint files in the model archive to ensemble (default: 'model.pt') data_name_or_path (str, optional): point args.data to the archive at the given path/URL. Can start with '.' or './' to reuse the model archive path. """ x = hub_utils.from_pretrained( model_name_or_path, checkpoint_file, data_name_or_path, archive_map=cls.hub_models(), **kwargs, ) logger.info(x["args"]) return hub_utils.GeneratorHubInterface(x["args"], x["task"], x["models"]) @classmethod def hub_models(cls): return {} class FairseqEncoderDecoderModel(BaseFairseqModel): """Base class for encoder-decoder models. Args: encoder (FairseqEncoder): the encoder decoder (FairseqDecoder): the decoder """ def __init__(self, encoder, decoder): super().__init__() self.encoder = encoder self.decoder = decoder check_type(self.encoder, FairseqEncoder) check_type(self.decoder, FairseqDecoder) def forward(self, src_tokens, src_lengths, prev_output_tokens, **kwargs): """ Run the forward pass for an encoder-decoder model. First feed a batch of source tokens through the encoder. Then, feed the encoder output and previous decoder outputs (i.e., teacher forcing) to the decoder to produce the next outputs:: encoder_out = self.encoder(src_tokens, src_lengths) return self.decoder(prev_output_tokens, encoder_out) Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (LongTensor): source sentence lengths of shape `(batch)` prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for teacher forcing Returns: tuple: - the decoder's output of shape `(batch, tgt_len, vocab)` - a dictionary with any model-specific outputs """ encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs) decoder_out = self.decoder( prev_output_tokens, encoder_out=encoder_out, **kwargs ) return decoder_out def forward_decoder(self, prev_output_tokens, **kwargs): return self.decoder(prev_output_tokens, **kwargs) def extract_features(self, src_tokens, src_lengths, prev_output_tokens, **kwargs): """ Similar to *forward* but only return features. Returns: tuple: - the decoder's features of shape `(batch, tgt_len, embed_dim)` - a dictionary with any model-specific outputs """ encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs) features = self.decoder.extract_features( prev_output_tokens, encoder_out=encoder_out, **kwargs ) return features def output_layer(self, features, **kwargs): """Project features to the default output size (typically vocabulary size).""" return self.decoder.output_layer(features, **kwargs) def max_positions(self): """Maximum length supported by the model.""" return (self.encoder.max_positions(), self.decoder.max_positions()) def max_decoder_positions(self): """Maximum length supported by the decoder.""" return self.decoder.max_positions() class FairseqModel(FairseqEncoderDecoderModel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) utils.deprecation_warning( "FairseqModel is deprecated, please use FairseqEncoderDecoderModel " "or BaseFairseqModel instead", stacklevel=4, ) class FairseqMultiModel(BaseFairseqModel): """Base class for combining multiple encoder-decoder models.""" def __init__(self, encoders, decoders): super().__init__() assert encoders.keys() == decoders.keys() self.keys = list(encoders.keys()) for key in self.keys: check_type(encoders[key], FairseqEncoder) check_type(decoders[key], FairseqDecoder) self.models = nn.ModuleDict( { key: FairseqEncoderDecoderModel(encoders[key], decoders[key]) for key in self.keys } ) @staticmethod def build_shared_embeddings(
dicts: Dict[str, Dictionary],
1
2023-11-27 09:53:58+00:00
12k
zerolink-io/zerolink-python
zerolink/api.py
[ { "identifier": "read_docx", "path": "zerolink/extract.py", "snippet": "def read_docx(path: str) -> str:\n \"\"\"\n Turn the Microsoft Word document into a raw bytestring\n \"\"\"\n if NO_DOCX:\n print(\"Microsoft Word document support is not available\")\n sys.exit(1)\n\n d...
import json import os import zerolink.attribute as attr import zerolink.req as req from typing import Any, Generator, List, Optional, Union from zerolink.extract import read_docx from zerolink.settings import api_key from zerolink_client.models import ( AttributeType, ContextAssumption, CreateAttribute, CreateEntity, CreateRule, CreateRuleContext, CreateTriple, EntityType, ExtractModel, ResultStatus, SpatialAssumption, TemporalAssumption, TextExtract, WorldAssumption, ) from zerolink_client.types import File
7,234
The Foundation knowledge graph is a collection of entities and relations that are common to all knowledge graphs and form the foundation of commonsense reasoning. The graph is read-only. """ def __init__(self) -> None: self.name = "Foundation" self.session_id = None def entity(self, name: str) -> Entity: """ Get a foundation entity by name. """ ents = list(find_entity(name)) if len(ents) == 0: raise ValueError(f"Entity '{name}' not found") else: return ents[0] def entity_id(self, id: str) -> Entity: """ Get a foundation entity by id. """ e = req.get_entity_id(id) desc = e.description if e.description else None return Entity(e.id, e.entity, desc) def property(self, name: str) -> Relation: """ Get a foundation property by name. """ rels = list(find_relation(name)) if len(rels) == 0: raise ValueError(f"Relation '{name}' not found") else: return rels[0] def attribute(self, name: str) -> Relation: """ Get a foundation attribute by name. """ rels = list(find_relation(name)) if len(rels) == 0: raise ValueError(f"Relation '{name}' not found") else: return rels[0] def reasoner(self, name: str): """ Get a foundation reasoner by name. """ reasoners = set(req.get_reasoners(name)) if name in reasoners: return name else: raise ValueError(f"Reasoner '{name}' not found") class UserKnowledgeGraph(KnowledgeGraph): """ A knowledge graph is a collection of entities and relations. """ session_id: int def __init__(self, session_id: int, name: str): self.name = name self.session_id = session_id @property def entities(self) -> List[Entity]: rep = req.get_session_entities_list(self.session_id) return [ Entity(id=e.id, name=e.entity, description=e.desc, kg=self) for e in rep ] @property def facts(self) -> List[Fact]: rep = req.get_session_facts_list(self.session_id) return [ Fact(id=f.id, subject=f.subject, predicate=f.predicate, object=f.object_) for f in rep ] def add_entity( self, name: str, type: Optional[Union[EntityType, Entity, str]] = None, description: Optional[str] = None, ) -> Entity: if isinstance(type, EntityType): body = CreateEntity(name, entity_type=type) elif isinstance(type, Entity): body = CreateEntity(name, entity_str=type.id) elif isinstance(type, str): body = CreateEntity(name, entity_str=type) elif type is None: body = CreateEntity(name) else: raise ValueError("Invalid type") rep = req.add_entity(self.session_id, body) return Entity(id=rep.id, name=rep.entity, description=None, kg=self) def get_or_add_entity( self, name: str, type: Union[EntityType, Entity, str] ) -> Entity: raise NotImplementedError() def add_relation(self, *args, **kwargs): """ Add a relation to a user knowledge graph. """ raise NotImplementedError() def add_attribute(self, e: Entity, a: str, v: Any): """ Add an attribute to a user knowledge graph. """ value = attr.value(v)
# ------------------------------------------------------------------------ # Entities # ------------------------------------------------------------------------ class Entity(object): """ An entity is an object/node in a knowledge graph. """ def __init__( self, id: str, name: str, description: Optional[str] = None, kg: Optional["KnowledgeGraph"] = None, ): self.id = id self.name = name self.description = description self.kg = kg def instance(self, class_: "Entity") -> "Fact": """ Add a fact that this entity is an instance of a class. """ if self.kg: return self.kg.add_fact(self, "instance of", class_) else: raise ValueError("Not attached to a knowledge graph") def is_a(self, class_: "Entity") -> "Fact": """ Add a fact that this entity is an instance of a class. """ return self.instance(class_) def subclass(self, superclass: "Entity") -> "Fact": """ Add a fact that this entity is a subclass of a superclass. """ if self.kg: return self.kg.add_fact(self, "subclass of", superclass) else: raise ValueError("Not attached to a knowledge graph") def is_type(self, type_: "Entity") -> "Fact": """ Add a fact that this entity is a subclass of a superclass. """ if self.kg: return self.kg.add_fact(self, "is subclass", type_) else: raise ValueError("Not attached to a knowledge graph") def quality(self, quality: "Entity") -> "Fact": """ Add a fact that this entity has a quality. """ if self.kg: return self.kg.add_fact(self, "has quality", quality) else: raise ValueError("Not attached to a knowledge graph") def characteristic(self, characteristic: "Entity") -> "Fact": """ Add a fact that this entity has a characteristic. """ if self.kg: return self.kg.add_fact(self, "has characteristic", characteristic) else: raise ValueError("Not attached to a knowledge graph") def part_of(self, whole: "Entity") -> "Fact": """ Add a fact that this entity is part of another entity. """ if self.kg: return self.kg.add_fact(self, "part of", whole) else: raise ValueError("Not attached to a knowledge graph") def add_fact(self, predicate: str, object: "Entity") -> "Fact": """ Add an arbitrary fact about this entity. """ if self.kg: return self.kg.add_fact(self, predicate, object) else: raise ValueError("Not attached to a knowledge graph") def add_attribute(self, attribute: str, value: Any) -> None: """ Add an attribute to this entity. """ if self.kg: self.kg.add_attribute(self, attribute, value) else: raise ValueError("Not attached to a knowledge graph") @property def user_entity(self) -> bool: # If the id starts with EU then it is a user entity, otherwise it is a # foundation entity return self.id.startswith("EU") def ontology(self) -> dict[str, Any]: return ontology(self.id) def __str__(self) -> str: return f"{self.name} : ({self.id}) - {self.description}" def __repr__(self) -> str: return f'<Entity id="{self.id}" name="{self.name}" description="{self.description}">' class Relation(object): """ A relation is an edge in a knowledge graph. """ def __init__(self, id: str, name: str): self.id = id self.name = name def __str__(self): return f"{self.name} : ({self.id})" def __repr__(self): return f'<Relation id="{self.id}" name="{self.name}">' class Fact(object): def __init__(self, id: str, subject: str, predicate: str, object: str, kg=None): self.id = id self.subject = subject self.predicate = predicate self.object = object self.kg = kg def __str__(self) -> str: return f"{self.subject} {self.predicate} {self.object}" def __rep__(self) -> str: return ( f'<Fact "{self.subject}" "{self.predicate}" "{self.object}" id="{self.id}">' ) # ------------------------------------------------------------------------ # Knowledge Graph # ------------------------------------------------------------------------ class KnowledgeGraph(object): name: str session_id: Optional[int] def __repr__(self): return f'<KnowledgeGraph name="{self.name}" session_id="{self.session_id}">' def ask( self, question: str, spatial: SpatialAssumption = SpatialAssumption.EARTH, temporal: TemporalAssumption = TemporalAssumption.CURRENT, world: WorldAssumption = WorldAssumption.PARTIAL, context: ContextAssumption = ContextAssumption.GLOBAL, reasoners: Optional[list[str]] = None, dump_interpretation: bool = True, **kwargs, ) -> "Result": assumps = { "spatial": spatial, "temporal": temporal, "world": world, "context": context, } rep = req.ask_question(self.session_id, question, assumps, **kwargs) if rep.query and dump_interpretation: print("Interpretation:") print(json.dumps(rep.query.to_dict(), indent=4)) if rep is None: return Result(data=[], status=ResultStatus.EMPTY) if rep.msg == "Found the answer": return Result(data=rep.answers, status=ResultStatus.ANSWERS) else: return Result(data=[], status=ResultStatus.EMPTY) def add_entity( self, name: str, type: Optional[Union[EntityType, Entity, str]] = None, description: Optional[str] = None, ) -> Entity: raise ValueError("Cannot add entity to a read-only knowledge graph") def add_fact(self, s: Entity, p: str, o: Entity) -> Fact: raise ValueError("Cannot add fact to a read-only knowledge graph") def add_rule(self, rule: str, ctx: Optional[dict[str, Any]] = None) -> str: raise ValueError("Cannot add rule to a read-only knowledge graph") def add_attribute(self, e: Entity, a: str, v: Any) -> Fact: raise ValueError("Cannot add attribute to a read-only knowledge graph") @property def entities(self) -> List[Entity]: raise NotImplementedError() @property def facts(self) -> List[Fact]: raise NotImplementedError() class Foundation(KnowledgeGraph): """ The Foundation knowledge graph is a collection of entities and relations that are common to all knowledge graphs and form the foundation of commonsense reasoning. The graph is read-only. """ def __init__(self) -> None: self.name = "Foundation" self.session_id = None def entity(self, name: str) -> Entity: """ Get a foundation entity by name. """ ents = list(find_entity(name)) if len(ents) == 0: raise ValueError(f"Entity '{name}' not found") else: return ents[0] def entity_id(self, id: str) -> Entity: """ Get a foundation entity by id. """ e = req.get_entity_id(id) desc = e.description if e.description else None return Entity(e.id, e.entity, desc) def property(self, name: str) -> Relation: """ Get a foundation property by name. """ rels = list(find_relation(name)) if len(rels) == 0: raise ValueError(f"Relation '{name}' not found") else: return rels[0] def attribute(self, name: str) -> Relation: """ Get a foundation attribute by name. """ rels = list(find_relation(name)) if len(rels) == 0: raise ValueError(f"Relation '{name}' not found") else: return rels[0] def reasoner(self, name: str): """ Get a foundation reasoner by name. """ reasoners = set(req.get_reasoners(name)) if name in reasoners: return name else: raise ValueError(f"Reasoner '{name}' not found") class UserKnowledgeGraph(KnowledgeGraph): """ A knowledge graph is a collection of entities and relations. """ session_id: int def __init__(self, session_id: int, name: str): self.name = name self.session_id = session_id @property def entities(self) -> List[Entity]: rep = req.get_session_entities_list(self.session_id) return [ Entity(id=e.id, name=e.entity, description=e.desc, kg=self) for e in rep ] @property def facts(self) -> List[Fact]: rep = req.get_session_facts_list(self.session_id) return [ Fact(id=f.id, subject=f.subject, predicate=f.predicate, object=f.object_) for f in rep ] def add_entity( self, name: str, type: Optional[Union[EntityType, Entity, str]] = None, description: Optional[str] = None, ) -> Entity: if isinstance(type, EntityType): body = CreateEntity(name, entity_type=type) elif isinstance(type, Entity): body = CreateEntity(name, entity_str=type.id) elif isinstance(type, str): body = CreateEntity(name, entity_str=type) elif type is None: body = CreateEntity(name) else: raise ValueError("Invalid type") rep = req.add_entity(self.session_id, body) return Entity(id=rep.id, name=rep.entity, description=None, kg=self) def get_or_add_entity( self, name: str, type: Union[EntityType, Entity, str] ) -> Entity: raise NotImplementedError() def add_relation(self, *args, **kwargs): """ Add a relation to a user knowledge graph. """ raise NotImplementedError() def add_attribute(self, e: Entity, a: str, v: Any): """ Add an attribute to a user knowledge graph. """ value = attr.value(v)
body = CreateAttribute(
4
2023-12-03 07:50:04+00:00
12k
amazon-science/discal
run_summarization_w_calib.py
[ { "identifier": "CustomSeq2SeqTrainer", "path": "calibration_utils.py", "snippet": "class CustomSeq2SeqTrainer(Seq2SeqTrainer):\n '''\n This is a custom seq2seq training, supporting an EMA-based generator for calibaration.\n '''\n def __init__(self, teacher_model=None, calibration_params...
import logging import os import sys import datasets import nltk # Here to have a nice missing dependency error message early on import torch import transformers import numpy as np from dataclasses import dataclass, field from typing import Optional from datasets import load_dataset, load_metric from filelock import FileLock from transformers import ( AutoTokenizer, DataCollatorForSeq2Seq, HfArgumentParser, Seq2SeqTrainingArguments, set_seed ) from transformers.file_utils import is_offline_mode from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version from transformers.utils.versions import require_version from calibration_utils import CustomSeq2SeqTrainer from distillation_utils import get_teacher_model, get_student_model
9,677
return model_inputs column_names = raw_datasets["train"].column_names if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset") train_dataset = raw_datasets["train"] if data_args.max_train_samples is not None: train_dataset = train_dataset.select(range(data_args.max_train_samples)) #with training_args.main_process_first(desc="train dataset map pre-processing"): train_dataset = train_dataset.map( preprocess_function, batched=True, num_proc=data_args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on train dataset", ) column_names = raw_datasets["validation"].column_names if training_args.do_eval: max_target_length = data_args.val_max_target_length if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset") eval_dataset = raw_datasets["validation"] if data_args.max_eval_samples is not None: eval_dataset = eval_dataset.select(range(data_args.max_eval_samples)) #with training_args.main_process_first(desc="validation dataset map pre-processing"): eval_dataset = eval_dataset.map( preprocess_function, batched=True, num_proc=data_args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on validation dataset", ) column_names = raw_datasets["test"].column_names if training_args.do_predict: max_target_length = data_args.val_max_target_length if "test" not in raw_datasets: raise ValueError("--do_predict requires a test dataset") predict_dataset = raw_datasets["test"] if data_args.max_predict_samples is not None: predict_dataset = predict_dataset.select(range(data_args.max_predict_samples)) #with training_args.main_process_first(desc="prediction dataset map pre-processing"): predict_dataset = predict_dataset.map( preprocess_function, batched=True, num_proc=data_args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on prediction dataset", ) # Data collator label_pad_token_id = -100 if data_args.ignore_pad_token_for_loss else tokenizer.pad_token_id data_collator = DataCollatorForSeq2Seq( tokenizer, model=model, label_pad_token_id=label_pad_token_id, pad_to_multiple_of=8 if training_args.fp16 else None, ) # Metric metric = load_metric("rouge") def postprocess_text(preds, labels): preds = [pred.strip() for pred in preds] labels = [label.strip() for label in labels] # rougeLSum expects newline after each sentence preds = ["\n".join(nltk.sent_tokenize(pred)) for pred in preds] labels = ["\n".join(nltk.sent_tokenize(label)) for label in labels] return preds, labels def compute_metrics(eval_preds): preds, labels = eval_preds if isinstance(preds, tuple): preds = preds[0] decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True) if data_args.ignore_pad_token_for_loss: # Replace -100 in the labels as we can't decode them. labels = np.where(labels != -100, labels, tokenizer.pad_token_id) decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True) # Some simple post-processing decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels) result = metric.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True) # Extract a few results from ROUGE result = {key: value.mid.fmeasure * 100 for key, value in result.items()} prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds] result["gen_len"] = np.mean(prediction_lens) result = {k: round(v, 4) for k, v in result.items()} return result # Configuration for calibration calibration_params = {} calibration_params['num_beams'] = training_args.generation_num_beams calibration_params['num_candidate_beams'] = training_args.num_candidate_beams calibration_params['calibration'] = training_args.calibration calibration_params['min_length'] = training_args.generation_min_length calibration_params['max_length'] = training_args.generation_max_length calibration_params['length_penalty'] = training_args.generation_length_penalty calibration_params['mle_weight'] = training_args.mle_weight calibration_params['calibration_weight'] = training_args.calibration_weight calibration_params['disversity_penalty'] = training_args.disversity_penalty calibration_params['abstract_weight'] = training_args.abstract_weight calibration_params['normalize'] = True calibration_params['score_mode'] = 'log' training_args.load_best_model_at_end = False # Need this line for keeping all the columns training_args.remove_unused_columns=False # Initialize our Trainer
""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 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. 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. """ """ Fine-tuning the library models for sequence to sequence. """ # You can also adapt this script on your own sequence to sequence task. Pointers for this are left as comments. # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.9.0.dev0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/summarization/requirements.txt") logger = logging.getLogger(__name__) try: nltk.data.find("tokenizers/punkt") except (LookupError, OSError): if is_offline_mode(): raise LookupError( "Offline mode: run this script without TRANSFORMERS_OFFLINE first to download nltk data files" ) with FileLock(".lock") as lock: nltk.download("punkt", quiet=True) @dataclass class ModelArguments: """ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. """ model_name_or_path: str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models (student)"} ) teacher_model_name_or_path: Optional[str] = field( default=None, metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models (teacher)"} ) config_name: Optional[str] = field( default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} ) tokenizer_name: Optional[str] = field( default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) cache_dir: Optional[str] = field( default=None, metadata={"help": "Where to store the pretrained models downloaded from huggingface.co"}, ) use_fast_tokenizer: bool = field( default=True, metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}, ) model_revision: str = field( default="main", metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, ) use_auth_token: bool = field( default=False, metadata={ "help": "Will use the token generated when running `transformers-cli login` (necessary to use this script " "with private models)." }, ) @dataclass class DataTrainingArguments: """ Arguments pertaining to what data we are going to input our model for training and eval. """ dataset_name: Optional[str] = field( default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."} ) dataset_config_name: Optional[str] = field( default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) text_column: Optional[str] = field( default=None, metadata={"help": "The name of the column in the datasets containing the full texts (for summarization)."}, ) summary_column: Optional[str] = field( default=None, metadata={"help": "The name of the column in the datasets containing the summaries (for summarization)."}, ) train_file: Optional[str] = field( default=None, metadata={"help": "The input training data file (a jsonlines or csv file)."} ) validation_file: Optional[str] = field( default=None, metadata={ "help": "An optional input evaluation data file to evaluate the metrics (rouge) on " "(a jsonlines or csv file)." }, ) test_file: Optional[str] = field( default=None, metadata={ "help": "An optional input test data file to evaluate the metrics (rouge) on " "(a jsonlines or csv file)." }, ) overwrite_cache: bool = field( default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} ) preprocessing_num_workers: Optional[int] = field( default=None, metadata={"help": "The number of processes to use for the preprocessing."}, ) max_source_length: Optional[int] = field( default=1024, metadata={ "help": "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." }, ) max_target_length: Optional[int] = field( default=128, metadata={ "help": "The maximum total sequence length for target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." }, ) val_max_target_length: Optional[int] = field( default=None, metadata={ "help": "The maximum total sequence length for validation target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded. Will default to `max_target_length`." "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used " "during ``evaluate`` and ``predict``." }, ) pad_to_max_length: bool = field( default=False, metadata={ "help": "Whether to pad all samples to model maximum sentence length. " "If False, will pad the samples dynamically when batching to the maximum length in the batch. More " "efficient on GPU but very bad for TPU." }, ) max_train_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." }, ) max_eval_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." }, ) max_predict_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." }, ) num_beams: Optional[int] = field( default=None, metadata={ "help": "Number of beams to use for evaluation. This argument will be passed to ``model.generate``, " "which is used during ``evaluate`` and ``predict``." }, ) ignore_pad_token_for_loss: bool = field( default=True, metadata={ "help": "Whether to ignore the tokens corresponding to padded labels in the loss computation or not." }, ) source_prefix: Optional[str] = field( default=None, metadata={"help": "A prefix to add before every source text (useful for T5 models)."} ) eval_type: Optional[str] = field( default='plain', metadata={ "help": "spans_combined: splitting prediction into ISSUE, OUTCOME, NEXTSTEP spans for evaluation; " "plain: filtering out ISSUE, OUTCOME, NEXTSTEP tokens, evaluating the entire summary text" }, ) early_stopping_patience: Optional[int] = field( default=5, metadata={ "help": "the training will be stopped after this many checkpoints with no improvement" }, ) def __post_init__(self): if self.dataset_name is None and self.train_file is None and self.validation_file is None: raise ValueError("Need either a dataset name or a training/validation file.") else: if self.train_file is not None: extension = self.train_file.split(".")[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: extension = self.validation_file.split(".")[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." if self.val_max_target_length is None: self.val_max_target_length = self.max_target_length @dataclass class BARTrainingArguments(Seq2SeqTrainingArguments): """ sortish_sampler (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether to use a `sortish sampler` or not. Only possible if the underlying datasets are `Seq2SeqDataset` for now but will become generally available in the near future. It sorts the inputs according to lengths in order to minimize the padding size, with a bit of randomness for the training set. predict_with_generate (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether to use generate to calculate generative metrics (ROUGE, BLEU). generation_max_length (:obj:`int`, `optional`): The :obj:`max_length` to use on each evaluation loop when :obj:`predict_with_generate=True`. Will default to the :obj:`max_length` value of the model configuration. generation_num_beams (:obj:`int`, `optional`): The :obj:`num_beams` to use on each evaluation loop when :obj:`predict_with_generate=True`. Will default to the :obj:`num_beams` value of the model configuration. """ predict_with_generate: bool = field( default=True, metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) generation_min_length: Optional[int] = field( default=10, metadata={ "help": "The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `max_length` value of the model configuration." }, ) generation_max_length: Optional[int] = field( default=360, metadata={ "help": "The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `max_length` value of the model configuration." }, ) generation_num_beams: Optional[int] = field( default=6, metadata={ "help": "The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `num_beams` value of the model configuration." }, ) generation_length_penalty: Optional[float] = field( default=0.0, metadata={ "help": "Value > 0.0 promotes longer sequences in beam decoding, value < 0.0 promotes shorter ones" }, ) generation_no_repeat_ngram_size: Optional[int] = field( default=3, metadata={ "help": "Is > 0, no ngram of this size will be repeated in the output sequences" }, ) metric_for_best_model: Optional[str] = field( default="loss", metadata={ "help": "can be loss or Rouge score for some/all of the spans" }, ) #### new arguments for calibration process calibration: bool = field( default=False, metadata={"help": "Whether to use the calibration loss."}, ) num_candidate_beams: int = field( default=6, metadata={"help": "The number of candidate summaries used for probability calibration."}, ) disversity_penalty: float = field( default=0.1, metadata={"help": "penalty for diverse beamserch in pseudo summary generation."}, ) mle_weight: float = field( default=0.01, metadata={"help": "Weight of MLE Loss."}, ) calibration_weight: float = field( default=1.0, metadata={"help": "Weight of calibration loss."}, ) abstract_weight: float = field( default=0.0, metadata={"help": "Weight of abstractiveness."}, ) #### new arguments for distillation shrink_type: Optional[str] = field( default=None, metadata={"help": "Types of distillation."}, ) dynamic_temperature: bool = field( default=False, metadata={"help": "Whether to use dynamic temperature scaling for the teacher model."}, ) temperature_scaling: float = field( default=1.0, metadata={"help": "Temperature scaling value for the teacher model."}, ) summarization_name_mapping = { "amazon_reviews_multi": ("review_body", "review_title"), "big_patent": ("description", "abstract"), "cnn_dailymail": ("article", "highlights"), "orange_sum": ("text", "summary"), "pn_summary": ("article", "summary"), "psc": ("extract_text", "summary_text"), "samsum": ("dialogue", "summary"), "thaisum": ("body", "summary"), "xglue": ("news_body", "news_title"), "xsum": ("document", "summary"), "wiki_summary": ("article", "highlights"), } def main(): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, BARTrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)], ) log_level = training_args.get_process_log_level() logger.setLevel(log_level) datasets.utils.logging.set_verbosity(log_level) transformers.utils.logging.set_verbosity(log_level) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" ) logger.info(f"Training/evaluation parameters {training_args}") if data_args.source_prefix is None and model_args.model_name_or_path in [ "t5-small", "t5-base", "t5-large", "t5-3b", "t5-11b", ]: logger.warning( "You're running a t5 model but didn't provide a source prefix, which is the expected, e.g. with " "`--source_prefix 'summarize: ' `" ) # Detecting last checkpoint. last_checkpoint = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed) # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files this script will use the first column for the full texts and the second column for the # summaries (unless you specify column names for this with the `text_column` and `summary_column` arguments). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. raw_datasets = load_dataset( data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir ) else: data_files = {} if data_args.train_file is not None: data_files["train"] = data_args.train_file extension = data_args.train_file.split(".")[-1] if data_args.validation_file is not None: data_files["validation"] = data_args.validation_file extension = data_args.validation_file.split(".")[-1] if data_args.test_file is not None: data_files["test"] = data_args.test_file extension = data_args.test_file.split(".")[-1] raw_datasets = load_dataset(extension, data_files=data_files, cache_dir=model_args.cache_dir) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. tokenizer = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) # teacher model teacher_model = None if model_args.teacher_model_name_or_path is not None: teacher_model = get_teacher_model(model_args, training_args) teacher_model.resize_token_embeddings(len(tokenizer)) if training_args.fp16: teacher_model.half() if torch.cuda.is_available(): teacher_model.to('cuda') teacher_model.eval() trainable_n_parameters = sum(p.numel() for p in teacher_model.parameters() if p.requires_grad) total_n_parameters = sum(p.numel() for p in teacher_model.parameters()) print(teacher_model.config) print(f'Model # total params: {total_n_parameters}') print(f'Model # trainable params: {trainable_n_parameters}') # student model model = get_student_model(model_args, training_args) trainable_n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) total_n_parameters = sum(p.numel() for p in model.parameters()) print(model.config) print(f'Model # total params: {total_n_parameters}') print(f'Model # trainable params: {trainable_n_parameters}') model.resize_token_embeddings(len(tokenizer)) if model.config.decoder_start_token_id is None: raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined") prefix = data_args.source_prefix if data_args.source_prefix is not None else "" # Preprocessing the datasets. # We need to tokenize inputs and targets. if training_args.do_train: column_names = raw_datasets["train"].column_names elif training_args.do_eval: column_names = raw_datasets["validation"].column_names elif training_args.do_predict: column_names = raw_datasets["test"].column_names else: logger.info("There is nothing to do. Please pass `do_train`, `do_eval` and/or `do_predict`.") return # Get the column names for input/target. dataset_columns = summarization_name_mapping.get(data_args.dataset_name, None) if data_args.text_column is None: text_column = dataset_columns[0] if dataset_columns is not None else column_names[0] else: text_column = data_args.text_column if text_column not in column_names: raise ValueError( f"--text_column' value '{data_args.text_column}' needs to be one of: {', '.join(column_names)}" ) if data_args.summary_column is None: summary_column = dataset_columns[1] if dataset_columns is not None else column_names[1] else: summary_column = data_args.summary_column if summary_column not in column_names: raise ValueError( f"--summary_column' value '{data_args.summary_column}' needs to be one of: {', '.join(column_names)}" ) # Temporarily set max_target_length for training. max_target_length = data_args.max_target_length padding = "max_length" if data_args.pad_to_max_length else False if training_args.label_smoothing_factor > 0 and not hasattr(model, "prepare_decoder_input_ids_from_labels"): logger.warning( "label_smoothing is enabled but the `prepare_decoder_input_ids_from_labels` method is not defined for" f"`{model.__class__.__name__}`. This will lead to loss being calculated twice and will take up more memory" ) def preprocess_function(examples): inputs = examples[text_column] targets = examples[summary_column] inputs = [prefix + inp for inp in inputs] model_inputs = tokenizer(inputs, max_length=data_args.max_source_length, padding=padding, truncation=True) # Setup the tokenizer for targets with tokenizer.as_target_tokenizer(): labels = tokenizer(targets, max_length=max_target_length, padding=padding, truncation=True) # If we are padding here, replace all tokenizer.pad_token_id in the labels by -100 when we want to ignore # padding in the loss. if padding == "max_length" and data_args.ignore_pad_token_for_loss: labels["input_ids"] = [ [(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"] ] model_inputs["labels"] = labels["input_ids"] return model_inputs column_names = raw_datasets["train"].column_names if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset") train_dataset = raw_datasets["train"] if data_args.max_train_samples is not None: train_dataset = train_dataset.select(range(data_args.max_train_samples)) #with training_args.main_process_first(desc="train dataset map pre-processing"): train_dataset = train_dataset.map( preprocess_function, batched=True, num_proc=data_args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on train dataset", ) column_names = raw_datasets["validation"].column_names if training_args.do_eval: max_target_length = data_args.val_max_target_length if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset") eval_dataset = raw_datasets["validation"] if data_args.max_eval_samples is not None: eval_dataset = eval_dataset.select(range(data_args.max_eval_samples)) #with training_args.main_process_first(desc="validation dataset map pre-processing"): eval_dataset = eval_dataset.map( preprocess_function, batched=True, num_proc=data_args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on validation dataset", ) column_names = raw_datasets["test"].column_names if training_args.do_predict: max_target_length = data_args.val_max_target_length if "test" not in raw_datasets: raise ValueError("--do_predict requires a test dataset") predict_dataset = raw_datasets["test"] if data_args.max_predict_samples is not None: predict_dataset = predict_dataset.select(range(data_args.max_predict_samples)) #with training_args.main_process_first(desc="prediction dataset map pre-processing"): predict_dataset = predict_dataset.map( preprocess_function, batched=True, num_proc=data_args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on prediction dataset", ) # Data collator label_pad_token_id = -100 if data_args.ignore_pad_token_for_loss else tokenizer.pad_token_id data_collator = DataCollatorForSeq2Seq( tokenizer, model=model, label_pad_token_id=label_pad_token_id, pad_to_multiple_of=8 if training_args.fp16 else None, ) # Metric metric = load_metric("rouge") def postprocess_text(preds, labels): preds = [pred.strip() for pred in preds] labels = [label.strip() for label in labels] # rougeLSum expects newline after each sentence preds = ["\n".join(nltk.sent_tokenize(pred)) for pred in preds] labels = ["\n".join(nltk.sent_tokenize(label)) for label in labels] return preds, labels def compute_metrics(eval_preds): preds, labels = eval_preds if isinstance(preds, tuple): preds = preds[0] decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True) if data_args.ignore_pad_token_for_loss: # Replace -100 in the labels as we can't decode them. labels = np.where(labels != -100, labels, tokenizer.pad_token_id) decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True) # Some simple post-processing decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels) result = metric.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True) # Extract a few results from ROUGE result = {key: value.mid.fmeasure * 100 for key, value in result.items()} prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds] result["gen_len"] = np.mean(prediction_lens) result = {k: round(v, 4) for k, v in result.items()} return result # Configuration for calibration calibration_params = {} calibration_params['num_beams'] = training_args.generation_num_beams calibration_params['num_candidate_beams'] = training_args.num_candidate_beams calibration_params['calibration'] = training_args.calibration calibration_params['min_length'] = training_args.generation_min_length calibration_params['max_length'] = training_args.generation_max_length calibration_params['length_penalty'] = training_args.generation_length_penalty calibration_params['mle_weight'] = training_args.mle_weight calibration_params['calibration_weight'] = training_args.calibration_weight calibration_params['disversity_penalty'] = training_args.disversity_penalty calibration_params['abstract_weight'] = training_args.abstract_weight calibration_params['normalize'] = True calibration_params['score_mode'] = 'log' training_args.load_best_model_at_end = False # Need this line for keeping all the columns training_args.remove_unused_columns=False # Initialize our Trainer
trainer = CustomSeq2SeqTrainer(
0
2023-11-30 19:49:45+00:00
12k
JunMa11/UHNSeg-Quiz
nnunetv2/evaluation/find_best_configuration.py
[ { "identifier": "default_num_processes", "path": "nnunetv2/configuration.py", "snippet": "ANISO_THRESHOLD = 3 # determines when a sample is considered anisotropic (3 means that the spacing in the low" }, { "identifier": "ensemble_crossvalidations", "path": "nnunetv2/ensembling/ensemble.py",...
import argparse import os.path from copy import deepcopy from typing import Union, List, Tuple from batchgenerators.utilities.file_and_folder_operations import load_json, join, isdir, save_json from nnunetv2.configuration import default_num_processes from nnunetv2.ensembling.ensemble import ensemble_crossvalidations from nnunetv2.evaluation.accumulate_cv_results import accumulate_cv_results from nnunetv2.evaluation.evaluate_predictions import compute_metrics_on_folder, load_summary_json from nnunetv2.paths import nnUNet_preprocessed, nnUNet_raw, nnUNet_results from nnunetv2.postprocessing.remove_connected_components import determine_postprocessing from nnunetv2.utilities.file_path_utilities import maybe_convert_to_dataset_name, get_output_folder, \ convert_identifier_to_trainer_plans_config, get_ensemble_name, folds_tuple_to_string from nnunetv2.utilities.plans_handling.plans_handler import PlansManager
8,184
f"Inferred plans file: {join(nnUNet_preprocessed, maybe_convert_to_dataset_name(dataset_name_or_id), trained_model['plans'] + '.json')}.") continue # check if trained model output folder exists. This is a requirement. No mercy here. expected_output_folder = get_output_folder(dataset_name_or_id, trained_model['trainer'], trained_model['plans'], trained_model['configuration'], fold=None) if not isdir(expected_output_folder): raise RuntimeError(f"Trained model {trained_model} does not have an output folder. " f"Expected: {expected_output_folder}. Please run the training for this model! (don't forget " f"the --npz flag if you want to ensemble multiple configurations)") valid.append(trained_model) return valid def generate_inference_command(dataset_name_or_id: Union[int, str], configuration_name: str, plans_identifier: str = 'nnUNetPlans', trainer_name: str = 'nnUNetTrainer', folds: Union[List[int], Tuple[int, ...]] = (0, 1, 2, 3, 4), folder_with_segs_from_prev_stage: str = None, input_folder: str = 'INPUT_FOLDER', output_folder: str = 'OUTPUT_FOLDER', save_npz: bool = False): fold_str = '' for f in folds: fold_str += f' {f}' predict_command = '' trained_model_folder = get_output_folder(dataset_name_or_id, trainer_name, plans_identifier, configuration_name, fold=None) plans_manager = PlansManager(join(trained_model_folder, 'plans.json')) configuration_manager = plans_manager.get_configuration(configuration_name) if 'previous_stage' in plans_manager.available_configurations: prev_stage = configuration_manager.previous_stage_name predict_command += generate_inference_command(dataset_name_or_id, prev_stage, plans_identifier, trainer_name, folds, None, output_folder='OUTPUT_FOLDER_PREV_STAGE') + '\n' folder_with_segs_from_prev_stage = 'OUTPUT_FOLDER_PREV_STAGE' predict_command = f'nnUNetv2_predict -d {dataset_name_or_id} -i {input_folder} -o {output_folder} -f {fold_str} ' \ f'-tr {trainer_name} -c {configuration_name} -p {plans_identifier}' if folder_with_segs_from_prev_stage is not None: predict_command += f' -prev_stage_predictions {folder_with_segs_from_prev_stage}' if save_npz: predict_command += ' --save_probabilities' return predict_command def find_best_configuration(dataset_name_or_id, allowed_trained_models: Union[List[dict], Tuple[dict, ...]] = default_trained_models, allow_ensembling: bool = True, num_processes: int = default_num_processes, overwrite: bool = True, folds: Union[List[int], Tuple[int, ...]] = (0, 1, 2, 3, 4), strict: bool = False): dataset_name = maybe_convert_to_dataset_name(dataset_name_or_id) all_results = {} allowed_trained_models = filter_available_models(deepcopy(allowed_trained_models), dataset_name_or_id) for m in allowed_trained_models: output_folder = get_output_folder(dataset_name_or_id, m['trainer'], m['plans'], m['configuration'], fold=None) if not isdir(output_folder) and strict: raise RuntimeError(f'{dataset_name}: The output folder of plans {m["plans"]} configuration ' f'{m["configuration"]} is missing. Please train the model (all requested folds!) first!') identifier = os.path.basename(output_folder) merged_output_folder = join(output_folder, f'crossval_results_folds_{folds_tuple_to_string(folds)}') accumulate_cv_results(output_folder, merged_output_folder, folds, num_processes, overwrite) all_results[identifier] = { 'source': merged_output_folder, 'result': load_summary_json(join(merged_output_folder, 'summary.json'))['foreground_mean']['Dice'] } if allow_ensembling: for i in range(len(allowed_trained_models)): for j in range(i + 1, len(allowed_trained_models)): m1, m2 = allowed_trained_models[i], allowed_trained_models[j] output_folder_1 = get_output_folder(dataset_name_or_id, m1['trainer'], m1['plans'], m1['configuration'], fold=None) output_folder_2 = get_output_folder(dataset_name_or_id, m2['trainer'], m2['plans'], m2['configuration'], fold=None) identifier = get_ensemble_name(output_folder_1, output_folder_2, folds) output_folder_ensemble = join(nnUNet_results, dataset_name, 'ensembles', identifier) ensemble_crossvalidations([output_folder_1, output_folder_2], output_folder_ensemble, folds, num_processes, overwrite=overwrite) # evaluate ensembled predictions plans_manager = PlansManager(join(output_folder_1, 'plans.json')) dataset_json = load_json(join(output_folder_1, 'dataset.json')) label_manager = plans_manager.get_label_manager(dataset_json) rw = plans_manager.image_reader_writer_class() compute_metrics_on_folder(join(nnUNet_preprocessed, dataset_name, 'gt_segmentations'), output_folder_ensemble, join(output_folder_ensemble, 'summary.json'), rw, dataset_json['file_ending'], label_manager.foreground_regions if label_manager.has_regions else label_manager.foreground_labels, label_manager.ignore_label, num_processes) all_results[identifier] = \ { 'source': output_folder_ensemble, 'result': load_summary_json(join(output_folder_ensemble, 'summary.json'))['foreground_mean']['Dice'] } # pick best and report inference command best_score = max([i['result'] for i in all_results.values()]) best_keys = [k for k in all_results.keys() if all_results[k]['result'] == best_score] # may never happen but theoretically # there can be a tie. Let's pick the first model in this case because it's going to be the simpler one (ensembles # come after single configs) best_key = best_keys[0] print() print('***All results:***') for k, v in all_results.items(): print(f'{k}: {v["result"]}') print(f'\n*Best*: {best_key}: {all_results[best_key]["result"]}') print() print('***Determining postprocessing for best model/ensemble***')
default_trained_models = tuple([ {'plans': 'nnUNetPlans', 'configuration': '2d', 'trainer': 'nnUNetTrainer'}, {'plans': 'nnUNetPlans', 'configuration': '3d_fullres', 'trainer': 'nnUNetTrainer'}, {'plans': 'nnUNetPlans', 'configuration': '3d_lowres', 'trainer': 'nnUNetTrainer'}, {'plans': 'nnUNetPlans', 'configuration': '3d_cascade_fullres', 'trainer': 'nnUNetTrainer'}, ]) def filter_available_models(model_dict: Union[List[dict], Tuple[dict, ...]], dataset_name_or_id: Union[str, int]): valid = [] for trained_model in model_dict: plans_manager = PlansManager(join(nnUNet_preprocessed, maybe_convert_to_dataset_name(dataset_name_or_id), trained_model['plans'] + '.json')) # check if configuration exists # 3d_cascade_fullres and 3d_lowres do not exist for each dataset so we allow them to be absent IF they are not # specified in the plans file if trained_model['configuration'] not in plans_manager.available_configurations: print(f"Configuration {trained_model['configuration']} not found in plans {trained_model['plans']}.\n" f"Inferred plans file: {join(nnUNet_preprocessed, maybe_convert_to_dataset_name(dataset_name_or_id), trained_model['plans'] + '.json')}.") continue # check if trained model output folder exists. This is a requirement. No mercy here. expected_output_folder = get_output_folder(dataset_name_or_id, trained_model['trainer'], trained_model['plans'], trained_model['configuration'], fold=None) if not isdir(expected_output_folder): raise RuntimeError(f"Trained model {trained_model} does not have an output folder. " f"Expected: {expected_output_folder}. Please run the training for this model! (don't forget " f"the --npz flag if you want to ensemble multiple configurations)") valid.append(trained_model) return valid def generate_inference_command(dataset_name_or_id: Union[int, str], configuration_name: str, plans_identifier: str = 'nnUNetPlans', trainer_name: str = 'nnUNetTrainer', folds: Union[List[int], Tuple[int, ...]] = (0, 1, 2, 3, 4), folder_with_segs_from_prev_stage: str = None, input_folder: str = 'INPUT_FOLDER', output_folder: str = 'OUTPUT_FOLDER', save_npz: bool = False): fold_str = '' for f in folds: fold_str += f' {f}' predict_command = '' trained_model_folder = get_output_folder(dataset_name_or_id, trainer_name, plans_identifier, configuration_name, fold=None) plans_manager = PlansManager(join(trained_model_folder, 'plans.json')) configuration_manager = plans_manager.get_configuration(configuration_name) if 'previous_stage' in plans_manager.available_configurations: prev_stage = configuration_manager.previous_stage_name predict_command += generate_inference_command(dataset_name_or_id, prev_stage, plans_identifier, trainer_name, folds, None, output_folder='OUTPUT_FOLDER_PREV_STAGE') + '\n' folder_with_segs_from_prev_stage = 'OUTPUT_FOLDER_PREV_STAGE' predict_command = f'nnUNetv2_predict -d {dataset_name_or_id} -i {input_folder} -o {output_folder} -f {fold_str} ' \ f'-tr {trainer_name} -c {configuration_name} -p {plans_identifier}' if folder_with_segs_from_prev_stage is not None: predict_command += f' -prev_stage_predictions {folder_with_segs_from_prev_stage}' if save_npz: predict_command += ' --save_probabilities' return predict_command def find_best_configuration(dataset_name_or_id, allowed_trained_models: Union[List[dict], Tuple[dict, ...]] = default_trained_models, allow_ensembling: bool = True, num_processes: int = default_num_processes, overwrite: bool = True, folds: Union[List[int], Tuple[int, ...]] = (0, 1, 2, 3, 4), strict: bool = False): dataset_name = maybe_convert_to_dataset_name(dataset_name_or_id) all_results = {} allowed_trained_models = filter_available_models(deepcopy(allowed_trained_models), dataset_name_or_id) for m in allowed_trained_models: output_folder = get_output_folder(dataset_name_or_id, m['trainer'], m['plans'], m['configuration'], fold=None) if not isdir(output_folder) and strict: raise RuntimeError(f'{dataset_name}: The output folder of plans {m["plans"]} configuration ' f'{m["configuration"]} is missing. Please train the model (all requested folds!) first!') identifier = os.path.basename(output_folder) merged_output_folder = join(output_folder, f'crossval_results_folds_{folds_tuple_to_string(folds)}') accumulate_cv_results(output_folder, merged_output_folder, folds, num_processes, overwrite) all_results[identifier] = { 'source': merged_output_folder, 'result': load_summary_json(join(merged_output_folder, 'summary.json'))['foreground_mean']['Dice'] } if allow_ensembling: for i in range(len(allowed_trained_models)): for j in range(i + 1, len(allowed_trained_models)): m1, m2 = allowed_trained_models[i], allowed_trained_models[j] output_folder_1 = get_output_folder(dataset_name_or_id, m1['trainer'], m1['plans'], m1['configuration'], fold=None) output_folder_2 = get_output_folder(dataset_name_or_id, m2['trainer'], m2['plans'], m2['configuration'], fold=None) identifier = get_ensemble_name(output_folder_1, output_folder_2, folds) output_folder_ensemble = join(nnUNet_results, dataset_name, 'ensembles', identifier) ensemble_crossvalidations([output_folder_1, output_folder_2], output_folder_ensemble, folds, num_processes, overwrite=overwrite) # evaluate ensembled predictions plans_manager = PlansManager(join(output_folder_1, 'plans.json')) dataset_json = load_json(join(output_folder_1, 'dataset.json')) label_manager = plans_manager.get_label_manager(dataset_json) rw = plans_manager.image_reader_writer_class() compute_metrics_on_folder(join(nnUNet_preprocessed, dataset_name, 'gt_segmentations'), output_folder_ensemble, join(output_folder_ensemble, 'summary.json'), rw, dataset_json['file_ending'], label_manager.foreground_regions if label_manager.has_regions else label_manager.foreground_labels, label_manager.ignore_label, num_processes) all_results[identifier] = \ { 'source': output_folder_ensemble, 'result': load_summary_json(join(output_folder_ensemble, 'summary.json'))['foreground_mean']['Dice'] } # pick best and report inference command best_score = max([i['result'] for i in all_results.values()]) best_keys = [k for k in all_results.keys() if all_results[k]['result'] == best_score] # may never happen but theoretically # there can be a tie. Let's pick the first model in this case because it's going to be the simpler one (ensembles # come after single configs) best_key = best_keys[0] print() print('***All results:***') for k, v in all_results.items(): print(f'{k}: {v["result"]}') print(f'\n*Best*: {best_key}: {all_results[best_key]["result"]}') print() print('***Determining postprocessing for best model/ensemble***')
determine_postprocessing(all_results[best_key]['source'], join(nnUNet_preprocessed, dataset_name, 'gt_segmentations'),
6
2023-12-04 19:43:14+00:00
12k
Inflectra/spira-jira-migration-advanced
convert_jira_to_spira_issue_elements.py
[ { "identifier": "Spira", "path": "spira.py", "snippet": "class Spira:\n def __init__(self, base_url, basic_auth, verify=True):\n if base_url[-1] == \"/\":\n self.base_url = base_url\n else:\n self.base_url = base_url + \"/\"\n\n self.host = urlparse(base_url...
from spira import Spira from utility import convert_jira_markup_to_html from convert_jira_to_spira_issues import ( jira_string_field_to_spira_custom_prop, jira_datetime_field_to_spira_custom_prop, ) import json
9,399
def convert_jira_to_spira_issue_elements( jira_connection_dict, skip_ssl, jira_output_dict, mapping_dict, all_artifacts_in_spira, action, spira: Spira, spira_metadata={}, jira_metadata={}, ): print("Starting conversion") to_validate = open("temp/to_spira.json", "w") validation_dict = {"update_action": "", "artifacts": []} issues = jira_output_dict["issues"] issues_with_outward_links = [] all_outward_links = [] if action == "associations": # For all issues found for issue in issues: # Check if issue has any links if issue["fields"]["issuelinks"]: # If there are links check which of those are outward links for link in issue["fields"]["issuelinks"]: artifact = {"project_id": mapping_dict["spira_product_id"]} if "outwardIssue" in link.keys(): source_id_data = get_artifact_id_data_from_jira_id( issue["key"], all_artifacts_in_spira ) dest_id_data = get_artifact_id_data_from_jira_id( link["outwardIssue"]["key"], all_artifacts_in_spira ) issues_with_outward_links.append(issue["key"]) all_outward_links.append(link["outwardIssue"]["key"]) if source_id_data and dest_id_data: payload = { # "ArtifactLinkId":None, "SourceArtifactId": source_id_data["artifact_id"], "SourceArtifactTypeId": source_id_data[ "artifact_type_id" ], "DestArtifactId": dest_id_data["artifact_id"], "DestArtifactTypeId": dest_id_data["artifact_type_id"], "ArtifactLinkTypeId": 1, # At the moment they will all be set to "relates to" # "CreatorId":None, "Comment": link["type"]["outward"], # "CreationDate":None, # "DestArtifactName":None, # "DestArtifactTypeName":None, # "CreatorName":None, # "ArtifactLinkTypeName":None, # "Guid":None, # "ConcurrencyGuid":None, # "LastUpdateDate":None } validation_dict["update_action"] = "association" artifact["payload"] = payload validation_dict["artifacts"].append(artifact) print( "Found " + str(len(list(set(issues_with_outward_links)))) + " issues with at total of " + str(len(all_outward_links)) + "links" ) elif action == "comments": # For all issues found for issue in issues: # Check if issue has any links if issue["fields"]["comment"]["comments"]: # If there are links check which of those are outward links for comment in issue["fields"]["comment"]["comments"]: artifact = {"project_id": mapping_dict["spira_product_id"]} source_id_data = get_artifact_id_data_from_jira_id( issue["key"], all_artifacts_in_spira ) userinfo = get_user_info_from_email( comment["author"]["emailAddress"], spira_metadata["users"] ) if source_id_data: payload = { # "CommentId":None, ReadOnly "ArtifactId": source_id_data["artifact_id"], # "Guid":None, "UserId": userinfo["spira_id"], # "UserGuid":None, "UserName": userinfo["name"],
def convert_jira_to_spira_issue_elements( jira_connection_dict, skip_ssl, jira_output_dict, mapping_dict, all_artifacts_in_spira, action, spira: Spira, spira_metadata={}, jira_metadata={}, ): print("Starting conversion") to_validate = open("temp/to_spira.json", "w") validation_dict = {"update_action": "", "artifacts": []} issues = jira_output_dict["issues"] issues_with_outward_links = [] all_outward_links = [] if action == "associations": # For all issues found for issue in issues: # Check if issue has any links if issue["fields"]["issuelinks"]: # If there are links check which of those are outward links for link in issue["fields"]["issuelinks"]: artifact = {"project_id": mapping_dict["spira_product_id"]} if "outwardIssue" in link.keys(): source_id_data = get_artifact_id_data_from_jira_id( issue["key"], all_artifacts_in_spira ) dest_id_data = get_artifact_id_data_from_jira_id( link["outwardIssue"]["key"], all_artifacts_in_spira ) issues_with_outward_links.append(issue["key"]) all_outward_links.append(link["outwardIssue"]["key"]) if source_id_data and dest_id_data: payload = { # "ArtifactLinkId":None, "SourceArtifactId": source_id_data["artifact_id"], "SourceArtifactTypeId": source_id_data[ "artifact_type_id" ], "DestArtifactId": dest_id_data["artifact_id"], "DestArtifactTypeId": dest_id_data["artifact_type_id"], "ArtifactLinkTypeId": 1, # At the moment they will all be set to "relates to" # "CreatorId":None, "Comment": link["type"]["outward"], # "CreationDate":None, # "DestArtifactName":None, # "DestArtifactTypeName":None, # "CreatorName":None, # "ArtifactLinkTypeName":None, # "Guid":None, # "ConcurrencyGuid":None, # "LastUpdateDate":None } validation_dict["update_action"] = "association" artifact["payload"] = payload validation_dict["artifacts"].append(artifact) print( "Found " + str(len(list(set(issues_with_outward_links)))) + " issues with at total of " + str(len(all_outward_links)) + "links" ) elif action == "comments": # For all issues found for issue in issues: # Check if issue has any links if issue["fields"]["comment"]["comments"]: # If there are links check which of those are outward links for comment in issue["fields"]["comment"]["comments"]: artifact = {"project_id": mapping_dict["spira_product_id"]} source_id_data = get_artifact_id_data_from_jira_id( issue["key"], all_artifacts_in_spira ) userinfo = get_user_info_from_email( comment["author"]["emailAddress"], spira_metadata["users"] ) if source_id_data: payload = { # "CommentId":None, ReadOnly "ArtifactId": source_id_data["artifact_id"], # "Guid":None, "UserId": userinfo["spira_id"], # "UserGuid":None, "UserName": userinfo["name"],
"Text": convert_jira_markup_to_html(
1
2023-11-28 20:31:27+00:00
12k
Zuricho/chroma_pipeline
chroma/models/graph_classifier.py
[ { "identifier": "validate_XC", "path": "chroma/data/xcs.py", "snippet": "def validate_XCS(all_atom=None, sequence=True):\n def decorator(func):\n def new_func(*args, **kwargs):" }, { "identifier": "basic", "path": "chroma/layers/basic.py", "snippet": "class NoOp(nn.Module):\ncl...
from types import SimpleNamespace from chroma.data.xcs import validate_XC from chroma.layers import basic from chroma.layers.attention import AttentionChainPool from chroma.layers.basic import NodeProduct, NoOp from chroma.layers.graph import MLP, MaskedNorm from chroma.layers.structure import diffusion from chroma.models.graph_design import BackboneEncoderGNN from chroma.utility.model import load_model as utility_load_model import torch import torch.nn as nn
10,581
edge_update=True, edge_mlp_layers=1, edge_mlp_dim=None, skip_connect_input=False, mlp_activation="softplus", graph_criterion="knn", graph_random_min_local=20, use_time_features=True, noise_schedule="log_snr", noise_beta_min=0.2, noise_beta_max=70.0, checkpoint_gradients=False, class_config={}, out_mlp_layers=2, noise_covariance_model="globular", noise_log_snr_range=(-7.0, 13.5), time_feature_type="t", time_log_feature_scaling=0.05, fourier_scale=16.0, zero_grad_fix=False, **kwargs, ): """Initialize GraphBackbone network.""" super().__init__() # Save configuration in kwargs self.kwargs = locals() self.kwargs.pop("self") for key in list(self.kwargs.keys()): if key.startswith("__") and key.endswith("__"): self.kwargs.pop(key) args = SimpleNamespace(**self.kwargs) self.class_config = class_config # Important global options self.dim_nodes = args.dim_nodes self.dim_edges = args.dim_edges self.mlp_activation = args.mlp_activation self.zero_grad_fix = zero_grad_fix if "random_fourier_2mer" in args.edge_features: index = args.edge_features.index("random_fourier_2mer") args.edge_features.pop(index) args.edge_features.append( ( "random_fourier_2mer", { "dim_embedding": args.dim_edges, "trainable": False, "scale": args.fourier_scale, }, ) ) # Encoder GNN process backbone self.encoder = BackboneEncoderGNN( dim_nodes=args.dim_nodes, dim_edges=args.dim_edges, num_neighbors=args.num_neighbors, node_features=args.node_features, edge_features=args.edge_features, num_layers=args.num_layers, node_mlp_layers=args.node_mlp_layers, node_mlp_dim=args.node_mlp_dim, edge_update=args.edge_update, edge_mlp_layers=args.edge_mlp_layers, edge_mlp_dim=args.edge_mlp_dim, mlp_activation=args.mlp_activation, dropout=args.dropout, skip_connect_input=args.skip_connect_input, graph_criterion=args.graph_criterion, graph_random_min_local=args.graph_random_min_local, checkpoint_gradients=checkpoint_gradients, ) self.time_feature_type = args.time_feature_type self.time_log_feature_scaling = time_log_feature_scaling self.use_time_features = use_time_features if self.use_time_features: self.time_features = basic.FourierFeaturization( d_input=1, d_model=dim_nodes, trainable=False, scale=16.0 ) self.sequence_embedding = nn.Embedding(20, dim_nodes) self.noise_perturb = diffusion.DiffusionChainCov( noise_schedule=args.noise_schedule, beta_min=args.noise_beta_min, beta_max=args.noise_beta_max, log_snr_range=args.noise_log_snr_range, covariance_model=args.noise_covariance_model, ) self._init_heads(class_config, dim_nodes, out_mlp_layers, dropout) self.condition_sequence_frequency = 0.3 def _init_heads(self, class_config, dim_nodes, out_mlp_layers, dropout): self.heads = {"chain": {}, "first_order": {}, "second_order": {}, "complex": {}} for label, config in class_config.items(): group = config["level"] if label == "is_interface" or label == "contact": dim_out = 1 else: dim_out = len(config["tokens"]) if group == "chain": pool = AttentionChainPool(8, dim_nodes) elif group == "complex": raise NotImplementedError elif group == "second_order": pool = NoOp() else: pool = NoOp() if group != "second_order": if self.zero_grad_fix: node_norm_layer = MaskedNorm( dim=1, num_features=dim_nodes, affine=True, norm="layer" )
# Copyright Generate Biomedicines, Inc. # # 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. """Models for generating protein sequence and side chain conformations given backbones. These can be used for sequence design and packing. """ class GraphClassifier(nn.Module): """Graph-based protein classification Args: See documention of `structure.protein_graph.ProteinFeatureGraph`, and `graph.GraphNN` for more details. Inputs: X (Tensor): Backbone coordinates with shape `(num_batch, num_residues, num_atoms, 3)`. C (LongTensor): Chain map with shape `(num_batch, num_residues)`. O (Tensor) (optional): One-hot sequence tensor of shape `(num_batch, num_residues)` Outputs: node_h (Tensor): residue-based representations that can be used to project various classification predictions """ def __init__( self, dim_nodes=128, dim_edges=128, num_neighbors=30, node_features=(("internal_coords", {"log_lengths": True}),), edge_features=["random_fourier_2mer", "orientations_2mer", "distances_chain"], num_layers=3, dropout=0.1, node_mlp_layers=1, node_mlp_dim=None, edge_update=True, edge_mlp_layers=1, edge_mlp_dim=None, skip_connect_input=False, mlp_activation="softplus", graph_criterion="knn", graph_random_min_local=20, use_time_features=True, noise_schedule="log_snr", noise_beta_min=0.2, noise_beta_max=70.0, checkpoint_gradients=False, class_config={}, out_mlp_layers=2, noise_covariance_model="globular", noise_log_snr_range=(-7.0, 13.5), time_feature_type="t", time_log_feature_scaling=0.05, fourier_scale=16.0, zero_grad_fix=False, **kwargs, ): """Initialize GraphBackbone network.""" super().__init__() # Save configuration in kwargs self.kwargs = locals() self.kwargs.pop("self") for key in list(self.kwargs.keys()): if key.startswith("__") and key.endswith("__"): self.kwargs.pop(key) args = SimpleNamespace(**self.kwargs) self.class_config = class_config # Important global options self.dim_nodes = args.dim_nodes self.dim_edges = args.dim_edges self.mlp_activation = args.mlp_activation self.zero_grad_fix = zero_grad_fix if "random_fourier_2mer" in args.edge_features: index = args.edge_features.index("random_fourier_2mer") args.edge_features.pop(index) args.edge_features.append( ( "random_fourier_2mer", { "dim_embedding": args.dim_edges, "trainable": False, "scale": args.fourier_scale, }, ) ) # Encoder GNN process backbone self.encoder = BackboneEncoderGNN( dim_nodes=args.dim_nodes, dim_edges=args.dim_edges, num_neighbors=args.num_neighbors, node_features=args.node_features, edge_features=args.edge_features, num_layers=args.num_layers, node_mlp_layers=args.node_mlp_layers, node_mlp_dim=args.node_mlp_dim, edge_update=args.edge_update, edge_mlp_layers=args.edge_mlp_layers, edge_mlp_dim=args.edge_mlp_dim, mlp_activation=args.mlp_activation, dropout=args.dropout, skip_connect_input=args.skip_connect_input, graph_criterion=args.graph_criterion, graph_random_min_local=args.graph_random_min_local, checkpoint_gradients=checkpoint_gradients, ) self.time_feature_type = args.time_feature_type self.time_log_feature_scaling = time_log_feature_scaling self.use_time_features = use_time_features if self.use_time_features: self.time_features = basic.FourierFeaturization( d_input=1, d_model=dim_nodes, trainable=False, scale=16.0 ) self.sequence_embedding = nn.Embedding(20, dim_nodes) self.noise_perturb = diffusion.DiffusionChainCov( noise_schedule=args.noise_schedule, beta_min=args.noise_beta_min, beta_max=args.noise_beta_max, log_snr_range=args.noise_log_snr_range, covariance_model=args.noise_covariance_model, ) self._init_heads(class_config, dim_nodes, out_mlp_layers, dropout) self.condition_sequence_frequency = 0.3 def _init_heads(self, class_config, dim_nodes, out_mlp_layers, dropout): self.heads = {"chain": {}, "first_order": {}, "second_order": {}, "complex": {}} for label, config in class_config.items(): group = config["level"] if label == "is_interface" or label == "contact": dim_out = 1 else: dim_out = len(config["tokens"]) if group == "chain": pool = AttentionChainPool(8, dim_nodes) elif group == "complex": raise NotImplementedError elif group == "second_order": pool = NoOp() else: pool = NoOp() if group != "second_order": if self.zero_grad_fix: node_norm_layer = MaskedNorm( dim=1, num_features=dim_nodes, affine=True, norm="layer" )
mlp = MLP(
5
2023-11-28 00:09:40+00:00
12k
RWTH-EBC/vclibpy
vclibpy/flowsheets/vapor_injection.py
[ { "identifier": "BaseCycle", "path": "vclibpy/flowsheets/base.py", "snippet": "class BaseCycle:\n \"\"\"\n Base class for a heat pump. More complex systems may inherit from this class\n All HP have a compressor, two HE and a source and sink.\n Therefore, the parameters defined here are gener...
import abc import logging import numpy as np from copy import deepcopy from vclibpy.flowsheets import BaseCycle from vclibpy.datamodels import Inputs, FlowsheetState from vclibpy.components.compressors import Compressor from vclibpy.components.expansion_valves import ExpansionValve from vclibpy.media import ThermodynamicState
8,798
logger = logging.getLogger(__name__) class BaseVaporInjection(BaseCycle, abc.ABC): """ Partial cycle with vapor injection, using two separated compressors and expansion valves. Notes ----- See parent docstring for info on further assumptions and parameters. """ flowsheet_name = "VaporInjectionPhaseSeparator" def __init__( self, high_pressure_compressor: Compressor, low_pressure_compressor: Compressor,
logger = logging.getLogger(__name__) class BaseVaporInjection(BaseCycle, abc.ABC): """ Partial cycle with vapor injection, using two separated compressors and expansion valves. Notes ----- See parent docstring for info on further assumptions and parameters. """ flowsheet_name = "VaporInjectionPhaseSeparator" def __init__( self, high_pressure_compressor: Compressor, low_pressure_compressor: Compressor,
high_pressure_valve: ExpansionValve,
4
2023-11-30 12:54:59+00:00
12k
BiQiWHU/CMFormer
train_net.py
[ { "identifier": "add_maskformer2_config", "path": "mask2former/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...
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 from detectron2.engine import ( DefaultTrainer, default_argument_parser, default_setup, launch, ) from detectron2.evaluation import ( CityscapesInstanceEvaluator, CityscapesSemSegEvaluator, COCOEvaluator, COCOPanopticEvaluator, DatasetEvaluators, LVISEvaluator, SemSegEvaluator, verify_results, ) 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 mask2former import ( COCOInstanceNewBaselineDatasetMapper, COCOPanopticNewBaselineDatasetMapper, InstanceSegEvaluator, MaskFormerInstanceDatasetMapper, MaskFormerPanopticDatasetMapper, MaskFormerSemanticDatasetMapper, SemanticSegmentorWithTTA, add_maskformer2_config, ) import warnings import copy import itertools import logging import os import torch import detectron2.utils.comm as comm
10,728
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ MaskFormer 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 os.environ['DETECTRON2_DATASETS'] = 'E:/DGtask/datasets' # MaskFormer class Trainer(DefaultTrainer): """ Extension of the Trainer class adapted to MaskFormer. """ @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") evaluator_list = [] evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type # semantic segmentation if evaluator_type in ["sem_seg", "ade20k_panoptic_seg"]: evaluator_list.append( SemSegEvaluator( dataset_name, distributed=True, output_dir=output_folder, ) ) # instance segmentation if evaluator_type == "coco": evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) # panoptic segmentation if evaluator_type in [ "coco_panoptic_seg", "ade20k_panoptic_seg", "cityscapes_panoptic_seg", "mapillary_vistas_panoptic_seg", ]: if cfg.MODEL.MASK_FORMER.TEST.PANOPTIC_ON: evaluator_list.append(COCOPanopticEvaluator(dataset_name, output_folder)) # COCO if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Mapillary Vistas if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON:
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ MaskFormer 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 os.environ['DETECTRON2_DATASETS'] = 'E:/DGtask/datasets' # MaskFormer class Trainer(DefaultTrainer): """ Extension of the Trainer class adapted to MaskFormer. """ @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") evaluator_list = [] evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type # semantic segmentation if evaluator_type in ["sem_seg", "ade20k_panoptic_seg"]: evaluator_list.append( SemSegEvaluator( dataset_name, distributed=True, output_dir=output_folder, ) ) # instance segmentation if evaluator_type == "coco": evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) # panoptic segmentation if evaluator_type in [ "coco_panoptic_seg", "ade20k_panoptic_seg", "cityscapes_panoptic_seg", "mapillary_vistas_panoptic_seg", ]: if cfg.MODEL.MASK_FORMER.TEST.PANOPTIC_ON: evaluator_list.append(COCOPanopticEvaluator(dataset_name, output_folder)) # COCO if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Mapillary Vistas if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON:
evaluator_list.append(InstanceSegEvaluator(dataset_name, output_dir=output_folder))
7
2023-11-29 15:26:53+00:00
12k
soumik-kanad/diffssl
finetune.py
[ { "identifier": "DiffSSLModelFeedbackFusion", "path": "ssl_diff/ssl_model_feedback_fusion.py", "snippet": "class DiffSSLModelFeedbackFusion(nn.Module):\n\n \"\"\" SSL model with feedback loop between the decoder features of the UNet and the \n encoder features of the UNet\n \"\"\"\n def ...
import argparse import torch import numpy as np import sys import os import glob import torch.distributed as dist import wandb from torch.nn.parallel import DistributedDataParallel as DDP from tqdm import tqdm from ssl_diff import DiffSSLModelFeedbackFusion from ssl_diff import AttentionFusion, Head from ssl_diff import DM_FEAT_DIM_DICT,DM_FEAT_SIZE_DICT from guided_diffusion.image_datasets import load_data from guided_diffusion import dist_util #, logger from guided_diffusion.image_datasets import load_data from guided_diffusion.resample import create_named_schedule_sampler from guided_diffusion.script_util import ( model_and_diffusion_defaults, create_model_and_diffusion, args_to_dict, add_dict_to_argparser, )
7,868
targets = extra["y"].to(dist_util.dev()) output = model(imgs, args.t_list) pred = torch.argmax(output, dim=1) # print("Pred:", pred) # print("Targets:", targets) num_correct += (pred == targets).sum() total += pred.shape[0] # print(dist_util.get_rank(), total, num_correct) # print("Acc now:", num_correct/total) all_num_correct = sync_tensor_across_gpus(torch.tensor(num_correct).to(dist_util.dev()).reshape(1)) all_total = sync_tensor_across_gpus(torch.tensor(total).to(dist_util.dev()).reshape(1)) if dist_util.is_main_process(): num_correct = all_num_correct.sum().item() total = all_total.sum().item() if args.use_wandb: wandb.log({f"Accuracy/{split}": num_correct / total, "epoch": epoch}) print(f'{split} accuracy: {num_correct / total}, Num correct: {num_correct}, Total: {total}') def create_argparser(): defaults = dict( # dataset data_dir="", val_data_dir="", num_classes=50, # training setting schedule_sampler="uniform", weight_decay=0.0, lr_anneal_steps=0, epochs = 50, lr=1e-2, # use 1e-2 for freeze, 1e-3 for finetune batch_size=16, microbatch=-1, # -1 disables microbatches ema_rate="0.9999", # comma-separated list of EMA values use_fp16=False, fp16_scale_growth=1e-3, mode='freeze', # "freeze" or "finetune" for backbone # feedback&fusion head_type="attention", # "linear" or "attention" head_arc='', #can be "h1_h2_h3" to use mlp head(when head_type=="linear") norm_type="", # ["batch", "layer", ""], pre_pool_size=16, # pooling size before attention or linear head fusion_arc="", # architecture of attention head feedback_arch='C_B_R', # architecture for feedback network(Conv-BatchNorm-ReLU) checkpoint_path='', # encoder path # add distributed training args dist_url='env://', dist_backend='nccl', world_size=1, # log output_dir='./output', resume_checkpoint="", log_interval=10, save_interval=10000, eval_interval=5, only_eval=False, wandb_run_name=None, use_wandb=True, ) defaults.update(model_and_diffusion_defaults()) parser = argparse.ArgumentParser() parser.add_argument("--local-rank", type=int, default=0, help="For distributed training.") parser.add_argument("--t_list", nargs='+', required=True, type=int, help="list of noise step t to use") parser.add_argument("--first_fw_b_list", nargs='+', required=True, type=int, help="list of feature block to use from first forward(-1 if not used)") parser.add_argument("--second_fw_b_list", nargs='+', required=True, type=int, help="list of feature block to use from second forward(=feedback)(-1 if not used)") parser.add_argument("--feedback_b_list", nargs='+', required=True, type=int, help="list of feature block for feedback(-1 if not used)") add_dict_to_argparser(parser, defaults) return parser def main(): print('Reading args') args = create_argparser().parse_args() args.device = 'cuda' if args.first_fw_b_list[0] == -1: args.first_fw_b_list = [] if args.second_fw_b_list[0] == -1: args.second_fw_b_list = [] use_feedback = len(args.second_fw_b_list) > 0 if args.feedback_b_list[0] == -1: args.feedback_b_list = [] assert use_feedback==False, "blocks for feedback are not specified" if args.head_type == "linear": assert len(args.first_fw_b_list) == 1 and len(args.t_list) == 1 and len(args.second_fw_b_list) == 0, "linear head cannot be used for feedback/fusion" print('Setting up dist') # Setup CUDA, GPU & distributed training args.num_gpus = int(os.environ['WORLD_SIZE']) if 'WORLD_SIZE' in os.environ else 1 args.distributed = args.num_gpus > 1 # args.distributed = True args.device = torch.device(args.device) if args.distributed: args.rank = int(os.environ["RANK"]) args.world_size = int(os.environ['WORLD_SIZE']) args.local_rank = int(os.environ['LOCAL_RANK']) print("") print("Init distributed training on local rank {} ({}), world size {}".format(args.local_rank, int(os.environ["LOCAL_RANK"]), args.num_gpus)) torch.cuda.set_device(args.local_rank) torch.distributed.init_process_group( backend='nccl', init_method=args.dist_url, world_size=args.world_size, rank=args.rank ) local_rank = int(os.environ["LOCAL_RANK"]) args.device = torch.device("cuda", local_rank) torch.distributed.barrier() if dist_util.is_main_process(): print(f'args: {args}') exist_ok = len(glob.glob(os.path.join(args.output_dir, "*"))) == 0 or (args.output_dir == os.path.dirname(args.resume_checkpoint)) or (os.path.basename(args.output_dir) == "debug") os.makedirs(args.output_dir, exist_ok=exist_ok) print('Creating model') if args.head_type =="linear":
def train(model, lr, e, bs, train_dataloader, test_dataloader, args, checkpoint_dict=None): # optimizer = torch.optim.SGD(model.parameters(), lr=lr) # apply optimizer only on the head and feedback layers use_feedback = len(args.second_fw_b_list) > 0 if args.distributed: optimized_params_lst = [{'params': model.module.head.parameters()}] if use_feedback: optimized_params_lst.append({'params': model.module.feedback_layers.parameters()}) if args.mode == 'update': optimized_params_lst.append({'params': model.module.update_blocks.parameters()}) if args.mode == 'add_fpn' or args.mode == 'mult_fpn': optimized_params_lst.append({'params': model.module.fpn_blocks.parameters()}) if args.mode == "finetune": optimized_params_lst.append({'params': model.module.encoder.parameters()}) else: optimized_params_lst = [{'params': model.head.parameters()}] if use_feedback: optimized_params_lst.append({'params': model.feedback_layers.parameters()}) if args.mode == 'update': optimized_params_lst.append({'params': model.update_blocks.parameters()}) if args.mode == 'add_fpn' or args.mode == 'mult_fpn': optimized_params_lst.append({'params': model.fpn_blocks.parameters()}) if args.mode == "finetune": optimized_params_lst.append({'params': model.encoder.parameters()}) optimizer = torch.optim.SGD(optimized_params_lst, lr=lr) loss_fn = torch.nn.CrossEntropyLoss() scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 7, 0.1) if checkpoint_dict is not None: print(f"Loading model, optimizer, and scheduler from checkpoint from!") model.module.head.load_state_dict(checkpoint_dict['model_head']) if use_feedback: print("Loading feedback layers") model.module.feedback_layers.load_state_dict(checkpoint_dict['model_feedback']) if args.mode == 'update': print("Loading update blocks") model.module.update_blocks.load_state_dict(checkpoint_dict['model_update']) elif args.mode == 'add_fpn' or args.mode == 'mult_fpn': print("Loading fpn blocks") model.module.fpn_blocks.load_state_dict(checkpoint_dict['model_fpn']) optimizer.load_state_dict(checkpoint_dict['optimizer']) scheduler.load_state_dict(checkpoint_dict['scheduler']) start_epoch = checkpoint_dict['epoch'] else: start_epoch = 0 losses = [] model.train() batch_num = 0 for i in range(start_epoch, e): for batch in (tqdm(train_dataloader, total=len(train_dataloader))): # # measure execution time in pytorch # start = torch.cuda.Event(enable_timing=True) # end = torch.cuda.Event(enable_timing=True) # start.record() imgs, extra = batch #next(train_dataloader) imgs = imgs.to(dist_util.dev()) targets = extra["y"].to(dist_util.dev()) # end.record() # # Waits for everything to finish running # torch.cuda.synchronize() # print("Inputs: ", start.elapsed_time(end)) # start.record() output = model(imgs, args.t_list) # end.record() # # Waits for everything to finish running # torch.cuda.synchronize() # print("Forward: ", start.elapsed_time(end)) # start.record() #calculate loss loss = loss_fn(output, targets) # end.record() # # Waits for everything to finish running # torch.cuda.synchronize() # print("Loss: ", start.elapsed_time(end)) #backprop # start.record() optimizer.zero_grad() loss.backward() # store 'module.encoder.time_embed.0.bias' weight # import pdb;x pdb.set_trace() # print(old - model.module.encoder.time_embed[0].bias.clone().detach()) # old = model.module.encoder.time_embed[0].bias.clone().detach() optimizer.step() # end.record() # # Waits for everything to finish running # torch.cuda.synchronize() # print("Backward: ", start.elapsed_time(end)) # start.record() if len(losses) == 100: losses = losses[1:] losses.append(loss.item()) if dist_util.is_main_process(): if (batch_num + 1) % 100 == 0: print(f'Epoch: {i+1}/{e}, Batch Num: {batch_num+1}: Loss: {np.mean(losses):0.6f}', flush=True) if args.use_wandb: wandb.log({"Loss/train": np.mean(losses), "epoch": (batch_num+1) / len(train_dataloader)}) batch_num += 1 # end.record() # # Waits for everything to finish running # torch.cuda.synchronize() # print("Logging: ", start.elapsed_time(end)) scheduler.step() if (i + 1) % args.eval_interval == 0: test(model, test_dataloader, args, 'Val (Test)', i+1) # Save checkpoint every epoch if dist_util.is_main_process(): save_file = os.path.join(args.output_dir, f'epoch_latest.pth') print(f"Saving checkpoint @ Epoch: {i+1} to {save_file}") save_dict ={ 'optimizer': optimizer.state_dict(), 'scheduler': scheduler.state_dict(), 'epoch': i+1 } save_dict['model_head'] = model.module.head.state_dict() if use_feedback: save_dict['model_feedback'] = model.module.feedback_layers.state_dict() if args.mode == 'update': save_dict['model_update'] = model.module.update_blocks.state_dict() elif args.mode == 'add_fpn' or args.mode == 'mult_fpn': save_dict['model_fpn'] = model.module.fpn_blocks.state_dict() # torch.save(save_dict, save_file) torch.save(save_dict, os.path.join(args.output_dir, f'latest.pth')) # https://discuss.pytorch.org/t/ddp-evaluation-gather-output-loss-and-stuff-how-to/130593/2 def sync_tensor_across_gpus(t): # t needs to have dim 0 for torch.cat below. # if not, you need to prepare it. if t is None: return None group = dist.group.WORLD group_size = torch.distributed.get_world_size(group) gather_t_tensor = [torch.zeros_like(t) for _ in range(group_size)] dist.all_gather(gather_t_tensor, t) # this works with nccl backend when tensors need to be on gpu. # for gloo and mpi backends, tensors need to be on cpu. also this works single machine with # multiple gpus. for multiple nodes, you should use dist.all_gather_multigpu. both have the # same definition... see [here](https://pytorch.org/docs/stable/distributed.html). # somewhere in the same page, it was mentioned that dist.all_gather_multigpu is more for # multi-nodes. still dont see the benefit of all_gather_multigpu. the provided working case in # the doc is vague... return torch.cat(gather_t_tensor, dim=0) def test(model, dataloader, args, split='Test', epoch=0): model.eval() num_correct = 0 total = 0 num_val_batches = len(dataloader) with torch.no_grad(): for batch in tqdm(dataloader, total=num_val_batches): imgs, extra = batch imgs = imgs.to(dist_util.dev()) targets = extra["y"].to(dist_util.dev()) output = model(imgs, args.t_list) pred = torch.argmax(output, dim=1) # print("Pred:", pred) # print("Targets:", targets) num_correct += (pred == targets).sum() total += pred.shape[0] # print(dist_util.get_rank(), total, num_correct) # print("Acc now:", num_correct/total) all_num_correct = sync_tensor_across_gpus(torch.tensor(num_correct).to(dist_util.dev()).reshape(1)) all_total = sync_tensor_across_gpus(torch.tensor(total).to(dist_util.dev()).reshape(1)) if dist_util.is_main_process(): num_correct = all_num_correct.sum().item() total = all_total.sum().item() if args.use_wandb: wandb.log({f"Accuracy/{split}": num_correct / total, "epoch": epoch}) print(f'{split} accuracy: {num_correct / total}, Num correct: {num_correct}, Total: {total}') def create_argparser(): defaults = dict( # dataset data_dir="", val_data_dir="", num_classes=50, # training setting schedule_sampler="uniform", weight_decay=0.0, lr_anneal_steps=0, epochs = 50, lr=1e-2, # use 1e-2 for freeze, 1e-3 for finetune batch_size=16, microbatch=-1, # -1 disables microbatches ema_rate="0.9999", # comma-separated list of EMA values use_fp16=False, fp16_scale_growth=1e-3, mode='freeze', # "freeze" or "finetune" for backbone # feedback&fusion head_type="attention", # "linear" or "attention" head_arc='', #can be "h1_h2_h3" to use mlp head(when head_type=="linear") norm_type="", # ["batch", "layer", ""], pre_pool_size=16, # pooling size before attention or linear head fusion_arc="", # architecture of attention head feedback_arch='C_B_R', # architecture for feedback network(Conv-BatchNorm-ReLU) checkpoint_path='', # encoder path # add distributed training args dist_url='env://', dist_backend='nccl', world_size=1, # log output_dir='./output', resume_checkpoint="", log_interval=10, save_interval=10000, eval_interval=5, only_eval=False, wandb_run_name=None, use_wandb=True, ) defaults.update(model_and_diffusion_defaults()) parser = argparse.ArgumentParser() parser.add_argument("--local-rank", type=int, default=0, help="For distributed training.") parser.add_argument("--t_list", nargs='+', required=True, type=int, help="list of noise step t to use") parser.add_argument("--first_fw_b_list", nargs='+', required=True, type=int, help="list of feature block to use from first forward(-1 if not used)") parser.add_argument("--second_fw_b_list", nargs='+', required=True, type=int, help="list of feature block to use from second forward(=feedback)(-1 if not used)") parser.add_argument("--feedback_b_list", nargs='+', required=True, type=int, help="list of feature block for feedback(-1 if not used)") add_dict_to_argparser(parser, defaults) return parser def main(): print('Reading args') args = create_argparser().parse_args() args.device = 'cuda' if args.first_fw_b_list[0] == -1: args.first_fw_b_list = [] if args.second_fw_b_list[0] == -1: args.second_fw_b_list = [] use_feedback = len(args.second_fw_b_list) > 0 if args.feedback_b_list[0] == -1: args.feedback_b_list = [] assert use_feedback==False, "blocks for feedback are not specified" if args.head_type == "linear": assert len(args.first_fw_b_list) == 1 and len(args.t_list) == 1 and len(args.second_fw_b_list) == 0, "linear head cannot be used for feedback/fusion" print('Setting up dist') # Setup CUDA, GPU & distributed training args.num_gpus = int(os.environ['WORLD_SIZE']) if 'WORLD_SIZE' in os.environ else 1 args.distributed = args.num_gpus > 1 # args.distributed = True args.device = torch.device(args.device) if args.distributed: args.rank = int(os.environ["RANK"]) args.world_size = int(os.environ['WORLD_SIZE']) args.local_rank = int(os.environ['LOCAL_RANK']) print("") print("Init distributed training on local rank {} ({}), world size {}".format(args.local_rank, int(os.environ["LOCAL_RANK"]), args.num_gpus)) torch.cuda.set_device(args.local_rank) torch.distributed.init_process_group( backend='nccl', init_method=args.dist_url, world_size=args.world_size, rank=args.rank ) local_rank = int(os.environ["LOCAL_RANK"]) args.device = torch.device("cuda", local_rank) torch.distributed.barrier() if dist_util.is_main_process(): print(f'args: {args}') exist_ok = len(glob.glob(os.path.join(args.output_dir, "*"))) == 0 or (args.output_dir == os.path.dirname(args.resume_checkpoint)) or (os.path.basename(args.output_dir) == "debug") os.makedirs(args.output_dir, exist_ok=exist_ok) print('Creating model') if args.head_type =="linear":
head = Head(args, DM_FEAT_DIM_DICT,DM_FEAT_SIZE_DICT)
1
2023-11-29 17:46:18+00:00
12k
Uli-Z/autoPDFtagger
autoPDFtagger/AIAgents_OpenAI_pdf.py
[ { "identifier": "AIAgent_OpenAI", "path": "autoPDFtagger/AIAgents.py", "snippet": "class AIAgent_OpenAI(AIAgent):\n def __init__(self, \n model=\"gpt-3.5-turbo-1106\", \n system_message=\"You are a helpful assistant\"):\n super().__init__()\n \n se...
from autoPDFtagger.AIAgents import AIAgent_OpenAI from autoPDFtagger.AIAgents import OpenAI_model_pricelist from autoPDFtagger.config import config from autoPDFtagger.PDFDocument import PDFDocument import logging import json import pprint import re import copy import tiktoken
10,135
try: pdf_document.set_from_json(response) except Exception as e: logging.error("API-Call for image analysis failed") logging.error(e) if pdf_document.has_sufficient_information(): logging.info("Document information sufficient. Proceeding with next document.") return pdf_document else: logging.info("Still lacking information, looking for more images") logging.info("No more images found.") return pdf_document def process_images_by_page(self, pdf_document: PDFDocument): for page in pdf_document.pages: logging.debug(f"Checking Page {page['page_number']} looking for largest image") # Skip page if no images are present if 'max_img_xref' not in page or not page['max_img_xref']: logging.debug("Page not analyzed: (no images)") continue # Get the largest image of the site (assuming it to be the scan-image) image_base64 = pdf_document.get_png_image_base64_by_xref(page['max_img_xref']) # Send it to GPT logging.info("Asking AI for analyzing scanned page") response = self.send_image_request(pdf_document, [image_base64]) try: pdf_document.set_from_json(response) except Exception as e: logging.error("API-Call for image analysis failed") logging.error(e) # Only proceed if the information about the document is still insufficient if pdf_document.has_sufficient_information(): logging.info("Document information sufficient, proceeding.") return pdf_document else: logging.info("Still lacking information, looking for more pages") logging.info("No more pages available.") return pdf_document # TEXT-Analysis class AIAgent_OpenAI_pdf_text_analysis(AIAgent_OpenAI): def __init__(self): system_message = ( "You are a helpful assistant analyzing OCR outputs. It's important " "to remember that these outputs may represent only a part of the document. " "Provide the following information:\n" "1. Creation date of the document.\n" "2. A short title of 3-4 words.\n" "3. A meaningful summary of 3-4 sentences.\n" "4. Creator/Issuer\n" "5. Suitable keywords/tags related to the content.\n" "6. Rate the importance of the document on a scale from 0 (unimportant) to " "10 (vital).\n" "7. Rate your confidence for each of the above points on a scale " "from 0 (no information, text not readable) over 5 (possibly right, but only " "few hints about the content of the whole document) to 10 (very sure). " "You always answer in {LANGUAGE} language. For gathering information, " "you use the given filename, pathname and OCR-analyzed text. " "If you are seeing a blank document, your title-confidence is alway 0." "You always answer in a specified JSON-Format like in this example:\n" "{\n" " 'summary': '[summary]',\n" " 'summary_confidence': [number],\n" " 'title': '[title]',\n" " 'title_confidence': [number],\n" " 'creation_date': '[Date YY-mm-dd]',\n" " 'creation_date_confidence': [number],\n" " 'creator': '[creator name]',\n" " 'creator_confidence': [number],\n" " 'tags': ['[tag 1]', '[tag 2]', ...],\n" " 'tags_confidence': [[confidence tag 1], [confidence tag 2]],\n" " 'importance': [number],\n" " 'importance_confidence': [number]\n" "}" ) # Parent constructor super().__init__(model="gpt-4-1106-preview", system_message=system_message) self.response_format="json_object" # Main working function to get info about a PDFDocument by # sending a GPT-API-Request def analyze_text(self, pdf_document: PDFDocument): # Step 1: Analyze the number of potentially meaningful words # to decide which model to use # GPT-3.5 is good enough for long texts and much cheaper. # Especially in shorter texts, GPT-4 gives much more high-quality answers word_count = len([word for word in re.split(r'\W+', pdf_document.get_pdf_text()) if len(word) >= 3]) model_choice = "gpt-3.5-turbo-1106" if word_count > 100 else "gpt-4-1106-preview" #model_choice = "gpt-4-1106-preview" # for test purposes logging.debug("Opting for " + model_choice) self.set_model(model_choice) message = ("Analyze following OCR-Output. Try to imagine as many valuable keywords and categories as possible. " "Imagine additional keywords thinking of a wider context and possible categories in an archive system. " f"Use {LANGUAGE} Language. Answer in the given pattern (JSON): " + pdf_document.get_short_description() ) # in case of very long text, we have to shorten it depending on # the specific token-limit of the actual model # Optimize request data # Convert message-list to str request_test_str = pprint.pformat(self.messages) # estimate token-number for request num_tokens = num_tokens_from_string(request_test_str) # estimate 500 Tokens for answer tokens_required = num_tokens + 500 # max tokens of the actual model stored in price list table
# Here, the task-specific AI agents for text analysis, # image analysis, and keyword/tag analysis are specified. # The general logic for API communication with OpenAI is # established in the parent classes AIAgent and AIAgent_OpenAI # (see AIAgents.py). api_key = config['OPENAI-API']['API-Key'] LANGUAGE = config['DEFAULT']['language'] # IMAGE-Analysis class AIAgent_OpenAI_pdf_image_analysis(AIAgent_OpenAI): def __init__(self): system_message = f""" You are a helpful assistant analyzing images inside of documents. Based on the shown images, provide the following information:\n 1. Creation date of the document.\n 2. A short title of 3-4 words.\n 3. A short summary of 3-4 sentences.\n 4. Creator/Issuer\n 5. Suitable keywords/tags related to the content.\n 6. Rate the importance of the document on a scale from 0 (unimportant) to 10 (vital).\n 7. Rate your confidence for each of the above points on a scale from 0 (no information) over 5 (possibly right, but only few hints) to 10 (very sure). You always answer in {LANGUAGE} language. For gathering information, you use the given filename, pathname and ocr-analyzed text. You always answer in a specified JSON-Format which is given in the question. """ # calling parent class constructor super().__init__(model="gpt-4-vision-preview", system_message=system_message) self.response_format="json_object" # Main function of this class: Try to extract relevant metadata # out of a PDFDocument (pdf_document) by analyzing their images # and return result as a json-string def analyze_images(self, pdf_document: PDFDocument): pdf_document.analyze_document_images() # Prevent modifying the original document working_doc = copy.deepcopy(pdf_document) # For the general requirement of this function, # I have different approaches, which vary depending # on the structure of the document. In the case of a # scanned document, at least the first page should be # completely analyzed, as it is where most of the relevant # information (title, summary, date) can be expected. # Subsequent pages should only be examined for cost reasons # if the collected information is insufficient. This approach # is implemented in the function process_images_by_page. # In cases where the document is not a scanned one, but an # originally digital document, images contained within it # (of a certain minimum size) can also hold valuable information. # These images can be analyzed in blocks (currently 3 at a time) # by GPT. We start with the largest images. At least one block # will be analyzed. Additional blocks only if the quality of the # metadata is not yet sufficient (similar to process_images_by_pages). # This approach is specified by the function process_images_by_size. # No scanned document if pdf_document.image_coverage < 100: logging.info("Analyzing smaller Images") # Wir sortieren alle Bilder mit einer bestimmten Mindestgröße und # fangen von oben an, diese in 5er Gruppen in einzelnen Anfragen # an GPT-Vision zu schicken, so lange, bis entweder alle Bilder # analysiert sind oder has_sufficient_information true ergibt working_doc = self.process_images_by_size(working_doc) # Scanned document if pdf_document.image_coverage >= 100: # Hier alle Seiten als Bild GTP-Vision vorlegen, welche weniger als 100 Wörter enthalten logging.info("Recognizing scanned document") working_doc = self.process_images_by_page(working_doc) return working_doc.to_api_json() # A generic function to ask GPT to analyze a list of Images (list_imgaes_base64) # in context of information of a PDFDocument (document) # The decision regarding the selection of images and their # extraction from the document is made separately, therefore # these must be passed as additional parameters. def send_image_request(self, document: PDFDocument, list_images_base64): logging.info("Asking GPT-Vision for analysis of " + str(len(list_images_base64)) + " Images found in " + document.get_absolute_path()) user_message = ( "Analyze following Images which are found in a document. " "Please extend the existing information by keeping their JSON-Format: " + document.to_api_json() + " Try to imagine as many valuable keywords and categories as possible. " "Imagine additional keywords thinking of a wider context and possible categories in an archive system. " "Answer in JSON-Format corresponding to given input." ) message_content = [ { "type": "text", "text": user_message }] # Add individual images to the message for base64_image in list_images_base64: image_content = { "type": "image_url", "image_url": { "url": f"data:image/png;base64,{base64_image}" } } message_content.append(image_content) self.add_message(message_content) try: response = super().send_request(temperature=0.2, response_format = None, ) return response except Exception as e: logging.error("API-Call failed") logging.error(e) return None def process_images_by_size(self, pdf_document: PDFDocument): # Create a list of all images from each page all_images = [image for page in pdf_document.images for image in page] # Sort images by pixel count (width x height) sorted_images = sorted(all_images, key=lambda img: img["original_width"] * img["original_height"], reverse=True) # Filter out images smaller than 90000 pixels (e.g., less than 300x300) relevant_images = [img for img in sorted_images if img["original_width"] * img["original_height"] >= 90000] # Process images in groups of 3 for i in range(0, len(relevant_images), 3): group = relevant_images[i:i + 3] base64_group = [] for image in group: base64_group.append(pdf_document.get_png_image_base64_by_xref(image['xref'])) # Call ai_analyze_images with the group of images response = self.send_image_request(pdf_document, base64_group) try: pdf_document.set_from_json(response) except Exception as e: logging.error("API-Call for image analysis failed") logging.error(e) if pdf_document.has_sufficient_information(): logging.info("Document information sufficient. Proceeding with next document.") return pdf_document else: logging.info("Still lacking information, looking for more images") logging.info("No more images found.") return pdf_document def process_images_by_page(self, pdf_document: PDFDocument): for page in pdf_document.pages: logging.debug(f"Checking Page {page['page_number']} looking for largest image") # Skip page if no images are present if 'max_img_xref' not in page or not page['max_img_xref']: logging.debug("Page not analyzed: (no images)") continue # Get the largest image of the site (assuming it to be the scan-image) image_base64 = pdf_document.get_png_image_base64_by_xref(page['max_img_xref']) # Send it to GPT logging.info("Asking AI for analyzing scanned page") response = self.send_image_request(pdf_document, [image_base64]) try: pdf_document.set_from_json(response) except Exception as e: logging.error("API-Call for image analysis failed") logging.error(e) # Only proceed if the information about the document is still insufficient if pdf_document.has_sufficient_information(): logging.info("Document information sufficient, proceeding.") return pdf_document else: logging.info("Still lacking information, looking for more pages") logging.info("No more pages available.") return pdf_document # TEXT-Analysis class AIAgent_OpenAI_pdf_text_analysis(AIAgent_OpenAI): def __init__(self): system_message = ( "You are a helpful assistant analyzing OCR outputs. It's important " "to remember that these outputs may represent only a part of the document. " "Provide the following information:\n" "1. Creation date of the document.\n" "2. A short title of 3-4 words.\n" "3. A meaningful summary of 3-4 sentences.\n" "4. Creator/Issuer\n" "5. Suitable keywords/tags related to the content.\n" "6. Rate the importance of the document on a scale from 0 (unimportant) to " "10 (vital).\n" "7. Rate your confidence for each of the above points on a scale " "from 0 (no information, text not readable) over 5 (possibly right, but only " "few hints about the content of the whole document) to 10 (very sure). " "You always answer in {LANGUAGE} language. For gathering information, " "you use the given filename, pathname and OCR-analyzed text. " "If you are seeing a blank document, your title-confidence is alway 0." "You always answer in a specified JSON-Format like in this example:\n" "{\n" " 'summary': '[summary]',\n" " 'summary_confidence': [number],\n" " 'title': '[title]',\n" " 'title_confidence': [number],\n" " 'creation_date': '[Date YY-mm-dd]',\n" " 'creation_date_confidence': [number],\n" " 'creator': '[creator name]',\n" " 'creator_confidence': [number],\n" " 'tags': ['[tag 1]', '[tag 2]', ...],\n" " 'tags_confidence': [[confidence tag 1], [confidence tag 2]],\n" " 'importance': [number],\n" " 'importance_confidence': [number]\n" "}" ) # Parent constructor super().__init__(model="gpt-4-1106-preview", system_message=system_message) self.response_format="json_object" # Main working function to get info about a PDFDocument by # sending a GPT-API-Request def analyze_text(self, pdf_document: PDFDocument): # Step 1: Analyze the number of potentially meaningful words # to decide which model to use # GPT-3.5 is good enough for long texts and much cheaper. # Especially in shorter texts, GPT-4 gives much more high-quality answers word_count = len([word for word in re.split(r'\W+', pdf_document.get_pdf_text()) if len(word) >= 3]) model_choice = "gpt-3.5-turbo-1106" if word_count > 100 else "gpt-4-1106-preview" #model_choice = "gpt-4-1106-preview" # for test purposes logging.debug("Opting for " + model_choice) self.set_model(model_choice) message = ("Analyze following OCR-Output. Try to imagine as many valuable keywords and categories as possible. " "Imagine additional keywords thinking of a wider context and possible categories in an archive system. " f"Use {LANGUAGE} Language. Answer in the given pattern (JSON): " + pdf_document.get_short_description() ) # in case of very long text, we have to shorten it depending on # the specific token-limit of the actual model # Optimize request data # Convert message-list to str request_test_str = pprint.pformat(self.messages) # estimate token-number for request num_tokens = num_tokens_from_string(request_test_str) # estimate 500 Tokens for answer tokens_required = num_tokens + 500 # max tokens of the actual model stored in price list table
diff_to_max = tokens_required - OpenAI_model_pricelist[self.model][2]
1
2023-12-04 09:30:53+00:00
12k
PopicLab/insilicoSV
insilicosv/simulate.py
[ { "identifier": "utils", "path": "insilicosv/utils.py", "snippet": "class NestedDict(defaultdict):\nclass OverlapEvents:\n def __call__(self):\ndef is_overlapping(event_ranges, addition, called_from_helper=False, strictly_partial=False):\ndef fail_if_any_overlapping(arr):\ndef validate_symbols(source...
import random import logging import time from insilicosv import utils from os import write from insilicosv.processing import FormatterIO, collect_args from pysam import FastaFile from pysam import VariantFile from insilicosv.constants import * from insilicosv.structural_variant import Structural_Variant, Event from collections import defaultdict
10,773
self.avg_len[0] += event.length self.avg_len[1] += 1 self.avg_len = self.avg_len[0] // self.avg_len[1] if self.avg_len[1] != 0 else 0 def export_data(self, fileout): """ Exports all collected data to entered file fileout: Location to export stats file """ def write_item(fout, name, item, prefix=""): fout.write("{}{}: {}\n".format(prefix, str(name), str(item))) with open(fileout, "w") as fout: fout.write("===== Overview =====\n") write_item(fout, "SVs successfully simulated", str(self.active_svs) + "/" + str(self.total_svs)) for sv_type in self.sv_types: write_item(fout, sv_type, self.sv_types[sv_type], prefix="\t- ") write_item(fout, "Homozygous SVs", self.num_homozygous) write_item(fout, "Heterozygous SVs", self.num_heterozygous) write_item(fout, "Average length of SV symbols/components (excluding dispersions)", self.avg_len) write_item(fout, "Min length of non-dispersion event", self.min_event_len) write_item(fout, "Max length of non-dispersion event", self.max_event_len) for id in self.chr_ids: fout.write("\n===== {} =====\n".format(id)) write_item(fout, "Length of sequence", self.chr_lengths[id]) write_item(fout, "Total impacted length of reference chromosome", self.len_frags_chr[id]) class SV_Simulator: def __init__(self, par_file, log_file=None): """ par_file: file location to configuration file (.yaml) log_file: location to store log file with diagnostic information if config parameters indicate so """ global time_start print("Setting up Simulator...") self.formatter = FormatterIO(par_file) self.formatter.yaml_to_var_list() config = self.formatter.config self.ref_file = config['sim_settings']['reference'] self.ref_fasta = FastaFile(self.ref_file) self.svs_config = config['variant_sets'] self.sim_settings = config['sim_settings'] if log_file and "generate_log_file" in self.sim_settings.keys(): logging.basicConfig(filename=log_file, filemode="w", level=logging.DEBUG, format='[%(name)s: %(levelname)s - %(asctime)s] %(message)s') self.log_to_file("YAML Configuration: {}".format(config)) # get all chromosome ids self.order_ids = self.ref_fasta.references self.len_dict = dict() # stores mapping with key = chromosome, value = chromosome length for id in self.order_ids: chrom_len = self.ref_fasta.get_reference_length(id) if 'filter_small_chr' in self.sim_settings and chrom_len < self.sim_settings['filter_small_chr']: print("Filtering chromosome {}: Length of {} below threshold of {}".format(id, chrom_len, self.sim_settings['filter_small_chr'])) else: self.len_dict[id] = chrom_len print("Length of chromosome {}: {}".format(id, self.len_dict[id])) # initialize stats file to be generated after all edits and exporting are finished self.stats = StatsCollection(self.order_ids, self.len_dict) self.mode = "randomized" self.vcf_path = None if "vcf_path" in self.svs_config[0]: self.mode = "fixed" self.vcf_path = self.svs_config[0]["vcf_path"] self.svs = [] self.event_ranges = defaultdict(list) if "avoid_intervals" in config: # extract {chrom: [(start, end)]} intervals from vcf, add intervals from vcf to event range self.extract_vcf_event_intervals(config["avoid_intervals"]) self.overlap_events = None if "overlap_events" not in config.keys() \ else utils.OverlapEvents(config, allow_chroms=self.order_ids) self.initialize_svs() print("Finished Setting up Simulator in {} seconds\n".format(time.time() - time_start)) time_start = time.time() def __repr__(self): return "All structural variants entered into simulator: {}".format(self.svs) def log_to_file(self, info, key="DEBUG"): # only logs to file if config setting indicates so key_to_func = {"DEBUG": logging.debug, "WARNING": logging.warning} if "generate_log_file" in self.sim_settings and self.sim_settings["generate_log_file"]: key_to_func[key](info) def get_rand_chr(self, check_size=None, fixed_chrom=None): # random assignment of SV to a chromosome (unless we have a predetermined chromosome for this event) valid_chrs = self.order_ids if check_size is not None: valid_chrs = [chrom for chrom, chr_size in self.len_dict.items() if chr_size >= check_size] if len(valid_chrs) == 0: raise Exception("SVs are too big for the reference!") rand_id = valid_chrs[random.randint(0, len(valid_chrs) - 1)] if fixed_chrom is None else fixed_chrom chr_len = self.len_dict[rand_id] chr_event_ranges = self.event_ranges[rand_id] assert rand_id is not None return rand_id, chr_len, chr_event_ranges def extract_vcf_event_intervals(self, vcf_path): vcf = VariantFile(vcf_path) for rec in vcf.fetch(): self.event_ranges[rec.chrom].append((rec.start, rec.stop)) def process_vcf(self, vcf_path): # process vcf containing SVs to be added (deterministically) to reference active_svs_total = 0 time_start_local = 0 vcf = VariantFile(vcf_path) for rec in vcf.fetch(): svtype = Variant_Type(rec.info['SVTYPE']) if 'SVTYPE' in rec.info else Variant_Type(rec.id) self.event_ranges[rec.chrom].append((rec.start, rec.stop))
time_start = time.time() class StatsCollection: """collection of information for stats file, if requested""" def __init__(self, chr_ids, chr_lens): self.num_heterozygous = 0 self.num_homozygous = 0 self.total_svs = 0 self.active_svs = 0 self.active_events_chr = dict() self.chr_ids = chr_ids self.chr_lengths = chr_lens self.avg_len = [0, 0] # Average length of SV events/components self.len_frags_chr = dict() # Lengths of altered fragments within chromosome self.sv_types = dict() for id in self.chr_ids: self.len_frags_chr[id] = 0 self.active_events_chr[id] = 0 def get_info(self, svs): """ collects all information for stats file after all edits are completed svs: list of Structural_Variant objects -> return None """ self.total_svs = len(svs) self.min_event_len = min([event.length for sv in svs if sv.active for key, event in sv.events_dict.items() if not event.symbol.startswith(Symbols.DIS.value)]) self.max_event_len = max([event.length for sv in svs if sv.active for key, event in sv.events_dict.items() if not event.symbol.startswith(Symbols.DIS.value)]) for sv in svs: if sv.active: self.active_svs += 1 if sv.name in self.sv_types: self.sv_types[sv.name] += 1 else: self.sv_types[sv.name] = 1 if sv.hap[0] and sv.hap[1]: # homozygous SV self.num_homozygous += 1 else: # heterozygous SV self.num_heterozygous += 1 # add up the lengths of impacted regions on the reference for frag in sv.changed_fragments: self.len_frags_chr[frag[0]] += frag[2] - frag[1] # count up average length of non-dispersion events for symbol in sv.events_dict: if not symbol.startswith(Symbols.DIS.value): event = sv.events_dict[symbol] self.avg_len[0] += event.length self.avg_len[1] += 1 self.avg_len = self.avg_len[0] // self.avg_len[1] if self.avg_len[1] != 0 else 0 def export_data(self, fileout): """ Exports all collected data to entered file fileout: Location to export stats file """ def write_item(fout, name, item, prefix=""): fout.write("{}{}: {}\n".format(prefix, str(name), str(item))) with open(fileout, "w") as fout: fout.write("===== Overview =====\n") write_item(fout, "SVs successfully simulated", str(self.active_svs) + "/" + str(self.total_svs)) for sv_type in self.sv_types: write_item(fout, sv_type, self.sv_types[sv_type], prefix="\t- ") write_item(fout, "Homozygous SVs", self.num_homozygous) write_item(fout, "Heterozygous SVs", self.num_heterozygous) write_item(fout, "Average length of SV symbols/components (excluding dispersions)", self.avg_len) write_item(fout, "Min length of non-dispersion event", self.min_event_len) write_item(fout, "Max length of non-dispersion event", self.max_event_len) for id in self.chr_ids: fout.write("\n===== {} =====\n".format(id)) write_item(fout, "Length of sequence", self.chr_lengths[id]) write_item(fout, "Total impacted length of reference chromosome", self.len_frags_chr[id]) class SV_Simulator: def __init__(self, par_file, log_file=None): """ par_file: file location to configuration file (.yaml) log_file: location to store log file with diagnostic information if config parameters indicate so """ global time_start print("Setting up Simulator...") self.formatter = FormatterIO(par_file) self.formatter.yaml_to_var_list() config = self.formatter.config self.ref_file = config['sim_settings']['reference'] self.ref_fasta = FastaFile(self.ref_file) self.svs_config = config['variant_sets'] self.sim_settings = config['sim_settings'] if log_file and "generate_log_file" in self.sim_settings.keys(): logging.basicConfig(filename=log_file, filemode="w", level=logging.DEBUG, format='[%(name)s: %(levelname)s - %(asctime)s] %(message)s') self.log_to_file("YAML Configuration: {}".format(config)) # get all chromosome ids self.order_ids = self.ref_fasta.references self.len_dict = dict() # stores mapping with key = chromosome, value = chromosome length for id in self.order_ids: chrom_len = self.ref_fasta.get_reference_length(id) if 'filter_small_chr' in self.sim_settings and chrom_len < self.sim_settings['filter_small_chr']: print("Filtering chromosome {}: Length of {} below threshold of {}".format(id, chrom_len, self.sim_settings['filter_small_chr'])) else: self.len_dict[id] = chrom_len print("Length of chromosome {}: {}".format(id, self.len_dict[id])) # initialize stats file to be generated after all edits and exporting are finished self.stats = StatsCollection(self.order_ids, self.len_dict) self.mode = "randomized" self.vcf_path = None if "vcf_path" in self.svs_config[0]: self.mode = "fixed" self.vcf_path = self.svs_config[0]["vcf_path"] self.svs = [] self.event_ranges = defaultdict(list) if "avoid_intervals" in config: # extract {chrom: [(start, end)]} intervals from vcf, add intervals from vcf to event range self.extract_vcf_event_intervals(config["avoid_intervals"]) self.overlap_events = None if "overlap_events" not in config.keys() \ else utils.OverlapEvents(config, allow_chroms=self.order_ids) self.initialize_svs() print("Finished Setting up Simulator in {} seconds\n".format(time.time() - time_start)) time_start = time.time() def __repr__(self): return "All structural variants entered into simulator: {}".format(self.svs) def log_to_file(self, info, key="DEBUG"): # only logs to file if config setting indicates so key_to_func = {"DEBUG": logging.debug, "WARNING": logging.warning} if "generate_log_file" in self.sim_settings and self.sim_settings["generate_log_file"]: key_to_func[key](info) def get_rand_chr(self, check_size=None, fixed_chrom=None): # random assignment of SV to a chromosome (unless we have a predetermined chromosome for this event) valid_chrs = self.order_ids if check_size is not None: valid_chrs = [chrom for chrom, chr_size in self.len_dict.items() if chr_size >= check_size] if len(valid_chrs) == 0: raise Exception("SVs are too big for the reference!") rand_id = valid_chrs[random.randint(0, len(valid_chrs) - 1)] if fixed_chrom is None else fixed_chrom chr_len = self.len_dict[rand_id] chr_event_ranges = self.event_ranges[rand_id] assert rand_id is not None return rand_id, chr_len, chr_event_ranges def extract_vcf_event_intervals(self, vcf_path): vcf = VariantFile(vcf_path) for rec in vcf.fetch(): self.event_ranges[rec.chrom].append((rec.start, rec.stop)) def process_vcf(self, vcf_path): # process vcf containing SVs to be added (deterministically) to reference active_svs_total = 0 time_start_local = 0 vcf = VariantFile(vcf_path) for rec in vcf.fetch(): svtype = Variant_Type(rec.info['SVTYPE']) if 'SVTYPE' in rec.info else Variant_Type(rec.id) self.event_ranges[rec.chrom].append((rec.start, rec.stop))
sv = Structural_Variant(sv_type=svtype, mode='fixed', vcf_rec=rec, ref_fasta=self.ref_fasta)
3
2023-12-01 14:39:20+00:00
12k
BiQiWHU/BWG
train_net.py
[ { "identifier": "add_maskformer2_config", "path": "mask2former/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...
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 from detectron2.engine import ( DefaultTrainer, default_argument_parser, default_setup, launch, ) from detectron2.evaluation import ( CityscapesInstanceEvaluator, CityscapesSemSegEvaluator, COCOEvaluator, COCOPanopticEvaluator, DatasetEvaluators, LVISEvaluator, SemSegEvaluator, verify_results, ) 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 mask2former import ( COCOInstanceNewBaselineDatasetMapper, COCOPanopticNewBaselineDatasetMapper, InstanceSegEvaluator, MaskFormerInstanceDatasetMapper, MaskFormerPanopticDatasetMapper, MaskFormerSemanticDatasetMapper, SemanticSegmentorWithTTA, add_maskformer2_config, ) import warnings import copy import itertools import logging import os import torch import detectron2.utils.comm as comm
10,728
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ MaskFormer 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 os.environ['DETECTRON2_DATASETS'] = 'E:/DGtask/datasets' # MaskFormer class Trainer(DefaultTrainer): """ Extension of the Trainer class adapted to MaskFormer. """ @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") evaluator_list = [] evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type # semantic segmentation if evaluator_type in ["sem_seg", "ade20k_panoptic_seg"]: evaluator_list.append( SemSegEvaluator( dataset_name, distributed=True, output_dir=output_folder, ) ) # instance segmentation if evaluator_type == "coco": evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) # panoptic segmentation if evaluator_type in [ "coco_panoptic_seg", "ade20k_panoptic_seg", "cityscapes_panoptic_seg", "mapillary_vistas_panoptic_seg", ]: if cfg.MODEL.MASK_FORMER.TEST.PANOPTIC_ON: evaluator_list.append(COCOPanopticEvaluator(dataset_name, output_folder)) # COCO if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Mapillary Vistas if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON:
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ MaskFormer 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 os.environ['DETECTRON2_DATASETS'] = 'E:/DGtask/datasets' # MaskFormer class Trainer(DefaultTrainer): """ Extension of the Trainer class adapted to MaskFormer. """ @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") evaluator_list = [] evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type # semantic segmentation if evaluator_type in ["sem_seg", "ade20k_panoptic_seg"]: evaluator_list.append( SemSegEvaluator( dataset_name, distributed=True, output_dir=output_folder, ) ) # instance segmentation if evaluator_type == "coco": evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) # panoptic segmentation if evaluator_type in [ "coco_panoptic_seg", "ade20k_panoptic_seg", "cityscapes_panoptic_seg", "mapillary_vistas_panoptic_seg", ]: if cfg.MODEL.MASK_FORMER.TEST.PANOPTIC_ON: evaluator_list.append(COCOPanopticEvaluator(dataset_name, output_folder)) # COCO if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Mapillary Vistas if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON:
evaluator_list.append(InstanceSegEvaluator(dataset_name, output_dir=output_folder))
7
2023-11-29 17:15:46+00:00
12k